hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
7432bbb0cda2b148c865ed39176d9929dfda4669 | 3,667 | import org.sql2o.*;
import java.util.List;
public class Text {
private int id;
private int panel_id;
private int sequence;
private String body;
private String box_style;
private String font;
private String orientation;
private String speaker;
public Text(int panel_id, int sequence, String body, String orientation) {
this.panel_id = panel_id;
this.sequence = sequence;
this.body = body;
this.orientation = orientation;
}
public int getId() {
return id;
}
public int getPanelId() {
return panel_id;
}
public void setPanelId(int panel_id) {
this.panel_id = panel_id;
}
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
public String getBody(){
return body;
}
public void setBody(String body){
this.body = body;
}
public String getOrientation(){
return orientation;
}
public void setOrientation(String orientation){
this.orientation = orientation;
}
public String getBoxStyle() {
return box_style;
}
public void setBoxStyle(String box_style) {
this.box_style = box_style;
}
public String getFont() {
return font;
}
public void setFont(String font) {
this.font = font;
}
public void save() {
try(Connection con = DB.sql2o.open()) {
String sql = "INSERT INTO texts (panel_id, sequence, body, orientation) VALUES (:panel_id, :sequence, :body, :orientation);";
this.id = (int) con.createQuery(sql, true)
.addParameter("panel_id", this.panel_id)
.addParameter("sequence", this.sequence)
.addParameter("body", this.body)
.addParameter("orientation", this.orientation)
.executeUpdate()
.getKey();
}
}
public static List<Text> all() {
try(Connection con = DB.sql2o.open()) {
String sql = "SELECT * FROM texts;";
return con.createQuery(sql)
.executeAndFetch(Text.class);
}
}
public static Text find(int id) {
try(Connection con = DB.sql2o.open()) {
String sql = "SELECT * FROM texts WHERE id = :id;";
return con.createQuery(sql)
.addParameter("id", id)
.executeAndFetchFirst(Text.class);
}
}
@Override
public boolean equals(Object otherText) {
if(!(otherText instanceof Text)) {
return false;
} else {
Text newText = (Text) otherText;
return this.getPanelId() == newText.getPanelId() &&
this.getSequence() == newText.getSequence() &&
this.getBody().equals(newText.getBody()) &&
this.getOrientation().equals(newText.getOrientation());
}
}
public void update() {
try(Connection con = DB.sql2o.open()) {
String sql = "UPDATE texts SET panel_id = :panel_id, sequence = :sequence, body = :body, orientation = :orientation WHERE id = :id;";
con.createQuery(sql)
.addParameter("panel_id", this.panel_id)
.addParameter("sequence", this.sequence)
.addParameter("body", this.body)
.addParameter("orientation", this.orientation)
.addParameter("id", this.id)
.executeUpdate();
}
}
public void delete() {
try(Connection con = DB.sql2o.open()) {
String reSequence = "UPDATE texts SET sequence = sequence - 1 WHERE panel_id = :panel_id AND sequence > :sequence;";
con.createQuery(reSequence)
.addParameter("panel_id", this.panel_id)
.addParameter("sequence", this.sequence)
.executeUpdate();
String delete = "DELETE FROM texts WHERE id = :id;";
con.createQuery(delete)
.addParameter("id", this.id)
.executeUpdate();
}
}
}
| 25.643357 | 139 | 0.636215 |
6ceabd78fc5352b2a8eafaf3728316646b7783f0 | 7,330 | package schach.game.state;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import schach.common.Color;
import schach.common.Constants;
import schach.common.Position;
import schach.game.moves.Movement;
import schach.game.pieces.BishopPiece;
import schach.game.pieces.HistoryPiece;
import schach.game.pieces.KnightPiece;
import schach.game.pieces.PawnPiece;
import schach.game.pieces.Piece;
import schach.game.pieces.QueenPiece;
import schach.game.pieces.RookPiece;
//a NOPMD is required here because PMD has false positives when importing GameTestUtils
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
//NOPMD is required here to suppress false positives
import static schach.game.GameTestUtils.*; //NOPMD
/**
* Tests the behavior of the board.
*/
public class BoardTest {
/**
* Tests if getPieces returns the correct HashMap.
*/
@Test
public void testGetPieces() {
Board board = new Board(new GameState());
Position position = new Position(0, 3);
int index = position.getBoardIndex();
Piece piece = new RookPiece(Color.BLACK);
board.placeNewPiece(position, piece);
assertEquals(piece, board.getPieces().get(index));
}
/**
* Tests that the attack detection works correctly.
*/
@Test
public void testIsAttackedAt() {
GameState game = gameFromMoves("a2-a4", "b7-b5");
Board board = game.getBoard();
assertTrue(board.isAttackedAt(new Position(1, 3)));
assertTrue(board.isAttackedAt(new Position(0, 4)));
assertFalse(board.isAttackedAt(new Position(1, 4)));
}
/**
* Tests if the captured pieces are properly sorted into the list of captured
* pieces. For this, the captured pieces from game2 (intoDraw) are used.
*/
@Test
public void testGetSortedCapturedPieces() {
GameState game = new GameState();
// setup of the pieces that are captured by intoDraw() in sorted order
List<Piece> sortedList = List.of(new BishopPiece(Color.BLACK), new KnightPiece(Color.BLACK),
new PawnPiece(Color.BLACK), new PawnPiece(Color.BLACK), new PawnPiece(Color.BLACK), new PawnPiece(Color.BLACK));
// move game into draw and get the captured pieces as a sorted list
intoDraw(game);
List<Piece> gameList = game.getBoard().getSortedCapturedPieces();
assertEquals(sortedList.size(), gameList.size());
int count = 0;
for (Piece expected : sortedList) {
assertEqualPieces(gameList.get(count++), expected);
}
}
/**
* Tests that getKingPosition returns the correct position for each king.
*/
@Test
public void testGetKingPositionFor() {
Board board = new Board(new GameState());
Position whiteKing = new Position(4, 7);
Position blackKing = new Position(4, 0);
assertEquals(whiteKing, board.getKingPositionFor(Color.WHITE));
assertEquals(blackKing, board.getKingPositionFor(Color.BLACK));
}
/**
* Tests that capturing a pice gets rid of it.
*/
@Test
public void testCapturePiece() {
GameState game = new GameState();
Board board = game.getBoard();
board.capturePiece(new Position(0, 0));
assertNull(board.getPieceAt(0, 0));
assertThrows(IllegalStateException.class, () -> board.capturePiece(new Position(5, 5)));
assertThrows(IllegalStateException.class, () -> board.capturePiece(new Position(-1, 5)));
}
/**
* Tests that getPieceAt returns the correct piece for a pair of coordinates.
*/
@Test
public void testGetPieceAt() {
GameState game = new GameState();
Piece blackRook = new RookPiece(Color.BLACK);
assertEquals(blackRook.getColor(), game.getPieceAt(0, 0).getColor());
assertEquals(blackRook.getFullName(), game.getPieceAt(0, 0).getFullName());
}
/**
* Test that placing a new piece has the desired effect.
*/
@Test
public void testPlaceNewPiece() {
Board board = new Board(new GameState());
Position position = new Position(0, 0);
HistoryPiece piece = new RookPiece(Color.WHITE);
board.placeNewPiece(position, piece);
// test 2: that 'pieces' (HashMap) is updated with the new piece that was placed
int boardIndex = position.getBoardIndex();
assertTrue(board.getPieces().containsKey(boardIndex));
assertEquals(piece, board.getPieces().get(boardIndex));
// test 3: that replacedPiece is updated if the target position is already
// occupied
Piece newPiece = new RookPiece(Color.BLACK);
board.placeNewPiece(position, newPiece);
assertEquals(piece, newPiece.getReplacedPiece());
// test 5: put a piece in a position where no piece has yet been put, e.g.
// presentPiece == null
Piece anotherPiece = new QueenPiece(Color.WHITE);
Position empty = new Position(0, 4);
board.placeNewPiece(empty, anotherPiece);
assertEquals(anotherPiece, board.getPieceAt(empty));
}
/**
* Tests that apply movement actually applies the movement.
*
* TODO: test more branches
*/
@Test
public void testApplyMovement() {
GameState game = new GameState();
Board board = game.getBoard();
assertThrows(IllegalArgumentException.class, () -> board.applyMovement(new Movement(5, 5, 5, 5)));
}
/**
* Asserts that if all pieces except the ones at the given positions are removed
* there is or isn't sufficient material. The kings are never removed.
*
* @param sufficient If the material should be sufficient or not
* @param retainPositions Array of positions to retain
*/
private void assertSufficientMaterial(boolean sufficient, Position... retainPositions) {
GameState game = new GameState();
Board board = game.getBoard();
// remove all if not in set of positions to retain
Set<Position> retainSet = new HashSet<>(Arrays.asList(retainPositions));
for (Color color : Color.values()) {
retainSet.add(board.getKingPositionFor(color));
}
for (int x = 0; x < Constants.BOARD_SIZE; x++) {
for (int y = 0; y < Constants.BOARD_SIZE; y++) {
Position toRemove = new Position(x, y);
if (!retainSet.contains(toRemove) && board.getPieceAt(toRemove) != null) {
board.capturePiece(toRemove);
}
}
}
// assert that there is or isn't sufficient material
assertEquals(sufficient, !board.hasInsufficientMaterial());
}
/**
* Tests that the empty board does not have sufficient material.
*/
@Test
public void testEmptyBoardMaterial() {
assertSufficientMaterial(false);
}
/**
* Tests that the detection works for only one bishop or one knight.
*
* TODO: cover remaining branch
*/
@Test
public void testHasInsufficientMaterial() {
assertSufficientMaterial(true, new Position(0, 0));
assertSufficientMaterial(false, new Position(1, 0));
assertSufficientMaterial(false, new Position(2, 7));
}
/**
* Tests that boards with only kinds and two bishops are sufficient in certain
* cases.
*/
@Test
public void testBishopBoardMaterial() {
assertSufficientMaterial(true, new Position(0, 0), new Position(0, 1));
assertSufficientMaterial(true, new Position(2, 0), new Position(0, 1));
assertSufficientMaterial(true, new Position(2, 0), new Position(2, 7));
assertSufficientMaterial(false, new Position(2, 0), new Position(5, 7));
}
}
| 33.318182 | 120 | 0.697681 |
8be391442f2a6a2ef5810081a941366f7d888562 | 13,417 | package com.airbnb.lottie.p085a.p086a;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import com.airbnb.lottie.C5663B;
import com.airbnb.lottie.C5718c;
import com.airbnb.lottie.C5851x;
import com.airbnb.lottie.p085a.p087b.C5698a;
import com.airbnb.lottie.p085a.p087b.C5698a.C5699a;
import com.airbnb.lottie.p085a.p087b.C5714p;
import com.airbnb.lottie.p089c.C5776e;
import com.airbnb.lottie.p089c.p090a.C5721b;
import com.airbnb.lottie.p089c.p090a.C5723d;
import com.airbnb.lottie.p089c.p091b.C5757r.C5758a;
import com.airbnb.lottie.p089c.p092c.C5762c;
import com.airbnb.lottie.p095f.C5828e;
import com.airbnb.lottie.p095f.C5829f;
import com.airbnb.lottie.p096g.C5833c;
import java.util.ArrayList;
import java.util.List;
/* renamed from: com.airbnb.lottie.a.a.b */
/* compiled from: BaseStrokeContent */
public abstract class C5676b implements C5699a, C5686k, C5680e {
/* renamed from: a */
private final PathMeasure f9656a = new PathMeasure();
/* renamed from: b */
private final Path f9657b = new Path();
/* renamed from: c */
private final Path f9658c = new Path();
/* renamed from: d */
private final RectF f9659d = new RectF();
/* renamed from: e */
private final C5851x f9660e;
/* renamed from: f */
private final C5762c f9661f;
/* renamed from: g */
private final List<C5677a> f9662g = new ArrayList();
/* renamed from: h */
private final float[] f9663h;
/* renamed from: i */
final Paint f9664i = new Paint(1);
/* renamed from: j */
private final C5698a<?, Float> f9665j;
/* renamed from: k */
private final C5698a<?, Integer> f9666k;
/* renamed from: l */
private final List<C5698a<?, Float>> f9667l;
/* renamed from: m */
private final C5698a<?, Float> f9668m;
/* renamed from: n */
private C5698a<ColorFilter, ColorFilter> f9669n;
/* renamed from: com.airbnb.lottie.a.a.b$a */
/* compiled from: BaseStrokeContent */
private static final class C5677a {
/* access modifiers changed from: private */
/* renamed from: a */
public final List<C5690o> f9670a;
/* access modifiers changed from: private */
/* renamed from: b */
public final C5697v f9671b;
private C5677a(C5697v trimPath) {
this.f9670a = new ArrayList();
this.f9671b = trimPath;
}
}
C5676b(C5851x lottieDrawable, C5762c layer, Cap cap, Join join, float miterLimit, C5723d opacity, C5721b width, List<C5721b> dashPattern, C5721b offset) {
this.f9660e = lottieDrawable;
this.f9661f = layer;
this.f9664i.setStyle(Style.STROKE);
this.f9664i.setStrokeCap(cap);
this.f9664i.setStrokeJoin(join);
this.f9664i.setStrokeMiter(miterLimit);
this.f9666k = opacity.mo17984a();
this.f9665j = width.mo17984a();
if (offset == null) {
this.f9668m = null;
} else {
this.f9668m = offset.mo17984a();
}
this.f9667l = new ArrayList(dashPattern.size());
this.f9663h = new float[dashPattern.size()];
for (int i = 0; i < dashPattern.size(); i++) {
this.f9667l.add(((C5721b) dashPattern.get(i)).mo17984a());
}
layer.mo18084a(this.f9666k);
layer.mo18084a(this.f9665j);
for (int i2 = 0; i2 < this.f9667l.size(); i2++) {
layer.mo18084a((C5698a) this.f9667l.get(i2));
}
C5698a<?, Float> aVar = this.f9668m;
if (aVar != null) {
layer.mo18084a(aVar);
}
this.f9666k.mo17951a((C5699a) this);
this.f9665j.mo17951a((C5699a) this);
for (int i3 = 0; i3 < dashPattern.size(); i3++) {
((C5698a) this.f9667l.get(i3)).mo17951a((C5699a) this);
}
C5698a<?, Float> aVar2 = this.f9668m;
if (aVar2 != null) {
aVar2.mo17951a((C5699a) this);
}
}
/* renamed from: a */
public void mo17932a() {
this.f9660e.invalidateSelf();
}
/* renamed from: a */
public void mo17937a(List<C5678c> contentsBefore, List<C5678c> contentsAfter) {
C5697v trimPathContentBefore = null;
for (int i = contentsBefore.size() - 1; i >= 0; i--) {
C5678c content = (C5678c) contentsBefore.get(i);
if ((content instanceof C5697v) && ((C5697v) content).mo17947e() == C5758a.Individually) {
trimPathContentBefore = (C5697v) content;
}
}
if (trimPathContentBefore != null) {
trimPathContentBefore.mo17943a(this);
}
C5677a currentPathGroup = null;
for (int i2 = contentsAfter.size() - 1; i2 >= 0; i2--) {
C5678c content2 = (C5678c) contentsAfter.get(i2);
if ((content2 instanceof C5697v) && ((C5697v) content2).mo17947e() == C5758a.Individually) {
if (currentPathGroup != null) {
this.f9662g.add(currentPathGroup);
}
currentPathGroup = new C5677a((C5697v) content2);
((C5697v) content2).mo17943a(this);
} else if (content2 instanceof C5690o) {
if (currentPathGroup == null) {
currentPathGroup = new C5677a(trimPathContentBefore);
}
currentPathGroup.f9670a.add((C5690o) content2);
}
}
if (currentPathGroup != null) {
this.f9662g.add(currentPathGroup);
}
}
/* renamed from: a */
public void mo17933a(Canvas canvas, Matrix parentMatrix, int parentAlpha) {
String str = "StrokeContent#draw";
C5718c.m10176a(str);
this.f9664i.setAlpha(C5828e.m10527a((int) ((((((float) parentAlpha) / 255.0f) * ((float) ((Integer) this.f9666k.mo17955d()).intValue())) / 100.0f) * 255.0f), 0, 255));
this.f9664i.setStrokeWidth(((Float) this.f9665j.mo17955d()).floatValue() * C5829f.m10535a(parentMatrix));
if (this.f9664i.getStrokeWidth() <= 0.0f) {
C5718c.m10178c(str);
return;
}
m10030a(parentMatrix);
C5698a<ColorFilter, ColorFilter> aVar = this.f9669n;
if (aVar != null) {
this.f9664i.setColorFilter((ColorFilter) aVar.mo17955d());
}
for (int i = 0; i < this.f9662g.size(); i++) {
C5677a pathGroup = (C5677a) this.f9662g.get(i);
if (pathGroup.f9671b != null) {
m10029a(canvas, pathGroup, parentMatrix);
} else {
String str2 = "StrokeContent#buildPath";
C5718c.m10176a(str2);
this.f9657b.reset();
for (int j = pathGroup.f9670a.size() - 1; j >= 0; j--) {
this.f9657b.addPath(((C5690o) pathGroup.f9670a.get(j)).getPath(), parentMatrix);
}
C5718c.m10178c(str2);
String str3 = "StrokeContent#drawPath";
C5718c.m10176a(str3);
canvas.drawPath(this.f9657b, this.f9664i);
C5718c.m10178c(str3);
}
}
C5718c.m10178c(str);
}
/* renamed from: a */
private void m10029a(Canvas canvas, C5677a pathGroup, Matrix parentMatrix) {
float startValue;
float endValue;
float startValue2;
Canvas canvas2 = canvas;
Matrix matrix = parentMatrix;
String str = "StrokeContent#applyTrimPath";
C5718c.m10176a(str);
if (pathGroup.f9671b == null) {
C5718c.m10178c(str);
return;
}
this.f9657b.reset();
for (int j = pathGroup.f9670a.size() - 1; j >= 0; j--) {
this.f9657b.addPath(((C5690o) pathGroup.f9670a.get(j)).getPath(), matrix);
}
this.f9656a.setPath(this.f9657b, false);
float totalLength = this.f9656a.getLength();
while (this.f9656a.nextContour()) {
totalLength += this.f9656a.getLength();
}
float offsetLength = (((Float) pathGroup.f9671b.mo17945c().mo17955d()).floatValue() * totalLength) / 360.0f;
float startLength = ((((Float) pathGroup.f9671b.mo17946d().mo17955d()).floatValue() * totalLength) / 100.0f) + offsetLength;
float endLength = ((((Float) pathGroup.f9671b.mo17944b().mo17955d()).floatValue() * totalLength) / 100.0f) + offsetLength;
float currentLength = 0.0f;
for (int j2 = pathGroup.f9670a.size() - 1; j2 >= 0; j2--) {
this.f9658c.set(((C5690o) pathGroup.f9670a.get(j2)).getPath());
this.f9658c.transform(matrix);
this.f9656a.setPath(this.f9658c, false);
float length = this.f9656a.getLength();
if (endLength > totalLength && endLength - totalLength < currentLength + length && currentLength < endLength - totalLength) {
if (startLength > totalLength) {
startValue2 = (startLength - totalLength) / length;
} else {
startValue2 = 0.0f;
}
C5829f.m10538a(this.f9658c, startValue2, Math.min((endLength - totalLength) / length, 1.0f), 0.0f);
canvas2.drawPath(this.f9658c, this.f9664i);
} else if (currentLength + length >= startLength && currentLength <= endLength) {
if (currentLength + length > endLength || startLength >= currentLength) {
if (startLength < currentLength) {
startValue = 0.0f;
} else {
startValue = (startLength - currentLength) / length;
}
if (endLength > currentLength + length) {
endValue = 1.0f;
} else {
endValue = (endLength - currentLength) / length;
}
C5829f.m10538a(this.f9658c, startValue, endValue, 0.0f);
canvas2.drawPath(this.f9658c, this.f9664i);
} else {
canvas2.drawPath(this.f9658c, this.f9664i);
}
}
currentLength += length;
}
C5718c.m10178c(str);
}
/* renamed from: a */
public void mo17934a(RectF outBounds, Matrix parentMatrix) {
String str = "StrokeContent#getBounds";
C5718c.m10176a(str);
this.f9657b.reset();
for (int i = 0; i < this.f9662g.size(); i++) {
C5677a pathGroup = (C5677a) this.f9662g.get(i);
for (int j = 0; j < pathGroup.f9670a.size(); j++) {
this.f9657b.addPath(((C5690o) pathGroup.f9670a.get(j)).getPath(), parentMatrix);
}
}
this.f9657b.computeBounds(this.f9659d, false);
float width = ((Float) this.f9665j.mo17955d()).floatValue();
RectF rectF = this.f9659d;
rectF.set(rectF.left - (width / 2.0f), rectF.top - (width / 2.0f), rectF.right + (width / 2.0f), rectF.bottom + (width / 2.0f));
outBounds.set(this.f9659d);
outBounds.set(outBounds.left - 1.0f, outBounds.top - 1.0f, outBounds.right + 1.0f, outBounds.bottom + 1.0f);
C5718c.m10178c(str);
}
/* renamed from: a */
private void m10030a(Matrix parentMatrix) {
String str = "StrokeContent#applyDashPattern";
C5718c.m10176a(str);
if (this.f9667l.isEmpty()) {
C5718c.m10178c(str);
return;
}
float scale = C5829f.m10535a(parentMatrix);
for (int i = 0; i < this.f9667l.size(); i++) {
this.f9663h[i] = ((Float) ((C5698a) this.f9667l.get(i)).mo17955d()).floatValue();
if (i % 2 == 0) {
float[] fArr = this.f9663h;
if (fArr[i] < 1.0f) {
fArr[i] = 1.0f;
}
} else {
float[] fArr2 = this.f9663h;
if (fArr2[i] < 0.1f) {
fArr2[i] = 0.1f;
}
}
float[] fArr3 = this.f9663h;
fArr3[i] = fArr3[i] * scale;
}
C5698a<?, Float> aVar = this.f9668m;
this.f9664i.setPathEffect(new DashPathEffect(this.f9663h, aVar == null ? 0.0f : ((Float) aVar.mo17955d()).floatValue()));
C5718c.m10178c(str);
}
/* renamed from: a */
public void mo17935a(C5776e keyPath, int depth, List<C5776e> accumulator, C5776e currentPartialKeyPath) {
C5828e.m10530a(keyPath, depth, accumulator, currentPartialKeyPath, this);
}
/* renamed from: a */
public <T> void mo17936a(T property, C5833c<T> callback) {
if (property == C5663B.f9598d) {
this.f9666k.mo17952a(callback);
} else if (property == C5663B.f9605k) {
this.f9665j.mo17952a(callback);
} else if (property != C5663B.f9618x) {
} else {
if (callback == null) {
this.f9669n = null;
return;
}
this.f9669n = new C5714p(callback);
this.f9669n.mo17951a((C5699a) this);
this.f9661f.mo18084a(this.f9669n);
}
}
}
| 39.116618 | 175 | 0.569352 |
fe37e36f2fd88932d28b442aa0eed57916fcae35 | 892 | package it.polito.dp2.NFFG;
import java.util.Set;
/**
* An interface for accessing the data associated to an Isolation policy.
* An isolation policy specifies a property that is the absence of paths
* in the NF-FG that connect nodes belonging to two different sets (in
* practice it states that the two sets of nodes are isolated from each
* other).
*/
public interface IsolationPolicyReader extends PolicyReader {
/**
* Gives the first set of nodes of this policy.
* The nodes in the set belong to the NF-FG on which the policy has to be verified.
* @return the first set of nodes of this policy.
*/
Set<NodeReader> getFirstNodeSet();
/**
* Gives the second set of nodes of this policy.
* The nodes in the set belong to the NF-FG on which the policy has to be verified.
* @return the second set of nodes of this policy.
*/
Set<NodeReader> getSecondNodeSet();
}
| 34.307692 | 84 | 0.729821 |
f4e20103e05db8254ac1493f3116e6cd23643954 | 2,270 | package henryrichard.epicwasteoftime.client.event;
import henryrichard.epicwasteoftime.EwotMain;
import henryrichard.epicwasteoftime.client.model.MaskedToolModel;
import henryrichard.epicwasteoftime.client.render.tileentity.AluminumTankTileEntityRenderer;
import henryrichard.epicwasteoftime.init.EwotTileEntities;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.model.ModelLoaderRegistry;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import static henryrichard.epicwasteoftime.init.EwotBlocks.*;
@OnlyIn(Dist.CLIENT)
@Mod.EventBusSubscriber(modid = EwotMain.MODID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)
public abstract class ClientSetupEvent {
@SuppressWarnings("ConstantConditions")
@SubscribeEvent
public static void doClientStuff(final FMLClientSetupEvent event) {
//Block render types
//Since I'm overlaying a texture for these they have to be cutouts, even though they're opaque. Sadness.
RenderTypeLookup.setRenderLayer(amethyst_ore, RenderType.getCutoutMipped());
RenderTypeLookup.setRenderLayer(endust_ore, RenderType.getCutoutMipped());
RenderTypeLookup.setRenderLayer(slime_ore, RenderType.getTranslucent());
RenderTypeLookup.setRenderLayer(lavaleaves, RenderType.getCutoutMipped());
RenderTypeLookup.setRenderLayer(lavalogged_lavaleaves, RenderType.getCutoutMipped());
RenderTypeLookup.setRenderLayer(lavaleaf_sapling, RenderType.getCutout());
RenderTypeLookup.setRenderLayer(aluminum_tank, RenderType.getCutoutMipped());
//Tile Entities
ClientRegistry.bindTileEntityRenderer(EwotTileEntities.aluminum_tank, AluminumTankTileEntityRenderer::new);
//Model Loaders
ModelLoaderRegistry.registerLoader(new ResourceLocation(EwotMain.MODID, "masked_tool"), MaskedToolModel.Loader.INSTANCE);
}
}
| 46.326531 | 129 | 0.805727 |
c96b32c6ef7aeccb89c2f2ff9a716b98330f8a5a | 3,952 | /**
* Copyright 2017 Comcast Cable Communications Management, LLC
*
* 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.comcast.redirector.api.config;
import com.comcast.redirector.common.config.Config;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.stereotype.Component;
@Component
public class RedirectorConfig implements Config {
private int connectionTimeoutMs = 10000;
private String connectionUrl = "127.0.0.1:2181";
private int retryCount = 10;
private int sleepsBetweenRetryMs = 500;
private int zooKeeperWaitTimeBeforeReconnect = 5 * 60 * 1000;
private String zookeeperBasePath = "";
private boolean cacheHosts = true;
private String snapshotBasePath = "";
private String metricsConfigUrl = "";
private long stacksSnapshotRateInSeconds = 60;
public RedirectorConfig() {}
@ManagedAttribute
public int getConnectionTimeoutMs() {
return connectionTimeoutMs;
}
@ManagedAttribute
public void setConnectionTimeoutMs(int connectionTimeoutMs) {
this.connectionTimeoutMs = connectionTimeoutMs;
}
@ManagedAttribute
public String getConnectionUrl() {
return connectionUrl;
}
@ManagedAttribute
public void setConnectionUrl(String connectionUrl) {
this.connectionUrl = connectionUrl;
}
@ManagedAttribute
public int getRetryCount() {
return retryCount;
}
@ManagedAttribute
public void setRetryCount(int retryCount) {
this.retryCount = retryCount;
}
@ManagedAttribute
public int getSleepsBetweenRetryMs() {
return sleepsBetweenRetryMs;
}
@ManagedAttribute
public void setSleepsBetweenRetryMs(int sleepsBetweenRetryMs) {
this.sleepsBetweenRetryMs = sleepsBetweenRetryMs;
}
@ManagedAttribute
public String getZookeeperBasePath() {
return zookeeperBasePath;
}
@ManagedAttribute
public void setZookeeperBasePath(String zookeeperBasePath) {
this.zookeeperBasePath = zookeeperBasePath;
}
@ManagedAttribute
public boolean isCacheHosts() {
return cacheHosts;
}
@ManagedAttribute
public void setCacheHosts(boolean cacheHosts) {
this.cacheHosts = cacheHosts;
}
@ManagedAttribute
public String getSnapshotBasePath() {
return snapshotBasePath;
}
@ManagedAttribute
public void setSnapshotBasePath(String snapshotBasePath) {
this.snapshotBasePath = snapshotBasePath;
}
@ManagedAttribute
public void setZooKeeperWaitTimeBeforeReconnect(int zooKeeperWaitTimeBeforeReconnect) {
this.zooKeeperWaitTimeBeforeReconnect = zooKeeperWaitTimeBeforeReconnect;
}
@ManagedAttribute
public int getZooKeeperWaitTimeBeforeReconnect() {
return this.zooKeeperWaitTimeBeforeReconnect;
}
@ManagedAttribute
public String getMetricsConfigUrl() {
return metricsConfigUrl;
}
@ManagedAttribute
public void setMetricsConfigUrl(String metricsConfigUrl) {
this.metricsConfigUrl = metricsConfigUrl;
}
@ManagedAttribute
public long getStacksSnapshotRateInSeconds() {
return stacksSnapshotRateInSeconds;
}
@ManagedAttribute
public void setStacksSnapshotRateInSeconds(long stacksSnapshotRateInSeconds) {
this.stacksSnapshotRateInSeconds = stacksSnapshotRateInSeconds;
}
}
| 29.058824 | 91 | 0.726468 |
fa521d37c7b1ab8797786a5fce5ee39d3c527898 | 749 | package pl.edu.agh.geotime.repository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import pl.edu.agh.geotime.domain.Department;
import java.util.List;
import java.util.Optional;
@Repository
@Transactional
public interface DepartmentRepository extends JpaRepository<Department, Long> {
Optional<Department> findById(Long id);
@EntityGraph(attributePaths = {"studyFields"})
Optional<Department> findOneByIdAndFunctionalIsFalse(Long id);
@EntityGraph(attributePaths = {"studyFields"})
List<Department> findAllByFunctionalIsFalse();
}
| 32.565217 | 79 | 0.811749 |
dcc775cc96139fdb56db398044d3b96c4883bdbb | 2,979 | /**
* Autogenerated by Thrift Compiler (0.13.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.omnisci.thrift.calciteserver;
public enum TExtArgumentType implements org.apache.thrift.TEnum {
Int8(0),
Int16(1),
Int32(2),
Int64(3),
Float(4),
Double(5),
Void(6),
PInt8(7),
PInt16(8),
PInt32(9),
PInt64(10),
PFloat(11),
PDouble(12),
PBool(13),
Bool(14),
ArrayInt8(15),
ArrayInt16(16),
ArrayInt32(17),
ArrayInt64(18),
ArrayFloat(19),
ArrayDouble(20),
ArrayBool(21),
GeoPoint(22),
GeoLineString(23),
Cursor(24),
GeoPolygon(25),
GeoMultiPolygon(26),
ColumnInt8(27),
ColumnInt16(28),
ColumnInt32(29),
ColumnInt64(30),
ColumnFloat(31),
ColumnDouble(32),
ColumnBool(33),
TextEncodingNone(34),
TextEncodingDict8(35),
TextEncodingDict16(36),
TextEncodingDict32(37);
private final int value;
private TExtArgumentType(int value) {
this.value = value;
}
/**
* Get the integer value of this enum value, as defined in the Thrift IDL.
*/
public int getValue() {
return value;
}
/**
* Find a the enum type by its integer value, as defined in the Thrift IDL.
* @return null if the value is not found.
*/
@org.apache.thrift.annotation.Nullable
public static TExtArgumentType findByValue(int value) {
switch (value) {
case 0:
return Int8;
case 1:
return Int16;
case 2:
return Int32;
case 3:
return Int64;
case 4:
return Float;
case 5:
return Double;
case 6:
return Void;
case 7:
return PInt8;
case 8:
return PInt16;
case 9:
return PInt32;
case 10:
return PInt64;
case 11:
return PFloat;
case 12:
return PDouble;
case 13:
return PBool;
case 14:
return Bool;
case 15:
return ArrayInt8;
case 16:
return ArrayInt16;
case 17:
return ArrayInt32;
case 18:
return ArrayInt64;
case 19:
return ArrayFloat;
case 20:
return ArrayDouble;
case 21:
return ArrayBool;
case 22:
return GeoPoint;
case 23:
return GeoLineString;
case 24:
return Cursor;
case 25:
return GeoPolygon;
case 26:
return GeoMultiPolygon;
case 27:
return ColumnInt8;
case 28:
return ColumnInt16;
case 29:
return ColumnInt32;
case 30:
return ColumnInt64;
case 31:
return ColumnFloat;
case 32:
return ColumnDouble;
case 33:
return ColumnBool;
case 34:
return TextEncodingNone;
case 35:
return TextEncodingDict8;
case 36:
return TextEncodingDict16;
case 37:
return TextEncodingDict32;
default:
return null;
}
}
}
| 19.728477 | 77 | 0.580732 |
3d9f4158349b2efb863018ed03df727fda684ec8 | 893 | package com.github.entropyfeng.mydb;
import com.github.entropyfeng.mydb.server.TurtleServer;
import com.github.entropyfeng.mydb.server.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.github.entropyfeng.mydb.server.util.ServerUtil.createDumpFolder;
/**
* @author entropyfeng
* @date 2019/12/27 13:34
*/
public class ServerBootStrap {
private static final Logger logger = LoggerFactory.getLogger(ServerBootStrap.class);
public static void main(String[] args) {
try {
if (!createDumpFolder()) {
logger.error("create dump directory error !");
}
String host = ServerConfig.serverHost;
Integer port = ServerConfig.port;
new TurtleServer(host, port).start();
} catch (Exception e) {
logger.error(e.getMessage());
}
}
}
| 27.90625 | 88 | 0.664054 |
5dc5a3a649e58fd41a8fcfde264cabc430011cbc | 254 | package com.lucky.jacklamb.exception;
public class InjectionPropertiesException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
public InjectionPropertiesException(String message){
super(message);
}
}
| 16.933333 | 68 | 0.759843 |
7bcc195fdf16b62e08e1181749db755a29fef6c2 | 2,856 | /*
* Copyright 2009-2013 Hippo B.V. (http://www.onehippo.com)
*
* 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.hippoecm.repository.query.lucene;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.spi.commons.namespace.NamespaceResolver;
public class OverlayNamespaceResolver implements NamespaceResolver {
private final Map<String,String> overlayPrefixToURI = new HashMap<String,String>();
private final Map<String,String> overlayUriToPrefix = new HashMap<String,String>();
private NamespaceRegistry upstream;
public OverlayNamespaceResolver(NamespaceRegistry nsMappings, Properties namespaces) {
this.upstream = nsMappings;
for(Enumeration prefixes = namespaces.propertyNames(); prefixes.hasMoreElements(); ) {
String prefix = (String) prefixes.nextElement();
addOverlayNamespace(prefix, namespaces.getProperty(prefix));
}
}
/**
* Adds the given namespace declaration to this resolver.
*
* @param prefix namespace prefix
* @param uri namespace URI
*/
private void addOverlayNamespace(String prefix, String uri) {
overlayPrefixToURI.put(prefix, uri);
overlayUriToPrefix.put(uri, prefix);
}
/** {@inheritDoc} */
public String getURI(String prefix) throws NamespaceException {
String uri = overlayPrefixToURI.get(prefix);
if (uri != null) {
return uri;
} else {
try {
return upstream.getURI(prefix);
} catch (RepositoryException ex) {
throw new NamespaceException("namespace "+prefix+" not defined", ex);
}
}
}
/** {@inheritDoc} */
public String getPrefix(String uri) throws NamespaceException {
String prefix = overlayUriToPrefix.get(uri);
if (prefix != null) {
return prefix;
} else {
try {
return upstream.getPrefix(uri);
} catch (RepositoryException ex) {
throw new NamespaceException("namespace " + uri + " not defined", ex);
}
}
}
}
| 34.409639 | 94 | 0.662115 |
84c7139f51befe088025b7c3d6a8da583aea35c1 | 1,830 | package com.quickblox.sample.chat.utils;
import com.quickblox.sample.core.utils.SharedPrefsHelper;
import com.quickblox.users.model.QBUser;
public class SharedPreferencesUtil {
private static final String QB_USER_ID = "qb_user_id";
private static final String QB_USER_LOGIN = "qb_user_login";
private static final String QB_USER_PASSWORD = "qb_user_password";
private static final String QB_USER_FULL_NAME = "qb_user_full_name";
public static void saveQbUser(QBUser qbUser) {
SharedPrefsHelper helper = SharedPrefsHelper.getInstance();
helper.save(QB_USER_ID, qbUser.getId());
helper.save(QB_USER_LOGIN, qbUser.getLogin());
helper.save(QB_USER_PASSWORD, qbUser.getPassword());
helper.save(QB_USER_FULL_NAME, qbUser.getFullName());
}
public static void removeQbUser() {
SharedPrefsHelper helper = SharedPrefsHelper.getInstance();
helper.delete(QB_USER_ID);
helper.delete(QB_USER_LOGIN);
helper.delete(QB_USER_PASSWORD);
helper.delete(QB_USER_FULL_NAME);
}
public static boolean hasQbUser() {
SharedPrefsHelper helper = SharedPrefsHelper.getInstance();
return helper.has(QB_USER_LOGIN) && helper.has(QB_USER_PASSWORD);
}
public static QBUser getQbUser() {
SharedPrefsHelper helper = SharedPrefsHelper.getInstance();
if (hasQbUser()) {
Integer id = helper.get(QB_USER_ID);
String login = helper.get(QB_USER_LOGIN);
String password = helper.get(QB_USER_PASSWORD);
String fullName = helper.get(QB_USER_FULL_NAME);
QBUser user = new QBUser(login, password);
user.setId(id);
user.setFullName(fullName);
return user;
} else {
return null;
}
}
}
| 35.192308 | 73 | 0.67541 |
69cdf1ae2f01d22aa7ef930b65e98226cdaa2d34 | 1,235 | package de.asvaachen.workinghours.backend.project.persistence;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.UUID;
@Entity
@Table(name = "project_item_hour")
public class ProjectItemHourEntity {
@Id
private UUID id;
@ManyToOne
@JoinColumn(name = "projectItemId", nullable = false)
private ProjectItemEntity projectItem;
@ManyToOne
@JoinColumn(name = "memberId", nullable = false)
private MemberEntity member;
private Integer duration;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public ProjectItemEntity getProjectItem() {
return projectItem;
}
public void setProjectItem(ProjectItemEntity projectItem) {
this.projectItem = projectItem;
}
public MemberEntity getMember() {
return member;
}
public void setMember(MemberEntity member) {
this.member = member;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
}
| 20.932203 | 63 | 0.679352 |
1f6474ada926100a4366170bced9b90a498823ed | 191 | class Foo {
void fromSuper() {}
void overridden() {}
}
class FooImpl extends Foo {
void overridden() {}
void fromThis() {}
}
class Bar {
{
new FooImpl().<caret>
}
}
| 11.9375 | 29 | 0.554974 |
2324743bbedc4aac28fe2ad3ad68561b9b8f4bff | 4,701 | package com.example.myapplication6;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private TextView mTvdg,mTvzg,mTvkg;
private Button mBtn,mBtn1,mBtn2,mBtn3,mBtn4;
private List<String> list1=new ArrayList<String>();
private List<String> list2=new ArrayList<String>();
private List<String> list3=new ArrayList<String>();
private Spinner mSpinner1,mSpinner2,mSpinner3;
private ArrayAdapter<String> adapter1,adapter2,adapter3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvdg=findViewById(R.id.tv_dengji);
mTvzg=findViewById(R.id.tv_zhengxing);
mTvkg=findViewById(R.id.tv_kaigong);
mSpinner1=findViewById(R.id.spinner1);
mSpinner2=findViewById(R.id.spinner2);
mSpinner3=findViewById(R.id.spinner3);
list1.add("一等");
list1.add("二等");
list1.add("三等");
list1.add("四等");
list1.add("五等");
list2.add("安全帽佩戴问题");
list2.add("工作服穿着问题");
list2.add("工地人数问题");
list3.add("2019.12.30");
list3.add("2020.03.12");
list3.add("2020.04.15");
list3.add("2020.02.26");
list3.add("2020.05.05");
adapter1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner1.setAdapter(adapter1);
adapter2=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list2);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner2.setAdapter(adapter2);
adapter3=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list3);
adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner3.setAdapter(adapter3);
mSpinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mTvdg.setText("隐患等级:");
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mTvdg.setText("NONE");
}
});
mSpinner2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mTvzg.setText("整改类型:");
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mTvzg.setText("NONE");
}
});
mSpinner3.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mTvkg.setText("开工日期:");
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mTvkg.setText("NONE");
}
});
mBtn=findViewById(R.id.list_right_btn);
mBtn1=findViewById(R.id.list_right_btn1);
mBtn2=findViewById(R.id.list_right_btn2);
mBtn3=findViewById(R.id.list_right_btn3);
mBtn4=findViewById(R.id.list_right_btn4);
OnClick onClick=new OnClick();
mBtn.setOnClickListener(onClick);
mBtn1.setOnClickListener(onClick);
mBtn2.setOnClickListener(onClick);
mBtn3.setOnClickListener(onClick);
mBtn4.setOnClickListener(onClick);
}
class OnClick implements View.OnClickListener{
@Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()){
case R.id.list_right_btn:
case R.id.list_right_btn3:
case R.id.list_right_btn4:
intent=new Intent(MainActivity.this,MainActivity3.class);
break;
case R.id.list_right_btn1:
case R.id.list_right_btn2:
intent=new Intent(MainActivity.this,MainActivity2.class);
break;
}
startActivity(intent);
}
}
}
| 32.874126 | 97 | 0.630291 |
eeaa735f3633abb6559ec1997be37cf6beb19888 | 4,198 | /**
* (C) Copyright IBM Corp. 2010, 2015
*
* 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.ibm.bi.dml.runtime.transform;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.Counters;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.mapred.lib.NullOutputFormat;
import com.ibm.bi.dml.parser.DataExpression;
import com.ibm.bi.dml.runtime.matrix.data.CSVFileFormatProperties;
import com.ibm.bi.dml.runtime.matrix.mapred.MRJobConfiguration;
/**
* MR Job to Generate Transform Metadata based on a given transformation specification file (JSON format).
*
*/
public class GenTfMtdMR {
public static final String DELIM = ",";
//public static void runJob(String inputPath, String txMtdPath, boolean hasHeader, String delim, String naStrings, String specFile, String smallestFile) throws IOException, ClassNotFoundException, InterruptedException {
public static long runJob(String inputPath, String txMtdPath, String specFileWithIDs, String smallestFile, String partOffsetsFile, CSVFileFormatProperties inputDataProperties, long numCols, int replication, String headerLine) throws IOException, ClassNotFoundException, InterruptedException {
JobConf job = new JobConf(GenTfMtdMR.class);
job.setJobName("GenTfMTD");
/* Setup MapReduce Job */
job.setJarByClass(GenTfMtdMR.class);
// set relevant classes
job.setMapperClass(GTFMTDMapper.class);
job.setReducerClass(GTFMTDReducer.class);
// set input and output properties
job.setInputFormat(TextInputFormat.class);
job.setOutputFormat(NullOutputFormat.class);
job.setMapOutputKeyClass(IntWritable.class);
job.setMapOutputValueClass(DistinctValue.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
job.setInt("dfs.replication", replication);
FileInputFormat.addInputPath(job, new Path(inputPath));
// delete outputPath, if exists already.
Path outPath = new Path(txMtdPath);
FileSystem fs = FileSystem.get(job);
fs.delete(outPath, true);
FileOutputFormat.setOutputPath(job, outPath);
job.set(MRJobConfiguration.TF_HAS_HEADER, Boolean.toString(inputDataProperties.hasHeader()));
job.set(MRJobConfiguration.TF_DELIM, inputDataProperties.getDelim());
if ( inputDataProperties.getNAStrings() != null)
// Adding "dummy" string to handle the case of na_strings = ""
job.set(MRJobConfiguration.TF_NA_STRINGS, inputDataProperties.getNAStrings() + DataExpression.DELIM_NA_STRING_SEP + "dummy");
job.set(MRJobConfiguration.TF_SPEC_FILE, specFileWithIDs);
job.set(MRJobConfiguration.TF_SMALLEST_FILE, smallestFile);
job.setLong(MRJobConfiguration.TF_NUM_COLS, numCols);
job.set(MRJobConfiguration.TF_HEADER, headerLine);
job.set(MRJobConfiguration.OUTPUT_MATRICES_DIRS_CONFIG, txMtdPath);
// offsets file to store part-file names and offsets for each input split
job.set(MRJobConfiguration.TF_OFFSETS_FILE, partOffsetsFile);
//turn off adaptivemr
job.setBoolean("adaptivemr.map.enable", false);
// Run the job
RunningJob runjob = JobClient.runJob(job);
Counters c = runjob.getCounters();
long tx_numRows = c.findCounter(MRJobConfiguration.DataTransformCounters.TRANSFORMED_NUM_ROWS).getCounter();
return tx_numRows;
}
}
| 38.513761 | 293 | 0.782277 |
cac0e10287cebf126a0294dd9dd4c6f5b26c2ce8 | 167 | package com.hellorin.stickyMoss.documents.exceptions;
/**
* Created by hellorin on 28.09.17.
*/
public class DocumentNotFoundException extends RuntimeException {
}
| 20.875 | 65 | 0.784431 |
2256597ba8f30ef9b4c8815f0175882da156b519 | 2,196 | package org.support.project.web.dao;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.support.project.di.Container;
import org.support.project.di.DI;
import org.support.project.di.Instance;
import org.support.project.web.dao.gen.GenLocalesDao;
import org.support.project.web.entity.LocalesEntity;
/**
* ロケール
*/
@DI(instance = Instance.Singleton)
public class LocalesDao extends GenLocalesDao {
/** SerialVersion */
private static final long serialVersionUID = 1L;
/**
* インスタンス取得 AOPに対応
*
* @return インスタンス
*/
public static LocalesDao get() {
return Container.getComp(LocalesDao.class);
}
/**
* ロケールデータを取得
*
* @param locale locale
* @return data
*/
public LocalesEntity selectOrCreate(Locale locale) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT * FROM LOCALES WHERE ");
List<String> params = new ArrayList<>();
if (locale.getLanguage() != null) {
sql.append("LANGUAGE = ? ");
params.add(locale.getLanguage());
} else {
sql.append("LANGUAGE IS NULLL ");
}
if (!params.isEmpty()) {
sql.append("AND ");
}
if (locale.getCountry() != null) {
sql.append("COUNTRY = ? ");
params.add(locale.getCountry());
} else {
sql.append("COUNTRY IS NULLL ");
}
if (!params.isEmpty()) {
sql.append("AND ");
}
if (locale.getVariant() != null) {
sql.append("VARIANT = ? ");
params.add(locale.getVariant());
} else {
sql.append("VARIANT IS NULLL ");
}
LocalesEntity entity = executeQuerySingle(sql.toString(), LocalesEntity.class, params.toArray(new String[0]));
if (entity == null) {
entity = new LocalesEntity();
entity.setKey(locale.toString());
entity.setLanguage(locale.getLanguage());
entity.setCountry(locale.getCountry());
entity.setVariant(locale.getVariant());
insert(entity);
}
return entity;
}
}
| 28.153846 | 118 | 0.57286 |
30e43bc6c619274d9bc872c936bc67c05e5eee68 | 357 | package com.wildspirit.hubspot.search;
public class Sort {
public final String propertyName;
public final Direction direction;
public Sort(String propertyName, Direction direction) {
this.propertyName = propertyName;
this.direction = direction;
}
public enum Direction {
DESCENDING,
ASCENDING
}
}
| 19.833333 | 59 | 0.672269 |
52adc173e482598794486d54724514f0a8036d5a | 13,170 | package com.opencsv.bean;
import com.opencsv.CSVReader;
import com.opencsv.ICSVParser;
import com.opencsv.exceptions.CsvBadConverterException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Allows for the mapping of columns with their positions. Using this strategy
* without annotations ({@link com.opencsv.bean.CsvBindByPosition} or
* {@link com.opencsv.bean.CsvCustomBindByPosition}) requires all the columns
* to be present in the CSV file and for them to be in a particular order. Using
* annotations allows one to specify arbitrary zero-based column numbers for
* each bean member variable to be filled. Also this strategy requires that the
* file does NOT have a header. That said, the main use of this strategy is
* files that do not have headers.
*
* @param <T> Type of object that is being processed.
*/
public class ColumnPositionMappingStrategy<T> extends AbstractMappingStrategy<String, Integer, ComplexFieldMapEntry<String, Integer, T>, T> {
/**
* Whether the user has programmatically set the map from column positions
* to field names.
*/
private boolean columnsExplicitlySet = false;
/**
* The map from column position to {@link BeanField}.
*/
private FieldMapByPosition<T> fieldMap;
/**
* Holds a {@link java.util.Comparator} to sort columns on writing.
*/
private Comparator<Integer> writeOrder;
/**
* Used to store a mapping from presumed input column index to desired
* output column index, as determined by applying {@link #writeOrder}.
*/
private Integer[] columnIndexForWriting = null;
/**
* Default constructor.
*/
public ColumnPositionMappingStrategy() {
}
/**
* There is no header per se for this mapping strategy, but this method
* checks the first line to determine how many fields are present and
* adjusts its field map accordingly.
*/
// The rest of the Javadoc is inherited
@Override
public void captureHeader(CSVReader reader) throws IOException {
// Validation
if (type == null) {
throw new IllegalStateException(ResourceBundle
.getBundle(ICSVParser.DEFAULT_BUNDLE_NAME, errorLocale)
.getString("type.unset"));
}
String[] firstLine = ObjectUtils.defaultIfNull(reader.peek(), ArrayUtils.EMPTY_STRING_ARRAY);
fieldMap.setMaxIndex(firstLine.length - 1);
if (!columnsExplicitlySet) {
headerIndex.clear();
for (FieldMapByPositionEntry<T> entry : fieldMap) {
Field f = entry.getField().getField();
if (f.getAnnotation(CsvCustomBindByPosition.class) != null
|| f.getAnnotation(CsvBindAndSplitByPosition.class) != null
|| f.getAnnotation(CsvBindAndJoinByPosition.class) != null
|| f.getAnnotation(CsvBindByPosition.class) != null) {
headerIndex.put(entry.getPosition(), f.getName().toUpperCase().trim());
}
}
}
}
/**
* @return {@inheritDoc} For this mapping strategy, it's simply
* {@code index} wrapped as an {@link java.lang.Integer}.
*/
// The rest of the Javadoc is inherited
@Override
protected Integer chooseMultivaluedFieldIndexFromHeaderIndex(int index) {
return Integer.valueOf(index);
}
@Override
protected BeanField<T, Integer> findField(int col) {
// If we have a mapping for changing the order of the columns on
// writing, be sure to use it.
if (columnIndexForWriting != null) {
return col < columnIndexForWriting.length ? fieldMap.get(columnIndexForWriting[col]) : null;
}
return fieldMap.get(col);
}
/**
* This method returns an empty array.
* The column position mapping strategy assumes that there is no header, and
* thus it also does not write one, accordingly.
*
* @return An empty array
*/
// The rest of the Javadoc is inherited
@Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] h = super.generateHeader(bean);
columnIndexForWriting = new Integer[h.length];
Arrays.setAll(columnIndexForWriting, i -> i);
// Create the mapping for input column index to output column index.
Arrays.sort(columnIndexForWriting, writeOrder);
return ArrayUtils.EMPTY_STRING_ARRAY;
}
/**
* Gets a column name.
*
* @param col Position of the column.
* @return Column name or null if col > number of mappings.
*/
@Override
public String getColumnName(int col) {
return headerIndex.getByPosition(col);
}
/**
* Retrieves the column mappings.
*
* @return String array with the column mappings.
*/
public String[] getColumnMapping() {
return headerIndex.getHeaderIndex();
}
/**
* Setter for the column mapping.
* This mapping is for reading. Use of this method in conjunction with
* writing is undefined.
*
* @param columnMapping Column names to be mapped.
*/
public void setColumnMapping(String... columnMapping) {
if (columnMapping != null) {
headerIndex.initializeHeaderIndex(columnMapping);
} else {
headerIndex.clear();
}
columnsExplicitlySet = true;
if(getType() != null) {
loadFieldMap(); // In case setType() was called first.
}
}
private void loadAnnotatedFieldMap(List<Field> fields) {
boolean required;
for (Field field : fields) {
String fieldLocale, capture, format;
// Custom converters always have precedence.
if (field.isAnnotationPresent(CsvCustomBindByPosition.class)) {
CsvCustomBindByPosition annotation = field
.getAnnotation(CsvCustomBindByPosition.class);
@SuppressWarnings("unchecked")
Class<? extends AbstractBeanField<T, Integer>> converter = (Class<? extends AbstractBeanField<T, Integer>>)annotation.converter();
BeanField<T, Integer> bean = instantiateCustomConverter(converter);
bean.setField(field);
required = annotation.required();
bean.setRequired(required);
fieldMap.put(annotation.position(), bean);
}
// Then check for a collection
else if (field.isAnnotationPresent(CsvBindAndSplitByPosition.class)) {
CsvBindAndSplitByPosition annotation = field.getAnnotation(CsvBindAndSplitByPosition.class);
required = annotation.required();
fieldLocale = annotation.locale();
String splitOn = annotation.splitOn();
String writeDelimiter = annotation.writeDelimiter();
Class<? extends Collection> collectionType = annotation.collectionType();
Class<?> elementType = annotation.elementType();
Class<? extends AbstractCsvConverter> splitConverter = annotation.converter();
capture = annotation.capture();
format = annotation.format();
CsvConverter converter = determineConverter(field, elementType, fieldLocale, splitConverter);
fieldMap.put(annotation.position(), new BeanFieldSplit<>(
field, required, errorLocale, converter, splitOn,
writeDelimiter, collectionType, capture, format));
}
// Then check for a multi-column annotation
else if (field.isAnnotationPresent(CsvBindAndJoinByPosition.class)) {
CsvBindAndJoinByPosition annotation = field.getAnnotation(CsvBindAndJoinByPosition.class);
required = annotation.required();
fieldLocale = annotation.locale();
Class<?> elementType = annotation.elementType();
Class<? extends MultiValuedMap> mapType = annotation.mapType();
Class<? extends AbstractCsvConverter> joinConverter = annotation.converter();
capture = annotation.capture();
format = annotation.format();
CsvConverter converter = determineConverter(field, elementType, fieldLocale, joinConverter);
fieldMap.putComplex(annotation.position(), new BeanFieldJoinIntegerIndex<>(
field, required, errorLocale, converter, mapType, capture, format));
}
// Then it must be a bind by position.
else {
CsvBindByPosition annotation = field.getAnnotation(CsvBindByPosition.class);
required = annotation.required();
fieldLocale = annotation.locale();
capture = annotation.capture();
format = annotation.format();
CsvConverter converter = determineConverter(field, field.getType(), fieldLocale, null);
fieldMap.put(annotation.position(), new BeanFieldSingleValue<>(
field, required, errorLocale, converter, capture, format));
}
}
}
private void loadUnadornedFieldMap(List<Field> fields) {
for(Field field : fields) {
CsvConverter converter = determineConverter(field, field.getType(), null, null);
int[] indices = headerIndex.getByName(field.getName());
if(indices.length != 0) {
fieldMap.put(indices[0], new BeanFieldSingleValue<>(
field, false, errorLocale, converter, null, null));
}
}
}
@Override
protected void loadFieldMap() throws CsvBadConverterException {
fieldMap = new FieldMapByPosition<>(errorLocale);
fieldMap.setColumnOrderOnWrite(writeOrder);
Map<Boolean, List<Field>> partitionedFields = Stream.of(FieldUtils.getAllFields(getType()))
.filter(f -> !f.isSynthetic())
.collect(Collectors.partitioningBy(
f -> f.isAnnotationPresent(CsvBindByPosition.class)
|| f.isAnnotationPresent(CsvCustomBindByPosition.class)
|| f.isAnnotationPresent(CsvBindAndJoinByPosition.class)
|| f.isAnnotationPresent(CsvBindAndSplitByPosition.class)));
if(!partitionedFields.get(Boolean.TRUE).isEmpty()) {
loadAnnotatedFieldMap(partitionedFields.get(Boolean.TRUE));
}
else {
loadUnadornedFieldMap(partitionedFields.get(Boolean.FALSE));
}
}
@Override
protected void verifyLineLength(int numberOfFields) throws CsvRequiredFieldEmptyException {
if (!headerIndex.isEmpty()) {
BeanField<T, Integer> f;
StringBuilder sb = null;
for (int i = numberOfFields; i <= headerIndex.findMaxIndex(); i++) {
f = findField(i);
if (f != null && f.isRequired()) {
if (sb == null) {
sb = new StringBuilder(ResourceBundle.getBundle(ICSVParser.DEFAULT_BUNDLE_NAME, errorLocale).getString("multiple.required.field.empty"));
}
sb.append(' ');
sb.append(f.getField().getName());
}
}
if (sb != null) {
throw new CsvRequiredFieldEmptyException(type, sb.toString());
}
}
}
/**
* Returns the column position for the given column number.
* Yes, they're the same thing. For this mapping strategy, it's a simple
* conversion from an integer to a string.
*/
// The rest of the Javadoc is inherited
@Override
public String findHeader(int col) {
return Integer.toString(col);
}
@Override
protected FieldMap<String, Integer, ? extends ComplexFieldMapEntry<String, Integer, T>, T> getFieldMap() {
return fieldMap;
}
/**
* Sets the {@link java.util.Comparator} to be used to sort columns when
* writing beans to a CSV file.
* Behavior of this method when used on a mapping strategy intended for
* reading data from a CSV source is not defined.
*
* @param writeOrder The {@link java.util.Comparator} to use. May be
* {@code null}, in which case the natural ordering is used.
* @since 4.3
*/
public void setColumnOrderOnWrite(Comparator<Integer> writeOrder) {
this.writeOrder = writeOrder;
if (fieldMap != null) {
fieldMap.setColumnOrderOnWrite(this.writeOrder);
}
}
}
| 40.900621 | 161 | 0.623766 |
d7588a8a0bb3fa314b04779ccd9aeca8cd7f08c5 | 2,038 | /*******************************************************************************
* Copyright 2019 T-Mobile USA, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
* See the LICENSE file for additional language around disclaimer of warranties.
* Trademark Disclaimer: Neither the name of "T-Mobile, USA" nor the names of
* its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
******************************************************************************/
package com.tmobile.kardio.surveiller.util;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
/**
* Class to handle the JSON validation
*/
public class JSONUtil {
private static final Logger logger = Logger.getLogger(JSONUtil.class);
private JSONUtil() {}
/**
* Function to validate the json string
* @param json
* @return
*/
public static boolean isJSONValid(String json) {
boolean valid = false;
try {
final JsonParser parser = new ObjectMapper().getJsonFactory()
.createJsonParser(json);
while (parser.nextToken() != null) {
}
valid = true;
} catch (JsonParseException jpe) {
logger.error("Invalid JSON String JsonParseException");
} catch (IOException ioe) {
logger.error("Invalid JSON String IOException");
}
return valid;
}
}
| 35.137931 | 80 | 0.661923 |
6f84accdc835d7993507997d01ec8da124cd8b88 | 1,954 | package com.gemography.challenge.svc;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gemography.challenge.model.RepoItem;
import com.gemography.challenge.model.TrendingDTO;
import com.gemography.challenge.model.TrendingResponseDTO;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.info.Info;
@OpenAPIDefinition(
info = @Info(
title = "Github trending repositories",
description = "Fetching the most starred repos created in the last 30 days"
)
)
@RestController
@RequestMapping("github-trending")
public class TrendingRestService {
@Autowired
ITrendingService serviceTrending;
@GetMapping("/all")
public TrendingResponseDTO getListRepo(@Parameter(allowEmptyValue = false,
example = "2021-04-20", description = "date format YYYY-MM-DD")
@PathParam("date") @DateTimeFormat(iso = ISO.DATE) Date date) {
List<RepoItem> reposItem = serviceTrending.getListRepo(date).getItems();
return new TrendingResponseDTO(reposItem.stream().map(RepoItem::getLanguage)
.distinct()
.map(r1 -> {
TrendingDTO trending = new TrendingDTO();
trending.setLanguage(r1);
reposItem.stream()
.filter(r2 -> r1.equals(r2.getLanguage()))
.forEach(r2 -> trending.addUrl(r2.getHtml_url()));
return trending;
})
.collect(Collectors.toList()));
}
}
| 34.280702 | 85 | 0.730297 |
60974fb309ede02a60a831ca463d835bc7739b3a | 9,210 | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.web.servlet;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceEditor;
import org.springframework.core.io.ResourceLoader;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.ServletContextResourceLoader;
import org.springframework.web.context.support.StandardServletEnvironment;
/**
* Simple extension of {@link javax.servlet.http.HttpServlet} which treats
* its config parameters ({@code init-param} entries within the
* {@code servlet} tag in {@code web.xml}) as bean properties.
*
* <p>A handy superclass for any type of servlet. Type conversion of config
* parameters is automatic, with the corresponding setter method getting
* invoked with the converted value. It is also possible for subclasses to
* specify required properties. Parameters without matching bean property
* setter will simply be ignored.
*
* <p>This servlet leaves request handling to subclasses, inheriting the default
* behavior of HttpServlet ({@code doGet}, {@code doPost}, etc).
*
* <p>This generic servlet base class has no dependency on the Spring
* {@link org.springframework.context.ApplicationContext} concept. Simple
* servlets usually don't load their own context but rather access service
* beans from the Spring root application context, accessible via the
* filter's {@link #getServletContext() ServletContext} (see
* {@link org.springframework.web.context.support.WebApplicationContextUtils}).
*
* <p>The {@link FrameworkServlet} class is a more specific servlet base
* class which loads its own application context. FrameworkServlet serves
* as direct base class of Spring's full-fledged {@link DispatcherServlet}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see #addRequiredProperty
* @see #initServletBean
* @see #doGet
* @see #doPost
*/
@SuppressWarnings("serial")
public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware {
private static org.slf4j.Logger log=org.slf4j.LoggerFactory.getLogger(HttpServletBean.class);
/** Logger available to subclasses. */
protected final Log logger = LogFactory.getLog(getClass());
@Nullable
private ConfigurableEnvironment environment;
private final Set<String> requiredProperties = new HashSet<>(4);
/**
* Subclasses can invoke this method to specify that this property
* (which must match a JavaBean property they expose) is mandatory,
* and must be supplied as a config parameter. This should be called
* from the constructor of a subclass.
* <p>This method is only relevant in case of traditional initialization
* driven by a ServletConfig instance.
* @param property name of the required property
*/
protected final void addRequiredProperty(String property) {
this.requiredProperties.add(property);
}
/**
* Set the {@code Environment} that this servlet runs in.
* <p>Any environment set here overrides the {@link StandardServletEnvironment}
* provided by default.
* @throws IllegalArgumentException if environment is not assignable to
* {@code ConfigurableEnvironment}
*/
@Override
public void setEnvironment(Environment environment) {
Assert.isInstanceOf(ConfigurableEnvironment.class, environment, "ConfigurableEnvironment required");
this.environment = (ConfigurableEnvironment) environment;
}
/**
* Return the {@link Environment} associated with this servlet.
* <p>If none specified, a default environment will be initialized via
* {@link #createEnvironment()}.
*/
@Override
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}
/**
* Create and return a new {@link StandardServletEnvironment}.
* <p>Subclasses may override this in order to configure the environment or
* specialize the environment type returned.
*/
protected ConfigurableEnvironment createEnvironment() {
return new StandardServletEnvironment();
}
/**
* Map config parameters onto bean properties of this servlet, and
* invoke subclass initialization.
* @throws ServletException if bean properties are invalid (or required
* properties are missing), or if subclass initialization fails.
*/
@Override
public final void init() throws ServletException {
log.info("--init()");
// Set bean properties from init parameters.
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
log.info(this.getClass()+"-init()");
// Let subclasses do whatever initialization they like.
initServletBean();
}
/**
* Initialize the BeanWrapper for this HttpServletBean,
* possibly with custom editors.
* <p>This default implementation is empty.
* @param bw the BeanWrapper to initialize
* @throws BeansException if thrown by BeanWrapper methods
* @see org.springframework.beans.BeanWrapper#registerCustomEditor
*/
protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
}
/**
* Subclasses may override this to perform custom initialization.
* All bean properties of this servlet will have been set before this
* method is invoked.
* <p>This default implementation is empty.
* @throws ServletException if subclass initialization fails
*/
protected void initServletBean() throws ServletException {
}
/**
* Overridden method that simply returns {@code null} when no
* ServletConfig set yet.
* @see #getServletConfig()
*/
@Override
@Nullable
public String getServletName() {
return (getServletConfig() != null ? getServletConfig().getServletName() : null);
}
/**
* PropertyValues implementation created from ServletConfig init parameters.
*/
private static class ServletConfigPropertyValues extends MutablePropertyValues {
/**
* Create new ServletConfigPropertyValues.
* @param config the ServletConfig we'll use to take PropertyValues from
* @param requiredProperties set of property names we need, where
* we can't accept default values
* @throws ServletException if any required properties are missing
*/
public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
throws ServletException {
Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ?
new HashSet<>(requiredProperties) : null);
Enumeration<String> paramNames = config.getInitParameterNames();
while (paramNames.hasMoreElements()) {
String property = paramNames.nextElement();
Object value = config.getInitParameter(property);
addPropertyValue(new PropertyValue(property, value));
if (missingProps != null) {
missingProps.remove(property);
}
}
// Fail if we are still missing properties.
if (!CollectionUtils.isEmpty(missingProps)) {
throw new ServletException(
"Initialization from ServletConfig for servlet '" + config.getServletName() +
"' failed; the following required properties were missing: " +
StringUtils.collectionToDelimitedString(missingProps, ", "));
}
}
}
}
| 37.439024 | 107 | 0.762866 |
3ed98cd840bef8fdb0d27400c927cf149ce3d7f4 | 1,312 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.trogdor.workload;
/**
* Describes a key in producer payload
*/
public enum PayloadKeyType {
// null key
KEY_NULL(0),
// fixed size key containing a long integer representing a message index (i.e., position of
// the payload generator)
KEY_MESSAGE_INDEX(8);
private final int maxSizeInBytes;
PayloadKeyType(int maxSizeInBytes) {
this.maxSizeInBytes = maxSizeInBytes;
}
public int maxSizeInBytes() {
return maxSizeInBytes;
}
}
| 32.8 | 95 | 0.728659 |
2f321374a77cf100d39adf21ba7b44b75ca39b88 | 724 | package com.bombhunt.game.model.ecs.systems;
import com.badlogic.gdx.math.Vector3;
/**
* Created by samuel on 20/04/18.
*/
public enum DIRECTION_ENUM {
UP(0, false, new Vector3(0, 1, 0)),
DOWN(1, false, new Vector3(0, -1, 0)),
LEFT(4, true, new Vector3(-1, 0, 0)),
RIGHT(4, false, new Vector3(1, 0, 0));
private int frame;
private boolean flip;
private Vector3 vector;
DIRECTION_ENUM(int frame, boolean flip, Vector3 vector) {
this.frame = frame;
this.flip = flip;
this.vector = vector;
}
public int getFrame(){
return frame;
}
public boolean isFlip() {
return flip;
}
public Vector3 getVector() { return vector; }
}
| 20.111111 | 61 | 0.603591 |
3f8be31cb6734023fda60ac4e9bbd82ce88252bd | 10,836 | package de.avalax.mtg_insight.presentation.card;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import de.avalax.mtg_insight.R;
import de.avalax.mtg_insight.application.representation.CardRepresentation;
import de.avalax.mtg_insight.domain.model.card.Card;
import de.avalax.mtg_insight.domain.model.color.Color;
import de.avalax.mtg_insight.domain.model.mana.ConvertedManaCost;
import de.bechte.junit.runners.context.HierarchicalContextRunner;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
@RunWith(HierarchicalContextRunner.class)
public class CardRepresentationToDrawableTest {
@InjectMocks
private CardRepresentationToDrawable cardRepresentationToDrawable;
@Mock
private Context context;
@Mock
private Drawable colorlessDrawable;
@Mock
private Drawable greenDrawable;
@Mock
private Resources resources;
@Mock
private Drawable blackDrawable;
@Mock
private Drawable whiteDrawable;
@Mock
private Drawable blueDrawable;
@Mock
private Drawable redDrawable;
@Mock
private Drawable multicolorDrawable;
private Drawable drawable(int resource) {
return ContextCompat.getDrawable(context, resource);
}
private CardRepresentation cardRepresentationFor(Color... colors) {
final List<Color> colorOfCard = new ArrayList<>();
Collections.addAll(colorOfCard, colors);
Card card = new Card() {
@Override
public String name() {
return null;
}
@Override
public List<Color> colorOfCard() {
return colorOfCard;
}
@Override
public ConvertedManaCost convertedManaCost() {
return null;
}
};
return new CardRepresentation(card);
}
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
when(context.getResources()).thenReturn(resources);
}
public class backgroundDrawable {
@Before
public void setUp() throws Exception {
when(resources.getDrawable(R.drawable.background_colorless)).thenReturn(colorlessDrawable);
when(resources.getDrawable(R.drawable.background_green)).thenReturn(greenDrawable);
when(resources.getDrawable(R.drawable.background_black)).thenReturn(blackDrawable);
when(resources.getDrawable(R.drawable.background_white)).thenReturn(whiteDrawable);
when(resources.getDrawable(R.drawable.background_blue)).thenReturn(blueDrawable);
when(resources.getDrawable(R.drawable.background_red)).thenReturn(redDrawable);
when(resources.getDrawable(R.drawable.background_multicolor)).thenReturn(multicolorDrawable);
}
@Test
public void shouldReturnBackground() throws Exception {
assertThat(cardRepresentationToDrawable.backgroundFrom(null), equalTo(drawable(R.drawable.background_colorless)));
assertThat(cardRepresentationToDrawable.backgroundFrom(cardRepresentationFor()), equalTo(drawable(R.drawable.background_colorless)));
assertThat(cardRepresentationToDrawable.backgroundFrom(cardRepresentationFor(Color.GREEN)), equalTo(drawable(R.drawable.background_green)));
assertThat(cardRepresentationToDrawable.backgroundFrom(cardRepresentationFor(Color.BLACK)), equalTo(drawable(R.drawable.background_black)));
assertThat(cardRepresentationToDrawable.backgroundFrom(cardRepresentationFor(Color.WHITE)), equalTo(drawable(R.drawable.background_white)));
assertThat(cardRepresentationToDrawable.backgroundFrom(cardRepresentationFor(Color.BLUE)), equalTo(drawable(R.drawable.background_blue)));
assertThat(cardRepresentationToDrawable.backgroundFrom(cardRepresentationFor(Color.RED)), equalTo(drawable(R.drawable.background_red)));
assertThat(cardRepresentationToDrawable.backgroundFrom(cardRepresentationFor(Color.RED, Color.BLACK)), equalTo(drawable(R.drawable.background_multicolor)));
}
}
public class windowBackgroundDrawable {
@Before
public void setUp() throws Exception {
when(resources.getDrawable(R.drawable.window_colorless)).thenReturn(colorlessDrawable);
when(resources.getDrawable(R.drawable.window_green)).thenReturn(greenDrawable);
when(resources.getDrawable(R.drawable.window_black)).thenReturn(blackDrawable);
when(resources.getDrawable(R.drawable.window_white)).thenReturn(whiteDrawable);
when(resources.getDrawable(R.drawable.window_blue)).thenReturn(blueDrawable);
when(resources.getDrawable(R.drawable.window_red)).thenReturn(redDrawable);
when(resources.getDrawable(R.drawable.window_multicolor)).thenReturn(multicolorDrawable);
}
@Test
public void shouldReturnWindowBackground() throws Exception {
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(null), equalTo(drawable(R.drawable.window_colorless)));
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(cardRepresentationFor()), equalTo(drawable(R.drawable.window_colorless)));
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(cardRepresentationFor(Color.GREEN)), equalTo(drawable(R.drawable.window_green)));
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(cardRepresentationFor(Color.BLACK)), equalTo(drawable(R.drawable.window_black)));
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(cardRepresentationFor(Color.WHITE)), equalTo(drawable(R.drawable.window_white)));
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(cardRepresentationFor(Color.BLUE)), equalTo(drawable(R.drawable.window_blue)));
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(cardRepresentationFor(Color.RED)), equalTo(drawable(R.drawable.window_red)));
assertThat(cardRepresentationToDrawable.windowBackgroundFrom(cardRepresentationFor(Color.RED, Color.BLACK)), equalTo(drawable(R.drawable.window_multicolor)));
}
}
public class cardBackgroundDrawable {
@Before
public void setUp() throws Exception {
when(resources.getDrawable(R.drawable.card_background_colorless)).thenReturn(colorlessDrawable);
when(resources.getDrawable(R.drawable.card_background_green)).thenReturn(greenDrawable);
when(resources.getDrawable(R.drawable.card_background_black)).thenReturn(blackDrawable);
when(resources.getDrawable(R.drawable.card_background_white)).thenReturn(whiteDrawable);
when(resources.getDrawable(R.drawable.card_background_blue)).thenReturn(blueDrawable);
when(resources.getDrawable(R.drawable.card_background_red)).thenReturn(redDrawable);
when(resources.getDrawable(R.drawable.card_background_multicolor)).thenReturn(multicolorDrawable);
}
@Test
public void shouldReturnBackground() throws Exception {
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(null), equalTo(drawable(R.drawable.card_background_colorless)));
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(cardRepresentationFor()), equalTo(drawable(R.drawable.card_background_colorless)));
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(cardRepresentationFor(Color.GREEN)), equalTo(drawable(R.drawable.card_background_green)));
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(cardRepresentationFor(Color.BLACK)), equalTo(drawable(R.drawable.card_background_black)));
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(cardRepresentationFor(Color.WHITE)), equalTo(drawable(R.drawable.card_background_white)));
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(cardRepresentationFor(Color.BLUE)), equalTo(drawable(R.drawable.card_background_blue)));
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(cardRepresentationFor(Color.RED)), equalTo(drawable(R.drawable.card_background_red)));
assertThat(cardRepresentationToDrawable.cardBackgroundFrom(cardRepresentationFor(Color.RED, Color.BLACK)), equalTo(drawable(R.drawable.card_background_multicolor)));
}
}
public class headerDrawable {
@Before
public void setUp() throws Exception {
when(resources.getDrawable(R.drawable.header_colorless)).thenReturn(colorlessDrawable);
when(resources.getDrawable(R.drawable.header_green)).thenReturn(greenDrawable);
when(resources.getDrawable(R.drawable.header_black)).thenReturn(blackDrawable);
when(resources.getDrawable(R.drawable.header_white)).thenReturn(whiteDrawable);
when(resources.getDrawable(R.drawable.header_blue)).thenReturn(blueDrawable);
when(resources.getDrawable(R.drawable.header_red)).thenReturn(redDrawable);
when(resources.getDrawable(R.drawable.header_multicolor)).thenReturn(multicolorDrawable);
}
@Test
public void shouldReturnHeaderDrawable() throws Exception {
assertThat(cardRepresentationToDrawable.headerFrom(null), equalTo(drawable(R.drawable.header_colorless)));
assertThat(cardRepresentationToDrawable.headerFrom(cardRepresentationFor()), equalTo(drawable(R.drawable.header_colorless)));
assertThat(cardRepresentationToDrawable.headerFrom(cardRepresentationFor(Color.GREEN)), equalTo(drawable(R.drawable.header_green)));
assertThat(cardRepresentationToDrawable.headerFrom(cardRepresentationFor(Color.BLACK)), equalTo(drawable(R.drawable.header_black)));
assertThat(cardRepresentationToDrawable.headerFrom(cardRepresentationFor(Color.WHITE)), equalTo(drawable(R.drawable.header_white)));
assertThat(cardRepresentationToDrawable.headerFrom(cardRepresentationFor(Color.BLUE)), equalTo(drawable(R.drawable.header_blue)));
assertThat(cardRepresentationToDrawable.headerFrom(cardRepresentationFor(Color.RED)), equalTo(drawable(R.drawable.header_red)));
assertThat(cardRepresentationToDrawable.headerFrom(cardRepresentationFor(Color.RED, Color.BLACK)), equalTo(drawable(R.drawable.header_multicolor)));
}
}
} | 57.638298 | 177 | 0.751107 |
cf7793fef033dc08b8b1a0cfe591448368c15804 | 173 | package cn.jeeweb.core.tags.form;
public class ErrorsTag extends org.springframework.web.servlet.tags.form.ErrorsTag {
private static final long serialVersionUID = 1L;
}
| 24.714286 | 84 | 0.803468 |
8de4402a7f668396769fb3f18ba4867773f280e1 | 45,563 | /*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* 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.seasar.aptina.unit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.Writer;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject.Kind;
import junit.framework.ComparisonFailure;
import junit.framework.TestCase;
import static java.util.Arrays.*;
import static org.seasar.aptina.unit.AssertionUtils.*;
import static org.seasar.aptina.unit.CollectionUtils.*;
import static org.seasar.aptina.unit.IOUtils.*;
/**
* {@link Processor} をテストするための抽象クラスです.
* <p>
* サブクラスのテストメソッドでは,コンパイルオプションやコンパイル対象などを設定して {@link #compile()} メソッドを呼び出します.
* コンパイル後に生成されたソースの検証などを行うことができます.
* </p>
* <dl>
* <dt>{@link #compile()} 前に以下のメソッドを呼び出すことができます ({@link #setUp()}から呼び出すこともできます).
* </dt>
* <dd>
* <ul>
* <li>{@link #setLocale(Locale)}</li>
* <li>{@link #setLocale(String)}</li>
* <li>{@link #setCharset(Charset)}</li>
* <li>{@link #setCharset(String)}</li>
* <li>{@link #setOut(Writer)}</li>
* <li>{@link #addSourcePath(File...)}</li>
* <li>{@link #addSourcePath(String...)}</li>
* <li>{@link #addOption(String...)}</li>
* <li>{@link #addProcessor(Processor...)}</li>
* <li>{@link #addCompilationUnit(Class)}</li>
* <li>{@link #addCompilationUnit(String)}</li>
* <li>{@link #addCompilationUnit(Class, CharSequence)}</li>
* <li>{@link #addCompilationUnit(String, CharSequence)}</li>
* </ul>
* </dd>
* <dt>{@link #compile()} 後に以下のメソッドを呼び出して情報を取得することができます.</dt>
* <dd>
* <ul>
* <li>{@link #getCompiledResult()}</li>
* <li>{@link #getDiagnostics()}</li>
* <li>{@link #getDiagnostics(Class)}</li>
* <li>{@link #getDiagnostics(String)}</li>
* <li>{@link #getDiagnostics(javax.tools.Diagnostic.Kind)}</li>
* <li>{@link #getDiagnostics(Class, javax.tools.Diagnostic.Kind)}</li>
* <li>{@link #getDiagnostics(String, javax.tools.Diagnostic.Kind)}</li>
* <li>{@link #getProcessingEnvironment()}</li>
* <li>{@link #getElementUtils()}</li>
* <li>{@link #getTypeUtils()}</li>
* <li>{@link #getTypeElement(Class)}</li>
* <li>{@link #getTypeElement(String)}</li>
* <li>{@link #getFieldElement(TypeElement, Field)}</li>
* <li>{@link #getFieldElement(TypeElement, String)}</li>
* <li>{@link #getConstructorElement(TypeElement)}</li>
* <li>{@link #getConstructorElement(TypeElement, Class...)}</li>
* <li>{@link #getConstructorElement(TypeElement, String...)}</li>
* <li>{@link #getMethodElement(TypeElement, String)}</li>
* <li>{@link #getMethodElement(TypeElement, String, Class...)}</li>
* <li>{@link #getMethodElement(TypeElement, String, String...)}</li>
* <li>{@link #getTypeMirror(Class)}</li>
* <li>{@link #getTypeMirror(String)}</li>
* <li>{@link #getGeneratedSource(Class)}</li>
* <li>{@link #getGeneratedSource(String)}</li>
* </ul>
* </dd>
* <dt>{@link #compile()} 後に以下のメソッドを呼び出して生成されたソースの内容を検証することができます.</dt>
* <dd>
* <ul>
* <li>{@link #assertEqualsGeneratedSource(CharSequence, Class)}</li>
* <li>{@link #assertEqualsGeneratedSource(CharSequence, String)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithFile(File, Class)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithFile(File, String)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithFile(String, Class)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithFile(String, String)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithResource(URL, Class)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithResource(URL, String)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithResource(String, Class)}</li>
* <li>{@link #assertEqualsGeneratedSourceWithResource(String, String)}</li>
* </ul>
* </dd>
* </dl>
* <p>
* {@link #compile()} を呼び出した後に状態をリセットしてコンパイル前の状態に戻すには, {@link #reset()} を呼び出します.
* </p>
*
* <p>
* 次のサンプルは, {@code src/test/java} フォルダにある {@code TestSource.java} をコンパイルすると,
* {@code foo.bar.Baz} クラスのソースを生成する {@code TestProcessor} のテストクラスです.
* </p>
*
* <pre>
* public class TestProcessorTest extends AptinaTestCase {
*
* @Override
* protected void setUp() throws Exception {
* super.setUp();
* // ソースパスを追加
* addSourcePath("src/test/java");
* }
*
* public void test() throws Exception {
* // テスト対象の Annotation Processor を生成して追加
* TestProcessor processor = new TestProcessor();
* addProcessor(processor);
*
* // コンパイル対象を追加
* addCompilationUnit(TestSource.class);
*
* // コンパイル実行
* compile();
*
* // テスト対象の Annotation Processor が生成したソースを検証
* assertEqualsGeneratedSource("package foo.bar; public class Baz {}",
* "foo.bar.Baz");
* }
*
* }
* </pre>
*
* @author koichik
*/
public abstract class AptinaTestCase extends TestCase {
Locale locale;
Charset charset;
Writer out;
final List<String> options = newArrayList();
final List<File> sourcePaths = newArrayList();
final List<Processor> processors = newArrayList();
{
processors.add(new AptinaUnitProcessor());
}
final List<CompilationUnit> compilationUnits = newArrayList();
JavaCompiler javaCompiler;
DiagnosticCollector<JavaFileObject> diagnostics;
StandardJavaFileManager standardJavaFileManager;
JavaFileManager testingJavaFileManager;
ProcessingEnvironment processingEnvironment;
Boolean compiledResult;
/**
* インスタンスを構築します.
*/
protected AptinaTestCase() {
}
/**
* インスタンスを構築します.
*
* @param name
* 名前
*/
protected AptinaTestCase(final String name) {
super(name);
}
@Override
protected void tearDown() throws Exception {
if (testingJavaFileManager != null) {
try {
testingJavaFileManager.close();
} catch (final Exception ignore) {
}
}
super.tearDown();
}
/**
* ロケールを返します.
*
* @return ロケールまたは {@code null}
*/
protected Locale getLocale() {
return locale;
}
/**
* ロケールを設定します.
* <p>
* 設定されなかった場合はプラットフォームデフォルトのロケールが使われます.
* </p>
*
* @param locale
* ロケール
* @see Locale#getDefault()
*/
protected void setLocale(final Locale locale) {
this.locale = locale;
}
/**
* ロケールを設定します.
* <p>
* 設定されなかった場合はプラットフォームデフォルトのロケールが使われます.
* </p>
*
* @param locale
* ロケール
* @see Locale#getDefault()
*/
protected void setLocale(final String locale) {
assertNotEmpty("locale", locale);
setLocale(new Locale(locale));
}
/**
* 文字セットを返します.
*
* @return 文字セットまたは {@code null}
*/
protected Charset getCharset() {
return charset;
}
/**
* 文字セットを設定します.
* <p>
* 設定されなかった場合はプラットフォームデフォルトの文字セットが使われます.
* </p>
*
* @param charset
* 文字セット
* @see Charset#defaultCharset()
*/
protected void setCharset(final Charset charset) {
this.charset = charset;
}
/**
* 文字セットを設定します.
* <p>
* 設定されなかった場合はプラットフォームデフォルトの文字セットが使われます.
* </p>
*
* @param charset
* 文字セット
* @see Charset#defaultCharset()
*/
protected void setCharset(final String charset) {
assertNotEmpty("charset", charset);
setCharset(Charset.forName(charset));
}
/**
* コンパイラがメッセージを出力する{@link Writer}を設定します.
* <p>
* 設定されなかった場合は標準エラーが使われます.
* </p>
*
* @param out
* コンパイラがメッセージを出力する{@link Writer}
*/
protected void setOut(final Writer out) {
this.out = out;
}
/**
* コンパイル時に参照するソースパスを追加します.
*
* @param sourcePaths
* コンパイル時に参照するソースパスの並び
*/
protected void addSourcePath(final File... sourcePaths) {
assertNotEmpty("sourcePaths", sourcePaths);
this.sourcePaths.addAll(asList(sourcePaths));
}
/**
* コンパイル時に参照するソースパスを追加します.
*
* @param sourcePaths
* コンパイル時に参照するソースパスの並び
*/
protected void addSourcePath(final String... sourcePaths) {
assertNotEmpty("sourcePaths", sourcePaths);
for (final String path : sourcePaths) {
this.sourcePaths.add(new File(path));
}
}
/**
* コンパイラオプションを追加します.
*
* @param options
* 形式のコンパイラオプションの並び
*/
protected void addOption(final String... options) {
assertNotEmpty("options", options);
this.options.addAll(asList(options));
}
/**
* 注釈を処理する{@link Processor}を追加します.
*
* @param processors
* 注釈を処理する{@link Processor}の並び
*/
protected void addProcessor(final Processor... processors) {
assertNotEmpty("processors", processors);
this.processors.addAll(asList(processors));
}
/**
* コンパイル対象のクラスを追加します.
* <p>
* 指定されたクラスのソースはソースパス上に存在していなければなりません.
* </p>
*
* @param clazz
* コンパイル対象クラス
*/
protected void addCompilationUnit(final Class<?> clazz) {
AssertionUtils.assertNotNull("clazz", clazz);
addCompilationUnit(clazz.getName());
}
/**
* コンパイル対象のクラスを追加します.
* <p>
* 指定されたクラスのソースはソースパス上に存在していなければなりません.
* </p>
*
* @param className
* コンパイル対象クラスの完全限定名
*/
protected void addCompilationUnit(final String className) {
assertNotEmpty("className", className);
compilationUnits.add(new FileCompilationUnit(className));
}
/**
* コンパイル対象のクラスをソースとともに追加します.
*
* @param clazz
* コンパイル対象クラス
* @param source
* ソース
*/
protected void addCompilationUnit(final Class<?> clazz,
final CharSequence source) {
AssertionUtils.assertNotNull("clazz", clazz);
assertNotEmpty("source", source);
addCompilationUnit(clazz.getName(), source);
}
/**
* コンパイル対象のクラスをソースとともに追加します.
*
* @param className
* コンパイル対象クラスの完全限定名
* @param source
* ソース
*/
protected void addCompilationUnit(final String className,
final CharSequence source) {
assertNotEmpty("className", className);
assertNotEmpty("source", source);
compilationUnits.add(new InMemoryCompilationUnit(className, source
.toString()));
}
/**
* コンパイルを実行します.
*
* @throws IOException
* 入出力例外が発生した場合
*/
protected void compile() throws IOException {
javaCompiler = ToolProvider.getSystemJavaCompiler();
diagnostics = new DiagnosticCollector<JavaFileObject>();
final DiagnosticListener<JavaFileObject> listener = new LoggingDiagnosticListener(
diagnostics);
standardJavaFileManager = javaCompiler.getStandardFileManager(
listener,
locale,
charset);
standardJavaFileManager.setLocation(
StandardLocation.SOURCE_PATH,
sourcePaths);
testingJavaFileManager = new TestingJavaFileManager(
standardJavaFileManager,
charset);
final CompilationTask task = javaCompiler.getTask(
out,
testingJavaFileManager,
listener,
options,
null,
getCompilationUnits());
task.setProcessors(processors);
compiledResult = task.call();
compilationUnits.clear();
}
/**
* コンパイラの実行結果を返します.
*
* @return コンパイラの実行結果
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @see CompilationTask#call()
*/
protected Boolean getCompiledResult() throws IllegalStateException {
assertCompiled();
return compiledResult;
}
/**
* コンパイル中に作成された {@link Diagnostic} のリストを返します.
*
* @return コンパイル中に作成された {@link Diagnostic} のリスト
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected List<Diagnostic<? extends JavaFileObject>> getDiagnostics()
throws IllegalStateException {
assertCompiled();
return diagnostics.getDiagnostics();
}
/**
* 指定されたクラスに対する {@link Diagnostic} のリストを返します.
*
* @param clazz
* 取得するクラス
* @return 指定されたクラスに対する {@link Diagnostic} のリスト
*/
protected List<Diagnostic<? extends JavaFileObject>> getDiagnostics(
final Class<?> clazz) {
assertCompiled();
return DiagnosticUtils.getDiagnostics(getDiagnostics(), clazz);
}
/**
* 指定されたクラスに対する {@link Diagnostic} のリストを返します.
*
* @param className
* 取得するクラス名
* @return 指定されたクラスに対する {@link Diagnostic} のリスト
*/
protected List<Diagnostic<? extends JavaFileObject>> getDiagnostics(
final String className) {
assertCompiled();
return DiagnosticUtils.getDiagnostics(getDiagnostics(), className);
}
/**
* 指定された {@link javax.tools.Diagnostic.Kind} を持つ {@link Diagnostic}
* のリストを返します.
*
* @param kind
* 取得する {@link javax.tools.Diagnostic.Kind}
* @return 指定された{@link javax.tools.Diagnostic.Kind} を持つ {@link Diagnostic}
* のリスト
*/
protected List<Diagnostic<? extends JavaFileObject>> getDiagnostics(
final javax.tools.Diagnostic.Kind kind) {
assertCompiled();
return DiagnosticUtils.getDiagnostics(getDiagnostics(), kind);
}
/**
* 指定されたクラスに対する指定された {@link javax.tools.Diagnostic.Kind} を持つ
* {@link Diagnostic} のリストを返します.
*
* @param clazz
* 取得するクラス
* @param kind
* 取得する {@link javax.tools.Diagnostic.Kind}
* @return 指定されたクラスに対する指定された {@link javax.tools.Diagnostic.Kind} を持つ
* {@link Diagnostic} のリスト
*/
protected List<Diagnostic<? extends JavaFileObject>> getDiagnostics(
final Class<?> clazz, final javax.tools.Diagnostic.Kind kind) {
assertCompiled();
return DiagnosticUtils.getDiagnostics(getDiagnostics(), clazz, kind);
}
/**
* 指定されたクラスに対する指定された {@link javax.tools.Diagnostic.Kind} を持つ
* {@link Diagnostic} のリストを返します.
*
* @param className
* 取得するクラス名
* @param kind
* 取得する {@link javax.tools.Diagnostic.Kind}
* @return 指定されたクラスに対する指定された {@link javax.tools.Diagnostic.Kind} を持つ
* {@link Diagnostic} のリスト
*/
protected List<Diagnostic<? extends JavaFileObject>> getDiagnostics(
final String className, final javax.tools.Diagnostic.Kind kind) {
assertCompiled();
return DiagnosticUtils
.getDiagnostics(getDiagnostics(), className, kind);
}
/**
* {@link ProcessingEnvironment} を返します.
*
* @return {@link ProcessingEnvironment}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected ProcessingEnvironment getProcessingEnvironment()
throws IllegalStateException {
assertCompiled();
return processingEnvironment;
}
/**
* {@link Elements} を返します.
*
* @return {@link Elements}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @see ProcessingEnvironment#getElementUtils()
*/
protected Elements getElementUtils() throws IllegalStateException {
assertCompiled();
return processingEnvironment.getElementUtils();
}
/**
* {@link Types} を返します.
*
* @return {@link Types}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @see ProcessingEnvironment#getTypeUtils()
*/
protected Types getTypeUtils() throws IllegalStateException {
assertCompiled();
return processingEnvironment.getTypeUtils();
}
/**
* クラスに対応する {@link TypeElement} を返します.
* <p>
* このメソッドが返す {@link TypeElement} およびその {@link Element#getEnclosedElements()}
* が返す {@link Element} から, {@link Elements#getDocComment(Element)} を使って
* Javadoc コメントを取得することはできません.
* </p>
*
* @param clazz
* クラス
* @return クラスに対応する{@link TypeElement}, 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected TypeElement getTypeElement(final Class<?> clazz)
throws IllegalStateException {
assertCompiled();
return ElementUtils.getTypeElement(getElementUtils(), clazz.getName());
}
/**
* クラスに対応する {@link TypeElement} を返します.
* <p>
* このメソッドが返す {@link TypeElement} およびその {@link Element#getEnclosedElements()}
* が返す {@link Element} から, {@link Elements#getDocComment(Element)} を使って
* Javadoc コメントを取得することはできません.
* </p>
*
* @param className
* クラスの完全限定名
* @return クラスに対応する{@link TypeElement}, 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected TypeElement getTypeElement(final String className)
throws IllegalStateException {
assertCompiled();
return ElementUtils.getTypeElement(getElementUtils(), className);
}
/**
* 型エレメントに定義されたフィールドの変数エレメントを返します.
*
* @param typeElement
* 型エレメント
* @param field
* フィールド
* @return 型エレメントに定義されたフィールドの変数エレメント. 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected VariableElement getFieldElement(final TypeElement typeElement,
final Field field) throws IllegalStateException {
assertCompiled();
return ElementUtils.getFieldElement(typeElement, field);
}
/**
* 型エレメントに定義されたフィールドの変数エレメントを返します.
*
* @param typeElement
* 型エレメント
* @param fieldName
* フィールド名
* @return 型エレメントに定義されたフィールドの変数エレメント. 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected VariableElement getFieldElement(final TypeElement typeElement,
final String fieldName) throws IllegalStateException {
assertCompiled();
return ElementUtils.getFieldElement(typeElement, fieldName);
}
/**
* 型エレメントに定義されたデフォルトコンストラクタの実行可能エレメントを返します.
*
* @param typeElement
* 型エレメント
* @return 型エレメントに定義されたデフォルトコンストラクタの実行可能エレメント. 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected ExecutableElement getConstructorElement(
final TypeElement typeElement) throws IllegalStateException {
assertCompiled();
return ElementUtils.getConstructorElement(typeElement);
}
/**
* 型エレメントに定義されたコンストラクタの実行可能エレメントを返します.
* <p>
* 引数型が型引数を持つ場合は {@link #getConstructorElement(TypeElement, String...)}
* を使用してください.
* </p>
*
* @param typeElement
* 型エレメント
* @param parameterTypes
* 引数型の並び
* @return 型エレメントに定義されたコンストラクタの実行可能エレメント. 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected ExecutableElement getConstructorElement(
final TypeElement typeElement, final Class<?>... parameterTypes)
throws IllegalStateException {
assertCompiled();
return ElementUtils.getConstructorElement(typeElement, parameterTypes);
}
/**
* 型エレメントに定義されたコンストラクタの実行可能エレメントを返します.
* <p>
* 引数がの型が配列の場合は, 要素型の名前の後に {@code []} を連ねる形式と, {@code [[LString;}
* のような形式のどちらでも指定することができます.
* </p>
* <p>
* 引数型が型引数を持つ場合は {@code "java.util.List<T>"} のようにそのまま指定します.
* </p>
*
* @param typeElement
* 型エレメント
* @param parameterTypeNames
* 引数の型名の並び
* @return 型エレメントに定義されたコンストラクタの実行可能エレメント. 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected ExecutableElement getConstructorElement(
final TypeElement typeElement, final String... parameterTypeNames)
throws IllegalStateException {
assertCompiled();
return ElementUtils.getConstructorElement(
typeElement,
parameterTypeNames);
}
/**
* 型エレメントに定義されたメソッドの実行可能エレメントを返します.
*
* @param typeElement
* 型エレメント
* @param methodName
* メソッド名
* @return 型エレメントに定義されたメソッドの実行可能エレメント.存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected ExecutableElement getMethodElement(final TypeElement typeElement,
final String methodName) throws IllegalStateException {
assertCompiled();
return ElementUtils.getMethodElement(typeElement, methodName);
}
/**
* 型エレメントに定義されたメソッドの実行可能エレメントを返します.
* <p>
* 引数型が型引数を持つ場合は {@link #getMethodElement(TypeElement, String, String...)}
* を使用してください.
* </p>
*
* @param typeElement
* 型エレメント
* @param methodName
* メソッド名
* @param parameterTypes
* 引数型の並び
* @return 型エレメントに定義されたメソッドの実行可能エレメント. 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected ExecutableElement getMethodElement(final TypeElement typeElement,
final String methodName, final Class<?>... parameterTypes)
throws IllegalStateException {
assertCompiled();
return ElementUtils.getMethodElement(
typeElement,
methodName,
parameterTypes);
}
/**
* 型エレメントに定義されたメソッドの実行可能エレメントを返します.
* <p>
* 引数がの型が配列の場合は, 要素型の名前の後に {@code []} を連ねる形式と, {@code [[LString;}
* のような形式のどちらでも指定することができます.
* </p>
* <p>
* 引数型が型引数を持つ場合は {@code "java.util.List<T>"} のようにそのまま指定します.
* </p>
*
* @param typeElement
* 型エレメント
* @param methodName
* メソッド名
* @param parameterTypeNames
* 引数の型名の並び
* @return 型エレメントに定義されたメソッドの実行可能エレメント. 存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected ExecutableElement getMethodElement(final TypeElement typeElement,
final String methodName, final String... parameterTypeNames)
throws IllegalStateException {
assertCompiled();
return ElementUtils.getMethodElement(
typeElement,
methodName,
parameterTypeNames);
}
/**
* クラスに対応する {@link TypeMirror} を返します.
*
* @param clazz
* クラス
* @return クラスに対応する{@link TypeMirror}, クラスが存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected TypeMirror getTypeMirror(final Class<?> clazz)
throws IllegalStateException {
assertCompiled();
return TypeMirrorUtils.getTypeMirror(
getTypeUtils(),
getElementUtils(),
clazz);
}
/**
* クラスに対応する {@link TypeMirror} を返します.
* <p>
* 配列の場合は要素型の名前の後に {@code []} を連ねる形式と, {@code [[LString;} のような
* 形式のどちらでも指定することができます.
* </p>
*
* @param className
* クラスの完全限定名
* @return クラスに対応する{@link TypeMirror}, クラスが存在しない場合は {@code null}
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
protected TypeMirror getTypeMirror(final String className)
throws IllegalStateException {
assertCompiled();
return TypeMirrorUtils.getTypeMirror(
getTypeUtils(),
getElementUtils(),
className);
}
/**
* {@link Processor} が生成したソースを返します.
*
* @param clazz
* 生成されたクラス
* @return 生成されたソースの内容
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
*/
protected String getGeneratedSource(final Class<?> clazz)
throws IllegalStateException, IOException,
SourceNotGeneratedException {
assertNotNull("clazz", clazz);
assertCompiled();
return getGeneratedSource(clazz.getName());
}
/**
* {@link Processor} が生成したソースを返します.
*
* @param className
* 生成されたクラスの完全限定名
* @return 生成されたソースの内容
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
*/
protected String getGeneratedSource(final String className)
throws IllegalStateException, IOException,
SourceNotGeneratedException {
assertNotEmpty("className", className);
assertCompiled();
final JavaFileObject javaFileObject = testingJavaFileManager
.getJavaFileForInput(
StandardLocation.SOURCE_OUTPUT,
className,
Kind.SOURCE);
if (javaFileObject == null) {
throw new SourceNotGeneratedException(className);
}
final CharSequence content = javaFileObject.getCharContent(true);
if (content == null) {
throw new SourceNotGeneratedException(className);
}
return content.toString();
}
/**
* 文字列を行単位で比較します.
*
* @param expected
* 期待される文字列
* @param actual
* 実際の文字列
*/
protected void assertEqualsByLine(final String expected, final String actual) {
if (expected == null || actual == null) {
assertEquals(expected, actual);
return;
}
final BufferedReader expectedReader = new BufferedReader(
new StringReader(expected.toString()));
final BufferedReader actualReader = new BufferedReader(
new StringReader(actual));
try {
assertEqualsByLine(expectedReader, actualReader);
} catch (final IOException ignore) {
// unreachable
} finally {
closeSilently(expectedReader);
closeSilently(actualReader);
}
}
/**
* 文字列を行単位で比較します.
*
* @param expectedReader
* 期待される文字列の入力ストリーム
* @param actualReader
* 実際の文字列の入力ストリーム
* @throws IOException
* 入出力例外が発生した場合
*/
protected void assertEqualsByLine(final BufferedReader expectedReader,
final BufferedReader actualReader) throws IOException {
String expectedLine;
String actualLine;
int lineNo = 0;
while ((expectedLine = expectedReader.readLine()) != null) {
++lineNo;
actualLine = actualReader.readLine();
assertEquals("line:" + lineNo, expectedLine, actualLine);
}
++lineNo;
assertEquals("line:" + lineNo, null, actualReader.readLine());
}
/**
* {@link Processor} が生成したソースを文字列と比較・検証します.
*
* @param expected
* 生成されたソースに期待される内容の文字列
* @param clazz
* 生成されたクラス
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSource(final CharSequence expected,
final Class<?> clazz) throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotEmpty("expected", expected);
assertNotNull("clazz", clazz);
assertCompiled();
assertEqualsGeneratedSource(expected, clazz.getName());
}
/**
* {@link Processor} が生成したソースを文字列と比較・検証します.
*
* @param expected
* 生成されたソースに期待される内容の文字列
* @param className
* 生成されたクラスの完全限定名
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSource(final CharSequence expected,
final String className) throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotEmpty("className", className);
assertCompiled();
final String actual = getGeneratedSource(className);
assertNotNull("actual", actual);
assertEqualsByLine(
expected == null ? null : expected.toString(),
actual);
}
/**
* {@link Processor} が生成したソースをファイルと比較・検証します.
*
* @param expectedSourceFile
* 生成されたソースに期待される内容を持つファイル
* @param clazz
* 生成されたクラス
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithFile(
final File expectedSourceFile, final Class<?> clazz)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotNull("expectedSourceFile", expectedSourceFile);
assertNotNull("clazz", clazz);
assertCompiled();
assertEqualsGeneratedSourceWithFile(expectedSourceFile, clazz.getName());
}
/**
* {@link Processor} が生成したソースをファイルと比較・検証します.
*
* @param expectedSourceFile
* 生成されたソースに期待される内容を持つファイル
* @param className
* クラスの完全限定名
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithFile(
final File expectedSourceFile, final String className)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotNull("expectedSourceFile", expectedSourceFile);
assertNotEmpty("className", className);
assertCompiled();
assertEqualsGeneratedSource(
readString(expectedSourceFile, charset),
className);
}
/**
* {@link Processor} が生成したソースをファイルと比較・検証します.
*
* @param expectedSourceFilePath
* 生成されたソースに期待される内容を持つファイルのパス
* @param clazz
* 生成されたクラス
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithFile(
final String expectedSourceFilePath, final Class<?> clazz)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotEmpty("expectedSourceFilePath", expectedSourceFilePath);
assertNotNull("clazz", clazz);
assertCompiled();
assertEqualsGeneratedSourceWithFile(expectedSourceFilePath, clazz
.getName());
}
/**
* {@link Processor} が生成したソースをファイルと比較・検証します.
*
* @param expectedSourceFilePath
* 生成されたソースに期待される内容を持つファイルのパス
* @param className
* 生成されたクラスの完全限定名
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithFile(
final String expectedSourceFilePath, final String className)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotEmpty("expectedSourceFilePath", expectedSourceFilePath);
assertNotEmpty("className", className);
assertCompiled();
assertEqualsGeneratedSourceWithFile(
new File(expectedSourceFilePath),
className);
}
/**
* {@link Processor} が生成したソースをクラスパス上のリソースと比較・検証します.
*
* @param expectedResourceUrl
* 生成されたソースに期待される内容を持つリソースのURL
* @param clazz
* 生成されたクラス
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithResource(
final URL expectedResourceUrl, final Class<?> clazz)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotNull("expectedResourceUrl", expectedResourceUrl);
assertNotNull("clazz", clazz);
assertCompiled();
assertEqualsGeneratedSourceWithResource(expectedResourceUrl, clazz
.getName());
}
/**
* {@link Processor} が生成したソースをクラスパス上のリソースと比較・検証します.
*
* @param expectedResourceUrl
* 生成されたソースに期待される内容を持つリソースのURL
* @param className
* 生成されたクラスの完全限定名
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithResource(
final URL expectedResourceUrl, final String className)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotNull("expectedResourceUrl", expectedResourceUrl);
assertNotEmpty("className", className);
assertCompiled();
assertEqualsGeneratedSource(
readFromResource(expectedResourceUrl),
className);
}
/**
* {@link Processor} が生成したソースをクラスパス上のリソースと比較・検証します.
*
* @param expectedResource
* 生成されたソースに期待される内容を持つリソースのパス
* @param clazz
* 生成されたクラス
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithResource(
final String expectedResource, final Class<?> clazz)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotEmpty("expectedResource", expectedResource);
assertNotNull("clazz", clazz);
assertCompiled();
assertEqualsGeneratedSourceWithResource(
clazz.getName(),
expectedResource);
}
/**
* {@link Processor} が生成したソースをクラスパス上のリソースと比較・検証します.
*
* @param expectedResource
* 生成されたソースに期待される内容を持つリソースのパス
* @param className
* 生成されたクラスの完全限定名
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
* @throws IOException
* 入出力例外が発生した場合
* @throws SourceNotGeneratedException
* ソースが生成されなかった場合
* @throws ComparisonFailure
* 生成されたソースが期待される内容と一致しなかった場合
*/
protected void assertEqualsGeneratedSourceWithResource(
final String expectedResource, final String className)
throws IllegalStateException, IOException,
SourceNotGeneratedException, ComparisonFailure {
assertNotEmpty("expectedResource", expectedResource);
assertNotEmpty("className", className);
assertCompiled();
final URL url = Thread
.currentThread()
.getContextClassLoader()
.getResource(expectedResource);
if (url == null) {
throw new FileNotFoundException(expectedResource);
}
assertEqualsGeneratedSourceWithResource(url, className);
}
/**
* 設定をリセットし,初期状態に戻します.
* <p>
* {@link #compile()} 呼び出し前に設定した内容も, {@link #compile()}
* によって得られた状態も全てリセットされます.
* </p>
*/
protected void reset() {
locale = null;
charset = null;
out = null;
options.clear();
sourcePaths.clear();
processors.clear();
processors.add(new AptinaUnitProcessor());
compilationUnits.clear();
javaCompiler = null;
diagnostics = null;
standardJavaFileManager = null;
if (testingJavaFileManager != null) {
try {
testingJavaFileManager.close();
} catch (final Exception ignore) {
}
}
testingJavaFileManager = null;
processingEnvironment = null;
compiledResult = null;
}
/**
* 追加されたコンパイル対象のリストを返します.
*
* @return 追加されたコンパイル対象のリスト
* @throws IOException
* 入出力例外が発生した場合
*/
List<JavaFileObject> getCompilationUnits() throws IOException {
final List<JavaFileObject> result = new ArrayList<JavaFileObject>(
compilationUnits.size());
for (final CompilationUnit compilationUnit : compilationUnits) {
result.add(compilationUnit.getJavaFileObject());
}
return result;
}
/**
* {@link #compile()} が呼び出されていなければ例外をスローします.
*
* @throws IllegalStateException
* {@link #compile()} が呼び出されていない場合
*/
void assertCompiled() throws IllegalStateException {
if (compiledResult == null) {
throw new IllegalStateException("not compiled");
}
}
/**
* URL から読み込んだ内容を文字列で返します.
* <p>
* URLで表されるリソースの内容は, {@link #charset} で指定された文字セットでエンコード
* (未設定時はプラットフォームデフォルトの文字セット) されていなければなりません.
* </p>
*
* @param url
* リソースのURL
* @return URL から読み込んだ内容の文字列
* @throws IOException
* 入出力例外が発生した場合
*/
String readFromResource(final URL url) throws IOException {
final InputStream is = url.openStream();
try {
return readString(is, charset);
} finally {
closeSilently(is);
}
}
/**
* 発生した {@link Diagnostic} をコンソールに出力する {@link DiagnosticListener} です.
* <p>
* {@link Diagnostic} コンソールに出力した後,後続の {@link DiagnosticListener} へ通知します.
* </p>
*
* @author koichik
*/
static class LoggingDiagnosticListener implements
DiagnosticListener<JavaFileObject> {
DiagnosticListener<JavaFileObject> listener;
/**
* インスタンスを構築します.
*
* @param listener
* 後続の {@link DiagnosticListener}
*/
LoggingDiagnosticListener(
final DiagnosticListener<JavaFileObject> listener) {
this.listener = listener;
}
@Override
public void report(final Diagnostic<? extends JavaFileObject> diagnostic) {
System.out.println(diagnostic);
listener.report(diagnostic);
}
}
/**
* コンパイル時に {@link Processor} に渡される @ ProcessingEnvironment} を取得するための
* {@link Processor} です.
*
* @author koichik
*/
@SupportedAnnotationTypes("*")
class AptinaUnitProcessor extends AbstractProcessor {
@Override
public synchronized void init(
final ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
AptinaTestCase.this.processingEnvironment = processingEnvironment;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
@Override
public boolean process(final Set<? extends TypeElement> annotations,
final RoundEnvironment roundEnv) {
return false;
}
}
/**
* コンパイル対象を表すインタフェースです.
*
* @author koichik
*/
interface CompilationUnit {
/**
* このコンパイル対象に対応する {@link JavaFileObject} を返します.
*
* @return このコンパイル対象に対応する {@link JavaFileObject}
* @throws IOException
* 入出力例外が発生した場合
*/
JavaFileObject getJavaFileObject() throws IOException;
}
/**
* ソースパス上のファイルとして存在するコンパイル対象を表すクラスです.
*
* @author koichik
*/
class FileCompilationUnit implements CompilationUnit {
String className;
/**
* インスタンスを構築します.
*
* @param className
* クラス名
*/
public FileCompilationUnit(final String className) {
this.className = className;
}
@Override
public JavaFileObject getJavaFileObject() throws IOException {
return standardJavaFileManager.getJavaFileForInput(
StandardLocation.SOURCE_PATH,
className,
Kind.SOURCE);
}
}
/**
* メモリ上に存在するコンパイル対象を表すクラスです.
*
* @author koichik
*/
class InMemoryCompilationUnit implements CompilationUnit {
String className;
String source;
/**
* インスタンスを構築します.
*
* @param className
* クラス名
* @param source
* ソース
*/
public InMemoryCompilationUnit(final String className,
final String source) {
this.className = className;
this.source = source;
}
@Override
public JavaFileObject getJavaFileObject() throws IOException {
final JavaFileObject javaFileObject = testingJavaFileManager
.getJavaFileForOutput(
StandardLocation.SOURCE_OUTPUT,
className,
Kind.SOURCE,
null);
final Writer writer = javaFileObject.openWriter();
try {
writer.write(source);
} finally {
closeSilently(writer);
}
return javaFileObject;
}
}
}
| 30.953125 | 90 | 0.60705 |
812f532224319c1b82a49738012f355191e3d7f9 | 713 | /*
* Copyright (c) 2021.
* Alexey Kozadaev
* akozadaev@inbox.ru
*/
package ru.akozadaev.addressbook.data.entity;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class Person {
public String result;
public Data data;
public List<Errors> errors;
public String getResult() {
return result;
}
public Data getData() {
return data;
}
public List<Errors> getErrors() {
return errors;
}
@Override
public String toString() {
return "Pers{" +
"result='" + result + '\'' +
", data=" + data +
", errors=" + errors +
'}';
}
}
| 16.97619 | 48 | 0.548387 |
6b4871e5cf895e616d55395046ed88f4eda92324 | 2,740 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.01.22 at 12:06:19 AM EST
//
package net.kenevans.trainingcenterdatabasev2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for Week_t complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Week_t">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Notes" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <attribute name="StartDay" use="required" type="{http://www.w3.org/2001/XMLSchema}date" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Week_t", propOrder = {
"notes"
})
public class WeekT {
@XmlElement(name = "Notes")
protected String notes;
@XmlAttribute(name = "StartDay", required = true)
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar startDay;
/**
* Gets the value of the notes property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNotes() {
return notes;
}
/**
* Sets the value of the notes property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNotes(String value) {
this.notes = value;
}
/**
* Gets the value of the startDay property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getStartDay() {
return startDay;
}
/**
* Sets the value of the startDay property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setStartDay(XMLGregorianCalendar value) {
this.startDay = value;
}
}
| 27.128713 | 125 | 0.60438 |
afa7d64ef9609a4939115d1d7d034735ea43044f | 2,064 | package com.linkedpipes.etl.convert.uv.configuration;
import com.linkedpipes.etl.convert.uv.pipeline.LpPipeline;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import java.util.ArrayList;
import java.util.List;
import org.openrdf.model.IRI;
import org.openrdf.model.Statement;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.SimpleValueFactory;
import org.openrdf.model.vocabulary.RDF;
@XStreamAlias("eu.unifiedviews.plugins.transformer.unzipper.UnZipperConfig_V1")
class UnZipperConfig_V1 implements Configuration {
boolean notPrefixed = false;
@Override
public void update(LpPipeline pipeline, LpPipeline.Component component,
boolean asTemplate) {
pipeline.renameInPort(component, "input", "FilesInput");
pipeline.renameOutPort(component, "output", "FilesOutput");
component.setTemplate("http://etl.linkedpipes.com/resources/components/t-unpackZip/0.0.0");
final ValueFactory vf = SimpleValueFactory.getInstance();
final List<Statement> st = new ArrayList<>();
st.add(vf.createStatement(
vf.createIRI("http://localhost/resources/configuration/t-unpackZip"),
RDF.TYPE,
vf.createIRI("http://plugins.linkedpipes.com/ontology/t-unpackZip#Configuration")));
st.add(vf.createStatement(
vf.createIRI("http://localhost/resources/configuration/t-unpackZip"),
vf.createIRI("http://plugins.linkedpipes.com/ontology/t-unpackZip#usePrefix"),
vf.createLiteral(!notPrefixed)));
if (asTemplate) {
final IRI force = vf.createIRI(
"http://plugins.linkedpipes.com/resource/configuration/Force");
st.add(vf.createStatement(
vf.createIRI("http://localhost/resources/configuration/t-unpackZip"),
vf.createIRI("http://plugins.linkedpipes.com/ontology/t-unpackZip#usePrefixControl"),
force));
}
component.setLpConfiguration(st);
}
}
| 38.222222 | 105 | 0.682171 |
b88e263b038b12ccfeb3bb7a1eafdd8972d45012 | 2,495 | package com.keveon.demo.config;
import com.keveon.demo.commons.exceptions.ResourceCreatedFailedException;
import com.keveon.demo.commons.exceptions.ResourceDoesNotExistException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* The type Rest controller advice.
*
* @author keveon on 2019/04/07.
* @version 1.0.0
* @since 1.0.0
*/
@ControllerAdvice
public class RestControllerAdvice {
/**
* Handle illegal argument exception.
*
* @param ex the ex
* @param response the response
* @throws IOException the io exception
*/
@ExceptionHandler(IllegalArgumentException.class)
public void handleIllegalArgumentException(IllegalArgumentException ex,
HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}
/**
* Handle resource does not exist exception.
*
* @param ex the ex
* @param request the request
* @param response the response
* @throws IOException the io exception
*/
@ExceptionHandler(ResourceDoesNotExistException.class)
public void handleResourceDoesNotExistException(ResourceDoesNotExistException ex,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.NOT_FOUND.value(),
"The resource '" + request.getRequestURI() + "' does not exist");
}
/**
* Handle created failed exception.
* TODO keveon on 2019/04/07. 只写资源创建失败太抽象了, 异常定义还需要具体一些.
*
* @param ex the ex
* @param request the request
* @param response the response
* @throws IOException the io exception
*/
@ExceptionHandler(ResourceCreatedFailedException.class)
public void handleCreatedFailedException(ResourceDoesNotExistException ex,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
}
}
| 37.238806 | 102 | 0.661723 |
f88ce79dc3e2663a68955f3e1683ebf218bf329a | 23,581 | /* Copyright 1999 Vince Via vvia@viaoa.com
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.viaoa.datasource.jdbc.delegate;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import com.viaoa.datasource.OADataSourceIterator;
import com.viaoa.datasource.jdbc.OADataSourceJDBC;
import com.viaoa.datasource.jdbc.db.Column;
import com.viaoa.datasource.jdbc.db.DBMetaData;
import com.viaoa.datasource.jdbc.db.DataAccessObject;
import com.viaoa.datasource.jdbc.db.Link;
import com.viaoa.datasource.jdbc.db.ManyToMany;
import com.viaoa.datasource.jdbc.db.Table;
import com.viaoa.datasource.jdbc.query.QueryConverter;
import com.viaoa.datasource.jdbc.query.ResultSetIterator;
import com.viaoa.object.OALinkInfo;
import com.viaoa.object.OAObject;
import com.viaoa.object.OAObjectInfo;
import com.viaoa.object.OAObjectInfoDelegate;
import com.viaoa.object.OAObjectKey;
import com.viaoa.object.OAObjectKeyDelegate;
import com.viaoa.transaction.OATransaction;
import com.viaoa.util.OAString;
/**
* Manages Selects/Queries for JDBC datasource.
*
* @author vvia
*/
public class SelectDelegate {
private static Logger LOG = Logger.getLogger(SelectDelegate.class.getName());
private static ConcurrentHashMap<WhereObjectSelect, String> hmPreparedStatementSql = new ConcurrentHashMap<WhereObjectSelect, String>();
private static ConcurrentHashMap<Class, String> hmPreparedStatementSqlx = new ConcurrentHashMap<Class, String>();
private static ConcurrentHashMap<Class, String> hmPreparedStatementSqlxDirty = new ConcurrentHashMap<Class, String>();
private static ConcurrentHashMap<Class, Column[]> hmPreparedStatementSqlxDirtyColumns = new ConcurrentHashMap<Class, Column[]>();
/*
public static Iterator select(OADataSourceJDBC ds, Class clazz, String queryWhere, String queryOrder, int max, boolean bDirty) {
return select(ds, clazz, queryWhere, (Object[]) null, queryOrder, max, bDirty);
}
*/
/*
public static Iterator select(OADataSourceJDBC ds, Class clazz, String queryWhere, Object param, String queryOrder, int max, boolean bDirty) {
Object[] params = null;
if (param != null) params = new Object[] {param};
return select(ds, clazz, queryWhere, params, queryOrder, max, bDirty);
}
*/
public static OADataSourceIterator select(OADataSourceJDBC ds, Class clazz, String queryWhere, Object[] params, String queryOrder,
int max, boolean bDirty) {
if (ds == null) {
return null;
}
if (clazz == null) {
return null;
}
Table table = ds.getDatabase().getTable(clazz);
if (table == null) {
return null;
}
QueryConverter qc = new QueryConverter(ds);
String[] queries = getSelectSQL(qc, ds, clazz, queryWhere, params, queryOrder, max, bDirty);
ResultSetIterator rsi;
DataAccessObject dao = table.getDataAccessObject();
if (!bDirty && dao != null) {
rsi = new ResultSetIterator(ds, clazz, dao, queries[0], queries[1], max);
} else {
Column[] columns = qc.getSelectColumnArray(clazz);
if (queries[1] != null) {
// this will take 2 queries. The first will only select pkey columns.
// the second query will then select the record using the pkey values in the where clause.
rsi = new ResultSetIterator(ds, clazz, columns, queries[0], queries[1], max);
} else {
rsi = new ResultSetIterator(ds, clazz, columns, queries[0], max);
}
}
rsi.setDirty(bDirty);
return rsi;
}
/**
* @returns array [0]=sql [1]=sql2 (if needed)
*/
private static String[] getSelectSQL(QueryConverter qc, OADataSourceJDBC ds, Class clazz, String queryWhere, Object[] params,
String queryOrder, int max, boolean bDirty) {
String[] queries = new String[2];
queries[0] = qc.convertToSql(clazz, queryWhere, params, queryOrder);
if (qc.getUseDistinct()) {
// distinct query will also need to have the order by keys
String s = " ORDER BY ";
int x = queries[0].indexOf(s);
if (x > 0) {
x += s.length();
s = queries[0].substring(x);
// need to remove ASC, DESC
// todo: this might not be needed anymore
StringTokenizer st = new StringTokenizer(s, ", ", false);
String s1 = null;
for (; st.hasMoreElements();) {
String s2 = (String) st.nextElement();
String s3 = s2.toUpperCase();
if (s3.equals("ASC")) {
continue;
}
if (s3.equals("DESC")) {
continue;
}
if (s1 == null) {
s1 = s2;
} else {
s1 += ", " + s2;
}
}
s = ", " + s1;
} else {
s = "";
}
// this will take 2 queries. The first will only select pkey columns.
// the second query will then select the record using the pkey values in the where clause.
queries[0] = "SELECT " + ds.getDBMetaData().distinctKeyword + " " + qc.getPrimaryKeyColumns(clazz) + s + " " + queries[0];
OAObjectInfo oi = OAObjectInfoDelegate.getOAObjectInfo(clazz);
String[] ids = oi.getIdProperties();
params = new Object[ids.length];
queries[1] = "";
for (int i = 0; ids != null && i < ids.length; i++) {
if (i > 0) {
queries[1] += " AND ";
}
queries[1] += ids[i] + " = ?";
params[i] = "7"; // fake out/position holder
}
queries[1] = qc.convertToSql(clazz, queries[1], params, null);
queries[1] = "SELECT " + qc.getSelectColumns(clazz, bDirty) + " " + queries[1];
queries[1] = OAString.convert(queries[1], "7", "?");
} else {
queries[0] = "SELECT " + qc.getSelectColumns(clazz, bDirty) + " " + queries[0];
//was: queries[0] = "SELECT " + getMax(ds,max) + qc.getSelectColumns(clazz, bDirty) + " " + queries[0];
}
return queries;
}
private static class WhereObjectSelect {
private Class clazz;
private Class whereClazz;
private String propertyFromWhereObject;
public WhereObjectSelect(Class clazz, Class whereClazz, String propertyFromWhereObject) {
this.clazz = clazz;
this.whereClazz = whereClazz;
this.propertyFromWhereObject = propertyFromWhereObject;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WhereObjectSelect)) {
return false;
}
WhereObjectSelect x = (WhereObjectSelect) obj;
if (clazz != x.clazz) {
if (clazz == null || x.clazz == null) {
return false;
}
if (!clazz.equals(x.clazz)) {
return false;
}
}
if (whereClazz != x.whereClazz) {
if (whereClazz == null || x.whereClazz == null) {
return false;
}
if (!whereClazz.equals(x.whereClazz)) {
return false;
}
}
if (propertyFromWhereObject != x.propertyFromWhereObject) {
if (propertyFromWhereObject == null || x.propertyFromWhereObject == null) {
return false;
}
if (!propertyFromWhereObject.equals(x.propertyFromWhereObject)) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int x = 0;
if (clazz != null) {
x += clazz.hashCode();
}
if (whereClazz != null) {
x += whereClazz.hashCode();
}
if (propertyFromWhereObject != null) {
x += propertyFromWhereObject.hashCode();
}
return x;
}
}
// 20121013 changes to use PreparedStatements for Selecting Many link
public static OADataSourceIterator select(OADataSourceJDBC ds, Class clazz, OAObject whereObject, String extraWhere, Object[] params,
String propertyFromWhereObject, String queryOrder, int max, boolean bDirty) {
// dont need to select if master object (whereObject) is new
if (whereObject == null || whereObject.getNew()) {
return null;
}
Table table = ds.getDatabase().getTable(clazz);
if (table == null) {
return null;
}
DataAccessObject dao = table.getDataAccessObject();
if (dao == null || whereObject == null || OAString.isEmpty(propertyFromWhereObject) || (params != null && params.length > 0)
|| max > 0) {
QueryConverter qc = new QueryConverter(ds);
String query = getSelectSQL(ds, qc, clazz, whereObject, extraWhere, params, propertyFromWhereObject, queryOrder, max, bDirty);
ResultSetIterator rsi;
if (!bDirty && dao != null) {
rsi = new ResultSetIterator(ds, clazz, dao, query, null, max);
} else {
Column[] columns = qc.getSelectColumnArray(clazz);
rsi = new ResultSetIterator(ds, clazz, columns, query, max);
}
rsi.setDirty(bDirty);
return rsi;
}
WhereObjectSelect wos = new WhereObjectSelect(clazz, whereObject == null ? null : whereObject.getClass(), propertyFromWhereObject);
String query = bDirty ? null : hmPreparedStatementSql.get(wos);
if (query == null) {
QueryConverter qc = new QueryConverter(ds);
query = "SELECT " + qc.getSelectColumns(clazz, bDirty);
query += " " + qc.convertToPreparedStatementSql(clazz, whereObject, extraWhere, params, propertyFromWhereObject, queryOrder);
params = qc.getArguments();
if (params == null || params.length == 0) {
return null; // null reference
}
if (!bDirty) {
hmPreparedStatementSql.put(wos, query);
}
} else {
OAObjectKey key = OAObjectKeyDelegate.getKey(whereObject);
params = key.getObjectIds();
}
ResultSetIterator rsi;
if (!bDirty && dao != null) {
rsi = new ResultSetIterator(ds, clazz, dao, query, params);
} else {
QueryConverter qc = new QueryConverter(ds);
Column[] columns = qc.getSelectColumnArray(clazz);
rsi = new ResultSetIterator(ds, clazz, columns, query, params, max);
}
rsi.setDirty(bDirty);
return rsi;
}
// 20121013
public static OADataSourceIterator selectObject(OADataSourceJDBC ds, Class clazz, OAObjectKey key, boolean bDirty) throws Exception {
if (ds == null) {
return null;
}
if (clazz == null) {
return null;
}
Table table = ds.getDatabase().getTable(clazz);
if (table == null) {
return null;
}
DataAccessObject dao = table.getDataAccessObject();
ResultSetIterator rsi;
if (!bDirty && dao != null) {
String sql = hmPreparedStatementSqlx.get(clazz);
if (sql == null) {
sql = dao.getSelectColumns();
sql = "SELECT " + sql;
sql += " FROM " + table.name + " WHERE ";
Column[] cols = table.getSelectColumns();
boolean b = false;
for (Column c : cols) {
if (c.primaryKey) {
if (!b) {
b = true;
} else {
sql += " AND ";
}
sql += c.columnName + " = ?";
}
}
hmPreparedStatementSqlx.put(clazz, sql);
}
rsi = new ResultSetIterator(ds, clazz, dao, sql, key.getObjectIds());
} else {
String sql = hmPreparedStatementSqlxDirty.get(clazz);
Column[] columns = hmPreparedStatementSqlxDirtyColumns.get(clazz);
if (sql == null) {
QueryConverter qc = new QueryConverter(ds);
sql = "SELECT " + qc.getSelectColumns(clazz, bDirty); // could use dao
sql += " FROM " + table.name + " WHERE ";
Column[] cols = table.getSelectColumns(); //
boolean b = false;
for (Column c : cols) {
if (c.primaryKey) {
if (!b) {
b = true;
} else {
sql += " AND ";
}
sql += c.columnName + " = ?";
}
}
hmPreparedStatementSqlxDirty.put(clazz, sql);
columns = qc.getSelectColumnArray(clazz);
hmPreparedStatementSqlxDirtyColumns.put(clazz, columns);
}
rsi = new ResultSetIterator(ds, clazz, columns, sql, key.getObjectIds(), 0);
}
rsi.setDirty(bDirty);
return rsi;
}
public static String getSelectSQL(OADataSourceJDBC ds, QueryConverter qc, Class clazz, OAObject whereObject, String extraWhere,
Object[] args, String propertyFromWhereObject, String queryOrder, int max, boolean bDirty) {
if (propertyFromWhereObject == null) {
propertyFromWhereObject = "";
}
String query = "SELECT " + qc.getSelectColumns(clazz, bDirty);
//was: String query = "SELECT " + getMax(ds,max) + qc.getSelectColumns(clazz, bDirty);
query += " " + qc.convertToSql(clazz, whereObject, extraWhere, args, propertyFromWhereObject, queryOrder);
return query;
}
public static Iterator selectPassthru(OADataSourceJDBC ds, Class clazz, String query, int max, boolean bDirty) {
Table table = ds.getDatabase().getTable(clazz);
if (table == null) {
return null;
}
QueryConverter qc = new QueryConverter(ds);
query = qc.getSelectColumns(clazz, bDirty) + " " + query;
ResultSetIterator rsi;
DataAccessObject dao = table.getDataAccessObject();
if (!bDirty && dao != null) {
rsi = new ResultSetIterator(ds, clazz, dao, query, null, max);
} else {
Column[] columns = qc.getSelectColumnArray(clazz);
rsi = new ResultSetIterator(ds, clazz, columns, "SELECT " + query, max);
//was: rsi = new ResultSetIterator(ds, clazz, columns, "SELECT "+getMax(ds,max)+query, max);
}
rsi.setDirty(bDirty);
return rsi;
}
/* use statement.setMaxRows(x) instead
private static String getMax(OADataSourceJDBC ds, int max) {
String str = "";
if (max > 0) {
DBMetaData dbmd = ds.getDBMetaData();
if (OAString.isNotEmpty(dbmd.maxString)) {
str = OAString.convert(dbmd.maxString, "?", (max+"")) + " ";
}
}
return str;
}
*/
/**
* Note: queryWhere needs to begin with "FROM TABLENAME WHERE ..." queryOrder will be prefixed with "ORDER BY "
*/
public static OADataSourceIterator selectPassthru(OADataSourceJDBC ds, Class clazz, String queryWhere, String queryOrder, int max,
boolean bDirty) {
Table table = ds.getDatabase().getTable(clazz);
if (table == null) {
return null;
}
QueryConverter qc = new QueryConverter(ds);
String query = qc.getSelectColumns(clazz, bDirty);
if (queryWhere != null && queryWhere.length() > 0) {
query += " " + queryWhere;
}
if (queryOrder != null && queryOrder.length() > 0) {
query += " ORDER BY " + queryOrder;
}
ResultSetIterator rsi;
DataAccessObject dao = table.getDataAccessObject();
if (!bDirty && dao != null) {
rsi = new ResultSetIterator(ds, clazz, dao, "SELECT " + query, null, max);
} else {
Column[] columns = qc.getSelectColumnArray(clazz);
rsi = new ResultSetIterator(ds, clazz, columns, "SELECT " + query, max);
//was: rsi = new ResultSetIterator(ds, clazz, columns, "SELECT "+getMax(ds,max)+query, max);
}
rsi.setDirty(bDirty);
return rsi;
}
public static Object execute(OADataSourceJDBC ds, String command) {
// LOG.fine("command="+command);
Statement st = null;
try {
st = ds.getStatement(command);
st.execute(command);
return null;
} catch (Exception e) {
throw new RuntimeException("OADataSourceJDBC.execute() " + command, e);
} finally {
if (st != null) {
ds.releaseStatement(st);
}
}
}
// Note: queryWhere needs to begin with "FROM TABLENAME WHERE ..."
public static int countPassthru(OADataSourceJDBC ds, String query, int max) {
String s = "SELECT COUNT(*) ";
//was: String s = "SELECT "+getMax(ds, max)+"COUNT(*) ";
if (query != null && query.length() > 0) {
s += query;
}
// LOG.fine("sql="+s);
Statement st = null;
try {
st = ds.getStatement(s);
java.sql.ResultSet rs = st.executeQuery(s);
rs.next();
int x = rs.getInt(1);
if (max > 0 && x > max) {
x = max;
}
return x;
} catch (Exception e) {
throw new RuntimeException("OADataSourceJDBC.count() " + query, e);
} finally {
if (st != null) {
ds.releaseStatement(st);
}
}
}
public static int count(OADataSourceJDBC ds, Class selectClass, Object whereObject, String propertyFromWhereObject, int max) {
return count(ds, selectClass, whereObject, null, null, propertyFromWhereObject, max);
}
public static int count(OADataSourceJDBC ds, Class selectClass, Object whereObject, String extraWhere, Object[] args,
String propertyFromWhereObject, int max) {
if (whereObject instanceof OAObject) {
if (((OAObject) whereObject).getNew()) {
return 0;
}
}
if (propertyFromWhereObject == null) {
propertyFromWhereObject = "";
}
QueryConverter qc = new QueryConverter(ds);
String s = qc.convertToSql(selectClass, whereObject, extraWhere, args, propertyFromWhereObject, "");
s = "SELECT COUNT(*) " + s;
//was: s = "SELECT "+getMax(ds, max)+"COUNT(*) " + s;
// LOG.fine("selectClass="+selectClass.getName()+", whereObject="+whereObject+", extraWhere="+extraWhere+", propertyFromWhereObject="+propertyFromWhereObject+", sql="+s);
Statement st = null;
try {
st = ds.getStatement(s);
if (max > 0) {
st.setMaxRows(max);
}
java.sql.ResultSet rs = st.executeQuery(s);
rs.next();
int x = rs.getInt(1);
if (max > 0 && x > max) {
x = max;
}
return x;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (max > 0) {
st.setMaxRows(0);
}
} catch (Exception ex) {
}
;
if (st != null) {
ds.releaseStatement(st);
}
}
}
public static int count(OADataSourceJDBC ds, Class clazz, String queryWhere, int max) {
return count(ds, clazz, queryWhere, (Object[]) null, max);
}
public static int count(OADataSourceJDBC ds, Class clazz, String queryWhere, Object param, int max) {
Object[] params = null;
if (param != null) {
params = new Object[] { param };
}
return count(ds, clazz, queryWhere, params, max);
}
public static int count(OADataSourceJDBC ds, Class clazz, String queryWhere, Object[] params, int max) {
QueryConverter qc = new QueryConverter(ds);
String s = qc.convertToSql(clazz, queryWhere, params, "");
s = "SELECT COUNT(*) " + s;
//was: s = "SELECT "+getMax(ds,max)+"COUNT(*) " + s;
// LOG.fine("selectClass="+clazz.getName()+", querWhere="+queryWhere+", sql="+s);
Statement st = null;
try {
st = ds.getStatement(s);
if (max > 0) {
st.setMaxRows(max);
}
java.sql.ResultSet rs = st.executeQuery(s);
rs.next();
int x = rs.getInt(1);
if (max > 0 && x > max) {
x = max;
}
return x;
} catch (Exception e) {
throw new RuntimeException("OADataSourceJDBC.count() ", e);
} finally {
if (max > 0) {
try {
st.setMaxRows(0);
} catch (Exception ex) {
}
;
}
if (st != null) {
ds.releaseStatement(st);
}
}
}
public static byte[] getPropertyBlobValue(OADataSourceJDBC ds, OAObject whereObject, String property) throws Exception {
if (whereObject.getNew()) {
return null;
}
if (property == null) {
return null;
}
Class clazz = whereObject.getClass();
Table table = ds.getDatabase().getTable(clazz);
if (table == null) {
throw new Exception("table not found for class=" + clazz + ", property=" + property);
}
QueryConverter qc = new QueryConverter(ds);
Column[] cols = qc.getSelectColumnArray(clazz);
String colName = "";
String pkeyColName = "";
String pkey = null;
Column[] columns = null;
for (Column c : cols) {
if (property.equalsIgnoreCase(c.propertyName)) {
colName = c.columnName;
columns = new Column[] { c };
} else if (c.primaryKey) {
pkeyColName = c.columnName;
pkey = whereObject.getPropertyAsString(c.propertyName);
}
}
if (columns == null) {
throw new Exception("column name not found for class=" + clazz + ", property=" + property);
}
if (pkey == null) {
throw new Exception("pkey column not found for class=" + clazz + ", property=" + property);
}
String query = "SELECT " + colName;
query += " FROM " + table.name + " WHERE " + pkeyColName + " = " + pkey;
byte[] result = null;
Statement statement = null;
OATransaction trans = null;
try {
//trans = new OATransaction(java.sql.Connection.TRANSACTION_READ_UNCOMMITTED);
//trans.start();
statement = ds.getStatement(query);
ResultSet rs = statement.executeQuery(query);
boolean b = rs.next();
if (!b) {
return null;
}
Blob blob = rs.getBlob(1);
if (blob != null) {
result = blob.getBytes(1, (int) blob.length());
}
rs.close();
} finally {
ds.releaseStatement(statement);
//trans.commit();
}
return result;
}
/**
* 20180602 select Link table.
*/
public static ArrayList<ManyToMany> getManyToMany(OADataSourceJDBC ds, OALinkInfo linkInfo) {
if (linkInfo == null) {
return null;
}
OALinkInfo revLinkInfo = linkInfo.getReverseLinkInfo();
if (linkInfo.getType() != OALinkInfo.MANY) {
return null;
}
if (revLinkInfo.getType() != OALinkInfo.MANY) {
return null;
}
Class classFrom = revLinkInfo.getToClass();
Class classTo = linkInfo.getToClass();
// Note: this assumes that fkeys are only one column
DBMetaData dbmd = ds.getDBMetaData();
Table linkTable = null;
Table fromTable = ds.getDatabase().getTable(classFrom);
if (fromTable == null) {
return null;
}
Link[] fromTableLinks = fromTable.getLinks();
if (fromTableLinks == null) {
return null;
}
Column[] fromFKeys = null;
for (int i = 0; i < fromTableLinks.length; i++) {
if (!fromTableLinks[i].toTable.bLink) {
continue;
}
if (!fromTableLinks[i].propertyName.equalsIgnoreCase(linkInfo.getName())) {
continue;
}
linkTable = fromTableLinks[i].toTable;
fromFKeys = fromTableLinks[i].fkeys;
break;
}
if (linkTable == null) {
return null;
}
if (fromFKeys == null) {
return null;
}
fromTableLinks = linkTable.getLinks();
if (fromTableLinks == null) {
return null;
}
Column[] linkTableFromFKeys = null;
for (int i = 0; i < fromTableLinks.length; i++) {
if (fromTableLinks[i].toTable == fromTable) {
linkTableFromFKeys = fromTableLinks[i].fkeys;
break;
}
}
if (linkTableFromFKeys == null) {
return null;
}
Table toTable = ds.getDatabase().getTable(classTo);
if (toTable == null) {
return null;
}
Link[] toTableLinks = toTable.getLinks();
if (toTableLinks == null) {
return null;
}
Column[] toFKeys = null;
for (int i = 0; i < toTableLinks.length; i++) {
if (!toTableLinks[i].toTable.bLink) {
continue;
}
if (!toTableLinks[i].propertyName.equalsIgnoreCase(revLinkInfo.getName())) {
continue;
}
linkTable = toTableLinks[i].toTable;
toFKeys = toTableLinks[i].fkeys;
break;
}
if (toFKeys == null) {
return null;
}
toTableLinks = linkTable.getLinks();
if (toTableLinks == null) {
return null;
}
Column[] linkTableToFKeys = null;
for (int i = 0; i < toTableLinks.length; i++) {
if (toTableLinks[i].toTable == toTable && linkTableFromFKeys != toTableLinks[i].fkeys) {
linkTableToFKeys = toTableLinks[i].fkeys;
break;
}
}
if (linkTableToFKeys == null) {
return null;
}
String query = "SELECT ";
query += linkTableFromFKeys[0].columnName;
query += ", " + linkTableToFKeys[0].columnName;
query += " FROM " + linkTable.name;
ArrayList<ManyToMany> al = null;
Statement st = null;
try {
st = ds.getStatement(query);
ResultSet rs = st.executeQuery(query);
al = new ArrayList<>();
while (rs.next()) {
OAObjectKey ok1 = new OAObjectKey(rs.getInt(1));
OAObjectKey ok2 = new OAObjectKey(rs.getInt(2));
al.add(new ManyToMany(ok1, ok2));
}
} catch (Exception e) {
throw new RuntimeException("OADataSourceJDBC.execute() " + query, e);
} finally {
if (st != null) {
ds.releaseStatement(st);
}
}
return al;
}
}
| 30.11622 | 172 | 0.659726 |
dcbcdece4038ec9c5e823b9160fe4b30327812e2 | 304 | package pl.maprzybysz.imagehostingvaadin.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.maprzybysz.imagehostingvaadin.model.Image;
@Repository
public interface ImageRepository extends JpaRepository<Image, Long> {
}
| 30.4 | 69 | 0.855263 |
51e40b3f59bc8c383345f48e2f4479263bf38f79 | 1,595 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.common;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static java.util.Objects.requireNonNull;
/**
* A registry from String to some class implementation. Used to ensure implementations are registered only once.
*/
public class NamedRegistry<T> {
private final Map<String, T> registry = new HashMap<>();
private final String targetName;
public NamedRegistry(String targetName) {
this.targetName = targetName;
}
public Map<String, T> getRegistry() {
return registry;
}
public void register(String name, T t) {
requireNonNull(name, "name is required");
requireNonNull(t, targetName + " is required");
if (registry.putIfAbsent(name, t) != null) {
throw new IllegalArgumentException(targetName + " for name [" + name + "] already registered");
}
}
public <P> void extractAndRegister(List<P> plugins, Function<P, Map<String, T>> lookup) {
for (P plugin : plugins) {
for (Map.Entry<String, T> entry : lookup.apply(plugin).entrySet()) {
register(entry.getKey(), entry.getValue());
}
}
}
}
| 32.55102 | 112 | 0.667712 |
01e287be7e5ab950d676104758c6a1dfc3987b8a | 740 | package page2.q149;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n = new Scanner(System.in).nextInt();
System.out.println(n < 200 ? getDigitCountSlowly(n) : getDigitCount(n));
}
private static int getDigitCount(int n) {
int d1 = (int)Math.floor(1 + Math.log10(Math.sqrt(2 * Math.PI * n)) + n * Math.log10(n / Math.E)),
d2 = (int)Math.floor(d1 + Math.log10(Math.E / Math.sqrt(2 * Math.PI)));
assert d1 == d2;
return d1;
}
private static int getDigitCountSlowly(int n) {
BigInteger b = BigInteger.ONE;
for(int i=2; i<=n; i++) b = b.multiply(new BigInteger(String.valueOf(i)));
return b.toString().length();
}
}
| 29.6 | 102 | 0.643243 |
e99ded8ddb0489f6b675d737982591f3dae8f924 | 312 | /*Bharathi BMS (C) 2020*/
package com.bharathi.todo.todoapp.repository;
import com.bharathi.todo.todoapp.model.Todo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TodoRepository extends JpaRepository<Todo,Long> {
}
| 28.363636 | 66 | 0.823718 |
4d0695b936b44a789efb61e290c98ed3d9bfb926 | 8,694 | /*****************************************************
*
* MultipleCurrencyAmountsTest.java
*
*
* Modified MIT License
*
* Copyright (c) 2010-2016 Kite Tech Ltd. https://www.kite.ly
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The software MAY ONLY be used with the Kite Tech Ltd platform and MAY NOT be modified
* to be used with any competitor platforms. This means the software MAY NOT be modified
* to place orders with any competitors to Kite Tech Ltd, all orders MUST go through the
* Kite Tech Ltd platform servers.
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*****************************************************/
///// Package Declaration /////
package ly.kite.catalogue;
///// Import(s) /////
import android.os.Parcel;
import junit.framework.Assert;
import junit.framework.TestCase;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.Locale;
///// Class Declaration /////
/*****************************************************
*
* This class tests the single currency amount class.
*
*****************************************************/
public class MultipleCurrencyAmountsTest extends TestCase
{
////////// Static Constant(s) //////////
@SuppressWarnings( "unused" )
private static final String LOG_TAG = "MultipleCurrencyAmountsTest";
////////// Static Variable(s) //////////
////////// Member Variable(s) //////////
////////// Static Initialiser(s) //////////
////////// Static Method(s) //////////
////////// Constructor(s) //////////
////////// Method(s) //////////
/*****************************************************
*
* Fallback tests.
*
*****************************************************/
public void testFallback1()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( "GBP" );
Assert.assertEquals( "ILS", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 4.99, singleAmounts.getAmountAsDouble() );
}
public void testFallback2()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 3.00 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( Locale.UK );
Assert.assertEquals( "ILS", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 3.00, singleAmounts.getAmountAsDouble() );
}
public void testFallback3()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "GBP" ), BigDecimal.valueOf( 1.49 ), BigDecimal.valueOf( 2.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( Locale.UK );
Assert.assertEquals( "GBP", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 1.49, singleAmounts.getAmountAsDouble() );
Assert.assertEquals( 2.99, singleAmounts.getOriginalAmountAsDouble() );
}
public void testFallback4()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "GBP" ), BigDecimal.valueOf( 1.49 ), BigDecimal.valueOf( 2.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( (Currency)null );
Assert.assertEquals( "GBP", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 1.49, singleAmounts.getAmountAsDouble() );
Assert.assertEquals( 2.99, singleAmounts.getOriginalAmountAsDouble() );
}
public void testFallback5()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "GBP" ), BigDecimal.valueOf( 1.49 ), BigDecimal.valueOf( 2.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( (Locale)null );
Assert.assertEquals( "GBP", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 1.49, singleAmounts.getAmountAsDouble() );
Assert.assertEquals( 2.99, singleAmounts.getOriginalAmountAsDouble() );
}
public void testFallback6()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "GBP" ), BigDecimal.valueOf( 1.49 ), BigDecimal.valueOf( 2.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( new Locale( "en" ) );
Assert.assertEquals( "GBP", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 1.49, singleAmounts.getAmountAsDouble() );
Assert.assertEquals( 2.99, singleAmounts.getOriginalAmountAsDouble() );
}
public void testFallback7()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "GBP" ), BigDecimal.valueOf( 1.49 ), BigDecimal.valueOf( 2.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( new Locale( "fa" ) );
Assert.assertEquals( "GBP", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 1.49, singleAmounts.getAmountAsDouble() );
Assert.assertEquals( 2.99, singleAmounts.getOriginalAmountAsDouble() );
}
public void testFallback8()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "GBP" ), BigDecimal.valueOf( 1.49 ), BigDecimal.valueOf( 2.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( new Locale( "en", "en" ) );
Assert.assertEquals( "GBP", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 1.49, singleAmounts.getAmountAsDouble() );
Assert.assertEquals( 2.99, singleAmounts.getOriginalAmountAsDouble() );
}
public void testFallback9()
{
MultipleCurrencyAmounts multipleAmounts = new MultipleCurrencyAmounts();
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "ILS" ), BigDecimal.valueOf( 4.99 ) ) );
multipleAmounts.add( new SingleCurrencyAmounts( Currency.getInstance( "GBP" ), BigDecimal.valueOf( 1.49 ), BigDecimal.valueOf( 2.99 ) ) );
SingleCurrencyAmounts singleAmounts = multipleAmounts.getAmountsWithFallback( new Locale( "fa", "FA" ) );
Assert.assertEquals( "GBP", singleAmounts.getCurrencyCode() );
Assert.assertEquals( 1.49, singleAmounts.getAmountAsDouble() );
Assert.assertEquals( 2.99, singleAmounts.getOriginalAmountAsDouble() );
}
////////// Inner Class(es) //////////
/*****************************************************
*
* ...
*
*****************************************************/
}
| 38.131579 | 142 | 0.685415 |
0968e3c7f59d24a62e636b4b20e33e7a04bf0002 | 260 | package com.mapledocs.api.dto.core;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.elasticsearch.action.index.IndexResponse;
@Data
@AllArgsConstructor
public class SearchIndexIndexingResponseDTO {
private IndexResponse indexResponse;
}
| 21.666667 | 52 | 0.834615 |
bd69d687d7d5aae640c66b286fa207ac318467e9 | 1,994 | package org.cloudfoundry.multiapps.mta.helpers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.cloudfoundry.multiapps.mta.util.NameUtil;
public class VisitableObject {
private final Object object;
public VisitableObject(Object object) {
this.object = object;
}
public Object accept(String key, SimplePropertyVisitor visitor) {
return accept(key, this.object, visitor);
}
public Object accept(SimplePropertyVisitor visitor) {
return accept("", this.object, visitor);
}
@SuppressWarnings("unchecked")
private Object accept(String key, Object value, SimplePropertyVisitor visitor) {
if (value instanceof Collection) {
return acceptInternal(key, (Collection<?>) value, visitor);
} else if (value instanceof Map) {
return acceptInternal(key, (Map<String, ?>) value, visitor);
} else if (value instanceof String) {
return acceptInternal(key, (String) value, visitor);
}
return value;
}
private Object acceptInternal(String key, Map<String, ?> value, SimplePropertyVisitor visitor) {
Map<String, Object> result = new TreeMap<>();
for (Map.Entry<String, ?> entry : value.entrySet()) {
result.put(entry.getKey(), accept(NameUtil.getPrefixedName(key, entry.getKey()), entry.getValue(), visitor));
}
return result;
}
private Object acceptInternal(String key, Collection<?> value, SimplePropertyVisitor visitor) {
List<Object> result = new ArrayList<>();
int i = 0;
for (Object element : value) {
result.add(accept(NameUtil.getPrefixedName(key, Integer.toString(i++)), element, visitor));
}
return result;
}
private Object acceptInternal(String key, String value, SimplePropertyVisitor visitor) {
return visitor.visit(key, value);
}
} | 33.233333 | 121 | 0.660481 |
e1810a2b02478f1be25d397fd1000882ba9ac9ad | 2,509 | package org.thekiddos.faith.functional;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.thekiddos.faith.Utils;
import org.thekiddos.faith.dtos.ProjectDto;
import org.thekiddos.faith.models.Stakeholder;
import org.thekiddos.faith.models.User;
import org.thekiddos.faith.services.ProjectService;
import org.thekiddos.faith.services.UserService;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class PublicProjectFeature {
private final WebDriver webDriver;
private final ProjectService projectService;
private final UserService userService;
@Autowired
public PublicProjectFeature( WebDriver webDriver, ProjectService projectService, UserService userService ) {
this.webDriver = webDriver;
this.projectService = projectService;
this.userService = userService;
setUp();
}
void setUp() {
User stakeholderUser = Utils.getOrCreateTestUser( userService, "stakeholder@projects.com", "Stakeholder" );
var project = ProjectDto.builder()
.allowBidding( true )
.description( "Hellooooo" )
.duration( 3 )
.minimumQualification( 20 )
.name( "Death" )
.preferredBid( 200 )
.build();
projectService.createProjectFor( (Stakeholder) stakeholderUser.getType(), project );
// TODO: create non public project and make sure it's not on page
// project.setAllowBidding( false );
// projectService.createProjectFor( (Stakeholder) stakeholderUser.getType(), project );
}
@Given( "a user open list of available projects for bidding" )
public void aUserOpenListOfAvailableProjectsForBidding() {
webDriver.get( Utils.PUBLIC_PROJECTS_PAGE );
}
@When( "user clicks on a project" )
public void userClicksOnAProject() {
webDriver.findElement( By.className( "btn" ) ).click();
}
@Then( "user is redirected to project details page" )
public void userIsRedirectedToProjectDetailsPage() {
assertTrue( isProjectDetailsUrl( webDriver.getCurrentUrl() ) );
webDriver.close();
}
private boolean isProjectDetailsUrl( String currentUrl ) {
return currentUrl.matches( Utils.PUBLIC_PROJECT_DETAILS_PAGE_PREFIX + "\\d+" );
}
}
| 36.897059 | 115 | 0.697489 |
6672d16897a8314f20d287b06a321c0469d62e74 | 1,904 | package com.project.employee.domains;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
@Entity
public class Division {
@Id
@GeneratedValue
private Long id;
private String name;
private String description;
@OneToMany(fetch = FetchType.LAZY,mappedBy = "division")
private Set<Position> positions = new HashSet<>();
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "department_id")
private Department department;
/**
* @return Long return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return String return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return String return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return Set<Position> return the positions
*/
public Set<Position> getPositions() {
return positions;
}
/**
* @param positions the positions to set
*/
public void setPositions(Set<Position> positions) {
this.positions = positions;
}
/**
* @return Department return the department
*/
public Department getDepartment() {
return department;
}
/**
* @param department the department to set
*/
public void setDepartment(Department department) {
this.department = department;
}
}
| 18.851485 | 60 | 0.594538 |
0ee8343318d93873b2454bdcec791f42d64a6a9d | 104 | /**
* 测试框架
*/
package com.ciaoshen.thinkinjava.newchapter17;
interface Builder<T> {
T build();
}
| 11.555556 | 46 | 0.653846 |
78d0fa2ece995f22ac5f956b2f2ad2e390fc7d94 | 4,334 | package com.uniform_imperials.herald.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.uniform_imperials.herald.BaseFragment;
import com.uniform_imperials.herald.MainApplication;
import com.uniform_imperials.herald.R;
import com.uniform_imperials.herald.adapters.AppSettingAdapter;
import com.uniform_imperials.herald.drawables.DividerItemDecoration;
import com.uniform_imperials.herald.model.AppSetting;
/**
* A fragment representing a list of Items.
* <p>
* Activities containing this fragment MUST implement the {@link AppSettingFragmentInteractionListener}
* interface.
*/
public class SettingFragment extends BaseFragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private AppSettingFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public SettingFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static SettingFragment newInstance(int columnCount) {
SettingFragment fragment = new SettingFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
this.mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View createView(LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(R.layout.fragment_setting_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
// To get main app, traverse to the parent context (MainActivity), and then get the app ctx.
MainApplication appContext = (MainApplication) this.getContext().getApplicationContext();
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
// Boilerplate for switching between grid and linear layouts.
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, this.mColumnCount));
}
// Attach the item decorator for the divider
recyclerView.addItemDecoration(new DividerItemDecoration(this.getActivity()));
// Create the adapter and attach it to the view.
recyclerView.setAdapter(new AppSettingAdapter(appContext, this.mListener));
}
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AppSettingFragmentInteractionListener) {
mListener = (AppSettingFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface AppSettingFragmentInteractionListener {
// TODO: Update argument type and name
void onAppSettingFragmentInteraction(AppSetting setting);
}
}
| 36.420168 | 104 | 0.699585 |
43f4d5e5e8e8b797ac346d0afee73ec3a2e26f7b | 953 | package tankgame.objects;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
public class Gun extends GameObject{
private int angle;
Gun(int x, int y, int angle,BufferedImage image) {
super(x, y, image);
this.angle = angle;
}
@Override
public Rectangle getBoundary() {
return super.getBoundary();
}
//@Override
public void drawImage(Graphics g) {
AffineTransform rotation = AffineTransform.getTranslateInstance(x, y);
rotation.rotate(Math.toRadians(angle), 0/ 2.0, 0 / 2.0);
((Graphics2D) g).drawImage(this.image,rotation,null);
}
public void setX(int input){
this.x = input;
}
public void setY(int input){
this.y = input;
}
public void setAngle(int input){
this.angle = input;
}
public int getAngle(){
return angle;
}
}
| 25.078947 | 79 | 0.598111 |
a842c6b2627d16679798919295ad75e2db4f9384 | 2,689 | package mekanism.common.content.tank;
import java.util.List;
import mekanism.api.Action;
import mekanism.common.Mekanism;
import mekanism.common.content.blocktype.BlockTypeTile;
import mekanism.common.multiblock.MultiblockCache;
import mekanism.common.multiblock.MultiblockManager;
import mekanism.common.multiblock.UpdateProtocol;
import mekanism.common.registries.MekanismBlockTypes;
import mekanism.common.tile.TileEntityDynamicTank;
import mekanism.common.util.StackUtils;
import mekanism.common.util.StorageUtils;
import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
public class TankUpdateProtocol extends UpdateProtocol<SynchronizedTankData> {
public static final int FLUID_PER_TANK = 64_000;
public TankUpdateProtocol(TileEntityDynamicTank tile) {
super(tile);
}
@Override
protected CasingType getCasingType(BlockPos pos) {
Block block = pointer.getWorld().getBlockState(pos).getBlock();
if (BlockTypeTile.is(block, MekanismBlockTypes.DYNAMIC_TANK)) {
return CasingType.FRAME;
} else if (BlockTypeTile.is(block, MekanismBlockTypes.DYNAMIC_VALVE)) {
return CasingType.VALVE;
}
return CasingType.INVALID;
}
@Override
protected TankCache getNewCache() {
return new TankCache();
}
@Override
protected SynchronizedTankData getNewStructure() {
return new SynchronizedTankData((TileEntityDynamicTank) pointer);
}
@Override
protected MultiblockManager<SynchronizedTankData> getManager() {
return Mekanism.tankManager;
}
@Override
protected void mergeCaches(List<ItemStack> rejectedItems, MultiblockCache<SynchronizedTankData> cache, MultiblockCache<SynchronizedTankData> merge) {
TankCache tankCache = (TankCache) cache;
TankCache mergeCache = (TankCache) merge;
StorageUtils.mergeTanks(tankCache.getFluidTanks(null).get(0), mergeCache.getFluidTanks(null).get(0));
tankCache.editMode = mergeCache.editMode;
List<ItemStack> rejects = StackUtils.getMergeRejects(tankCache.getInventorySlots(null), mergeCache.getInventorySlots(null));
if (!rejects.isEmpty()) {
rejectedItems.addAll(rejects);
}
StackUtils.merge(tankCache.getInventorySlots(null), mergeCache.getInventorySlots(null));
}
@Override
protected void onFormed() {
super.onFormed();
if (!structureFound.fluidTank.isEmpty()) {
structureFound.fluidTank.setStackSize(Math.min(structureFound.fluidTank.getFluidAmount(), structureFound.getTankCapacity()), Action.EXECUTE);
}
}
} | 37.347222 | 153 | 0.735218 |
8159dda49ee02f9bcc66a3e68a5ae8ee282f3f80 | 5,813 | package kunlun.test;
/*
* Copyright (c) 2019 ZettaDB inc. All rights reserved.
* This source code is licensed under Apache 2.0 License,
* combined with Common Clause Condition 1.0, as detailed in the NOTICE file.
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
public class SmokeTest {
static {
try {
Class.forName("org.postgresql.Driver");
//Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception ex) {
}
}
public static Connection getConnection(String user,
String password,
String host,
int port,
String dbname) {
String proto = "postgresql";
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
String url = "jdbc:" + proto+"://" + host + ":" + port + "/" + dbname;
try {
return DriverManager.getConnection(url, props);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void smokeTest(Connection conn) throws Exception{
boolean autocommit = conn.getAutoCommit();
System.out.println("default autocommit: " + autocommit);
conn.setAutoCommit(true);
Statement st =conn.createStatement();
st.execute("SET client_min_messages TO 'warning';");
st.execute("drop table if exists t1;");
st.execute("RESET client_min_messages;");
String createSql = "create table t1(id integer primary key, " +
"info text, wt integer);";
st.execute(createSql);
st.execute("insert into t1(id,info,wt) values(1, 'record1', 1);");
st.execute("insert into t1(id,info,wt) values(2, 'record2', 2);");
st.execute("update t1 set wt = 12 where id = 1;");
ResultSet res1 = st.executeQuery("select * from t1;");
System.out.printf("res1:%s%n", showResults(res1).toString());
res1.close();
st.close();
String pstr = "select * from t1 where id=?";
PreparedStatement ps = conn.prepareStatement(pstr);
ps.setInt(1, 1);
ResultSet pres = ps.executeQuery();
System.out.printf("pres1:%s%n", showResults(pres).toString());
ps.setInt(1, 2);
pres = ps.executeQuery();
System.out.printf("pres2:%s%n", showResults(pres).toString());
ps.close();
pstr = "update t1 set info=? , wt=? where id=?";
ps = conn.prepareStatement(pstr);
ps.setString(1, "Rec1");
ps.setInt(2, 2);
ps.setInt(3, 1);
ps.execute();
ps.setString(1, "Rec2");
ps.setInt(2, 3);
ps.setInt(3, 2);
ps.execute();
ps.close();
st =conn.createStatement();
ResultSet res2 = st.executeQuery("select * from t1;");
System.out.printf("res2:%s%n", showResults(res2).toString());
res2.close();
st.execute("delete from t1 where id = 1;");
ResultSet res3 = st.executeQuery("select * from t1;");
System.out.printf("res3:%s%n", showResults(res3).toString());
res3.close();
st.execute("drop table t1;");
st.close();
conn.setAutoCommit(autocommit);
}
/*
* We do the following actions:
* 1 Create the able
* 2 Insert two records
* 3 Update the first record.
* 4 Query the records(res1).
* 5 Delete the second record.
* 6 Query the records again(res2).
* 7 Drop the table.
*/
public static void smokeTestFile(Connection conn, String cmdfile) throws Exception{
boolean autocommit = conn.getAutoCommit();
System.out.println("default autocommit: " + autocommit);
conn.setAutoCommit(true);
Statement st =conn.createStatement();
BufferedReader br = new BufferedReader(new FileReader(cmdfile));
String cmd = null;
do {
cmd = br.readLine();
if (cmd == null) {
break;
}
if (cmd.toUpperCase().startsWith("SELECT")) {
ResultSet res = st.executeQuery(cmd);
System.out.printf("sql:%s, res:%s%n", cmd,
showResults(res).toString());
res.close();
} else {
st.execute(cmd);
}
} while (cmd != null);
br.close();
st.close();
conn.setAutoCommit(autocommit);
}
private static List<List<String>> showResults(ResultSet res)
throws Exception {
LinkedList<List<String>> results = new LinkedList<>();
int cols = res.getMetaData().getColumnCount();
while (res.next()) {
List<String> row = new ArrayList<>(cols);
for (int i = 0; i < cols; i++) {
row.add(res.getString(i + 1));
}
results.addLast(row);
}
return results;
}
public static void test1(String[] args) throws Exception{
String host = args[0];
int port = Integer.valueOf(args[1]);
String user = "abc";
String password = "abc";
String database = "postgres";
Connection conn = getConnection(user, password, host, port, database);
smokeTest(conn);
conn.close();
}
public static void main(String[] args) throws Exception {
test1(args);
}
}
| 34.60119 | 87 | 0.55892 |
6c470b251484965b806d5295778d2b2550a6440c | 6,032 | /*
* Copyright (c) 2013, Cloudera, Inc. All Rights Reserved.
*
* Cloudera, Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"). You may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 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.cloudera.oryx.common;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/**
* {@link Class}-related utility methods.
*
* @author Sean Owen
*/
public final class ClassUtils {
private static final Class<?>[] NO_TYPES = new Class<?>[0];
private static final Object[] NO_ARGS = new Object[0];
private ClassUtils() {
}
/**
* Like {@link #loadInstanceOf(String, Class)} where the reference returned is of the same type as
* the class being loaded -- not any supertype.
*
* @param <T> class of instance returned
* @param clazz {@link Class} of instance returned
* @return instance of {@code clazz}
*/
public static <T> T loadInstanceOf(Class<T> clazz) {
return loadInstanceOf(clazz.getName(), clazz);
}
/**
* Like {@link #loadInstanceOf(String, Class, Class[], Object[])} where the reference returned is
* of the same type as the class being loaded -- not any supertype.
*
* @param <T> class of instance returned
* @param clazz {@link Class} of instance returned
* @param constructorTypes argument types of constructor to use
* @param constructorArgs actual constructor arguments
* @return instance of {@code clazz}
*/
public static <T> T loadInstanceOf(Class<T> clazz, Class<?>[] constructorTypes, Object[] constructorArgs) {
return loadInstanceOf(clazz.getName(), clazz, constructorTypes, constructorArgs);
}
/**
* Like {@link #loadInstanceOf(String, Class, Class[], Object[])} for no-arg constructors.
*
* @param <T> (super)class of instance returned
* @param implClassName implementation class name
* @param superClass superclass or interface that the implementation extends
* @return instance of {@code implClassName}
*/
public static <T> T loadInstanceOf(String implClassName, Class<T> superClass) {
return loadInstanceOf(implClassName, superClass, NO_TYPES, NO_ARGS);
}
/**
* Loads and instantiates a named implementation class, a subclass of a given supertype,
* whose constructor takes the given arguments.
*
* @param <T> (super)class of instance returned
* @param implClassName implementation class name
* @param superClass superclass or interface that the implementation extends
* @param constructorTypes argument types of constructor to use
* @param constructorArgs actual constructor arguments
* @return instance of {@code implClassName}
*/
public static <T> T loadInstanceOf(String implClassName,
Class<T> superClass,
Class<?>[] constructorTypes,
Object[] constructorArgs) {
return doLoadInstanceOf(implClassName,
superClass,
constructorTypes,
constructorArgs,
ClassUtils.class.getClassLoader());
}
private static <T> Class<? extends T> doLoadClass(String implClassName,
Class<T> superClass,
ClassLoader classLoader) {
try {
return Class.forName(implClassName, true, classLoader).asSubclass(superClass);
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("No valid " + superClass + " binding exists", cnfe);
}
}
private static <T> T doLoadInstanceOf(String implClassName,
Class<T> superClass,
Class<?>[] constructorTypes,
Object[] constructorArgs,
ClassLoader classLoader) {
try {
Class<? extends T> configClass = doLoadClass(implClassName, superClass, classLoader);
Constructor<? extends T> constructor = configClass.getConstructor(constructorTypes);
return constructor.newInstance(constructorArgs);
} catch (NoSuchMethodException nsme) {
throw new IllegalStateException("No valid " + superClass + " binding exists", nsme);
} catch (InvocationTargetException ite) {
throw new IllegalStateException("Could not instantiate " + superClass + " due to exception", ite.getCause());
} catch (InstantiationException ie) {
throw new IllegalStateException("No valid " + superClass + " binding exists", ie);
} catch (IllegalAccessException iae) {
throw new IllegalStateException("No valid " + superClass + " binding exists", iae);
}
}
/**
* @param implClassName class name to text
* @return {@code true} if the class exists in the JVM and can be loaded
*/
public static boolean classExists(String implClassName) {
try {
Class.forName(implClassName);
return true;
} catch (ClassNotFoundException ignored) {
return false;
}
}
/**
* @param clazz the class containing the field to load
* @param fieldName the field name
* @return the named {@link Field}, made accessible, from the given {@link Class}
*/
public static Field loadField(Class<?> clazz, String fieldName) {
Field field;
try {
field = clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException nsfe) {
throw new IllegalStateException("Can't access " + clazz.getSimpleName() + '.' + fieldName, nsfe);
}
field.setAccessible(true);
return field;
}
}
| 38.916129 | 115 | 0.651691 |
ec460b0b62036ffb2a585baf220229b0adf9ba75 | 1,346 | package pinacolada.cards.pcl.curse;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import pinacolada.cards.base.CardUseInfo;
import pinacolada.cards.base.PCLCard;
import pinacolada.cards.base.PCLCardData;
import pinacolada.cards.base.PCLCardTarget;
import pinacolada.utilities.PCLActions;
import pinacolada.utilities.PCLGameUtilities;
public class Curse_Depression extends PCLCard
{
public static final PCLCardData DATA = Register(Curse_Depression.class)
.SetCurse(-2, PCLCardTarget.None, false);
public Curse_Depression()
{
super(DATA);
Initialize(0,0,1,0);
SetAffinity_Dark(1);
SetEthereal(true);
SetUnplayable(true);
}
@Override
public void triggerWhenDrawn()
{
super.triggerWhenDrawn();
PCLActions.Bottom.DiscardFromHand(name, 1, true)
.ShowEffect(true, true)
.SetOptions(false, false, false)
.SetFilter(card -> !PCLGameUtilities.IsHindrance(card));
PCLActions.Bottom.Flash(this);
}
@Override
public void triggerOnExhaust()
{
super.triggerOnExhaust();
PCLActions.Bottom.GainWisdom(magicNumber);
}
@Override
public void OnUse(AbstractPlayer p, AbstractMonster m, CardUseInfo info)
{
}
} | 25.396226 | 76 | 0.699851 |
3f3f0eacc0d2eb5ed1af5c728480ce3ecbcc8920 | 373 | package net.kodar.restaurantapi.dataaccess.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import net.kodar.restaurantapi.data.entities.ApiGroup;
@Repository
public interface ApiGroupRepository extends CrudRepository<ApiGroup, Long> {
//List<ApiGroup> findByApiUser(ApiUser user);
}
| 28.692308 | 77 | 0.812332 |
38ccb8f4ca64bbf0db05046e02f775c85781cf47 | 7,206 | /*
* Copyright 2020 SvenAugustus
*
* 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 xyz.flysium.dao.repository;
import java.util.List;
import org.apache.ibatis.jdbc.SQL;
import xyz.flysium.dao.entity.Emp;
import xyz.flysium.dao.entity.EmpExample;
import xyz.flysium.dao.entity.EmpExample.Criteria;
import xyz.flysium.dao.entity.EmpExample.Criterion;
public class EmpSqlProvider {
public String insertSelective(Emp record) {
SQL sql = new SQL();
sql.INSERT_INTO("emp");
if (record.getEname() != null) {
sql.VALUES("ENAME", "#{ename,jdbcType=VARCHAR}");
}
if (record.getJob() != null) {
sql.VALUES("JOB", "#{job,jdbcType=VARCHAR}");
}
if (record.getMgr() != null) {
sql.VALUES("MGR", "#{mgr,jdbcType=INTEGER}");
}
if (record.getHiredate() != null) {
sql.VALUES("HIREDATE", "#{hiredate,jdbcType=DATE}");
}
if (record.getSal() != null) {
sql.VALUES("SAL", "#{sal,jdbcType=DECIMAL}");
}
if (record.getComm() != null) {
sql.VALUES("COMM", "#{comm,jdbcType=DECIMAL}");
}
if (record.getDeptno() != null) {
sql.VALUES("DEPTNO", "#{deptno,jdbcType=INTEGER}");
}
return sql.toString();
}
public String selectByExample(EmpExample example) {
SQL sql = new SQL();
if (example != null && example.isDistinct()) {
sql.SELECT_DISTINCT("EMPNO");
} else {
sql.SELECT("EMPNO");
}
sql.SELECT("ENAME");
sql.SELECT("JOB");
sql.SELECT("MGR");
sql.SELECT("HIREDATE");
sql.SELECT("SAL");
sql.SELECT("COMM");
sql.SELECT("DEPTNO");
sql.FROM("emp");
applyWhere(sql, example, false);
if (example != null && example.getOrderByClause() != null) {
sql.ORDER_BY(example.getOrderByClause());
}
return sql.toString();
}
public String updateByPrimaryKeySelective(Emp record) {
SQL sql = new SQL();
sql.UPDATE("emp");
if (record.getEname() != null) {
sql.SET("ENAME = #{ename,jdbcType=VARCHAR}");
}
if (record.getJob() != null) {
sql.SET("JOB = #{job,jdbcType=VARCHAR}");
}
if (record.getMgr() != null) {
sql.SET("MGR = #{mgr,jdbcType=INTEGER}");
}
if (record.getHiredate() != null) {
sql.SET("HIREDATE = #{hiredate,jdbcType=DATE}");
}
if (record.getSal() != null) {
sql.SET("SAL = #{sal,jdbcType=DECIMAL}");
}
if (record.getComm() != null) {
sql.SET("COMM = #{comm,jdbcType=DECIMAL}");
}
if (record.getDeptno() != null) {
sql.SET("DEPTNO = #{deptno,jdbcType=INTEGER}");
}
sql.WHERE("EMPNO = #{empno,jdbcType=BIGINT}");
return sql.toString();
}
protected void applyWhere(SQL sql, EmpExample example, boolean includeExamplePhrase) {
if (example == null) {
return;
}
String parmPhrase1;
String parmPhrase1_th;
String parmPhrase2;
String parmPhrase2_th;
String parmPhrase3;
String parmPhrase3_th;
if (includeExamplePhrase) {
parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}";
parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}";
parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}";
parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
} else {
parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}";
parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}";
parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}";
parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
}
StringBuilder sb = new StringBuilder();
List<Criteria> oredCriteria = example.getOredCriteria();
boolean firstCriteria = true;
for (int i = 0; i < oredCriteria.size(); i++) {
Criteria criteria = oredCriteria.get(i);
if (criteria.isValid()) {
if (firstCriteria) {
firstCriteria = false;
} else {
sb.append(" or ");
}
sb.append('(');
List<Criterion> criterions = criteria.getAllCriteria();
boolean firstCriterion = true;
for (int j = 0; j < criterions.size(); j++) {
Criterion criterion = criterions.get(j);
if (firstCriterion) {
firstCriterion = false;
} else {
sb.append(" and ");
}
if (criterion.isNoValue()) {
sb.append(criterion.getCondition());
} else if (criterion.isSingleValue()) {
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j));
} else {
sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j,
criterion.getTypeHandler()));
}
} else if (criterion.isBetweenValue()) {
if (criterion.getTypeHandler() == null) {
sb.append(
String.format(parmPhrase2, criterion.getCondition(), i, j, i, j));
} else {
sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j,
criterion.getTypeHandler(), i, j, criterion.getTypeHandler()));
}
} else if (criterion.isListValue()) {
sb.append(criterion.getCondition());
sb.append(" (");
List<?> listItems = (List<?>) criterion.getValue();
boolean comma = false;
for (int k = 0; k < listItems.size(); k++) {
if (comma) {
sb.append(", ");
} else {
comma = true;
}
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase3, i, j, k));
} else {
sb.append(String
.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler()));
}
}
sb.append(')');
}
}
sb.append(')');
}
}
if (sb.length() > 0) {
sql.WHERE(sb.toString());
}
}
} | 32.754545 | 165 | 0.584513 |
bc569689a8618ee61418244d32e618b88fdaf951 | 1,782 | package ch.vorburger.blueprint.disrest.sampletest.statc.interactionmodel;
import static ch.vorburger.blueprint.disrest.core.ReferenceRemotingType.EMBED;
import static ch.vorburger.blueprint.disrest.core.ReferenceRemotingType.ONLY_REFERENCE;
import ch.vorburger.blueprint.disrest.core.Operation;
import ch.vorburger.blueprint.disrest.core.OperationReturn;
import ch.vorburger.blueprint.disrest.core.Property;
import ch.vorburger.blueprint.disrest.core.Resource;
import ch.vorburger.blueprint.disrest.core.SingleReference;
import ch.vorburger.blueprint.disrest.core.statc.Id;
import ch.vorburger.blueprint.disrest.core.statc.ReferenceRemoting;
import ch.vorburger.blueprint.disrest.sampletest.statc.interactionmodel.datatypes.ISBN;
/**
* Book Resource (Sample/Test).
*
* @author Michael Vorburger
*/
public interface Book extends Resource {
// NOTE This is the interaction model, the data (!) model probably has additional attributes such as boolean isActive, which we don't need/want to expose here.
@Id
Property<ISBN> isbn();
Property<String> title();
/* OR:
String getTitle();
void setTitle(String title);
boolean isTitleAvailable();
*/
// real-life books have many authors, but just to illustrate multiplicity many vs. single here we'll say a Book has only one Author
@ReferenceRemoting(EMBED)
SingleReference<Author> author();
@ReferenceRemoting(ONLY_REFERENCE)
SingleReference<Reservation> currentReservation();
Operation<Reservation> borrow();
// TODO how to model 'exceptions' - e.g. if a book is already borrowed() then the operation won't succeed...
/**
* Book Reservation Resource (Sample/Test).
*/
public interface Reservation extends Resource {
// TODO User borrower, Date from, Date to, int numberOfTimesToDateWasExtended
}
}
| 34.941176 | 160 | 0.785634 |
26d4a68a7401a2c95eb98d84823d5489ebbdd827 | 634 | package com.nimo.rediswebui.dao;
import com.nimo.rediswebui.entity.UserInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* @author nimo
* @version V1.0
* @date 2022/2/9 13:54
* @Description: UserDao
*/
@Repository
public interface UserDao extends JpaRepository<UserInfo,Long> {
/**
* 查找用户
* @param username
* @return
*/
UserInfo findByUserName(String username);
/**
* 验证用户
* @param username
* @param password
* @return
*/
UserInfo findByUserNameAndPassword(String username,String password);
}
| 21.133333 | 72 | 0.684543 |
c779875afbef694647b296f7c25cce116bbd8785 | 356 | package com.bizo.dtonator.domain;
public abstract class BlueAccount extends Account {
private boolean bar;
public BlueAccount() {
}
public BlueAccount(Long id, String name, boolean bar) {
super(id, name);
this.bar = bar;
}
public boolean isBar() {
return bar;
}
public void setBar(boolean bar) {
this.bar = bar;
}
}
| 15.478261 | 57 | 0.654494 |
fffc7668a2140fe1c13afb9132f6d685838223d5 | 1,647 | package com.bfsi.mfi.dao;
import java.util.List;
import com.bfsi.mfi.entity.Agent;
import com.bfsi.mfi.entity.AgentTransaction;
import com.bfsi.mfi.entity.CbsCodes;
import com.bfsi.mfi.vo.AgentVO;
/**
* User DAO
*
* @author akrishna
* @param <User>
*/
public interface AgentDao extends MaintenanceDao<Agent> {
public List<Agent> getAgendIdForAllocation();
public AgentVO generateRegKey(String id);
public String getAutoAgentId();
public boolean validateDeviceId(String uniqueId, String deviceId);
public void updateAgentWithDataKey(String agentId, String dataKey);
public void updateAgentRegistConfirm(String agentId);
public Agent checkDataKeyAvailable(String agentId);
public boolean isUserIdAvailable(String userId);
public Agent getAgentByUserName(String id);
public Agent getAgentIdByUserName(String userName);
public String deleteAgent(String id);
public List<Agent> getAuthorized();
public List<Agent> getAuthAgentHavCreditOfficer();
public List<Agent> getcountryCodes();
public int validateAgentForTransaction(AgentTransaction p_tran);
public void addRolesToAgent(Agent agent);
public List<String> getEntitlements(Agent agent);
public List<String> getAgentRoles(String agentId);
/**
* Insert to AMTB_AGENT_ROLES table.
*/
public void addRolesToUser(Agent agent);
/**
* Delete to AMTB_AGENT_ROLES table.
*/
public void deleteRolesToUser(Agent agent);
public String getMacId(String p_agentId);
public void unregisterAgent(String p_agentId);
public List<CbsCodes> getCbsAgentCode();
public List<Agent> getAgentIds();
public String agentDataKey(String agentId);
}
| 21.96 | 68 | 0.774135 |
1aa6ba75be2a7cc335fb21565ab6dc4c31e0807a | 706 | package com.langdon.ioc.context;
/**
* @desc
* @create by langdon on 2019/1/2-12:28 AM
**/
public interface AnnotationConfigRegistry {
/**
* Register one or more annotated classes to be processed.
* <p>Calls to {@code register} are idempotent; adding the same
* annotated class more than once has no additional effect.
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
*/
void register(Class<?>... annotatedClasses);
/**
* Perform a scan within the specified base packages.
* @param basePackages the packages to check for annotated classes
*/
void scan(String... basePackages);
}
| 29.416667 | 70 | 0.677054 |
121a9e2092a9a5b9e1acf84d910df251b828aef2 | 6,928 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.thespheres.betula.tableimport.impl;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.thespheres.betula.StudentId;
import org.thespheres.betula.UnitId;
import org.thespheres.betula.document.DocumentId;
import org.thespheres.betula.services.ServiceConstants;
import org.thespheres.betula.services.scheme.spi.Term;
import org.thespheres.betula.services.util.Signees;
import org.thespheres.betula.tableimport.action.XmlCsvImportSettings;
import org.thespheres.betula.util.CollectionUtil;
import org.thespheres.betula.xmlimport.ImportTargetsItem;
import org.thespheres.betula.xmlimport.ImportUtil;
import org.thespheres.betula.xmlimport.model.XmlStudentItem;
import org.thespheres.betula.xmlimport.model.XmlUnitItem;
import org.thespheres.betula.xmlimport.uiutil.AbstractFileImportAction;
import org.thespheres.betula.xmlimport.utilities.ConfigurableImportTarget;
import org.thespheres.betula.xmlimport.utilities.ImportStudentKey;
import org.thespheres.betula.xmlimport.utilities.TargetDocumentProperties;
import org.thespheres.betula.xmlimport.utilities.UpdaterFilter;
/**
*
* @author boris.heithecker
*/
public class PrimaryUnitsXmlCsvItem extends AbstractXmlCsvImportItem<XmlUnitItem> {
static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("d.M.y", Locale.getDefault());
public static final String PROP_CONFIGURATION = "configuration";
public static final String PROP_TARGET_ID = "targetId";
private final ConfigurableImportTargetHelper helper;
private final PrimaryUnitImportStudentsSet importStudents = new PrimaryUnitImportStudentsSet(this);
private IOException importStudentsException;
public PrimaryUnitsXmlCsvItem(String sourceNode, XmlUnitItem source) {
super(sourceNode, source);
this.helper = new ConfigurableImportTargetHelper(this);
}
public synchronized void initialize(final ConfigurableImportTarget config, final XmlCsvImportSettings wizard) {
final ConfigurableImportTarget oldCfg = getConfiguration();
final boolean configChanged = oldCfg == null
|| !oldCfg.getProviderInfo().equals(config.getProviderInfo());
uniqueMarkers.add(ServiceConstants.BETULA_PRIMARY_UNIT_MARKER);
//
Term term = (Term) wizard.getProperty(AbstractFileImportAction.TERM);
try {
setClientProperty(ImportTargetsItem.PROP_SELECTED_TERM, term);
} catch (PropertyVetoException ex) {
}
if (configChanged || getDeleteDate() == null) {
final Integer level = helper.findLevel();
if (level != null) {
setDeleteDate(ImportUtil.calculateDeleteDate(level, 5, Month.JULY));
}
}
if (configChanged) {
Signees.get(config.getWebServiceProvider().getInfo().getURL())
.flatMap(s -> s.findSignee(getSourceSigneeName()))
.ifPresent(this::setSignee);
}
if (configChanged) {
importStudents.setConfiguration(config);
if (!getSource().getStudents().isEmpty()) {
final List<XmlStudentItem> ls = getSource().getStudents();
setStudents(ls);
} else {
importStudents.clear();
students = null;
}
}
try {
setClientProperty(PROP_IMPORT_TARGET, config);
} catch (PropertyVetoException ex) {
ex.printStackTrace(ImportUtil.getIO().getErr());
}
}
public PrimaryUnitImportStudentsSet getImportStudents() {
return importStudents;
}
private void setStudents(final List<XmlStudentItem> ls) {
final Map<ImportStudentKey, XmlStudentItem> m = ls.stream()
.filter(i -> !StringUtils.isBlank(i.getSourceName()))
.collect(Collectors.groupingBy(ImportItemsUtil::createImportStudentKey, CollectionUtil.requireSingleOrNull()));
m.entrySet().forEach(me -> {
try {
importStudents.put(me.getKey(), me.getValue());
importStudentsException = null;
} catch (IOException ex) {
importStudentsException = ex;
ex.printStackTrace(ImportUtil.getIO().getErr());
}
});
}
@Override
public UnitId getUnitId() {
final UnitId u = super.getUnitId();
if (u != null) {
return u;
}
return helper.getGeneratedUnitId();
}
@Override
public StudentId[] getUnitStudents() {
return importStudents.getUnitStudents();
}
@Override
public void setUnitId(UnitId unit
) {
if (getSource().getStudents().isEmpty()) {
students = null;
}
super.setUnitId(unit);
}
@Override
public boolean isUnitIdGenerated() {
return super.getUnitId() == null;
}
@Override
public boolean existsUnitInSystem() {
return helper.existsUnit();
}
@Override
public DocumentId getTargetDocumentIdBase() {
return null;
}
@Override
public boolean isFragment() {
return false;
}
@Override
public TargetDocumentProperties[] getImportTargets() {
return new TargetDocumentProperties[0];
}
@Override
public boolean fileUnitParticipants() {
return true;
}
@Override
public String getUnitDisplayName() {
return helper.getUnitDisplayName();
}
@Override
public boolean isValid() {
return getDeleteDate() != null
&& getUnitId() != null
&& importStudents.isValid();
}
@Override
public int hashCode() {
int hash = 5;
return 97 * hash + Objects.hashCode(this.getSourceNodeLabel());
}
@Override
public boolean equals(Object obj
) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final PrimaryUnitsXmlCsvItem other = (PrimaryUnitsXmlCsvItem) obj;
return Objects.equals(this.getSourceNodeLabel(), other.getSourceNodeLabel());
}
public static class Filter implements UpdaterFilter<PrimaryUnitsXmlCsvItem, TargetDocumentProperties> {
@Override
public boolean accept(PrimaryUnitsXmlCsvItem iti) {
return iti.isSelected() && iti.isValid();
}
}
}
| 32.373832 | 127 | 0.661374 |
b7e7a5bf06def2df555155f3425be88c44b6d925 | 345 | package dev.base.entry;
import dev.base.DevEntry;
public class StringEntry<V>
extends DevEntry<String, V> {
public StringEntry() {
}
public StringEntry(final String key) {
super(key);
}
public StringEntry(
final String key,
final V value
) {
super(key, value);
}
} | 16.428571 | 42 | 0.568116 |
ad87a35bf2863bfd83ed4f9412bd916a890eec76 | 535 | package org.mx.comps.notify;
import org.junit.After;
import org.junit.Before;
import org.mx.comps.notify.config.TestConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class BaseTest {
protected AnnotationConfigApplicationContext context = null;
@Before
public void before() {
context = new AnnotationConfigApplicationContext(TestConfig.class);
}
@After
public void after() {
if (context != null) {
context.close();
}
}
}
| 23.26087 | 81 | 0.699065 |
59b2d4cca010516e71763ecf061b86f381627570 | 674 | package lab07.ex03;
import java.util.ArrayList;
public class Bloco extends Shape {
private ArrayList<Shape> elements;
private String name;
public Bloco(String name){
this.elements = new ArrayList<>();
this.name = name;
}
public void add(Shape c){
elements.add(c);
}
public void draw(){
System.out.println(super.getIndent().toString() + "Window " + this.name);
super.getIndent().append(" "); //Indent further
for(Shape i : elements){ //Print elements
i.draw();
}
super.getIndent().setLength(super.getIndent().length() - 3); //Get back to base indent
}
} | 22.466667 | 94 | 0.590504 |
9f76d06578c0ee21a2364224c8c52cabca08c851 | 1,217 | package com.joiller.gulimall.ware.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joiller.gulimall.common.utils.PageUtils;
import com.joiller.gulimall.common.utils.R;
import com.joiller.gulimall.ware.entity.WmsWareInfo;
import com.joiller.gulimall.ware.service.IWmsWareInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* <p>
* 仓库信息 前端控制器
* </p>
*
* @author jianghuilai
* @since 2021-02-22
*/
@RestController
@RequestMapping("/ware/wareinfo")
public class WmsWareInfoController {
@Autowired
IWmsWareInfoService wareInfoService;
@GetMapping("list")
public R list(@RequestParam Map<String, String> map) {
Page<WmsWareInfo> wareInfoPage = new PageUtils<WmsWareInfo>().page(map);
Page<WmsWareInfo> page = wareInfoService.page(wareInfoPage, map);
return R.ok().put("page", page);
}
}
| 29.682927 | 81 | 0.741988 |
c5816230b641f2c7ef566268a22c8580d6e0307b | 3,028 | package uk.gov.defra.plants.applicationform.dao;
import static uk.gov.defra.plants.applicationform.dao.CommodityDAOConstants.SQL_GET_POTATO_COMMODITY_BASE;
import java.util.List;
import java.util.UUID;
import org.jdbi.v3.sqlobject.SingleValue;
import org.jdbi.v3.sqlobject.config.RegisterConstructorMapper;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.customizer.BindBean;
import org.jdbi.v3.sqlobject.statement.SqlBatch;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
import uk.gov.defra.plants.applicationform.model.PersistentCommodityPotatoes;
@RegisterConstructorMapper(PersistentCommodityPotatoes.class)
public interface CommodityPotatoesDAO {
@SqlBatch(
"INSERT INTO"
+ " commodityPotatoes ("
+ " consignmentId, "
+ " potatoType,"
+ " soilSamplingApplicationNumber, "
+ " stockNumber, "
+ " lotReference, "
+ " variety, "
+ " chemicalUsed, "
+ " numberOfPackages, "
+ " packagingType, "
+ " packagingMaterial, "
+ " distinguishingMarks,"
+ " quantity,"
+ " unitOfMeasurement"
+ " ) VALUES ("
+ " :consignmentId, :potatoType, :soilSamplingApplicationNumber, :stockNumber, :lotReference, :variety, :chemicalUsed, :numberOfPackages, :packagingType, :packagingMaterial, :distinguishingMarks, :quantity, :unitOfMeasurement"
+ " ) ")
int[] insertCommodities(@BindBean List<PersistentCommodityPotatoes> persistentCommodityPotatoes);
@SqlUpdate("DELETE FROM commodityPotatoes " + "WHERE commodityUuid = :commodityUuid")
Integer deleteCommodityByUuid(@Bind("commodityUuid") UUID commodityUuid);
@SqlUpdate(
"UPDATE"
+ " commodityPotatoes"
+ " SET"
+ " potatoType = :potatoType,"
+ " soilSamplingApplicationNumber = :soilSamplingApplicationNumber, "
+ " stockNumber = :stockNumber, "
+ " lotReference = :lotReference, "
+ " variety = :variety, "
+ " chemicalUsed = :chemicalUsed, "
+ " numberOfPackages = :numberOfPackages, "
+ " packagingType = :packagingType, "
+ " packagingMaterial = :packagingMaterial, "
+ " distinguishingMarks = :distinguishingMarks, "
+ " quantity = :quantity, "
+ " unitOfMeasurement = :unitOfMeasurement "
+ " WHERE"
+ " id = :id")
Integer updateCommodity(@BindBean PersistentCommodityPotatoes persistentCommodityPotatoes);
@SqlQuery(SQL_GET_POTATO_COMMODITY_BASE + " WHERE commodityUuid = :commodityUuid")
@SingleValue
PersistentCommodityPotatoes getCommodityByCommodityUuid(
@Bind("commodityUuid") UUID commodityUuid);
@SqlQuery(
SQL_GET_POTATO_COMMODITY_BASE + " WHERE consignmentId = :consignmentId" + " ORDER BY id")
List<PersistentCommodityPotatoes> getCommoditiesByConsignmentId(
@Bind("consignmentId") UUID consignmentId);
}
| 41.479452 | 236 | 0.680317 |
02597b04f65590bc6d4cdc1e13c8b1a9f7903b99 | 3,835 | package com.acg12.lib.utils.glide;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;
import com.acg12.lib.constant.Constant;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.HttpException;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.util.ContentLengthInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
/**
* Fetches an {@link InputStream} using the okhttp library.
*/
public class OkHttpStreamFetcher implements DataFetcher<InputStream>, okhttp3.Callback {
private static final String TAG = "OkHttpFetcher";
private final Call.Factory client;
private final GlideUrl url;
private volatile Call call;
private DataCallback<? super InputStream> callback;
public OkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
this.client = client;
this.url = url;
}
@Override
public void loadData(Priority priority, final DataCallback<? super InputStream> callback) {
Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
String key = headerEntry.getKey();
// if ("referer".equals(key.toLowerCase())) {
// continue;
// }
requestBuilder.addHeader(key, headerEntry.getValue());
}
// requestBuilder.addHeader("referer", Constant.DOWNLOAD_IMG_REFERER);
Request request = requestBuilder.build();
this.callback = callback;
this.call = client.newCall(request);
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
this.call.enqueue(this);
} else {
try {
// Calling execute instead of enqueue is a workaround for #2355, where okhttp throws a
// ClassCastException on O.
onResponse(this.call, this.call.execute());
} catch (IOException e) {
onFailure(this.call, e);
} catch (ClassCastException e) {
// It's not clear that this catch is necessary, the error may only occur even on O if
// enqueue is used.
onFailure(this.call, new IOException("Workaround for framework bug on O", e));
}
}
}
@Override
public void onFailure(Call call, IOException e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "OkHttp failed to obtain result", e);
}
this.callback.onLoadFailed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
InputStream stream = ContentLengthInputStream.obtain(response.body().byteStream(), response.body().contentLength());
this.callback.onDataReady(stream);
} else {
//LogUtil.e("glide OkHttpStreamFetcher =============================>" + response.message() + "code:" + response.code() + " ==>" + call.request().toString());
this.callback.onLoadFailed(new HttpException(response.message(), response.code()));
}
}
@Override
public void cleanup() {
this.callback = null;
}
@Override
public void cancel() {
Call local = this.call;
if (local != null) {
local.cancel();
}
}
@NonNull
@Override
public Class<InputStream> getDataClass() {
return InputStream.class;
}
@NonNull
@Override
public DataSource getDataSource() {
return DataSource.REMOTE;
}
}
| 32.777778 | 170 | 0.632073 |
129bce53b4c22019b9541d2b517bd6680fdb3108 | 790 | package net.bytebuddy.implementation.bind;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.test.utility.MockitoRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
public abstract class AbstractAmbiguityResolverTest {
@Rule
public TestRule mockitoRule = new MockitoRule(this);
@Mock
protected MethodDescription source;
@Mock
protected MethodDescription leftMethod, rightMethod;
@Mock
protected MethodDelegationBinder.MethodBinding left, right;
@Before
public void setUp() throws Exception {
when(left.getTarget()).thenReturn(leftMethod);
when(right.getTarget()).thenReturn(rightMethod);
}
}
| 24.6875 | 63 | 0.756962 |
b620d0bf3ca0ee54b2da4b84759e5aa6955d0dfa | 1,074 | package com.l.library.gateway.config;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
/**
* 自定义限流标志的key,多个维度可以从这里入手
* exchange对象中获取服务ID、请求信息,用户信息等
*/
@Component
public class RequestRateLimiterConfig {
/**
* ip地址限流
*
* @return 限流key
*/
@Bean
@Primary
public KeyResolver remoteAddressKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
}
/**
* 请求路径限流
*
* @return 限流key
*/
@Bean
public KeyResolver apiKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getPath().value());
}
/**
* username限流
*
* @return 限流key
*/
@Bean
public KeyResolver userKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("username"));
}
}
| 22.851064 | 98 | 0.668529 |
448c840692a8f1ddc2f2b317017e110a56605554 | 368 | package xyz.rexhaif.jstore;
import org.mapdb.DB;
import org.mapdb.DBMaker;
public class Consts {
public static final int PORT = 8080;
public static final DBMaker.Maker dbConfig =
DBMaker
.memoryDB()
.cleanerHackEnable()
.closeOnJvmShutdown()
.executorEnable();
}
| 20.444444 | 48 | 0.559783 |
c5dc7a07453450ad940535afee4d085768ce0bc4 | 4,919 | /*
* Free Public License 1.0.0
* Permission to use, copy, modify, and/or distribute this software
* for any purpose with or without fee is hereby granted.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
* THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.atr.spacerocks.state;
import com.atr.jme.font.TrueTypeBMP;
import com.atr.jme.font.util.Style;
import com.atr.spacerocks.SpaceRocks;
import com.atr.spacerocks.ui.UI;
import com.atr.spacerocks.util.Callback;
import com.jme3.app.state.AbstractAppState;
import com.jme3.math.Vector3f;
import com.simsilica.lemur.Button;
import com.simsilica.lemur.Container;
import com.simsilica.lemur.FillMode;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.lemur.Insets3f;
import com.simsilica.lemur.Label;
import com.simsilica.lemur.ProgressBar;
import com.simsilica.lemur.component.HBoxLayout;
import com.simsilica.lemur.component.HBoxLayout.VAlign;
import com.simsilica.lemur.style.Attributes;
import com.simsilica.lemur.style.ElementId;
import com.simsilica.lemur.style.Styles;
import java.util.LinkedList;
/**
*
* @author Adam T. Ryder
* <a href="http://1337atr.weebly.com">http://1337atr.weebly.com</a>
*/
public class Restart extends AbstractAppState {
private final SpaceRocks app;
private final LinkedList<TrueTypeBMP> fonts = new LinkedList<TrueTypeBMP>();
private int currentFont = 0;
private final ProgressBar pb;
private boolean active = false;
public Restart(SpaceRocks app) {
this.app = app;
UI.setEnabled(false);
SpaceRocks.PAUSED.set(true);
UI.fade(false, 0, new Callback() {
@Override
public void call() {
active = true;
}
});
GuiGlobals g = GuiGlobals.getInstance();
Styles styles = g.getStyles();
String defaultPreText = SpaceRocks.res.getString("preloadchars");
g.setTrueTypePreloadCharacters("0123456789%");
Attributes attrs = styles.getSelector("progress", "label", "spacerocks");
if (attrs.get("font") == null) {
attrs.set("font", g.loadFontDP("Interface/Fonts/space age.ttf", Style.Italic, 12, g.dpInt(2)));
}
TrueTypeBMP ttf = attrs.get("font");
ttf.reloadTexture();
HBoxLayout hbox = new HBoxLayout(0, FillMode.ForcedEven, false, VAlign.Center, true);
Container container = new Container(hbox);
container.setPadding(new Insets3f(0, g.dpInt(16), 0, g.dpInt(16)));
container.setLocalTranslation(0, app.getHeight(), 0);
container.setPreferredSize(new Vector3f(app.getWidth(), app.getHeight(), 3));
container.setUserData("layer", 2);
pb = new ProgressBar();
float perc = 0;
pb.setProgressPercent(perc);
pb.setMessage("0%");
container.addChild(pb, VAlign.Center, false, true);
app.getStateManager().getState(Fade.class).getLayout().addChild(container);
g.setTrueTypePreloadCharacters(defaultPreText);
ttf = (TrueTypeBMP)new Label("reload").getFont();
fonts.add(ttf);
ttf = (TrueTypeBMP)new Label("Reload", new ElementId("titlelabel")).getFont();
if (!fonts.contains(ttf))
fonts.add(ttf);
ttf = (TrueTypeBMP)new Label("Reload", new ElementId("cliplabel")).getFont();
if (!fonts.contains(ttf))
fonts.add(ttf);
ttf = (TrueTypeBMP)new Label("Reload", new ElementId("letterpicker").child("label")).getFont();
if (!fonts.contains(ttf))
fonts.add(ttf);
ttf = (TrueTypeBMP)new Button("Reload").getFont();
if (!fonts.contains(ttf))
fonts.add(ttf);
}
@Override
public void update(float tpf) {
if (!active)
return;
if (currentFont == fonts.size()) {
app.getStateManager().detach(this);
UI.setEnabled(true);
if (app.getStateManager().getState(GameState.class) == null
|| !app.getUIView().isEnabled())
SpaceRocks.PAUSED.set(false);
UI.fade(true, 0.5f, null);
return;
}
fonts.get(currentFont).reloadTexture();
currentFont++;
float perc = (float)currentFont / fonts.size();
pb.setProgressPercent(perc);
pb.setMessage(Integer.toString((int)Math.floor(perc * 100)) + "%");
}
}
| 36.708955 | 107 | 0.641187 |
5c95c78d2591714472350ad91ca58922f2861868 | 631 | package com.kalessil.phpStorm.phpInspectionsEA.security;
import com.kalessil.phpStorm.phpInspectionsEA.PhpCodeInsightFixtureTestCase;
import com.kalessil.phpStorm.phpInspectionsEA.inspectors.security.CryptographicallySecureAlgorithmsInspector;
final public class CryptographicallySecureAlgorithmsInspectorTest extends PhpCodeInsightFixtureTestCase {
public void testIfFindsAllPatterns() {
myFixture.enableInspections(new CryptographicallySecureAlgorithmsInspector());
myFixture.configureByFile("testData/fixtures/security/weak-algorithms.php");
myFixture.testHighlighting(true, false, true);
}
}
| 45.071429 | 109 | 0.832013 |
f4cb5a52ca6e9bddd935f14d42588b9646b71671 | 12,751 | package org.cbioportal.genome_nexus.component.annotation;
import org.cbioportal.genome_nexus.model.GenomicLocation;
import org.cbioportal.genome_nexus.util.GenomicVariant;
import org.cbioportal.genome_nexus.util.GenomicVariantUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Component
public class NotationConverter {
public static final String DEFAULT_DELIMITER = ",";
public String hgvsNormalizer(String hgvs) {
return hgvs.replace("chr","").replace("23:g.","X:g.").replace("24:g.","Y:g.");
}
public String chromosomeNormalizer(String chromosome) {
return chromosome.trim().replace("chr","").replace("23","X").replace("24","Y");
}
public GenomicLocation hgvsgToGenomicLocation(String hgvsg) {
GenomicLocation gl = new GenomicLocation();
GenomicVariant gv = GenomicVariantUtil.fromHgvs(hgvsg);
gl.setChromosome(gv.getChromosome());
gl.setStart(gv.getStart());
gl.setEnd(gv.getEnd());
gl.setReferenceAllele(gv.getRef());
gl.setVariantAllele(gv.getAlt());
gl.setOriginalInput(hgvsg);
return gl;
}
public List<GenomicLocation> hgvsgToGenomicLocations(List<String> hgvsgs) {
List<GenomicLocation> genomicLocations = new ArrayList();
for (String hgvsg : hgvsgs) {
genomicLocations.add(hgvsgToGenomicLocation(hgvsg));
}
return genomicLocations;
}
@Nullable
public GenomicLocation parseGenomicLocation(String genomicLocation) {
return parseGenomicLocation(genomicLocation, DEFAULT_DELIMITER);
}
@Nullable
public GenomicLocation parseGenomicLocation(String genomicLocation, String delimiter) {
if (genomicLocation == null) {
return null;
}
String[] parts = genomicLocation.split(delimiter);
GenomicLocation location = null;
if (parts.length >= 5) {
// trim all parts
for (int i = 0; i < parts.length; i++) {
parts[i] = parts[i].trim();
}
location = new GenomicLocation();
location.setChromosome(chromosomeNormalizer(parts[0]));
location.setStart(Integer.parseInt(parts[1]));
location.setEnd(Integer.parseInt(parts[2]));
location.setReferenceAllele(parts[3]);
location.setVariantAllele(parts[4]);
location.setOriginalInput(genomicLocation);
}
return location;
}
@Nullable
public String genomicToHgvs(String genomicLocation) {
return genomicToHgvs(parseGenomicLocation(genomicLocation));
}
@Nullable
public String genomicToEnsemblRestRegion(String genomicLocation) {
return genomicToEnsemblRestRegion(parseGenomicLocation(genomicLocation));
}
/*
* Normalize genomic location:
*
* 1. Convert VCF style start,end,ref,alt to MAF by looking for common
* prefix. (TODO: not sure if this is always a good idea)
* 2. Normalize chromsome names.
*/
public GenomicLocation normalizeGenomicLocation(GenomicLocation genomicLocation) {
GenomicLocation normalizedGenomicLocation = new GenomicLocation();
// if original input is set in the incoming genomic location object then use the same value
// for the normalized genomic location object returned, otherwise set it to the
// string representation of the incoming genomic location object
if (genomicLocation.getOriginalInput() != null && !genomicLocation.getOriginalInput().isEmpty()) {
normalizedGenomicLocation.setOriginalInput(genomicLocation.getOriginalInput());
} else {
normalizedGenomicLocation.setOriginalInput(genomicLocation.toString());
}
// normalize chromosome name
String chr = chromosomeNormalizer(genomicLocation.getChromosome().trim());
normalizedGenomicLocation.setChromosome(chr);
// convert vcf style start,end,ref,alt to MAF style
Integer start = genomicLocation.getStart();
Integer end = genomicLocation.getEnd();
String ref = genomicLocation.getReferenceAllele().trim();
String var = genomicLocation.getVariantAllele().trim();
String prefix = "";
if (!ref.equals(var)) {
prefix = longestCommonPrefix(ref, var);
}
// Remove common prefix and adjust variant position accordingly
if (prefix.length() > 0) {
ref = ref.substring(prefix.length());
var = var.substring(prefix.length());
int nStart = start + prefix.length();
if (ref.length() == 0) {
nStart -= 1;
}
start = nStart;
}
normalizedGenomicLocation.setStart(start);
normalizedGenomicLocation.setEnd(end);
normalizedGenomicLocation.setReferenceAllele(ref);
normalizedGenomicLocation.setVariantAllele(var);
return normalizedGenomicLocation;
}
@Nullable
public String genomicToHgvs(GenomicLocation genomicLocation) {
if (genomicLocation == null) {
return null;
}
GenomicLocation normalizedGenomicLocation = normalizeGenomicLocation(genomicLocation);
String chr = normalizedGenomicLocation.getChromosome();
Integer start = normalizedGenomicLocation.getStart();
Integer end = normalizedGenomicLocation.getEnd();
String ref = normalizedGenomicLocation.getReferenceAllele().trim();
String var = normalizedGenomicLocation.getVariantAllele().trim();
String hgvs;
if (start < 1) {
// cannot convert invalid locations
// Ensembl uses a one-based coordinate system
hgvs = null;
} else if (ref.equals("-") || ref.length() == 0 || ref.equals("NA") || ref.contains("--")) {
/*
Process Insertion
Example insertion: 17 36002277 36002278 - A
Example output: 17:g.36002277_36002278insA
*/
try {
hgvs = chr + ":g." + start + "_" + String.valueOf(start + 1) + "ins" + var;
} catch (NumberFormatException e) {
return null;
}
} else if (var.equals("-") || var.length() == 0 || var.equals("NA") || var.contains("--")) {
if (ref.length() == 1) {
/*
Process Deletion (single positon)
Example deletion: 13 32914438 32914438 T -
Example output: 13:g.32914438del
*/
hgvs = chr + ":g." + start + "del";
}
else {
/*
Process Deletion (multiple postion)
Example deletion: 1 206811015 206811016 AC -
Example output: 1:g.206811015_206811016del
*/
hgvs = chr + ":g." + start + "_" + end + "del";
}
} else if (ref.length() > 1 && var.length() >= 1) {
/*
Process ONP (multiple deletion insertion)
Example INDEL : 2 216809708 216809709 CA T
Example output: 2:g.216809708_216809709delinsT
*/
hgvs = chr + ":g." + start + "_" + end + "delins" + var;
} else if (ref.length() == 1 && var.length() > 1) {
/*
Process ONP (single deletion insertion)
Example INDEL : 17 7579363 7579363 A TTT
Example output: 17:g.7579363delinsTTT
*/
hgvs = chr + ":g." + start + "delins" + var;
} else {
/*
Process SNV
Example SNP : 2 216809708 216809708 C T
Example output: 2:g.216809708C>T
*/
hgvs = chr + ":g." + start + ref + ">" + var;
}
return hgvs;
}
@Nullable
public String genomicToEnsemblRestRegion(GenomicLocation genomicLocation) {
if (genomicLocation == null) {
return null;
}
GenomicLocation normalizedGenomicLocation = normalizeGenomicLocation(genomicLocation);
String chr = normalizedGenomicLocation.getChromosome();
Integer start = normalizedGenomicLocation.getStart();
Integer end = normalizedGenomicLocation.getEnd();
String ref = normalizedGenomicLocation.getReferenceAllele().trim();
String var = normalizedGenomicLocation.getVariantAllele().trim();
String region;
// cannot convert invalid locations
// Ensembl uses a one-based coordinate system
if (start < 1) {
region = null;
} else if (ref.equals("-") || ref.length() == 0 || ref.equals("NA") || ref.contains("--")) {
/*
Process Insertion
Example insertion: 17 36002277 36002278 - A
Example output: 17:36002278-36002277:1/A
*/
try {
region = chr + ":" + String.valueOf(start + 1) + "-" + start + ":1/" + var;
}
catch (NumberFormatException e) {
return null;
}
} else if (var.equals("-") || var.length() == 0) {
/*
Process Deletion
Example deletion: 1 206811015 206811016 AC -
Example output: 1:206811015-206811016:1/-
*/
region = chr + ":" + start + "-" + end + ":1/-";
} else if (ref.length() > 1 || var.length() > 1) {
/*
Process ONP
Example SNP : 2 216809708 216809709 CA T
Example output: 2:216809708-216809709:1/T
*/
region = chr + ":" + start + "-" + end + ":1/" + var;
} else {
/*
Process SNV
Example SNP : 2 216809708 216809708 C T
Example output: 2:216809708-216809708:1/T
*/
region = chr + ":" + start + "-" + start + ":1/" + var;
}
return region;
}
@NotNull
public Map<String, GenomicLocation> genomicToHgvsMap(List<GenomicLocation> genomicLocations) {
Map<String, GenomicLocation> variantToGenomicLocation = new LinkedHashMap<>();
// convert genomic location to hgvs notation (there is always 1-1 mapping)
for (GenomicLocation location : genomicLocations) {
String hgvs = genomicToHgvs(location);
if (hgvs != null) {
variantToGenomicLocation.put(hgvs, location);
}
}
return variantToGenomicLocation;
}
public List<String> genomicToHgvs(List<GenomicLocation> genomicLocations) {
List<String> hgvsList = new ArrayList<>();
for (GenomicLocation location : genomicLocations) {
String hgvs = genomicToHgvs(location);
if (hgvs != null) {
hgvsList.add(hgvs);
}
}
return hgvsList;
}
@NotNull
public Map<String, GenomicLocation> genomicToEnsemblRestRegionMap(List<GenomicLocation> genomicLocations) {
Map<String, GenomicLocation> variantToGenomicLocation = new LinkedHashMap<>();
// convert genomic location to ensembl rest region notation (there is always 1-1 mapping)
for (GenomicLocation location : genomicLocations) {
String ensemblRestRegion = genomicToEnsemblRestRegion(location);
if (ensemblRestRegion != null) {
variantToGenomicLocation.put(ensemblRestRegion, location);
}
}
return variantToGenomicLocation;
}
public List<String> genomicToEnsemblRestRegion(List<GenomicLocation> genomicLocations) {
List<String> ensemblRestRegionsList = new ArrayList<>();
for (GenomicLocation location : genomicLocations) {
String ensemblRestRegion = genomicToEnsemblRestRegion(location);
if (ensemblRestRegion != null) {
ensemblRestRegionsList.add(ensemblRestRegion);
}
}
return ensemblRestRegionsList;
}
// TODO factor out to a utility class as a static method if needed
@NotNull
public String longestCommonPrefix(String str1, String str2) {
if (str1 == null || str2 == null) {
return "";
}
for (int prefixLen = 0; prefixLen < str1.length(); prefixLen++) {
char c = str1.charAt(prefixLen);
if (prefixLen >= str2.length() || str2.charAt(prefixLen) != c) {
// mismatch found
return str2.substring(0, prefixLen);
}
}
return str1;
}
}
| 39.233846 | 111 | 0.594463 |
0a8aa7d43c7f745d6811c144f13effc1b5178ff7 | 2,165 | /*
* 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.facebook.presto.execution;
import com.facebook.drift.annotations.ThriftConstructor;
import com.facebook.drift.annotations.ThriftField;
import com.facebook.drift.annotations.ThriftStruct;
import com.facebook.presto.server.thrift.Any;
import com.facebook.presto.spi.ConnectorMetadataUpdateHandle;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
@ThriftStruct
public class TaskWithConnectorType
{
private final int value;
//Connector specific Type
private ConnectorMetadataUpdateHandle connectorMetadataUpdateHandle;
//Connector specific Type serialized as Any
private Any connectorMetadataUpdateHandleAny;
@JsonCreator
public TaskWithConnectorType(
int value,
ConnectorMetadataUpdateHandle connectorMetadataUpdateHandle)
{
this.value = value;
this.connectorMetadataUpdateHandle = connectorMetadataUpdateHandle;
}
@ThriftConstructor
public TaskWithConnectorType(
int value,
Any connectorMetadataUpdateHandleAny)
{
this.value = value;
this.connectorMetadataUpdateHandleAny = connectorMetadataUpdateHandleAny;
}
@ThriftField(1)
@JsonProperty
public int getValue()
{
return value;
}
@ThriftField(2)
public Any getConnectorMetadataUpdateHandleAny()
{
return connectorMetadataUpdateHandleAny;
}
@JsonProperty
public ConnectorMetadataUpdateHandle getConnectorMetadataUpdateHandle()
{
return connectorMetadataUpdateHandle;
}
}
| 30.928571 | 81 | 0.744111 |
d3c48130ede066bf02720bfe99c7329eaf01f863 | 2,463 | /*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies Ltd. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. 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.cloudifysource.shell.installer;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**********
* Bootstrap listener, responsible for echoing messages to CLI.
* @author barakme
*
*/
public class CLILocalhostBootstrapperListener implements LocalhostBootstrapperListener {
private final CLIEventsDisplayer displayer;
private static final String REGEX =
"\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|\\s\\[]*(]*+)";
private final Pattern pattern = Pattern.compile(REGEX);
private final List<String> localcloudInfoEvents = new ArrayList<String>();
public CLILocalhostBootstrapperListener() {
this.displayer = new CLIEventsDisplayer();
}
@Override
public void onLocalhostBootstrapEvent(final String event) {
if (event == null) {
displayer.printNoChange();
} else {
// Check if the event contains a url string.
// if it does we classify it as an info event and print it in the end.
final Matcher matcher = pattern.matcher(event);
if (matcher.find()) {
if (event.contains("Webui")) {
localcloudInfoEvents.add("\t\tCLOUDIFY MANAGEMENT\t" + matcher.group());
} else if (event.contains("Rest")) {
localcloudInfoEvents.add("\t\tCLOUDIFY GATEWAY\t" + matcher.group());
printBootstrapInfo();
}
} else {
displayer.printEvent(event);
}
}
}
private void printBootstrapInfo() {
displayer.printEvent("CLOUDIFY LOCAL-CLOUD STARTED");
displayer.printEvent("");
displayer.printEvent("LOCAL-CLOUD INFO :");
for (final String eventString : localcloudInfoEvents) {
displayer.printEvent(eventString);
}
}
}
| 35.695652 | 118 | 0.670321 |
8315d29cbf064f32613adb0a2399f6b4e0dc1076 | 644 | package work.work1;
/**
* @author: 杜少雄 <github.com/shaoxiongdu>
* @date: 2021年08月26日 | 17:08
* @description:
*/
public class Penguin extends Pet{
public Penguin(int health, String name, int intimacy) {
super(health, name, intimacy);
}
@Override
public void play(String name) {
System.out.println("玩耍前: ");
System.out.println(this);
System.out.println(name + "和"+this.getName()+"和企鹅玩接游泳游戏,狗狗健康值-10,与主人亲密度+5");
super.setHealth(super.getHealth() - 10);
super.setIntimacy(super.getIntimacy() + 5);
System.out.println("玩耍后:");
System.out.println(this);
}
}
| 24.769231 | 84 | 0.61646 |
0b970c53a82af4109a5ae5249a234bf80b7c27b3 | 10,258 | /**
* Copyright (c) 2003-2005, David A. Czarnecki
* All rights reserved.
*
* Portions Copyright (c) 2003-2005 by Mark Lussier
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the "David A. Czarnecki" and "blojsom" nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Products derived from this software may not be called "blojsom",
* nor may "blojsom" appear in their name, without prior written permission of
* David A. Czarnecki.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.blojsom.plugin.export;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.blojsom.blog.BlogEntry;
import org.blojsom.blog.BlogUser;
import org.blojsom.blog.BlojsomConfiguration;
import org.blojsom.fetcher.BlojsomFetcher;
import org.blojsom.fetcher.BlojsomFetcherException;
import org.blojsom.plugin.BlojsomPluginException;
import org.blojsom.plugin.admin.WebAdminPlugin;
import org.blojsom.util.BlojsomUtils;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Export Blog plugin
*
* @author David Czarnecki
* @version $Id: ExportBlogPlugin.java,v 1.1.2.1 2005/07/21 04:30:21 johnan Exp $
* @since blojsom 2.17
*/
public class ExportBlogPlugin extends WebAdminPlugin {
private Log _logger = LogFactory.getLog(ExportBlogPlugin.class);
private BlojsomFetcher _fetcher;
/**
* Default constructor
*/
public ExportBlogPlugin() {
}
/**
* Return the display name for the plugin
*
* @return Display name for the plugin
*/
public String getDisplayName() {
return "Export Blog plugin";
}
/**
* Return the name of the initial editing page for the plugin
*
* @return Name of the initial editing page for the plugin
*/
public String getInitialPage() {
return "";
}
/**
* Initialize this plugin. This method only called when the plugin is instantiated.
*
* @param servletConfig Servlet config object for the plugin to retrieve any initialization parameters
* @param blojsomConfiguration {@link org.blojsom.blog.BlojsomConfiguration} information
* @throws org.blojsom.plugin.BlojsomPluginException
* If there is an error initializing the plugin
*/
public void init(ServletConfig servletConfig, BlojsomConfiguration blojsomConfiguration) throws BlojsomPluginException {
super.init(servletConfig, blojsomConfiguration);
String fetcherClassName = blojsomConfiguration.getFetcherClass();
try {
Class fetcherClass = Class.forName(fetcherClassName);
_fetcher = (BlojsomFetcher) fetcherClass.newInstance();
_fetcher.init(servletConfig, blojsomConfiguration);
_logger.info("Added blojsom fetcher: " + fetcherClassName);
} catch (ClassNotFoundException e) {
_logger.error(e);
throw new BlojsomPluginException(e);
} catch (InstantiationException e) {
_logger.error(e);
throw new BlojsomPluginException(e);
} catch (IllegalAccessException e) {
_logger.error(e);
throw new BlojsomPluginException(e);
} catch (BlojsomFetcherException e) {
_logger.error(e);
throw new BlojsomPluginException(e);
}
_logger.debug("Initialized export entries plugin");
}
/**
* Process the blog entries
*
* @param httpServletRequest Request
* @param httpServletResponse Response
* @param user {@link org.blojsom.blog.BlogUser} instance
* @param context Context
* @param entries Blog entries retrieved for the particular request
* @return Modified set of blog entries
* @throws org.blojsom.plugin.BlojsomPluginException
* If there is an error processing the blog entries
*/
public BlogEntry[] process(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlogUser user, Map context, BlogEntry[] entries) throws BlojsomPluginException {
entries = super.process(httpServletRequest, httpServletResponse, user, context, entries);
String page = BlojsomUtils.getRequestValue(PAGE_PARAM, httpServletRequest);
if (ADMIN_LOGIN_PAGE.equals(page)) {
return entries;
} else {
Map fetchParameters = new HashMap();
fetchParameters.put(BlojsomFetcher.FETCHER_FLAVOR, user.getBlog().getBlogDefaultFlavor());
fetchParameters.put(BlojsomFetcher.FETCHER_NUM_POSTS_INTEGER, new Integer(-1));
try {
BlogEntry[] allEntries = _fetcher.fetchEntries(fetchParameters, user);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String exportDate = simpleDateFormat.format(new Date());
httpServletResponse.setContentType("application/zip");
httpServletResponse.setHeader("Content-Disposition", "filename=blojsom-export-" + exportDate + ".zip");
ZipOutputStream zipOutputStream = new ZipOutputStream(httpServletResponse.getOutputStream());
zipOutputStream.putNextEntry(new ZipEntry("entries.xml"));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(zipOutputStream, UTF8);
XStream xStream = new XStream();
xStream.toXML(allEntries, outputStreamWriter);
zipOutputStream.closeEntry();
int length;
// Zip the resources
File resourcesDirectory = new File(_blojsomConfiguration.getQualifiedResourceDirectory() + "/" + user.getId() + "/");
String resourcesDirName = _blojsomConfiguration.getResourceDirectory();
File[] resourceFiles = resourcesDirectory.listFiles();
if (resourceFiles != null && resourceFiles.length > 0) {
for (int i = 0; i < resourceFiles.length; i++) {
File resourceFile = resourceFiles[i];
if (!resourceFile.isDirectory()) {
byte[] buffer = new byte[1024];
zipOutputStream.putNextEntry(new ZipEntry(resourcesDirName + user.getId() + "/" + resourceFile.getName()));
FileInputStream in = new FileInputStream(resourceFile.getAbsolutePath());
while ((length = in.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
}
}
}
// Zip the templates
File templatesDirectory = new File(_blojsomConfiguration.getInstallationDirectory() +
_blojsomConfiguration.getBaseConfigurationDirectory() + user.getId() +
_blojsomConfiguration.getTemplatesDirectory());
String templateDirName = _blojsomConfiguration.getTemplatesDirectory();
File[] templateFiles = templatesDirectory.listFiles();
if (templateFiles != null && templateFiles.length > 0) {
for (int i = 0; i < templateFiles.length; i++) {
File templateFile = templateFiles[i];
if (!templateFile.isDirectory()) {
byte[] buffer = new byte[1024];
zipOutputStream.putNextEntry(new ZipEntry(templateDirName + user.getId() + "/" + templateFile.getName()));
FileInputStream in = new FileInputStream(templateFile.getAbsolutePath());
while ((length = in.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
}
}
}
zipOutputStream.close();
} catch (BlojsomFetcherException e) {
_logger.error(e);
addOperationResultMessage(context, "Unable to retrieve entries for user: " + user.getId());
} catch (IOException e) {
_logger.error(e);
addOperationResultMessage(context, "Unable to create XML archive of entries for user: " + user.getId());
}
}
return entries;
}
} | 44.6 | 191 | 0.64691 |
ce6dc92992c7b088f84ff12ba9a20bb231285835 | 4,698 | package cn.glogs.activeauth.iamcore.service.impl;
import cn.glogs.activeauth.iamcore.domain.AuthenticationPrincipal;
import cn.glogs.activeauth.iamcore.domain.AuthorizationPolicy;
import cn.glogs.activeauth.iamcore.domain.AuthorizationPolicyGrant;
import cn.glogs.activeauth.iamcore.domain.AuthorizationPolicyGrantRow;
import cn.glogs.activeauth.iamcore.repository.AuthorizationPolicyGrantRepository;
import cn.glogs.activeauth.iamcore.repository.AuthorizationPolicyGrantRowRepository;
import cn.glogs.activeauth.iamcore.service.AuthorizationPolicyGrantService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.webjars.NotFoundException;
import javax.persistence.criteria.*;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class AuthorizationPolicyGrantServiceImpl implements AuthorizationPolicyGrantService {
private final AuthorizationPolicyGrantRepository authorizationPolicyGrantRepository;
private final AuthorizationPolicyGrantRowRepository authorizationPolicyGrantRowRepository;
public AuthorizationPolicyGrantServiceImpl(AuthorizationPolicyGrantRepository authorizationPolicyGrantRepository, AuthorizationPolicyGrantRowRepository authorizationPolicyGrantRowRepository) {
this.authorizationPolicyGrantRepository = authorizationPolicyGrantRepository;
this.authorizationPolicyGrantRowRepository = authorizationPolicyGrantRowRepository;
}
@Override
@Transactional
public List<AuthorizationPolicyGrant> addGrants(AuthenticationPrincipal granter, AuthenticationPrincipal grantee, List<AuthorizationPolicy> policies) {
List<AuthorizationPolicyGrant> savedGrants = new ArrayList<>();
policies.forEach(policy -> {
AuthorizationPolicyGrant toBeSavedGrant = new AuthorizationPolicyGrant();
toBeSavedGrant.setGranter(granter);
toBeSavedGrant.setGrantee(grantee);
toBeSavedGrant.setPolicy(policy);
toBeSavedGrant.setRevoked(false);
toBeSavedGrant.setCreatedAt(new Date());
AuthorizationPolicyGrant savedGrant = authorizationPolicyGrantRepository.save(toBeSavedGrant);
savedGrants.add(savedGrant);
List<AuthorizationPolicyGrantRow> toBeSavedGrantRows = cartesianProduct(granter, grantee, policy, policy.getActions(), policy.getResources());
authorizationPolicyGrantRowRepository.saveAll(toBeSavedGrantRows);
});
return savedGrants;
}
@Override
@Transactional
public AuthorizationPolicyGrant getGrantById(Long id) {
return authorizationPolicyGrantRepository.findById(id).orElseThrow(() -> new NotFoundException("Grant not found."));
}
@Override
@Transactional
public Page<AuthorizationPolicyGrant> pagingGrantsFrom(AuthenticationPrincipal granter, int page, int size) {
return authorizationPolicyGrantRepository.findAll((Specification<AuthorizationPolicyGrant>) (root, query, criteriaBuilder) -> {
Path<AuthenticationPrincipal> granterRoot = root.get("granter");
return criteriaBuilder.equal(granterRoot, granter);
}, PageRequest.of(page, size));
}
@Override
@Transactional
public Page<AuthorizationPolicyGrant> pagingGrantsTo(AuthenticationPrincipal grantee, int page, int size) {
return authorizationPolicyGrantRepository.findAll((Specification<AuthorizationPolicyGrant>) (root, query, criteriaBuilder) -> {
Path<AuthenticationPrincipal> granteeRoot = root.get("grantee");
return criteriaBuilder.equal(granteeRoot, grantee);
}, PageRequest.of(page, size));
}
@Override
@Transactional
public void deleteGrant(Long grantId) {
authorizationPolicyGrantRepository.findById(grantId);
List<AuthorizationPolicyGrantRow> grantRows = authorizationPolicyGrantRowRepository.findAllByGranterId(grantId);
authorizationPolicyGrantRowRepository.deleteInBatch(grantRows);
}
private List<AuthorizationPolicyGrantRow> cartesianProduct(
AuthenticationPrincipal granter, AuthenticationPrincipal grantee,
AuthorizationPolicy policy,
List<String> actions,
List<String> resources
) {
return actions.stream().flatMap(action -> resources.stream().map(resource -> new AuthorizationPolicyGrantRow(null, granter, grantee, policy, policy.getEffect(), action, resource, false))).collect(Collectors.toUnmodifiableList());
}
}
| 50.516129 | 237 | 0.775436 |
4a7358585381b67f5475fe532be2cc286a237412 | 815 | package org.colinw.oceanblast;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class OceanBlastActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
view = new OceanBlastView(this);
setContentView(view);
}
@Override
protected void onPause() {
super.onPause();
view.onPause();
}
@Override
protected void onResume() {
super.onResume();
view.onResume();
}
private OceanBlastView view;
}
| 20.897436 | 68 | 0.736196 |
18bc520a8169f2303e245a57157a8866b050e2d0 | 72 | package rosa.scanvas.model.client;
// TODO
public interface Range {
}
| 10.285714 | 34 | 0.736111 |
948259b160ba6fc67e19b0e0af4bcf0e970e9f3c | 5,519 | package com.ctapweb.feature.featureAE;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceAccessException;
import org.apache.uima.resource.ResourceInitializationException;
import com.ctapweb.feature.logging.LogMarker;
import com.ctapweb.feature.logging.message.AEType;
import com.ctapweb.feature.logging.message.DestroyAECompleteMessage;
import com.ctapweb.feature.logging.message.DestroyingAEMessage;
import com.ctapweb.feature.logging.message.InitializeAECompleteMessage;
import com.ctapweb.feature.logging.message.InitializingAEMessage;
import com.ctapweb.feature.logging.message.PopulatedFeatureValueMessage;
import com.ctapweb.feature.logging.message.ProcessingDocumentMessage;
import com.ctapweb.feature.type.LexicalSophistication_Bands;
import com.ctapweb.feature.type.NSurfaceForm;
import com.ctapweb.feature.type.SurfaceForm;
import com.ctapweb.feature.util.LookUpListResource;
/**
* Counts the number of words in a particular frequency band
*
* @author edemattos
*/
public class LexicalSophistication_Bands_AE extends JCasAnnotator_ImplBase {
//the analysis engine's id from the database
//this value needs to be set when initiating the analysis engine
public static final String PARAM_AEID = "aeID";
public static final String RESOURCE_KEY = "lookUpList";
public static final String PARAM_LANGUAGE_CODE = "LanguageCode";
private int aeID;
private LookUpListResource freqList;
private static final Logger logger = LogManager.getLogger();
private static final AEType aeType = AEType.FEATURE_EXTRACTOR;
private static final String aeName = "Frequency Band Feature Extractor";
@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
logger.trace(LogMarker.UIMA_MARKER, new InitializingAEMessage(aeType, aeName));
super.initialize(aContext);
//get the parameter value of analysis id
if (aContext.getConfigParameterValue(PARAM_AEID) == null) {
ResourceInitializationException e = new ResourceInitializationException("mandatory_value_missing",
new Object[]{PARAM_AEID});
logger.throwing(e);
throw e;
} else {
aeID = (Integer) aContext.getConfigParameterValue(PARAM_AEID);
}
// obtain mandatory language parameter and access language dependent resources
String lCode = "";
if (aContext.getConfigParameterValue(PARAM_LANGUAGE_CODE) == null) {
ResourceInitializationException e = new ResourceInitializationException("mandatory_value_missing",
new Object[]{PARAM_LANGUAGE_CODE});
logger.throwing(e);
throw e;
} else {
lCode = ((String) aContext.getConfigParameterValue(PARAM_LANGUAGE_CODE)).toUpperCase();
}
String languageSpecificResourceKey = RESOURCE_KEY + lCode;
try {
freqList = (LookUpListResource) aContext.getResourceObject(languageSpecificResourceKey);
} catch (ResourceAccessException e) {
logger.throwing(e);
throw new ResourceInitializationException(e);
}
logger.trace(LogMarker.UIMA_MARKER, new InitializeAECompleteMessage(aeType, aeName));
}
/* (non-Javadoc)
* @see org.apache.uima.analysis_component.JCasAnnotator_ImplBase#process(org.apache.uima.jcas.JCas)
*/
@Override
public void process(JCas aJCas) throws AnalysisEngineProcessException {
logger.trace(LogMarker.UIMA_MARKER, new ProcessingDocumentMessage(aeType, aeName, aJCas.getDocumentText()));
double occurrence = 0.0;
Iterator tokenIter = aJCas.getAnnotationIndex(SurfaceForm.type).iterator(false);
List<String> sentTokens = new ArrayList<>();
while (tokenIter.hasNext()) {
sentTokens.add(((SurfaceForm) tokenIter.next()).getSurfaceForm().trim().toLowerCase());
}
HashSet<String> freqWords = new HashSet<>(freqList.getKeys());
for (String token : sentTokens) {
if (freqWords.contains(token)) {
occurrence++;
}
}
occurrence = getNTokens(aJCas) != 0 ? occurrence / getNTokens(aJCas) : 0;
LexicalSophistication_Bands annotation = new LexicalSophistication_Bands(aJCas);
annotation.setId(aeID);
annotation.setValue(occurrence);
annotation.addToIndexes();
logger.info(new PopulatedFeatureValueMessage(aeID, occurrence));
}
/**
* Helper method to get the document's number of tokens from the CAS
*/
private int getNTokens(JCas aJCas) {
Iterator posIter = aJCas.getAllIndexedFS(NSurfaceForm.class);
if (posIter.hasNext()) {
NSurfaceForm nToken = (NSurfaceForm) posIter.next();
return (int) nToken.getValue();
}
return 0;
}
@Override
public void destroy() {
logger.trace(LogMarker.UIMA_MARKER, new DestroyingAEMessage(aeType, aeName));
super.destroy();
logger.trace(LogMarker.UIMA_MARKER, new DestroyAECompleteMessage(aeType, aeName));
}
}
| 39.992754 | 116 | 0.714441 |
98fb559315fd7d4860f4d75dbefed90f3b31b5bf | 1,320 | package org.wanglilong.ccm.po;
import java.util.Date;
import org.springframework.security.core.context.SecurityContextHolder;
import org.wanglilong.ccm.security.SessionUser;
public class BasePO {
private Integer isDeleted;
private Date createTime;
private Date updateTime;
private Date deleteTime;
private String creator;
public BasePO(){
try{
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof SessionUser) {
SessionUser user = (SessionUser) principal;
this.setCreator(user.getId());
}
}catch(Exception e){
e.printStackTrace();
}
}
public Integer getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Integer isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Date getDeleteTime() {
return deleteTime;
}
public void setDeleteTime(Date deleteTime) {
this.deleteTime = deleteTime;
}
}
| 18.333333 | 92 | 0.733333 |
7e9585ea488b3a21b86a4a5727cbdd47a359d672 | 489 | // java program for palindrome
// taken from https://stackoverflow.com/questions/4138827/check-string-for-palindrome?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
// authors (stackoverflow usernames): Michael Myers, dcp
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
} | 30.5625 | 158 | 0.642127 |
0145faf28ef2946bc1ca43680ef77a3274bd3fa9 | 3,403 | /*
* Licensed to DuraSpace under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* DuraSpace licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fcrepo.storage.ocfl.exception;
import java.util.Collection;
import java.util.Objects;
/**
* Indicates that an OCFL object is not a valid Fedora 6 object.
*
* @author pwinckles
*/
public class ValidationException extends RuntimeException {
private final String resourceId;
private final String ocflObjectId;
private final Collection<String> problems;
private String message;
/**
* @param problems the validation problems
* @return validation exception
*/
public static ValidationException create(final Collection<String> problems) {
return new ValidationException(null, null, problems);
}
/**
* @param resourceId the Fedora resource id that is invalid
* @param problems the validation problems
* @return validation exception
*/
public static ValidationException createForResource(final String resourceId, final Collection<String> problems) {
return new ValidationException(null, resourceId, problems);
}
/**
* @param ocflObjectId the ocfl object id that is invalid
* @param problems the validation problems
* @return validation exception
*/
public static ValidationException createForObject(final String ocflObjectId, final Collection<String> problems) {
return new ValidationException(ocflObjectId, null, problems);
}
private ValidationException(final String ocflObjectId,
final String resourceId,
final Collection<String> problems) {
this.ocflObjectId = ocflObjectId;
this.resourceId = resourceId;
this.problems = Objects.requireNonNull(problems, "problems cannot be null");
}
@Override
public String getMessage() {
if (message == null) {
final var builder = new StringBuilder();
if (ocflObjectId != null) {
builder.append("OCFL object ").append(ocflObjectId).append(" is not a valid Fedora 6 object. ");
}
if (resourceId != null) {
builder.append("Resource ").append(resourceId).append(" is not a valid Fedora 6 resource. ");
}
builder.append("The following problems were identified:");
var index = 1;
for (var problem : problems) {
builder.append("\n ").append(index++).append(". ");
builder.append(problem);
}
message = builder.toString();
}
return message;
}
public Collection<String> getProblems() {
return problems;
}
}
| 32.721154 | 117 | 0.660594 |
9c49f0bae0f0a1fb456a69bc6126071270234a23 | 1,801 | /*
* Copyright 2004-2006, Thorbjørn Lindeijer <thorbjorn@lindeijer.nl>
* Copyright 2004-2006, Adam Turk <aturk@biggeruniverse.com>
*
* This file is part of libtiled-java.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package tiled.io.xml;
/**
* an XMLWriterException is thrown if an error occurs while writing the xml-structure of a .tmx file.
*/
public class XMLWriterException extends RuntimeException
{
private static final long serialVersionUID = 1629373837269498797L;
public XMLWriterException(String error) {
super(error);
}
}
| 41.883721 | 101 | 0.754026 |
e54487d54f95134a858c947b7938984d876a1bee | 10,023 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.flink.connectors.sls.datastream.source;
import com.alibaba.flink.connectors.common.exception.ErrorUtils;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.Consts;
import com.aliyun.openservices.log.common.ConsumerGroup;
import com.aliyun.openservices.log.common.Shard;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.response.BatchGetLogResponse;
import org.apache.flink.configuration.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
class SlsClientProxy {
private static final Logger LOG = LoggerFactory.getLogger(SlsClientProxy.class);
private static final String ERROR_SHARD_NOT_EXIST = "ShardNotExist";
private static final String ERROR_CONSUMER_GROUP_EXIST = "ConsumerGroupAlreadyExist";
private static final int MAX_RETRIES_FOR_NON_SERVER_ERROR = 3;
private static final long MAX_RETRY_TIMEOUT_MILLIS = 10 * 60 * 1000;
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String project;
private String logstore;
private String consumerGroup;
private Configuration properties;
private boolean directMode;
private transient SlsClientProvider clientProvider = null;
public SlsClientProxy(String endpoint,
String accessKeyId,
String accessKeySecret,
String project,
String logstore,
String consumerGroup,
Configuration properties) {
this.endpoint = endpoint;
this.accessKeyId = accessKeyId;
this.accessKeySecret = accessKeySecret;
this.project = project;
this.logstore = logstore;
this.consumerGroup = consumerGroup;
this.properties = properties;
this.directMode = false;
}
private SlsClientProvider getSlsClientProvider() {
if (null == clientProvider) {
if (null != accessKeyId && null != accessKeySecret && !accessKeyId.isEmpty() &&
!accessKeySecret.isEmpty()) {
clientProvider = new SlsClientProvider(
endpoint,
accessKeyId,
accessKeySecret,
consumerGroup,
directMode);
} else {
clientProvider = new SlsClientProvider(
endpoint,
properties,
consumerGroup,
directMode);
}
}
return clientProvider;
}
public static class RequestContext {
private final long beginTime;
private int attempt;
public RequestContext() {
this.beginTime = System.currentTimeMillis();
this.attempt = 0;
}
public boolean waitForNextRetry(LogException ex) {
if (!shouldRetry(ex)) {
return false;
}
LOG.warn("Retrying for recoverable exception code = {}, message = {}, attempt={}",
ex.GetErrorCode(), ex.GetErrorMessage(), attempt);
++attempt;
try {
Thread.sleep(attempt * 1000);
} catch (InterruptedException iex) {
LOG.warn("Sleep interrupted", iex);
}
return true;
}
private boolean shouldRetry(LogException ex) {
int status = ex.GetHttpCode();
boolean isNetworkError = status == -1;
boolean isServerError = status >= 500;
boolean canRetry = isNetworkError
|| isServerError
|| (status != 400 && attempt < MAX_RETRIES_FOR_NON_SERVER_ERROR);
return canRetry && System.currentTimeMillis() - beginTime <= MAX_RETRY_TIMEOUT_MILLIS;
}
}
List<Shard> listShards() throws LogException {
Client client = getSlsClientProvider().getClient();
RequestContext ctx = new RequestContext();
while (true) {
try {
return client.ListShard(project, logstore).GetShards();
} catch (LogException ex) {
if (ctx.waitForNextRetry(ex)) {
continue;
}
LOG.error("Error while listing shards, code = {}", ex.GetErrorCode(), ex);
// We cannot start from empty shard list.
throw ex;
}
}
}
String getCursor(Consts.CursorMode cursorMode, int shard) throws LogException {
Client client = getSlsClientProvider().getClient();
RequestContext ctx = new RequestContext();
while (true) {
try {
return client.GetCursor(project, logstore, shard, cursorMode).GetCursor();
} catch (LogException ex) {
if (ctx.waitForNextRetry(ex)) {
continue;
}
LOG.error("Error while fetching cursor, code = {}", ex.GetErrorCode(), ex);
// We cannot start from null cursor.
throw ex;
}
}
}
String getCursor(int ts, int shard) throws LogException {
Client client = getSlsClientProvider().getClient();
RequestContext ctx = new RequestContext();
while (true) {
try {
return client.GetCursor(project, logstore, shard, ts).GetCursor();
} catch (LogException ex) {
if (ctx.waitForNextRetry(ex)) {
continue;
}
LOG.error("Error while fetching cursor, code = {}", ex.GetErrorCode(), ex);
// We cannot start from null cursor.
throw ex;
}
}
}
int getCursorTime(int shard, String cursor) {
Client client = getSlsClientProvider().getClient();
RequestContext ctx = new RequestContext();
while (true) {
try {
return client.GetCursorTime(project, logstore, shard, cursor).GetCursorTime();
} catch (LogException ex) {
if (ctx.waitForNextRetry(ex)) {
continue;
}
LOG.error("Error while fetching cursor time", ex);
return -1;
}
}
}
void updateCheckpoint(int shard, String cursor) {
Client client = getSlsClientProvider().getClient();
RequestContext ctx = new RequestContext();
while (true) {
try {
client.UpdateCheckPoint(project, logstore, consumerGroup, shard, cursor);
break;
} catch (LogException ex) {
if (ctx.waitForNextRetry(ex)) {
continue;
} else if (ERROR_SHARD_NOT_EXIST.equalsIgnoreCase(ex.GetErrorCode())) {
LOG.warn("Shard not exist, skip checkpointting, message = {}", ex.GetErrorMessage());
return;
}
LOG.error("Error while updating checkpoint", ex);
break;
}
}
}
BatchGetLogResponse pullData(int shard, int batchSize, String fromCursor, String endCursor) throws LogException {
Client client = getSlsClientProvider().getClient();
RequestContext ctx = new RequestContext();
while (true) {
try {
return client.BatchGetLog(project, logstore, shard, batchSize, fromCursor, endCursor);
} catch (LogException ex) {
if (ctx.waitForNextRetry(ex)) {
continue;
}
LOG.error("Error while pulling data from SLS", ex);
throw ex;
}
}
}
void refresh() {
getSlsClientProvider().getClient(true, true);
}
void ensureConsumerGroupCreated() {
if (consumerGroup == null || consumerGroup.isEmpty()) {
return;
}
Client client = getSlsClientProvider().getClient();
RequestContext ctx = new RequestContext();
while (true) {
try {
ConsumerGroup group = new ConsumerGroup(consumerGroup, 60, false);
client.CreateConsumerGroup(project, logstore, group);
} catch (LogException ex) {
if (ERROR_CONSUMER_GROUP_EXIST.equalsIgnoreCase(ex.GetErrorCode())) {
LOG.info("Consumer group {} exist, no need to create it", consumerGroup);
return;
}
// Retry for 500 error only here as failover is OK as we're not starting
if (ctx.waitForNextRetry(ex)) {
continue;
}
ErrorUtils.throwException(
"error occur when create consumer group, errorCode: " + ex.GetErrorCode() +
", errorMessage: " + ex.GetErrorMessage());
}
}
}
public void setDirectMode(boolean directMode) {
this.directMode = directMode;
}
}
| 37.965909 | 117 | 0.572683 |
5d2de3afd26804471a2424214bcae2c11c80fae7 | 68,709 | package net.cnri.cordra.storage.hds;
import com.sleepycat.je.*;
import net.cnri.cordra.api.ConflictCordraException;
import net.cnri.cordra.api.CordraException;
import net.cnri.cordra.api.InternalErrorCordraException;
import net.cnri.cordra.api.NotFoundCordraException;
import net.cnri.cordra.storage.LimitedInputStream;
import net.handle.hdllib.Encoder;
import net.handle.hdllib.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.channels.Channels;
import java.security.MessageDigest;
import java.util.*;
/**
* HashDirectoryStorage stores digital objects and associated data elements
* using the file system. In order to support ridiculously large numbers of
* digital objects on systems that have limited directory sizes, the digital
* object IDs are hashed into a hexadecimal form, of which every 4 digits
* represents a part of the path to the directory containing the digital
* object's data elements.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class HashDirectoryStorage {
public static final String DATE_CREATED_ATTRIBUTE = "internal.created";
public static final String DATE_MODIFIED_ATTRIBUTE = "internal.modified";
public static final String SIZE_ATTRIBUTE = "internal.size";
private static final String INTERNAL_ELEMENT_FILE = "internal.elementFile";
private static final int DEFAULT_MAX_DB_ELEMENT_SIZE = 1048576;
static final Logger logger = LoggerFactory.getLogger(HashDirectoryStorage.class);
private static final Object EMPTY_LOCK_VAL = new Object();
// The separator between directory/file names
private static final char FILE_SEPARATOR = File.separatorChar;
// The algorithm used to compute paths to DOs.
// We are using MD5 instead of SHA1 because it is faster.
private String HASH_ALG = "MD5";
// the forced length of the hexadecimal-encoded hash string
private int HASH_LENGTH = 15;
// the length of each segment of the hash string.
// a segment_size of 4 will put (at most) 65,536 entries in a directory
// a segment_size of 3 will put (at most) 4,096 entries in a directory
private int SEGMENT_SIZE = 3;
private File baseDirectory;
private String baseDirectoryPath;
private MessageDigest hash;
private Properties props;
private int maxDbElementSize = DEFAULT_MAX_DB_ELEMENT_SIZE;
// lock tables to keep track of currently-being-written and
// currently-being-read data
private Hashtable locks = new Hashtable();
// the Berkeley DB database environment
private Environment environment = null;
// the Berkeley DB index database
private Database indexDB;
// the database for elements
private Database elementDb;
private boolean readOnly;
public HashDirectoryStorage() {
}
/**
* Initializes the storage for use with server based in the given storage
* directory.
*/
@SuppressWarnings("hiding")
public void initWithDirectory(File baseDirectory) throws CordraException {
initWithDirectory(baseDirectory, false);
}
@SuppressWarnings("hiding")
public void initWithDirectory(File baseDirectory, boolean readOnly) throws CordraException {
this.baseDirectory = baseDirectory;
this.readOnly = readOnly;
this.props = new Properties();
try {
if (!baseDirectory.exists()) {
if (readOnly) {
throw new InternalErrorCordraException("DO Storage directory (" + baseDirectory + ") does not exist");
}
baseDirectory.mkdirs();
} else {
try {
File propsFile = new File(baseDirectory, "storage_properties");
if (propsFile.exists()) {
InputStream in = new FileInputStream(propsFile);
try {
props.load(in);
} finally {
in.close();
}
}
} catch (Exception e) {
logger.error("Error loading storage properties", e);
throw new InternalErrorCordraException("Error reading storage properties", e);
}
}
if (!readOnly && !baseDirectory.canWrite()) {
throw new InternalErrorCordraException("DO Storage directory (" + baseDirectory + ") is not writable");
}
baseDirectoryPath = baseDirectory.getCanonicalPath();
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
throw new InternalErrorCordraException("Unable to access storage directory: " + e);
}
try {
hash = MessageDigest.getInstance(HASH_ALG);
} catch (Exception e) {
throw new InternalErrorCordraException("Unable to initialize hash");
}
HASH_ALG = props.getProperty("hash_alg", HASH_ALG);
try {
HASH_LENGTH = Integer.parseInt(props.getProperty("hash_len", String.valueOf(HASH_LENGTH)));
} catch (Exception e) {
logger.error("Invalid hash length: " + props.getProperty("hash_len", String.valueOf(HASH_LENGTH)), e);
throw new InternalErrorCordraException("Invalid hash length in storage properties: "
+ props.getProperty("hash_len", String.valueOf(HASH_LENGTH)), e);
}
try {
SEGMENT_SIZE = Integer.parseInt(props.getProperty("segment_size", String.valueOf(SEGMENT_SIZE)));
if (SEGMENT_SIZE <= 0 || SEGMENT_SIZE > HASH_LENGTH)
throw new Exception("Invalid segment size: " + SEGMENT_SIZE);
} catch (Exception e) {
logger.error("Invalid segment size: " + props.getProperty("segment_size", String.valueOf(SEGMENT_SIZE)), e);
throw new InternalErrorCordraException("Invalid segment size in storage properties: "
+ props.getProperty("segment_size", String.valueOf(SEGMENT_SIZE)), e);
}
try {
maxDbElementSize = Integer
.parseInt(props.getProperty("max_db_element_size", String.valueOf(DEFAULT_MAX_DB_ELEMENT_SIZE)));
} catch (Exception e) {
logger.error("Invalid max_db_element_size: "
+ props.getProperty("max_db_element_size", String.valueOf(DEFAULT_MAX_DB_ELEMENT_SIZE)), e);
throw new InternalErrorCordraException("Invalid segment size in storage properties: "
+ props.getProperty("max_db_element_size", String.valueOf(DEFAULT_MAX_DB_ELEMENT_SIZE)), e);
}
// create the database environment
try {
File indexDir = new File(baseDirectory, "index");
if (!readOnly && !indexDir.exists())
indexDir.mkdirs();
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(!readOnly);
envConfig.setSharedCache(true);
envConfig.setReadOnly(readOnly);
envConfig.setConfigParam(EnvironmentConfig.FREE_DISK, "0");
environment = JeUpgradeTool.openEnvironment(indexDir, envConfig);
com.sleepycat.je.Transaction openTxn = environment.beginTransaction(null, null);
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setTransactional(true);
dbConfig.setAllowCreate(!readOnly);
dbConfig.setSortedDuplicates(false);
dbConfig.setReadOnly(readOnly);
indexDB = environment.openDatabase(openTxn, "objindex", dbConfig);
elementDb = environment.openDatabase(openTxn, "elementDb", dbConfig);
// if(logger.isDebugEnabled()) {
// logger.debug("DB Stats: "+indexDB.getStats(null));
// logger.debug("ElementDb Stats: "+elementDb.getStats(null));
// logger.debug("DB Dir: "+indexDir.getAbsolutePath());
// }
openTxn.commitSync();
} catch (Exception e) {
logger.error("Error loading storage index", e);
throw new InternalErrorCordraException("Error loading storage index", e);
}
}
public void close() {
if (indexDB != null)
try {
indexDB.close();
} catch (Exception e) {
logger.error("Exception closing", e);
}
if (elementDb != null)
try {
elementDb.close();
} catch (Exception e) {
logger.error("Exception closing", e);
}
if (environment != null)
try {
environment.close();
} catch (Exception e) {
logger.error("Exception closing", e);
}
}
/**
* Creates a new digital object with the given ID, if one does not already
* exist. Returns the object identifier.
*/
public String createObject(String id) throws CordraException {
try {
if (id == null) {
throw new UnsupportedOperationException("Id must not be null.");
}
synchronized (id.toLowerCase().intern()) {
DOMetadata metadata = getObjectInfo(id, null);
// make sure that the digital object doesn't already exist
if (metadata.objectExists()) {
throw new ConflictCordraException("Object already exists: " + id);
}
long creationTime = System.currentTimeMillis();
// record the metadata, indicating that the digital object now exists
long recordedCreationTime = Math.max(metadata.getDateCreated(), creationTime);
metadata.setDateCreated(recordedCreationTime);
metadata.updateModification(recordedCreationTime);
setObjectInfo(metadata);
return id;
}
} catch (Exception e) {
if (e instanceof CordraException) {
throw (CordraException) e;
} else {
logger.error("HashDirectoryStorage.createObject", e);
throw new InternalErrorCordraException("HashDirectoryStorage.createObject", e);
}
}
}
/**
* Deletes the given object.
*/
public void deleteObject(String objectID) throws CordraException {
long dateCreated;
long deletionTime;
boolean filesToDelete = false;
try {
synchronized (objectID.toLowerCase().intern()) {
DOMetadata metadata = getObjectInfo(objectID, null);
long dateDeleted = metadata.getDateDeleted();
dateCreated = metadata.getDateCreated();
if (dateCreated > 0 && dateDeleted > 0 && dateDeleted > dateCreated) {
throw new NotFoundCordraException("Object " + objectID + " has already been deleted");
}
deletionTime = System.currentTimeMillis();
if (deletionTime <= dateCreated) {
deletionTime = dateCreated + 1;
}
String timestampPrefix = getAttTSKey(null, "");
String valuePrefix = getAttValKey(null, "");
HashMap tagsToSet = new HashMap();
ArrayList tagsToDelete = new ArrayList();
// remove any attributes
for (Iterator it = metadata.getTagNames(); it.hasNext();) {
String tagName = (String) it.next();
// delete all elements
if (tagName.startsWith("de-exists."))
tagsToDelete.add(tagName);
if (tagName.startsWith("de-size."))
tagsToDelete.add(tagName);
if (tagName.startsWith("de-file.")) {
tagsToDelete.add(tagName);
filesToDelete = true;
}
if (tagName.startsWith(timestampPrefix)) {
String timestampVal = metadata.getTag(tagName, null);
if (timestampVal == null)
continue; // can't happen
try {
String valueKey = valuePrefix + tagName.substring(timestampPrefix.length());
tagsToDelete.add(valueKey);
tagsToSet.put(tagName, String.valueOf(deletionTime));
} catch (Exception e) {
// *very* unlikely to happen
logger.error("Error checking attribute timestamp", e);
}
}
}
for (Iterator iter = tagsToDelete.iterator(); iter.hasNext();) {
metadata.setTag((String) iter.next(), null);
}
for (Iterator iter = tagsToSet.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
metadata.setTag(key, (String) tagsToSet.get(key));
}
metadata.setDateDeleted(deletionTime);
metadata.updateModification(deletionTime);
setObjectInfo(metadata);
}
} catch (Exception e) {
if (e instanceof CordraException) {
logger.error("error recording object deletion", e);
throw (CordraException) e;
} else {
throw new InternalErrorCordraException("error recording object deletion", e);
}
}
deleteDbElementsForObject(objectID);
if (filesToDelete) {
// clean up the object storage...
File objDir = null;
try {
objDir = getObjectDir(objectID);
File parent = objDir.getParentFile();
removeAllFiles(objDir);
deleteEmptyDirectoriesStartingAt(parent);
} catch (Exception e) {
logger.error("Unable to finish deleting object " + objDir + " but the transaction was logged. "
+ (objDir == null ? "" : ("Check database consistency for the following path: " + objDir.getAbsolutePath())), e);
}
}
}
public static final void removeAllFiles(File dirToRemove) throws IOException {
File files[] = dirToRemove.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
removeAllFiles(files[i]);
else
files[i].delete();
}
}
dirToRemove.delete();
}
private void deleteEmptyDirectoriesStartingAt(File parent) {
while (true) {
File toDelete = parent;
parent = parent.getParentFile();
File files[] = toDelete.listFiles();
int numFiles = 0;
for (int i = 0; files != null && i < files.length; i++) {
if (files[i] == null)
continue;
if (files[i].getName().equals(".DS_Store")) {
files[i].delete();
continue;
}
numFiles++;
}
if (numFiles <= 0) {
toDelete.delete();
} else {
break;
}
}
}
/**
* Returns any known metadata for the digital object with the given
* identifier. If the given DOMetadata object is non-null then the metadata
* is stored in that object which is also returned. Otherwise, a new
* DOMetadata instance is constructed and returned. Note that this method
* returns a non-null value whether or not the object exists.
*/
public DOMetadata getObjectInfo(String objectID, DOMetadata metadata) throws CordraException {
return getObjectInfo(objectID, metadata, false);
}
private DOMetadata getObjectInfo(String objectID, DOMetadata metadata, boolean migrating) throws CordraException {
if (metadata == null)
metadata = new DOMetadata();
metadata.resetFields();
metadata.setObjectID(objectID);
// get the metadata database entry
try {
DatabaseEntry dbVal = new DatabaseEntry();
// Use unlocked reading. Puts to indexDB are autocommit.
// This function is locked by the object id for every write.
// It is also locked for element reads.
// There is a small chance of getting spurious information about
// object existence, element existence, or attributes
// if this is performed at just the same time as an autocommit put
// fails; in this case it should just look the same
// as if the put succeeded and was then reversed, which I consider
// acceptable.
if (indexDB.get(null, new DatabaseEntry(Util.encodeString(objectID.toLowerCase())), dbVal,
LockMode.READ_UNCOMMITTED) == OperationStatus.SUCCESS) {
HeaderSet headers = new HeaderSet();
headers.readHeadersFromBytes(dbVal.getData());
String mdID = headers.getStringHeader("id", objectID);
if (!mdID.equalsIgnoreCase(objectID))
throw new InternalErrorCordraException("Metadata ID does not match database ID: " + mdID + " != " + objectID);
metadata.setObjectID(mdID);
metadata.setDateCreated(headers.getLongHeader("date_created", 0));
metadata.setDateDeleted(headers.getLongHeader("date_deleted", 0));
for (Iterator headerItems = headers.iterator(); headerItems.hasNext();) {
HeaderItem item = (HeaderItem) headerItems.next();
if (item.getName().startsWith("md.")) {
metadata.setTag(item.getName().substring(3), item.getValue());
}
}
if (!readOnly && !migrating && null == metadata.getTag("elDb", null)) {
metadata = migrateObject(objectID);
}
} else {
metadata.setTag("elDb", "");
}
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
else
throw new InternalErrorCordraException("Unknown error getting metadata: ", e);
}
return metadata;
}
/** Sets the metadata for the given digital object. */
public void setObjectInfo(DOMetadata metadata) throws CordraException {
HeaderSet headers = new HeaderSet();
String id = metadata.getObjectID();
long dateCreated = metadata.getDateCreated();
long dateDeleted = metadata.getDateDeleted();
headers.addHeader("id", id);
if (dateCreated != 0)
headers.addHeader("date_created", dateCreated);
if (dateDeleted != 0)
headers.addHeader("date_deleted", dateDeleted);
for (Iterator tagKeys = metadata.getTagNames(); tagKeys.hasNext();) {
String tagName = (String) tagKeys.next();
headers.addHeader("md." + tagName, metadata.getTag(tagName, ""));
}
// store the updated info in the index database
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
headers.writeHeaders(bout);
DatabaseEntry key = new DatabaseEntry(Util.encodeString(id.toLowerCase()));
DatabaseEntry data = new DatabaseEntry(bout.toByteArray());
// long start = System.currentTimeMillis();
boolean success;
try {
success = indexDB.put(null, key, data) == OperationStatus.SUCCESS;
} catch (Exception e) {
throw new InternalErrorCordraException("Unknown error setting metadata", e);
}
// long end = System.currentTimeMillis();
// if (end-start > 500) {
// logger.warn("Long transaction (" + (end-start) + " = " + end +
// "-" + start + ") for " + Thread.currentThread().getName());
// }
if (!success) {
throw new InternalErrorCordraException("Unexpected status upon database 'put'");
}
} catch (Exception e) {
logger.error("Unknown error setting metadata", e);
if (e instanceof CordraException)
throw (CordraException) e;
else
throw new InternalErrorCordraException("Unknown error setting metadata", e);
}
}
/**
* Return the metadata key that refers to the attribute timestamp for the
* given attribute key
*/
private static final String getAttTSKey(String elementID, String attributeKey) {
if (elementID == null)
return "objatt-ts." + attributeKey;
return "elatt-ts." + escapeElementID(elementID) + "." + attributeKey;
}
/**
* Return the metadata key that refers to the attribute value for the given
* attribute key
*/
private static final String getAttValKey(String elementID, String attributeKey) {
if (elementID == null)
return "objatt." + attributeKey;
return "elatt." + escapeElementID(elementID) + "." + attributeKey;
}
/**
* Remove the attributes with the given keys from the object or data
* element. If the elementID is null then the attributes are removed from
* the object, otherwise they are removed from the element.
*/
public void deleteAttributes(String objectID, String elementID, String attributeKeys[]) throws CordraException {
if (attributeKeys == null)
throw new NullPointerException();
// sync on the object ID so that we have exclusive access to the object
// metadata
synchronized (objectID.toLowerCase().intern()) {
long timestamp = System.currentTimeMillis();
HeaderSet removedAtts = new HeaderSet();
DOMetadata metadata = getObjectInfo(objectID, null);
for (int i = 0; i < attributeKeys.length; i++) {
String key = attributeKeys[i];
String timestampKey = getAttTSKey(elementID, key);
metadata.setTag(timestampKey, String.valueOf(timestamp));
metadata.setTag(getAttValKey(elementID, key), null);
removedAtts.addHeader(key, "");
}
metadata.updateModification(timestamp);
setObjectInfo(metadata);
}
}
/**
* Add the given key-value attribute to the object, replacing any existing
* attribute that has the same key. If the elementID is non-null then the
* attribute is associated with the identified element within the object.
*/
public void setAttributes(String objectID, String elementID, HeaderSet headers) throws CordraException {
synchronized (objectID.toLowerCase().intern()) {
DOMetadata metadata = getObjectInfo(objectID, null);
HeaderSet txnAttributes = new HeaderSet();
long timestamp = System.currentTimeMillis();
for (Iterator it = headers.iterator(); it.hasNext();) {
HeaderItem item = (HeaderItem) it.next();
String key = item.getName();
String value = item.getValue();
String timestampKey = getAttTSKey(elementID, key);
String valueKey = getAttValKey(elementID, key);
metadata.setTag(timestampKey, String.valueOf(timestamp));
metadata.setTag(valueKey, value);
txnAttributes.addHeader(key, value);
}
metadata.updateModification(timestamp);
setObjectInfo(metadata);
}
}
/**
* Get the value that has been associated with the given key. If no value
* has been associated with the key then this will return null. If the given
* elementID is null then this will return object-level attributes.
* Otherwise it will return attributes for the given element.
*/
public HeaderSet getAttributes(String objectID, String elementID, HeaderSet container) throws CordraException {
if (container == null)
container = new HeaderSet();
DOMetadata md = getObjectInfo(objectID, null);
String prefix = getAttValKey(elementID, "");
int prefixLen = prefix.length();
for (Iterator it = md.getTagNames(); it.hasNext();) {
String tag = (String) it.next();
if (!tag.startsWith(prefix))
continue;
container.addHeader(tag.substring(prefixLen), md.getTag(tag, null));
}
// add the internal element attributes
if (elementID == null) {
// add the object timestamps
if (!container.hasHeader(DATE_CREATED_ATTRIBUTE)) {
container.addHeader(DATE_CREATED_ATTRIBUTE, md.getDateCreated());
}
String modTS = md.getTag("objmodified", null);
if (modTS != null && !container.hasHeader(DATE_MODIFIED_ATTRIBUTE)) {
container.addHeader(DATE_MODIFIED_ATTRIBUTE, modTS);
}
} else {
// add the element timestamps
String elementTS = md.getTag("de." + elementID, null);
if (elementTS != null && !container.hasHeader(DATE_MODIFIED_ATTRIBUTE)) {
container.addHeader(DATE_MODIFIED_ATTRIBUTE, elementTS);
}
String elementCreatedTS = md.getTag("de-created." + elementID, null);
if (elementCreatedTS != null && !container.hasHeader(DATE_CREATED_ATTRIBUTE)) {
container.addHeader(DATE_CREATED_ATTRIBUTE, elementCreatedTS);
}
if (!container.hasHeader(SIZE_ATTRIBUTE)) {
if (md.getTag("de-file." + elementID, null) != null) {
File objDir = getObjectDir(objectID);
File elFile = new File(objDir, convertToFileName(elementID));
container.addHeader(SIZE_ATTRIBUTE, elFile.length());
} else {
String sizeString = md.getTag("de-size." + elementID, null);
if (sizeString != null) {
long size = Long.parseLong(sizeString);
container.addHeader(SIZE_ATTRIBUTE, size);
}
}
}
}
return container;
}
/**
* Returns true if the given digital object exists.
*/
public boolean doesObjectExist(String objectID) throws CordraException {
return getObjectInfo(objectID, null).objectExists();
}
/**
* Returns true if the given data element exists
*/
public boolean doesDataElementExist(String objectID, String elementID) throws CordraException {
try {
DOMetadata metadata = getObjectInfo(objectID, null);
if (!metadata.objectExists())
return false;
String deExists = metadata.getTag("de-exists." + elementID, null);
// if (deExists != null) // now getObjectInfo ensures that de-exists
// is correct
return Boolean.parseBoolean(deExists);
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
else
throw new InternalErrorCordraException(String.valueOf(e));
}
}
/**
* Returns the File in which the given data element is stored, if any. This
* can return null on servers where data elements are not stored in files.
* This is used where operators need to do more with a data element than
* simple read and write operations. Examples inlude indexes, databases,
* etc.
*/
@SuppressWarnings("unused")
public File getFileForDataElement(String objectID, String elementID) throws CordraException {
return null;
}
/** Iterator over the object IDs in the Berkeley DB database. */
public class DBEnumerator implements Enumeration<String>, Closeable {
private Cursor cursor = null;
private DatabaseEntry keyEntry = new DatabaseEntry();
private DatabaseEntry valEntry = new DatabaseEntry();
private OperationStatus lastStatus = null;
private HeaderSet mdInfo;
private DOMetadata currentMD;
public DBEnumerator() {
mdInfo = new HeaderSet();
currentMD = new DOMetadata();
try {
// for logic of READ_UNCOMMITTED, see indexDB.put in
// getObjectInfo()
cursor = indexDB.openCursor(null, CursorConfig.READ_UNCOMMITTED);
preFetchNextItem();
} catch (Exception e) {
logger.error("Error in DBEnumerator()", e);
cursor = null;
lastStatus = null;
}
}
private void preFetchNextItem() {
// fetch the next item....
while (true) {
try {
lastStatus = cursor.getNext(keyEntry, valEntry, null);
if (lastStatus == null || lastStatus != OperationStatus.SUCCESS) {
cursor.close();
break;
}
loadObjectMD();
if (!currentMD.objectExists()) { // the object no longer
// exists. keep scanning
continue;
} else {
break;
}
} catch (Exception e) {
logger.error("Error scanning object index", e);
try {
cursor.close();
} catch (Throwable t) {
}
cursor = null;
lastStatus = null;
break;
}
}
}
@Override
public synchronized boolean hasMoreElements() {
return lastStatus == OperationStatus.SUCCESS;
}
private void loadObjectMD() throws Exception {
mdInfo.readHeaders(new ByteArrayInputStream(valEntry.getData()));
String objectID = Util.decodeString(keyEntry.getData());
String mdID = mdInfo.getStringHeader("id", objectID);
if (!mdID.equalsIgnoreCase(objectID)) {
logger.error(
"Error listing objects: Metadata ID does not match database ID: " + mdID + " != " + objectID);
mdID = objectID;
}
currentMD.setObjectID(mdID);
currentMD.setDateCreated(mdInfo.getLongHeader("date_created", 0));
currentMD.setDateDeleted(mdInfo.getLongHeader("date_deleted", 0));
}
@Override
public synchronized String nextElement() throws java.util.NoSuchElementException {
if (cursor == null || lastStatus == null || lastStatus != OperationStatus.SUCCESS)
throw new java.util.NoSuchElementException();
String objectID = currentMD.getObjectID();
preFetchNextItem();
return objectID;
}
@Override
public void close() {
try {
if (cursor != null)
cursor.close();
} catch (Throwable t) {
}
}
// public void finalize() throws Throwable {
// close();
// super.finalize();
// }
}
/**
* Returns an Enumeration of all of the objects in the repository.
*/
@SuppressWarnings("unused")
public Enumeration<String> listObjects() throws CordraException {
return new DBEnumerator();
}
public List<String> listDataElements(String objectID) throws CordraException {
try {
DOMetadata metadata = getObjectInfo(objectID, null);
if (!metadata.objectExists()) {
// Used to throw NO_SUCH_OBJECT; this caused issues due to lack
// of transactional semantics.
// Calls to this method are generally indirectly preceded by
// doesObjectExist.
return Collections.emptyList();
}
List<String> v = new ArrayList<>();
for (Iterator it = metadata.getTagNames(); it.hasNext();) {
String tag = (String) it.next();
if (!tag.startsWith("de-exists."))
continue;
if (Boolean.parseBoolean(metadata.getTag(tag, null))) {
v.add(tag.substring("de-exists.".length()));
}
}
return v;
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
else
throw new InternalErrorCordraException(String.valueOf(e));
}
}
/**
* Returns the identified data element for the given object.
*/
public InputStream getDataElement(String objectID, String elementID) throws CordraException {
return getDataElement(objectID, elementID, 0, -1);
}
@SuppressWarnings({"resource", "null"})
public InputStream getDataElement(String objectID, String elementID, long start, long len) throws CordraException {
String lockID = null;
ReadLock lock = null;
boolean returnedSuccessfully = false;
try {
DOMetadata metadata = getObjectInfo(objectID, null);
if (!metadata.objectExists()) {
// Used to throw NO_SUCH_OBJECT; this caused issues due to lack
// of transactional semantics.
// Calls to this method are generally indirectly preceded by
// doesObjectExist.
return null;
}
String deExists = metadata.getTag("de-exists." + elementID, null);
if (!Boolean.parseBoolean(deExists)) {
return null;
}
// Wait for any write operations to finish with the data alement
// and then register ourselves as reading it so that won't be
// written
// by others until we are finished
lockID = getLockID(objectID, elementID);
synchronized (lockID) {
while (true) {
Object lockObj = locks.get(lockID);
if (lockObj == null) {
lock = new ReadLock(lockID);
locks.put(lockID, lock);
break;
} else if (lockObj instanceof ReadLock) {
lock = (ReadLock) lockObj;
break;
} else {
// someone else has a write lock...
// wait for the lock to become available again
lockID.wait();
}
}
lock.readerCount++;
}
metadata = getObjectInfo(objectID, metadata);
deExists = metadata.getTag("de-exists." + elementID, null);
if (!Boolean.parseBoolean(deExists)) {
return null;
}
boolean deFile = null != metadata.getTag("de-file." + elementID, null);
if (start < 0)
start = 0;
if (deFile) {
File objDir = getObjectDir(objectID);
File elementFile = new File(objDir, convertToFileName(elementID));
if (!elementFile.exists()) {
return new ByteArrayInputStream(new byte[0]);
}
RandomAccessFile randomAccessElementFile = new RandomAccessFile(elementFile, "r");
InputStream in = Channels.newInputStream(randomAccessElementFile.getChannel().position(start));
if (len >= 0) {
in = new LimitedInputStream(in, 0, len);
}
InputStream lockedIn = new LockedInputStream(in, lock, randomAccessElementFile);
returnedSuccessfully = true;
return lockedIn;
} else {
byte[] bytes = getElementFromDb(objectID, elementID);
if (start >= bytes.length) {
return new ByteArrayInputStream(new byte[0]);
}
if (start > 0 || len >= 0) {
long end;
if (len < 0)
end = bytes.length;
else
end = start + len;
if (end > bytes.length) {
end = bytes.length;
}
bytes = Arrays.copyOfRange(bytes, (int) start, (int) end);
}
return new ByteArrayInputStream(bytes);
}
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
else {
logger.error("Error getting data element: objectID='" + objectID + "'; element='" + elementID, e);
throw new InternalErrorCordraException("Error getting data element: objectID='" + objectID + "'; element='" + elementID, e);
}
} finally {
if (lock != null && !returnedSuccessfully) {
lock.releaseLock();
}
}
}
/**
* InputStream subclass that decrements the lock (semaphore) when the stream
* is closed.
*/
@SuppressWarnings("sync-override")
private static class LockedInputStream extends BufferedInputStream {
private ReadLock lock;
private boolean hasBeenReleased = false;
private RandomAccessFile randomAccessElementFile;
LockedInputStream(InputStream in, ReadLock lock, RandomAccessFile randomAccessElementFile) {
super(in);
this.lock = lock;
this.randomAccessElementFile = randomAccessElementFile;
}
synchronized void releaseLock() {
if (hasBeenReleased)
return;
lock.releaseLock();
hasBeenReleased = true;
}
// Override read(...) methods to release lock when EOF reached.
// Just a safety net in case of poorly-behaved client.
// Note that BufferedInputStream guarantees that the
// underlying input is finished, even if the client uses
// mark() and reset().
@Override
public int read() throws IOException {
int res = super.read();
if (res < 0)
releaseLock();
return res;
}
@Override
public int read(byte[] b) throws IOException {
int res = super.read(b);
if (res < 0)
releaseLock();
return res;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int res = super.read(b, off, len);
if (res < 0)
releaseLock();
return res;
}
@Override
public void close() throws IOException {
try {
super.close();
this.randomAccessElementFile.close();
} finally {
releaseLock();
}
}
@Override
public synchronized void finalize() {
if (!hasBeenReleased) {
System.err.println(
"Warning: LockedInputStream with lock id " + lock.id + " finalized before being closed");
releaseLock();
}
}
}
private class ReadLock {
String id;
int readerCount = 0;
ReadLock(String id) {
this.id = id;
}
void releaseLock() {
synchronized (id) {
readerCount--;
if (readerCount == 0) {
locks.remove(id);
}
id.notifyAll();
}
}
}
/**
* Stores the data read from the given InputStream into the given data
* element for the object identified by objectID. This reads from the
* InputStream until the end of the stream has been reached.
*/
@SuppressWarnings("resource")
public void storeDataElement(String objectID, String elementID, InputStream input, boolean append) throws CordraException {
OutputStream fout = null;
int n = 0;
String lockID = null;
try {
// make sure the object exists
if (!doesObjectExist(objectID)) {
throw new NotFoundCordraException("Object '" + objectID + "' does not exist");
}
// Wait for everyone else to finish with the data element (reading
// and writing)
// and then lock it so that it cannot be read or written by others
// until we are done
String tmpLockID = getLockID(objectID, elementID);
synchronized (tmpLockID) {
while (locks.containsKey(tmpLockID)) {
// wait until there are no more readers...
tmpLockID.wait();
}
lockID = tmpLockID;
locks.put(tmpLockID, EMPTY_LOCK_VAL);
}
long modificationTime = 0;
boolean alreadyExisted;
boolean deFile = false;
boolean deForceFile = false;
synchronized (objectID.toLowerCase().intern()) {
DOMetadata metadata = getObjectInfo(objectID, null);
String mdTagName = "de." + elementID;
long oldTimestamp = 0;
try {
oldTimestamp = Long.parseLong(metadata.getTag(mdTagName, "0"));
} catch (Exception e) {
}
alreadyExisted = oldTimestamp > 0;
modificationTime = System.currentTimeMillis();
metadata.setTag(mdTagName, String.valueOf(modificationTime));
metadata.setTag("de-exists." + elementID, "true");
deFile = null != metadata.getTag("de-file." + elementID, null);
deForceFile = Boolean
.parseBoolean(metadata.getTag(getAttValKey(elementID, INTERNAL_ELEMENT_FILE), null));
String createdTagName = "de-created." + elementID;
if (!alreadyExisted && metadata.getTag(createdTagName, null) == null)
metadata.setTag(createdTagName, String.valueOf(modificationTime));
metadata.updateModification(modificationTime);
setObjectInfo(metadata);
}
// (over)write the data element
try {
if (deFile) {
File objDir = getObjectDir(objectID);
objDir.mkdirs();
File elementFile = new File(objDir, convertToFileName(elementID));
fout = new FileOutputStream(elementFile, append);
byte buf[] = new byte[4096];
int r;
n = 0;
while ((r = input.read(buf)) >= 0) {
fout.write(buf, 0, r);
n += r;
}
fout.close();
if (!deForceFile && !append && n < maxDbElementSize / 2) {
migrateElementFromFileToDb(null, null, objectID, elementID);
}
} else {
storeElementMaybeInDb(objectID, elementID, input, append, deForceFile);
}
} finally {
}
} catch (Exception e) {
logger.error("Got error writing element", e);
if (e instanceof CordraException)
throw (CordraException) e;
else
throw new InternalErrorCordraException("Got error writing element", e);
} finally {
try {
if (fout != null) fout.close();
} catch (Exception e) {
}
if (lockID != null) { // the data element was locked... unlock it
synchronized (lockID) {
locks.remove(lockID);
lockID.notifyAll();
}
}
}
}
/**
* Deletes the specified data element from the given object. Returns true if
* the specified data element ever existed in the first place.
*/
public boolean deleteDataElement(String objectID, String elementID) throws CordraException {
try {
// make sure the object exists
DOMetadata metadata = getObjectInfo(objectID, null);
if (!metadata.objectExists()) {
throw new NotFoundCordraException("Object '" + objectID + "' does not exist");
}
if (!Boolean.parseBoolean(metadata.getTag("de-exists." + elementID, null))) {
return false;
} else {
// get an exclusive write lock on the object metadata
long actualTime;
synchronized (objectID.toLowerCase().intern()) {
metadata = getObjectInfo(objectID, metadata);
actualTime = System.currentTimeMillis();
String mdTagName = "de." + elementID;
metadata.setTag(mdTagName, String.valueOf(actualTime));
metadata.setTag("de-exists." + elementID, null);
metadata.setTag("de-size." + elementID, null);
boolean deFile = null != metadata.getTag("de-file." + elementID, null);
if (deFile) {
File objDir = getObjectDir(objectID);
File elementFile = new File(objDir, convertToFileName(elementID));
// delete the actual file
if (elementFile.exists() && !elementFile.delete()) {
throw new InternalErrorCordraException("Unable to delete data element");
}
deleteEmptyDirectoriesStartingAt(objDir);
} else {
deleteElementFromDb(objectID, elementID);
}
metadata.setTag("de-file." + elementID, null);
String timestampPrefix = getAttTSKey(elementID, "");
String valuePrefix = getAttValKey(elementID, "");
HashMap tagsToSet = new HashMap();
ArrayList tagsToDelete = new ArrayList();
// remove any attributes
for (Iterator it = metadata.getTagNames(); it.hasNext();) {
String tagName = (String) it.next();
if (tagName.startsWith(timestampPrefix)) {
String timestampVal = metadata.getTag(tagName, null);
if (timestampVal == null)
continue; // can't happen
try {
String valueKey = valuePrefix + tagName.substring(timestampPrefix.length());
tagsToDelete.add(valueKey);
tagsToSet.put(tagName, String.valueOf(actualTime));
} catch (Exception e) {
// *very* unlikely to happen
logger.error("Error checking attribute timestamp", e);
}
}
}
for (Iterator iter = tagsToDelete.iterator(); iter.hasNext();) {
metadata.setTag((String) iter.next(), null);
}
for (Iterator iter = tagsToSet.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
metadata.setTag(key, (String) tagsToSet.get(key));
}
// update the metadata and attributes
metadata.updateModification(actualTime);
setObjectInfo(metadata);
}
return true;
}
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
else
throw new InternalErrorCordraException(String.valueOf(e));
}
}
private File getObjectDir(String objectID) throws CordraException {
return new File(baseDirectory, calculateObjectPath(objectID));
}
/**
* Get a key that identifies a unique lock object for the given object and
* data element
*/
private final String getLockID(String objectID, String elementID) {
return (convertToFileName(elementID) + "$" + objectID).intern();
}
private String calculateObjectPath(String objectID) throws CordraException {
// this assumes we are using case insensitive storage!
objectID = objectID.toLowerCase();
try {
byte buf[] = null;
synchronized (hash) {
hash.reset();
buf = hash.digest(objectID.getBytes("UTF8"));
}
StringBuffer sb = new StringBuffer(buf.length * 2);
encodeHex(buf, 0, buf.length, sb);
if (sb.length() > HASH_LENGTH)
sb.setLength(HASH_LENGTH);
int i = SEGMENT_SIZE;
while (i < sb.length()) {
sb.insert(i, FILE_SEPARATOR);
i += SEGMENT_SIZE + 1;
}
if (sb.charAt(sb.length() - 1) != FILE_SEPARATOR)
sb.append(FILE_SEPARATOR);
sb.append(convertToFileName(objectID));
return sb.toString();
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
throw new InternalErrorCordraException("Error computing object path: " + e);
}
}
@Override
public String toString() {
return "HashDirectoryStorage: " + baseDirectoryPath;
}
private static void printUsage() {
System.err.println("java net.cnri.apps.doserver.HashDirectoryStorage <dir> (list|getpath|getmetadata <id>)>");
}
public static void main(String argv[]) throws Exception {
if (argv.length < 2) {
printUsage();
return;
}
String dir = argv[0];
String cmd = argv[1];
HashDirectoryStorage hds = new HashDirectoryStorage();
hds.initWithDirectory(new File(dir), true);
if (cmd.equalsIgnoreCase("list")) {
System.out.println("listing elements...");
for (Enumeration en = hds.listObjects(); en.hasMoreElements();) {
System.out.println(String.valueOf(en.nextElement()));
}
System.out.println("done listing elements...");
} else if (cmd.equalsIgnoreCase("getpath")) {
for (int i = 2; i < argv.length; i++) {
System.out.println(" '" + argv[i] + "' -> '" + hds.calculateObjectPath(argv[i]) + "'");
}
} else if (cmd.equalsIgnoreCase("getmetadata")) {
for (int i = 2; i < argv.length; i++) {
System.out.println(argv[i] + ": " + hds.getObjectInfo(argv[i], null));
}
} else {
printUsage();
System.err.println("Unrecognized command: " + cmd);
System.exit(1);
}
System.exit(0);
}
private static final char HEX_VALUES[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F' };
/**
* Encode the given byte array into a hexadecimal string.
*/
public static final void encodeHex(byte buf[], int offset, int length, StringBuffer strBuf) {
if (buf == null)
return;
int n = 0;
for (int i = offset; i < buf.length && n < length; i++) {
strBuf.append(HEX_VALUES[(buf[i] & 0xF0) >>> 4]);
strBuf.append(HEX_VALUES[(buf[i] & 0xF)]);
n++;
}
}
/**
* Decode the given two hexadecimal characters into the byte that they
* represent.
*/
public static final byte decodeHex(char b1, char b2) {
b1 = Character.toUpperCase(b1);
b2 = Character.toUpperCase(b2);
byte result = (byte) 0;
if (b1 >= '0' && b1 <= '9') {
result = (byte) ((b1 - '0') << 4);
} else if (b1 >= 'A' && b1 <= 'F') {
result = (byte) ((b1 - 'A' + 10) << 4);
}
if (b2 >= '0' && b2 <= '9') {
result |= b2 - '0';
} else if (b2 >= 'A' && b2 <= 'F') {
result |= b2 - 'A' + 10;
}
return result;
}
/**
* Performs a conversion from the given encoded file name to the string that
* was encoded to get the file name.
*/
public static final String convertFromFileName(String fileName) {
if (fileName == null)
return "";
fileName = fileName.trim();
if (fileName.length() <= 0)
return "";
int strLen = fileName.length();
byte utf8Buf[] = new byte[strLen];
int buflen = 0;
for (int i = 0; i < strLen; i++) {
char ch = fileName.charAt(i);
if (ch == '.') {
utf8Buf[buflen++] = decodeHex(fileName.charAt(i + 1), fileName.charAt(i + 2));
i += 2;
} else {
utf8Buf[buflen++] = (byte) ch;
}
}
try {
return new String(utf8Buf, 0, buflen, "UTF8");
} catch (Exception e) {
return new String(utf8Buf, 0, buflen);
}
}
/**
* Performs a conversion from the given string to an encoded version that
* can be used as a file/URI name.
*/
public static final String convertToFileName(String str) {
byte buf[];
try {
buf = str.getBytes("UTF8");
} catch (Exception e) {
buf = str.getBytes();
}
StringBuffer sb = new StringBuffer(buf.length + 10);
for (int i = 0; i < buf.length; i++) {
byte b = buf[i];
if ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || b == '_' || b == '-') {
sb.append((char) b);
} else {
sb.append('.');
encodeHex(buf, i, 1, sb);
}
}
return sb.toString();
}
private static final String escapeElementID(String elementID) {
int len = elementID.length();
StringBuffer sb = new StringBuffer(len + 10);
for (int i = 0; i < len; i++) {
char ch = elementID.charAt(i);
switch (ch) {
case '%':
sb.append("%25");
break;
case '.':
sb.append("%2E");
break;
default:
sb.append(ch);
}
}
return sb.toString();
}
private static byte[] getElementDbKey(String objectID, String elementID) {
byte[] objIdBytes = Util.encodeString(objectID.toLowerCase(Locale.ENGLISH));
byte[] elIdBytes = Util.encodeString(elementID);
byte[] key = new byte[8 + objIdBytes.length + elIdBytes.length];
int offset = Encoder.writeByteArray(key, 0, objIdBytes);
Encoder.writeByteArray(key, offset, elIdBytes);
return key;
}
private byte[] getElementDbSearchKeyForObject(String objectID) {
byte[] objIdBytes = Util.encodeString(objectID.toLowerCase(Locale.ENGLISH));
byte[] key = new byte[4 + objIdBytes.length];
Encoder.writeByteArray(key, 0, objIdBytes);
return key;
}
private void deleteElementFromDb(String objectID, String elementID) throws CordraException {
byte[] key = getElementDbKey(objectID, elementID);
try {
elementDb.delete(null, new DatabaseEntry(key));
} catch (Exception e) {
logger.error("Error deleting data element " + elementID + " of " + objectID, e);
throw new InternalErrorCordraException("Error deleting data element " + elementID + " of " + objectID, e);
}
}
private byte[] getElementFromDb(String objectID, String elementID) throws CordraException {
byte[] key = getElementDbKey(objectID, elementID);
try {
DatabaseEntry dbVal = new DatabaseEntry();
OperationStatus status = elementDb.get(null, new DatabaseEntry(key), dbVal, null);
if (status == OperationStatus.NOTFOUND) {
return new byte[0];
} else if (status == OperationStatus.SUCCESS) {
return dbVal.getData();
} else {
throw new InternalErrorCordraException("Unexpected status " + status + " retrieving data element " + elementID + " of " + objectID);
}
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
throw new InternalErrorCordraException("Error retrieving data element " + elementID + " of " + objectID, e);
}
}
@SuppressWarnings("resource")
private void deleteDbElementsForObject(String objectID) throws CordraException {
com.sleepycat.je.Transaction dbtxn = null;
Cursor cursor = null;
try {
dbtxn = environment.beginTransaction(null, null);
cursor = elementDb.openCursor(dbtxn, null);
byte[] objectKey = getElementDbSearchKeyForObject(objectID);
DatabaseEntry key = new DatabaseEntry(objectKey);
DatabaseEntry data = new DatabaseEntry();
data.setPartial(0, 0, true);
OperationStatus status = cursor.getSearchKeyRange(key, data, LockMode.RMW);
while (status == OperationStatus.SUCCESS) {
if (Util.startsWith(key.getData(), objectKey)) {
cursor.delete();
} else {
break;
}
status = cursor.getNext(key, data, LockMode.RMW);
}
if (status != OperationStatus.SUCCESS && status != OperationStatus.NOTFOUND) {
throw new InternalErrorCordraException("Unexpected status " + status + " deleting data elements of " + objectID);
}
cursor.close();
cursor = null;
dbtxn.commit();
} catch (Exception e) {
if (cursor != null) {
try {
cursor.close();
} catch (DatabaseException ex) {
logger.error("Exception closing", ex);
}
}
if (dbtxn != null) {
try {
dbtxn.abort();
} catch (DatabaseException ex) {
logger.error("Exception closing", ex);
}
}
logger.error("Error deleting data elements of " + objectID, e);
if (e instanceof CordraException)
throw (CordraException) e;
throw new InternalErrorCordraException("Error deleting data elements of " + objectID, e);
}
}
private DOMetadata migrateObject(String objectID) throws CordraException {
com.sleepycat.je.Transaction dbtxn = null;
try {
synchronized (objectID.toLowerCase().intern()) {
DOMetadata metadata = getObjectInfo(objectID, null, true);
File objDir = getObjectDir(objectID);
String files[] = objDir.list();
if (files != null) {
dbtxn = environment.beginTransaction(null, null);
for (String filename : files) {
File file = new File(filename);
if (file.length() < maxDbElementSize / 2) {
String elementID = convertFromFileName(filename);
boolean deForceFile = Boolean.parseBoolean(
metadata.getTag(getAttValKey(elementID, INTERNAL_ELEMENT_FILE), null));
if (!deForceFile)
migrateElementFromFileToDb(metadata, dbtxn, objectID, elementID);
}
}
}
deleteEmptyDirectoriesStartingAt(objDir);
metadata.setTag("elDb", "");
setObjectInfo(metadata);
if (dbtxn != null) {
dbtxn.commit();
dbtxn = null;
}
return metadata;
}
} catch (Exception e) {
if (dbtxn != null) {
try {
dbtxn.abort();
} catch (DatabaseException ex) {
logger.error("Exception closing", ex);
}
}
if (e instanceof CordraException)
throw (CordraException) e;
throw new InternalErrorCordraException("Error migrating data elements of " + objectID, e);
}
}
private void migrateElementFromFileToDb(DOMetadata metadata, com.sleepycat.je.Transaction dbtxn, String objectID,
String elementID) throws CordraException {
InputStream in = null;
try {
File objDir = getObjectDir(objectID);
File elementFile = new File(objDir, convertToFileName(elementID));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
if (elementFile.exists()) {
in = new BufferedInputStream(new FileInputStream(elementFile));
byte[] buf = new byte[8192];
int r;
while ((r = in.read(buf)) > 0) {
bout.write(buf, 0, r);
}
in.close();
in = null;
}
byte[] key = getElementDbKey(objectID, elementID);
OperationStatus status = elementDb.put(dbtxn, new DatabaseEntry(key),
new DatabaseEntry(bout.toByteArray()));
if (status != OperationStatus.SUCCESS) {
throw new InternalErrorCordraException("Unexpected status " + status + " migrating data element " + elementID + " of " + objectID);
}
elementFile.delete();
if (metadata == null) {
deleteEmptyDirectoriesStartingAt(objDir);
synchronized (objectID.toLowerCase().intern()) {
metadata = getObjectInfo(objectID, null);
metadata.setTag("de-exists." + elementID, "true");
metadata.setTag("de-file." + elementID, null);
metadata.setTag("de-size." + elementID, String.valueOf(bout.size()));
setObjectInfo(metadata);
}
} else {
metadata.setTag("de-exists." + elementID, "true");
metadata.setTag("de-file." + elementID, null);
metadata.setTag("de-size." + elementID, String.valueOf(bout.size()));
}
} catch (Exception e) {
if (e instanceof CordraException)
throw (CordraException) e;
throw new InternalErrorCordraException("Error migrating data element " + elementID + " of " + objectID, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error("Error closing", e);
}
}
}
}
private void storeElementMaybeInDb(String objectID, String elementID, InputStream input, boolean append,
boolean forceFile) throws CordraException {
com.sleepycat.je.Transaction dbtxn = null;
FileOutputStream fout = null;
File elementFile = null;
try {
dbtxn = environment.beginTransaction(null, null);
byte[] key = getElementDbKey(objectID, elementID);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
if (append) {
DatabaseEntry dbVal = new DatabaseEntry();
OperationStatus status = elementDb.get(dbtxn, new DatabaseEntry(key), dbVal, LockMode.RMW);
if (status == OperationStatus.SUCCESS) {
bout.write(dbVal.getData());
} else if (status != OperationStatus.NOTFOUND) {
throw new InternalErrorCordraException("Unexpected status " + status
+ " retrieving data element " + elementID + " of " + objectID);
}
}
byte[] buf = new byte[8192];
int r;
boolean deFile = forceFile || bout.size() > maxDbElementSize;
if (!deFile) {
while ((r = input.read(buf)) > 0) {
bout.write(buf, 0, r);
if (bout.size() > maxDbElementSize) {
deFile = true;
break;
}
}
}
if (deFile) {
OperationStatus status = elementDb.delete(dbtxn, new DatabaseEntry(key));
if (status != OperationStatus.SUCCESS && status != OperationStatus.NOTFOUND) {
throw new InternalErrorCordraException("Unexpected status " + status + " migrating data element " + elementID + " of " + objectID);
}
File objDir = getObjectDir(objectID);
objDir.mkdirs();
elementFile = new File(objDir, convertToFileName(elementID));
fout = new FileOutputStream(elementFile);
fout.write(bout.toByteArray());
while ((r = input.read(buf)) > 0) {
fout.write(buf, 0, r);
}
fout.close();
fout = null;
synchronized (objectID.toLowerCase().intern()) {
DOMetadata metadata = getObjectInfo(objectID, null);
metadata.setTag("de-file." + elementID, "");
metadata.setTag("de-size." + elementID, null);
setObjectInfo(metadata);
}
} else {
OperationStatus status = elementDb.put(dbtxn, new DatabaseEntry(key),
new DatabaseEntry(bout.toByteArray()));
if (status != OperationStatus.SUCCESS) {
throw new InternalErrorCordraException("Unexpected status " + status + " storing data element " + elementID + " of " + objectID);
}
synchronized (objectID.toLowerCase().intern()) {
DOMetadata metadata = getObjectInfo(objectID, null);
metadata.setTag("de-file." + elementID, null);
metadata.setTag("de-size." + elementID, String.valueOf(bout.size()));
setObjectInfo(metadata);
}
}
dbtxn.commit();
dbtxn = null;
} catch (Exception e) {
if (fout != null) {
try {
fout.close();
} catch (IOException ex) {
logger.error("Exception closing", ex);
}
}
if (elementFile != null) {
elementFile.delete();
}
if (dbtxn != null) {
try {
dbtxn.abort();
} catch (DatabaseException ex) {
logger.error("Exception closing", ex);
}
}
if (e instanceof CordraException)
throw (CordraException) e;
throw new InternalErrorCordraException("Error storing data element " + elementID + " of " + objectID, e);
}
}
}
| 41.143114 | 151 | 0.538445 |
10792a6a7375f475b9548d47a832ec0ab6f8596f | 11,770 | package ox.util;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.getLast;
import static com.google.common.collect.Iterables.isEmpty;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.CharMatcher;
import com.google.common.base.Enums;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import ox.Log;
import ox.Money;
public class Utils {
private static final CharMatcher whiteSpace = CharMatcher.whitespace().or(CharMatcher.is('\0')).precomputed();
private static final Pattern emailPattern = Pattern.compile(
"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\." +
"[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$");
public static final DecimalFormat decimalFormat = new DecimalFormat("#,##0.00#########");
public static final DecimalFormat decimalFormat2 = new DecimalFormat("#,##0.00");
public static final DecimalFormat noDecimalFormat = new DecimalFormat("#,##0");
private static final CharMatcher moneyMatcher = CharMatcher.anyOf("$£€ ,-–()").precomputed();
private static final Map<String, Pattern> patternCache = Maps.newConcurrentMap();
public static String capitalize(String s) {
if (isNullOrEmpty(s)) {
return s;
}
StringBuilder sb = new StringBuilder(s.toLowerCase());
boolean up = true;
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (c == ' ') {
up = true;
} else if (c == '_') {
up = true;
sb.setCharAt(i, ' ');
} else if (up) {
sb.setCharAt(i, Character.toUpperCase(c));
up = false;
}
}
return sb.toString();
}
public static String sentenceCase(String s) {
if (isNullOrEmpty(s)) {
return s;
}
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
for (int i = 1; i < chars.length; i++) {
char c = chars[i];
if (c == '_') {
chars[i] = ' ';
} else {
chars[i] = Character.toLowerCase(c);
}
}
return new String(chars);
}
private static final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
public static String formatBytes(long size) {
if (size <= 0) {
return "0";
}
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
public static Double parseMoney(String s) {
if (isNullOrEmpty(s)) {
return null;
}
double ret;
try {
ret = parseDouble(moneyMatcher.removeFrom(s));
} catch (Throwable t) {
throw new RuntimeException("Couldn't parse money: " + s);
}
if (s.charAt(0) == '-' || s.charAt(0) == '–' || s.charAt(0) == '(') {
ret = -ret;
}
return ret;
}
public static double parsePercent(String s) {
return parseDouble(s.replace("%", "")) / 100.0;
}
public static String percent(double d) {
return percent(d, false);
}
public static String percent(double d, boolean decimals) {
if (decimals) {
return formatDecimal2(d * 100) + "%";
} else {
return format(d * 100) + "%";
}
}
public static String money(double d) {
return money(d, true);
}
public static String money(double d, boolean decimals) {
boolean negative = d < 0;
DecimalFormat format = decimals ? decimalFormat2 : noDecimalFormat;
synchronized (format) {
if (negative) {
return "-$" + format.format(-d);
} else {
return "$" + format.format(d);
}
}
}
public static String format(double d) {
synchronized (noDecimalFormat) {
return noDecimalFormat.format(d);
}
}
public static String formatDecimal(double d) {
synchronized (decimalFormat) {
return decimalFormat.format(d);
}
}
public static String formatDecimal2(double d) {
synchronized (decimalFormat2) {
return decimalFormat2.format(d);
}
}
public static String formatDecimal(double d, int decimalPlaces) {
StringBuilder pattern = new StringBuilder("#,##0.");
for (int i = 0; i < decimalPlaces; i++) {
pattern.append("0");
}
DecimalFormat format = new DecimalFormat(pattern.toString());
return format.format(d);
}
public static void debug(Object... objects) {
Log.debug(Arrays.toString(objects));
}
public static <T extends Enum<T>> T parseEnum(String s, Class<T> enumType) {
if (s == null) {
return null;
}
Optional<T> o = Enums.getIfPresent(enumType, s.replace(' ', '_').replace('-', '_').toUpperCase());
if (o.isPresent()) {
return o.get();
}
for (T constant : enumType.getEnumConstants()) {
if (Matchers.javaLetterOrDigit().retainFrom(constant.toString()).equalsIgnoreCase(s)) {
return constant;
}
}
throw new IllegalArgumentException("No enum: " + enumType + "." + s);
}
public static boolean isValidPhoneNumber(String phoneNumber) {
String digits = Matchers.javaDigit().retainFrom(phoneNumber);
return digits.length() >= 10; // TODO
}
public static String formatPhone(String phoneNumber) {
if (phoneNumber == null) {
return null;
}
if (phoneNumber.startsWith("+1")) {
phoneNumber = phoneNumber.substring(2);
}
if (phoneNumber.length() != 10) {
return phoneNumber;
}
return "(" + phoneNumber.substring(0, 3) + ") " + phoneNumber.substring(3, 6) + "-" + phoneNumber.substring(6, 10);
}
public static boolean isValidEmailAddress(String email) {
if (isNullOrEmpty(email)) {
return false;
}
return emailPattern.matcher(email).matches();
}
public static boolean isAlphaNumeric(String s) {
return Matchers.javaLetterOrDigit().matchesAllOf(s);
}
public static String trim(String s) {
return whiteSpace.trimFrom(s);
}
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw propagate(e);
}
}
public static String urlDecode(String s) {
try {
return URLDecoder.decode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw propagate(e);
}
}
public static int signum(double d) {
return (int) Math.signum(d);
}
public static int random(int n) {
return (int) (Math.random() * n);
}
public static <T> T random(T[] array) {
return array[random(array.length)];
}
public static <T> T random(Collection<T> c) {
if (c.isEmpty()) {
return null;
}
return Iterables.get(c, random(c.size()));
}
public static List<Integer> count(int from, int to) {
List<Integer> ret = Lists.newArrayList();
for (int i = from; i <= to; i++) {
ret.add(i);
}
return ret;
}
public static List<Double> count(double from, double to, double step) {
List<Double> ret = Lists.newArrayList();
for (double i = from; i <= to; i += step) {
ret.add(i);
}
return ret;
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Collection<T> data, Class<T> c) {
T[] ret = (T[]) Array.newInstance(c, data.size());
data.toArray(ret);
return ret;
}
public static <T> T first(Collection<T> c) {
if (c.isEmpty()) {
return null;
}
return c.iterator().next();
}
public static <T> T last(Iterable<T> c) {
if (isEmpty(c)) {
return null;
}
return getLast(c);
}
public static <T> T only(Iterable<T> c) {
Iterator<T> iter = c.iterator();
if (!iter.hasNext()) {
return null;
}
T ret = iter.next();
checkArgument(!iter.hasNext(), "Expected one element, but found multiple.");
return ret;
}
public static String normalize(String s) {
return s == null ? "" : trim(s);
}
public static double normalize(Double n) {
return n == null ? 0.0 : n;
}
public static int normalize(Integer n) {
return n == null ? 0 : n;
}
public static long normalize(Long n) {
return n == null ? 0 : n;
}
public static boolean normalize(Boolean b) {
return b == null ? Boolean.FALSE : b;
}
public static Money normalize(Money m) {
return m == null ? Money.ZERO : m;
}
public static String checkNotEmpty(String s) {
checkState(!isNullOrEmpty(s));
return s;
}
public static String checkNotEmpty(String s, Object errorMessage) {
checkState(!isNullOrEmpty(s), errorMessage);
return s;
}
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
public static String last(String s, int numCharacters) {
return s.substring(s.length() - numCharacters, s.length());
}
public static String first(String s, String delimiter) {
int i = s.indexOf(delimiter);
checkState(i != -1, "'" + delimiter + "' not found in " + s);
return s.substring(0, i);
}
public static String second(String s, String delimiter) {
int i = s.indexOf(delimiter);
checkState(i != -1, "'" + delimiter + "' not found in " + s);
return s.substring(i + delimiter.length());
}
public static Integer toInt(String s) {
return isNullOrEmpty(s) ? null : parseInt(s);
}
public static Double toDouble(String s) {
return isNullOrEmpty(s) ? null : parseDouble(s);
}
public static Long toLong(String s) {
return isNullOrEmpty(s) ? null : parseLong(s);
}
public static Boolean toBoolean(String s) {
return isNullOrEmpty(s) ? null : Boolean.parseBoolean(s);
}
public static LocalDate toDate(String s) {
return isNullOrEmpty(s) ? null : LocalDate.parse(s);
}
public static Money toMoney(String s) {
return isNullOrEmpty(s) ? null : Money.parse(s);
}
public static String uuid() {
return UUID.randomUUID().toString().replace("-", "");
}
public static <T> void sort(List<T> list, Comparator<? super T> c) {
if (list.isEmpty()) {
return;
}
list.sort(c);
}
public static <T> Collection<T> removeNulls(Collection<T> c) {
while (c.remove(null)) {
}
return c;
}
public static String regexMatch(String pattern, String document) {
Pattern p = patternCache.computeIfAbsent(pattern, Pattern::compile);
Matcher m = p.matcher(document);
if (!m.find()) {
return null;
}
if (m.groupCount() == 0) {
return m.group();
}
return m.group(1);
}
public static String getExtension(String path) {
int i = path.lastIndexOf(".");
if (i == -1) {
return "";
}
String ret = path.substring(i + 1);
if (!Matchers.javaLetter().matchesAllOf(ret)) {
return "";
}
return ret;
}
public static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw propagate(e);
}
}
public static RuntimeException propagate(Throwable throwable) {
Throwables.throwIfUnchecked(throwable);
throw new RuntimeException(throwable);
}
}
| 26.449438 | 119 | 0.625573 |
24b46ca80aaade1721cf5dc75af7574005abe2ba | 125 | package org.firstinspires.ftc.teamcode.Autonomous;
public enum AutoScenes {
FULL, INTERMEDIATE1, INTERMEDIATE2, WORST
}
| 20.833333 | 50 | 0.792 |
bed604cd00e9f647de7c172a294e05163b7eac9f | 2,019 | package mnm.mods.tabbychat.api.filters;
import com.google.common.base.Strings;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* Defines the settings used by filters.
*/
public class FilterSettings {
// destinations
private final Set<String> channels = new HashSet<>();
private boolean remove;
private boolean raw = true;
private boolean regex;
private int flags;
// notifications
private boolean soundNotification = false;
private String soundName = "";
public Set<String> getChannels() {
return channels;
}
public boolean isRemove() {
return remove;
}
public void setRemove(boolean value) {
this.remove = value;
}
public boolean isRaw() {
return raw;
}
public void setRaw(boolean raw) {
this.raw = raw;
}
public boolean isRegex() {
return regex;
}
public void setRegex(boolean regex) {
this.regex = regex;
}
public boolean isCaseInsensitive() {
return getFlag(Pattern.CASE_INSENSITIVE);
}
public void setCaseInsensitive(boolean value) {
setFlag(Pattern.CASE_INSENSITIVE, value);
}
private void setFlag(int flag, boolean value) {
if (value) {
this.flags |= flag;
} else {
this.flags &= ~flag;
}
}
private boolean getFlag(int flag) {
return (flags & flag) != 0;
}
public int getFlags() {
return flags;
}
public boolean isSoundNotification() {
return soundNotification;
}
public void setSoundNotification(boolean sound) {
this.soundNotification = sound;
}
public Optional<String> getSoundName() {
return Optional.ofNullable(soundName);
}
public void setSoundName(@Nullable String soundName) {
this.soundName = Strings.isNullOrEmpty(soundName) ? null : soundName;
}
}
| 21.03125 | 77 | 0.626548 |
55554b26f47b8c32e666cf129c22ea7723dcd228 | 2,490 | package com.zup.proposta.controller;
import com.zup.proposta.consultaExterna.IntegracaoApiCartao;
import com.zup.proposta.model.AvisoViagem;
import com.zup.proposta.model.Cartao;
import com.zup.proposta.request.AvisoViagemRequest;
import com.zup.proposta.response.AvisoViagemResponse;
import com.zup.proposta.transacaoGenerica.ExecutaTransacao;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.net.URI;
@RestController
@RequestMapping("avisos")
public class AvisoViagemController {
@Autowired
private ExecutaTransacao executaTransacao;
@Autowired
private IntegracaoApiCartao aviso;
@PersistenceContext
private EntityManager manager;
@PostMapping("/{idCartao}")
@Transactional
public ResponseEntity<?> criaAvisoViagem(@PathVariable("idCartao") String idCartao, @Valid @RequestBody AvisoViagemRequest request, @RequestHeader("User-Agent") String usuario, UriComponentsBuilder builder) {
Cartao cartao = manager.find(Cartao.class, idCartao);
if (cartao == null) {
return ResponseEntity.notFound().build();
}
String ip = ((WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getRemoteAddress();
AvisoViagem avisoViagem = new AvisoViagem(request.getDestino(), request.getValidoAte(), ip, usuario);
executaTransacao.salvaEComita(avisoViagem);
try {
AvisoViagemResponse avisoViagemResponse = aviso.AvisoViagem(cartao.getId(), new AvisoViagemRequest(request.getDestino(), request.getValidoAte()));
if (avisoViagemResponse.getResultado().equals("CRIADO")) {
cartao.getAvisos().add(avisoViagem);
executaTransacao.atualizaEComita(cartao);
}
} catch (FeignException e) {
System.out.println(e);
}
URI uri = builder.path("/avisos/{id}").build(avisoViagem.getId());
return ResponseEntity.created(uri).build();
}
}
| 41.5 | 212 | 0.751004 |
0f64f9ffe59bf326393968a5edd97fe1a23d87db | 9,189 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|jaxrs
operator|.
name|provider
operator|.
name|atom
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|InputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|OutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|annotation
operator|.
name|Annotation
import|;
end_import
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|reflect
operator|.
name|Type
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|logging
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|core
operator|.
name|MediaType
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|core
operator|.
name|MultivaluedMap
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|ext
operator|.
name|MessageBodyReader
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|ws
operator|.
name|rs
operator|.
name|ext
operator|.
name|MessageBodyWriter
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|stream
operator|.
name|XMLStreamReader
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|abdera
operator|.
name|Abdera
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|abdera
operator|.
name|model
operator|.
name|Document
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|abdera
operator|.
name|model
operator|.
name|Element
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|abdera
operator|.
name|parser
operator|.
name|Parser
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|abdera
operator|.
name|parser
operator|.
name|ParserOptions
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|abdera
operator|.
name|writer
operator|.
name|Writer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|common
operator|.
name|logging
operator|.
name|LogUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|jaxrs
operator|.
name|utils
operator|.
name|ExceptionUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|staxutils
operator|.
name|StaxUtils
import|;
end_import
begin_class
specifier|public
specifier|abstract
class|class
name|AbstractAtomProvider
parameter_list|<
name|T
extends|extends
name|Element
parameter_list|>
implements|implements
name|MessageBodyWriter
argument_list|<
name|T
argument_list|>
implements|,
name|MessageBodyReader
argument_list|<
name|T
argument_list|>
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LogUtils
operator|.
name|getL7dLogger
argument_list|(
name|AbstractAtomProvider
operator|.
name|class
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Abdera
name|ATOM_ENGINE
init|=
operator|new
name|Abdera
argument_list|()
decl_stmt|;
specifier|private
name|boolean
name|autodetectCharset
decl_stmt|;
specifier|private
name|boolean
name|formattedOutput
decl_stmt|;
specifier|public
name|long
name|getSize
parameter_list|(
name|T
name|element
parameter_list|,
name|Class
argument_list|<
name|?
argument_list|>
name|type
parameter_list|,
name|Type
name|genericType
parameter_list|,
name|Annotation
index|[]
name|annotations
parameter_list|,
name|MediaType
name|mt
parameter_list|)
block|{
return|return
operator|-
literal|1
return|;
block|}
specifier|public
name|void
name|writeTo
parameter_list|(
name|T
name|element
parameter_list|,
name|Class
argument_list|<
name|?
argument_list|>
name|clazz
parameter_list|,
name|Type
name|type
parameter_list|,
name|Annotation
index|[]
name|a
parameter_list|,
name|MediaType
name|mt
parameter_list|,
name|MultivaluedMap
argument_list|<
name|String
argument_list|,
name|Object
argument_list|>
name|headers
parameter_list|,
name|OutputStream
name|os
parameter_list|)
throws|throws
name|IOException
block|{
if|if
condition|(
name|MediaType
operator|.
name|APPLICATION_JSON_TYPE
operator|.
name|isCompatible
argument_list|(
name|mt
argument_list|)
condition|)
block|{
name|Writer
name|w
init|=
name|createWriter
argument_list|(
literal|"json"
argument_list|)
decl_stmt|;
if|if
condition|(
name|w
operator|==
literal|null
condition|)
block|{
throw|throw
name|ExceptionUtils
operator|.
name|toNotSupportedException
argument_list|(
literal|null
argument_list|,
literal|null
argument_list|)
throw|;
block|}
name|element
operator|.
name|writeTo
argument_list|(
name|w
argument_list|,
name|os
argument_list|)
expr_stmt|;
block|}
elseif|else
if|if
condition|(
name|formattedOutput
condition|)
block|{
name|Writer
name|w
init|=
name|createWriter
argument_list|(
literal|"prettyxml"
argument_list|)
decl_stmt|;
if|if
condition|(
name|w
operator|!=
literal|null
condition|)
block|{
name|element
operator|.
name|writeTo
argument_list|(
name|w
argument_list|,
name|os
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|element
operator|.
name|writeTo
argument_list|(
name|os
argument_list|)
expr_stmt|;
block|}
block|}
else|else
block|{
name|element
operator|.
name|writeTo
argument_list|(
name|os
argument_list|)
expr_stmt|;
block|}
block|}
specifier|protected
name|Writer
name|createWriter
parameter_list|(
name|String
name|writerName
parameter_list|)
block|{
name|Writer
name|w
init|=
name|ATOM_ENGINE
operator|.
name|getWriterFactory
argument_list|()
operator|.
name|getWriter
argument_list|(
name|writerName
argument_list|)
decl_stmt|;
if|if
condition|(
name|w
operator|==
literal|null
condition|)
block|{
name|LOG
operator|.
name|fine
argument_list|(
literal|"Atom writer \""
operator|+
name|writerName
operator|+
literal|"\" is not available"
argument_list|)
expr_stmt|;
block|}
return|return
name|w
return|;
block|}
specifier|public
name|T
name|readFrom
parameter_list|(
name|Class
argument_list|<
name|T
argument_list|>
name|clazz
parameter_list|,
name|Type
name|t
parameter_list|,
name|Annotation
index|[]
name|a
parameter_list|,
name|MediaType
name|mt
parameter_list|,
name|MultivaluedMap
argument_list|<
name|String
argument_list|,
name|String
argument_list|>
name|headers
parameter_list|,
name|InputStream
name|is
parameter_list|)
throws|throws
name|IOException
block|{
name|Parser
name|parser
init|=
name|ATOM_ENGINE
operator|.
name|getParser
argument_list|()
decl_stmt|;
synchronized|synchronized
init|(
name|parser
init|)
block|{
name|ParserOptions
name|options
init|=
name|parser
operator|.
name|getDefaultParserOptions
argument_list|()
decl_stmt|;
if|if
condition|(
name|options
operator|!=
literal|null
condition|)
block|{
name|options
operator|.
name|setAutodetectCharset
argument_list|(
name|autodetectCharset
argument_list|)
expr_stmt|;
block|}
block|}
name|XMLStreamReader
name|reader
init|=
name|StaxUtils
operator|.
name|createXMLStreamReader
argument_list|(
name|is
argument_list|)
decl_stmt|;
name|Document
argument_list|<
name|T
argument_list|>
name|doc
init|=
name|parser
operator|.
name|parse
argument_list|(
name|reader
argument_list|)
decl_stmt|;
return|return
name|doc
operator|.
name|getRoot
argument_list|()
return|;
block|}
specifier|public
name|void
name|setFormattedOutput
parameter_list|(
name|boolean
name|formattedOutput
parameter_list|)
block|{
name|this
operator|.
name|formattedOutput
operator|=
name|formattedOutput
expr_stmt|;
block|}
specifier|public
name|void
name|setAutodetectCharset
parameter_list|(
name|boolean
name|autodetectCharset
parameter_list|)
block|{
name|this
operator|.
name|autodetectCharset
operator|=
name|autodetectCharset
expr_stmt|;
block|}
block|}
end_class
end_unit
| 13.414599 | 810 | 0.801502 |
d7d5bd7dc612b0a59058c7c26a1a831b02d8bb7e | 3,529 | package edu.cmu.graphchi.apps.util;
import edu.cmu.graphchi.*;
import edu.cmu.graphchi.datablocks.FloatConverter;
import edu.cmu.graphchi.engine.GraphChiEngine;
import edu.cmu.graphchi.engine.VertexInterval;
import edu.cmu.graphchi.preprocessing.EdgeProcessor;
import edu.cmu.graphchi.preprocessing.FastSharder;
import edu.cmu.graphchi.preprocessing.VertexProcessor;
import java.io.*;
import java.util.logging.Logger;
/**
* Creates a cassovary adjacency
* @author Aapo Kyrola
*/
public class CreateCassovary implements GraphChiProgram<Integer, Integer> {
private static Logger logger = ChiLogger.getLogger("cassovaryconv");
private BufferedOutputStream bos;
@Override
public void update(ChiVertex<Integer, Integer> vertex, GraphChiContext context) {
try {
if (vertex.numOutEdges() > 0) {
synchronized(this) {
bos.write((context.getVertexIdTranslate().backward(vertex.getId()) + " " + vertex.numOutEdges() + "\n").getBytes());
for(int i=0; i < vertex.numOutEdges(); i++) {
bos.write((context.getVertexIdTranslate().backward(vertex.outEdge(i).getVertexId()) + "\n").getBytes());
}
}
}
} catch (IOException ioe) {}
}
@Override
public void beginIteration(GraphChiContext ctx) {
}
@Override
public void endIteration(GraphChiContext ctx) {
}
@Override
public void beginInterval(GraphChiContext ctx, VertexInterval interval) {
}
@Override
public void endInterval(GraphChiContext ctx, VertexInterval interval) {
}
@Override
public void beginSubInterval(GraphChiContext ctx, VertexInterval interval) {
}
@Override
public void endSubInterval(GraphChiContext ctx, VertexInterval interval) {
}
protected static FastSharder createSharder(String graphName, int numShards) throws IOException {
return new FastSharder<Integer, Integer>(graphName, numShards, null, null, null, null);
}
public static void main(String[] args) throws Exception {
String baseFilename = args[0];
int nShards = Integer.parseInt(args[1]);
String fileType = (args.length >= 3 ? args[2] : null);
/* Create shards */
FastSharder sharder = createSharder(baseFilename, nShards);
if (baseFilename.equals("pipein")) { // Allow piping graph in
sharder.shard(System.in, fileType);
} else {
if (!new File(ChiFilenames.getFilenameIntervals(baseFilename, nShards)).exists()) {
sharder.shard(new FileInputStream(new File(baseFilename)), fileType);
} else {
logger.info("Found shards -- no need to preprocess");
}
}
/* Run GraphChi */
GraphChiEngine<Integer, Integer> engine = new GraphChiEngine<Integer, Integer>(baseFilename, nShards);
engine.setEdataConverter(null);
engine.setVertexDataConverter(null);
engine.setModifiesInedges(false); // Important optimization
engine.setDisableInedges(true);
engine.setModifiesOutedges(false);
engine.setOnlyAdjacency(true);
CreateCassovary cassovaryConv = new CreateCassovary();
cassovaryConv.bos = new BufferedOutputStream(new FileOutputStream(baseFilename + ".cassovary"));
engine.run(cassovaryConv, 1);
cassovaryConv.bos.flush();
cassovaryConv.bos.close();
logger.info("Ready.");
}
}
| 34.598039 | 136 | 0.65826 |
16aa872d6d258f9b6b4db51bccfb33ae185501f2 | 1,002 | package ru.hh.oauth.subscribe.apis.google;
import ru.hh.oauth.subscribe.core.model.Token;
public class GoogleToken extends Token {
/**
* Id_token is part of OpenID Connect specification. It can hold user information that you can directly extract without additional request to
* provider. See http://openid.net/specs/openid-connect-core-1_0.html#id_token-tokenExample and
* https://bitbucket.org/nimbusds/nimbus-jose-jwt/wiki/Home
*
* Here will be encoded and signed id token in JWT format or null, if not defined.
*/
private final String openIdToken;
public GoogleToken(final String token, final String secret, final String rawResponse, final String openIdToken) {
super(token, secret, rawResponse);
this.openIdToken = openIdToken;
}
@Override
public String toString() {
return String.format("GoogleToken{'token'='%s', 'secret'='%s', 'openIdToken'='%s']", getToken(), getSecret(),
openIdToken);
}
}
| 37.111111 | 145 | 0.692615 |
ae1bc6ad1f2ffb9a83ca678746a470a606ca7ec4 | 1,092 | package otherStuff;
/**
* <p>Simple class designed for communication among components of the game and the game
* progressor</p>
*
* @author Aristocrates, barbecue chef / j̶a̶r̶g̶o̶n̶ ̶s̶p̶o̶u̶t̶i̶n̶g̶ ̶m̶a̶n̶i̶a̶c̶
* part time philosopher
* @version sin(π/2)
*/
public class GameEvent
{
public static final GameEvent CARRY_ON;
public static final GameEvent COLLISION;
static {
CARRY_ON = new GameEvent("carryOn","");
COLLISION = new GameEvent("collide","");
}
private String type, command;
private GameEvent(String type, String command)
{
this.type = type;
this.command = command;
}
public GameEvent(GameEvent type, String command)
{
this.type = type.type;
this.command = command;
}
public String toString()
{
return Math.random()+"";
}
public boolean equals(Object o)
{
if (!(o instanceof GameEvent))
return false;
return type.equals(((GameEvent)o).type);
}
} | 23.234043 | 89 | 0.569597 |
4ace405140bd5d76902d9f1f646cdfa2e84a165a | 2,429 | package ru.taxi.generator.generator;
import com.google.maps.model.LatLng;
import ru.taxi.generator.address.AddressEntity;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public class ArtificialDataHelper {
public static LatLng getRandomPoint(GeneratorParametersEntity gParams) {
Random random = new Random();
double radiusInDegrees = gParams.getRad() / 111320f;
double w = radiusInDegrees * Math.sqrt(random.nextDouble());
double t = 2 * Math.PI * random.nextDouble();
double new_x = w * Math.cos(t) / Math.cos(Math.toRadians(gParams.getLat()));
double foundLatitude = gParams.getLat() + w * Math.sin(t);
double foundLongitude = gParams.getLng() + new_x;
return new LatLng(foundLatitude, foundLongitude);
}
public static LocalDate getDate(LocalDate left, LocalDate right) {
if (left == right) {
return left;
}
long randomDay = ThreadLocalRandom.current().nextLong(left.toEpochDay(), right.toEpochDay());
return LocalDate.ofEpochDay(randomDay);
}
public static LocalTime getTime() {
LocalTime l = LocalTime.MIN;
LocalTime r = LocalTime.MAX;
long randomTime = ThreadLocalRandom.current().nextLong(l.toNanoOfDay(), r.toNanoOfDay());
return LocalTime.ofNanoOfDay(randomTime);
}
public static boolean validateAddress(AddressEntity ae) {
return !(Objects.nonNull(ae) && ae.getCity() != null);
}
public static LatLng generatePointIntoCircle(LatLng center, int radius) {
Random random = new Random();
// Convert radius from meters to degrees
double radiusInDegrees = radius / 111000f;
double u = random.nextDouble();
double v = random.nextDouble();
double w = radiusInDegrees * Math.sqrt(u);
double t = 2 * Math.PI * v;
double x = w * Math.cos(t);
double y = w * Math.sin(t);
// Adjust the x-coordinate for the shrinking of the east-west distances
double new_x = x / Math.cos(center.lat);
double foundLongitude = new_x + center.lng;
double foundLatitude = y + center.lat;
System.out.println("Longitude: " + foundLongitude + " Latitude: " + foundLatitude);
return new LatLng(foundLatitude, foundLongitude);
}
}
| 36.80303 | 101 | 0.661177 |
768f5083a7629269c04298bb5cca35d94d323401 | 4,527 | package org.batfish.datamodel;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/** A static route */
public class StaticRoute extends AbstractRoute {
static final long DEFAULT_STATIC_ROUTE_METRIC = 0L;
private static final String PROP_NEXT_HOP_INTERFACE = "nextHopInterface";
private static final long serialVersionUID = 1L;
private final int _administrativeCost;
private final long _metric;
@Nonnull private final String _nextHopInterface;
@Nonnull private final Ip _nextHopIp;
private final int _tag;
@JsonCreator
private static StaticRoute jsonCreator(
@Nullable @JsonProperty(PROP_NETWORK) Prefix network,
@Nullable @JsonProperty(PROP_NEXT_HOP_IP) Ip nextHopIp,
@Nullable @JsonProperty(PROP_NEXT_HOP_INTERFACE) String nextHopInterface,
@JsonProperty(PROP_ADMINISTRATIVE_COST) int administrativeCost,
@JsonProperty(PROP_METRIC) long metric,
@JsonProperty(PROP_TAG) int tag) {
return new StaticRoute(
requireNonNull(network), nextHopIp, nextHopInterface, administrativeCost, metric, tag);
}
private StaticRoute(
@Nonnull Prefix network,
@Nullable Ip nextHopIp,
@Nullable String nextHopInterface,
int administrativeCost,
long metric,
int tag) {
super(network);
checkArgument(
administrativeCost >= 0, "Invalid admin distance for static route: %d", administrativeCost);
_administrativeCost = administrativeCost;
_metric = metric;
_nextHopInterface = firstNonNull(nextHopInterface, Route.UNSET_NEXT_HOP_INTERFACE);
_nextHopIp = firstNonNull(nextHopIp, Route.UNSET_ROUTE_NEXT_HOP_IP);
_tag = tag;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof StaticRoute)) {
return false;
}
StaticRoute rhs = (StaticRoute) o;
return Objects.equals(_network, rhs._network)
&& _administrativeCost == rhs._administrativeCost
&& Objects.equals(_nextHopIp, rhs._nextHopIp)
&& Objects.equals(_nextHopInterface, rhs._nextHopInterface)
&& _tag == rhs._tag;
}
@Override
@JsonIgnore(false)
@JsonProperty(PROP_ADMINISTRATIVE_COST)
public int getAdministrativeCost() {
return _administrativeCost;
}
@Override
@JsonIgnore(false)
@JsonProperty(PROP_METRIC)
public Long getMetric() {
return _metric;
}
@Nonnull
@Override
@JsonIgnore(false)
@JsonProperty(PROP_NEXT_HOP_INTERFACE)
public String getNextHopInterface() {
return _nextHopInterface;
}
@Nonnull
@JsonIgnore(false)
@JsonProperty(PROP_NEXT_HOP_IP)
@Override
public Ip getNextHopIp() {
return _nextHopIp;
}
@Override
public RoutingProtocol getProtocol() {
return RoutingProtocol.STATIC;
}
@Override
@JsonIgnore(false)
@JsonProperty(PROP_TAG)
public int getTag() {
return _tag;
}
public static Builder builder() {
return new Builder();
}
@Override
public int hashCode() {
return Objects.hash(_administrativeCost, _metric, _nextHopInterface, _nextHopIp, _tag);
}
@Override
protected final String protocolRouteString() {
return " tag:" + _tag;
}
@Override
public int routeCompare(@Nonnull AbstractRoute rhs) {
return 0;
}
/** Builder for {@link StaticRoute} */
public static final class Builder extends AbstractRouteBuilder<Builder, StaticRoute> {
private int _administrativeCost = Route.UNSET_ROUTE_ADMIN;
private String _nextHopInterface = Route.UNSET_NEXT_HOP_INTERFACE;
private Builder() {}
@Override
public StaticRoute build() {
return new StaticRoute(
getNetwork(),
getNextHopIp(),
_nextHopInterface,
_administrativeCost,
getMetric(),
getTag());
}
@Override
protected Builder getThis() {
return this;
}
public Builder setAdministrativeCost(int administrativeCost) {
_administrativeCost = administrativeCost;
return this;
}
public Builder setNextHopInterface(String nextHopInterface) {
_nextHopInterface = nextHopInterface;
return this;
}
}
}
| 26.319767 | 100 | 0.71681 |
67f55b1f9fad723389e2298d51bafe8c555bf275 | 10,894 | package uk.co.omegaprime.mdbi;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/** Functions for creating useful instances of {@link BatchRead}. */
public class BatchReads {
private BatchReads() {}
/** Returns the first row of the {@code ResultSet}, and throws {@code NoSuchElementException} if no such row exists. */
public static <T> BatchRead<T> first(Class<T> klass) {
return first(new ContextRead<>(klass));
}
/** Returns the first row of the {@code ResultSet}, and throws {@code NoSuchElementException} if no such row exists. */
public static <T> BatchRead<T> first(Read<T> read) {
return (ctxt, rs) -> {
if (rs.next()) {
return read.bind(ctxt).get(rs, IndexRef.create());
} else {
throw new NoSuchElementException();
}
};
}
/** Returns the first row of the {@code ResultSet}, or null if no such row exists. */
public static <T> BatchRead<T> firstOrNull(Class<T> klass) {
return firstOrNull(new ContextRead<>(klass));
}
/** Returns the first row of the {@code ResultSet}, or null if no such row exists. */
public static <T> BatchRead<T> firstOrNull(Read<T> read) {
return (ctxt, rs) -> rs.next() ? read.bind(ctxt).get(rs, IndexRef.create()) : null;
}
public static <T> BatchRead<List<T>> asList(Class<T> klass) {
return asList(new ContextRead<>(klass));
}
public static <T> BatchRead<List<T>> asList(Read<T> read) {
return new CollectionBatchRead<>(ArrayList::new, read);
}
public static <T> BatchRead<Set<T>> asSet(Class<T> klass) {
return asSet(new ContextRead<>(klass));
}
public static <T> BatchRead<Set<T>> asSet(Read<T> read) {
return new CollectionBatchRead<>(LinkedHashSet::new, read);
}
/** Return the {@code ResultSet} as a map, failing if any key occurs more than once */
public static <K, V> BatchRead<Map<K, V>> asMap(Class<K> keyClass, Class<V> valueClass) {
return asMap(new ContextRead<>(keyClass), new ContextRead<>(valueClass));
}
/** Return the {@code ResultSet} as a map, failing if any key occurs more than once */
public static <K, V> BatchRead<Map<K, V>> asMap(Read<K> readKey, Read<V> readValue) {
return new MapBatchRead<>(LinkedHashMap::new, BatchReads::appendFail, readKey, readValue);
}
private static <K, V> V appendFail(K key, V oldValue, V newValue) {
throw new IllegalArgumentException("Key " + key + " occurs more than once in result, associated with both " + oldValue + " and " + newValue);
}
/** Return the {@code ResultSet} as a map, using the first value encountered for any given key */
public static <K, V> BatchRead<Map<K, V>> asMapFirst(Class<K> keyClass, Class<V> valueClass) {
return asMapFirst(new ContextRead<>(keyClass), new ContextRead<>(valueClass));
}
/** Return the {@code ResultSet} as a map, using the first value encountered for any given key */
public static <K, V> BatchRead<Map<K, V>> asMapFirst(Read<K> readKey, Read<V> readValue) {
return new MapBatchRead<>(LinkedHashMap::new, (_key, od, _nw) -> od, readKey, readValue);
}
/** Return the {@code ResultSet} as a map, using the last value encountered for any given key */
public static <K, V> BatchRead<Map<K, V>> asMapLast(Class<K> keyClass, Class<V> valueClass) {
return asMapLast(new ContextRead<>(keyClass), new ContextRead<>(valueClass));
}
/** Return the {@code ResultSet} as a map, using the last value encountered for any given key */
public static <K, V> BatchRead<Map<K, V>> asMapLast(Read<K> readKey, Read<V> readValue) {
return new MapBatchRead<>(LinkedHashMap::new, (_key, _od, nw) -> nw, readKey, readValue);
}
/** Return the {@code ResultSet} as a map, allowing multiple values for any given key */
public static <K, V> BatchRead<Map<K, List<V>>> asMultiMap(Class<K> keyClass, Class<V> valueClass) {
return asMultiMap(new ContextRead<>(keyClass), new ContextRead<>(valueClass));
}
/** Return the {@code ResultSet} as a map, allowing multiple values for any given key */
@SuppressWarnings("unchecked")
public static <K, V> BatchRead<Map<K, List<V>>> asMultiMap(Read<K> readKey, Read<V> readValue) {
return new MapBatchRead<>(LinkedHashMap::new, BatchReads::appendListHack, readKey, (Read<List<V>>)(Read)Reads.map(List.class, readValue, (V v) -> new ArrayList<V>(Collections.singletonList(v))));
}
/** Return the {@code ResultSet} as a {@code NavigableMap}, allowing multiple values for any given key */
@SuppressWarnings("unchecked")
public static <K, V> BatchRead<NavigableMap<K, List<V>>> asNavigableMultiMap(Class<K> keyClass, Class<V> valueClass) {
return asNavigableMultiMap(new ContextRead<>(keyClass), new ContextRead<>(valueClass));
}
/** Return the {@code ResultSet} as a {@code NavigableMap}, allowing multiple values for any given key */
@SuppressWarnings("unchecked")
public static <K, V> BatchRead<NavigableMap<K, List<V>>> asNavigableMultiMap(Read<K> readKey, Read<V> readValue) {
return new MapBatchRead<>(TreeMap::new, BatchReads::appendListHack, readKey, (Read<List<V>>)(Read)Reads.map(List.class, readValue, (V v) -> new ArrayList<V>(Collections.singletonList(v))));
}
// Bit dodgy because correctness depends crucially on how we are called
private static <K, V> List<V> appendListHack(K key, List<V> od, List<V> nw) {
if (nw.size() != 1) throw new IllegalStateException("This really shouldn't happen..");
od.add(nw.get(0));
return od;
}
/** As {@link #asMap(Read, BatchRead)} but simply reads the key using the {@code Context}-default read instance for the class */
public static <K, V> BatchRead<Map<K, V>> asMap(Class<K> readKey, BatchRead<V> readValue) {
return asMap(Reads.useContext(readKey), readValue);
}
/**
* Splits the {@code ResultSet} into contiguous runs based on equality of the supplied key type. Reads the remaining
* columns in each segment using the supplied {@code BatchRead}.
* <p>
* So for example, {@code asMap(key, value)} is equivalent to {@code segmented(key, first(value)}, and {@code asMultiMap(key, value)}
* is equivalent to {@code segmented(key, asList(value)} in the case where the {@code ResultSet} is sorted by the key columns.
* <p>
* If a key occurs non-contiguously then {@code IllegalArgumentException} will be thrown.
*/
public static <K, V> BatchRead<Map<K, V>> asMap(Read<K> readKey, BatchRead<V> readValue) {
return new SegmentedMapBatchRead<>(LinkedHashMap::new, BatchReads::appendFail, readKey, readValue);
}
/** As {@link #asMapFirst(Read, BatchRead)} but simply reads the key using the {@code Context}-default read instance for the class */
public static <K, V> BatchRead<Map<K, V>> asMapFirst(Class<K> readKey, BatchRead<V> readValue) {
return asMapFirst(Reads.useContext(readKey), readValue);
}
/** As {@link #asMap(Read, BatchRead)} but returns the value associated with the first occurrence of a given key instead of failing. */
public static <K, V> BatchRead<Map<K, V>> asMapFirst(Read<K> readKey, BatchRead<V> readValue) {
return new SegmentedMapBatchRead<>(LinkedHashMap::new, (_key, od, _nw) -> od, readKey, readValue);
}
/** As {@link #asMapLast(Read, BatchRead)} but simply reads the key using the {@code Context}-default read instance for the class */
public static <K, V> BatchRead<Map<K, V>> asMapLast(Class<K> readKey, BatchRead<V> readValue) {
return asMapLast(Reads.useContext(readKey), readValue);
}
/** As {@link #asMap(Read, BatchRead)} but returns the value associated with the first occurrence of a given key instead of failing. */
public static <K, V> BatchRead<Map<K, V>> asMapLast(Read<K> readKey, BatchRead<V> readValue) {
return new SegmentedMapBatchRead<>(LinkedHashMap::new, (_key, _od, nw) -> nw, readKey, readValue);
}
/** As {@link #asMultiMap(Read, BatchRead)} but simply reads the key using the {@code Context}-default read instance for the class */
public static <K, V> BatchRead<Map<K, List<V>>> asMultiMap(Class<K> readKey, BatchRead<V> readValue) {
return asMultiMap(Reads.useContext(readKey), readValue);
}
/** As {@link #asMap(Read, BatchRead)} but returns all values associated with the a given key instead of failing. */
@SuppressWarnings("unchecked")
public static <K, V> BatchRead<Map<K, List<V>>> asMultiMap(Read<K> readKey, BatchRead<V> readValue) {
return new SegmentedMapBatchRead<>(LinkedHashMap::new, BatchReads::appendListHack, readKey, (BatchRead<List<V>>)(BatchRead)BatchReads.map(readValue, (V v) -> new ArrayList<V>(Collections.singletonList(v))));
}
public static <U, V> BatchRead<V> map(BatchRead<U> read, Function<U, V> f) {
return (ctxt, rs) -> f.apply(read.get(ctxt, rs));
}
/**
* Returns the {@code ResultSet} interpreted as an array of column vectors.
* <p>
* The classes specify the element types of the column vectors. So if you call {@code matrix(String.class, int.class)}
* then your {@code ResultSet} will be turned into an {@code Object[]} with two elements: a {@code String[]} and a {@code int[]}.
*/
public static BatchRead<Object[]> matrix(Class<?>... klasses) {
return matrix(Arrays.asList(klasses).stream().map(ContextRead::new).collect(Collectors.toList()));
}
/** As {@link #matrix(Class[])}, but for the case where you want to be explicit about how the columns are constructed. */
public static BatchRead<Object[]> matrix(Collection<Read<?>> reads) {
return new MatrixBatchRead(reads);
}
/**
* Returns the {@code ResultSet} interpreted as a map of column names to column vectors.
* <p>
* The classes specify the element types of the column vectors. So if you call {@code matrix(String.class, int.class)}
* then your {@code ResultSet} will be turned into a {@code Map} with two elements: a {@code String[]} and a {@code int[]}.
* <p>
* If a {@code Read} instance spans more than one column, the name chosen will be that of the first column.
*/
public static BatchRead<Map<String, Object>> labelledMatrix(Class<?>... klasses) {
return labelledMatrix(Arrays.asList(klasses).stream().map(ContextRead::new).collect(Collectors.toList()));
}
/** As {@link #labelledMatrix(Class[])}, but for the case where you want to be explicit about how the columns are constructed. */
public static BatchRead<Map<String, Object>> labelledMatrix(Collection<Read<?>> reads) {
return new LabelledMatrixBatchRead(reads);
}
}
| 53.930693 | 215 | 0.668166 |
493e5bcc3d3d1feda95cca455f01a9a6ff84a041 | 1,032 | package org.kittelson.interviewsetter;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class DisplayTextActivity extends AppCompatActivity {
public static final String CONTENT_KEY = "content";
public static final String TITLE_KEY = "title";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_text);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView contentView = findViewById(R.id.text_display);
contentView.setText(getIntent().getStringExtra(CONTENT_KEY));
contentView.setMovementMethod(new ScrollingMovementMethod());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getIntent().getStringExtra(TITLE_KEY));
}
}
| 35.586207 | 78 | 0.761628 |
634d8809f78194f3dea065bc4164653ea34a410f | 3,290 | // Copyright by Barry G. Becker, 2012. Licensed under MIT License: http://www.opensource.org/licenses/MIT
package com.barrybecker4.game.twoplayer.comparison.ui.configuration;
import com.barrybecker4.game.common.GameContext;
import com.barrybecker4.game.twoplayer.common.search.options.SearchOptions;
import com.barrybecker4.game.twoplayer.common.ui.dialogs.searchoptions.SearchOptionsPanel;
import com.barrybecker4.game.twoplayer.comparison.model.config.SearchOptionsConfig;
import com.barrybecker4.ui.components.GradientButton;
import com.barrybecker4.ui.components.TextInput;
import com.barrybecker4.ui.dialogs.OptionsDialog;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* Allow for editing player search options.
*
* @author Barry Becker
*/
public class SearchOptionsDialog extends OptionsDialog {
private GradientButton okButton;
private TextInput nameField;
private SearchOptionsConfig existingOptions;
private SearchOptionsPanel searchOptionsPanel;
/** Constructor */
public SearchOptionsDialog(Component parent) {
super( parent );
showContent();
}
/**
* Constructor.
* Use this version if we want to initialize with existing options
*/
public SearchOptionsDialog(Component parent, SearchOptionsConfig options) {
super( parent );
existingOptions = options;
showContent();
}
@Override
public String getTitle() {
return GameContext.getLabel("EDIT_PLAYER_OPTIONS");
}
public SearchOptionsConfig getSearchOptionsConfig() {
return new SearchOptionsConfig(nameField.getValue(), searchOptionsPanel.getOptions());
}
@Override
public JComponent createDialogContent() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout( new BorderLayout() );
// all defaults initially.
String title = (existingOptions != null) ? existingOptions.getName() : "";
SearchOptions searchOptions =
(existingOptions != null) ? existingOptions.getSearchOptions(): new SearchOptions();
nameField = new TextInput("Configuration Name:", title, 30);
nameField.setBorder(BorderFactory.createEmptyBorder(5, 5, 10, 5));
searchOptionsPanel = new SearchOptionsPanel(searchOptions);
mainPanel.add(nameField, BorderLayout.NORTH);
mainPanel.add( searchOptionsPanel, BorderLayout.CENTER);
mainPanel.add(createButtonsPanel(), BorderLayout.SOUTH);
return mainPanel;
}
@Override
public JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel( new FlowLayout() );
okButton = new GradientButton();
initBottomButton(okButton, GameContext.getLabel("OK"), GameContext.getLabel("ACCEPT_PLAYER_OPTIONS") );
initBottomButton(cancelButton(), GameContext.getLabel("CANCEL"), GameContext.getLabel("CANCEL_EDITS") );
buttonsPanel.add(okButton);
buttonsPanel.add(cancelButton());
return buttonsPanel;
}
@Override
public void actionPerformed( ActionEvent e ) {
super.actionPerformed(e);
Object source = e.getSource();
if ( source == okButton) {
searchOptionsPanel.ok();
dispose();
}
}
}
| 32.574257 | 112 | 0.700304 |
63d37d81ab93f1e210378402384ac8912572465e | 929 | package server;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import server.control.Controller;
import shared.model.Co;
public class Main{
public Main(){
}
public static void main(String[] args){
sapphire();
@SuppressWarnings("unused")
Controller controller=new Controller();
}
private static void sapphire(){
try{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}catch(UnsupportedLookAndFeelException|InstantiationException|IllegalAccessException|ClassNotFoundException ex){
Co.error("Main: lookAndFeel error");
}
UIManager.put("ProgressBar.background",Color.DARK_GRAY);
UIManager.put("ProgressBar.foreground",Color.GRAY);
UIManager.put("ProgressBar.selectionBackground",Color.WHITE);
UIManager.put("ProgressBar.selectionForeground",Color.WHITE);
UIManager.put("ComboBox.background",Color.GRAY);
}
}
| 26.542857 | 114 | 0.783638 |
e3cebd6031b759c561937d8347abcc17db73182e | 597 | package com.facebook.react.jscexecutor;
import com.facebook.jni.HybridData;
import com.facebook.react.bridge.JavaScriptExecutor;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.soloader.SoLoader;
class JSCExecutor extends JavaScriptExecutor {
private static native HybridData initHybrid(ReadableNativeMap readableNativeMap);
public String getName() {
return "JSCExecutor";
}
static {
SoLoader.loadLibrary("jscexecutor");
}
JSCExecutor(ReadableNativeMap readableNativeMap) {
super(initHybrid(readableNativeMap));
}
}
| 25.956522 | 85 | 0.755444 |
1249efb335bba3fc789636df3cb0855828833de4 | 3,324 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.security.ejb;
import java.security.Principal;
import java.util.Set;
import java.util.Iterator;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.InitialContext;
import javax.security.auth.Subject;
import org.apache.log4j.Logger;
/** Test return of a custom principal from getCallerPrincipal.
*
* @author Scott.Stark@jboss.org
* @version $Revision: 57211 $
*/
public class CustomPrincipalBean implements SessionBean
{
private static Logger log = Logger.getLogger(CustomPrincipalBean.class);
private SessionContext ctx;
public void ejbCreate()
{
}
public void ejbActivate()
{
}
public void ejbPassivate()
{
}
public void ejbRemove()
{
}
public void setSessionContext(SessionContext ctx)
{
this.ctx = ctx;
}
public boolean validateCallerPrincipal(Class type)
{
ClassLoader typeLoader = type.getClassLoader();
log.info("validateCallerPrincipal, type="+type+", loader="+typeLoader);
Principal caller = ctx.getCallerPrincipal();
log.info("caller="+caller+", class="+caller.getClass());
boolean isType = true;
if( caller.getClass().isAssignableFrom(type) == false )
{
log.error("type of caller is not: "+type);
isType = false;
}
try
{
InitialContext ctx = new InitialContext();
Subject s = (Subject) ctx.lookup("java:comp/env/security/subject");
Set principals = s.getPrincipals();
Iterator iter = principals.iterator();
while( iter.hasNext() )
{
Object p = iter.next();
ClassLoader pLoader = p.getClass().getClassLoader();
log.info("type="+p.getClass()+", loader="+pLoader);
}
Set customPrincipals = s.getPrincipals(type);
caller = (Principal) customPrincipals.iterator().next();
log.info("Subject caller="+caller+", class="+caller.getClass());
if( caller.getClass().isAssignableFrom(type) == true )
{
log.info("type of caller is: "+type);
isType = true;
}
}
catch(Exception e)
{
log.error("Failed to lookup security mgr", e);
}
return isType;
}
}
| 31.065421 | 77 | 0.66065 |
3f15fff278b0fbd377faf6ce5227c3642bd641ba | 1,663 | /*
* Created on 29/10/2006 11:07:46
*/
package net.jforum.wiki.plugins;
import java.util.Map;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.plugin.PluginException;
import com.ecyrd.jspwiki.plugin.WikiPlugin;
/**
* @author Rafael Steil
* @version $Id: InformationPlugin.java,v 1.3 2006/11/15 15:46:24 rafaelsteil Exp $
*/
public abstract class InformationPlugin implements WikiPlugin {
private static final String CMD_LINE = "_cmdline";
private static final String BODY = "_body";
private static final String TITLE = "title";
private String icon;
private String css;
protected InformationPlugin(String icon, String css)
{
this.icon = icon;
this.css = css;
}
/**
* @see com.ecyrd.jspwiki.plugin.WikiPlugin#execute(com.ecyrd.jspwiki.WikiContext, java.util.Map)
*/
public String execute(WikiContext context, Map params) throws PluginException {
StringBuffer sb = new StringBuffer(256);
String title = (String)params.get(TITLE);
String text = title == null
? (String)params.get(CMD_LINE)
: (String)params.get(BODY);
sb.append("<table class='").append(this.css).append("' cellpadding='5' width='85%'>")
.append("<tr>")
.append("<td valign='top' width='16'>")
.append("<img src='").append(context.getEngine().getBaseURL())
.append("/images/").append(this.icon).append("'></td>")
.append("<td>");
if (title != null) {
sb.append("<b>").append(context.getEngine().textToHTML(context, title)).append("</b><br>");
}
sb.append("<p>").append(context.getEngine().textToHTML(context, text)).append("</p></td>")
.append("</tr>")
.append("</table>");
return sb.toString();
}
}
| 28.186441 | 98 | 0.680096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.