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 |
|---|---|---|---|---|---|
8d8a81a7d025b2bba99b6ce1e12d053cad8ad6cc | 4,041 | package net.minecraft.block;
import java.util.Random;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
public class BlockFrostedIce extends BlockIce
{
public static final PropertyInteger AGE = PropertyInteger.create("age", 0, 3);
public BlockFrostedIce()
{
this.setDefaultState(this.blockState.getBaseState().withProperty(AGE, Integer.valueOf(0)));
}
/**
* Convert the BlockState into the correct metadata value
*/
public int getMetaFromState(IBlockState state)
{
return ((Integer)state.getValue(AGE)).intValue();
}
/**
* Convert the given metadata into a BlockState for this Block
*/
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(AGE, Integer.valueOf(MathHelper.clamp(meta, 0, 3)));
}
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
{
if ((rand.nextInt(3) == 0 || this.countNeighbors(worldIn, pos) < 4) && worldIn.getLightFromNeighbors(pos) > 11 - ((Integer)state.getValue(AGE)).intValue() - state.getLightOpacity())
{
this.slightlyMelt(worldIn, pos, state, rand, true);
}
else
{
worldIn.scheduleUpdate(pos, this, MathHelper.getInt(rand, 20, 40));
}
}
/**
* Called when a neighboring block was changed and marks that this state should perform any checks during a neighbor
* change. Cases may include when redstone power is updated, cactus blocks popping off due to a neighboring solid
* block, etc.
*/
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn, BlockPos fromPos)
{
if (blockIn == this)
{
int i = this.countNeighbors(worldIn, pos);
if (i < 2)
{
this.turnIntoWater(worldIn, pos);
}
}
}
private int countNeighbors(World p_185680_1_, BlockPos p_185680_2_)
{
int i = 0;
for (EnumFacing enumfacing : EnumFacing.values())
{
if (p_185680_1_.getBlockState(p_185680_2_.offset(enumfacing)).getBlock() == this)
{
++i;
if (i >= 4)
{
return i;
}
}
}
return i;
}
protected void slightlyMelt(World p_185681_1_, BlockPos p_185681_2_, IBlockState p_185681_3_, Random p_185681_4_, boolean p_185681_5_)
{
int i = ((Integer)p_185681_3_.getValue(AGE)).intValue();
if (i < 3)
{
p_185681_1_.setBlockState(p_185681_2_, p_185681_3_.withProperty(AGE, Integer.valueOf(i + 1)), 2);
p_185681_1_.scheduleUpdate(p_185681_2_, this, MathHelper.getInt(p_185681_4_, 20, 40));
}
else
{
this.turnIntoWater(p_185681_1_, p_185681_2_);
if (p_185681_5_)
{
for (EnumFacing enumfacing : EnumFacing.values())
{
BlockPos blockpos = p_185681_2_.offset(enumfacing);
IBlockState iblockstate = p_185681_1_.getBlockState(blockpos);
if (iblockstate.getBlock() == this)
{
this.slightlyMelt(p_185681_1_, blockpos, iblockstate, p_185681_4_, false);
}
}
}
}
}
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] {AGE});
}
public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state)
{
return ItemStack.EMPTY;
}
}
| 31.570313 | 189 | 0.611482 |
9255bfd3d0340d21f4129af357f4f62bd49791e0 | 10,768 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.widget;
import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import org.chromium.ui.base.LocalizationUtils;
import org.chromium.ui.interpolators.BakedBezierInterpolator;
/**
* An animating ImageView that is drawn on top of the progress bar. This will animate over the
* current length of the progress bar only if the progress bar is static for some amount of time.
*/
public class ToolbarProgressBarAnimatingView extends ImageView {
/** The drawable inside this ImageView. */
private final ColorDrawable mAnimationDrawable;
/** The fraction of the total time that the slow animation should take. */
private static final float SLOW_ANIMATION_FRACTION = 0.60f;
/** The fraction of the total time that the fast animation delay should take. */
private static final float FAST_ANIMATION_DELAY = 0.02f;
/** The fraction of the total time that the fast animation should take. */
private static final float FAST_ANIMATION_FRACTION = 0.38f;
/** The time between animation sequences. */
private static final int ANIMATION_DELAY_MS = 1000;
/** The width of the animating bar relative to the current width of the progress bar. */
private static final float ANIMATING_BAR_SCALE = 0.3f;
/**
* The width of the animating bar relative to the current width of the progress bar for the
* first half of the slow animation.
*/
private static final float SMALL_ANIMATING_BAR_SCALE = 0.1f;
/** The fraction of overall completion that the small animating bar should be expanded at. */
private static final float SMALL_BAR_EXPANSION_COMPLETE = 0.6f;
/** The maximum size of the animating view. */
private static final float ANIMATING_VIEW_MAX_WIDTH_DP = 400;
/** Interpolator for enter and exit animation. */
private final BakedBezierInterpolator mBezier = BakedBezierInterpolator.FADE_OUT_CURVE;
/** The current width of the progress bar. */
private float mProgressWidth;
/** The set of individual animators that constitute the whole animation sequence. */
private final AnimatorSet mAnimatorSet;
/** The animator controlling the fast animation. */
private final ValueAnimator mFastAnimation;
/** The animator controlling the slow animation. */
private final ValueAnimator mSlowAnimation;
/** Track if the animation has been canceled. */
private boolean mIsCanceled;
/** If the layout is RTL. */
private boolean mIsRtl;
/** The update listener for the animation. */
private ProgressBarUpdateListener mListener;
/** The last fraction of the animation that was drawn. */
private float mLastAnimatedFraction;
/** The last animation that received an update. */
private ValueAnimator mLastUpdatedAnimation;
/** The ratio of px to dp. */
private float mDpToPx;
/**
* An animation update listener that moves an ImageView across the progress bar.
*/
private class ProgressBarUpdateListener implements AnimatorUpdateListener {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mLastUpdatedAnimation = animation;
mLastAnimatedFraction = animation.getAnimatedFraction();
updateAnimation(mLastUpdatedAnimation, mLastAnimatedFraction);
}
}
/**
* @param context The Context for this view.
* @param height The LayoutParams for this view.
*/
public ToolbarProgressBarAnimatingView(Context context, LayoutParams layoutParams) {
super(context);
setLayoutParams(layoutParams);
mIsCanceled = true;
mIsRtl = LocalizationUtils.isLayoutRtl();
mDpToPx = getResources().getDisplayMetrics().density;
mAnimationDrawable = new ColorDrawable(Color.WHITE);
setImageDrawable(mAnimationDrawable);
mListener = new ProgressBarUpdateListener();
mAnimatorSet = new AnimatorSet();
mSlowAnimation = new ValueAnimator();
mSlowAnimation.setFloatValues(0.0f, 1.0f);
mSlowAnimation.addUpdateListener(mListener);
mFastAnimation = new ValueAnimator();
mFastAnimation.setFloatValues(0.0f, 1.0f);
mFastAnimation.addUpdateListener(mListener);
updateAnimationDuration();
mAnimatorSet.playSequentially(mSlowAnimation, mFastAnimation);
AnimatorListener listener = new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator a) {
// Replay the animation if it has not been canceled.
if (mIsCanceled) return;
// Repeats of the animation should have a start delay.
mAnimatorSet.setStartDelay(ANIMATION_DELAY_MS);
updateAnimationDuration();
// Only restart the animation if the last animation is ending.
if (a == mFastAnimation) mAnimatorSet.start();
}
};
mSlowAnimation.addListener(listener);
mFastAnimation.addListener(listener);
}
/**
* Update the duration of the animation based on the width of the progress bar.
*/
private void updateAnimationDuration() {
// If progress is <= 0, the duration is also 0.
if (mProgressWidth <= 0) return;
// Total duration: logE(progress_dp) * 200 * 1.3
long totalDuration = (long) (Math.log(mProgressWidth / mDpToPx) / Math.log(Math.E)) * 260;
if (totalDuration <= 0) return;
mSlowAnimation.setDuration((long) (totalDuration * SLOW_ANIMATION_FRACTION));
mFastAnimation.setStartDelay((long) (totalDuration * FAST_ANIMATION_DELAY));
mFastAnimation.setDuration((long) (totalDuration * FAST_ANIMATION_FRACTION));
}
/**
* Start the animation if it hasn't been already.
*/
public void startAnimation() {
mIsCanceled = false;
if (!mAnimatorSet.isStarted()) {
updateAnimationDuration();
// Set the initial start delay to 0ms so it starts immediately.
mAnimatorSet.setStartDelay(0);
// Reset position.
setScaleX(0.0f);
setTranslationX(0.0f);
mAnimatorSet.start();
// Fade in to look nice on sites that trigger many loads that end quickly.
animate().alpha(1.0f)
.setDuration(500)
.setInterpolator(BakedBezierInterpolator.FADE_IN_CURVE);
}
}
/**
* Update the animating view.
* @param animator The current running animator.
* @param animatedFraction The current fraction of completion for the animation.
*/
private void updateAnimation(ValueAnimator animator, float animatedFraction) {
if (mIsCanceled) return;
float bezierProgress = mBezier.getInterpolation(animatedFraction);
// Left and right bound change based on if the layout is RTL.
float leftBound = mIsRtl ? -mProgressWidth : 0.0f;
float rightBound = mIsRtl ? 0.0f : mProgressWidth;
float barScale = ANIMATING_BAR_SCALE;
// If the current animation is the slow animation, the bar slowly expands from 20% of the
// progress bar width to 30%.
if (animator == mSlowAnimation && animatedFraction <= SMALL_BAR_EXPANSION_COMPLETE) {
float sizeDiff = ANIMATING_BAR_SCALE - SMALL_ANIMATING_BAR_SCALE;
// Since the bar will only expand for the first 60% of the animation, multiply the
// animated fraction by 1/0.6 to get the fraction completed.
float completeFraction = (animatedFraction / SMALL_BAR_EXPANSION_COMPLETE);
barScale = SMALL_ANIMATING_BAR_SCALE + sizeDiff * completeFraction;
}
// Include the width of the animating bar in this computation so it comes from
// off-screen.
float animatingWidth = Math.min(ANIMATING_VIEW_MAX_WIDTH_DP * mDpToPx,
mProgressWidth * barScale);
float animatorCenter =
((mProgressWidth + animatingWidth) * bezierProgress) - animatingWidth / 2.0f;
if (mIsRtl) animatorCenter *= -1.0f;
// The left and right x-coordinate of the animating view.
float animatorRight = animatorCenter + (animatingWidth / 2.0f);
float animatorLeft = animatorCenter - (animatingWidth / 2.0f);
// "Clip" the view so it doesn't go past where the progress bar starts or ends.
if (animatorRight > rightBound) {
animatingWidth -= Math.abs(animatorRight - rightBound);
animatorCenter -= Math.abs(animatorRight - rightBound) / 2.0f;
} else if (animatorLeft < leftBound) {
animatingWidth -= Math.abs(animatorLeft - leftBound);
animatorCenter += Math.abs(animatorLeft - leftBound) / 2.0f;
}
setScaleX(animatingWidth);
setTranslationX(animatorCenter);
}
/**
* @return True if the animation is running.
*/
public boolean isRunning() {
return !mIsCanceled;
}
/**
* Cancel the animation.
*/
public void cancelAnimation() {
mIsCanceled = true;
mAnimatorSet.cancel();
// Reset position and alpha.
setScaleX(0.0f);
setTranslationX(0.0f);
animate().cancel();
setAlpha(0.0f);
mLastAnimatedFraction = 0.0f;
mProgressWidth = 0;
}
/**
* Update info about the progress bar holding this animating block.
* @param progressWidth The width of the contaiing progress bar.
*/
public void update(float progressWidth) {
// Since the progress bar can become visible before current progress is sent, the width
// needs to be updated even if the progess bar isn't showing. The result of not having
// this is most noticable if you rotate the device on a slow page.
mProgressWidth = progressWidth;
updateAnimation(mLastUpdatedAnimation, mLastAnimatedFraction);
}
/**
* @param color The Android color that the animating bar should be.
*/
public void setColor(int color) {
mAnimationDrawable.setColor(color);
}
}
| 38.184397 | 98 | 0.675706 |
63d84404c8d85b06a081503d1766a1a6947df646 | 3,054 | /**
* TODO
*
*
* lmf 创建于2018年11月30日
*/
package cn.obcp.user.util;
import com.google.common.base.Strings;
/**
* @author lmf
*
*/
public class CheckStrength {
/**
* 定义数据类型以及相应分数
*/
private static final int NUM = 1;
private static final int SMALL_LETTER = 2;
private static final int CAPITAL_LETTER = 3;
private static final int OTHER_CHAR = 4;
/**
* 验证字符类型,判断属于:数字,大写字母,小写字母,其他字符
* TODO
* @param c
* @return
* int
* lmf 创建于2018年11月30日
*/
private static int checkCharacterType(char c) {
if (c >= 48 && c <= 57) {
return NUM;
}
if (c >= 65 && c <= 90) {
return CAPITAL_LETTER;
}
if (c >= 97 && c <= 122) {
return SMALL_LETTER;
}
return OTHER_CHAR;
}
/**
* 返回字符串中,参数字符类型的字符数量
* TODO
* @param passwd
* @param type
* @return
* int
* lmf 创建于2018年11月30日
*/
private static int countLetter(String passwd, int type) {
int count = 0;
if (null != passwd && passwd.length() > 0) {
for (char c : passwd.toCharArray()) {
if (checkCharacterType(c) == type) {
count++;
}
}
}
return count;
}
/**
* 验证密码强度
* TODO
* @param password
* @return
* int
* lmf 创建于2018年11月30日
*/
public static int score(String password) {
int total = 0;
if(Strings.isNullOrEmpty(password)) {
return total;
}else {
int length = password.length();//长度
//int numCount = countLetter(password, 1);
int smallCount = countLetter(password, 2);
//int capitalCount = countLetter(password, 3);
// int otherCount = countLetter(password, 4);
if(length < 6 || length > 18 || smallCount == 0) { //
total = -1;
}
/*if(length >= 8) {total += 20;} // 位数大于等于8,加20分
if(numCount > 1) {total += total += 20;} //存在两个或以上数字,加20分
else if(numCount > 0) {total += 10;} //存在一个数字,加10分
if(smallCount > 1) {total += total += 20;} //存在两个或以上小写字母,加20分
else if(smallCount > 0) {total += 10;}//存在一个小写字母,加10分
if(capitalCount > 1) {total += total += 20;} //存在两个或以上大写字母 ,加20分
else if(capitalCount > 0) {total += 10;} //存在一个大写字母,加10分
if(otherCount > 1) {total += total += 25;} //存在两个或以上字母数字外的字符,加25分
else if(otherCount > 0) {total += 10;} //存在一个字母数字外的字符,加25分
if(otherCount > 0 && capitalCount > 0 && smallCount > 0 && numCount > 0) { //存在其他字符,大写,小写,数字:奖励5分
total += 5;
}else if(otherCount > 0 && numCount >0 && (capitalCount >0 || smallCount > 0)) { //存在其他字符,字母,数字,奖励三分
total += 3;
}else if(numCount > 0 && (capitalCount >0 || smallCount > 0)) { //存在 数字,字母 ,奖励2分
total += 2;
}*/
return total;
}
}
public static void main(String args[]) {
System.out.println("51d9fb3dd118fb8fd7c3be1726a8497d".length());
}
}
| 25.663866 | 108 | 0.522921 |
6eda03c1abcc9ecf1a8c8616ba81ef1abdd1a397 | 4,815 | import java.io.IOException;
import java.util.Scanner;
//TODO: Add the ability to split, this will be a little complicated because there are specific rules and the player will have two hands.
class Main {
public static void main(String[] args) {
Deck deck = new Deck();
Player dealer = new Player();
Player players[] = new Player[3];
Scanner KBIn = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
players[i] = new Player();
}
for (int i = 0; i < 3; i++) {
//Give all players two cards
players[i].hit(deck.getCard());
players[i].hit(deck.getCard());
//Allow players to place initial bets.
System.out.print("Player " + (i + 1) + "\'s bet: ");
int amount = KBIn.nextInt();
players[i].raiseBet(amount);
}
clear();
dealer.hit(deck.getCard());
do {
for (int i = 0; i < 3; i++) {
if (players[i].bust) { //Skip players who have lost.
continue; //! Probably not the best solution!
}
System.out.print("\u001b[30;41m");
System.out.println("Dealer's cards:");
dealer.hand.display();
int dealerScores[] = new int[2];
dealerScores[0] = dealer.sum()[0];
dealerScores[1] = dealer.sum()[1];
if (dealerScores[0] != dealerScores[1] && dealerScores[1] <= 21) {
System.out.println("Dealer\'s score: " + dealerScores[0] + " or " + dealerScores[1]);
}
else {
System.out.println("Dealer\'s score: " + dealerScores[0]);
}
switch (i) {
case 0: System.out.print("\u001b[33;40m"); break;
case 1: System.out.print("\u001b[32;40m"); break;
case 2: System.out.print("\u001b[94;40m"); break;
}
System.out.println("\nPlayer " + (i + 1));
System.out.println("Your bet: " + players[i].bet);
System.out.println("\nYour cards:");
players[i].hand.display();
int scores[] = new int[2];
scores[0] = players[i].sum()[0];
scores[1] = players[i].sum()[1];
System.out.print("\n");
if (scores[0] != scores[1] && scores[1] <= 21) {
System.out.println("Your score is: " + scores[0] + " or " + scores[1]);
}
else {
System.out.println("Your score is: " + scores[0]);
}
if (!players[i].standing) {
System.out.println("Options:");
System.out.println("1. Hit");
System.out.println("2. Stand");
System.out.println("3. Raise bet");
int choice = KBIn.nextInt();
switch (choice) {
case 1: players[i].hit(deck.getCard()); break;
case 2: players[i].standing = true; break;
case 3:
System.out.print("Amount: ");
int amount = KBIn.nextInt();
players[i].raiseBet(amount);
break;
default: System.out.print("ERROR"); return; //TODO: Add better input handling
}
}
if (players[i].sum()[0] > 21) {
players[i].bust = true;
}
clear();
}
dealer.hit(deck.getCard());
if (dealer.sum()[0] > 21) {
System.out.println("The Dealer busted!");
return;
}
} while(dealer.sum()[0] <= 17 && dealer.sum()[1] <= 17);
System.out.println("\u001bcGame Over");
for (int i = 0; i < 3; i++) {
if (!players[i].bust) {
int dealerScores[] = new int[2];
dealerScores[0] = dealer.sum()[0];
dealerScores[1] = dealer.sum()[1];
int scores[] = new int[2];
scores[0] = players[i].sum()[0];
scores[1] = players[i].sum()[1];
if (scores[0] > dealerScores[0] || scores[1] > dealerScores[0]) {
System.out.println("Player " + (i + 1) + " got back " + players[i].bet*1.5);
}
}
}
}
static void clear() {
System.out.print("\u001b[2J");
System.out.print("\u001b[0;0H");
}
} | 36.203008 | 136 | 0.425545 |
2169ceeca436a71fa41ea1d5fe4caddf79373467 | 4,101 | /*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.log;
import org.junit.Before;
import org.junit.Test;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* 消息辅助类的测试用例.
*
* @author 小流氓[176543888@qq.com]
* @since 3.4
*/
@ThreadSafe
public class MessageHelperTest {
private RuntimeException exception = new RuntimeException("测试异常");
private Date now = new Date();
@Before
public void setUp() throws Exception {
}
@Test
public void testPreprocessingEnteringLogThreadBefore() {
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(null), null);
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(1), Integer.valueOf(1));
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(now), now);
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore("123"), "123");
Character character = new Character('!');
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(character), character);
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(exception), exception);
MessageHelperTest test = new MessageHelperTest();
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(test), test);
byte[] array = new byte[]{1, 2, 3};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(array), "[1, 2, 3]");
short[] shortArray = new short[]{1, 2, 3};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(shortArray), "[1, 2, 3]");
int[] intArray = new int[]{1, 2, 3};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(intArray), "[1, 2, 3]");
long[] longArray = new long[]{1, 2, 3};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(longArray), "[1, 2, 3]");
float[] floatArray = new float[]{1, 2, 3};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(floatArray), "[1.0, 2.0, 3.0]");
double[] doubleArray = new double[]{1, 2, 3};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(doubleArray), "[1.0, 2.0, 3.0]");
String[] stringArray = new String[]{"1", "2", "3"};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(stringArray), "[1, 2, 3]");
Object[] objectArray = new Object[]{"1", 2, "3"};
assertEquals(MessageHelper.preprocessingEnteringLogThreadBefore(objectArray), "[1, 2, 3]");
}
@Test
public void testAppend() {
StringBuilder sb = new StringBuilder();
MessageHelper.append(sb, null);
assertEquals(sb.toString(), "null");
sb.setLength(0);
MessageHelper.append(sb, exception);
assertNotEquals(sb.toString(), "null");
sb.setLength(0);
SimpleDateFormat pattern = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
MessageHelper.append(sb, now);
assertEquals(sb.toString(), pattern.format(now));
sb.setLength(0);
MessageHelper.append(sb, "123");
assertEquals(sb.toString(), "123");
sb.setLength(0);
RuntimeException exception = new RuntimeException("测试异常") {
private static final long serialVersionUID = 1L;
@Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
throw new RuntimeException("假装他会出异常");
}
};
MessageHelper.append(sb, exception);
// xyz.noark.log.MessageHelperTest$1: 测试异常
assertNotEquals(sb.toString(), "null");
sb.setLength(0);
}
}
| 35.051282 | 105 | 0.67642 |
34e3bdfa13314ff2b948f391d6cdfa05d40232af | 1,739 | package test;
import java.io.File;
import java.net.URL;
/**
* @author aloha_world_
* @date 2016年9月15日 下午12:30:15
* @version v1.00
* @description
*/
public class CreateFolder {
public static void main(String[] args) throws Exception {
creatFolder();
}
public static void creatFolder() {
File file = new File("C:/Users/aloha/Desktop/BigTalkDesignPattenSourceCode");
String targetFolder=System.getProperty("user.dir")+File.separator+"src";
File[] files = file.listFiles();
for (File f : files) {
String fileName = f.getName();
System.out.println(targetFolder+File.separator+fileName);
File newFile=new File(targetFolder+File.separator+fileName);
newFile.mkdir();
}
}
public static void testGetPath() throws Exception {
// 第一种:获取类加载的根路径 D:\git\daotie\daotie\target\classes
File f = new File(CreateFolder.class.getResource("/").getPath());
System.out.println(f);
// 获取当前类的所在工程路径; 如果不加“/” 获取当前类的加载目录
// D:\git\daotie\daotie\target\classes\my
File f2 = new File(CreateFolder.class.getResource("").getPath());
System.out.println(f2);
// 第二种:获取项目路径 D:\git\daotie\daotie
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println(courseFile);
// 第三种: file:/D:/git/daotie/daotie/target/classes/
URL xmlpath = CreateFolder.class.getClassLoader().getResource("");
System.out.println(xmlpath);
// 第四种: D:\git\daotie\daotie
System.out.println(System.getProperty("user.dir"));
/*
* 结果: C:\Documents and Settings\Administrator\workspace\projectName
* 获取当前工程路径
*/
// 第五种: 获取所有的类路径 包括jar包的路径
System.out.println(System.getProperty("java.class.path"));
}
}
| 28.508197 | 80 | 0.682001 |
65d4ad7afbb763ecad393696ea16c55dae04d64d | 320 | package org.jetio;
import java.nio.ByteBuffer;
import java.util.Collection;
/**
* A place to get {@link ByteBuffer} instances from
*
* @author <a href="mailto:peter.royal@pobox.com">peter royal</a>
*/
public interface BufferSource {
ByteBuffer acquire();
void release( Collection<ByteBuffer> buffers );
}
| 20 | 65 | 0.7125 |
43b75526ed8f7159d0d247d47315ad18839ab390 | 5,882 | package org.ofbiz.base.util;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* SCIPIO: Utilities for implementing and using {@link PropertyMessageEx}.
*/
public abstract class PropertyMessageExUtil {
public static final String MSG_INTRO_DELIM = ": ";
protected PropertyMessageExUtil() {
}
/**
* SCIPIO: Safely makes a PropertyMessage list for storage in an exception.
* If null given, returns null.
*/
public static List<PropertyMessage> makePropertyMessageList(Collection<?> messages) {
return PropertyMessage.makeListAutoSafe(messages);
}
/**
* SCIPIO: Safely makes a PropertyMessage list for storage in an exception.
* The argument can be a single message or collection.
* If null given, returns null.
*/
public static List<PropertyMessage> makePropertyMessageList(Object messageOrList) {
return PropertyMessage.makeListAutoSafe(messageOrList);
}
/**
* Returns the localized property exception message, or fallback on non-localized detail message.
*/
public static String getExceptionMessage(Throwable t, Locale locale) {
if (t instanceof PropertyMessageEx) {
PropertyMessageEx propEx = (PropertyMessageEx) t;
String message = propEx.getPropertyMessage().getMessage(locale);
if (UtilValidate.isNotEmpty(message)) return message;
}
return t.getMessage();
}
/**
* Returns the localized property exception message, or fallback on non-localized detail message.
*/
public static String getExceptionMessage(Throwable t, Map<String, ?> context) {
return getExceptionMessage(t, PropertyMessage.getLocale(context));
}
/**
* Returns the localized property exception message list, or null if none.
*/
public static List<String> getExceptionMessageList(Throwable t, Locale locale) {
if (t instanceof PropertyMessageEx) {
PropertyMessageEx propEx = (PropertyMessageEx) t;
return PropertyMessage.getMessages(propEx.getPropertyMessageList(), locale);
}
return null;
}
/**
* Returns the localized property exception message list, or null if none.
*/
public static List<String> getExceptionMessageList(Throwable t, Map<String, ?> context) {
return getExceptionMessageList(t, PropertyMessage.getLocale(context));
}
/**
* Returns the property exception message in log locale (english), or fallback on non-localized detail message.
* NOTE: Depending on the exception implementation, this may be redundant, and in some cases
* it can be better to simply call {@code t.getMessage()} instead of this.
*/
public static String getLogLocaleExceptionMessage(Throwable t) {
if (t instanceof PropertyMessageEx) {
PropertyMessageEx propEx = (PropertyMessageEx) t;
String message = propEx.getPropertyMessage().getMessage(PropertyMessage.getLogLocale());
if (UtilValidate.isNotEmpty(message)) return message;
}
return t.getMessage();
}
/**
* Returns the property exception message in exception locale (english), or fallback on non-localized detail message.
* NOTE: Depending on the exception implementation, this may be redundant, and in some cases
* it can be better to simply call {@code t.getMessage()} instead of this.
*/
public static String getDefExLocaleExceptionMessage(Throwable t) {
if (t instanceof PropertyMessageEx) {
PropertyMessageEx propEx = (PropertyMessageEx) t;
String message = propEx.getPropertyMessage().getMessage(PropertyMessage.getDefExLocale());
if (UtilValidate.isNotEmpty(message)) return message;
}
return t.getMessage();
}
/**
* Makes a localized service message from the given message intro plus the property message from the exception OR
* detail message if none (abstraction).
* Does NOT include any message lists the exception may contain (use {@link #makeServiceMessageList}).
*/
public static String makeServiceMessage(PropertyMessage messageIntro, Throwable t, Locale locale) {
return PropertyMessage.combineMessages(locale, MSG_INTRO_DELIM, messageIntro, getExceptionMessage(t, locale));
}
/**
* Makes a localized service message from the given message intro plus the property message from the exception OR
* detail message if none (abstraction).
* Does NOT include any message lists the exception may contain (use {@link #makeServiceMessageList}).
*/
public static String makeServiceMessage(String messageIntro, Throwable t, Locale locale) {
return makeServiceMessage(PropertyMessage.makeFromStatic(messageIntro), t, locale);
}
/**
* Extracts any message lists from the exception and localizes them for service message list (abstraction).
*/
public static List<String> makeServiceMessageList(Throwable t, Locale locale) {
return getExceptionMessageList(t, locale);
}
/**
* Makes a log-language (english) message from the given message intro plus the property message from the exception OR
* detail message if none (abstraction).
*/
public static String makeLogMessage(PropertyMessage messageIntro, Throwable t) {
return PropertyMessage.combineLogMessages(MSG_INTRO_DELIM, messageIntro, getLogLocaleExceptionMessage(t));
}
/**
* Makes a log-language (english) message from the given message intro plus the property message from the exception OR
* detail message if none (abstraction).
*/
public static String makeLogMessage(String messageIntro, Throwable t) {
return makeLogMessage(PropertyMessage.makeFromStatic(messageIntro), t);
}
} | 41.716312 | 122 | 0.701462 |
21f5c49b5b025d73c172ed3a84f6b2cff6fda7b4 | 1,520 | package at.fhjoanneum.ippr.commons.dto.processengine.stateobject;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class BusinessObjectFieldDTO implements Serializable {
private static final long serialVersionUID = -2396191843338173896L;
private Long bofmId;
private Long bofiId;
private String name;
private String type;
private boolean required;
private boolean readonly;
private String value;
private int indent;
public BusinessObjectFieldDTO() {}
public BusinessObjectFieldDTO(final Long bofmId, final Long bofiId, final String name,
final String type, final boolean required, final boolean readonly, final String value,
final int indent) {
this.bofmId = bofmId;
this.bofiId = bofiId;
this.name = name;
this.type = type;
this.required = required;
this.readonly = readonly;
this.value = value;
this.indent = indent;
}
public Long getBofmId() {
return bofmId;
}
public Long getBofiId() {
return bofiId;
}
public boolean isReadonly() {
return readonly;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public boolean isRequired() {
return required;
}
public String getValue() {
return value;
}
public int getIndent() {
return indent;
}
public void setValue(final String value) {
this.value = value;
}
}
| 20.821918 | 93 | 0.665132 |
d71fc6455c6e919101dbab98feaaaa4a386e0ca3 | 2,372 | package artisynth.demos.tutorial;
import java.awt.Color;
import artisynth.core.gui.ControlPanel;
import artisynth.core.materials.SimpleAxialMuscle;
import artisynth.core.mechmodels.FrameMarker;
import artisynth.core.mechmodels.MechModel;
import artisynth.core.mechmodels.MultiPointMuscle;
import artisynth.core.mechmodels.Particle;
import artisynth.core.mechmodels.RigidBody;
import artisynth.core.workspace.RootModel;
import maspack.matrix.Point3d;
import maspack.render.RenderProps;
public class ViaPointMuscle extends RootModel {
protected static double size = 1.0;
public void build (String[] args) {
MechModel mech = new MechModel ("mech");
addModel (mech);
mech.setFrameDamping (1.0); // set damping parameters
mech.setRotaryDamping (0.1);
// create block to which muscle will be attached
RigidBody block = RigidBody.createBox (
"block", /*widths=*/1.0, 1.0, 1.0, /*density=*/1.0);
mech.addRigidBody (block);
// create muscle start and end points
Particle p0 = new Particle (/*mass=*/0.1, /*x,y,z=*/-3.0, 0, 0.5);
p0.setDynamic (false);
mech.addParticle (p0);
Particle p1 = new Particle (/*mass=*/0.1, /*x,y,z=*/3.0, 0, 0.5);
p1.setDynamic (false);
mech.addParticle (p1);
// create markers to serve as via points
FrameMarker via0 = new FrameMarker();
mech.addFrameMarker (via0, block, new Point3d (-0.5, 0, 0.5));
FrameMarker via1 = new FrameMarker();
mech.addFrameMarker (via1, block, new Point3d (0.5, 0, 0.5));
// create muscle, set material, and add points
MultiPointMuscle muscle = new MultiPointMuscle ();
muscle.setMaterial (new SimpleAxialMuscle (/*k=*/1, /*d=*/0, /*maxf=*/10));
muscle.addPoint (p0);
muscle.addPoint (via0);
muscle.addPoint (via1);
muscle.addPoint (p1);
mech.addMultiPointSpring (muscle);
// set render properties
RenderProps.setSphericalPoints (mech, 0.1, Color.WHITE);
RenderProps.setCylindricalLines (mech, 0.03, Color.RED);
createControlPanel();
}
private void createControlPanel() {
// creates a panel to adjust the muscle excitation
ControlPanel panel = new ControlPanel ("options", "");
panel.addWidget (this, "models/mech/multiPointSprings/0:excitation");
addControlPanel (panel);
}
}
| 34.376812 | 81 | 0.675379 |
786f1c1118cb2b6a555f6a5501d7f213a42d494e | 790 | package subroute.block;
import subroute.texture.Icon;
import subroute.texture.TileRegister;
import subroute.util.Side;
import subroute.world.storage.IWorldAccess;
public class Glass extends Block {
Icon icon;
public Glass(){
super(8);
}
@Override
public void registerTexTiles(TileRegister reg) {
this.icon = reg.loadNewIcon("resource/textures/blocks/glass.png");
}
@Override
public Icon getIconForSide(IWorldAccess wld, int x, int y, int z, Side side) {
return icon;
}
@Override
public boolean isSolidOpaque(){
return false;
}
@Override
public boolean shouldRenderSide(IWorldAccess wld, int x, int y, int z, Side side) {
return true;
}
@Override
public boolean shouldRenderInPass(int pass){
return pass == 1;
}
}
| 19.75 | 85 | 0.7 |
4104fdf20e980fc1b8eb3698fd0f1013dfce7a49 | 977 | package mediation.helper;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;
public class IUtils {
public static boolean isPackageInstalled(String pkgName, Context context) {
try {
PackageManager packageManager = context.getPackageManager();
packageManager.getPackageInfo(pkgName, PackageManager.GET_ACTIVITIES);
return true;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return false;
}
public static boolean isContainPkg(String pkgName) {
if(TextUtils.isEmpty(pkgName) ||pkgName == null)
return false;
if (pkgName.contains("play.google.com/"))
return true;
else
return false;
}
public static String getPackageName(String url){
String[] gPkg = url.split("=");
return gPkg[1];
}
}
| 25.051282 | 82 | 0.63869 |
dcf026c1e9cbeea97fbc71238c4b5e783bdf3297 | 2,724 | package classes.SqlParser.Alter;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import classes.DBNode;
import classes.DateNode;
import classes.FileSystemFactory;
import classes.FloatNode;
import classes.IntegerNode;
import classes.StringNode;
import classes.TabelImp;
import interfaces.WriterInterface;
public class AddColumn extends Alter {
String tableName, columnName;
String type;
public AddColumn(String input) {
super(input);
// TODO Auto-generated constructor stub
}
@Override
public ArrayList<ArrayList<String>> alter() throws Exception {
// TODO Auto-generated method stub
Pattern alterPattern = Pattern.compile(
"(?i)\\s*alter\\s+table\\s+(\\w+)\\s+add\\s+(?:column\\s+|(\\w+)\\s*)\\s*(\\w+)?\\s+(\\w+)\\s*;?");
Matcher alterMatcher = alterPattern.matcher(input);
if (alterMatcher.find()) {
tableName = alterMatcher.group(1);
columnName = alterMatcher.group(2) == null ? alterMatcher.group(3) : alterMatcher.group(2);
type = alterMatcher.group(4);
try {
TabelImp table = parser.read(tableName);
DBNode column = makeColumn(type, columnName);
ArrayList<DBNode> columns = makeColumns(table, column);
TabelImp updated = updateNewTable(columns);
parser.write(updated);
return LastReturn(tableName);
} catch (Exception e) {
throw new RuntimeException("Invalid Alter operation");
}
} else
throw new RuntimeException("Invalid Query for Alter");
}
private DBNode makeColumn(String type, String name) {
if (type.toLowerCase().equals("int"))
return new IntegerNode(name);
else if (type.toLowerCase().equals("varchar"))
return new StringNode(name);
else if (type.toLowerCase().equals("date"))
return new DateNode(name);
else if (type.toLowerCase().equals("float"))
return new FloatNode(name);
else
throw new RuntimeException("Invalid Type");
}
private ArrayList<DBNode> makeColumns(TabelImp table, DBNode x) throws Exception {
ArrayList<DBNode> all = table.getTable();
for (int i = 0; i < all.get(0).getColumn().size(); i++) {
x.getColumn().add(null);
}
all.add(x);
return all;
}
private TabelImp updateNewTable(ArrayList<DBNode> all) {
TabelImp newTable = new TabelImp(tableName, all);
return newTable;
}
} | 35.376623 | 116 | 0.593979 |
8508a03a1b148cf5bb80b4b7eeb7c30ca495f2d9 | 187 | class CalcVelocity {
static int distance = 10;
static int time = 2;
public static void main(String[] args) {
int speed = distance / time;
System.out.println(speed);
}
}
| 17 | 42 | 0.647059 |
50c2750dfb083cabe930026f329b84b1cd0043d3 | 2,498 |
package com.htfyun.uartJni;
public class UartJni {
/*****************************************************************/
/*****************************************************************/
/***** *****/
/***** U A R T C O N F I G E R *****/
/***** *****/
/*****************************************************************/
/*****************************************************************/
/**
*
* @param fd---openUartChannel的返回值
* @param baudrate-- 比如(115200, 38400, 19200, 9600, 4800, 2400, 1200, 300)
* @return true--ok,false--fail
* 参考:uartSetSpeed(fd,9600);
*/
public static native boolean uartSetSpeed(int fd,int baudrate);
/**
*
* @param fd--openUartChannel的返回值
* @param databits--数据位 取值为 7 或者8
* @param stopbits--停止位 取值为 1 或者2
* @param parity--效验类型 取值为N,E,O,S
* N: No parity
* E: even parity
* O: odd parity
* S: as no parity
* @return true--ok,false--fail
*
* 参考:uartSetParity(fd, 8, 1, 'N')
*/
public static native boolean uartSetParity(int fd,int databits,int stopbits,int parity);
/*****************************************************************/
/*****************************************************************/
/***** *****/
/***** U A R T O P E R A T I O N *****/
/***** *****/
/*****************************************************************/
/*****************************************************************/
/**
*
* @param name (如/dev/ttyS0,/dev/ttyS1)
* @return fd---文件句柄
*
* 参考:fd = openUartChannel("/dev/ttyS1")
*/
public static native int openUartChannel(String name);
/**
*
* @param fd---openUartChannel的返回值
*/
public static native void closeUartChannel(int fd);
/**
*
* @param fd--openUartChannel的返回值
* @param buf--写入串口的数据
* @param len--Data Length
* @return real write bytes
*/
public static native int uartWriteBytes(int fd,byte[] buf,int len);
/**
*
* @param fd--openUartChannel的返回值
* @param buf--从串口读到的数据
* @param len--Need Data Length
* @return real read bytes
*/
public static native int uartReadBytes(int fd,byte[] buf,int len);
static
{
try {
System.loadLibrary("uartJni");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 27.755556 | 89 | 0.399119 |
2896b413aa7ff09f754ff04a92ac591f7af5d589 | 530 | package urlshortener.demo.repository;
import urlshortener.demo.domain.URIItem;
import java.util.Date;
import java.util.Map;
public interface URIRepository extends IRepository<String, URIItem> {
Map<String, URIItem> getAllURIS();
Map<String, Date> getAllFechas();
void removeFecha(String id);
void addFecha(String id, Date fecha);
long getRedirectionAmount(String hash, long timeFromNow);
void add(URIItem uri);
URIItem get(String hash);
void remove(String hash);
void removeAll();
}
| 19.62963 | 69 | 0.724528 |
5096db71e0116e62b437ebad2644db1abb76d7cc | 2,736 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.impl.stubs;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.stubs.StubInputStream;
import com.intellij.psi.stubs.StubOutputStream;
import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.psi.PyFromImportStatement;
import com.jetbrains.python.psi.PyStubElementType;
import com.jetbrains.python.psi.impl.PyFromImportStatementImpl;
import com.jetbrains.python.psi.stubs.PyFromImportStatementStub;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
/**
* @author yole
*/
public class PyFromImportStatementElementType extends PyStubElementType<PyFromImportStatementStub, PyFromImportStatement> {
public PyFromImportStatementElementType() {
this("FROM_IMPORT_STATEMENT");
}
public PyFromImportStatementElementType(@NotNull @NonNls String debugName) {
super(debugName);
}
@NotNull
@Override
public PsiElement createElement(@NotNull ASTNode node) {
return new PyFromImportStatementImpl(node);
}
@Override
public PyFromImportStatement createPsi(@NotNull PyFromImportStatementStub stub) {
return new PyFromImportStatementImpl(stub);
}
@NotNull
@Override
public PyFromImportStatementStub createStub(@NotNull PyFromImportStatement psi, StubElement parentStub) {
return new PyFromImportStatementStubImpl(psi.getImportSourceQName(), psi.isStarImport(), psi.getRelativeLevel(), parentStub,
getStubElementType());
}
@Override
public void serialize(@NotNull PyFromImportStatementStub stub, @NotNull StubOutputStream dataStream) throws IOException {
final QualifiedName qName = stub.getImportSourceQName();
QualifiedName.serialize(qName, dataStream);
dataStream.writeBoolean(stub.isStarImport());
dataStream.writeVarInt(stub.getRelativeLevel());
}
@Override
@NotNull
public PyFromImportStatementStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
QualifiedName qName = QualifiedName.deserialize(dataStream);
boolean isStarImport = dataStream.readBoolean();
int relativeLevel = dataStream.readVarInt();
return new PyFromImportStatementStubImpl(qName, isStarImport, relativeLevel, parentStub, getStubElementType());
}
protected IStubElementType getStubElementType() {
return PyElementTypes.FROM_IMPORT_STATEMENT;
}
}
| 38 | 140 | 0.789839 |
2e2772608ed183151138323b6d4ced9da07bd821 | 663 | package com.pilicon.concurrency.thinkinginjava;
public class SimplePriority implements Runnable {
@Override
public void run() {
}
// private int countDown = 5 ;
//
// private volatile double d ;
//
// private int priority;
//
// public SimplePriority(int priority) {
// this.priority = priority;
// }
//
// @Override
// public String toString() {
// return Thread.currentThread() + ":" + countDown;
// }
//
// @Override
// public void run() {
// Thread.currentThread().setPriority();
// while (true){
// for (int i = 1 ; i< 10000 ;i++){
//
// }
// }
// }
}
| 19.5 | 58 | 0.533937 |
032e7587941315c135f5cd15d4fdbb03c68c1308 | 2,484 | /*
* 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.hyracks.storage.am.common.dataflow;
import java.util.EnumSet;
import java.util.Set;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.IOperatorNodePushable;
import org.apache.hyracks.api.dataflow.value.IRecordDescriptorProvider;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.job.IOperatorDescriptorRegistry;
import org.apache.hyracks.dataflow.std.base.AbstractSingleActivityOperatorDescriptor;
public class IndexDropOperatorDescriptor extends AbstractSingleActivityOperatorDescriptor {
public enum DropOption {
IF_EXISTS,
WAIT_ON_IN_USE
}
private static final long serialVersionUID = 1L;
private final IIndexDataflowHelperFactory dataflowHelperFactory;
private final Set<DropOption> options;
public IndexDropOperatorDescriptor(IOperatorDescriptorRegistry spec,
IIndexDataflowHelperFactory dataflowHelperFactory) {
this(spec, dataflowHelperFactory, EnumSet.noneOf(DropOption.class));
}
public IndexDropOperatorDescriptor(IOperatorDescriptorRegistry spec,
IIndexDataflowHelperFactory dataflowHelperFactory, Set<DropOption> options) {
super(spec, 0, 0);
this.dataflowHelperFactory = dataflowHelperFactory;
this.options = options;
}
@Override
public IOperatorNodePushable createPushRuntime(IHyracksTaskContext ctx,
IRecordDescriptorProvider recordDescProvider, int partition, int nPartitions) throws HyracksDataException {
return new IndexDropOperatorNodePushable(dataflowHelperFactory, options, ctx, partition);
}
}
| 40.721311 | 119 | 0.77657 |
8ba70b4a565f297f6fc74a343e13fb1fcb466634 | 978 | package ru.job4j.board;
import java.lang.Math;
/**
* @author vsokolov
* @version $Id$
* @since 0.1
*/
public class Bishop extends Figure {
private Cell position;
public Bishop(Cell position) {
super(position);
}
public Bishop copy(Cell dest) {
return new Bishop(dest);
}
@Override
public Cell[] way(Cell start, Cell dest) throws ImpossibleMoveException {
if (isMovePossible(start, dest)) {
Cell[] result = new Cell[Math.abs(start.getX() - dest.getX())];
int position = 0;
for (int i = start.getX() + 1, j = start.getY() + 1; i <= dest.getX(); i++, j++) {
Cell add = new Cell(i, j);
result[position++] = add;
}
return result;
} else {
throw new ImpossibleMoveException();
}
}
@Override
public boolean isMovePossible(Cell start, Cell dest) {
return (Math.abs(start.getX() - dest.getX())) == (Math.abs(start.getY() - dest.getY()));
}
public Cell getPosition() {
return this.position;
}
}
| 21.26087 | 90 | 0.618609 |
2e201b932282a6edd8452d7fa5e96ea4403a1d36 | 1,008 | package com.alibaba.rsocket.client.demo;
import com.alibaba.rsocket.config.bootstrap.RSocketConfigPropertySourceLocator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import static org.springframework.context.annotation.ScopedProxyMode.DEFAULT;
/**
* config testing controller
*
* @author leijuan
*/
@RestController
@RefreshScope(proxyMode = DEFAULT)
public class ConfigTestingController {
@Value("${developer:unknown}")
private String developer;
@RequestMapping("/config/display")
public Mono<String> serverInstances() {
return Mono.just(RSocketConfigPropertySourceLocator.getLastConfigText());
}
@RequestMapping("/config/developer")
private Mono<String> developer() {
return Mono.just(developer);
}
}
| 30.545455 | 81 | 0.779762 |
530fd021c26cb37297340500ec8bf49ddff4ab06 | 454 | package com.alternate.sample.services;
import com.alternate.sample.entities.SampleEntity;
import java.util.Optional;
/*
* normally we use interface to abstract implementation
* useful when using dependency injection
* no need to depend on concrete implementation
*/
public interface SampleService {
void addSample(SampleEntity sampleEntity);
Iterable<SampleEntity> getAllSamples();
Optional<SampleEntity> getSampleById(Integer id);
}
| 25.222222 | 55 | 0.786344 |
3993a52d0b3c5085f16c2cdaa6770c4cd62af86c | 68 | package org.andot.share.common.utils;
public class ZipFileUtil {
}
| 13.6 | 37 | 0.779412 |
7d741ad5e030a5aa35560f8bf706325b739e8c9d | 6,363 | package org.jeecg.modules.nuoze.nz.service.impl;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.nuoze.nz.entity.NzSourceType;
import org.jeecg.modules.nuoze.nz.mapper.NzSourceTypeMapper;
import org.jeecg.modules.nuoze.nz.service.INzSourceTypeService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
* @Description: 原药材种类
* @Author: jeecg-boot
* @Date: 2020-12-01
* @Version: V1.0
*/
@Service
public class NzSourceTypeServiceImpl extends ServiceImpl<NzSourceTypeMapper, NzSourceType> implements INzSourceTypeService {
@Override
public void addNzSourceType(NzSourceType nzSourceType) {
if(oConvertUtils.isEmpty(nzSourceType.getPid())){
nzSourceType.setPid(INzSourceTypeService.ROOT_PID_VALUE);
}else{
//如果当前节点父ID不为空 则设置父节点的hasChildren 为1
NzSourceType parent = baseMapper.selectById(nzSourceType.getPid());
if(parent!=null && !"1".equals(parent.getHasChild())){
parent.setHasChild("1");
baseMapper.updateById(parent);
}
}
baseMapper.insert(nzSourceType);
}
@Override
public void updateNzSourceType(NzSourceType nzSourceType) {
NzSourceType entity = this.getById(nzSourceType.getId());
if(entity==null) {
throw new JeecgBootException("未找到对应实体");
}
String old_pid = entity.getPid();
String new_pid = nzSourceType.getPid();
if(!old_pid.equals(new_pid)) {
updateOldParentNode(old_pid);
if(oConvertUtils.isEmpty(new_pid)){
nzSourceType.setPid(INzSourceTypeService.ROOT_PID_VALUE);
}
if(!INzSourceTypeService.ROOT_PID_VALUE.equals(nzSourceType.getPid())) {
baseMapper.updateTreeNodeStatus(nzSourceType.getPid(), INzSourceTypeService.HASCHILD);
}
}
baseMapper.updateById(nzSourceType);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteNzSourceType(String id) throws JeecgBootException {
//查询选中节点下所有子节点一并删除
id = this.queryTreeChildIds(id);
if(id.indexOf(",")>0) {
StringBuffer sb = new StringBuffer();
String[] idArr = id.split(",");
for (String idVal : idArr) {
if(idVal != null){
NzSourceType nzSourceType = this.getById(idVal);
String pidVal = nzSourceType.getPid();
//查询此节点上一级是否还有其他子节点
List<NzSourceType> dataList = baseMapper.selectList(new QueryWrapper<NzSourceType>().eq("pid", pidVal).notIn("id",Arrays.asList(idArr)));
if((dataList == null || dataList.size()==0) && !Arrays.asList(idArr).contains(pidVal)
&& !sb.toString().contains(pidVal)){
//如果当前节点原本有子节点 现在木有了,更新状态
sb.append(pidVal).append(",");
}
}
}
//批量删除节点
baseMapper.deleteBatchIds(Arrays.asList(idArr));
//修改已无子节点的标识
String[] pidArr = sb.toString().split(",");
for(String pid : pidArr){
this.updateOldParentNode(pid);
}
}else{
NzSourceType nzSourceType = this.getById(id);
if(nzSourceType==null) {
throw new JeecgBootException("未找到对应实体");
}
updateOldParentNode(nzSourceType.getPid());
baseMapper.deleteById(id);
}
}
@Override
public List<NzSourceType> queryTreeListNoPage(QueryWrapper<NzSourceType> queryWrapper) {
List<NzSourceType> dataList = baseMapper.selectList(queryWrapper);
List<NzSourceType> mapList = new ArrayList<>();
for(NzSourceType data : dataList){
String pidVal = data.getPid();
//递归查询子节点的根节点
if(pidVal != null && !"0".equals(pidVal)){
NzSourceType rootVal = this.getTreeRoot(pidVal);
if(rootVal != null && !mapList.contains(rootVal)){
mapList.add(rootVal);
}
}else{
if(!mapList.contains(data)){
mapList.add(data);
}
}
}
return mapList;
}
/**
* 根据所传pid查询旧的父级节点的子节点并修改相应状态值
* @param pid
*/
private void updateOldParentNode(String pid) {
if(!INzSourceTypeService.ROOT_PID_VALUE.equals(pid)) {
Integer count = baseMapper.selectCount(new QueryWrapper<NzSourceType>().eq("pid", pid));
if(count==null || count<=1) {
baseMapper.updateTreeNodeStatus(pid, INzSourceTypeService.NOCHILD);
}
}
}
/**
* 递归查询节点的根节点
* @param pidVal
* @return
*/
private NzSourceType getTreeRoot(String pidVal){
NzSourceType data = baseMapper.selectById(pidVal);
if(data != null && !"0".equals(data.getPid())){
return this.getTreeRoot(data.getPid());
}else{
return data;
}
}
/**
* 根据id查询所有子节点id
* @param ids
* @return
*/
private String queryTreeChildIds(String ids) {
//获取id数组
String[] idArr = ids.split(",");
StringBuffer sb = new StringBuffer();
for (String pidVal : idArr) {
if(pidVal != null){
if(!sb.toString().contains(pidVal)){
if(sb.toString().length() > 0){
sb.append(",");
}
sb.append(pidVal);
this.getTreeChildIds(pidVal,sb);
}
}
}
return sb.toString();
}
/**
* 递归查询所有子节点
* @param pidVal
* @param sb
* @return
*/
private StringBuffer getTreeChildIds(String pidVal,StringBuffer sb){
List<NzSourceType> dataList = baseMapper.selectList(new QueryWrapper<NzSourceType>().eq("pid", pidVal));
if(dataList != null && dataList.size()>0){
for(NzSourceType tree : dataList) {
if(!sb.toString().contains(tree.getId())){
sb.append(",").append(tree.getId());
}
this.getTreeChildIds(tree.getId(),sb);
}
}
return sb;
}
}
| 33.489474 | 157 | 0.604118 |
f3dfd804d895149b0daf8c385e0511bcda8378bd | 2,213 | // Copyright 2016 Xiaomi, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.xiaomi.linden.plugin.metrics;
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Throwables;
import com.xiaomi.linden.plugin.LindenPluginFactory;
import com.xiaomi.linden.plugin.ClassLoaderUtils;
public class MetricsManagerFactory implements LindenPluginFactory<MetricsManager> {
private static final Logger LOGGER = LoggerFactory.getLogger(MetricsManagerFactory.class);
private static final String PLUGIN_PATH = "plugin.path";
private static final String CLASS_NAME = "class.name";
private static final String REPORT_PERIOD = "report.period";
private static final String REPORT_TAG = "report.tag";
@Override
public MetricsManager getInstance(Map<String,String> config) {
try {
String pluginPath = config.get(PLUGIN_PATH);
if (pluginPath == null) {
throw new IOException("Plugin path is null");
}
String className = config.get(CLASS_NAME);
Class<?> clazz = ClassLoaderUtils.load(pluginPath, className);
if (clazz != null) {
String tag = config.get(REPORT_TAG);
String periodStr = config.get(REPORT_PERIOD);
int period = Integer.valueOf(periodStr);
return (MetricsManager) clazz.getConstructor(int.class, String.class).newInstance(period, tag);
} else {
throw new IOException("Plugin " + className + " not found.");
}
} catch (Exception e) {
LOGGER.warn("Get MetricsManager Instance failed, Use Default, {}", Throwables.getStackTraceAsString(e));
}
return MetricsManager.DEFAULT;
}
}
| 36.883333 | 110 | 0.726164 |
75104440150608829d1e5d8dbf85aa5207bc6746 | 409 | package com.tz.pojo.vo;
import java.io.Serializable;
//分类名称
public class CategoryNames implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7206099568738869602L;
//分类名称
private String categoryName;
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
} | 15.730769 | 67 | 0.721271 |
b7f6978e7e6248a26e562a7090b48fa256c2c91d | 2,972 | /**
* This class is generated by jOOQ
*/
package org.jooq.test.cubrid.generatedclasses.tables;
/**
* This class is generated by jOOQ.
*/
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class XTestCase_85 extends org.jooq.impl.TableImpl<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record> {
private static final long serialVersionUID = -1834659466;
/**
* The singleton instance of <code>x_test_case_85</code>
*/
public static final org.jooq.test.cubrid.generatedclasses.tables.XTestCase_85 X_TEST_CASE_85 = new org.jooq.test.cubrid.generatedclasses.tables.XTestCase_85();
/**
* The class holding records for this type
*/
@Override
public java.lang.Class<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record> getRecordType() {
return org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record.class;
}
/**
* The column <code>x_test_case_85.id</code>.
*/
public static final org.jooq.TableField<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record, java.lang.Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), X_TEST_CASE_85);
/**
* The column <code>x_test_case_85.x_unused_id</code>.
*/
public static final org.jooq.TableField<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record, java.lang.Integer> X_UNUSED_ID = createField("x_unused_id", org.jooq.impl.SQLDataType.INTEGER, X_TEST_CASE_85);
/**
* The column <code>x_test_case_85.x_unused_name</code>.
*/
public static final org.jooq.TableField<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record, java.lang.String> X_UNUSED_NAME = createField("x_unused_name", org.jooq.impl.SQLDataType.VARCHAR.length(10), X_TEST_CASE_85);
/**
* No further instances allowed
*/
private XTestCase_85() {
super("x_test_case_85", org.jooq.test.cubrid.generatedclasses.DefaultSchema.DEFAULT_SCHEMA);
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.UniqueKey<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record> getPrimaryKey() {
return org.jooq.test.cubrid.generatedclasses.Keys.X_TEST_CASE_85__PK_X_TEST_CASE_85;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.UniqueKey<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record>> getKeys() {
return java.util.Arrays.<org.jooq.UniqueKey<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record>>asList(org.jooq.test.cubrid.generatedclasses.Keys.X_TEST_CASE_85__PK_X_TEST_CASE_85);
}
/**
* {@inheritDoc}
*/
@Override
public java.util.List<org.jooq.ForeignKey<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record, ?>> getReferences() {
return java.util.Arrays.<org.jooq.ForeignKey<org.jooq.test.cubrid.generatedclasses.tables.records.XTestCase_85Record, ?>>asList(org.jooq.test.cubrid.generatedclasses.Keys.X_TEST_CASE_85__FK_X_TEST_CASE_85);
}
}
| 40.712329 | 239 | 0.777254 |
68f76c52c2cf3e7915b051514068f02f9440b282 | 658 | package simpleci.dispatcher.listener;
import simpleci.dispatcher.model.event.BuildStartEvent;
import simpleci.dispatcher.model.event.BuildStopEvent;
import simpleci.dispatcher.model.repository.UpdaterRepository;
public class BuildListener {
private final UpdaterRepository repository;
public BuildListener(UpdaterRepository repository) {
this.repository = repository;
}
public void buildStart(BuildStartEvent event)
{
repository.buildStarted(event.buildId, event.startedAt);
}
public void buildStop(BuildStopEvent event) {
repository.buildStopped(event.buildId, event.status, event.endedAt);
}
}
| 27.416667 | 76 | 0.762918 |
a894fd9e5c0a3be5121cccde7aad81796fc3da88 | 1,984 | package org.but.feec.library.api;
import javafx.beans.property.LongProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class LibraryFilterView {
private final LongProperty id = new SimpleLongProperty();
private final LongProperty isbn = new SimpleLongProperty();
private final StringProperty bookTitle = new SimpleStringProperty();
private final StringProperty authorName = new SimpleStringProperty();
private final StringProperty authorSurname = new SimpleStringProperty();
////////////////
public void setId(long id) {
this.id.set(id);
}
public void setIsbn(long isbn) {
this.isbn.set(isbn);
}
public void setBookTitle(String bookTitle) {
this.bookTitle.set(bookTitle);
}
public void setAuthorName(String authorName) {
this.authorName.set(authorName);
}
public void setAuthorSurname(String authorSurname) {
this.authorSurname.set(authorSurname);
}
////////////////////////////
public long getId() {
return idProperty().get();
}
public long getIsbn() {
return isbnProperty().get();
}
public String getAuthorName() {
return authorNameProperty().get();
}
public String getBookTitle() {
return bookTitleProperty().get();
}
public String getAuthorSurname() {
return authorSurnameProperty().get();
}
///////////////////////
public StringProperty bookTitleProperty() {
return bookTitle;
}
public LongProperty isbnProperty() {
return isbn;
}
public StringProperty authorNameProperty() {
return authorName;
}
public StringProperty authorSurnameProperty() {
return authorSurname;
}
public LongProperty idProperty() {
return id;
}
}
| 26.105263 | 77 | 0.628024 |
2d365e3a60ad2cff36067cbf16c6dafc3a382271 | 9,780 | /*
* Copyright 2013 Bazaarvoice, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.bazaarvoice.jolt;
import com.beust.jcommander.internal.Sets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.collections.Lists;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsonUtilsTest {
private Diffy diffy = new Diffy();
private Map ab = ImmutableMap.builder().put( "a", "b" ).build();
private Map cd = ImmutableMap.builder().put( "c", "d" ).build();
private Map top = ImmutableMap.builder().put( "A", ab ).put( "B", cd ).build();
private String jsonSourceString = "{ " +
" \"a\": { " +
" \"b\": [ " +
" 0, " +
" 1, " +
" 2, " +
" 1.618 " +
" ] " +
" }, " +
" \"p\": [ " +
" \"m\", " +
" \"n\", " +
" { " +
" \"1\": 1, " +
" \"2\": 2, " +
" \"pi\": 3.14159 " +
" } " +
" ], " +
" \"x\": \"y\" " +
"}\n";
private Object jsonSource;
@BeforeClass
@SuppressWarnings("unchecked")
public void setup() throws IOException {
jsonSource = JsonUtils.jsonToObject(jsonSourceString);
// added for type cast checking
Set<String> aSet = Sets.newHashSet();
aSet.add("i");
aSet.add("j");
((Map) jsonSource).put("s", aSet);
}
@DataProvider
public Object[][] removeRecursiveCases() {
Map empty = ImmutableMap.builder().build();
Map barToFoo = ImmutableMap.builder().put( "bar", "foo" ).build();
Map fooToBar = ImmutableMap.builder().put( "foo", "bar" ).build();
return new Object[][] {
{ null, null, null },
{ null, "foo", null },
{ "foo", null, "foo" },
{ "foo", "foo", "foo" },
{ Maps.newHashMap(), "foo", empty },
{ Maps.newHashMap( barToFoo ), "foo", barToFoo },
{ Maps.newHashMap( fooToBar ), "foo", empty },
{ Lists.newArrayList(), "foo", ImmutableList.builder().build() },
{
Lists.newArrayList( ImmutableList.builder()
.add( Maps.newHashMap( barToFoo ) )
.build() ),
"foo",
ImmutableList.builder()
.add( barToFoo )
.build()
},
{
Lists.newArrayList( ImmutableList.builder()
.add( Maps.newHashMap( fooToBar ) )
.build() ),
"foo",
ImmutableList.builder()
.add( empty )
.build()
}
};
}
@Test(dataProvider = "removeRecursiveCases")
@SuppressWarnings("deprecation")
public void testRemoveRecursive(Object json, String key, Object expected) throws IOException {
JsonUtils.removeRecursive( json, key );
Diffy.Result result = diffy.diff( expected, json );
if (!result.isEmpty()) {
Assert.fail( "Failed.\nhere is a diff:\nexpected: " + JsonUtils.toJsonString( result.expected ) + "\n actual: " + JsonUtils.toJsonString( result.actual ) );
}
}
@Test
@SuppressWarnings("deprecation")
public void runFixtureTests() throws IOException {
String testFixture = "/jsonUtils/jsonUtils-removeRecursive.json";
@SuppressWarnings("unchecked")
List<Map<String, Object>> tests = (List<Map<String, Object>>) JsonUtils.classpathToObject( testFixture );
for ( Map<String,Object> testUnit : tests ) {
Object data = testUnit.get( "input" );
String toRemove = (String) testUnit.get( "remove" );
Object expected = testUnit.get( "expected" );
JsonUtils.removeRecursive( data, toRemove );
Diffy.Result result = diffy.diff( expected, data );
if (!result.isEmpty()) {
Assert.fail( "Failed.\nhere is a diff:\nexpected: " + JsonUtils.toJsonString(result.expected) + "\n actual: " + JsonUtils.toJsonString(result.actual));
}
}
}
@Test
public void validateJacksonClosesInputStreams() {
final Set<String> closedSet = new HashSet<>();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( "{ \"a\" : \"b\" }".getBytes() ) {
@Override
public void close() throws IOException {
closedSet.add("closed");
super.close();
}
};
// Pass our wrapped InputStream to Jackson via JsonUtils.
Map<String,Object> map = JsonUtils.jsonToMap( byteArrayInputStream );
// Verify that we in fact loaded some data
Assert.assertNotNull( map );
Assert.assertEquals( 1, map.size() );
// Verify that the close method was in fact called on the InputStream
Assert.assertEquals( 1, closedSet.size() );
}
@DataProvider (parallel = true)
public Iterator<Object[]> coordinates() throws IOException {
List<Object[]> testCases = com.beust.jcommander.internal.Lists.newArrayList();
testCases.add(new Object[] { 0, new Object[] {"a", "b", 0}} );
testCases.add(new Object[] { 1, new Object[] {"a", "b", 1}} );
testCases.add(new Object[] { 2, new Object[] {"a", "b", 2}} );
testCases.add(new Object[] { 1.618, new Object[] {"a", "b", 3}} );
testCases.add(new Object[] { "m", new Object[] {"p", 0}} );
testCases.add(new Object[] { "n", new Object[] {"p", 1}} );
testCases.add(new Object[] { 1, new Object[] {"p", 2, "1"}} );
testCases.add(new Object[] { 2, new Object[] {"p", 2, "2"}} );
testCases.add(new Object[] { 3.14159, new Object[] {"p", 2, "pi"}} );
testCases.add(new Object[] { "y", new Object[] {"x"}} );
testCases.add(new Object[] { ((Map) jsonSource).get("a"), new Object[] {"a"}} );
testCases.add(new Object[] { ((Map)(((Map) jsonSource).get("a"))).get("b"), new Object[] {"a", "b"}} );
testCases.add(new Object[] { ((List)((Map)(((Map) jsonSource).get("a"))).get("b")).get(0), new Object[] {"a", "b", 0}} );
testCases.add(new Object[] { ((List)((Map)(((Map) jsonSource).get("a"))).get("b")).get(1), new Object[] {"a", "b", 1}} );
testCases.add(new Object[] { ((List)((Map)(((Map) jsonSource).get("a"))).get("b")).get(2), new Object[] {"a", "b", 2}} );
testCases.add(new Object[] { ((List)((Map)(((Map) jsonSource).get("a"))).get("b")).get(3), new Object[] {"a", "b", 3}} );
testCases.add(new Object[] { ((Map) jsonSource).get("p"), new Object[] {"p"}} );
testCases.add(new Object[] { ((List)(((Map) jsonSource).get("p"))).get(0), new Object[] {"p", 0}} );
testCases.add(new Object[] { ((List)(((Map) jsonSource).get("p"))).get(1), new Object[] {"p", 1}} );
testCases.add(new Object[] { ((List)(((Map) jsonSource).get("p"))).get(2), new Object[] {"p", 2}} );
testCases.add(new Object[] { ((Map)((List)(((Map) jsonSource).get("p"))).get(2)).get("1"), new Object[] {"p", 2, "1"}} );
testCases.add(new Object[] { ((Map)((List)(((Map) jsonSource).get("p"))).get(2)).get("2"), new Object[] {"p", 2, "2"}} );
testCases.add(new Object[] { ((Map)((List)(((Map) jsonSource).get("p"))).get(2)).get("pi"), new Object[] {"p", 2, "pi"}} );
testCases.add(new Object[] { ((Map) jsonSource).get("x"), new Object[] {"x"}} );
return testCases.iterator();
}
/**
* Method: navigate(Object source, Object... paths)
*/
@Test (dataProvider = "coordinates")
@SuppressWarnings("deprecation")
public void navigator(Object expected, Object[] path) throws Exception {
Object actual = JsonUtils.navigate(jsonSource, path);
Assert.assertEquals(actual, expected);
}
}
| 45.069124 | 169 | 0.499796 |
2bc380186aac0849faad0cf9a00351a20f8453fd | 2,335 | //
// Decompiled by Procyon v0.5.36
//
package vip.Resolute.command;
import java.util.Iterator;
import vip.Resolute.Resolute;
import java.util.Arrays;
import vip.Resolute.events.impl.EventChat;
import vip.Resolute.command.impl.NameProtect;
import vip.Resolute.command.impl.SpectatorAlt;
import vip.Resolute.command.impl.API;
import vip.Resolute.command.impl.HClip;
import vip.Resolute.command.impl.Configure;
import vip.Resolute.command.impl.Clientname;
import vip.Resolute.command.impl.Unhide;
import vip.Resolute.command.impl.Hide;
import vip.Resolute.command.impl.VClip;
import vip.Resolute.command.impl.Bind;
import vip.Resolute.command.impl.Toggle;
import java.util.ArrayList;
import java.util.List;
public class CommandManager
{
public List<Command> commands;
public String prefix;
public CommandManager() {
this.commands = new ArrayList<Command>();
this.prefix = ".";
this.setup();
}
public void setup() {
this.commands.add(new Toggle());
this.commands.add(new Bind());
this.commands.add(new VClip());
this.commands.add(new Hide());
this.commands.add(new Unhide());
this.commands.add(new Clientname());
this.commands.add(new Configure());
this.commands.add(new HClip());
this.commands.add(new API());
this.commands.add(new SpectatorAlt());
this.commands.add(new NameProtect());
}
public void handleChat(final EventChat event) {
String message = event.getMessage();
if (!message.startsWith(this.prefix)) {
return;
}
event.setCancelled(true);
message = message.substring(this.prefix.length());
boolean foundCommand = false;
if (message.split(" ").length > 0) {
final String commandName = message.split(" ")[0];
for (final Command c : this.commands) {
if (c.aliases.contains(commandName) || c.name.equalsIgnoreCase(commandName)) {
c.onCommand(Arrays.copyOfRange(message.split(" "), 1, message.split(" ").length), message);
foundCommand = true;
break;
}
}
}
if (!foundCommand) {
Resolute.addChatMessage("Could not find command");
}
}
}
| 31.986301 | 111 | 0.631263 |
df90d5941efd545f33cc1d9f74a3a5fb64956642 | 47,743 | /*
* Licensed to Julian Hyde 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 net.hydromatic.quidem;
import org.hamcrest.Matcher;
import org.hamcrest.core.SubstringMatcher;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Script-based tests for {@link Quidem}.
*/
public class QuidemTest {
@Test public void testBasic() {
check(
"!use scott\n"
+ "select count(*) as c from scott.emp;\n"
+ "!ok\n"
+ "!set outputformat mysql\n"
+ "select count(*) as c from scott.emp;\n"
+ "!ok\n"
+ "!plan\n"
+ "\n")
.outputs(
"!use scott\n"
+ "select count(*) as c from scott.emp;\n"
+ "C\n"
+ "14\n"
+ "!ok\n"
+ "!set outputformat mysql\n"
+ "select count(*) as c from scott.emp;\n"
+ "+----+\n"
+ "| C |\n"
+ "+----+\n"
+ "| 14 |\n"
+ "+----+\n"
+ "(1 row)\n"
+ "\n"
+ "!ok\n"
+ "isDistinctSelect=[false]\n"
+ "isGrouped=[false]\n"
+ "isAggregated=[true]\n"
+ "columns=[\n"
+ " COUNT arg=[ OpTypes.ASTERISK \n"
+ " nullable\n"
+ "\n"
+ "]\n"
+ "[range variable 1\n"
+ " join type=INNER\n"
+ " table=EMP\n"
+ " cardinality=14\n"
+ " access=FULL SCAN\n"
+ " join condition = [index=SYS_IDX_10095\n"
+ " ]\n"
+ " ]]\n"
+ "PARAMETERS=[]\n"
+ "SUBQUERIES[]\n"
+ "!plan\n"
+ "\n");
}
@Test public void testError() {
check(
"!use scott\n"
+ "select blah from blah;\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "select blah from blah;\n"
+ "java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: BLAH");
}
@Test public void testErrorTruncated() {
check(
"!use scott\n"
+ "select blah from blah;\n"
+ "!ok\n"
+ "\n")
.limit(10)
.contains(
"!use scott\n"
+ "select blah from blah;\n"
+ "java.sql.S (stack truncated)");
}
@Test public void testErrorNotTruncated() {
check(
"!use scott\n"
+ "select blah from blah;\n"
+ "!ok\n"
+ "\n")
.limit(1000)
.contains(
"!use scott\n"
+ "select blah from blah;\n"
+ "java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: BLAH");
}
@Test public void testExpectError() {
check(
"!use scott\n"
+ "select blah from blah;\n"
+ "user lacks privilege or object not found: BLAH\n"
+ "!error\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "select blah from blah;\n"
+ "user lacks privilege or object not found: BLAH\n"
+ "!error\n"
+ "\n");
}
/** The error does not even need to be a fully line. */
@Test public void testExpectErrorPartialLine() {
final String input = "!use scott\n"
+ "select blah from blah;\n"
+ "lacks privilege\n"
+ "!error\n"
+ "\n";
final String expected = "(?s)!use scott\n"
+ "select blah from blah;\n"
+ "lacks privilege\n"
+ "!error\n"
+ "\n";
check(input).matches(expected);
}
@Test public void testExpectErrorNoExpected() {
check(
"!use scott\n"
+ "select blah from blah;\n"
+ "!error\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "select blah from blah;\n"
+ "java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: BLAH\n"
+ "\tat org.hsqldb.jdbc.JDBCUtil.sqlException\\(Unknown Source\\)\n"
+ "\tat org.hsqldb.jdbc.JDBCUtil.sqlException\\(Unknown Source\\)\n"
+ "\tat org.hsqldb.jdbc.JDBCStatement.fetchResult\\(Unknown Source\\)\n"
+ ".*"
+ "!error\n"
+ "\n");
}
@Test public void testExpectErrorPermissiveTabs() {
// Quidem matches even though there are differences in tabs, multiple
// spaces, spaces at the start of lines, and different line endings.
// Quidem converts line endings to linux.
check(
"!use scott\n"
+ "select blah from blah;\n"
+ "java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: BLAH \n"
+ "\tat org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)\n"
+ " at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)\r\n"
+ "at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source) \n"
+ "!error\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "select blah from blah;\n"
+ "java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: BLAH \n"
+ "\tat org.hsqldb.jdbc.JDBCUtil.sqlException\\(Unknown Source\\)\n"
+ " at org.hsqldb.jdbc.JDBCUtil.sqlException\\(Unknown Source\\)\n"
+ "at org.hsqldb.jdbc.JDBCStatement.fetchResult\\(Unknown Source\\) \n"
+ "!error\n"
+ "\n");
}
@Test public void testExpectErrorDifferent() {
check(
"!use scott\n"
+ "select blah from blah;\n"
+ "user lacks bizz buzz\n"
+ "!error\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "select blah from blah;\n"
+ "java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: BLAH\n"
+ "\tat org.hsqldb.jdbc.JDBCUtil.sqlException\\(Unknown Source\\)\n"
+ ".*"
+ " more\n"
+ "!error\n"
+ "\n");
}
@Test public void testPlan() {
check(
"!use scott\n"
+ "values (1), (2);\n"
+ "!plan\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "values \\(1\\), \\(2\\);\n"
+ "isDistinctSelect=.*"
+ "!plan\n"
+ "\n");
}
@Test public void testPlanAfterOk() {
check(
"!use scott\n"
+ "values (1), (2);\n"
+ "!ok\n"
+ "!plan\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "values \\(1\\), \\(2\\);\n"
+ "C1\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "isDistinctSelect=.*"
+ "!plan\n"
+ "\n");
}
/** It is OK to have consecutive '!plan' calls and no '!ok'.
* (Previously there was a "result already open" error.) */
@Test public void testPlanPlan() {
check(
"!use scott\n"
+ "values (1), (2);\n"
+ "!plan\n"
+ "values (3), (4);\n"
+ "!plan\n"
+ "!ok\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "values \\(1\\), \\(2\\);\n"
+ "isDistinctSelect=.*\n"
+ "!plan\n"
+ "values \\(3\\), \\(4\\);\n"
+ "isDistinctSelect=.*\n"
+ "!plan\n"
+ "C1\n"
+ "3\n"
+ "4\n"
+ "!ok\n"
+ "\n");
}
/** Content inside a '!ok' command, that needs to be matched. */
@Test public void testOkContent() {
check(
"!use scott\n"
+ "values (1), (2);\n"
+ "baz\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "values (1), (2);\n"
+ "C1\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "\n");
}
/** If the statement contains 'order by', result is not re-ordered to match
* the input string. */
@Test public void testOkOrderBy() {
// In (2, 1), out (1, 2). Test gives a diff (correctly).
check("!use scott\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "C\n"
+ "2\n"
+ "1\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "C\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "\n");
// In (1, 2), out (1, 2). Test passes.
check("!use scott\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "C\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "C\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "\n");
}
/** As {@link #testOkOrderBy()} but for MySQL. */
@Test public void testOkOrderByMySQL() {
// In (2, 1), out (1, 2). Test gives a diff (correctly).
check("!use scott\n"
+ "!set outputformat mysql\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "+---+\n"
+ "| C |\n"
+ "+---+\n"
+ "| 2 |\n"
+ "| 1 |\n"
+ "+---+\n"
+ "(2 rows)\n"
+ "\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "!set outputformat mysql\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "+---+\n"
+ "| C |\n"
+ "+---+\n"
+ "| 1 |\n"
+ "| 2 |\n"
+ "+---+\n"
+ "(2 rows)\n"
+ "\n"
+ "!ok\n"
+ "\n");
// In (1, 2), out (1, 2). Test passes.
check("!use scott\n"
+ "!set outputformat mysql\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "+---+\n"
+ "| C |\n"
+ "+---+\n"
+ "| 1 |\n"
+ "| 2 |\n"
+ "+---+\n"
+ "(2 rows)\n"
+ "\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "!set outputformat mysql\n"
+ "select * from (values (1), (2)) as t(c) order by 1;\n"
+ "+---+\n"
+ "| C |\n"
+ "+---+\n"
+ "| 1 |\n"
+ "| 2 |\n"
+ "+---+\n"
+ "(2 rows)\n"
+ "\n"
+ "!ok\n"
+ "\n");
}
/** If the statement does not contain 'order by', result is re-ordered to
* match the input string. */
@Test public void testOkNoOrderBy() {
// In (2, 1), out (2, 1). Result would be correct in either order, but
// we output in the original order, so as not to cause a diff.
check(
"!use scott\n"
+ "select * from (values (1), (2)) as t(c);\n"
+ "C\n"
+ "2\n"
+ "1\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "select * from (values (1), (2)) as t(c);\n"
+ "C\n"
+ "2\n"
+ "1\n"
+ "!ok\n"
+ "\n");
// In (1, 2), out (1, 2).
check(
"!use scott\n"
+ "select * from (values (1), (2)) as t(c);\n"
+ "C\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "\n")
.contains(
"!use scott\n"
+ "select * from (values (1), (2)) as t(c);\n"
+ "C\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "\n");
}
/** Content inside a '!plan' command, that needs to be matched. */
@Test public void testPlanContent() {
check(
"!use scott\n"
+ "values (1), (2);\n"
+ "foo\n"
+ "!plan\n"
+ "baz\n"
+ "!ok\n"
+ "\n")
.matches(
"(?s)!use scott\n"
+ "values \\(1\\), \\(2\\);\n"
+ "isDistinctSelect=.*\n"
+ "!plan\n"
+ "C1\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "\n");
}
@Test public void testIfFalse() {
check(
"!use scott\n"
+ "!if (false) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!plan\n"
+ "!}\n"
+ "\n")
.contains(
"!use scott\n"
+ "!if (false) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!plan\n"
+ "!}\n"
+ "\n");
}
@Test public void testIfTrue() {
check(
"!use scott\n"
+ "!if (true) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "\n")
.contains(
"!use scott\n"
+ "!if (true) {\n"
+ "values (1), (2);\n"
+ "C1\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "!}\n"
+ "\n");
}
/** Test case for
* <a href="https://github.com/julianhyde/quidem/issues/8">[QUIDEM-8]
* Allow variable in 'if'</a>. */
@Test public void testIfVariable() {
check("!use scott\n"
+ "!if (affirmative) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "!if (negative) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "!if (unset) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "\n")
.contains("!use scott\n"
+ "!if (affirmative) {\n"
+ "values (1), (2);\n"
+ "C1\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "!}\n"
+ "!if (negative) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "!if (unset) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "\n");
}
/** Test case for
* <a href="https://github.com/julianhyde/quidem/issues/11">[QUIDEM-11]
* Nested variables</a>. */
@Test public void testIfVariableNested() {
final String input = "!use scott\n"
+ "!if (sun.self.self.hot) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "!if (sun.cold) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "!if (sun.unset.foo.baz) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "\n";
final String output = "!use scott\n"
+ "!if (sun.self.self.hot) {\n"
+ "values (1), (2);\n"
+ "C1\n"
+ "1\n"
+ "2\n"
+ "!ok\n"
+ "!}\n"
+ "!if (sun.cold) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "!if (sun.unset.foo.baz) {\n"
+ "values (1), (2);\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "\n";
check(input).contains(output);
}
@Test public void testSkip() {
check(
"!use scott\n"
+ "!skip\n"
+ "values (1);\n"
+ "anything\n"
+ "!ok\n"
+ "values (1);\n"
+ "you like\n"
+ "!error\n"
+ "\n")
.contains(
"!use scott\n"
+ "!skip\n"
+ "values (1);\n"
+ "anything\n"
+ "!ok\n"
+ "values (1);\n"
+ "you like\n"
+ "!error\n"
+ "\n");
}
@Test public void testSqlIfFalsePlan() {
final String input = "!use scott\n"
+ "values 1;\n"
+ "!if (false) {\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "something\n"
+ "!type\n"
+ "\n";
final String expected = "!use scott\n"
+ "values 1;\n"
+ "!if (false) {\n"
+ "anything\n"
+ "you like\n"
+ "!ok\n"
+ "!}\n"
+ "C1 INTEGER(32)\n"
+ "!type\n"
+ "\n";
check(input).contains(expected);
}
@Test public void testJustify() {
check(
"!use scott\n"
+ "select true as b00000,\n"
+ " cast(1 as tinyint) as t000,\n"
+ " cast(1 as integer) as i000,\n"
+ " cast(1 as float) as f00000,\n"
+ " cast(1 as double) as d00000,\n"
+ " cast(1 as varchar(3)) as v003\n"
+ "from (values (1));\n"
+ "!set outputformat mysql\n"
+ "!ok\n"
+ "!set outputformat psql\n"
+ "!ok\n"
+ "!set outputformat oracle\n"
+ "!ok\n"
+ "!set outputformat csv\n"
+ "!ok\n"
+ "\n")
.contains("!use scott\n"
+ "select true as b00000,\n"
+ " cast(1 as tinyint) as t000,\n"
+ " cast(1 as integer) as i000,\n"
+ " cast(1 as float) as f00000,\n"
+ " cast(1 as double) as d00000,\n"
+ " cast(1 as varchar(3)) as v003\n"
+ "from (values (1));\n"
+ "!set outputformat mysql\n"
+ "+--------+------+------+--------+--------+------+\n"
+ "| B00000 | T000 | I000 | F00000 | D00000 | V003 |\n"
+ "+--------+------+------+--------+--------+------+\n"
+ "| TRUE | 1 | 1 | 1.0E0 | 1.0E0 | 1 |\n"
+ "+--------+------+------+--------+--------+------+\n"
+ "(1 row)\n"
+ "\n"
+ "!ok\n"
+ "!set outputformat psql\n"
+ " B00000 | T000 | I000 | F00000 | D00000 | V003\n"
+ "--------+------+------+--------+--------+------\n"
+ " TRUE | 1 | 1 | 1.0E0 | 1.0E0 | 1\n"
+ "(1 row)\n"
+ "\n"
+ "!ok\n"
+ "!set outputformat oracle\n"
+ "B00000 T000 I000 F00000 D00000 V003\n"
+ "------ ---- ---- ------ ------ ----\n"
+ "TRUE 1 1 1.0E0 1.0E0 1\n"
+ "\n"
+ "!ok\n"
+ "!set outputformat csv\n"
+ "B00000, T000, I000, F00000, D00000, V003\n"
+ "TRUE, 1, 1, 1.0E0, 1.0E0, 1\n"
+ "!ok\n"
+ "\n");
}
@Test public void testOracle() {
final String input = "!use scott\n"
+ "!set outputformat oracle\n"
+ "select * from (values 1) where 1 = 0;\n"
+ "!ok\n"
+ "select * from (values 1);\n"
+ "!ok\n"
+ "select * from (values (1), (2), (3), (4), (5));\n"
+ "!ok\n"
+ "select * from (values (1), (2), (3), (4), (5), (6));\n"
+ "!ok\n"
+ "\n";
final String output = "!use scott\n"
+ "!set outputformat oracle\n"
+ "select * from (values 1) where 1 = 0;\n"
+ "\n"
+ "no rows selected\n"
+ "\n"
+ "!ok\n"
+ "select * from (values 1);\n"
+ "C1\n"
+ "--\n"
+ " 1\n"
+ "\n"
+ "!ok\n"
+ "select * from (values (1), (2), (3), (4), (5));\n"
+ "C1\n"
+ "--\n"
+ " 1\n"
+ " 2\n"
+ " 3\n"
+ " 4\n"
+ " 5\n"
+ "\n"
+ "!ok\n"
+ "select * from (values (1), (2), (3), (4), (5), (6));\n"
+ "C1\n"
+ "--\n"
+ " 1\n"
+ " 2\n"
+ " 3\n"
+ " 4\n"
+ " 5\n"
+ " 6\n"
+ "\n"
+ "6 rows selected.\n"
+ "\n"
+ "!ok\n"
+ "\n";
check(input).contains(output);
}
@Test public void testTrimTrailingSpacesOracle() {
final String input = "!use scott\n"
+ "!set outputformat oracle\n"
+ "select empno, deptno, comm from scott.emp where empno < 7700;\n"
+ "!ok\n"
+ "\n";
final String output = "!use scott\n"
+ "!set outputformat oracle\n"
+ "select empno, deptno, comm from scott.emp where empno < 7700;\n"
+ "EMPNO DEPTNO COMM\n"
+ "----- ------ -------\n"
+ " 7369 20\n"
+ " 7499 30 300.00\n"
+ " 7521 30 500.00\n"
+ " 7566 20\n"
+ " 7654 30 1400.00\n"
+ " 7698 30\n"
+ "\n"
+ "6 rows selected.\n"
+ "\n"
+ "!ok\n"
+ "\n";
check(input).contains(output);
}
@Test public void testTrimTrailingSpacesPsql() {
final String input = "!use scott\n"
+ "!set outputformat psql\n"
+ "select empno, deptno, comm from scott.emp where empno < 7700;\n"
+ "!ok\n"
+ "\n";
final String output = "!use scott\n"
+ "!set outputformat psql\n"
+ "select empno, deptno, comm from scott.emp where empno < 7700;\n"
+ " EMPNO | DEPTNO | COMM\n"
+ "-------+--------+---------\n"
+ " 7369 | 20 |\n"
+ " 7499 | 30 | 300.00\n"
+ " 7521 | 30 | 500.00\n"
+ " 7566 | 20 |\n"
+ " 7654 | 30 | 1400.00\n"
+ " 7698 | 30 |\n"
+ "(6 rows)\n"
+ "\n"
+ "!ok\n"
+ "\n";
check(input).contains(output);
}
/** Test case for
* <a href="https://github.com/julianhyde/quidem/issues/3">[QUIDEM-3]
* Trailing spaces in psql output format</a>. */
@Test public void testColumnHeading() {
// Note: There must not be trailing spaces after 'DEPTNO | B'
check(
"!use scott\n"
+ "!set outputformat psql\n"
+ "select deptno, deptno > 20 as b from scott.dept order by 1;\n"
+ "!ok\n"
+ "\n")
.contains("!use scott\n"
+ "!set outputformat psql\n"
+ "select deptno, deptno > 20 as b from scott.dept order by 1;\n"
+ " DEPTNO | B\n"
+ "--------+-------\n"
+ " 10 | FALSE\n"
+ " 20 | FALSE\n"
+ " 30 | TRUE\n"
+ " 40 | TRUE\n"
+ "(4 rows)\n"
+ "\n"
+ "!ok\n"
+ "\n");
}
/** Tests the '!update' command against INSERT and DELETE statements,
* and also checks an intervening '!plan'. */
@Test public void testUpdate() {
final String input = "!use scott\n"
+ "insert into scott.dept values (50, 'DEV', 'SAN DIEGO');\n"
+ "!update\n"
+ "!plan\n"
+ "\n";
final String output = "!use scott\n"
+ "insert into scott.dept values (50, 'DEV', 'SAN DIEGO');\n"
+ "(1 row modified)\n"
+ "\n"
+ "!update\n"
+ "INSERT VALUES[\n"
+ "\n"
+ "TABLE[DEPT]\n"
+ "PARAMETERS=[]\n"
+ "SUBQUERIES[]]\n"
+ "!plan\n"
+ "\n";
check(input).contains(output);
// remove the row
final String input2 = "!use scott\n"
+ "delete from scott.dept where deptno = 50;\n"
+ "!update\n"
+ "\n";
final String output2 = "!use scott\n"
+ "delete from scott.dept where deptno = 50;\n"
+ "(1 row modified)\n"
+ "\n"
+ "!update\n"
+ "\n";
check(input2).contains(output2);
// no row to remove
final String output3 = "!use scott\n"
+ "delete from scott.dept where deptno = 50;\n"
+ "(0 rows modified)\n"
+ "\n"
+ "!update\n"
+ "\n";
check(input2).contains(output3);
// for DML, using '!ok' works, but is not as pretty as '!update'
final String input4 = "!use scott\n"
+ "delete from scott.dept where deptno = 50;\n"
+ "!ok\n"
+ "\n";
final String output4 = "!use scott\n"
+ "delete from scott.dept where deptno = 50;\n"
+ "C1\n"
+ "!ok\n"
+ "\n";
check(input4).contains(output4);
}
/** Tests the '!type' command. */
@Test public void testType() {
final String input = "!use scott\n"
+ "select empno, deptno, sal from scott.emp where empno < 7400;\n"
+ "!ok\n"
+ "!type\n"
+ "\n";
final String output = "!use scott\n"
+ "select empno, deptno, sal from scott.emp where empno < 7400;\n"
+ "EMPNO, DEPTNO, SAL\n"
+ "7369, 20, 800.00\n"
+ "!ok\n"
+ "EMPNO SMALLINT(16) NOT NULL\n"
+ "DEPTNO TINYINT(8)\n"
+ "SAL DECIMAL(7, 2)\n"
+ "!type\n"
+ "\n";
check(input).contains(output);
}
/** Tests the '!verify' command. */
@Test public void testVerify() {
final String input = "!use empty\n"
+ "select * from INFORMATION_SCHEMA.TABLES;\n"
+ "!verify\n"
+ "\n";
final String output = "!use empty\n"
+ "select * from INFORMATION_SCHEMA.TABLES;\n"
+ "!verify\n"
+ "\n";
check(input).contains(output);
}
/** Tests the '!verify' command where the reference database produces
* different output. */
@Test public void testVerifyDiff() {
// Database "empty" sorts nulls first;
// its reference database sorts nulls last.
final String input = "!use empty\n"
+ "select * from (values (1,null),(2,'a')) order by 2;\n"
+ "!verify\n"
+ "\n";
final String output = "!use empty\n"
+ "select * from (values (1,null),(2,'a')) order by 2;\n"
+ "!verify\n"
+ "Error while executing command VerifyCommand [sql: select * from (values (1,null),(2,'a')) order by 2]\n"
+ "java.lang.IllegalArgumentException: Reference query returned different results.\n"
+ "expected:\n"
+ "C1, C2\n"
+ "2, a\n"
+ "1, null\n"
+ "actual:\n"
+ "C1, C2\n"
+ "1, null\n"
+ "2, a\n";
check(input).contains(output);
}
/** Tests the '!verify' command with a database that has no reference. */
@Test public void testVerifyNoReference() {
final String input = "!use scott\n"
+ "select * from scott.emp;\n"
+ "!verify\n"
+ "\n";
final String output = "!use scott\n"
+ "select * from scott.emp;\n"
+ "!verify\n"
+ "Error while executing command VerifyCommand [sql: select * from scott.emp]\n"
+ "java.lang.IllegalArgumentException: no reference connection\n";
check(input).contains(output);
}
@Test public void testUsage() throws Exception {
final Matcher<String> matcher =
startsWith("Usage: quidem argument... inFile outFile");
checkMain(matcher, 0, "--help");
}
@Test public void testDbBad() throws Exception {
checkMain(startsWith("Insufficient arguments for --db"), 1,
"--db", "name", "jdbc:url");
}
@Test public void testDb() throws Exception {
final File inFile =
writeFile("!use fm\nselect * from scott.dept;\n!ok\n");
final File outFile = File.createTempFile("outFile", ".iq");
final Matcher<String> matcher = equalTo("");
checkMain(matcher, 0, "--db", "fm", "jdbc:hsqldb:res:scott", "SA", "",
inFile.getAbsolutePath(), outFile.getAbsolutePath());
assertThat(toLinux(contents(outFile)),
equalTo("!use fm\n"
+ "select * from scott.dept;\n"
+ "DEPTNO, DNAME, LOC\n"
+ "10, ACCOUNTING, NEW YORK\n"
+ "20, RESEARCH, DALLAS\n"
+ "30, SALES, CHICAGO\n"
+ "40, OPERATIONS, BOSTON\n"
+ "!ok\n"));
//noinspection ResultOfMethodCallIgnored
inFile.delete();
//noinspection ResultOfMethodCallIgnored
outFile.delete();
}
private File writeFile(String contents) throws IOException {
final File inFile = File.createTempFile("inFile", ".iq");
final FileWriter fw = new FileWriter(inFile);
fw.append(contents);
fw.close();
return inFile;
}
@Test public void testFactoryBad() throws Exception {
checkMain(startsWith("Factory class non.existent.ClassName not found"), 1,
"--factory", "non.existent.ClassName");
}
@Test public void testFactoryBad2() throws Exception {
checkMain(startsWith("Error instantiating factory class java.lang.String"),
1, "--factory", "java.lang.String");
}
@Test public void testHelp() throws Exception {
final String in = "!use foo\n"
+ "values 1;\n"
+ "!ok\n";
final File inFile = writeFile(in);
final File outFile = File.createTempFile("outFile", ".iq");
final String out = "Usage: quidem argument... inFile outFile\n"
+ "\n"
+ "Arguments:\n"
+ " --help\n"
+ " Print usage\n"
+ " --db name url user password\n"
+ " Add a database to the connection factory\n"
+ " --var name value\n"
+ " Assign a value to a variable\n"
+ " --factory className\n"
+ " Define a connection factory (must implement interface\n"
+ " net.hydromatic.quidem.Quidem.ConnectionFactory)\n"
+ " --command-handler className\n"
+ " Define a command-handler (must implement interface\n"
+ " net.hydromatic.quidem.CommandHandler)\n";
checkMain(equalTo(out), 0, "--help",
inFile.getAbsolutePath(), outFile.getAbsolutePath());
assertThat(toLinux(contents(outFile)), equalTo(""));
//noinspection ResultOfMethodCallIgnored
inFile.delete();
//noinspection ResultOfMethodCallIgnored
outFile.delete();
}
@Test public void testFactory() throws Exception {
final File inFile =
writeFile("!use foo\nvalues 1;\n!ok\n");
final File outFile = File.createTempFile("outFile", ".iq");
checkMain(equalTo(""), 0, "--factory", FooFactory.class.getName(),
inFile.getAbsolutePath(), outFile.getAbsolutePath());
assertThat(toLinux(contents(outFile)),
equalTo("!use foo\nvalues 1;\nC1\n1\n!ok\n"));
//noinspection ResultOfMethodCallIgnored
inFile.delete();
//noinspection ResultOfMethodCallIgnored
outFile.delete();
}
@Test public void testUnknownCommandFails() {
final String in = "!use foo\nvalues 1;\n!ok\n!foo-command args";
try {
check(in).contains("xx");
fail("expected throw");
} catch (RuntimeException e) {
assertThat(e.getMessage(),
is("Unknown command: foo-command args"));
}
}
@Test public void testCustomCommandHandler() {
final String in0 = "!use foo\n"
+ "values 1;\n"
+ "!ok\n"
+ "!baz-command args";
final Quidem.ConfigBuilder configBuilder =
Quidem.configBuilder()
.withConnectionFactory(new FooFactory())
.withCommandHandler(new FooCommandHandler());
try {
new Fluent(in0, configBuilder)
.contains("xx");
fail("expected throw");
} catch (RuntimeException e) {
assertThat(e.getMessage(),
is("Unknown command: baz-command args"));
}
final String in = "!use foo\n"
+ "values 1;\n"
+ "!ok\n"
+ "!foo-command args";
final String out = "!use foo\n"
+ "values 1;\n"
+ "C1\n"
+ "1\n"
+ "!ok\n"
+ "the line: foo-command args\n"
+ "the command: FooCommand\n"
+ "previous SQL command: SqlCommand[sql: values 1, sort:true]\n";
new Fluent(in, configBuilder)
.contains(out);
}
@Test public void testCustomCommandHandlerMain() throws Exception {
final String in = "!use foo\n"
+ "values 1;\n"
+ "!ok\n"
+ "!foo-command args\n";
final File inFile = writeFile(in);
final File outFile = File.createTempFile("outFile", ".iq");
checkMain(equalTo(""), 0,
"--factory", FooFactory.class.getName(),
"--command-handler", FooCommandHandler.class.getName(),
inFile.getAbsolutePath(), outFile.getAbsolutePath());
final String expected = "!use foo\n"
+ "values 1;\n"
+ "C1\n"
+ "1\n"
+ "!ok\n"
+ "the line: foo-command args\n"
+ "the command: FooCommand\n"
+ "previous SQL command: SqlCommand[sql: values 1, sort:true]\n";
assertThat(toLinux(contents(outFile)),
equalTo(expected));
//noinspection ResultOfMethodCallIgnored
inFile.delete();
//noinspection ResultOfMethodCallIgnored
outFile.delete();
}
@Test public void testVar() throws Exception {
final File inFile =
writeFile("!if (myVar) {\nblah;\n!ok\n!}\n");
final File outFile = File.createTempFile("outFile", ".iq");
final Matcher<String> matcher = equalTo("");
checkMain(matcher, 0, "--var", "myVar", "true",
inFile.getAbsolutePath(), outFile.getAbsolutePath());
assertThat(toLinux(contents(outFile)),
startsWith("!if (myVar) {\n"
+ "blah;\n"
+ "!ok\n"
+ "Error while executing command OkCommand [sql: blah]\n"
+ "java.lang.RuntimeException: no connection\n"));
//noinspection ResultOfMethodCallIgnored
inFile.delete();
//noinspection ResultOfMethodCallIgnored
outFile.delete();
}
@Test public void testVarFalse() throws Exception {
final File inFile =
writeFile("!if (myVar) {\nblah;\n!ok\n!}\n");
final File outFile = File.createTempFile("outFile", ".iq");
final Matcher<String> matcher = equalTo("");
checkMain(matcher, 0, "--var", "myVar", "false",
inFile.getAbsolutePath(), outFile.getAbsolutePath());
assertThat(toLinux(contents(outFile)),
equalTo("!if (myVar) {\nblah;\n!ok\n!}\n"));
//noinspection ResultOfMethodCallIgnored
inFile.delete();
//noinspection ResultOfMethodCallIgnored
outFile.delete();
}
@Test public void testSetBoolean() {
final String input = "!use scott\n"
+ "!show foo\n"
+ "!set foo true\n"
+ "!show foo\n"
+ "!if (foo) {\n"
+ "values 1;\n"
+ "!ok;\n"
+ "!}\n"
+ "!set foo false\n"
+ "!if (foo) {\n"
+ "values 2;\n"
+ "!ok;\n"
+ "!}\n"
+ "!push foo true\n"
+ "!push foo false\n"
+ "!push foo true\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n";
final String output = "!use scott\n"
+ "foo null\n"
+ "!show foo\n"
+ "!set foo true\n"
+ "foo true\n"
+ "!show foo\n"
+ "!if (foo) {\n"
+ "values 1;\n"
+ "C1\n"
+ "1\n"
+ "!ok;\n"
+ "!}\n"
+ "!set foo false\n"
+ "!if (foo) {\n"
+ "values 2;\n"
+ "!ok;\n"
+ "!}\n"
+ "!push foo true\n"
+ "!push foo false\n"
+ "!push foo true\n"
+ "foo true\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo false\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo true\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo false\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo null\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "Cannot pop foo: stack is empty\n"
+ "foo null\n"
+ "!show foo\n";
check(input).contains(output);
}
@Test public void testSetInteger() {
final String input = "!use scott\n"
+ "!show foo\n"
+ "!set foo -123\n"
+ "!show foo\n"
+ "!push foo 345\n"
+ "!push bar 0\n"
+ "!push foo hello\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n";
final String output = "!use scott\n"
+ "foo null\n"
+ "!show foo\n"
+ "!set foo -123\n"
+ "foo -123\n"
+ "!show foo\n"
+ "!push foo 345\n"
+ "!push bar 0\n"
+ "!push foo hello\n"
+ "foo hello\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo 345\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo -123\n"
+ "!show foo\n"
+ "foo -123\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo null\n"
+ "!show foo\n";
check(input).contains(output);
}
/** Tests that the {@link net.hydromatic.quidem.Quidem.PropertyHandler} is
* called whenever there is a set, push or pop. */
@Test public void testPropertyHandler() {
final String input = "!use scott\n"
+ "!show foo\n"
+ "!set foo -123\n"
+ "!show foo\n"
+ "!push foo 345\n"
+ "!push bar 0\n"
+ "!push foo hello\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "!show foo\n";
final String output = "!use scott\n"
+ "foo null\n"
+ "!show foo\n"
+ "!set foo -123\n"
+ "foo -123\n"
+ "!show foo\n"
+ "!push foo 345\n"
+ "!push bar 0\n"
+ "!push foo hello\n"
+ "foo hello\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo 345\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo -123\n"
+ "!show foo\n"
+ "foo -123\n"
+ "!show foo\n"
+ "!pop foo\n"
+ "foo null\n"
+ "!show foo\n";
final StringBuilder b = new StringBuilder();
final Quidem.PropertyHandler propertyHandler =
(propertyName, value) -> b.append(propertyName).append('=')
.append(value).append('\n');
check(input).withPropertyHandler(propertyHandler).contains(output);
final String propertyEvents = "foo=-123\n"
+ "foo=345\n"
+ "bar=0\n"
+ "foo=hello\n"
+ "foo=345\n"
+ "foo=-123\n"
+ "foo=null\n";
assertThat(b.toString(), is(propertyEvents));
}
@Test public void testLimitWriter() throws IOException {
final StringWriter w = new StringWriter();
LimitWriter limitWriter = new LimitWriter(w, 6);
limitWriter.append("abcdefghiklmnopq");
assertThat(w.toString(), equalTo("abcdef"));
// We already exceeded limit. Clearing the backing buffer does not help.
w.getBuffer().setLength(0);
limitWriter.append("xxxxx");
limitWriter.append("yyyyy");
assertThat(w.toString(), equalTo(""));
// Create a new writer to reset the count.
limitWriter = new LimitWriter(w, 6);
w.getBuffer().setLength(0);
limitWriter.append("xxxxx");
limitWriter.append("yyyyy");
assertThat(w.toString(), equalTo("xxxxxy"));
limitWriter = new LimitWriter(w, 6);
w.getBuffer().setLength(0);
limitWriter.append("xxx");
limitWriter.append('y');
limitWriter.append('y');
limitWriter.append('y');
limitWriter.append('y');
limitWriter.append('y');
limitWriter.append('y');
limitWriter.append('y');
limitWriter.append("");
limitWriter.append('z');
limitWriter.append("zzzzzzzzz");
assertThat(w.toString(), equalTo("xxxyyy"));
limitWriter = new LimitWriter(w, 6);
w.getBuffer().setLength(1);
assertThat(w.toString(), equalTo("x"));
w.getBuffer().setLength(2);
assertThat(w.toString(), equalTo("x\0"));
limitWriter.write(new char[]{'a', 'a', 'a', 'a', 'a'}, 0, 3);
assertThat(w.toString(), equalTo("x\0aaa"));
}
private void checkMain(Matcher<String> matcher, int expectedCode,
String... args) throws Exception {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
final int code = Launcher.main2(pw, pw, Arrays.asList(args));
pw.close();
assertThat(code, equalTo(expectedCode));
assertThat(sw.toString(), matcher);
}
private static String contents(File file) throws IOException {
final FileReader reader = new FileReader(file);
final StringWriter sw = new StringWriter();
final char[] buf = new char[1024];
for (;;) {
final int read = reader.read(buf, 0, 1024);
if (read < 0) {
break;
}
sw.write(buf, 0, read);
}
return sw.toString();
}
static Fluent check(String input) {
return new Fluent(input);
}
static void check(String input, Quidem.ConfigBuilder configBuilder,
Matcher<String> matcher) {
final StringWriter writer = new StringWriter();
final Quidem.Config config = configBuilder
.withWriter(writer)
.withReader(new StringReader(input))
.build();
final Quidem run = new Quidem(config);
run.execute();
writer.flush();
String out = toLinux(writer.toString());
assertThat(out, matcher);
}
/** Creates a connection factory for use in tests. */
private static Quidem.ConnectionFactory dummyConnectionFactory() {
return (name, reference) -> {
if (name.equals("scott")) {
Class.forName("org.hsqldb.jdbcDriver");
final Connection connection =
DriverManager.getConnection("jdbc:hsqldb:res:scott", "SA",
"");
if (reference) {
return null; // no reference connection available for empty
}
return connection;
}
if (name.startsWith("empty")) {
Class.forName("org.hsqldb.jdbcDriver");
if (reference) {
name += "_ref";
}
final Connection connection =
DriverManager.getConnection("jdbc:hsqldb:mem:" + name, "",
"");
if (reference) {
final Statement statement = connection.createStatement();
statement.executeQuery("SET DATABASE SQL NULLS FIRST FALSE");
statement.close();
}
return connection;
}
throw new RuntimeException("unknown connection '" + name + "'");
};
}
/** Creates an environment for use in tests. */
private static Object dummyEnv(String input) {
assert input != null;
switch (input) {
case "affirmative":
return Boolean.TRUE;
case "negative":
return Boolean.FALSE;
case "sun":
return new Function<String, Object>() {
public Object apply(String input) {
assert input != null;
switch (input) {
case "hot":
return Boolean.TRUE;
case "cold":
return Boolean.FALSE;
case "self":
return this;
default:
return null;
}
}
};
default:
return null;
}
}
public static String toLinux(String s) {
return s.replaceAll("\r\n", "\n");
}
/** Matcher that applies a regular expression. */
public static class StringMatches extends SubstringMatcher {
public StringMatches(String pattern) {
super(pattern);
}
@Override protected boolean evalSubstringOf(String s) {
return s.matches(substring);
}
@Override protected String relationship() {
return "matching";
}
}
public static class FooFactory implements Quidem.ConnectionFactory {
public Connection connect(String name, boolean reference) throws Exception {
if (name.equals("foo")) {
return DriverManager.getConnection("jdbc:hsqldb:res:scott", "SA", "");
}
return null;
}
}
/** Implementation of {@link CommandHandler} for test purposes. */
public static class FooCommandHandler implements CommandHandler {
@Override public Command parseCommand(List<String> lines,
List<String> content, final String line) {
if (line.startsWith("foo")) {
return new Command() {
@Override public String describe(Context x) {
return "FooCommand";
}
@Override public void execute(Context x, boolean execute) {
x.writer().println("the line: " + line);
x.writer().println("the command: " + describe(x));
x.writer().println("previous SQL command: "
+ x.previousSqlCommand().describe(x));
}
};
}
return null;
}
}
/** Fluent class that contains an input string and allows you to test the
* output in various ways. */
private static class Fluent {
private final String input;
private final Quidem.ConfigBuilder configBuilder;
Fluent(String input) {
this(input, Quidem.configBuilder()
.withConnectionFactory(dummyConnectionFactory())
.withEnv((Function<String, Object>) QuidemTest::dummyEnv));
}
Fluent(String input, Quidem.ConfigBuilder configBuilder) {
this.input = input;
this.configBuilder = configBuilder;
}
public Fluent contains(String string) {
check(input, configBuilder, containsString(string));
return this;
}
public Fluent outputs(String string) {
check(input, configBuilder, equalTo(string));
return this;
}
public Fluent matches(String pattern) {
check(input, configBuilder, new StringMatches(pattern));
return this;
}
public Fluent limit(final int i) {
return new Fluent(input, configBuilder.withStackLimit(i));
}
public Fluent withPropertyHandler(
final Quidem.PropertyHandler propertyHandler) {
return new Fluent(input,
configBuilder.withPropertyHandler(propertyHandler));
}
}
}
// End QuidemTest.java
| 30.506709 | 115 | 0.473368 |
6b0a84def470473f19c4afc17cec28db1a9ac20d | 340 | package pl.lodz.p.edu.database.dao.definitions;
import androidx.room.Dao;
import androidx.room.Insert;
import pl.lodz.p.edu.database.entity.definitions.PackingListSectionDefinition;
@Dao
public interface PackingListSectionDefinitionsDao {
@Insert
void insertAll(PackingListSectionDefinition... packingListSectionDefinitions);
}
| 24.285714 | 82 | 0.820588 |
fe146f6408fd565febcb3a35ef8ef8d089421586 | 6,979 | /**
* Copyright (C) 2011-2018 Red Hat, Inc. (https://github.com/Commonjava/indy)
*
* 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.commonjava.indy.metrics.jaxrs.interceptor;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import org.commonjava.indy.measure.annotation.Measure;
import org.commonjava.indy.measure.annotation.MetricNamed;
import org.commonjava.indy.metrics.IndyMetricsManager;
import org.commonjava.indy.metrics.conf.IndyMetricsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.codahale.metrics.MetricRegistry.name;
import static org.commonjava.indy.metrics.IndyMetricsConstants.DEFAULT;
import static org.commonjava.indy.metrics.IndyMetricsConstants.EXCEPTION;
import static org.commonjava.indy.metrics.IndyMetricsConstants.METER;
import static org.commonjava.indy.metrics.IndyMetricsConstants.TIMER;
import static org.commonjava.indy.metrics.IndyMetricsConstants.getDefaultName;
import static org.commonjava.indy.metrics.IndyMetricsConstants.getName;
@Interceptor
@Measure
public class MetricsInterceptor
{
private final Logger logger = LoggerFactory.getLogger( getClass() );
@Inject
private IndyMetricsManager metricsManager;
@Inject
private IndyMetricsConfig config;
@AroundInvoke
public Object operation( InvocationContext context ) throws Exception
{
if ( !config.isMetricsEnabled() )
{
return context.proceed();
}
Method method = context.getMethod();
Measure measure = method.getAnnotation( Measure.class );
if ( measure == null )
{
measure = method.getDeclaringClass().getAnnotation( Measure.class );
}
String defaultName = getDefaultName( context.getMethod().getDeclaringClass(), context.getMethod().getName() );
logger.trace( "Gathering metrics for: {} using context: {}", defaultName, context.getContextData() );
boolean inject = measure.timers().length < 1 && measure.exceptions().length < 1 && measure.meters().length < 1;
List<Timer.Context> timers = initTimers( measure, defaultName, inject );
List<String> exceptionMeters = initMeters( measure, measure.exceptions(), EXCEPTION, defaultName, inject );
List<String> meters = initMeters( measure, measure.meters(), METER, defaultName, inject );
try
{
meters.forEach( ( name ) -> {
Meter meter = metricsManager.getMeter( name + ".starts" );
logger.trace( "CALLS++ {}", name );
meter.mark();
logger.trace("Meter count for: {} is: {}", name, new Object(){
public String toString(){
return String.valueOf( metricsManager.getMeter( name ).getCount() );
}
});
} );
return context.proceed();
}
catch ( Exception e )
{
exceptionMeters.forEach( ( name ) -> {
metricsManager.getMeter( name ).mark();
logger.trace("Meter count for: {} is: {}", name, new Object(){
public String toString(){
return String.valueOf( metricsManager.getMeter( name ).getCount() );
}
});
metricsManager.getMeter( name( name, e.getClass().getSimpleName() ) ).mark();
logger.trace("Meter count for: {} is: {}", name, new Object(){
public String toString(){
return String.valueOf( metricsManager.getMeter( name ).getCount() );
}
});
} );
throw e;
}
finally
{
if ( timers != null )
{
timers.forEach( timer->{
logger.trace( "STOP: {}", timer );
timer.stop();
} );
}
meters.forEach( ( name ) -> {
Meter meter = metricsManager.getMeter( name );
logger.trace( "CALLS++ {}", name );
meter.mark();
logger.trace("Meter count for: {} is: {}", name, new Object(){
public String toString(){
return String.valueOf( metricsManager.getMeter( name ).getCount() );
}
});
} );
}
}
private List<String> initMeters( final Measure measure, final MetricNamed[] metrics, String classifier,
final String defaultName, final boolean inject )
{
List<String> meters;
if ( inject && ( metrics == null || metrics.length == 0 ) )
{
meters = Collections.singletonList( getName( config.getNodePrefix(), DEFAULT, defaultName, classifier ) );
}
else
{
meters = Stream.of( metrics )
.map( metric -> getName( config.getNodePrefix(), metric.value(), defaultName, classifier ) )
.collect( Collectors.toList() );
}
logger.trace( "Got meters for {} with classifier: {}: {}", defaultName, classifier, meters );
return meters;
}
private List<Timer.Context> initTimers( final Measure measure, String defaultName, final boolean inject )
{
List<Timer.Context> timers;
MetricNamed[] timerMetrics = measure.timers();
if ( inject && timerMetrics.length == 0 )
{
timers = Collections.singletonList(
metricsManager.getTimer( getName( config.getNodePrefix(), DEFAULT, defaultName, TIMER ) ).time() );
}
else
{
timers = Stream.of( timerMetrics ).map( named -> {
String name = getName( config.getNodePrefix(), named.value(), defaultName, TIMER );
Timer.Context tc = metricsManager.getTimer( name ).time();
logger.trace( "START: {} ({})", name, tc );
return tc;
} ).collect( Collectors.toList() );
}
return timers;
}
}
| 37.929348 | 119 | 0.597077 |
0b42261c1822e03c24df39042f93056951cd030b | 2,160 | package com.example.demo.service.Impl;
import com.example.demo.exception.NotFound;
import com.example.demo.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author WeLong
* @create 2019/10/25 20:11
*/
@Service
public class ArtServiceImpl implements ArtService {
@Autowired
MovieService movieService;
@Autowired
MusicService musicService;
@Autowired
SentenceService sentenceService;
@Autowired
BookService bookService;
@Override
public Object getData(int art_id, int type){
switch (type){
case 100:
return movieService.getData(art_id,type);
case 200:
return musicService.getData(art_id,type);
case 300:
return sentenceService.getData(art_id,type);
case 400:
break;
default:
throw new NotFound("资源未找到");
}
throw new NotFound("资源未找到");
}
@Override
public void updataData(int art_id, int type){
switch (type){
case 100:
movieService.updataData(art_id,type);
break;
case 200:
musicService.updataData(art_id,type);
break;
case 300:
sentenceService.updataData(art_id,type);
break;
case 400:
bookService.updateData(art_id);
break;
default:
throw new NotFound("点赞失败!");
}
}
@Override
public void deleteData(int art_id, int type){
switch (type){
case 100:
movieService.deleteData(art_id,type);
break;
case 200:
musicService.deleteData(art_id,type);
break;
case 300:
sentenceService.deleteData(art_id,type);
break;
case 400:
bookService.deleteData(art_id);
break;
default:
throw new NotFound("取消点赞失败!");
}
}
}
| 26.666667 | 62 | 0.539352 |
6d852b5bb4942d7ce003fe5f74963b3e07856482 | 8,961 | package com.averi.worldscribe.activities;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.averi.worldscribe.ArticleTextField;
import com.averi.worldscribe.Category;
import com.averi.worldscribe.Membership;
import com.averi.worldscribe.R;
import com.averi.worldscribe.adapters.MembersAdapter;
import com.averi.worldscribe.utilities.ExternalDeleter;
import com.averi.worldscribe.utilities.ExternalWriter;
import com.averi.worldscribe.utilities.IntentFields;
import com.averi.worldscribe.views.ArticleSectionCollapser;
import com.averi.worldscribe.views.BottomBar;
import java.util.ArrayList;
public class GroupActivity extends ArticleActivity {
public static final int RESULT_NEW_MEMBER = 300;
private RecyclerView membersList;
private Button addMemberButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
membersList = (RecyclerView) findViewById(R.id.recyclerMembers);
addMemberButton = (Button) findViewById(R.id.buttonAddMember);
addMemberButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { addMember(); }
});
}
@Override
protected int getLayoutResourceID() {
return R.layout.activity_group;
}
@Override
protected ViewGroup getRootLayout() {
return (ViewGroup) findViewById(R.id.coordinatorLayout);
}
@Override
protected NestedScrollView getNestedScrollView() {
return (NestedScrollView) findViewById(R.id.scrollView);
}
@Override
protected ImageView getImageView() { return (ImageView) findViewById(R.id.imageGroup); }
@Override
protected BottomBar getBottomBar() {
return (BottomBar) findViewById(R.id.bottomBar);
}
@Override
protected RecyclerView getConnectionsRecycler() {
return (RecyclerView) findViewById(R.id.recyclerConnections);
}
@Override
protected Button getAddConnectionButton() {
return (Button) findViewById(R.id.buttonAddConnection);
}
@Override
protected RecyclerView getSnippetsRecycler() {
return (RecyclerView) findViewById(R.id.recyclerSnippets);
}
@Override
protected Button getAddSnippetButton() {
return (Button) findViewById(R.id.buttonAddSnippet);
}
@Override
protected ArrayList<ArticleTextField> getTextFields() {
Resources resources = getResources();
ArrayList<ArticleTextField> textFields = new ArrayList<>();
textFields.add(new ArticleTextField("Mandate",
(EditText) findViewById(R.id.editMandate),
this, getWorldName(), Category.Group, getArticleName()));
textFields.add(new ArticleTextField("History",
(EditText) findViewById(R.id.editHistory),
this, getWorldName(), Category.Group, getArticleName()));
return textFields;
}
@Override
protected TextView getGeneralInfoHeader() {
return (TextView) findViewById(R.id.textGeneralInfo);
}
@Override
protected ViewGroup getGeneralInfoLayout() {
return (LinearLayout) findViewById(R.id.linearGeneralInfo);
}
@Override
protected TextView getConnectionsHeader() {
return (TextView) findViewById(R.id.textConnections);
}
@Override
protected ViewGroup getConnectionsLayout() {
return (LinearLayout) findViewById(R.id.linearConnections);
}
@Override
protected TextView getSnippetsHeader() {
return (TextView) findViewById(R.id.textSnippets);
}
@Override
protected ViewGroup getSnippetsLayout() {
return (LinearLayout) findViewById(R.id.linearSnippets);
}
@Override
protected void onResume() {
super.onResume();
populateMembers();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_NEW_MEMBER:
if (resultCode == RESULT_OK) {
Membership newMembership = new Membership();
newMembership.worldName = getWorldName();
newMembership.groupName = getArticleName();
newMembership.memberName = data.getStringExtra(IntentFields.ARTICLE_NAME);
Intent editMembershipIntent = new Intent(this, EditMembershipActivity.class);
editMembershipIntent.putExtra(IntentFields.MEMBERSHIP, newMembership);
startActivity(editMembershipIntent);
}
}
}
@Override
protected void addSectionCollapsers() {
TextView membersHeader = (TextView) findViewById(R.id.textMembers);
membersHeader.setOnClickListener(new ArticleSectionCollapser(this, membersHeader,
(LinearLayout) findViewById(R.id.linearMembers)));
super.addSectionCollapsers();
}
private void populateMembers() {
membersList.setLayoutManager(new LinearLayoutManager(this));
membersList.setAdapter(new MembersAdapter(this, getWorldName(), getArticleName()));
}
/**
* Opens SelectArticleActivity so the user can select a new Member to add to this Group.
*/
private void addMember() {
Intent selectGroupIntent = new Intent(this, SelectArticleActivity.class);
MembersAdapter membersAdapter = (MembersAdapter) membersList.getAdapter();
selectGroupIntent.putExtra(IntentFields.WORLD_NAME, getWorldName());
selectGroupIntent.putExtra(IntentFields.CATEGORY, Category.Person);
selectGroupIntent.putExtra(IntentFields.MAIN_ARTICLE_CATEGORY, Category.Group);
selectGroupIntent.putExtra(IntentFields.MAIN_ARTICLE_NAME, getArticleName());
selectGroupIntent.putExtra(IntentFields.EXISTING_LINKS,
membersAdapter.getLinkedArticleList());
startActivityForResult(selectGroupIntent, RESULT_NEW_MEMBER);
}
@Override
protected void deleteArticle() {
if (removeAllMembers()) {
super.deleteArticle();
} else {
Toast.makeText(this, getString(R.string.deleteArticleError), Toast.LENGTH_SHORT).show();
}
}
/**
* Deletes all Memberships to this Group.
* @return True if all Memberships were deleted successfully; false otherwise.
*/
private boolean removeAllMembers() {
boolean membersWereRemoved = true;
ArrayList<Membership> allMemberships = (
(MembersAdapter) membersList.getAdapter()).getMemberships();
Membership membership;
int index = 0;
while ((index < allMemberships.size()) && (membersWereRemoved)) {
membership = allMemberships.get(index);
membersWereRemoved = ExternalDeleter.deleteMembership(this, membership);
index++;
}
return membersWereRemoved;
}
@Override
protected boolean renameArticle(String newName) {
boolean renameWasSuccessful = false;
if (renameGroupInMemberships(newName)) {
renameWasSuccessful = super.renameArticle(newName);
} else {
Toast.makeText(this, R.string.renameArticleError, Toast.LENGTH_SHORT).show();
}
return renameWasSuccessful;
}
/**
* <p>
* Updates all Memberships to this Group to reflect a new Group name.
* </p>
* <p>
* If one or more Memberships failed to be updated, an error message is displayed.
* </p>
* @param newName The new name for this Group.
* @return True if all Memberships updated successfully; false otherwise.
*/
private boolean renameGroupInMemberships(String newName) {
boolean membershipsWereUpdated = true;
MembersAdapter adapter = (MembersAdapter) membersList.getAdapter();
ArrayList<Membership> memberships = adapter.getMemberships();
int index = 0;
Membership membership;
while ((index < memberships.size()) && (membershipsWereUpdated)) {
membership = memberships.get(index);
if (ExternalWriter.renameGroupInMembership(this, membership, newName)) {
membership.groupName = newName;
} else {
membershipsWereUpdated = false;
}
index++;
}
return membershipsWereUpdated;
}
}
| 33.066421 | 100 | 0.679165 |
5243350935b96058a8eaad118fc8a2dbc3836ef2 | 1,585 | package com.hnsfdx.hslife.service.serviceimpl;
import com.hnsfdx.hslife.annotation.ReadCache;
import com.hnsfdx.hslife.annotation.WriteCache;
import com.hnsfdx.hslife.async.EventType;
import com.hnsfdx.hslife.pojo.Answer;
import com.hnsfdx.hslife.repository.AnswerRepository;
import com.hnsfdx.hslife.service.AnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AnswerServicelmpl implements AnswerService {
private AnswerRepository answerRepository;
@Autowired
public AnswerServicelmpl(AnswerRepository answerRepository){
this.answerRepository = answerRepository;
}
@WriteCache(topic = "answer")
@Override
public Integer addSingleAnswer(Answer answer){
return answerRepository.insertSingleAnswer(answer);
}
@ReadCache(value = "answer")
@Override
public List<Answer> getAllAnswerByEntertainmentId(Integer enterId,Integer offset, Integer size){
return answerRepository.findAllAnswerByEntertainmentId(enterId,offset,size);
}
@Override
public Integer getAllAnswersCount(Integer enId) {
return answerRepository.countAllAnswers(enId);
}
@Override
public Integer doUserAnswer(Integer qid, String uid){return answerRepository.doUserAnswer(qid,uid);}
@ReadCache(value = "answer")
@Override
public List<Answer> get3FirstRightAnswer(Integer enterId, String rightAnswer) {
return answerRepository.find3FirstRightAnswer(enterId, rightAnswer);
}
}
| 31.7 | 104 | 0.769716 |
7de6499896f8d331bb74a52ff12736fd4d7a2dd8 | 1,381 | package controllers;
import com.typesafe.plugin.MailerAPI;
import com.typesafe.plugin.MailerPlugin;
import play.*;
import play.data.Form;
import play.mvc.*;
import views.html.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Application extends Controller {
private static String ADMIN_EMAIL = Play.application().configuration().getString("admin.email");
public static Result index() {
return ok(index.render());
}
public static Result email() {
String name = Form.form().bindFromRequest().data().get("name");
String email = Form.form().bindFromRequest().data().get("email");
String phone = Form.form().bindFromRequest().data().get("phone");
String message = Form.form().bindFromRequest().data().get("message");
MailerAPI mail = play.Play.application().plugin(MailerPlugin.class).email();
mail.setSubject("New message from website visitor " + name);
mail.setRecipient(ADMIN_EMAIL);
mail.setFrom(ADMIN_EMAIL);
String body = "Received an inquiry from the website's contact form at:<br/><br/>" +
"Name: " + name + "<br/>" +
"Email: " + email + "<br/>" +
"Phone: " + phone + "<br/>" +
"Message: " + message + "<br/>";
mail.sendHtml(body);
return ok(index.render());
}
}
| 31.386364 | 100 | 0.619117 |
556d77bf87875684baec3e6d1b7e2cc885852d31 | 473 | package top.gumt.mall.coupon.service;
import com.baomidou.mybatisplus.extension.service.IService;
import top.gumt.common.utils.PageUtils;
import top.gumt.mall.coupon.entity.SmsSeckillSkuNoticeEntity;
import java.util.Map;
/**
* 秒杀商品通知订阅
*
* @author zhaoming
* @email gumt0310@gmail.com
* @date 2021-07-15 20:45:27
*/
public interface SmsSeckillSkuNoticeService extends IService<SmsSeckillSkuNoticeEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| 22.52381 | 89 | 0.778013 |
f3b11ee44b977ea302944e44f9052e848b2d9667 | 334 | package br.com.zupacademy.rafael.casadocodigo.repositories;
import br.com.zupacademy.rafael.casadocodigo.entities.Categoria;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoriaRepository extends JpaRepository<Categoria,Long> {
}
| 23.857143 | 76 | 0.847305 |
0ed3330981455e41f83b78d74b2bbc1574902300 | 2,538 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class CCC00S4 {
static int[] clubs;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int distance = Integer.parseInt(reader.readLine());
int numClubs = Integer.parseInt(reader.readLine());
// Read in all the clubs
clubs = new int[numClubs];
for(int i = 0; i < numClubs; i ++) {
clubs[i] = Integer.parseInt(reader.readLine());
}
int result = fewestStrokes(distance);
System.out.println(result == Integer.MAX_VALUE ? "Roberta acknowledges defeat."
: "Roberta wins in " + result + " strokes.");
}
// This map keeps track of all the distances for which the fewest strokes is known
// This is so that we can reuse our previous results
static Map<Integer, Integer> known = new HashMap<>();
static int fewestStrokes(int distance) {
// Base case
if(distance == 0) {
return 0;
}
// Check if we encountered this distance before
if(known.containsKey(distance)) {
return known.get(distance);
}
// Another base case
// Check if any of the clubs have the exact same distance as requested
for(int club : clubs) {
if(club == distance) {
return 1;
}
}
// No matches found - break up the problem into sub-problems
// Try out every club
int min = Integer.MAX_VALUE;
for(int club : clubs) {
// Make sure the club hits a distance less than the distance left
if(club <= distance) {
// Recurse with the new distance after hitting with this club
int result = fewestStrokes(distance - club);
min = Math.min(result, min);
}
}
// Now min should hold the fewest strokes possible after trying out one club
// or Integer.MAX_VALUE if it's not possible
// Add one to the result since we used a stroke above
// But if it's not possible then don't add 1, as that would overflow the int and make it negative
min = min == Integer.MAX_VALUE ? min : min + 1;
// First put the result into the map for future use
known.put(distance, min);
return min;
}
}
| 34.767123 | 105 | 0.595351 |
575f19c99e3a8a54d8e96d0c121e87e9e6571b02 | 11,908 | package com.enjin.enjincraft.spigot.token;
import com.enjin.enjincraft.spigot.SpigotBootstrap;
import com.enjin.enjincraft.spigot.player.EnjPlayer;
import com.enjin.enjincraft.spigot.player.PlayerManager;
import com.enjin.sdk.services.notification.NotificationsService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.*;
public class TokenManager {
// Status codes
public static final int TOKEN_CREATE_SUCCESS = 200; // Token was created
public static final int TOKEN_UPDATE_SUCCESS = 201; // Token was updated
public static final int TOKEN_CREATE_FAILED = 400; // Token was not created
public static final int TOKEN_UPDATE_FAILED = 401; // Token was not updated
public static final int TOKEN_NOSUCHTOKEN = 402; // The token does not exist
public static final int TOKEN_DUPLICATENICKNAME = 403; // Token alternate id already exists
public static final int TOKEN_HASNICKNAME = 404; // Token has alternate
public static final int PERM_ADDED_SUCCESS = 210; // Permission was added
public static final int PERM_ADDED_DUPLICATEPERM = 410; // Permission is a duplicate
public static final int PERM_ADDED_BLACKLISTED = 411; // Permission is blacklisted
public static final int PERM_REMOVED_SUCCESS = 250; // Permission was removed
public static final int PERM_REMOVED_NOPERMONTOKEN = 450; // Permission is not assigned
public static final String JSON_EXT = ".json";
public static final int JSON_EXT_LENGTH = JSON_EXT.length();
public static final String GLOBAL = "*";
private final Gson gson = new GsonBuilder()
.registerTypeAdapter(TokenPermission.class, new TokenPermission.TokenPermissionSerializer())
.registerTypeAdapter(TokenPermission.class, new TokenPermission.TokenPermissionDeserializer())
.setPrettyPrinting()
.create();
private SpigotBootstrap bootstrap;
private File dir;
private Map<String, TokenModel> tokenModels = new HashMap<>();
private Map<String, String> alternateIds = new HashMap<>();
private TokenPermissionGraph permGraph = new TokenPermissionGraph();
public TokenManager(SpigotBootstrap bootstrap, File dir) {
this.bootstrap = bootstrap;
this.dir = new File(dir, "tokens");
}
public void loadTokens() {
if (!dir.exists())
dir.mkdirs();
tokenModels.clear();
for (File file : dir.listFiles()) {
// Ignores directories and non-JSON files
if (file.isDirectory() || !file.getName().endsWith(".json"))
continue;
TokenModel tokenModel = null;
boolean changed = false;
try (FileReader fr = new FileReader(file)) {
tokenModel = gson.fromJson(fr, TokenModel.class);
tokenModel.load();
changed = tokenModel.applyBlacklist(bootstrap.getConfig().getPermissionBlacklist());
cacheAndSubscribe(tokenModel);
} catch (Exception e) {
bootstrap.log(e);
} finally {
if (changed)
saveToken(tokenModel);
}
}
LegacyTokenConverter legacyConverter = new LegacyTokenConverter(bootstrap);
if (legacyConverter.fileExists())
legacyConverter.process();
}
public int saveToken(TokenModel tokenModel) {
// Prevents tokens with the same alternate id from existing
String alternateId = tokenModel.getAlternateId();
String otherToken = alternateIds.get(alternateId);
if (alternateId != null && otherToken != null && !otherToken.equals(tokenModel.getId()))
return TOKEN_DUPLICATENICKNAME;
if (!dir.exists())
dir.mkdirs();
File file = new File(dir, String.format("%s%s", tokenModel.getId(), JSON_EXT));
tokenModel.applyBlacklist(bootstrap.getConfig().getPermissionBlacklist());
try (FileWriter fw = new FileWriter(file, false)) {
gson.toJson(tokenModel, fw);
tokenModel.load();
cacheAndSubscribe(tokenModel);
if (tokenModel.getAlternateId() != null)
alternateIds.put(tokenModel.getAlternateId(), tokenModel.getId());
} catch (Exception e) {
bootstrap.log(e);
return TOKEN_CREATE_FAILED;
}
return TOKEN_CREATE_SUCCESS;
}
private void cacheAndSubscribe(TokenModel tokenModel) {
tokenModels.put(tokenModel.getId(), tokenModel);
permGraph.addToken(tokenModel);
subscribeToToken(tokenModel);
}
public int updateTokenConf(TokenModel tokenModel) {
TokenModel oldModel = tokenModels.get(tokenModel.getId());
if (!dir.exists() || oldModel == null)
return saveToken(tokenModel);
File file = new File(dir, String.format("%s%s", tokenModel.getId(), JSON_EXT));
tokenModel.applyBlacklist(bootstrap.getConfig().getPermissionBlacklist());
boolean newNbt = !tokenModel.getNbt().equals(oldModel.getNbt());
try (FileWriter fw = new FileWriter(file, false)) {
gson.toJson(tokenModel, fw);
tokenModel.load();
tokenModels.put(tokenModel.getId(), tokenModel);
} catch (Exception e) {
bootstrap.log(e);
return TOKEN_UPDATE_FAILED;
}
if (newNbt)
updateTokenOnPlayers(tokenModel.getId());
return TOKEN_UPDATE_SUCCESS;
}
private void updateTokenOnPlayers(String tokenId) {
PlayerManager playerManager = bootstrap.getPlayerManager();
if (playerManager == null)
return;
for (UUID uuid : playerManager.getPlayers().keySet()) {
Optional<EnjPlayer> player = playerManager.getPlayer(uuid);
player.ifPresent(enjPlayer -> enjPlayer.updateToken(tokenId));
}
}
public int updateAlternateId(String tokenId, String alternateId) {
if (!tokenModels.containsKey(tokenId))
return TOKEN_NOSUCHTOKEN;
TokenModel tokenModel = tokenModels.get(tokenId);
if (tokenModel.getAlternateId() != null && alternateId.equals(tokenModel.getAlternateId()))
return TOKEN_HASNICKNAME;
else if (alternateIds.containsKey(alternateId))
return TOKEN_DUPLICATENICKNAME;
if (tokenModel.getAlternateId() != null)
alternateIds.remove(tokenModel.getAlternateId());
tokenModel.setAlternateId(alternateId);
alternateIds.put(alternateId, tokenId);
return updateTokenConf(tokenModel);
}
public int addPermissionToToken(String perm, String id, String world) {
if (bootstrap.getConfig().getPermissionBlacklist().contains(perm))
return PERM_ADDED_BLACKLISTED;
TokenModel tokenModel = getToken(id);
if (tokenModel == null)
return TOKEN_NOSUCHTOKEN;
// Checks if the permission was not added
if (!tokenModel.addPermissionToWorld(perm, world))
return PERM_ADDED_DUPLICATEPERM;
permGraph.addTokenPerm(perm, tokenModel.getId(), world);
int status = updateTokenConf(tokenModel);
addPermissionToPlayers(perm, tokenModel.getId(), world);
if (status != TOKEN_UPDATE_SUCCESS)
return status;
return PERM_ADDED_SUCCESS;
}
public int addPermissionToToken(String perm, String id, Collection<String> worlds) {
if (bootstrap.getConfig().getPermissionBlacklist().contains(perm))
return PERM_ADDED_BLACKLISTED;
TokenModel tokenModel = getToken(id);
if (tokenModel == null)
return TOKEN_NOSUCHTOKEN;
// Checks if the permission was not added
if (!tokenModel.addPermissionToWorlds(perm, worlds))
return PERM_ADDED_DUPLICATEPERM;
permGraph.addTokenPerm(perm, tokenModel.getId(), worlds);
int status = updateTokenConf(tokenModel);
worlds.forEach(world -> addPermissionToPlayers(perm, tokenModel.getId(), world));
if (status != TOKEN_UPDATE_SUCCESS)
return status;
return PERM_ADDED_SUCCESS;
}
private void addPermissionToPlayers(String perm, String tokenId, String world) {
PlayerManager playerManager = bootstrap.getPlayerManager();
for (UUID uuid : playerManager.getPlayers().keySet()) {
Optional<EnjPlayer> player = playerManager.getPlayer(uuid);
player.ifPresent(enjPlayer -> enjPlayer.addPermission(perm, tokenId, world));
}
}
public int removePermissionFromToken(String perm, String id, String world) {
TokenModel tokenModel = getToken(id);
if (tokenModel == null)
return TOKEN_NOSUCHTOKEN;
// Checks if the permission was not removed
if (!tokenModel.removePermissionFromWorld(perm, world))
return PERM_REMOVED_NOPERMONTOKEN;
permGraph.removeTokenPerm(perm, tokenModel.getId(), world);
int status = updateTokenConf(tokenModel);
removePermissionFromPlayers(perm, world);
if (status != TOKEN_UPDATE_SUCCESS)
return status;
return PERM_REMOVED_SUCCESS;
}
public int removePermissionFromToken(String perm, String id, Collection<String> worlds) {
TokenModel tokenModel = getToken(id);
if (tokenModel == null)
return TOKEN_NOSUCHTOKEN;
// Checks if the permission was not removed
if (!tokenModel.removePermissionFromWorlds(perm, worlds))
return PERM_REMOVED_NOPERMONTOKEN;
permGraph.removeTokenPerm(perm, tokenModel.getId(), worlds);
int status = updateTokenConf(tokenModel);
worlds.forEach(world -> removePermissionFromPlayers(perm, world));
if (status != TOKEN_UPDATE_SUCCESS)
return status;
return PERM_REMOVED_SUCCESS;
}
private void removePermissionFromPlayers(String perm, String world) {
PlayerManager playerManager = bootstrap.getPlayerManager();
for (UUID uuid : playerManager.getPlayers().keySet()) {
Optional<EnjPlayer> player = playerManager.getPlayer(uuid);
player.ifPresent(enjPlayer -> enjPlayer.removePermission(perm, world));
}
}
public boolean hasToken(String id) {
if (hasAlternateId(id))
return true;
return tokenModels.containsKey(id);
}
public boolean hasAlternateId(String id) {
return alternateIds.containsKey(id);
}
public TokenModel getToken(String id) {
if (hasAlternateId(id))
id = alternateIds.get(id);
return tokenModels.get(id);
}
public Set<String> getTokenIds() {
return new HashSet<>(tokenModels.keySet());
}
public Set<String> getAlternateIds() {
return new HashSet<>(alternateIds.keySet());
}
public Set<TokenModel> getTokens() {
return new HashSet<>(tokenModels.values());
}
public Set<Map.Entry<String, TokenModel>> getEntries() {
return new HashSet<>(tokenModels.entrySet());
}
public TokenPermissionGraph getTokenPermissions() {
return permGraph;
}
public void subscribeToTokens() {
for (Map.Entry<String, TokenModel> entry : tokenModels.entrySet()) {
subscribeToToken(entry.getValue());
}
}
private void subscribeToToken(TokenModel tokenModel) {
if (tokenModel == null)
return;
NotificationsService service = bootstrap.getNotificationsService();
if (service != null && !service.isSubscribedToToken(tokenModel.getId()))
service.subscribeToToken(tokenModel.getId());
}
}
| 35.023529 | 106 | 0.652586 |
92f9861cedbd46c7303b4a58fc9d802239cb4b4f | 350 | package de.teamLocster.chat;
import de.teamLocster.core.BaseRepository;
import de.teamLocster.user.User;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* has not yet been implemented
*/
@Repository
public interface ChatRepository extends BaseRepository<Chat> {
List<Chat> findChatsByUsersContains(User user);
}
| 21.875 | 62 | 0.794286 |
994b7745e000812d80d7ba936dadd5ecff4dc339 | 17,130 | package org.ovirt.engine.core.bll.tasks;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import org.ovirt.engine.core.bll.CommandBase;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.tasks.interfaces.CommandCoordinator;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.asynctasks.AsyncTaskCreationInfo;
import org.ovirt.engine.core.common.businessentities.AsyncTask;
import org.ovirt.engine.core.common.businessentities.AsyncTaskStatus;
import org.ovirt.engine.core.common.businessentities.CommandAssociatedEntity;
import org.ovirt.engine.core.common.businessentities.CommandEntity;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.SubjectEntity;
import org.ovirt.engine.core.compat.CommandStatus;
import org.ovirt.engine.core.compat.DateTime;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.backendcompat.CommandExecutionStatus;
public class CommandCoordinatorUtil {
public static final CommandCoordinator coco = new CommandCoordinatorImpl();
/**
* Start polling the task identified by the vdsm task id
* @param taskID The vdsm task id
*/
public static void startPollingTask(Guid taskID) {
getAsyncTaskManager().startPollingTask(taskID);
}
/**
* Retrieves from the specified storage pool the tasks that exist on it and
* adds them to the async task manager.
*
* @param sp the storage pool to retrieve running tasks from
*/
public static void addStoragePoolExistingTasks(StoragePool sp) {
getAsyncTaskManager().addStoragePoolExistingTasks(sp);
}
/**
* Checks if there are tasks of the specified type existing on the entity
* @param id The entity id
* @param type The action type
*/
public static boolean hasTasksForEntityIdAndAction(Guid id, VdcActionType type) {
return getAsyncTaskManager().hasTasksForEntityIdAndAction(id, type);
}
/**
* Checks if there are tasks existing on the storage pool
* @param storagePoolID Id of the storage pool
*/
public static boolean hasTasksByStoragePoolId(Guid storagePoolID) {
return getAsyncTaskManager().hasTasksByStoragePoolId(storagePoolID);
}
/**
* Initialize Async Task Manager.
*/
public static void initAsyncTaskManager() {
getAsyncTaskManager().initAsyncTaskManager();
}
/**
* Checks if there are tasks on the entity
* @param id The entity id
*/
public static boolean entityHasTasks(Guid id) {
return getAsyncTaskManager().entityHasTasks(id);
}
/**
* Poll vdsm for the task status and update the task
* @param taskIdList The list of task ids
* @return List of async task status
*/
public static ArrayList<AsyncTaskStatus> pollTasks(java.util.ArrayList<Guid> taskIdList) {
return getAsyncTaskManager().pollTasks(taskIdList);
}
/**
* Create an Async Task.
* @param taskId the id of the async task place holder in the database
* @param command the command object creating the task
* @param asyncTaskCreationInfo Info on how to create the task
* @param parentCommand The type of command issuing the task
* @param description A message which describes the task
* @param entitiesMap map of entities
*/
public static Guid createTask(
Guid taskId,
CommandBase<?> command,
AsyncTaskCreationInfo asyncTaskCreationInfo,
VdcActionType parentCommand,
String description,
Map<Guid, VdcObjectType> entitiesMap) {
return coco.createTask(taskId,
command,
asyncTaskCreationInfo,
parentCommand,
description,
entitiesMap);
}
/**
* Create the {@link SPMAsyncTask} object to be run
* @param taskId the id of the async task place holder in the database
* @param command the command object creating the task
* @param asyncTaskCreationInfo Info on how to create the task
* @param parentCommand The type of command issuing the task
*/
public static SPMAsyncTask concreteCreateTask(
Guid taskId,
CommandBase<?> command,
AsyncTaskCreationInfo asyncTaskCreationInfo,
VdcActionType parentCommand) {
return coco.concreteCreateTask(taskId,
command,
asyncTaskCreationInfo,
parentCommand);
}
/**
* Stops all tasks, and set them to polling state, for clearing them up later.
* @param command The command whose vdsm tasks need to be cancelled
*/
public static void cancelTasks(final CommandBase<?> command) {
coco.cancelTasks(command);
}
/**
* Revert the vdsm tasks associated with the command
* @param command The command whose vdsm tasks need to be reverted
*/
public static void revertTasks(final CommandBase<?> command) {
coco.revertTasks(command);
}
/**
* Retrieve the async task by task id, create one if it does not exist.
* @param taskId the id of the async task place holder in the database
* @param command the command object retrieving or creating the task
* @param asyncTaskCreationInfo Info on how to create the task if one does not exist
* @param parentCommand The type of command issuing the task
*/
public static AsyncTask getAsyncTask(
Guid taskId,
CommandBase<?> command,
AsyncTaskCreationInfo asyncTaskCreationInfo,
VdcActionType parentCommand) {
return coco.getAsyncTask(taskId, command, asyncTaskCreationInfo, parentCommand);
}
/**
* Create Async Task to be run
* @param command the command object creating the task
* @param asyncTaskCreationInfo Info on how to create the task
* @param parentCommand The type of command issuing the task
*/
public static AsyncTask createAsyncTask(
CommandBase<?> command,
AsyncTaskCreationInfo asyncTaskCreationInfo,
VdcActionType parentCommand) {
return coco.createAsyncTask(command, asyncTaskCreationInfo, parentCommand);
}
/**
* Fail the command associated with the task identified by the task id that has empty vdsm id and log the failure
* with the specified message.
* @param taskId the id of the async task in the database
* @param message the message to be logged for the failure
*/
public static void logAndFailTaskOfCommandWithEmptyVdsmId(Guid taskId, String message) {
getAsyncTaskManager().logAndFailTaskOfCommandWithEmptyVdsmId(taskId, message);
}
/**
* Get the ids of the users executing the vdsm tasks.
* @param tasksIDs The vdsm task ids being executed
* @return The collection of user ids
*/
public static Collection<Guid> getUserIdsForVdsmTaskIds(ArrayList<Guid> tasksIDs) {
return getAsyncTaskManager().getUserIdsForVdsmTaskIds(tasksIDs);
}
/**
* Remove the async task identified the task id from the database.
* @param taskId The task id of the async task in the database
*/
public static void removeTaskFromDbByTaskId(Guid taskId) {
AsyncTaskManager.removeTaskFromDbByTaskId(taskId);
}
/**
* Get the async task from the database identified by the asyncTaskId
* @return The async task to be saved
*/
public static AsyncTask getAsyncTaskFromDb(Guid asyncTaskId) {
return coco.getAsyncTaskFromDb(asyncTaskId);
}
/**
* Save the async task in the database
* @param asyncTask the async task to be saved in to the database
*/
public static void saveAsyncTaskToDb(AsyncTask asyncTask) {
coco.saveAsyncTaskToDb(asyncTask);
}
/**
* Remove the async task identified the task id from the database.
* @param taskId The task id of the async task in the database
* @return The number of rows updated in the database
*/
public static int callRemoveTaskFromDbByTaskId(Guid taskId) {
return coco.removeTaskFromDbByTaskId(taskId);
}
/**
* Save or update the async task in the database.
* @param asyncTask The async task to be saved or updated
*/
public static void addOrUpdateTaskInDB(AsyncTask asyncTask) {
coco.addOrUpdateTaskInDB(asyncTask);
}
/**
* Persist the command entity in the database
* @param cmdEntity The command entity to be persisted
* @param cmdContext The CommandContext object associated with the command being persisted
*/
public static void persistCommand(CommandEntity cmdEntity, CommandContext cmdContext) {
coco.persistCommand(cmdEntity, cmdContext);
}
/**
* Persist the command related entities in the database
*/
public static void persistCommandAssociatedEntities(Guid cmdId, Collection<SubjectEntity> subjectEntities) {
coco.persistCommandAssociatedEntities(buildCommandAssociatedEntities(cmdId, subjectEntities));
}
private static Collection<CommandAssociatedEntity> buildCommandAssociatedEntities(Guid cmdId,
Collection<SubjectEntity> subjectEntities) {
if (subjectEntities.isEmpty()) {
return Collections.emptySet();
}
return subjectEntities.stream().map(subjectEntity -> new CommandAssociatedEntity(cmdId,
subjectEntity.getEntityType(),
subjectEntity.getEntityId()))
.collect(Collectors.toSet());
}
/**
* Return the child command ids for the parent command identified by commandId
* @param commandId The id of the parent command
* @return The list of child command ids
*/
public static List<Guid> getChildCommandIds(Guid commandId) {
return coco.getChildCommandIds(commandId);
}
/**
* Return the child command ids for the parent command identified by commandId with the given action type and
* status.
* @param commandId The id of the parent command
* @param childActionType The action type of the child command
* @param status The status of the child command, can be null
*/
public static List<Guid> getChildCommandIds(Guid commandId, VdcActionType childActionType, CommandStatus status) {
return coco.getChildCommandIds(commandId, childActionType, status);
}
/**
* Return the command ids being executed by the user identified by engine session seq id.
* @param engineSessionSeqId The id of the user's engine session
*/
public static List<Guid> getCommandIdsBySessionSeqId(long engineSessionSeqId) {
return coco.getCommandIdsBySessionSeqId(engineSessionSeqId);
}
/**
* Get the command entity for the command identified by the commandId
* @param commandId The id of the command
* @return The command entity for the command id
*/
public static CommandEntity getCommandEntity(Guid commandId) {
return coco.getCommandEntity(commandId);
}
/**
* Get the command object for the command identified by command id.
* @param commandId The id of the command
* @return The command
*/
@SuppressWarnings("unchecked")
public static <C extends CommandBase<?>> C retrieveCommand(Guid commandId) {
return (C) coco.retrieveCommand(commandId);
}
/**
* Remove the command entity for the command identified by command id
* @param commandId The id of the command
*/
public static void removeCommand(Guid commandId) {
coco.removeCommand(commandId);
}
/**
* Remove the command entities for the command and the command's child commands from the database
* @param commandId The id of the command
*/
public static void removeAllCommandsInHierarchy(Guid commandId) {
coco.removeAllCommandsInHierarchy(commandId);
}
/**
* Remove all command entities whose creation date is before the cutoff
* @param cutoff The cutoff date
*/
public static void removeAllCommandsBeforeDate(DateTime cutoff) {
coco.removeAllCommandsBeforeDate(cutoff);
}
/**
* Get the status of command identified by command id
* @param commandId The id of the command
* @return The status of the command
*/
public static CommandStatus getCommandStatus(Guid commandId) {
return coco.getCommandStatus(commandId);
}
/**
* Update the status of command identified by command id
* @param commandId The id of the command
* @param status The new status of the command
*/
public static void updateCommandStatus(Guid commandId, CommandStatus status) {
coco.updateCommandStatus(commandId, status);
}
/**
* Get the async task command execution status
* @param commandId The id of the command
* @return The async task command execution status
*/
public static CommandExecutionStatus getCommandExecutionStatus(Guid commandId) {
CommandEntity cmdEntity = coco.getCommandEntity(commandId);
return cmdEntity == null ? CommandExecutionStatus.UNKNOWN :
cmdEntity.isExecuted() ? CommandExecutionStatus.EXECUTED : CommandExecutionStatus.NOT_EXECUTED;
}
/**
* Returns the command entity's data for the command identified by the command id.
* @param commandId The id of the command
*/
public static Map<String, Serializable> getCommandData(Guid commandId) {
CommandEntity cmdEntity = coco.getCommandEntity(commandId);
return cmdEntity == null ? new HashMap<>() : cmdEntity.getData();
}
/**
* Set the command entity's data for the command identified by the command id.
* @param commandId The id of the command
*/
public static void updateCommandData(Guid commandId, Map<String, Serializable> data) {
coco.updateCommandData(commandId, data);
}
/**
* Set the command entity's executed status for the command identified by the command id.
* @param commandId The id of the command
*/
public static void updateCommandExecuted(Guid commandId) {
coco.updateCommandExecuted(commandId);
}
/**
* Submit the command for asynchronous execution to the Command Executor thread pool.
* @param actionType The action type of the command
* @param parameters The parameters for the command
* @param cmdContext The command context for the command
* @return The future object for the command submitted to the thread pool
*/
public static Future<VdcReturnValueBase> executeAsyncCommand(VdcActionType actionType,
VdcActionParametersBase parameters,
CommandContext cmdContext) {
return coco.executeAsyncCommand(actionType, parameters, cmdContext);
}
/**
* Get the ids of the commands which are associated with the entity.
* @param entityId The id of the entity
* @return The list of command ids
*/
public static List<Guid> getCommandIdsByEntityId(Guid entityId) {
return coco.getCommandIdsByEntityId(entityId);
}
/**
* Get the associated entities for the command
* @param cmdId The id of the entity
* @return The list of associated entities
*/
public static List<CommandAssociatedEntity> getCommandAssociatedEntities(Guid cmdId) {
return coco.getCommandAssociatedEntities(cmdId);
}
/**
* Get the return value for the command identified by the command id.
* @param cmdId The id of the command
* @return The return value for the command
*/
public static VdcReturnValueBase getCommandReturnValue(Guid cmdId) {
CommandEntity cmdEnity = coco.getCommandEntity(cmdId);
return cmdEnity == null ? null : cmdEnity.getReturnValue();
}
private static AsyncTaskManager getAsyncTaskManager() {
return AsyncTaskManager.getInstance(coco);
}
/**
* Subscribes the given command for an event by its given event key
*
* @param eventKey
* the event key to subscribe
* @param commandEntity
* the subscribed command, which its callback will be invoked upon event
*/
public static void subscribe(String eventKey, CommandEntity commandEntity) {
coco.subscribe(eventKey, commandEntity);
}
}
| 37.982262 | 123 | 0.686281 |
c377ec6d703e3eb01a77dba7a7a9a70f5eea9d42 | 481 | package db;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TiempoInicio {
private String inicio;
public TiempoInicio(String inicio) {
super();
this.inicio = inicio;
}
public TiempoInicio(ResultSet datos) {
try {
this.inicio = datos.getString(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getInicio() {
return inicio;
}
}
| 15.516129 | 42 | 0.629938 |
07655f6eceb92dca8b392b9e7fb3446196ab1955 | 1,650 | package com.vmware.boot.consumer.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import com.vmware.boot.consumer.model.Student;
@Repository
public class StudentDaoImpl implements StudentDao {
@Autowired
private MongoTemplate mongoTemplate;
public StudentDaoImpl(MongoTemplate mongoTemplate) {
super();
this.mongoTemplate = mongoTemplate;
}
@Override
public Student addStudent(Student student) {
mongoTemplate.save(student);
return student;
}
@Override
public Student updateStudent(int studentId, Student student) {
student.setStudentId(studentId);
mongoTemplate.save(student);
return student;
}
@Override
public Object getStudent(int studentId) {
Query query = new Query();
query.addCriteria(Criteria.where("studentId").in(studentId));
return mongoTemplate.findOne(query, Student.class);
}
@Override
public List<Student> getStudentList() {
return mongoTemplate.findAll(Student.class);
}
@Override
public List<Student> deleteStudent(int studentId) {
Query query = new Query();
query.addCriteria(Criteria.where("studentId").in(studentId));
mongoTemplate.remove(query, Student.class);
return getStudentList();
}
}
| 27.966102 | 70 | 0.68303 |
e5086c0131625770250f5bfa7af210c0b1a95c18 | 620 | /**
*
* License: http://www.apache.org/licenses/LICENSE-2.0
* Home page: https://github.com/linlurui/ccweb
* Note: to build on java, include the jdk1.8+ compiler symbol (and yes,
* I know the difference between language and runtime versions; this is a compromise).
* @author linlurui
* @Date Date: 2019-02-10
*/
package ccait.ccweb.entites;
import java.io.Serializable;
public class FieldInfo extends GroupByInfo implements Serializable {
private Object value;
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
| 22.142857 | 87 | 0.685484 |
b5dfba7523f060ce1b169d1686f084507276d3b0 | 362 | package JunitTest;
import org.junit.experimental.categories.Categories;
import org.junit.experimental.categories.Categories.IncludeCategory;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;
@SuiteClasses({AppTest.class})
@RunWith(Categories.class)
@IncludeCategory(MyCategories.PositiveTests.class)
public class PositiveSuite {
}
| 25.857143 | 68 | 0.837017 |
3155a85aac513f5fb02f059796a4d8a2af8829f3 | 3,094 | /*
* 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.axiom.ts.dimension;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.axiom.om.OMMetaFactory;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axiom.testutils.stax.XMLStreamReaderComparator;
import org.apache.axiom.testutils.suite.MatrixTestCase;
import org.apache.axiom.ts.jaxp.DOMImplementation;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Creates an {@link OMXMLParserWrapper} by parsing the input using DOM and passing it as a DOM tree
* to Axiom.
*/
final class DOMBuilderFactory extends BuilderFactory {
private final DOMImplementation implementation;
DOMBuilderFactory(DOMImplementation implementation) {
this.implementation = implementation;
}
public boolean isDeferredParsing() {
return true;
}
public void configureXMLStreamReaderComparator(XMLStreamReaderComparator comparator) {
comparator.setCompareCharacterEncodingScheme(implementation.isDOM3());
comparator.setCompareEncoding(implementation.isDOM3());
comparator.setCompareInternalSubset(implementation.supportsGetInternalSubset());
comparator.setTreatSpaceAsCharacters(!implementation.isDOM3());
// DOM gives access to the parsed replacement value (via the Entity interface), but Axiom
// stores the unparsed replacement value. Therefore OMEntityReference#getReplacementText()
// returns null for nodes created from a DOM tree.
comparator.setCompareEntityReplacementValue(false);
// DOM (or at least Xerces) sorts attributes
comparator.setSortAttributes(true);
}
public void addTestParameters(MatrixTestCase testCase) {
testCase.addTestParameter("source", implementation.getName() + "-dom");
}
public OMXMLParserWrapper getBuilder(OMMetaFactory metaFactory, InputSource inputSource) throws Exception {
DocumentBuilderFactory dbf = implementation.newDocumentBuilderFactory();
dbf.setNamespaceAware(true);
dbf.setExpandEntityReferences(false);
Document document = dbf.newDocumentBuilder().parse(inputSource);
return OMXMLBuilderFactory.createOMBuilder(metaFactory.getOMFactory(), document, false);
}
} | 43.577465 | 111 | 0.760827 |
9b1b4a2d81411c1fae5ece1a08f6310c5b705d87 | 168 | package practice;
public class Problem {
static String s;
static class Inner {
void testMethod() {
s = "Set from Inner";
}
}
}
| 15.272727 | 33 | 0.529762 |
a14a564bddb1a1bbc2a8ae26aede6451f486d787 | 3,182 | package io.github.marcelovca90.ml;
import org.encog.ml.data.MLData;
import org.encog.ml.data.MLDataPair;
import org.encog.ml.data.basic.BasicMLDataSet;
import org.encog.ml.svm.KernelType;
import org.encog.ml.svm.SVM;
import org.encog.ml.svm.SVMType;
import org.encog.ml.svm.training.SVMTrain;
import io.github.marcelovca90.common.MessageLabel;
import io.github.marcelovca90.helper.DataSetHelper;
import io.github.marcelovca90.helper.MethodHelper;
public class SVM_RBF extends AbstractClassifier
{
@Override
public void train(BasicMLDataSet trainingSet, BasicMLDataSet validationSet)
{
int inputCount = trainingSet.get(0).getInput().size();
SVM svm = new SVM(inputCount, SVMType.SupportVectorClassification, KernelType.RadialBasisFunction);
double bestC = 0, bestGamma = 0, bestError = Double.MAX_VALUE;
for (int i = 1; i <= 1000; i++)
{
SVMTrain svmTrainTemp = new SVMTrain(svm, validationSet);
svmTrainTemp.setC(Math.random());
svmTrainTemp.setGamma(Math.random());
svmTrainTemp.setFold((int) Math.log10(inputCount) + 1);
svmTrainTemp.iteration();
if (svmTrainTemp.getError() < bestError)
{
bestError = svmTrainTemp.getError();
bestC = svmTrainTemp.getC();
bestGamma = svmTrainTemp.getGamma();
// logger.debug(String.format( "Best error so far = %f (i = %d, C=%f, GAMMA=%f)", bestError, i, bestC, bestGamma));
}
}
SVMTrain svmTrain = new SVMTrain(svm, trainingSet);
svmTrain.setC(bestC);
svmTrain.setGamma(bestGamma);
svmTrain.iteration();
svmTrain.finishTraining();
this.method = svm;
}
@Override
public void test(BasicMLDataSet testSet)
{
int hamCount = 0, hamCorrect = 0;
int spamCount = 0, spamCorrect = 0;
SVM svm = (SVM) this.method;
for (MLDataPair pair : testSet)
{
MLData input = pair.getInput();
MLData ideal = pair.getIdeal();
MLData output = svm.compute(input);
if (MethodHelper.infer(ideal.getData()) == MessageLabel.HAM)
{
hamCount++;
if (Math.abs(output.getData(0) - 0.0) < 1e-6)
{
hamCorrect++;
}
}
else if (MethodHelper.infer(ideal.getData()) == MessageLabel.SPAM)
{
spamCount++;
if (Math.abs(output.getData(0) - 1.0) < 1e-6)
{
spamCorrect++;
}
}
}
double hamPrecision = 100.0 * hamCorrect / hamCount;
double spamPrecision = 100.0 * spamCorrect / spamCount;
double precision = 100.0 * (hamCorrect + spamCorrect) / (hamCount + spamCount);
logger.info(String.format("%s @ %d\t%s\tHP: %.2f%% (%d/%d)\tSP: %.2f%% (%d/%d)\tGP: %.2f%%", "SVC-RBF", seed,
folder.replace(DataSetHelper.BASE_FOLDER, ""), hamPrecision, hamCorrect, hamCount, spamPrecision, spamCorrect, spamCount, precision));
}
}
| 33.851064 | 150 | 0.583595 |
75150f183ee2de085b0f6a41d364363b262d7794 | 7,016 | package tlf.com.tlfdebug.ui;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.tlf.keep.callback.ISerialportDataCallback;
import com.tlf.keep.controller.MainSerialportController;
import com.tlf.keep.value.Actions;
import com.tlf.keep.value.StateType;
import java.util.Map;
import tlf.com.tlfdebug.R;
import tlf.com.tlfdebug.tool.ShowTool;
public class BpActivity extends BaseActivity implements View.OnClickListener {
private MainSerialportController mSerialportController;
private TextView tv_bp_content;
private Button btn_bp_power_mode;
private Button btn_bp_start;
private Button btn_bp_stop;
private Button btn_bp_status;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bp);
initView();
initData();
}
private void initView() {
tv_bp_content = (TextView) findViewById(R.id.tv_bp_content);
btn_bp_power_mode = (Button) findViewById(R.id.btn_bp_power_mode);
btn_bp_start = (Button) findViewById(R.id.btn_bp_start);
btn_bp_stop = (Button) findViewById(R.id.btn_bp_stop);
btn_bp_status = (Button) findViewById(R.id.btn_bp_status);
btn_bp_power_mode.setOnClickListener(this);
btn_bp_start.setOnClickListener(this);
btn_bp_stop.setOnClickListener(this);
btn_bp_status.setOnClickListener(this);
}
private void initData() {
mSerialportController = MainSerialportController.getInstance(new BpCallback());
}
@Override
protected void onResume() {
super.onResume();
mSerialportController.action(Actions.ACTION_SERIAL_BP_OPEN);
}
@Override
protected void onStop() {
super.onStop();
ShowTool.clear();
tv_bp_content.setText("");
mSerialportController.action(Actions.ACTION_SERIAL_BP_CLOSE);
}
@Override
protected void onDestroy() {
super.onDestroy();
mSerialportController.action(Actions.ACTION_RELEASE_DATA);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_bp_power_mode:
mSerialportController.action(Actions.ACTION_SERIAL_BP_RESET);
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// mSerialportController.action(Actions.ACTION_BP_START);
// }
// }, 500);
break;
case R.id.btn_bp_start:
mSerialportController.action(Actions.ACTION_BP_START);
break;
case R.id.btn_bp_stop:
mSerialportController.action(Actions.ACTION_BP_STOP);
break;
case R.id.btn_bp_status:
mSerialportController.action(Actions.ACTION_BP_STATUS);
break;
}
}
private String status = "";
private String result = "";
private class BpCallback implements ISerialportDataCallback {
@Override
public void onReceive(int state) {
switch (state) {
//拒绝执行此命令
case StateType.BP_REFUSE_EXECUTION:
status = "拒绝执行此命令";
break;
//复位
case StateType.BP_POWER_ON:
status = "复位";
break;
//进入待机模式
case StateType.BP_ENTER_STANDBY_MODE:
status = "进入待机模式";
break;
//进入测量模式
case StateType.BP_ENTER_MEASURE_MODE:
status = "进入测量模式";
break;
//血压计正常
case StateType.BP_NORMAL:
status = "血压计正常";
break;
//测量完成
case StateType.BP_MEASURE_FINISHED:
status = "测量完成";
break;
//正在测量
case StateType.BP_MEASURE_RUNNING:
status = "正在测量";
break;
//系统异常
case StateType.BP_SYSTEM_EXCEPTION:
status = "系统异常";
break;
//脉搏信号微弱
case StateType.BP_WEAK_PULSE_SIGNAL:
status = "脉搏信号微弱";
break;
//杂讯太大导致脉搏信号弱
case StateType.BP_WEAK_PULSE_SIGNAL_BY_NOISE:
status = "杂讯太大导致脉搏信号弱";
break;
//测量超出正常范围
case StateType.BP_OUT_OF_RANGE:
status = "测量超出正常范围";
break;
case StateType.BP_OUT_OF_PRESSURE:
status = "压力过高";
break;
//电压过低
case StateType.BP_VOLTAGE_LOW:
status = "电压过低";
break;
//袖带异常,请佩戴好袖带
case StateType.BP_CUFF_EXCEPTION:
status = "袖带异常,请佩戴好袖带";
break;
}
mHandler.post(new Runnable() {
@Override
public void run() {
tv_bp_content.setText(ShowTool.getLinkString(status));
}
});
}
@Override
public void onReceive(Map map) {
if (StateType.TYPE_BP_PRESSURE.equals(map.get(StateType.DATA_TYPE))) {
final String pre = map.get(StateType.BP_PRESSURE).toString();
mHandler.post(new Runnable() {
@Override
public void run() {
tv_bp_content.setText(ShowTool.getLinkString(pre));
}
});
return;
}
int type = Integer.valueOf((String) map.get(StateType.BP_IS_IRREGULAR_HEARTBEAT));
if (type == 0) {
result = "测量结束,结果为:" + "收缩压:" + map.get(StateType.BP_SYSTOLIC_PRESSURE) + " 舒张压:" + map.get(StateType.BP_DIASTOLIC_PRESSURE) +
" 心率:" + map.get(StateType.BP_HEART_RATE) + " 无心率不齐";
} else {
result = "测量结束,结果为:" + "收缩压:" + map.get(StateType.BP_SYSTOLIC_PRESSURE) + " 舒张压:" + map.get(StateType.BP_DIASTOLIC_PRESSURE) +
" 心率:" + map.get(StateType.BP_HEART_RATE) + " 心率不齐";
}
mHandler.post(new Runnable() {
@Override
public void run() {
tv_bp_content.setText(ShowTool.getLinkString(result));
}
});
}
}
;
}
| 33.09434 | 143 | 0.534065 |
846a264e4497dd0a6d99469ca350a5e301d7530b | 719 | package play.learn.java.design.balking;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
// https://java-design-patterns.com/patterns/balking/
public class BalkingDemo {
public static void main(String[] args) {
WashingMachine washingMachine = new WashingMachine();
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 3; i++) {
executorService.execute(washingMachine::wash);
}
executorService.shutdown();
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
System.err.println("error : waiting on executor service shutdown!");
}
}
}
| 27.653846 | 71 | 0.748261 |
b2cf73f57c8a98ab2548ea1e2c8a4e1b3f8110fb | 582 | package ac.cn.saya.lab.api.entity;
import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
/**
* @Title: OutExcelEntity
* @ProjectName lab
* @Description: TODO
* @Author saya
* @Date: 2020/6/18 18:18
* @Description: 导出到Excel时,封装的参数
*/
@NoArgsConstructor
@Getter
@Setter
public class OutExcelEntity {
/**
* 表格数据主键字段
*/
private String[] keys;
/**
* 字段名
*/
private String[] titles;
/**
* 表格数据
*/
private List<JSONObject> bodyData;
}
| 14.923077 | 39 | 0.646048 |
47a6e521302172381bf50dbffdafda868ca7f1e0 | 342 | package com.leetcode.algorithm.medium.subarraysumsdivisiblebyk;
class Solution {
public int subarraysDivByK(int[] arr, int k) {
int[] count = new int[k];
count[0] = 1;
int prefix = 0;
int res = 0;
for (int num: arr) {
prefix = (prefix + num % k + k) % k;
res += count[prefix]++;
}
return res;
}
}
| 21.375 | 63 | 0.573099 |
ec9f6d7f6c1db4c586d7a3cac7c34a9656e576aa | 1,387 | /*
* Copyright (c) 2015 FUJI Goro (gfx).
*
* 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.github.gfx.android.orma.example.orma;
import com.github.gfx.android.orma.annotation.Column;
import com.github.gfx.android.orma.annotation.PrimaryKey;
import com.github.gfx.android.orma.annotation.Table;
import org.threeten.bp.LocalDateTime;
import org.threeten.bp.ZonedDateTime;
import android.support.annotation.Nullable;
/**
* To demonstrate multiple associations to the same model.
*
* @see Item2_Schema
*/
@Table
public class Item2 {
@PrimaryKey
public String name;
@Column(indexed = true)
public Category category1;
@Nullable
@Column(indexed = true)
public Category category2;
@Column
public ZonedDateTime zonedTimestamp = ZonedDateTime.now();
@Column
public LocalDateTime localDateTime = LocalDateTime.now();
}
| 26.673077 | 75 | 0.741168 |
d299d59710210572fe095a36f2caf031a99c3368 | 726 | package hu.advancedweb.scott;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
import hu.advancedweb.scott.runtime.track.StateRegistry;
public class MethodNameAndClassTrackingTest {
@Test
public void test1() throws Exception {
assertThat(StateRegistry.getTestClassType(), equalTo("hu/advancedweb/scott/MethodNameAndClassTrackingTest"));
assertThat(StateRegistry.getTestMethodName(), equalTo("test1"));
}
@Test
public void test2() throws Exception {
assertThat(StateRegistry.getTestClassType(), equalTo("hu/advancedweb/scott/MethodNameAndClassTrackingTest"));
assertThat(StateRegistry.getTestMethodName(), equalTo("test2"));
}
}
| 29.04 | 111 | 0.800275 |
f937a4c52c730f48733c1cd154e56fd679dd8479 | 3,993 | package us.ihmc.scs2.sessionVisualizer.jfx.charts;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.Property;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import us.ihmc.euclid.tuple2D.Point2D;
public class NumberSeries
{
/** The user displayable name for this series */
private final StringProperty seriesNameProperty = new SimpleStringProperty(this, "seriesName", null);
private final StringProperty currentValueProperty = new SimpleStringProperty(this, "currentValue", null);
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final Property<ChartIntegerBounds> xBoundsProperty = new SimpleObjectProperty<>(this, "xBounds", null);
private final Property<ChartDoubleBounds> yBoundsProperty = new SimpleObjectProperty<>(this, "yBounds", null);
private final List<Point2D> data = new ArrayList<>();
private final IntegerProperty bufferCurrentIndexProperty = new SimpleIntegerProperty(this, "bufferCurrentIndex", -1);
private final BooleanProperty dirtyProperty = new SimpleBooleanProperty(this, "dirtyFlag", false);
// User properties
private final BooleanProperty negatedProperty = new SimpleBooleanProperty(this, "negated", false);
private final ObjectProperty<ChartDoubleBounds> customYBoundsProperty = new SimpleObjectProperty<>(this, "customYBounds", null);
public NumberSeries(String name)
{
setSeriesName(name);
negatedProperty.addListener((InvalidationListener) -> markDirty());
customYBoundsProperty.addListener((InvalidationListener) -> markDirty());
}
public final String getSeriesName()
{
return seriesNameProperty.get();
}
public final void setSeriesName(String value)
{
seriesNameProperty.set(value);
}
public final StringProperty seriesNameProperty()
{
return seriesNameProperty;
}
public final void setCurrentValue(String value)
{
currentValueProperty.set(value);
}
public final String getCurrentValue()
{
return currentValueProperty.get();
}
public final StringProperty currentValueProperty()
{
return currentValueProperty;
}
public ReentrantReadWriteLock getLock()
{
return lock;
}
public Property<ChartIntegerBounds> xBoundsProperty()
{
return xBoundsProperty;
}
public Property<ChartDoubleBounds> yBoundsProperty()
{
return yBoundsProperty;
}
public List<Point2D> getData()
{
return data;
}
public IntegerProperty bufferCurrentIndexProperty()
{
return bufferCurrentIndexProperty;
}
public void markDirty()
{
dirtyProperty.set(true);
}
public boolean peekDirty()
{
return dirtyProperty.get();
}
public boolean pollDirty()
{
boolean result = dirtyProperty.get();
dirtyProperty.set(false);
return result;
}
public BooleanProperty dirtyProperty()
{
return dirtyProperty;
}
public final boolean isNegated()
{
return negatedProperty.get();
}
public final void setNegated(boolean value)
{
negatedProperty.set(value);
}
public final BooleanProperty negatedProperty()
{
return negatedProperty;
}
public final ChartDoubleBounds getCustomYBounds()
{
return customYBoundsProperty.get();
}
public final void setCustomYBounds(ChartDoubleBounds customYBounds)
{
customYBoundsProperty.set(customYBounds);
}
public ObjectProperty<ChartDoubleBounds> customYBoundsProperty()
{
return customYBoundsProperty;
}
} | 26.62 | 131 | 0.735036 |
58446e8a4346aeab5539d371247debb7c85be83c | 395 | package com.dyllongagnier.cs3810;
import java.util.Random;
public class RandomArrayGenerator
{
private Random rand = new Random();
// Makes an N by N array.
public IntArray2D getRandomIntArray(int N)
{
IntArray2D result = new IntArray2D(N, N);
for(int row = 0; row < N; row++)
for(int col = 0; col < N; col++)
result.setInt(row, col, rand.nextInt());
return result;
}
}
| 19.75 | 44 | 0.670886 |
25a9be225f4314d994d4aac77bf6e62e72289dbd | 3,061 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.element;
import org.kuali.rice.krad.datadictionary.parse.BeanTag;
import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute;
import org.kuali.rice.krad.datadictionary.parse.BeanTags;
/**
* builds <link> tags with various attributes
* in the <head> of the html document
*
*/
@BeanTags({@BeanTag(name = "view-headLink", parent = "Uif-HeadLink")})
public class HeadLink extends ContentElementBase {
private String media;
private String href;
private String relation;
private String type;
private String includeCondition;
public HeadLink() {
super();
}
/**
*
* @return media
*/
@BeanTagAttribute(name = "media")
public String getMedia() {
return media;
}
/**
*
* @param media
*/
public void setMedia(String media) {
this.media = media;
}
/**
*
* @return href
*/
@BeanTagAttribute(name = "href")
public String getHref() {
return href;
}
/**
*
* @param href
*/
public void setHref(String href) {
this.href = href;
}
/**
* rel attribute for <link>
*
* @return relation
*/
@BeanTagAttribute(name = "relation")
public String getRelation() {
return relation;
}
/**
*
* @param rel
*/
public void setRelation(String relation) {
this.relation = relation;
}
/**
*
* @return type
*/
@BeanTagAttribute(name = "type")
public String getType() {
return type;
}
/**
*
* @param type
*/
public void setType(String type) {
this.type = type;
}
/**
* includeCondition wraps conditional html comments for
* choosing css files based on browser info
* exampe:
* for the folling code
* {@code
* <!--[if ie 9]>
* <link href="ie9.css" type="text/stylesheet"></link>
* <![endif]-->
* }
*
* the includeCondition would be "if ie 9"
*
* @return includeCondition
*/
@BeanTagAttribute(name = "includeCondition")
public String getIncludeCondition() {
return includeCondition;
}
/**
*
* @param includeCondition
*/
public void setIncludeCondition(String includeCondition) {
this.includeCondition = includeCondition;
}
}
| 21.864286 | 81 | 0.599477 |
1cd67d8cf43796cabf581140d7bc3730a74710a0 | 1,804 | package org.telegram.api.message.media;
import org.telegram.api.document.TLAbsDocument;
import org.telegram.tl.StreamingUtils;
import org.telegram.tl.TLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The type TL message media document.
*/
public class TLMessageMediaDocument extends TLAbsMessageMedia {
/**
* The constant CLASS_ID.
*/
public static final int CLASS_ID = 0xf3e02ea8;
private TLAbsDocument document;
private String caption;
/**
* Instantiates a new TL message media document.
*/
public TLMessageMediaDocument() {
super();
}
@Override
public int getClassId() {
return CLASS_ID;
}
/**
* Gets document.
*
* @return the document
*/
public TLAbsDocument getDocument() {
return this.document;
}
/**
* Sets document.
*
* @param document the document
*/
public void setDocument(TLAbsDocument document) {
this.document = document;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
@Override
public void serializeBody(OutputStream stream)
throws IOException {
StreamingUtils.writeTLObject(this.document, stream);
StreamingUtils.writeTLString(this.caption, stream);
}
@Override
public void deserializeBody(InputStream stream, TLContext context)
throws IOException {
this.document = ((TLAbsDocument) StreamingUtils.readTLObject(stream, context));
this.caption = StreamingUtils.readTLString(stream);
}
@Override
public String toString() {
return "messageMediaDocument#f3e02ea8";
}
} | 22.835443 | 87 | 0.651885 |
cf4acdbdf516194f7fa443cae8c557f83a51912a | 2,516 | package com.hbm.items.food;
import java.util.List;
import java.util.Random;
import com.hbm.items.ModItems;
import com.hbm.lib.ModDamageSource;
import com.hbm.potion.HbmPotion;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;
public class ItemPill extends ItemFood {
Random rand = new Random();
public ItemPill(int hunger, String s) {
super(hunger, false);
this.setUnlocalizedName(s);
this.setRegistryName(s);
ModItems.ALL_ITEMS.add(this);
}
@Override
protected void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) {
if (!worldIn.isRemote)
{
if(this == ModItems.pill_iodine) {
player.removePotionEffect(MobEffects.BLINDNESS);
player.removePotionEffect(MobEffects.NAUSEA);
player.removePotionEffect(MobEffects.MINING_FATIGUE);
player.removePotionEffect(MobEffects.HUNGER);
player.removePotionEffect(MobEffects.SLOWNESS);
player.removePotionEffect(MobEffects.POISON);
player.removePotionEffect(MobEffects.WEAKNESS);
player.removePotionEffect(MobEffects.WITHER);
player.removePotionEffect(HbmPotion.radiation);
}
if(this == ModItems.plan_c) {
for(int i = 0; i < 10; i++)
player.attackEntityFrom(rand.nextBoolean() ? ModDamageSource.euthanizedSelf : ModDamageSource.euthanizedSelf2, 1000);
}
if(this == ModItems.radx) {
player.addPotionEffect(new PotionEffect(HbmPotion.radx, 3 * 60 * 20, 0));
}
}
}
@Override
public void addInformation(ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
if(this == ModItems.pill_iodine) {
tooltip.add("Removes negative effects");
}
if(this == ModItems.plan_c) {
tooltip.add("Deadly");
}
if(this == ModItems.radx) {
tooltip.add("Increases radiation resistance by 0.4 for 3 minutes");
}
}
@Override
public int getMaxItemUseDuration(ItemStack stack) {
return 10;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer playerIn, EnumHand handIn) {
playerIn.setActiveHand(handIn);
return super.onItemRightClick(worldIn, playerIn, handIn);
}
}
| 30.313253 | 128 | 0.715421 |
1d52ae2809d107c7062caab578be0ad36c9f6554 | 962 | package com.tcwong.pengms.model;
import java.io.Serializable;
public class Logdic implements Serializable {
private Integer typeid;
private String typename;
private static final long serialVersionUID = 1L;
public Integer getTypeid() {
return typeid;
}
public void setTypeid(Integer typeid) {
this.typeid = typeid;
}
public String getTypename() {
return typename;
}
public void setTypename(String typename) {
this.typename = typename;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", typeid=").append(typeid);
sb.append(", typename=").append(typename);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
| 23.463415 | 66 | 0.616424 |
fc4fe245012c2881894a9ed9e60786f38a2207ab | 9,142 | package com.keptn.neotys.testexecutor.NeoLoadFolder.datamodel;
import com.keptn.neotys.testexecutor.NeoLoadFolder.NeoloadInfrastructureModel.NeoLoadInfrastructureFile;
import com.keptn.neotys.testexecutor.NeoLoadFolder.NeoloadInfrastructureModel.NeoloadInfra;
import com.keptn.neotys.testexecutor.exception.NeoLoadJgitExeption;
import com.keptn.neotys.testexecutor.exception.NeoLoadSerialException;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.keptn.neotys.testexecutor.conf.NeoLoadConfiguration.*;
public class NeoLoadTest {
String stage;
List<Project> project;
String description;
String scenario;
Infrastructure infrastructure;
String global_infrasctructure;
List<Constants> constant_variables;
public NeoLoadTest() {
project = new ArrayList<>();
constant_variables = new ArrayList<>();
}
public NeoLoadTest(String stage, List<Project> project, String description, String scenario, @Nullable Infrastructure infrastructure, @Nullable String global_infrasctructure, @Nullable List<Constants> constant_variables) {
this.stage = stage;
this.project = project;
this.description = description;
this.scenario = scenario;
this.infrastructure = infrastructure;
this.global_infrasctructure = global_infrasctructure;
this.constant_variables = constant_variables;
}
public String getStage() {
return stage;
}
public void setStage(String stage) {
this.stage = stage;
}
// public Optional<List<Constants>> getConstant_variables() {
// return Optional.ofNullable(constant_variables).flatMap(list -> list.isEmpty() ? Optional.empty() : Optional.of(list));
// }
public List<Constants> getConstant_variables() {
return constant_variables;
}
public void setConstant_variables(List<Constants> constant_variables) {
this.constant_variables = constant_variables;
}
// public Optional<Infrastructure> getInfrastructure() {
// return Optional.ofNullable( infrastructure);
// }
public Infrastructure getInfrastructure() {
return infrastructure;
}
public void setInfrastructure(Infrastructure infrastructure) {
this.infrastructure = infrastructure;
}
public Optional<String> getGlobal_infrasctructure() {
return Optional.ofNullable(global_infrasctructure);
}
public void setGlobal_infrasctructure(String global_infrasctructure) {
this.global_infrasctructure = global_infrasctructure;
}
public List<Project> getProject() {
return project;
}
public void setProject(List<Project> project) {
this.project = project;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getScenario() {
return scenario;
}
public void setScenario(String scenario) {
this.scenario = scenario;
}
public boolean globalInfastructurefileExists(Path gitrepo) {
return fileExists(gitrepo, getGlobal_infrasctructure());
}
public boolean isInfastructurefile(Path gitrepo) {
return isANeoLoadInfastructureFile(gitrepo, getGlobal_infrasctructure());
}
public boolean checkProject(Path gitfolder) throws NeoLoadJgitExeption, NeoLoadSerialException, IOException {
if (project.size() <= 0)
throw new NeoLoadJgitExeption("you need to refer to at least one project ");
else {
List<String> error = new ArrayList<>();
project.stream().forEach(project1 ->
{
if (!project1.isANeoLoadProjectFile(gitfolder))
error.add("This project path needs to have nlp or yaml extension " + project1.getPath());
if (!project1.projectExists(gitfolder))
error.add("This project file doesn't not exists " + project1.getPath());
});
if (error.size() > 0)
throw new NeoLoadJgitExeption(error.stream().collect(Collectors.joining("\n")));
}
if (scenario == null)
throw new NeoLoadJgitExeption("Scenario cannot be null ");
final Optional<String> optGlobalInfrasctructure = getGlobal_infrasctructure();
if (optGlobalInfrasctructure.isPresent()) {
if (globalInfastructurefileExists(gitfolder))
throw new NeoLoadJgitExeption("global instastructure file doesn't exists in " + optGlobalInfrasctructure.get());
if (!isInfastructurefile(gitfolder))
throw new NeoLoadJgitExeption("global instastructure file not a yaml file " + optGlobalInfrasctructure.get());
List<NeoloadInfra> loadInfraFromGlobalFile = getNeoLoadInfraFromGlobalFile(gitfolder);
if (loadInfraFromGlobalFile.size() < 0)
throw new NeoLoadJgitExeption("There is no Infrastructure define in " + optGlobalInfrasctructure.get());
List<String> error = new ArrayList<>();
loadInfraFromGlobalFile.stream().parallel().forEach(infra -> {
if (infra.getZones().size() <= 0)
error.add("There is no zones define in " + infra.getName());
else {
infra.getZones().stream().parallel().forEach(zone -> {
if (zone.getMachines().size() <= 0)
error.add("There is no machines define in the zone " + infra.getName());
});
}
});
if (error.size() > 0)
throw new NeoLoadJgitExeption(error.stream().collect(Collectors.joining("\n")));
return true;
} else {
//---infra manage directly on population level
final Optional<Infrastructure> optInfrastructure = Optional.ofNullable(infrastructure);
if (!optInfrastructure.isPresent())
throw new NeoLoadJgitExeption("infrastructure needs to be define if there is no global infrastructure file");
if (optInfrastructure.get().getLocal_LG().size() <= 0)
throw new NeoLoadJgitExeption("You need to define at least one LoadGenerator");
if (optInfrastructure.get().populations.size() <= 0)
throw new NeoLoadJgitExeption("You ned to configure at least one population");
List<String> error = new ArrayList();
optInfrastructure.get().populations.stream().forEach(population -> {
if (population.lgs.size() <= 0)
error.add("You need to define one Load Generator at least on population :" + population.getName());
});
if (error.size() > 0)
throw new NeoLoadJgitExeption(error.stream().collect(Collectors.joining("\n")));
return true;
}
}
public List<String> getNameOfLGtoStart(Path gitFolder) throws NeoLoadSerialException, IOException {
List<String> machinenameList = new ArrayList<>();
if (getGlobal_infrasctructure().isPresent()) {
List<NeoloadInfra> loadInfraFromGlobalFile = getNeoLoadInfraFromGlobalFile(gitFolder);
loadInfraFromGlobalFile.stream().filter(infras -> infras.getType().equalsIgnoreCase(ON_PREM_ZONE)).forEach(infra -> {
infra.getZones().stream().parallel().forEach(zone -> {
machinenameList.addAll(zone.getMachines());
});
});
} else {
final Optional<Infrastructure> optionalInfrastructure = Optional.ofNullable(this.infrastructure);
if (optionalInfrastructure.isPresent()) {
machinenameList.addAll(optionalInfrastructure.get().local_LG.stream().map(lg ->
{
return lg.getName();
}).collect(Collectors.toList()));
}
}
return machinenameList;
}
private boolean fileExists(Path gitrepo, Optional<String> file) {
if (file.isPresent()) {
File neoloadprojectFile = new File(gitrepo.toAbsolutePath() + "/" + file.get());
if (neoloadprojectFile.exists())
return true;
else
return false;
} else
return false;
}
private boolean isANeoLoadInfastructureFile(Path pathinGit, Optional<String> file)
{
if(file.isPresent())
{
File neoloadprojectFile = new File(pathinGit.toAbsolutePath()+"/"+file.get());
Path full=neoloadprojectFile.toPath();
if (full.endsWith(YAML_EXTENSION) || full.endsWith(YML_EXTENSION))
return true;
else
return false;
} else
return false;
}
public List<NeoloadInfra> getNeoLoadInfraFromGlobalFile(Path git) throws NeoLoadSerialException, IOException {
if (getGlobal_infrasctructure().isPresent()) {
final String yamlFile = Files.readAllLines(Paths.get(git.toAbsolutePath().toString(), NEOLOAD_FOLDER, this.getGlobal_infrasctructure().get())).stream().collect(Collectors.joining("\n"));
NeoLoadInfrastructureFile neoLoadInfrastructureFile = new Yaml().loadAs(yamlFile, NeoLoadInfrastructureFile.class);
if (neoLoadInfrastructureFile != null) {
return neoLoadInfrastructureFile.getInfrastructures();
} else {
throw new NeoLoadSerialException("Unable to deserialize global infranstructure file " + getGlobal_infrasctructure().get());
}
} else
return null;
}
@Override
public String toString() {
return "NeoLoadTest{" +
"stage='" + stage + '\'' +
", project=" + project +
", description='" + description + '\'' +
", scenario='" + scenario + '\'' +
", infrastructure=" + infrastructure +
", global_infrasctructure='" + global_infrasctructure + '\'' +
", constant_variables=" + constant_variables +
'}';
}
}
| 33.123188 | 223 | 0.735616 |
43283b65c5ab004fe8a18d96fbcc33b32abb2fcc | 1,244 | /**
* $Id$
* $URL$
* ClassConverter.java - genericdao - Sep 8, 2008 2:47:07 PM - azeckoski
**************************************************************************
* Copyright (c) 2008 Aaron Zeckoski
* Licensed under the Apache License, Version 2.0
*
* A copy of the Apache License has been included in this
* distribution and is available at: http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Aaron Zeckoski (azeckoski @ gmail.com) (aaronz @ vt.edu) (aaron @ caret.cam.ac.uk)
*/
package org.azeckoski.reflectutils.converters;
import org.azeckoski.reflectutils.ClassLoaderUtils;
import org.azeckoski.reflectutils.converters.api.Converter;
/**
* Converts a string to a class (this is pretty much the only conversion supported)
*
* @author Aaron Zeckoski (azeckoski @ gmail.com)
*/
public class ClassConverter implements Converter<Class<?>> {
public Class<?> convert(Object value) {
String className = value.toString();
Class<?> c = ClassLoaderUtils.getClassFromString(className);
if (c == null) {
throw new UnsupportedOperationException("Class convert failure: cannot convert source ("+value+") and type ("+value.getClass()+") to a Class");
}
return c;
}
}
| 32.736842 | 155 | 0.647106 |
663465b11d04ed52d2c9018abd4913ca46cbd404 | 2,533 | /*
* Copyright 2006-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.objenesis.instantiator.exotic.util;
import org.junit.jupiter.api.Test;
import org.objenesis.ObjenesisException;
import org.objenesis.instantiator.util.ClassUtils;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Henri Tremblay
*/
public class ClassUtilsTest {
private final String className = "org.objenesis.test.EmptyClassBis";
@Test
public void testClassNameToInternalClassName() {
String actual = ClassUtils.classNameToInternalClassName(className);
assertEquals("org/objenesis/test/EmptyClassBis", actual);
}
@Test
public void testClassNameToResource() {
String actual = ClassUtils.classNameToResource(className);
assertEquals("org/objenesis/test/EmptyClassBis.class", actual);
}
@Test
public void testGetExistingClass_existing() {
Class<?> actual = ClassUtils.getExistingClass(getClass().getClassLoader(),
getClass().getName());
assertSame(actual, getClass());
}
@Test
public void testGetExistingClass_notExisting() {
Class<?> actual = ClassUtils.getExistingClass(getClass().getClassLoader(), getClass().getName() + "$$$1");
assertNull(actual);
}
@Test
public void testNewInstance_noArgsConstructorPresent() {
ArrayList<?> i = ClassUtils.newInstance(ArrayList.class);
assertTrue(i.isEmpty());
}
@Test
public void testNewInstance_noArgsConstructorAbsent() {
ObjenesisException exception = assertThrows(ObjenesisException.class, () -> ClassUtils.newInstance(Integer.class));
assertEquals(exception.getCause().getClass(), InstantiationException.class);
}
}
| 34.22973 | 121 | 0.743387 |
7fbc6b46c8c3cb55f3a2d6ad9bd5c4f40e2b8bb1 | 1,925 | package com.john.crush.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.john.crush.entity.User;
import com.john.crush.service.UserService;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserRestController {
@Autowired
private UserService userService;
// get all users
@GetMapping("")
public List<User> getUsers() {
System.out.println("yes");
return userService.findAll();
}
// get user with userID
@GetMapping("/{userId}")
public User getUser(@PathVariable int userId) {
// check if th user id is valid
User user = userService.findById(userId);
if (user == null) {
throw new UserNotFoundException("User ID not found - " + userId);
}
return userService.findById(userId);
}
// add a new user, return the update user object
@PostMapping("/")
public User saveUser(@RequestBody User user) {
System.out.println("Yes");
user.setId(0); // means null, so insert as a new user
return userService.saveUser(user);
}
// update user
@PutMapping("")
public void updateUser(@RequestBody User user) {
// check if the user exists by checking id
User theUser = userService.findById(user.getId());
if (theUser == null) {
throw new UserNotFoundException("User not found");
}
userService.update(user);
}
@DeleteMapping("/{userId}")
public String deleteUser(@PathVariable int userId) {
// check if th user id is valid
User user = userService.findById(userId);
if (user == null) {
throw new UserNotFoundException("User ID not found - " + userId);
}
userService.deleteById(userId);
return "Delete user with user id - " + userId;
}
} | 27.898551 | 77 | 0.631169 |
301cb46118fc3a7c65c1393a3d4071b50a689451 | 7,360 | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.customers.business.service;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mifos.accounts.business.AccountFeesEntity;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.customers.center.business.CenterBO;
import org.mifos.customers.group.business.GroupBO;
import org.mifos.customers.office.business.OfficeBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.util.helpers.CustomerStatus;
import org.mifos.domain.builders.CenterBuilder;
import org.mifos.domain.builders.GroupBuilder;
import org.mifos.domain.builders.MeetingBuilder;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.business.util.Address;
import org.mifos.framework.util.StandardTestingService;
import org.mifos.framework.util.helpers.IntegrationTestObjectMother;
import org.mifos.framework.util.helpers.Money;
import org.mifos.service.test.TestMode;
import org.mifos.test.framework.util.DatabaseCleaner;
import org.springframework.beans.factory.annotation.Autowired;
public class GroupCreationUsingCustomerServiceIntegrationTest extends MifosIntegrationTestCase {
@Autowired
private CustomerService customerService;
@Autowired
private DatabaseCleaner databaseCleaner;
private static MifosCurrency oldDefaultCurrency;
private PersonnelBO existingUser;
private PersonnelBO existingLoanOfficer;
private OfficeBO existingOffice;
private MeetingBO existingMeeting;
private CenterBO existingCenter;
private List<AccountFeesEntity> noAccountFees;
@BeforeClass
public static void initialiseHibernateUtil() {
oldDefaultCurrency = Money.getDefaultCurrency();
Money.setDefaultCurrency(TestUtils.RUPEE);
new StandardTestingService().setTestMode(TestMode.INTEGRATION);
}
@AfterClass
public static void resetCurrency() {
Money.setDefaultCurrency(oldDefaultCurrency);
}
@After
public void cleanDatabaseTablesAfterTest() {
// NOTE: - only added to stop older integration tests failing due to brittleness
databaseCleaner.clean();
}
@Before
public void cleanDatabaseTables() {
databaseCleaner.clean();
noAccountFees = new ArrayList<AccountFeesEntity>();
existingUser = IntegrationTestObjectMother.testUser();
existingLoanOfficer = IntegrationTestObjectMother.testUser();
existingOffice = IntegrationTestObjectMother.sampleBranchOffice();
existingMeeting = new MeetingBuilder().customerMeeting().weekly().every(1).startingToday().build();
IntegrationTestObjectMother.saveMeeting(existingMeeting);
existingCenter = new CenterBuilder().with(existingMeeting).withName("Center-IntegrationTest")
.with(existingOffice).withLoanOfficer(existingLoanOfficer).withUserContext().build();
IntegrationTestObjectMother.createCenter(existingCenter, existingMeeting);
}
@Test
public void shouldCreateGroupAndRelatedCustomerAccountWithGlobalCustomerNumbersGenerated() throws Exception {
// setup
GroupBO group = new GroupBuilder().withParentCustomer(existingCenter).formedBy(existingUser).build();
// exercise test
customerService.createGroup(group, existingMeeting, noAccountFees);
// verification
assertThat(group.getCustomerId(), is(notNullValue()));
assertThat(group.getGlobalCustNum(), is(notNullValue()));
assertThat(group.getCustomerAccount(), is(notNullValue()));
assertThat(group.getCustomerAccount().getAccountId(), is(notNullValue()));
assertThat(group.getCustomerAccount().getGlobalAccountNum(), is(notNullValue()));
}
@Test
public void shouldSaveAllDetailsToDoWithGroup() throws Exception {
// setup
Address address = new Address("line1", "line2", "line3", "city", "state", "country", "zip", "phonenumber");
GroupBO group = new GroupBuilder().withName("newGroup").withAddress(address).withStatus(
CustomerStatus.GROUP_ACTIVE).withParentCustomer(existingCenter).formedBy(existingUser).build();
// exercise test
customerService.createGroup(group, existingMeeting, noAccountFees);
// verification
assertThat(group.getDisplayName(), is("newGroup"));
assertThat(group.getAddress().getDisplayAddress(), is("line1, line2, line3"));
assertThat(group.getSearchId(), is("1." + group.getParentCustomer().getCustomerId() + ".3"));
assertThat(group.getStatus(), is(CustomerStatus.GROUP_ACTIVE));
assertThat(group.getGroupPerformanceHistory().getGroup().getCustomerId(), is(group.getCustomerId()));
assertThat(group.getCustomFields().size(), is(0));
assertThat(group.getMaxChildCount(), is(0));
assertThat(existingCenter.getMaxChildCount(), is(3));
}
@Test
public void shouldCreateGroupAsTopOfHierarchy() throws Exception {
// setup
GroupBO group = new GroupBuilder().withName("group-on-top-of-hierarchy")
.withStatus(CustomerStatus.GROUP_ACTIVE)
.withLoanOfficer(existingLoanOfficer)
.withOffice(existingOffice)
.withMeeting(existingMeeting)
.formedBy(existingUser)
.isNotTrained()
.trainedOn(null)
.buildAsTopOfHierarchy();
// exercise test
this.customerService.createGroup(group, existingMeeting, noAccountFees);
// verification
assertThat(group.getDisplayName(), is("group-on-top-of-hierarchy"));
assertThat(group.getSearchId(), is("1." + group.getCustomerId()));
assertThat(group.getStatus(), is(CustomerStatus.GROUP_ACTIVE));
assertThat(group.getGroupPerformanceHistory().getGroup().getCustomerId(), is(group.getCustomerId()));
assertThat(group.getCustomFields().size(), is(0));
assertThat(group.getMaxChildCount(), is(0));
}
} | 42.057143 | 115 | 0.70788 |
924ef68d60c6a50f7ee2735f502d844fc22ebfaf | 2,454 | package universalelectricity.core.electricity;
public class ElectricityPack implements Cloneable {
public double amperes;
public double voltage;
public ElectricityPack(double amperes, double voltage) {
this.amperes = amperes;
this.voltage = voltage;
}
public ElectricityPack() {
this(0.0D, 0.0D);
}
public static ElectricityPack getFromWatts(double watts, double voltage) {
return new ElectricityPack(watts / voltage, voltage);
}
public double getWatts() {
return getWatts(this.amperes, this.voltage);
}
public double getConductance() {
return getConductance(this.amperes, this.voltage);
}
public double getResistance() {
return getResistance(this.amperes, this.voltage);
}
public static double getJoules(double watts, double seconds) {
return watts * seconds;
}
public static double getJoules(double amps, double voltage, double seconds) {
return amps * voltage * seconds;
}
public static double getWattsFromJoules(double joules, double seconds) {
return joules / seconds;
}
public static double getAmps(double watts, double voltage) {
return watts / voltage;
}
public static double getAmps(double ampHours) {
return ampHours * 3600.0D;
}
public static double getAmpsFromWattHours(double wattHours, double voltage) {
return getWatts(wattHours) / voltage;
}
public static double getWattHoursFromAmpHours(double ampHours, double voltage) {
return ampHours * voltage;
}
public static double getAmpHours(double amps) {
return amps / 3600.0D;
}
public static double getWatts(double amps, double voltage) {
return amps * voltage;
}
public static double getWatts(double wattHours) {
return wattHours * 3600.0D;
}
public static double getWattHours(double watts) {
return watts / 3600.0D;
}
public static double getWattHours(double amps, double voltage) {
return getWattHours(getWatts(amps, voltage));
}
public static double getResistance(double amps, double voltage) {
return voltage / amps;
}
public static double getConductance(double amps, double voltage) {
return amps / voltage;
}
public String toString() {
return "ElectricityPack [Amps:" + this.amperes + " Volts:" + this.voltage + "]";
}
public ElectricityPack clone() {
return new ElectricityPack(this.amperes, this.voltage);
}
public boolean isEqual(ElectricityPack electricityPack) {
return this.amperes == electricityPack.amperes && this.voltage == electricityPack.voltage;
}
}
| 24.29703 | 92 | 0.742869 |
118177894e2894a7be01ec38cab2438d675a3baa | 9,537 | /*
* 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 prod;
import prod.Models.Reminder;
import java.util.Date;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author giantas
*/
public class ReminderTest {
public ReminderTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getTitle method, of class Reminder.
*/
@Test
public void testGetTitle() {
Reminder instance = new Reminder("Sample");
String expResult = "Sample";
String result = instance.getTitle();
assertEquals(expResult, result);
}
/**
* Test of getTitle method, of class Reminder.
* Test should return empty title given empty title.
*/
@Test
public void testShouldReturnEmptyTitleGivenEmptyTitle() {
Reminder instance = new Reminder("");
String expResult = "";
String result = instance.getTitle();
assertEquals(expResult, result);
}
/**
* Test of getTitle method, of class Reminder.
* Test should return null given if title is null.
*/
@Test
public void testShouldReturnNullTitleGivenNullTitle() {
Reminder instance = new Reminder("");
String expResult = null;
instance.setTitle(null);
String result = instance.getTitle();
assertEquals(expResult, result);
}
/**
* Test of getBody method, of class Reminder.
*/
@Test
public void testGetBody() {
Reminder instance = new Reminder("Sample");
String expResult = "Sample Body";
String result = instance.getBody();
assertEquals(expResult, result);
}
/**
* Test of getBody method, of class Reminder.
* Test should return empty title given empty title.
*/
@Test
public void testShouldReturnEmptyBodyGivenEmptyBody() {
Reminder instance = new Reminder("");
String expResult = "";
instance.setBody("");
String result = instance.getBody();
assertEquals(expResult, result);
}
/**
* Test of getBody method, of class Reminder.
* Test should return null if body is null.
*/
@Test
public void testShouldReturnNullBodyGivenNullBody() {
Reminder instance = new Reminder("");
String expResult = null;
instance.setBody(null);
String result = instance.getBody();
assertEquals(expResult, result);
}
/**
* Test of getDate method, of class Reminder.
*/
@Test
public void testGetDate() {
Reminder instance = new Reminder("Sample");
String expResult = null;
String result = instance.getDate();
assertEquals(expResult, result);
}
/**
* Test of getDateObj method, of class Reminder.
* Test returns correct string-formatted date object
* given day having a leading zero
*/
@Test
public void testShouldReturnDateAsStringWithLeadingZero() {
Reminder instance = new Reminder("Sample");
instance.setDate("01/12/2017");
String expResult = "Fri Dec 01 00:00:00 EAT 2017";
Date result = instance.getDateObj();
assertEquals(expResult, result.toString());
}
/**
* Test of getDateObj method, of class Reminder.
* Test returns correct string-formatted date object
* given day having NO leading zero
*/
@Test
public void testShouldReturnDateAsStringWithoutLeadingZero() {
Reminder instance = new Reminder("Sample");
instance.setDate("1/12/2017");
String expResult = "Fri Dec 01 00:00:00 EAT 2017";
Date result = instance.getDateObj();
assertEquals(expResult, result.toString());
}
/**
* Test of getStringDate method, of class Reminder.
*/
@Test
public void testGetStringDate() {
Reminder instance = new Reminder("Sample");
String expResult = null;
String result = instance.getStringDate();
assertEquals(expResult, result);
}
/**
* Test of getDateObj method, of class Reminder.
*/
@Test
public void testGetDateObj() {
Reminder instance = new Reminder("Sample");
Date expResult = null;
Date result = instance.getDateObj();
assertEquals(expResult, result);
}
/**
* Test of getMonthInt method, of class Reminder.
* Test should return null if date not set
*/
@Test
public void testGetMonthIntGivenEmptyDate() {
Reminder instance = new Reminder("Sample");
Integer expResult = null;
Integer result = instance.getMonthInt();
assertEquals(expResult, result);
}
/**
* Test of getMonthInt method, of class Reminder.
* Test should return zero-index month int
*/
@Test
public void testGetMonthInt() {
Reminder instance = new Reminder("Sample");
instance.setDate("12/03/2017");
Integer expResult = 2;
Integer result = instance.getMonthInt();
assertEquals(expResult, result);
}
/**
* Test of getLongMonthName method, of class Reminder.
* Test should return null given null date
*/
@Test
public void testShouldReturnNullGivenNullDate() {
Reminder instance = new Reminder("Sample");
String expResult = null;
String result = instance.getLongMonthName();
assertEquals(expResult, result);
}
/**
* Test of getLongMonthName method, of class Reminder.
* Test should return month String in full
*/
@Test
public void testGetLongMonthName() {
Reminder instance = new Reminder("Sample");
instance.setDate("2/04/1920");
String expResult = "April";
String result = instance.getLongMonthName();
assertEquals(expResult, result);
}
/**
* Test of getShortMonthName method, of class Reminder.
*/
@Test
public void testGetShortMonthName() {
Reminder instance = new Reminder("Sample");
String expResult = null;
String result = instance.getShortMonthName();
assertEquals(expResult, result);
}
/**
* Test of getShortMonthName method, of class Reminder.
* Test should return month String in short
*/
@Test
public void testGetLongMonthNameInShort() {
Reminder instance = new Reminder("Sample");
instance.setDate("2/04/1920");
String expResult = "Apr";
String result = instance.getShortMonthName();
assertEquals(expResult, result);
}
/**
* Test of getYear method, of class Reminder.
* Test should return null if date is null
*/
@Test
public void testGetYearGivenNullDate() {
Reminder instance = new Reminder("Sample");
Integer expResult = null;
Integer result = instance.getYear();
assertEquals(expResult, result);
}
/**
* Test of getYear method, of class Reminder.
* Test should return year (Integer) in full if date not null
*/
@Test
public void testGetYear() {
Reminder instance = new Reminder("Sample");
instance.setDate("8/6/1856");
Integer expResult = 1856;
Integer result = instance.getYear();
assertEquals(expResult, result);
}
/**
* Test of getShortYear method, of class Reminder.
* Test should return null if date is null
*/
@Test
public void testGetShortYearGivenNullDate() {
Reminder instance = new Reminder("Sample");
Integer expResult = null;
Integer result = instance.getShortYear();
assertEquals(expResult, result);
}
/**
* Test of getShortYear method, of class Reminder.
* Test should return 2-digit year (Integer) if date not null
*/
@Test
public void testGetShortYear() {
Reminder instance = new Reminder("Sample");
instance.setDate("8/6/1856");
Integer expResult = 56;
Integer result = instance.getShortYear();
assertEquals(expResult, result);
}
/**
* Test of setTitle method, of class Reminder.
*/
@Test
public void testSetTitle() {
String expResult = "This is a sample title";
String title = "This is a sample title";
Reminder instance = new Reminder("Sample");
instance.setTitle(title);
assertEquals(expResult, instance.getTitle());
}
/**
* Test of setBody method, of class Reminder.
*/
@Test
public void testSetBody() {
String body = "";
Reminder instance = new Reminder("Sample");
String expResult = "";
instance.setBody(body);
assertEquals(expResult, instance.getBody());
}
/**
* Test of setDate method, of class Reminder.
*/
@Test
public void testSetDate() {
String date = "01/10/2017";
Reminder instance = new Reminder("Sample");
String expResult = "01/10/2017";
instance.setDate(date);
assertEquals(expResult, instance.getDate());
}
}
| 28.299703 | 79 | 0.611513 |
c3f4714d42bc06dc74b3336bebd73a66d2e7516f | 957 | package qj.blog.classreloading.example2;
import qj.util.ReflectUtil;
import qj.util.ThreadUtil;
import qj.util.lang.DynamicClassLoader;
/**
* Created by Quan on 31/10/2014.
*/
public class ReloadingContinuously {
public static void main(String[] args) {
for (;;) {
Class<?> userClass = new DynamicClassLoader("target/classes")
.load("qj.blog.classreloading.example2.ReloadingContinuously$User");
ReflectUtil.invokeStatic("hobby", userClass);
ThreadUtil.sleep(2000);
}
}
@SuppressWarnings("UnusedDeclaration")
public static class User {
public static void hobby() {
playFootball(); // Will comment during runtime
// playBasketball(); // Will uncomment during runtime
}
// Will comment during runtime
public static void playFootball() {
System.out.println("Play Football");
}
// Will uncomment during runtime
// public static void playBasketball() {
// System.out.println("Play Basketball");
// }
}
}
| 25.184211 | 72 | 0.710554 |
14ac0e1d91a65e8fa3037bb51000122d2576b5bd | 6,016 | /*
* 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 pckg.testingbanksimulation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.DisplayName;
/**
*
* @author Owen Bueso
*/
public class BankTest {
private String NAME;
private final Map<String, Customer> customers = new HashMap<>();
private double insufficientFundsPenalty = 10.00; // Default, in dollars
public BankTest() {
}
//@BeforeAll
//public static void setUpClass() {
//}
//@AfterAll
//public static void tearDownClass() {
//}
@BeforeEach
public void setUp() {
NAME = ("My Bank");
}
@AfterEach
public void tearDown() {
}
/**
* Not necessary to test the main method;
*/
public void testMain() {
System.out.println("Hello from My Bank");
String[] args = null;
Bank.main(args);
// TODO review the generated test code and remove the default call to fail.
}
/**
* Not necessary to test this Get Method since its only return the Constant InsufficientFundPenalty
*/
public void testGetInsufficientFundsPenalty() {
System.out.println("getInsufficientFundsPenalty");
Bank instance = null;
double expResult = 10.0;
double result = instance.getInsufficientFundsPenalty();
assertEquals(expResult, result, 10.0);
}
/**
* Test of setInsufficientFundsPenalty method, of class Bank.
*/
@Test
@DisplayName("Bank.SetInsufficientFundPenalty Tests")
public void testSetInsufficientFundsPenalty() {
System.out.println("setInsufficientFundsPenalty");
double insufficientFundsPenalty = 10.0;
Bank instance = null;
instance.setInsufficientFundsPenalty(insufficientFundsPenalty);
}
/**
* Not necessary to test this Get Method since its only return the string Name
*/
public void testGetNAME() {
System.out.println("getNAME");
Bank instance = null;
String expResult = "";
String result = instance.getNAME();
assertEquals(expResult, result);
}
/**
* Not necessary to test since its a GUI function.
*/
public void testAddAccountWizard() {
System.out.println("addAccountWizard");
Bank instance = null;
instance.addAccountWizard();
}
/**
* Test of GetAllAccounts, of class Bank.
*/
@Test
@DisplayName("Bank.GetAllAccounts Tests")
public void testGetAllAccounts() {
System.out.println("getAllAccounts");
Bank instance = null;
SortedSet<Account> expResult = null;
SortedSet<Account> result = instance.getAllAccounts();
assertEquals(expResult, result);
}
/**
* Not necessary to test since its a GUI function.
*/
public void testAddCustomerWizard() {
System.out.println("addCustomerWizard");
Bank instance = null;
instance.addCustomerWizard();
}
/**
* Test of addCustomer method, of class Bank.
*/
@Test
@DisplayName("Bank.AddCustomer Tests")
public void testAddCustomer() {
System.out.println("addCustomer");
String lastName = "Bueso";
String firstName = "Owen";
Bank instance = null;
String expResult = "Owen Bueso";
String result = instance.addCustomer(lastName, firstName);
assertEquals(expResult, result);
}
/**
* Test of removeCustomer method, of class Bank.
*/
@Test
@DisplayName("Bank.RemoveCustomer Tests")
public void testRemoveCustomer() {
System.out.println("removeCustomer");
String customerId = "";
Bank instance = null;
instance.removeCustomer(customerId);
}
/**
* Test of getAllCustomers method, of class Bank.
*/
@Test
@DisplayName("Bank.GetAllCustomers Tests")
public void testGetAllCustomers() {
System.out.println("getAllCustomers");
Bank instance = null;
SortedSet<Customer> expResult = null;
SortedSet<Customer> result = instance.getAllCustomers();
assertEquals(expResult, result);
}
/**
* Test of getCustomer method, of class Bank.
*/
@Test
@DisplayName("Bank.GetCustomer_String Tests")
public void testGetCustomer_String() {
System.out.println("getCustomer");
String customerId = "001";
Bank instance = null;
Customer expResult = null;
Customer result = instance.getCustomer(customerId);
assertEquals(expResult, result);
}
/**
* Test of getCustomer method, of class Bank.
*/
@Test
@DisplayName("Bank.GetCustomer_String_String Tests")
public void testGetCustomer_String_String() {
System.out.println("getCustomer");
String lastName = "Bueso";
String firstName = "Owen";
Bank instance = null;
List<Customer> expResult = null;
List<Customer> result = instance.getCustomer(lastName, firstName);
assertEquals(expResult, result);
}
/**
* Test of getCustomer method, of class Bank.
*/
@Test
@DisplayName("Bank.GetCustomerAccounts Tests")
public void testGetCustomersAccounts() {
System.out.println("getCustomersAccounts");
String customerId = "001";
Bank instance = null;
List<Account> expResult = null;
List<Account> result = instance.getCustomersAccounts(customerId);
assertEquals(expResult, result);
}
}
| 28.377358 | 103 | 0.635638 |
f6fd104c361aaa6b589bcb879c87b09c48e9bf52 | 25,022 | package com.ppdai.das.server;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.google.common.collect.Lists.newArrayList;
import static com.ppdai.das.core.DasConfigureFactory.configContextRef;
import static com.ppdai.das.util.ConvertUtils.*;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Ints;
import com.google.gson.Gson;
import com.ppdai.das.client.*;
import com.ppdai.das.client.sqlbuilder.SqlBuilderSerializer;
import com.ppdai.das.core.DasLogger;
import com.ppdai.das.core.LogContext;
import com.ppdai.das.service.*;
import com.ppdai.das.util.ConvertUtils;
import com.sun.net.httpserver.HttpServer;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TThreadedSelectorServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.ppdai.das.client.delegate.DasDelegate;
import com.ppdai.das.client.delegate.remote.BuilderUtils;
import com.ppdai.das.core.DasConfigureFactory;
import com.ppdai.das.core.DasDiagnose;
import com.ppdai.das.core.TransactionId;
import com.ppdai.das.core.TransactionServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DasServer implements DasService.Iface {
private static final Logger logger = LoggerFactory.getLogger(DasServer.class);
public final static int DEFAULT_PORT = 9090;
public static final String SELECTING_NUMBER = "selectingNumber";
public static final String WORKING_NUMBER = "workingNumber";
public static final String PORT = "port";
private final TransactionServer transServer;
private final String address;
private final String workerId;
private final DasServerStatusMonitor monitor;
private int port = DEFAULT_PORT;
public DasServer(String address, String workerId) throws UnknownHostException, SQLException {
this.address = address;
this.workerId = workerId;
createPIDFile();
transServer = new TransactionServer(address, workerId);
monitor = new DasServerStatusMonitor(transServer);
DasConfigureFactory.warmUpAllConnections();
}
@Override
public DasResult execute(DasRequest request) throws DasException, TException {
monitor.receive(request);
DasLogger dalLogger = configContextRef.get().getLogger();
Throwable ex = null;
LogContext logContext = dalLogger.receiveRemoteRequest(request);
try {
return transServer.doInTransaction(getTransactionId(request.transactionId), () -> {
switch (request.getOperation()) {
case QueryBySample:
return queryBySample(request);
case QueryByPK:
return queryByPK(request);
case CountBySample:
return countBySample(request);
case Insert:
return insert(request);
case InsertList:
return insertList(request);
case DeleteByPk:
return deleteByPk(request);
case DeleteBySample:
return deleteBySample(request);
case Update:
return update(request);
case BatchUpdate:
return batchUpdate(request);
case BatchDelete:
return batchDelete(request);
case BatchInsert:
return batchInsert(request);
case UpdateWithSqlBuilder:
return updateWithSqlBuilder(request);
case BatchUpdateWithSqlBuilder:
return batchUpdateWithSqlBuilder(request);
case Query:
return query(request);
case QueryObject:
return queryObject(request);
case Call:
return call(request);
case BatchCall:
return batchCall(request);
case BatchQuery:
return batchQuery(request);
case QueryBySampleWithRange:
return queryBySampleWithRange(request);
default:
throw new IllegalArgumentException("Unknown Operation:" + request.getOperation());
}
});
} catch (Throwable e) {
ex = e;
logger.error(e.getMessage(), e);
SQLException sqlException = com.ppdai.das.core.DasException.wrap(e);
throw new DasException(sqlException.getErrorCode() + "", sqlException.getMessage());
} finally {
dalLogger.finishRemoteRequest(logContext, ex);
monitor.complete(request, ex);
}
}
private String getTransactionId(DasTransactionId transactionId) {
if(transactionId == null)
return null;
return buildTransactionId(transactionId);
}
private DasDelegate getDelegate(String appId, String logicDbName, String customerClientVersion) {
return new ServerDasDelegate(appId, logicDbName, customerClientVersion);
}
private DasDelegate getDelegate(DasRequest request) {
return getDelegate(request.appId, request.logicDbName, request.ppdaiClientVersion);
}
private DasResult intResult(int result){
return new DasResult()
.setRows(Arrays.asList(new Entity().setValue(new Gson().toJson(result))))
.setRowCount(1);
}
private DasResult intsResult(int[] results){
return new DasResult()
.setRowCount(results.length)
.setRows(pojo2Entities(Ints.asList(results), null));
}
private SqlBuilder toSqlBuilder(DasRequest request) {
List<SqlBuilder> builders = BuilderUtils.fromSqlBuilders(request.getSqlBuilders());
if(builders.isEmpty()) {
return null;
} else {
SqlBuilder builder = Iterables.getFirst(builders, null);
String entityTypeInStr = Iterables.getFirst(request.getSqlBuilders(), null).getEntityType();
if(entityTypeInStr != null) {
Class clz = entityTypes.getOrDefault(entityTypeInStr, Entity.class);
builder.into(clz);
}
builder.setHints(translate(request.getHints()));
return builder;
}
}
final static ImmutableMap<String, Class> entityTypes = ImmutableMap.of(
Object.class.getName(), Object.class,
Entity.class.getName(), Entity.class,
String.class.getName(), String.class,
Map.class.getName(), Map.class
);
private BatchUpdateBuilder toBatchUpdateBuilder(DasRequest request) {
BatchUpdateBuilder result = new BatchUpdateBuilder(toSqlBuilder(request));
List<Object[]> values = BuilderUtils.toList(request.getBatchUpdateBuilder().getValuesList(), v-> {
List l = SqlBuilderSerializer.deserializePrimitive(v);
return l.toArray(new Object[l.size()]);
});
result.getValuesList().addAll(values);
List<String> statementList = request.getBatchUpdateBuilder().getStatements();
if(!statementList.isEmpty()) {
//BatchUpdateBuilder checks statements null
String[] statements = statementList.toArray(new String[statementList.size()]);
result.setStatements(statements);
}
result.setHints(translate(request.getHints()));
return result;
}
private DasResult updateWithSqlBuilder(DasRequest request) throws SQLException {
SqlBuilder sqlBuilder = toSqlBuilder(request);
int result = getDelegate(request).update(sqlBuilder);
return intResult(result).setDiagInfo(diagInfo2Hints(sqlBuilder.hints().getDiagnose()));
}
private DasResult batchUpdateWithSqlBuilder(DasRequest request) throws SQLException {
BatchUpdateBuilder batchUpdateBuilder = toBatchUpdateBuilder(request);
int[] results = getDelegate(request).batchUpdate(batchUpdateBuilder);
return intsResult(results).setDiagInfo(diagInfo2Hints(batchUpdateBuilder.hints().getDiagnose()));
}
private DasResult query(DasRequest request) throws SQLException {
SqlBuilder sqlBuilder = toSqlBuilder(request);
List list = getDelegate(request).query(sqlBuilder);
List<Entity> entities = ConvertUtils.pojo2Entities(list, sqlBuilder.getEntityMeta());
return new DasResult()
.setRowCount(list.size())
.setRows(entities)
.setEntityMeta(sqlBuilder.getEntityMeta())
.setDiagInfo(diagInfo2Hints(sqlBuilder.hints().getDiagnose()));
}
private DasResult queryObject(DasRequest request) throws SQLException {
EntityMeta meta = request.getSqlBuilders().get(0).getEntityMeta();
SqlBuilder sqlBuilder = toSqlBuilder(request).setEntityMeta(meta);
Object r = null;
if(request.getSqlBuilders().get(0).isNullable()){
r = getDelegate(request).queryObjectNullable(sqlBuilder);
} else {
r = getDelegate(request).queryObject(sqlBuilder);
}
DasResult dasResult = new DasResult();
List<Entity> entities = ConvertUtils.pojo2Entities(r == null ? Arrays.asList() : Arrays.asList(r), sqlBuilder.getEntityMeta());
return dasResult.setRowCount(entities.size())
.setRows(entities)
.setDiagInfo(diagInfo2Hints(sqlBuilder.hints().getDiagnose()));
}
private DasResult call(DasRequest request) throws SQLException {
CallBuilder callBuilder = BuilderUtils.fromCallBuilder(request.getCallBuilder());
callBuilder.setHints(translate(request.getHints()));//Copy Hints from DasRequest to CallBuilder
getDelegate(request).call(callBuilder);
return new DasResult().setParameters(new DasParameters().setParameters(
BuilderUtils.buildParameters(callBuilder.getParameters())))
.setDiagInfo(diagInfo2Hints(callBuilder.hints().getDiagnose()));
}
private DasResult batchCall(DasRequest request) throws SQLException {
BatchCallBuilder batchCallBuilder = BuilderUtils.fromBatchCallBuilder(request.getBatchCallBuilder());
batchCallBuilder.setHints(translate(request.getHints()));//Copy Hints from DasRequest to BatchCallBuilder
int[] results = getDelegate(request).batchCall(batchCallBuilder);
return intsResult(results).setDiagInfo(diagInfo2Hints(batchCallBuilder.hints().getDiagnose()));
}
private DasResult batchQuery(DasRequest request) throws SQLException {
List<SqlBuilder> sqlBuilders = BuilderUtils.fromSqlBuilders(request.getSqlBuilders());
BatchQueryBuilder batchQueryBuilder = new BatchQueryBuilder();
for (SqlBuilder builder : sqlBuilders) {
batchQueryBuilder.addBatch(builder.into(Entity.class));
}
batchQueryBuilder.setHints(translate(request.getHints()));//Copy Hints from DasRequest to BatchQueryBuilder
List<List<Entity>> results = (List<List<Entity>>) getDelegate(request).batchQuery(batchQueryBuilder);
Object[] flatResult = flatResult(results);
return new DasResult()
.setRowCount(results.size())
.setRows((List<Entity>)flatResult[0])
.setBatchRowsIndex((List<Integer>)flatResult[1])
.setDiagInfo(diagInfo2Hints(batchQueryBuilder.hints().getDiagnose()));
}
private Object[] flatResult(List<List<Entity>> results) {
List<Entity> list = new ArrayList<>();
List<Integer> index = new ArrayList<>();
results.stream().forEach(l -> {
index.add(l.size());
list.addAll(l);
});
return new Object[]{list, index};
}
private DasResult deleteByPk(DasRequest request) throws SQLException {
Entity entity = fillMeta(request);
Hints hints = translate(request.getHints());
int result = getDelegate(request).deleteByPk(entity, hints);
return intResult(result).setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult deleteBySample(DasRequest request) throws SQLException {
Entity entity = fillMeta(request);
Hints hints = translate(request.getHints());
int result = getDelegate(request).deleteBySample(entity, hints);
return intResult(result).setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult insertList(DasRequest request) throws SQLException {
List<Entity> entities = fillMetas(request);
Hints hints = translate(request.getHints());
int result = getDelegate(request).insert(entities, hints);
return idBackResult(result, entities, hints.isSetIdBack())
.setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult insert(DasRequest request) throws SQLException {
Entity entity = fillMeta(request);
Hints hints = translate(request.getHints());
int result = getDelegate(request).insert(entity, hints);
return idBackResult(result, newArrayList(entity), hints.isSetIdBack())
.setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult idBackResult(int insertResult, List<Entity> entities, boolean isIdBack) {
List<Entity> insertResults = newArrayList(new Entity().setValue(new Gson().toJson(insertResult)));
DasResult dasResult = new DasResult().setRows(insertResults);
if(isIdBack) {
insertResults.addAll(entities);
return dasResult.setRowCount(1 + entities.size());
} else {
return dasResult.setRowCount(entities.size());
}
}
private DasResult update(DasRequest request) throws SQLException {
Entity entity = fillMeta(request);
Hints hints = translate(request.getHints());
int result = getDelegate(request).update(entity, hints);
return intResult(result).setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult batchUpdate(DasRequest request) throws SQLException {
List<Entity> entities = fillMetas(request);
Hints hints = translate(request.getHints());
int[] result = getDelegate(request).batchUpdate(entities, hints);
return intsResult(result).setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult batchDelete(DasRequest request) throws SQLException {
List<Entity> entities = fillMetas(request);
Hints hints = translate(request.getHints());
int[] result = getDelegate(request).batchDelete(entities, hints);
return intsResult(result).setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult queryBySample(DasRequest request) throws SQLException {
EntityList entities = request.getEntityList();
checkArgument(!entities.getRows().isEmpty());
Hints hints = translate(request.getHints());
List<Entity> list = getDelegate(request).queryBySample(fillMeta(request), hints);
return new DasResult()
.setRowCount(list.size())
.setRows(list)
.setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult queryBySampleWithRange(DasRequest request) throws SQLException {
return query(request);
}
DasDiagInfo diagInfo2Hints(DasDiagnose dasDiagnose) {
if (dasDiagnose == null) {
return null;
}
Map<String, String> diagnoseInfoMap = Maps.transformEntries(dasDiagnose.getDiagnoseInfoMap(), (key, value) -> Objects.toString(value, ""));
List<DasDiagInfo> subs = dasDiagnose.getChildDiagnoses().stream().map(d -> diagInfo2Hints(d)).collect(Collectors.toList());
return new DasDiagInfo()
.setName(dasDiagnose.getName())
.setDiagnoseInfoMap(diagnoseInfoMap)
.setSpaceLevel(dasDiagnose.getSpaceLevel())
.setEntries(subs);
}
private Hints translate(DasHints dasHints) {
if (dasHints == null) {
return null;
}
Map<DasHintEnum, String> map = dasHints.getHints();
Hints result = new Hints();
String dbShard = map.get(DasHintEnum.dbShard);
if(!isNullOrEmpty(dbShard)){
result.inShard(dbShard);
}
String tableShard = map.get(DasHintEnum.tableShard);
if(!isNullOrEmpty(tableShard)){
result.inTableShard(tableShard);
}
String dbShardValue = map.get(DasHintEnum.dbShardValue);
if(!isNullOrEmpty(dbShardValue)){
result.shardValue(dbShardValue);
}
String tableShardValue = map.get(DasHintEnum.tableShardValue);
if(!isNullOrEmpty(tableShardValue)){
result.tableShardValue(tableShardValue);
}
if(Boolean.valueOf(map.get(DasHintEnum.setIdentityBack))) {
result.setIdBack();
}
if(Boolean.valueOf(map.get(DasHintEnum.enableIdentityInsert))) {
result.insertWithId();
}
if(Boolean.valueOf(map.get(DasHintEnum.diagnoseMode))) {
result.diagnose();
}
return result;
}
private DasResult queryByPK(DasRequest request) throws SQLException {
EntityList entities = request.getEntityList();
checkArgument(!entities.getRows().isEmpty());
Entity pk = fillMeta(request);
Hints hints = translate(request.getHints());
Entity entity = getDelegate(request).queryByPk(pk, hints);
if (entity == null) {
return new DasResult()
.setRowCount(0)
.setRows(Arrays.asList())
.setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
} else {
return new DasResult()
.setRowCount(1)
.setRows(Arrays.asList(entity))
.setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
}
private DasResult countBySample(DasRequest request) throws SQLException {
EntityList entities = request.getEntityList();
checkArgument(!entities.getRows().isEmpty());
Entity sample = fillMeta(request);
Hints hints = translate(request.getHints());
Number count = getDelegate(request).countBySample(sample, hints);
return new DasResult()
.setRowCount(1)
.setRows(Arrays.asList(new Entity().setValue(new Gson().toJson(count))))
.setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
private DasResult batchInsert(DasRequest request) throws SQLException {
EntityList entities = request.getEntityList();
checkArgument(!entities.getRows().isEmpty());
Hints hints = translate(request.getHints());
int[] results = getDelegate(request).batchInsert(fillMetas(request), hints);
return new DasResult()
.setRowCount(results.length)
.setRows(pojo2Entities(Ints.asList(results), null))
.setDiagInfo(diagInfo2Hints(hints.getDiagnose()));
}
@Override
public void commit(DasTransactionId tranId) throws DasException, TException {
try {
transServer.commit(buildTransactionId(tranId));
} catch (SQLException e) {
throw toDasException(e);
}
}
@Override
public void rollback(DasTransactionId tranId) throws DasException, TException {
try {
transServer.rollback(buildTransactionId(tranId));
} catch (SQLException e) {
throw toDasException(e);
}
}
private String buildTransactionId(DasTransactionId tranId) {
return TransactionId.buildUniqueId(tranId.logicDbName, tranId.serverAddress, workerId, tranId.createTime, tranId.sequenceNumber);
}
@Override
public DasTransactionId start(String appId, String logicDbName, DasHints dasHints) throws DasException, TException {
TransactionId id;
try {
id = transServer.start(appId, logicDbName, translate(dasHints));
} catch (SQLException e) {
throw toDasException(e);
}
String clientAddress = "";
DasTransactionId tranId = new DasTransactionId().
setClientAddress(clientAddress).
setCreateTime(id.getLast()).
setCompleted(false).
setLogicDbName(logicDbName).
setPhysicalDbName(id.getPhysicalDbName()).
setSequenceNumber(id.getIndex()).
setRolledBack(false).
setServerAddress(address).
setShardId(id.getShardId());
return tranId;
}
@Override
public DasServerStatus check(DasCheckRequest request) throws DasException, TException {
return monitor.getStatues();
}
private DasException toDasException(SQLException e) {
return new DasException().setCode(String.valueOf(e.getErrorCode())).setMessage(e.getMessage());
}
public static void startServer(int port) throws TTransportException, UnknownHostException, SQLException {
final long start = System.currentTimeMillis();
String address = InetAddress.getLocalHost().getHostAddress();
DasServerContext serverContext = new DasServerContext(address, port);
DasServer server = new DasServer(address, serverContext.getWorkerId());
TBinaryProtocol.Factory protocolFactory = new TBinaryProtocol.Factory();
DasService.Processor<DasService.Iface> processor = new DasService.Processor<>(
server);
int selector = Integer.parseInt(serverContext.getServerConfigure().get(SELECTING_NUMBER));
int worker = Integer.parseInt(serverContext.getServerConfigure().get(WORKING_NUMBER));
TThreadedSelectorServer ttServer = new TThreadedSelectorServer(
new TThreadedSelectorServer.Args(new TNonblockingServerSocket(port))
.selectorThreads(selector)
.processor(processor)
.workerThreads(worker)
.protocolFactory(protocolFactory));
startupHSServer();
logger.info("Start server duration on port [" + port + "]: [" +
TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - start) + "] seconds.");
ttServer.serve();
}
//This server is called by Ops team to check the application aliveness
private static void startupHSServer() {
HttpServer server;
try {
server = HttpServer.create(new InetSocketAddress(8080), 0);
} catch (IOException e) {
logger.error("Fail to startup HSServer", e);
throw new RuntimeException(e);
}
server.createContext("/hs", t -> {
String response = "OK";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
});
server.setExecutor(null);
server.start();
}
//Create a pid file when the process is running
private void createPIDFile(){
try {
final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
final int index = jvmName.indexOf('@');
String pid = "-1";
try {
if (index > 0) {
pid = jvmName.substring(0, index);
}
} catch (NumberFormatException e) {
// ignore
}
Path pidFile = Files.createFile(Paths.get(System.getProperty("user.dir"), pid +".pid"));
Files.write(pidFile, (port + "").getBytes());
pidFile.toFile().deleteOnExit();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws TTransportException, UnknownHostException, SQLException {
startServer(DEFAULT_PORT);
}
}
| 40.952537 | 147 | 0.643594 |
4bbcbae6d0f5e946616ba62dcabe12d4fa89be85 | 10,860 | package com.afeng.common.utils;
import com.google.zxing.*;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 250;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
/**
* 生成Base64图片流编码字符串
*
* @param content 文本
* @author AFeng
* @createDate 2020/12/28 17:14
**/
public static String createBase64(String content) throws Exception {
String qr = null;
// 读取图片
BufferedImage image = QRCodeUtil.createImage(content);
// 创建输出流
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
// 写入流
ImageIO.write(image, "png", byteArrayOutputStream);
byteArrayOutputStream.flush();
// 转为byte[]
byte[] byteArray = byteArrayOutputStream.toByteArray();
//转base64
BASE64Encoder encoder = new BASE64Encoder();
String png_base64 = encoder.encodeBuffer(byteArray).trim();//转换成base64串
//删除 \r\n
png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");
qr = "data:image/png;base64," + png_base64;
} catch (IOException e) {
e.printStackTrace();
}
return qr;
}
/**
* 生成二维码
*/
public static BufferedImage createImage(String content) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
public static BufferedImage createImage(String content, InputStream logo) throws Exception {
BufferedImage image = createImage(content);
// 插入图片
QRCodeUtil.insertImage(image, logo, true);
return image;
}
/**
* 在二维码中间插入logo图片
*/
private static void insertImage(BufferedImage source, InputStream logo, boolean needCompress) throws Exception {
if (logo == null) return;
Image src = ImageIO.read(logo);
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码
*
* @param content 文本内容
* @param logo 内嵌图标
* @param output 输出流
* @throws Exception
*/
public static void encode(String content, InputStream logo, OutputStream output) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content);
ImageIO.write(image, FORMAT_NAME, output);
}
public static void encode(String content, InputStream logo, File out) throws Exception {
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
out.createNewFile();
QRCodeUtil.encode(content, logo, new FileOutputStream(out));
}
public static void encode(String content, File logo, OutputStream out) throws Exception {
if (logo.exists()) {
QRCodeUtil.encode(content, new FileInputStream(logo), out);
} else {
QRCodeUtil.encode(content, (InputStream) null, out);
}
}
public static void encode(String content, File logo, File out) throws Exception {
if (!out.getParentFile().exists()) {
out.getParentFile().mkdirs();
}
out.createNewFile();
if (logo.exists()) {
QRCodeUtil.encode(content, new FileInputStream(logo), out);
} else {
QRCodeUtil.encode(content, (InputStream) null, out);
}
}
public static void encode(String content, InputStream logo, String out) throws Exception {
QRCodeUtil.encode(content, logo, new File(out));
}
public static void encode(String content, String logo, String out) throws Exception {
QRCodeUtil.encode(content, new File(logo), new File(out));
}
public static void encode(String content, OutputStream out) throws Exception {
QRCodeUtil.encode(content, (InputStream) null, out);
}
public static void encode(String content, String out) throws Exception {
QRCodeUtil.encode(content, (InputStream) null, new File(out));
}
/**
* 解析二维码,input是二维码图片流
*/
public static String decode(InputStream input) throws Exception {
BufferedImage image = ImageIO.read(input);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码,file是二维码图片
*/
public static String decode(File file) throws Exception {
return decode(new FileInputStream(file));
}
/**
* 解析二维码,path是二维码图片路径
*/
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}
public static void main(String[] args) throws Exception {
QRCodeUtil.encode("http://baike.xsoftlab.net/view/1114.html", "", "D:/abc/qr/1.jpg");
String data = QRCodeUtil.decode("D:/abc/qr/1.jpg");
System.out.println(data);
}
private static class BufferedImageLuminanceSource extends LuminanceSource {
private final BufferedImage image;
private final int left;
private final int top;
public BufferedImageLuminanceSource(BufferedImage image) {
this(image, 0, 0, image.getWidth(), image.getHeight());
}
public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width,
int height) {
super(width, height);
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
if (left + width > sourceWidth || top + height > sourceHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
for (int y = top; y < top + height; y++) {
for (int x = left; x < left + width; x++) {
if ((image.getRGB(x, y) & 0xFF000000) == 0) {
image.setRGB(x, y, 0xFFFFFFFF); // = white
}
}
}
this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
this.image.getGraphics().drawImage(image, 0, 0, null);
this.left = left;
this.top = top;
}
@Override
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
image.getRaster().getDataElements(left, top + y, width, 1, row);
return row;
}
@Override
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
int area = width * height;
byte[] matrix = new byte[area];
image.getRaster().getDataElements(left, top, width, height, matrix);
return matrix;
}
@Override
public boolean isCropSupported() {
return true;
}
@Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width,
height);
}
@Override
public boolean isRotateSupported() {
return true;
}
@Override
public LuminanceSource rotateCounterClockwise() {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth,
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
int width = getWidth();
return new BufferedImageLuminanceSource(rotatedImage, top,
sourceWidth - (left + width), getHeight(), width);
}
}
}
| 35.032258 | 126 | 0.595028 |
1b561277dbd8ae3ab160afec04faf3c3d722e850 | 6,245 | package swle.xyz.austers.activity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.Objects;
import swle.xyz.austers.R;
import swle.xyz.austers.callback.BasicInfoCallBack;
import swle.xyz.austers.callback.ResponseCallBack;
import swle.xyz.austers.http.UserHttpUtil;
import swle.xyz.austers.room.User;
import swle.xyz.austers.room.UserDao;
import swle.xyz.austers.room.UserDataBase;
import swle.xyz.austers.room.UserRoom;
import swle.xyz.austers.http.JWXT;
public class IdentityAuthenticateActivity extends AppCompatActivity {
private EditText editText_student_number;
private EditText editText_password;
private Button button_login;
private AlertDialog.Builder builder = null;
UserDataBase userDataBase;
UserDao userDao;
SharedPreferences loginInfo = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_identity_authenticate);
initView();
initEvent();
loginInfo = getSharedPreferences("loginInfo", MODE_PRIVATE);
userDataBase = UserRoom.getInstance(getApplicationContext());
userDao = userDataBase.getUserDao();
}
private void initView(){
editText_student_number=findViewById(R.id.editText_student_number);
editText_password=findViewById(R.id.editText_intranet_password);
button_login=findViewById(R.id.button_identity);
Toolbar toolbar = findViewById(R.id.toolbar_identity_authenticate);
setSupportActionBar(toolbar); //将toolbar设置为当前activity的操作栏
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);//添加默认的返回图标
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
getSupportActionBar().setHomeButtonEnabled(true);//设置返回键可用
getSupportActionBar().setDisplayShowTitleEnabled(false);//隐藏toolbar默认显示的label
}
private void initEvent(){
button_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
builder = new AlertDialog.Builder(IdentityAuthenticateActivity.this);
builder.setMessage("验证中");
builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
new Thread(){
@Override
public void run(){
if(!editText_password.getText().toString().equals("") &&
!editText_student_number.getText().toString().equals("")){
JWXT jwxt = new JWXT(editText_student_number.getText().toString(),
editText_password.getText().toString());
jwxt.getName(new BasicInfoCallBack() {
@Override
public void failure(int status_code) {
switch (status_code){
case -1:
dialog.setMessage("请检查是否开启VPN或使用校园网连接");
break;
case -2:
dialog.setMessage("密码错误,请重试");
break;
case -3:
dialog.setMessage("账户不存在");
break;
}
}
@Override
public void success(String[] info) {
String phonenumber = loginInfo.getString("current_user","");
User user = new User();
user.setStudent_id(editText_student_number.getText().toString());
user.setPhonenumber(phonenumber);
user.setStudent_id(info[0]);
user.setOrganization(info[9]);
user.setTrue_name(info[1]);
user.setMajor(info[10]);
user.setIs_student(true);
user.setPassword_jwxt(editText_password.getText().toString());
swle.xyz.austers.bean.User user1 = new swle.xyz.austers.bean.User();
user1.setIsStudent(1);
user1.setPhonenumber(phonenumber);
updateUser(user,user1);
dialog.setMessage(info[1]+"同学,你好!");
}
});
}else {
dialog.setMessage("请检查用户名和密码是否为空");
}
}
}.start();
}
});
}
void updateUser(final User user, swle.xyz.austers.bean.User user1){
UserHttpUtil.update(user1, new ResponseCallBack() {
@Override
public void failure() {
}
@Override
public void success(int code, String message, Object data) {
}
});
new Thread(new Runnable() {
@Override
public void run() {
userDao.InsertUser(user);
}
}).start();
}
}
| 38.78882 | 104 | 0.521217 |
12dce11f63e525c9f6d98862e43fc9f611529775 | 1,137 | package ru.mativ.client.widgets;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Panel;
public abstract class HasValueComposite<T> extends Composite implements HasValue<T> {
private Panel mainPanel;
public HasValueComposite(Panel mainPanel) {
this.mainPanel = mainPanel;
init();
build();
initWidget(mainPanel);
}
protected Panel getMainPanel() {
return mainPanel;
}
protected abstract void init();
protected abstract void build();
protected void fireValueChangeEvent() {
ValueChangeEvent.fire(this, getValue());
}
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
return this.addHandler(handler, ValueChangeEvent.getType());
}
@Override
public void setValue(T value) {
setValue(value, false);
}
}
| 26.44186 | 85 | 0.712401 |
25489ca86af5bf6cf8b32549a60652bbdd8e22e9 | 419 | /*% if (feature.connected) { %*/
package gpl.workspace;
import gpl.vertex.IVertex;
public class ConnectedWorkspace implements IWorkspace {
private int counter = 0;
@Override
public void initVertex(IVertex v) {
v.setComponentNumber(-1);
}
@Override
public void postVisitAction(IVertex v) {
v.setComponentNumber(counter);
}
@Override
public void nextRegionAction(IVertex v) {
counter++;
}
}
/*% } %*/ | 17.458333 | 55 | 0.711217 |
fa413eb78f16e3a8cbb13ea8e743cd0016b12f81 | 10,764 | package com.searchview;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* 项目名:SearchView
* 包名: com.searchview
* 文件名:SearchView
* 创建者:HY
* 创建时间:2019/1/31 14:26
* 描述: 自定义控件SearchView
*/
@SuppressWarnings("unused")
public class SearchView extends RelativeLayout implements ISearcher {
private TextWatcher textWatcher;
private ISearcher.OnImageViewClickListener onSearchImageViewClickListener;
private ISearcher.OnImageButtonClickListener onClearImageButtonClickListener;
private ISearcher.OnImageButtonClickListener onVoiceImageButtonClickListener;
private OnSearchTextViewClickListener onSearchTextViewClickListener;
EditText et_input;
/**
* 点击搜索后是否自动隐藏虚拟键盘
*/
private boolean enableAutoHideSoftKey;
/**
* 点击了搜索(不是搜索图标)后是否清除EditText的焦点
*/
private boolean enableClearFocusAfterSearch;
ImageButton imgBtn_voice; //语音图标
ImageButton imgBtn_cancel; //清除图标
ImageView iv_search; //搜索图标
TextView tv_search;
ConstraintLayout constraintLayout;
View view;
public SearchView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
view = LayoutInflater.from(context).inflate(R.layout.layout_searchview, this);
initTextWatcher();
initView();
initParams(context, attrs);
}
public SearchView(Context context, AttributeSet attrs) {
super(context, attrs);
view = LayoutInflater.from(context).inflate(R.layout.layout_searchview, this);
initTextWatcher();
initView();
initParams(context, attrs);
}
/**
* 初始化自定义属性
*
* @param context context
* @param attrs attrs
*/
private void initParams(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchView);
if (typedArray != null) {
String hint = typedArray.getString(R.styleable.SearchView_hint);
if (hint != null) {
et_input.setHint(hint);
}
Drawable clear_ico = typedArray.getDrawable(R.styleable.SearchView_svClearIcon);
if (clear_ico != null) {
imgBtn_cancel.setBackground(clear_ico);
}
Drawable voice_ico = typedArray.getDrawable(R.styleable.SearchView_svVoiceIcon);
if (clear_ico != null) {
imgBtn_voice.setBackground(voice_ico);
}
Drawable search_ico = typedArray.getDrawable(R.styleable.SearchView_svSearchIcon);
if (clear_ico != null) {
this.iv_search.setImageDrawable(search_ico);
}
this.enableAutoHideSoftKey = typedArray.getBoolean(R.styleable.SearchView_svEnableAutoHideSoftKey, true);
this.enableClearFocusAfterSearch = typedArray.getBoolean(R.styleable.SearchView_svEnableClearFocusAfterSearch, true);
typedArray.recycle();
}
}
private void initView() {
et_input = view.findViewById(R.id.et_input);
imgBtn_voice = view.findViewById(R.id.ib_voice);
imgBtn_cancel = view.findViewById(R.id.ib_cancle);
iv_search = view.findViewById(R.id.iv_search);
tv_search = view.findViewById(R.id.tv_search);
constraintLayout = view.findViewById(R.id.rl_mapsearcher);
et_input.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
constraintLayout.setSelected(true);
et_input.setHint("");
if (et_input.getText().length() > 0) {
imgBtn_cancel.setVisibility(View.VISIBLE);
tv_search.setVisibility(View.VISIBLE);
imgBtn_voice.setVisibility(View.GONE);
} else {
et_input.setSelected(false);
imgBtn_cancel.setVisibility(View.GONE);
tv_search.setVisibility(View.GONE);
imgBtn_voice.setVisibility(View.VISIBLE);
}
} else {
et_input.setHint("请输入关键字");
}
}
});
if (textWatcher != null) {
et_input.addTextChangedListener(textWatcher);
}
//搜索图标点击事件
iv_search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onSearchImageViewClickListener != null) {
onSearchImageViewClickListener.onImageViewClick(et_input, iv_search, v);
}
}
});
//语音图标
imgBtn_voice.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onVoiceImageButtonClickListener != null) {
onVoiceImageButtonClickListener.onImageButtonClick(et_input, imgBtn_voice, SearchView.this);
}
}
});
//取消图标
imgBtn_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
et_input.setText("");
if (onClearImageButtonClickListener != null) {
onClearImageButtonClickListener.onImageButtonClick(et_input, imgBtn_cancel, v);
}
}
});
//搜索
tv_search.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (enableClearFocusAfterSearch) {
et_input.clearFocus();
}
Context context = getContext();
if (context != null && context instanceof Activity && enableAutoHideSoftKey) {
//收起软键盘
Activity activity = (Activity) context;
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && activity.getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); //强制隐藏键盘
}
}
if (onSearchTextViewClickListener != null) {
onSearchTextViewClickListener.onSearchClick(et_input, v);
}
}
});
}
/**
* 设置点击搜索时是否自动隐藏虚拟键盘
*
* @param enableAutoHideSoftKey 点击搜索时是否自动隐藏虚拟键盘
*/
public void setEnableAutoHideSoftKey(boolean enableAutoHideSoftKey) {
this.enableAutoHideSoftKey = enableAutoHideSoftKey;
}
/**
* 点击了搜索(不是搜索图标)后是否清除EditText的焦点
*
* @param enableClearFocusAfterSearch 点击了搜索(不是搜索图标)后是否清除EditText的焦点
*/
public void setEnableClearFocusAfterSearch(boolean enableClearFocusAfterSearch) {
this.enableClearFocusAfterSearch = enableClearFocusAfterSearch;
}
/**
* 搜索图标点击事件
*
* @param listener 回调接口listener
*/
@Override
public void setOnSearchImageViewClickListener(OnImageViewClickListener listener) {
this.onSearchImageViewClickListener = listener;
}
/**
* 清除图标点击事件
*
* @param listener 回调接口listener
*/
@Override
public void setOnClearImageButtonClickListener(OnImageButtonClickListener listener) {
this.onClearImageButtonClickListener = listener;
}
/**
* 语音图标点击事件
*
* @param listener 回调接口listener
*/
@Override
public void setOnVoiceImageButtonClickListener(OnImageButtonClickListener listener) {
this.onVoiceImageButtonClickListener = listener;
}
/**
* "搜索"点击事件
*
* @param listener 回调接口listener
*/
@Override
public void setOnSearchTextViewClickListener(OnSearchTextViewClickListener listener) {
this.onSearchTextViewClickListener = listener;
}
/**
* 获取EditText的内容
*
* @return EditText的内容
*/
@Override
public String getSearchContent() {
return et_input.getText().toString().trim();
}
/**
* 设置EditText的内容
*
* @param content content
*/
@Override
public void setSearchContent(String content) {
et_input.setText(content);
}
/**
* 获取EditText
*
* @return EditText
*/
@Override
public EditText getEditText() {
return et_input;
}
/**
* 设置搜索图标
*
* @param resId DrawableRes
*/
public void setSearchIcon(@DrawableRes int resId) {
this.iv_search.setImageDrawable(getContext().getDrawable(resId));
}
/**
* 设置语音图标
*
* @param resId DrawableRes
*/
public void setVoiceIcon(@DrawableRes int resId) {
imgBtn_voice.setBackground(getContext().getDrawable(resId));
}
/**
* 设置清除图标
*
* @param resId DrawableRes
*/
public void setClearIcon(@DrawableRes int resId) {
imgBtn_cancel.setBackground(getContext().getDrawable(resId));
}
/**
* 初始化textWatcher
*/
private void initTextWatcher() {
textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
int length = s.length();
if (length > 0 && et_input.isFocused()) {
imgBtn_voice.setVisibility(View.GONE);
imgBtn_cancel.setVisibility(View.VISIBLE);
tv_search.setVisibility(View.VISIBLE);
} else {
imgBtn_cancel.setVisibility(View.GONE);
tv_search.setVisibility(View.GONE);
imgBtn_voice.setVisibility(View.VISIBLE);
}
}
};
}
}
| 30.931034 | 129 | 0.607116 |
dd285839e180f85e8f00a0355c9c1999b335c5c4 | 57,354 | package com.ngdesk.modules.fields;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.commons.validator.routines.EmailValidator;
import org.apache.commons.validator.routines.UrlValidator;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import com.mongodb.client.model.Projections;
import com.mongodb.client.model.Sorts;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.Updates;
import com.ngdesk.Authentication;
import com.ngdesk.Global;
import com.ngdesk.exceptions.BadRequestException;
import com.ngdesk.exceptions.ForbiddenException;
import com.ngdesk.exceptions.InternalErrorException;
import com.ngdesk.roles.FieldPermission;
import com.ngdesk.roles.RoleService;
import com.ngdesk.wrapper.Wrapper;
@RestController
@Component
public class FieldService {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private Global global;
@Autowired
private Authentication auth;
@Autowired
RoleService roleService;
@Autowired
private SimpMessagingTemplate template;
@Autowired
Wrapper wrapper;
private final Logger log = LoggerFactory.getLogger(FieldService.class);
// this call is used for master page of fields
@GetMapping("/modules/{module_id}/fields/master")
public ResponseEntity<Object> getFieldsMaster(HttpServletRequest request,
@RequestParam(value = "authentication_token", required = false) String uuid,
@PathVariable("module_id") String moduleId,
@RequestParam(value = "page_size", required = false) String pageSize,
@RequestParam(value = "page", required = false) String page,
@RequestParam(value = "sort", required = false) String sort,
@RequestParam(value = "order", required = false) String order) {
JSONArray fields = new JSONArray();
int totalSize = 0;
JSONObject resultObj = new JSONObject();
try {
log.trace("Enter FieldService.getFields() moduleId: " + moduleId);
if (request.getHeader("authentication_token") != null) {
uuid = request.getHeader("authentication_token");
}
JSONObject user = auth.getUserDetails(uuid);
String companyId = user.getString("COMPANY_ID");
String userId = user.getString("USER_ID");
String collectionName = "modules_" + companyId;
// Retrieving a collection
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
// Get Document
if (!ObjectId.isValid(moduleId)) {
throw new BadRequestException("INVALID_MODULE_ID");
}
Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (module != null) {
String moduleName = module.getString("NAME");
if (!roleService.isAuthorizedForModule(userId, "GET", moduleId, companyId)) {
throw new ForbiddenException("FORBIDDEN");
}
ArrayList<Document> fieldDocuments = (ArrayList) module.get("FIELDS");
totalSize = fieldDocuments.size();
AggregateIterable<Document> sortedDocuments = null;
List<String> fieldNames = new ArrayList<String>();
fieldNames.add("FIELD_ID");
fieldNames.add("NAME");
fieldNames.add("DISPLAY_LABEL");
fieldNames.add("DATA_TYPE");
// by default return all documents
int skip = 0;
int pgSize = 100;
int pg = 1;
if (pageSize != null && page != null) {
pgSize = Integer.valueOf(pageSize);
pg = Integer.valueOf(page);
if (pgSize <= 0) {
throw new BadRequestException("INVALID_PAGE_SIZE");
} else if (pg <= 0) {
throw new BadRequestException("INVALID_PAGE_NUMBER");
} else {
skip = (pg - 1) * pgSize;
}
}
if (sort != null && order != null) {
sort = "FIELDS." + sort;
if (order.equalsIgnoreCase("asc")) {
sortedDocuments = collection.aggregate(Arrays
.asList(Aggregates.unwind("$FIELDS"), Aggregates.match(Filters.eq("NAME", moduleName)),
Aggregates.sort(Sorts.orderBy(Sorts.ascending(sort))),
Aggregates.project(Filters.and(
Projections.computed("FIELDS", Projections.include(fieldNames)),
Projections.excludeId())),
Aggregates.skip(skip), Aggregates.limit(pgSize)));
} else if (order.equalsIgnoreCase("desc")) {
sortedDocuments = collection.aggregate(Arrays
.asList(Aggregates.unwind("$FIELDS"), Aggregates.match(Filters.eq("NAME", moduleName)),
Aggregates.sort(Sorts.orderBy(Sorts.descending(sort))),
Aggregates.project(Filters.and(
Projections.computed("FIELDS", Projections.include(fieldNames)),
Projections.excludeId())),
Aggregates.skip(skip), Aggregates.limit(pgSize)));
} else {
throw new BadRequestException("INVALID_SORT_ORDER");
}
} else {
sortedDocuments = collection.aggregate(Arrays.asList(Aggregates.unwind("$FIELDS"),
Aggregates.match(Filters.eq("NAME", moduleName)),
Aggregates.project(
Filters.and(Projections.computed("FIELDS", Projections.include(fieldNames)),
Projections.excludeId())),
Aggregates.skip(skip), Aggregates.limit(pgSize)));
}
for (Document document : sortedDocuments) {
Document data = (Document) document.get("FIELDS");
fields.put(data);
}
} else {
throw new BadRequestException("MODULE_NOT_EXISTS");
}
resultObj.put("FIELDS", fields);
resultObj.put("TOTAL_RECORDS", totalSize);
log.trace("Exit FieldService.getFields() moduleId: " + moduleId);
return new ResponseEntity<>(resultObj.toString(), Global.postHeaders, HttpStatus.OK);
} catch (JSONException e) {
e.printStackTrace();
}
throw new InternalErrorException("INTERNAL_ERROR");
}
@GetMapping("/modules/{module_id}/fields")
public ResponseEntity<Object> getFields(HttpServletRequest request,
@RequestParam(value = "authentication_token", required = false) String uuid,
@PathVariable("module_id") String moduleId,
@RequestParam(value = "page_size", required = false) String pageSize,
@RequestParam(value = "page", required = false) String page,
@RequestParam(value = "sort", required = false) String sort,
@RequestParam(value = "order", required = false) String order) {
JSONArray fields = new JSONArray();
int totalSize = 0;
JSONObject resultObj = new JSONObject();
try {
log.trace("Enter FieldService.getFields() moduleId: " + moduleId);
if (request.getHeader("authentication_token") != null) {
uuid = request.getHeader("authentication_token");
}
JSONObject user = auth.getUserDetails(uuid);
String companyId = user.getString("COMPANY_ID");
String userId = user.getString("USER_ID");
String collectionName = "modules_" + companyId;
// Retrieving a collection
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
// Get Document
if (!ObjectId.isValid(moduleId)) {
throw new BadRequestException("INVALID_MODULE_ID");
}
Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (module != null) {
String moduleName = module.getString("NAME");
if (!roleService.isAuthorizedForModule(userId, "GET", moduleId, companyId)) {
throw new ForbiddenException("FORBIDDEN");
}
ArrayList<Document> fieldDocuments = (ArrayList) module.get("FIELDS");
totalSize = fieldDocuments.size();
AggregateIterable<Document> sortedDocuments = null;
// by default return all documents
int skip = 0;
int pgSize = 100;
int pg = 1;
if (pageSize != null && page != null) {
pgSize = Integer.valueOf(pageSize);
pg = Integer.valueOf(page);
if (pgSize <= 0) {
throw new BadRequestException("INVALID_PAGE_SIZE");
} else if (pg <= 0) {
throw new BadRequestException("INVALID_PAGE_NUMBER");
} else {
skip = (pg - 1) * pgSize;
}
}
if (sort != null && order != null) {
sort = "FIELDS." + sort;
if (order.equalsIgnoreCase("asc")) {
sortedDocuments = collection.aggregate(Arrays.asList(Aggregates.unwind("$FIELDS"),
Aggregates.match(Filters.eq("NAME", moduleName)),
Aggregates.sort(Sorts.orderBy(Sorts.ascending(sort))),
Aggregates
.project(Filters.and(Projections.computed("FIELDS", Projections.excludeId()))),
Aggregates.skip(skip), Aggregates.limit(pgSize)));
} else if (order.equalsIgnoreCase("desc")) {
sortedDocuments = collection.aggregate(Arrays.asList(Aggregates.unwind("$FIELDS"),
Aggregates.match(Filters.eq("NAME", moduleName)),
Aggregates.sort(Sorts.orderBy(Sorts.descending(sort))),
Aggregates
.project(Filters.and(Projections.computed("FIELDS", Projections.excludeId()))),
Aggregates.skip(skip), Aggregates.limit(pgSize)));
} else {
throw new BadRequestException("INVALID_SORT_ORDER");
}
} else {
sortedDocuments = collection.aggregate(Arrays.asList(Aggregates.unwind("$FIELDS"),
Aggregates.match(Filters.eq("NAME", moduleName)),
Aggregates.project(Filters.and(Projections.computed("FIELDS", Projections.excludeId()))),
Aggregates.skip(skip), Aggregates.limit(pgSize)));
}
for (Document document : sortedDocuments) {
Document data = (Document) document.get("FIELDS");
fields.put(data);
}
} else {
throw new BadRequestException("MODULE_NOT_EXISTS");
}
resultObj.put("FIELDS", fields);
resultObj.put("TOTAL_RECORDS", totalSize);
log.trace("Exit FieldService.getFields() moduleId: " + moduleId);
return new ResponseEntity<>(resultObj.toString(), Global.postHeaders, HttpStatus.OK);
} catch (JSONException e) {
e.printStackTrace();
}
throw new InternalErrorException("INTERNAL_ERROR");
}
@GetMapping("/modules/{module_id}/fields/{field_name}")
public Field getField(HttpServletRequest request,
@RequestParam(value = "authentication_token", required = false) String uuid,
@PathVariable("module_id") String moduleId, @PathVariable("field_name") String fieldName)
throws JsonParseException, JsonMappingException, IOException {
try {
log.trace("Enter FieldService.getField() moduleId: " + moduleId + ", fieldName: " + fieldName);
if (request.getHeader("authentication_token") != null) {
uuid = request.getHeader("authentication_token");
}
JSONObject user = auth.getUserDetails(uuid);
String userId = user.getString("USER_ID");
String companyId = user.getString("COMPANY_ID");
String collectionName = "modules_" + companyId;
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
if (!ObjectId.isValid(moduleId)) {
throw new BadRequestException("INVALID_MODULE_ID");
}
Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (module != null) {
String moduleName = module.getString("NAME");
if ((moduleName.equals("Users") && fieldName.equals("PASSWORD"))) {
throw new ForbiddenException("FIELD_NOT_EXISTS");
}
if (fieldName.equalsIgnoreCase("DELETED")) {
throw new ForbiddenException("FIELD_NOT_EXISTS");
}
if (!roleService.isAuthorizedForModule(userId, "GET", moduleId, companyId)) {
throw new ForbiddenException("FORBIDDEN");
}
if (global.isExistsInModule("FIELDS", fieldName, collectionName, moduleName)) {
ArrayList<Document> fieldDocuments = (ArrayList) module.get("FIELDS");
// GET SPECIFIC FIELD
for (Document fieldDocument : fieldDocuments) {
if (fieldDocument.getString("NAME").equals(fieldName)) {
Field field = new ObjectMapper().readValue(fieldDocument.toJson(), Field.class);
log.trace("Exit FieldService.getField() moduleName: " + moduleName + ", fieldName: "
+ fieldName);
return field;
}
}
} else {
throw new ForbiddenException("FIELD_NOT_EXISTS");
}
} else {
throw new ForbiddenException("MODULE_NOT_EXISTS");
}
} catch (JSONException e) {
e.printStackTrace();
}
throw new InternalErrorException("INTERNAL_ERROR");
}
@GetMapping("/modules/{module_id}/fields/id/{field_id}")
public Field getFieldById(HttpServletRequest request,
@RequestParam(value = "authentication_token", required = false) String uuid,
@PathVariable("module_id") String moduleId, @PathVariable("field_id") String fieldId)
throws JsonParseException, JsonMappingException, IOException {
try {
log.trace("Enter FieldService.getFieldById() moduleId: " + moduleId + ", fieldId: " + fieldId);
if (request.getHeader("authentication_token") != null) {
uuid = request.getHeader("authentication_token");
}
JSONObject user = auth.getUserDetails(uuid);
String userId = user.getString("USER_ID");
String companyId = user.getString("COMPANY_ID");
String collectionName = "modules_" + companyId;
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
if (!ObjectId.isValid(moduleId)) {
throw new BadRequestException("INVALID_MODULE_ID");
}
Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (module != null) {
String moduleName = module.getString("NAME");
if ((moduleName.equals("Users") && fieldId.equals("cb3a9d64-0b46-43f0-8452-6038429e6bcb"))) {
throw new ForbiddenException("FIELD_NOT_EXISTS");
}
if (!roleService.isAuthorizedForModule(userId, "GET", moduleId, companyId)) {
throw new ForbiddenException("FORBIDDEN");
}
if (collection.find(Filters.and(Filters.eq("NAME", moduleName),
Filters.elemMatch("FIELDS", Filters.eq("FIELD_ID", fieldId)))).first() != null) {
ArrayList<Document> fieldDocuments = (ArrayList) module.get("FIELDS");
// GET SPECIFIC FIELD
for (Document fieldDocument : fieldDocuments) {
if (fieldDocument.get("FIELD_ID") != null
&& fieldDocument.getString("FIELD_ID").equals(fieldId)) {
String fieldString = new ObjectMapper().writeValueAsString(fieldDocument);
Field field = new ObjectMapper().readValue(fieldString, Field.class);
// GETTING DATA FILTER FROM THE RELATIONFIELD FIELD
if (field.getDatatypes().getDisplay().equalsIgnoreCase("relationship")
&& field.getModule() != null && field.getRelationshipField() != null) {
Document relationModule = collection
.find(Filters.eq("_id", new ObjectId(field.getModule()))).first();
List<Document> fields = (List<Document>) relationModule.get("FIELDS");
for (Document relationField : fields) {
if (relationField.getString("FIELD_ID")
.equalsIgnoreCase(field.getRelationshipField())) {
if (relationField.get("DATA_FILTER") == null) {
field.setDataFilter(null);
} else {
Document relationDataFilter = (Document) relationField.get("DATA_FILTER");
DataFilter dataFilter = new ObjectMapper()
.readValue(relationDataFilter.toJson(), DataFilter.class);
field.setDataFilter(dataFilter);
}
}
}
}
log.trace("Exit FieldService.getFieldById() moduleName: " + moduleName + ", fieldId: "
+ fieldId);
return field;
}
}
} else {
throw new ForbiddenException("FIELD_NOT_EXISTS");
}
} else {
throw new ForbiddenException("MODULE_NOT_EXISTS");
}
} catch (JSONException e) {
e.printStackTrace();
}
throw new InternalErrorException("INTERNAL_ERROR");
}
@PostMapping("/modules/{module_id}/fields/{field_name}")
public Field postFields(HttpServletRequest request,
@RequestParam(value = "authentication_token", required = false) String uuid,
@PathVariable("module_id") String moduleId, @PathVariable("field_name") String fieldName,
@Valid @RequestBody Field field) {
try {
log.trace("Enter FieldService.postFields() moduleId: " + moduleId + ", fieldName: " + fieldName);
if (request.getHeader("authentication_token") != null) {
uuid = request.getHeader("authentication_token");
}
fieldName = fieldName.trim();
fieldName = fieldName.toUpperCase();
fieldName = fieldName.replaceAll("\\s+", "_");
String fName = field.getName();
fName = fName.trim();
fName = fName.toUpperCase();
fName = fName.replaceAll("\\s+", "_");
field.setName(fName);
JSONObject user = auth.getUserDetails(uuid);
String userId = user.getString("USER_ID");
String companyId = user.getString("COMPANY_ID");
String collectionName = "modules_" + companyId;
field.setDateCreated(new Timestamp(new Date().getTime()));
field.setCreatedBy(userId);
if (global.restrictedFieldNames.contains(field.getName())) {
throw new BadRequestException("RESTRICTED_FIELDS_SAVE");
}
if (field.getDatatypes().getDisplay().equals("Relationship")) {
throw new BadRequestException("INVALID_REQUEST");
}
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
List<Document> modules = (List<Document>) collection.find().into(new ArrayList<>());
if (!ObjectId.isValid(moduleId)) {
throw new BadRequestException("INVALID_MODULE_ID");
}
Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (module != null) {
String moduleName = module.getString("NAME");
if (!roleService.isAuthorizedForModule(userId, "POST", moduleId, companyId)) {
throw new ForbiddenException("FORBIDDEN");
}
ArrayList<Document> fieldDocuments = (ArrayList) module.get("FIELDS");
if (fieldDocuments.size() >= 100) {
throw new BadRequestException("MAX_FIELDS_REACHED");
}
for (Document document : fieldDocuments) {
if (document.getString("NAME").equals(field.getName())) {
throw new BadRequestException("FIELD_EXISTS");
}
}
if (!verifyInternal(field)) {
throw new BadRequestException("INTERNAL_INVALID");
}
if (!isFieldDiscussion(module, field, collectionName)) {
throw new BadRequestException("FIELD_DISCUSSION_EXISTS");
}
String displayDataType = field.getDatatypes().getDisplay();
if (displayDataType.equals("Picklist")) {
if (field.getPicklistValues().size() < 1) {
throw new BadRequestException("PICKLIST_VALUES_EMPTY");
}
List<String> picklistValues = field.getPicklistValues();
Set<String> uniqueValues = new HashSet<String>(picklistValues);
if (picklistValues.size() != uniqueValues.size()) {
throw new BadRequestException("PICKLIST_VALUES_NOT_UNIQUE");
}
}
if (displayDataType.equals("Picklist (Multi-Select)")) {
if (field.getPicklistValues().size() < 1) {
throw new BadRequestException("PICKLIST_VALUES_EMPTY");
}
}
if (field.getName().contains(".")) {
throw new BadRequestException("INVALID_FIELD_NAME");
}
if (!displayDataType.equals("Formula") && !field.getDatatypes().getBackend().equals("Formula")) {
if (field.getFormula() != null) {
throw new BadRequestException("INVALID_REQUEST");
}
}
if (displayDataType.equals("Button")) {
if (field.getWorkflow() == null) {
throw new BadRequestException("WORKFLOW_NULL");
}
List<Document> workflows = (List<Document>) module.get("WORKFLOWS");
boolean workflowFound = false;
for (Document workflow : workflows) {
String workflowId = workflow.getString("WORKFLOW_ID");
if (workflowId.equalsIgnoreCase(field.getWorkflow())) {
workflowFound = true;
break;
}
}
if (!workflowFound) {
throw new BadRequestException("INVALID_WORKFLOW");
}
}
if (displayDataType.equals("Aggregate")) {
if (field.getAggregationField() == null) {
throw new BadRequestException("AGGREGATION_FIELD_NULL");
}
if (field.getAggregationType() == null) {
throw new BadRequestException("NOT_VALID_AGGREGATION_TYPE");
}
if (field.getAggregationRelatedField() == null) {
throw new BadRequestException("RELATIONSHIP_FIELD_REQUIRED");
}
Optional<Document> optional = fieldDocuments.stream()
.filter(f -> f.getString("FIELD_ID").equals(field.getAggregationField())).findAny();
if (!optional.isPresent()) {
throw new BadRequestException("AGGREGATION_FIELD_SHOULD_BE_ONE_TO_MANY");
}
Document relationshipField = optional.get();
Document relatedModule = collection
.find(Filters.eq("_id", new ObjectId(relationshipField.getString("MODULE")))).first();
List<Document> relatedModuleFields = (List<Document>) relatedModule.get("FIELDS");
Optional<Document> optionalRelatedField = relatedModuleFields.stream()
.filter(f -> f.getString("FIELD_ID").equals(field.getAggregationRelatedField())).findAny();
if (!optionalRelatedField.isPresent()) {
throw new BadRequestException("INVALID_AGGREGATION_RELATIONSHIP_FIELD");
}
Document relatedField = optionalRelatedField.get();
Document dataType = (Document) relatedField.get("DATA_TYPE");
String backendDataType = dataType.getString("BACKEND");
if (!backendDataType.equals("Float") && !backendDataType.equals("Integer")
&& !backendDataType.equals("Double")) {
throw new BadRequestException("INVALID_AGGREGATION_RELATIONSHIP_FIELD");
}
}
if (field.getDefaultValue() != null && !field.getDefaultValue().equals("")) {
isValidDefaultValue(field, companyId);
}
if (field.getDatatypes().getDisplay().equals("Chronometer") && field.getDefaultValue() != null) {
long chronometerValueInSecond = 0;
String value = field.getDefaultValue().toString();
String valueWithoutSpace = value.replaceAll("\\s+", "");
if (valueWithoutSpace.length() == 0 || valueWithoutSpace.charAt(0) == '-') {
field.setDefaultValue(null);
} else if (valueWithoutSpace.length() != 0) {
chronometerValueInSecond = global.chronometerValueConversionInSeconds(valueWithoutSpace);
field.setDefaultValue(chronometerValueInSecond + "");
}
}
if (field.getDatatypes().getDisplay().equals("Address")) {
String[] TypeName = { "Street 1", "Street 2", "City", "State", "Zipcode" };
String groupId = UUID.randomUUID().toString();
for (int i = 0; i < TypeName.length; i++) {
String name = null;
DataType dataType = new DataType();
String displayType = TypeName[i];
dataType.setDisplay(displayType);
dataType.setBackend("String");
Field fieldobj = new Field();
fieldobj.setFieldId(UUID.randomUUID().toString());
fieldobj.setDisplayLabel(field.getName().toLowerCase() + " " + displayType);
if (displayType.contains("Street")) {
name = displayType.substring(0, 6).toUpperCase() + "_" + displayType.split("Street ")[1];
} else {
name = displayType.toUpperCase();
}
fieldobj.setName(field.getName() + "_" + name);
fieldobj.setDatatypes(dataType);
fieldobj.setGroupId(groupId);
fieldobj.setPicklist("Enter Values");
String fieldBody = new ObjectMapper().writeValueAsString(fieldobj).toString();
Document fieldDocument = Document.parse(fieldBody);
collection.updateOne(Filters.eq("NAME", moduleName), Updates.addToSet("FIELDS", fieldDocument));
}
} else {
field.setFieldId(UUID.randomUUID().toString());
String fieldBody = new ObjectMapper().writeValueAsString(field).toString();
Document fieldDocument = Document.parse(fieldBody);
collection.updateOne(Filters.eq("NAME", moduleName), Updates.addToSet("FIELDS", fieldDocument));
}
updateRoles(moduleId, field.getFieldId(), companyId);
int size = 0;
int totalDataTimeField = 0;
for (Document doc : fieldDocuments) {
Document type = (Document) doc.get("DATA_TYPE");
if (type.getString("DISPLAY").equals("Date/Time") || type.getString("DISPLAY").equals("Date")
|| type.getString("DISPLAY").equals("Time")) {
totalDataTimeField++;
}
}
if (totalDataTimeField == 0 && !field.getDatatypes().getDisplay().equals("Date/Time")
&& !field.getDatatypes().getDisplay().equals("Date")
&& !field.getDatatypes().getDisplay().equals("Time")) {
size = fieldDocuments.size();
} else if (totalDataTimeField == 0 && (field.getDatatypes().getDisplay().equals("Date/Time")
|| field.getDatatypes().getDisplay().equals("Date")
|| field.getDatatypes().getDisplay().equals("Time"))) {
size = 84;
} else if (totalDataTimeField != 0 && !field.getDatatypes().getDisplay().equals("Date/Time")
&& !field.getDatatypes().getDisplay().equals("Date")
&& !field.getDatatypes().getDisplay().equals("Time")) {
size = fieldDocuments.size() - totalDataTimeField;
} else if (totalDataTimeField != 0 && (field.getDatatypes().getDisplay().equals("Date/Time")
|| field.getDatatypes().getDisplay().equals("Date")
|| field.getDatatypes().getDisplay().equals("Time"))) {
size = 84 + totalDataTimeField;
}
// Load putmapping request for all the modules On elastic
wrapper.putMappingForNewField(companyId, moduleId, field.getName(), size + 1);
if (field.getDatatypes().getDisplay().equals("Auto Number") && field.isAutonumberGeneration()) {
// GENERATE AUTONUMBER TO ALL EXISTING ENTRIES
generateAutoNumberToExistingEntries(moduleName, companyId, field, moduleId);
}
// INDEX NOT CREATED FOR DISCUSSION, PICKLIST (MULIT-SELECT), PHONE.
createIndexForTheField(companyId, moduleId, field);
log.trace("Exit FieldService.postFields() moduleName: " + moduleName + ", fieldName: " + fieldName);
this.template.convertAndSend("rest/" + moduleId + "/channels/email/mapping/field-created",
"Field Created Successfully");
return field;
} else {
throw new ForbiddenException("MODULE_NOT_EXISTS");
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
throw new InternalErrorException("INTERNAL_ERROR");
}
@PostMapping("/modules/{module_id}/fields/{field_name}/relationship")
public Field postRelationshipField(HttpServletRequest request,
@RequestParam(value = "authentication_token", required = false) String uuid,
@PathVariable("module_id") String moduleId, @PathVariable("field_name") String fieldName,
@RequestParam("required") Boolean requiredField2,
@RequestParam("primary_display_field") String displayField,
@RequestParam("display_name") String displayName, @RequestParam("name") String field2Name,
@Valid @RequestBody Field field) {
log.trace("Enter FieldService.postRelationshipField() moduleId: " + moduleId + ", fieldName: " + fieldName);
try {
if (request.getHeader("authentication_token") != null) {
uuid = request.getHeader("authentication_token");
}
if (displayName == null || displayName.trim().isEmpty()) {
throw new BadRequestException("DISPLAY_NAME_REQUIRED");
}
if (field2Name == null || field2Name.trim().isEmpty()) {
throw new BadRequestException("SYSTEM_NAME_REQUIRED");
}
if (displayField == null || displayField.trim().isEmpty()) {
if (field.getRelationshipType().equals("One to Many")
|| field.getRelationshipType().equals("One to One")) {
throw new BadRequestException("PRIMARY_DISPLAY_FIELD_REQUIRED");
}
}
JSONObject user = auth.getUserDetails(uuid);
String userId = user.getString("USER_ID");
String companyId = user.getString("COMPANY_ID");
String collectionName = "modules_" + companyId;
if (global.restrictedFieldNames.contains(field.getName())) {
throw new BadRequestException("FIELD_NAME_INVALID");
}
if (!field.getDatatypes().getDisplay().equals("Relationship")) {
throw new BadRequestException("INVALID_REQUEST");
}
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
MongoCollection<Document> rolesCollection = mongoTemplate.getCollection("roles_" + companyId);
if (!ObjectId.isValid(moduleId)) {
throw new BadRequestException("INVALID_MODULE_ID");
}
Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (module != null) {
String moduleName = module.getString("NAME");
if (!roleService.isAuthorizedForModule(userId, "POST", moduleId, companyId)) {
throw new ForbiddenException("FORBIDDEN");
}
ArrayList<Document> fieldDocuments = (ArrayList) module.get("FIELDS");
for (Document document : fieldDocuments) {
if (document.getString("NAME").equals(field.getName())) {
throw new BadRequestException("FIELD_EXISTS");
}
if (fieldDocuments.size() >= 100) {
throw new BadRequestException("MAX_FIELDS_REACHED");
}
if (document.getString("FIELD_ID").equals(displayField)) {
Document datatype = (Document) document.get("DATA_TYPE");
if (datatype.getString("DISPLAY").equals("Relationship")) {
throw new BadRequestException("PRIMARY_DISPLAY_CANNOT_BE_RELATIONSHIP");
}
}
}
if (!verifyInternal(field)) {
throw new BadRequestException("INTERNAL_INVALID");
}
if (field.getRelationshipType() == null) {
throw new BadRequestException("RELATIONSHIP_TYPE_REQUIRED");
}
if (field.getRelationshipType().equals("Many to One")) {
throw new BadRequestException("NOT_VALID_RELATIONSHIP_TYPE");
} else if (field.getRelationshipType().equals("One to Many")) {
if (field.isRequired()) {
throw new BadRequestException("REQUIRED_FIELD_MUST_BE_FALSE");
}
}
Document relationModule = null;
if (field.getModule() == null) {
throw new BadRequestException("MODULE_REQUIRED");
} else {
if (!new ObjectId().isValid(field.getModule())) {
throw new BadRequestException("INVALID_MODULE_ID");
}
relationModule = collection.find(Filters.eq("_id", new ObjectId(field.getModule()))).first();
if (relationModule == null) {
throw new ForbiddenException("MODULE_NOT_EXISTS");
}
}
if (field.getLookupRelationshipField() == null) {
if (field.getRelationshipType().equals("One to One"))
throw new BadRequestException("RELATIONSHIP_FIELD_REQUIRED");
}
List<Document> relationModuleFields = (List<Document>) relationModule.get("FIELDS");
HashSet<String> fieldIds = new HashSet<String>();
for (Document moduleField : relationModuleFields) {
fieldIds.add(moduleField.getString("FIELD_ID"));
if (field.getRelationshipType().equals("One to One")) {
if (field.getLookupRelationshipField().equals(moduleField.getString("FIELD_ID"))) {
Document datatype = (Document) moduleField.get("DATA_TYPE");
if (datatype.getString("DISPLAY").equals("Relationship")) {
throw new BadRequestException("PRIMARY_DISPLAY_CANNOT_BE_RELATIONSHIP");
}
}
}
}
if (field.getRelationshipType().equals("One to One")) {
if (!fieldIds.contains(field.getLookupRelationshipField())) {
throw new BadRequestException("RELATIONSHIP_FIELD_NOT_EXISTS");
}
}
Field field2 = new Field();
field2.setFieldId(UUID.randomUUID().toString());
field.setFieldId(UUID.randomUUID().toString());
field.setRelationshipField(field2.getFieldId());
field2.setDataFilter(field.getDataFilter());
field.setDataFilter(null);
String fieldJson = new ObjectMapper().writeValueAsString(field);
Document fieldDocument = Document.parse(fieldJson);
collection.updateOne(Filters.eq("NAME", moduleName), Updates.addToSet("FIELDS", fieldDocument));
// CREATING INDEX FOR FIRST FIELD
createIndexForTheField(companyId, moduleId, field);
FieldPermission permission = new FieldPermission();
permission.setFieldId(field.getFieldId());
permission.setPermission("Not Set");
String permissionJson = new ObjectMapper().writeValueAsString(permission);
Document document = Document.parse(permissionJson);
updateRoles(moduleId, field.getFieldId(), companyId);
field2.setName(field2Name);
DataType datatype = new DataType();
datatype.setDisplay("Relationship");
if (field.getRelationshipType().equals("One to Many")) {
field2.setRelationshipType("Many to One");
field2.setRequired(requiredField2);
datatype.setBackend("String");
} else if (field.getRelationshipType().equals("Many to Many")) {
field2.setRelationshipType("Many to Many");
field2.setRequired(requiredField2);
datatype.setBackend("Array");
} else if (field.getRelationshipType().equals("One to One")) {
field2.setRelationshipType("One to One");
field2.setRequired(requiredField2);
datatype.setBackend("String");
}
field2.setDisplayLabel(displayName);
field2.setDatatypes(datatype);
field2.setLookupRelationshipField(displayField);
field2.setModule(module.getObjectId("_id").toString());
field2.setRelationshipField(field.getFieldId());
String field2Json = new ObjectMapper().writeValueAsString(field2);
Document field2Doc = Document.parse(field2Json);
collection.updateOne(Filters.eq("NAME", relationModule.getString("NAME")),
Updates.addToSet("FIELDS", field2Doc));
// CREATE INDEX FOR FIELD2
createIndexForTheField(companyId, field.getModule(), field2);
String permissionJson2 = new ObjectMapper().writeValueAsString(permission);
Document document2 = Document.parse(permissionJson2);
updateRoles(moduleId, field2.getFieldId(), companyId);
this.template.convertAndSend("rest/" + field.getModule() + "/channels/email/mapping/field-created",
"Field Created Successfully");
return field;
} else {
throw new ForbiddenException("MODULE_NOT_EXISTS");
}
} catch (JSONException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
log.trace("Exit FieldService.postRelationshipField() moduleId: " + moduleId + ", fieldName: " + fieldName);
throw new InternalErrorException("INTERNAL_ERROR");
}
private void generateAutoNumberToExistingEntries(String moduleName, String companyId, Field field,
String moduleId) {
try {
String collectionName = moduleName.replaceAll("\\s+", "_") + "_" + companyId;
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
int count = (int) collection.countDocuments();
int autoNumber = (int) field.getAutonumberStartingNumber();
List<Document> entries = collection.find().sort(Sorts.ascending("DATE_CREATED")).skip(0).limit(count)
.into(new ArrayList<Document>());
for (Document entry : entries) {
entry.put(field.getName(), autoNumber);
String dataId = entry.remove("_id").toString();
String entryString = new ObjectMapper().writeValueAsString(entry);
wrapper.putData(companyId, moduleId, moduleName, entryString, dataId);
autoNumber++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
@PutMapping("/modules/{module_id}/fields/{field_name}")
public Field putFields(HttpServletRequest request,
@RequestParam(value = "authentication_token", required = false) String uuid,
@PathVariable("module_id") String moduleId, @PathVariable("field_name") String fieldName,
@Valid @RequestBody Field field) {
try {
log.trace("Enter FieldService.putFields() moduleId: " + moduleId + ", fieldName: " + fieldName);
if (request.getHeader("authentication_token") != null) {
uuid = request.getHeader("authentication_token");
}
JSONObject user = auth.getUserDetails(uuid);
String companyId = user.getString("COMPANY_ID");
String userId = user.getString("USER_ID");
field.setDateUpdated(new Timestamp(new Date().getTime()));
field.setLastUpdatedBy(userId);
String collectionName = "modules_" + companyId;
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
if (!ObjectId.isValid(moduleId)) {
throw new BadRequestException("INVALID_MODULE_ID");
}
Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (field.getFieldId() != null) {
if (module != null) {
String moduleName = module.getString("NAME");
if (!roleService.isAuthorizedForModule(userId, "PUT", moduleId, companyId)) {
throw new ForbiddenException("FORBIDDEN");
}
if (collection.find(Filters.and(Filters.eq("FIELDS.FIELD_ID", field.getFieldId()),
Filters.eq("NAME", moduleName))).first() != null) {
ArrayList<Document> fields = (ArrayList) module.get("FIELDS");
for (Document fielddoc : fields) {
if (fielddoc.getString("NAME").equals(field.getName()) && fielddoc.getBoolean("INTERNAL")) {
throw new BadRequestException("RESTRICTED_FIELDS_SET");
}
if (!fielddoc.getString("FIELD_ID").equals(field.getFieldId())) {
// if (fielddoc.getString("NAME").equals(field.getName())) {
// throw new BadRequestException("FIELD_EXISTS");
// }
Document fieldDataTypeDoc = (Document) fielddoc.get("DATA_TYPE");
if (field.getDatatypes().getDisplay().equals("Discussion")
&& fieldDataTypeDoc.get("DISPLAY").equals("Discussion")) {
throw new BadRequestException("FIELD_DISCUSSION_EXISTS");
}
} else {
// SAME FIELD
JSONObject existingField = new JSONObject(fielddoc.toJson());
String existingFieldName = existingField.getString("NAME");
String datatypeDisplay = field.getDatatypes().getDisplay();
String datatypeBackend = field.getDatatypes().getBackend();
String existingDisplayDatatype = existingField.getJSONObject("DATA_TYPE")
.getString("DISPLAY");
String existingBackEndDatatype = existingField.getJSONObject("DATA_TYPE")
.getString("BACKEND");
if (!datatypeDisplay.equals(existingDisplayDatatype)
|| !existingBackEndDatatype.equals(datatypeBackend)) {
throw new BadRequestException("DATA_TYPE_MODIFIED");
}
if (!field.getName().equals(existingFieldName)) {
throw new BadRequestException("FIELD_NAME_CANNOT_BE_CHANGED");
}
}
}
if (field.getDatatypes().getDisplay().equals("Button")) {
if (field.getWorkflow() == null) {
throw new BadRequestException("WORKFLOW_NULL");
}
List<Document> workflows = (List<Document>) module.get("WORKFLOWS");
boolean workflowFound = false;
for (Document workflow : workflows) {
String workflowId = workflow.getString("WORKFLOW_ID");
if (workflowId.equalsIgnoreCase(field.getWorkflow())) {
workflowFound = true;
break;
}
}
if (!workflowFound) {
throw new BadRequestException("INVALID_WORKFLOW");
}
}
if (field.getDatatypes().getDisplay().equals("Chronometer")
&& field.getDefaultValue() != null) {
long chronometerValueInSecond = 0;
String value = field.getDefaultValue().toString();
String valueWithoutSpace = value.replaceAll("\\s+", "");
if (valueWithoutSpace.length() == 0 || valueWithoutSpace.charAt(0) == '-') {
field.setDefaultValue(null);
} else if (valueWithoutSpace.length() != 0) {
chronometerValueInSecond = global
.chronometerValueConversionInSeconds(valueWithoutSpace);
field.setDefaultValue(chronometerValueInSecond + "");
}
}
if (!verifyInternal(field)) {
throw new BadRequestException("INTERNAL_INVALID");
}
if (field.getDefaultValue() != null && !field.getDefaultValue().equals("")) {
isValidDefaultValue(field, companyId);
}
if (field.getDatatypes().getDisplay().equals("Picklist")) {
if (field.getPicklistValues().size() < 1) {
throw new BadRequestException("PICKLIST_VALUES_EMPTY");
}
List<String> picklistValues = field.getPicklistValues();
Set<String> uniqueValues = new HashSet<String>(picklistValues);
if (picklistValues.size() != uniqueValues.size()) {
throw new BadRequestException("PICKLIST_VALUES_NOT_UNIQUE");
}
}
if (field.getDatatypes().getDisplay().equals("Picklist (Multi-Select)")) {
if (field.getPicklistValues().size() < 1) {
throw new BadRequestException("PICKLIST_VALUES_EMPTY");
}
}
if (field.getDatatypes().getDisplay().equalsIgnoreCase("Relationship")) {
if (field.getRelationshipType().equalsIgnoreCase("Many To One")
&& field.getInheritanceMapping() != null) {
// TODO: implement checkValidInheritanceMap logic
}
if (field.getDataFilter() != null && field.getModule() != null
&& field.getRelationshipField() != null) {
Document dataFilter = Document
.parse(new ObjectMapper().writeValueAsString(field.getDataFilter()));
collection.updateOne(Filters.eq("_id", new ObjectId(field.getModule())),
Updates.set("FIELDS.$[field].DATA_FILTER", dataFilter),
new UpdateOptions().arrayFilters(Arrays
.asList(Filters.eq("field.RELATIONSHIP_FIELD", field.getFieldId()))));
}
}
field.setDataFilter(null);
String fieldBody = new ObjectMapper().writeValueAsString(field).toString();
Document fieldDocument = Document.parse(fieldBody);
collection.updateOne(Filters.eq("NAME", moduleName),
Updates.pull("FIELDS", Filters.eq("FIELD_ID", field.getFieldId())));
collection.updateOne(Filters.eq("NAME", moduleName), Updates.push("FIELDS", fieldDocument));
log.trace("Exit FieldService.putFields() moduleName: " + moduleName + ", fieldName: "
+ fieldName);
return field;
} else {
throw new ForbiddenException("FIELD_NOT_EXISTS");
}
} else {
throw new ForbiddenException("MODULE_NOT_EXISTS");
}
} else {
throw new BadRequestException("FIELD_ID_NULL");
}
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
throw new InternalErrorException("INTERNAL_ERROR");
}
// @DeleteMapping("/modules/{module_id}/fields/{field_name}")
// public ResponseEntity<Object> deleteFields(HttpServletRequest request,
// @RequestParam("authentication_token") String uuid, @PathVariable("field_name") String fieldName,
// @PathVariable("module_id") String moduleId) {
// try {
// log.trace("Enter FieldService.deleteFields() moduleId: " + moduleId + ", fieldName: " + fieldName);
// JSONObject user = auth.getUserDetails(uuid);
// String userId = user.getString("USER_ID");
// String companyId = user.getString("COMPANY_ID");
// String collectionName = "modules_" + companyId;
// MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
// if (!ObjectId.isValid(moduleId)) {
// throw new BadRequestException("INVALID_MODULE_ID");
// }
// Document module = collection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
//
// if (module != null) {
//
// String moduleName = module.getString("NAME");
// if (!roleService.isAuthorizedForModule(userId, "DELETE", moduleId, companyId)) {
// throw new ForbiddenException("FORBIDDEN");
// }
//
// List<Document> fields = (List<Document>) module.get("FIELDS");
//
// Document fieldToBeDeleted = null;
//
// for(Document field: fields) {
//
// String name = field.getString("NAME");
//
// if(name.equals(fieldName)) {
// fieldToBeDeleted = field;
// break;
// }
// }
//
// if (fieldToBeDeleted != null) {
//
// if(fieldToBeDeleted.getBoolean("INTERNAL")) {
// throw new BadRequestException("INTERNAL_INVALID");
// }
//
// collection.updateOne(Filters.eq("NAME", moduleName),
// Updates.pull("FIELDS", Filters.eq("NAME", fieldName)));
// log.trace(
// "Exit FieldService.deleteFields() moduleName: " + moduleName + ", fieldName: " + fieldName);
// return new ResponseEntity<Object>(HttpStatus.OK);
// } else {
// throw new ForbiddenException("FIELD_NOT_EXISTS");
// }
// } else {
// throw new ForbiddenException("MODULE_NOT_EXISTS");
// }
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
// }
public boolean isFieldDiscussion(Document module, Field field, String collectionName) {
try {
MongoCollection<Document> collection = mongoTemplate.getCollection(collectionName);
if (field.getDatatypes().getDisplay().equals("Discussion")) {
if (collection
.find(Filters.and(Filters.eq("_id", new ObjectId(module.get("_id").toString())),
Filters.eq("FIELDS.DATA_TYPE.DISPLAY", field.getDatatypes().getDisplay())))
.first() != null) {
return false;
}
}
} catch (Exception e) {
e.printStackTrace();
throw new InternalErrorException("INTERNAL_ERROR");
}
return true;
}
public boolean verifyInternal(Field field) {
if (field.isInternal()) {
return false;
}
return true;
}
private void updateRoles(String moduleId, String fieldId, String companyId) {
try {
MongoCollection<Document> collection = mongoTemplate.getCollection("roles_" + companyId);
FieldPermission permission = new FieldPermission();
permission.setFieldId(fieldId);
permission.setPermission("Not Set");
String permissionJson = new ObjectMapper().writeValueAsString(permission);
Document document = Document.parse(permissionJson);
collection.updateMany(
Filters.and(Filters.ne("NAME", "SystemAdmin"),
Filters.elemMatch("PERMISSIONS", Filters.eq("MODULE", moduleId))),
Updates.addToSet("PERMISSIONS.$.FIELD_PERMISSIONS", document));
} catch (Exception e) {
e.printStackTrace();
}
}
private void createIndexForTheField(String companyId, String moduleId, Field field) {
try {
String displayDataType = field.getDatatypes().getDisplay();
if (!(displayDataType.equalsIgnoreCase("Picklist (Multi-Select)")
|| displayDataType.equalsIgnoreCase("Discussion") || displayDataType.equalsIgnoreCase("Phone")
|| displayDataType.equalsIgnoreCase("Text Area")
|| displayDataType.equalsIgnoreCase("Text Area Long")
|| displayDataType.equalsIgnoreCase("Text Area Rich"))) {
MongoCollection<Document> modulesCollection = mongoTemplate.getCollection("modules_" + companyId);
Document module = modulesCollection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
String moduleName = module.getString("NAME");
String collectionName = moduleName.replaceAll("\\s+", "_") + "_" + companyId;
MongoCollection<Document> entriesCollection = mongoTemplate.getCollection(collectionName);
if (displayDataType.equalsIgnoreCase("Relationship")) {
if (!(field.getRelationshipType().equalsIgnoreCase("Many to Many")
|| field.getRelationshipType().equalsIgnoreCase("One to Many"))) {
// INDEX TO MONGO
entriesCollection.createIndex(Indexes.ascending(field.getName()),
new IndexOptions().background(true));
}
} else {
// INDEX TO MONGO
entriesCollection.createIndex(Indexes.ascending(field.getName()),
new IndexOptions().background(true));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean isValidDefaultValue(Field field, String companyId) {
try {
log.trace("Enter FieldService.isValidDefaultValue()");
String fieldName = field.getName();
MongoCollection<Document> collection = mongoTemplate.getCollection("modules_" + companyId);
String dataType = field.getDatatypes().getDisplay();
if (dataType.equals("Email")) {
String value = field.getDefaultValue();
if (!EmailValidator.getInstance().isValid(value)) {
throw new BadRequestException("EMAIL_INVALID");
}
} else if (dataType.equals("Number")) {
try {
int value = Integer.parseInt(field.getDefaultValue());
} catch (NumberFormatException e) {
e.printStackTrace();
throw new BadRequestException("INVALID_DEFAULT_FIELD");
}
} else if (dataType.equals("Percent")) {
Double value = Double.parseDouble(field.getDefaultValue());
} else if (dataType.equals("Currency")) {
Double value = Double.parseDouble(field.getDefaultValue());
if (BigDecimal.valueOf(value).scale() > 3) {
throw new BadRequestException("INVALID_NUMBER");
}
} else if (dataType.equals("Phone")) {
JSONObject phoneObject = new JSONObject(field.getDefaultValue());
if (!phoneObject.getString("DIAL_CODE").equalsIgnoreCase("")
&& !phoneObject.getString("PHONE_NUMBER").equalsIgnoreCase("")) {
String phoneNumberE164Format = phoneObject.getString("DIAL_CODE")
+ phoneObject.getString("PHONE_NUMBER");
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber phoneNumberProto = phoneUtil.parse(phoneNumberE164Format, null);
boolean isValid = phoneUtil.isValidNumber(phoneNumberProto);
if (!isValid) {
throw new BadRequestException("PHONE_NUMBER_LENGHT_INVALID");
}
} catch (NumberParseException e) {
throw new BadRequestException("PHONE_NUMBER_LENGHT_INVALID");
}
} else if (field.isRequired()) {
throw new BadRequestException("PHONE_NUMBER_LENGHT_INVALID");
}
} else if (dataType.equals("Checkbox")) {
Boolean value = Boolean.parseBoolean(field.getDefaultValue());
} else if (dataType.equals("URL")) {
String[] schemes = { "http", "https" }; // DEFAULT schemes = "http", "https", "ftp"
UrlValidator urlValidator = new UrlValidator(schemes);
String value = field.getDefaultValue();
if (!urlValidator.isValid(value)) {
throw new BadRequestException("INVALID_URL");
}
} else if (dataType.equals("Date/Time") || dataType.equals("Date") || dataType.equals("Time")) {
String value = field.getDefaultValue();
if (global.verifyDateTime(value) == null) {
throw new BadRequestException("INVALID_DATE_TIME");
}
} else if (dataType.equalsIgnoreCase("Picklist")) {
List<String> picklistValues = field.getPicklistValues();
String value = field.getDefaultValue();
boolean valueExists = false;
for (int i = 0; i < picklistValues.size(); i++) {
if (picklistValues.get(i).equals(value)) {
valueExists = true;
break;
}
}
if (!valueExists) {
throw new BadRequestException("VALUE_MISSING_IN_PICKLIST");
}
} else if (dataType.equals("Relationship")) { // RELATIONSHIP VALIDATION NOT REQUIRED AS OF 05/31/2019
String relationshipType = field.getRelationshipType();
String relationModuleId = field.getModule();
Document relationModule = collection.find(Filters.eq("_id", new ObjectId(relationModuleId))).first();
if (relationModule == null) {
throw new BadRequestException("INVALID_RELATIONSHIP");
}
String relationModuleName = relationModule.getString("NAME");
String relationshipField = field.getRelationshipField();
MongoCollection<Document> entriesCollection = mongoTemplate
.getCollection(relationModuleName + "_" + companyId);
if (relationshipType.equals("One to One") || relationshipType.equals("Many to One")) {
if (field.isRequired()) {
String value = field.getDefaultValue();
if (!new ObjectId().isValid(value)) {
throw new BadRequestException("INVALID_ENTRY_ID");
}
Document entry = entriesCollection.find(Filters.eq("_id", new ObjectId(value))).first();
if (entry == null) {
throw new BadRequestException("ENTRY_NOT_EXIST");
}
}
} else if (relationshipType.equals("One to Many")) {
if (field.getName() != null) {
throw new BadRequestException("ONE_TO_MANY_ERROR");
}
} else if (relationshipType.equals("Many to Many")) {
String value = field.getDefaultValue();
List<String> validValues = new ArrayList<String>();
if (!new ObjectId().isValid(value)) {
throw new BadRequestException("INVALID_ENTRY_ID");
}
Document entry = entriesCollection.find(Filters.eq("_id", new ObjectId(value))).first();
if (entry == null) {
throw new BadRequestException("ENTRIES_NOT_EXIST");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
throw new InternalError("INTERNAL_ERROR");
}
log.trace("Exit FieldService.isValidDefaultValue() companyId: " + companyId);
return true;
}
public void createFieldIfNotExists(String companyId, String moduleId, String fieldName, String displayLabel,
String displayDataType, String backendDatatype, boolean required, boolean visibility, boolean notEditable,
List<String> picklistValues) {
try {
MongoCollection<Document> modulesCollection = mongoTemplate.getCollection("modules_" + companyId);
Document moduleWithThisField = modulesCollection
.find(Filters.elemMatch("FIELDS", Filters.eq("NAME", fieldName))).first();
if (moduleWithThisField == null) {
Document module = modulesCollection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
List<Document> fields = (List<Document>) module.get("FIELDS");
int size = 0;
int totalDataTimeField = 0;
for (Document doc : fields) {
Document type = (Document) doc.get("DATA_TYPE");
if (type.getString("DISPLAY").equals("Date/Time") || type.getString("DISPLAY").equals("Date")
|| type.getString("DISPLAY").equals("Time")) {
totalDataTimeField++;
}
}
if (totalDataTimeField == 0 && !displayDataType.equals("Date/Time") && !displayDataType.equals("Date")
&& !displayDataType.equals("Time")) {
size = fields.size();
} else if (totalDataTimeField == 0 && (displayDataType.equals("Date/Time")
|| displayDataType.equals("Date") || !displayDataType.equals("Time"))) {
size = 84;
} else if (totalDataTimeField != 0 && !displayDataType.equals("Date/Time")
&& !displayDataType.equals("Date") && !displayDataType.equals("Time")) {
size = fields.size() - totalDataTimeField;
} else if (totalDataTimeField != 0 && (displayDataType.equals("Date/Time")
|| displayDataType.equals("Date") || displayDataType.equals("Time"))) {
size = 84 + totalDataTimeField;
}
Field fieldObject = new Field();
fieldObject.setName(fieldName);
fieldObject.setDisplayLabel(displayLabel);
DataType datatypeObject = new DataType();
datatypeObject.setBackend(backendDatatype);
datatypeObject.setDisplay(displayDataType);
fieldObject.setDatatypes(datatypeObject);
fieldObject.setRequired(required);
fieldObject.setVisibility(visibility);
fieldObject.setNotEditable(notEditable);
fieldObject.setFieldId(UUID.randomUUID().toString());
if ((displayDataType.equals("Picklist") || displayDataType.equals("Picklist (Multi-Select)"))
&& !picklistValues.isEmpty()) {
fieldObject.setPicklistValues(picklistValues);
}
String json = new ObjectMapper().writeValueAsString(fieldObject);
modulesCollection.findOneAndUpdate(Filters.eq("_id", new ObjectId(moduleId)),
Updates.addToSet("FIELDS", Document.parse(json)));
wrapper.putMappingForNewField(companyId, moduleId, fieldName, size + 1);
createIndexForTheField(companyId, moduleId, fieldObject);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// TODO: Add the code for validation and use it in Put Call for fields
private boolean checkValidInheritanceMap(Map<String, String> inheritanceMap, List<Field> currentModuleFields,
Field field) {
try {
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
| 39.122783 | 110 | 0.690623 |
59fd089ad36abd3f8514b4f0840f99222f95d8d9 | 648 | package hyweb.jo.model.event;
import hyweb.jo.JOProcObject;
import hyweb.jo.JOTestConst;
import hyweb.jo.util.JOTools;
import org.junit.Test;
/**
*
* @author william
*/
public class JOMEventTest {
@Test
public void test_query(){
String base = JOTestConst.base("prj.baphiq");
JOProcObject proc = new JOProcObject(base);
try{
proc.params().putAll(JOTools.loadString("{$metaId:posm_upload,$eventId:mail,license:1400000008}"));
IJOMEvent event = new JOMEventQuery();
event.execute(proc);
} finally{
proc.release();
}
}
}
| 24 | 112 | 0.600309 |
6c04c623f3a0514db243e1492b2aea95fcaa0b95 | 21,723 | /**
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 Marc de Verdelhan & respective authors (see AUTHORS)
*
* 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 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 NONINFRINGEMENT. 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 eu.verdelhan.ta4j;
import eu.verdelhan.ta4j.Order.OrderType;
import eu.verdelhan.ta4j.mocks.MockTick;
import eu.verdelhan.ta4j.mocks.MockTimeSeries;
import eu.verdelhan.ta4j.trading.rules.FixedRule;
import java.util.LinkedList;
import java.util.List;
import java.time.Duration;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class TimeSeriesTest {
private TimeSeries defaultSeries;
private TimeSeries subSeries;
private TimeSeries emptySeries;
private TimeSeries seriesForRun;
private Strategy strategy;
private List<Tick> ticks;
private String defaultName;
private ZonedDateTime date;
@Before
public void setUp() {
date = ZonedDateTime.now();
ticks = new LinkedList<>();
ticks.add(new MockTick(ZonedDateTime.of(2014, 6, 13, 0, 0, 0, 0, ZoneId.systemDefault()), 1d));
ticks.add(new MockTick(ZonedDateTime.of(2014, 6, 14, 0, 0, 0, 0, ZoneId.systemDefault()), 2d));
ticks.add(new MockTick(ZonedDateTime.of(2014, 6, 15, 0, 0, 0, 0, ZoneId.systemDefault()), 3d));
ticks.add(new MockTick(ZonedDateTime.of(2014, 6, 20, 0, 0, 0, 0, ZoneId.systemDefault()), 4d));
ticks.add(new MockTick(ZonedDateTime.of(2014, 6, 25, 0, 0, 0, 0, ZoneId.systemDefault()), 5d));
ticks.add(new MockTick(ZonedDateTime.of(2014, 6, 30, 0, 0, 0, 0, ZoneId.systemDefault()), 6d));
defaultName = "Series Name";
defaultSeries = new TimeSeries(defaultName, ticks);
subSeries = defaultSeries.subseries(2, 4);
emptySeries = new TimeSeries();
final DateTimeFormatter dtf = DateTimeFormatter.ISO_ZONED_DATE_TIME;
seriesForRun = new MockTimeSeries(
new double[] { 1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d, 9d },
new ZonedDateTime[] {
ZonedDateTime.parse("2013-01-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2013-08-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2013-10-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2013-12-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2014-02-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2015-01-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2015-08-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2015-10-01T00:00:00-05:00", dtf),
ZonedDateTime.parse("2015-12-01T00:00:00-05:00", dtf)
});
strategy = new Strategy(new FixedRule(0, 2, 3, 6), new FixedRule(1, 4, 7, 8));
strategy.setUnstablePeriod(2); // Strategy would need a real test class
}
@Test
public void getEndGetBeginGetTickCount() {
// Original series
assertEquals(0, defaultSeries.getBegin());
assertEquals(ticks.size() - 1, defaultSeries.getEnd());
assertEquals(ticks.size(), defaultSeries.getTickCount());
// Sub-series
assertEquals(2, subSeries.getBegin());
assertEquals(4, subSeries.getEnd());
assertEquals(3, subSeries.getTickCount());
// Empty series
assertEquals(-1, emptySeries.getBegin());
assertEquals(-1, emptySeries.getEnd());
assertEquals(0, emptySeries.getTickCount());
}
@Test
public void getSeriesPeriodDescription() {
// Original series
assertTrue(defaultSeries.getSeriesPeriodDescription().endsWith(ticks.get(defaultSeries.getEnd()).getEndTime().format(DateTimeFormatter.ISO_DATE_TIME)));
assertTrue(defaultSeries.getSeriesPeriodDescription().startsWith(ticks.get(defaultSeries.getBegin()).getEndTime().format(DateTimeFormatter.ISO_DATE_TIME)));
// Sub-series
assertTrue(subSeries.getSeriesPeriodDescription().endsWith(ticks.get(subSeries.getEnd()).getEndTime().format(DateTimeFormatter.ISO_DATE_TIME)));
assertTrue(subSeries.getSeriesPeriodDescription().startsWith(ticks.get(subSeries.getBegin()).getEndTime().format(DateTimeFormatter.ISO_DATE_TIME)));
// Empty series
assertEquals("", emptySeries.getSeriesPeriodDescription());
}
@Test
public void getName() {
assertEquals(defaultName, defaultSeries.getName());
assertEquals(defaultName, subSeries.getName());
}
@Test
public void getTickWithRemovedIndexOnMovingSeriesShouldReturnFirstRemainingTick() {
Tick tick = defaultSeries.getTick(4);
defaultSeries.setMaximumTickCount(2);
assertSame(tick, defaultSeries.getTick(0));
assertSame(tick, defaultSeries.getTick(1));
assertSame(tick, defaultSeries.getTick(2));
assertSame(tick, defaultSeries.getTick(3));
assertSame(tick, defaultSeries.getTick(4));
assertNotSame(tick, defaultSeries.getTick(5));
}
@Test(expected = IndexOutOfBoundsException.class)
public void getTickOnMovingAndEmptySeriesShouldThrowException() {
defaultSeries.setMaximumTickCount(2);
ticks.clear(); // Should not be used like this
defaultSeries.getTick(1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getTickWithNegativeIndexShouldThrowException() {
defaultSeries.getTick(-1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void getTickWithIndexGreaterThanTickCountShouldThrowException() {
defaultSeries.getTick(10);
}
@Test
public void getTickOnMovingSeries() {
Tick tick = defaultSeries.getTick(4);
defaultSeries.setMaximumTickCount(2);
assertEquals(tick, defaultSeries.getTick(4));
}
@Test(expected = IllegalStateException.class)
public void maximumTickCountOnSubserieShouldThrowException() {
subSeries.setMaximumTickCount(10);
}
@Test(expected = IllegalArgumentException.class)
public void negativeMaximumTickCountShouldThrowException() {
defaultSeries.setMaximumTickCount(-1);
}
@Test
public void setMaximumTickCount() {
// Before
assertEquals(0, defaultSeries.getBegin());
assertEquals(ticks.size() - 1, defaultSeries.getEnd());
assertEquals(ticks.size(), defaultSeries.getTickCount());
defaultSeries.setMaximumTickCount(3);
// After
assertEquals(0, defaultSeries.getBegin());
assertEquals(5, defaultSeries.getEnd());
assertEquals(3, defaultSeries.getTickCount());
}
@Test(expected = IllegalArgumentException.class)
public void addNullTickShouldThrowException() {
defaultSeries.addTick(null);
}
@Test(expected = IllegalArgumentException.class)
public void addTickWithEndTimePriorToSeriesEndTimeShouldThrowException() {
defaultSeries.addTick(new MockTick(ZonedDateTime.of(2000, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault()), 99d));
}
@Test
public void addTick() {
defaultSeries = new TimeSeries();
Tick firstTick = new MockTick(ZonedDateTime.of(2014, 6, 13, 0, 0, 0, 0, ZoneId.systemDefault()), 1d);
Tick secondTick = new MockTick(ZonedDateTime.of(2014, 6, 14, 0, 0, 0, 0, ZoneId.systemDefault()), 2d);
assertEquals(0, defaultSeries.getTickCount());
assertEquals(-1, defaultSeries.getBegin());
assertEquals(-1, defaultSeries.getEnd());
defaultSeries.addTick(firstTick);
assertEquals(1, defaultSeries.getTickCount());
assertEquals(0, defaultSeries.getBegin());
assertEquals(0, defaultSeries.getEnd());
defaultSeries.addTick(secondTick);
assertEquals(2, defaultSeries.getTickCount());
assertEquals(0, defaultSeries.getBegin());
assertEquals(1, defaultSeries.getEnd());
}
@Test
public void subseriesWithIndexes() {
TimeSeries subSeries2 = defaultSeries.subseries(2, 5);
assertEquals(defaultSeries.getName(), subSeries2.getName());
assertEquals(2, subSeries2.getBegin());
assertNotEquals(defaultSeries.getBegin(), subSeries2.getBegin());
assertEquals(5, subSeries2.getEnd());
assertEquals(defaultSeries.getEnd(), subSeries2.getEnd());
assertEquals(4, subSeries2.getTickCount());
}
@Test(expected = IllegalStateException.class)
public void subseriesOnSeriesWithMaximumTickCountShouldThrowException() {
defaultSeries.setMaximumTickCount(3);
defaultSeries.subseries(0, 1);
}
@Test(expected = IllegalArgumentException.class)
public void subseriesWithInvalidIndexesShouldThrowException() {
defaultSeries.subseries(4, 2);
}
@Test
public void subseriesWithDuration() {
TimeSeries subSeries2 = defaultSeries.subseries(1, Duration.ofDays(14));
assertEquals(defaultSeries.getName(), subSeries2.getName());
assertEquals(1, subSeries2.getBegin());
assertNotEquals(defaultSeries.getBegin(), subSeries2.getBegin());
assertEquals(4, subSeries2.getEnd());
assertNotEquals(defaultSeries.getEnd(), subSeries2.getEnd());
assertEquals(4, subSeries2.getTickCount());
}
@Test
public void subseriesWithPeriod() {
TimeSeries subSeries2 = defaultSeries.subseries(1, Period.ofDays(14));
assertEquals(defaultSeries.getName(), subSeries2.getName());
assertEquals(1, subSeries2.getBegin());
assertNotEquals(defaultSeries.getBegin(), subSeries2.getBegin());
assertEquals(4, subSeries2.getEnd());
assertNotEquals(defaultSeries.getEnd(), subSeries2.getEnd());
assertEquals(4, subSeries2.getTickCount());
}
@Test
public void splitEvery3Ticks() {
TimeSeries series = new MockTimeSeries(
date.withYear(2010),
date.withYear(2011),
date.withYear(2012),
date.withYear(2015),
date.withYear(2016),
date.withYear(2017),
date.withYear(2018),
date.withYear(2019));
List<TimeSeries> subseries = series.split(3);
assertEquals(3, subseries.size());
assertEquals(0, subseries.get(0).getBegin());
assertEquals(2, subseries.get(0).getEnd());
assertEquals(3, subseries.get(1).getBegin());
assertEquals(5, subseries.get(1).getEnd());
assertEquals(6, subseries.get(2).getBegin());
assertEquals(7, subseries.get(2).getEnd());
}
@Test
public void splitByYearForTwoYearsSubseries() {
TimeSeries series = new MockTimeSeries(
date.withYear(2010),
date.withYear(2011),
date.withYear(2012),
date.withYear(2015),
date.withYear(2016));
List<TimeSeries> subseries = series.split(Duration.ofDays(365), Duration.ofDays(730));
assertEquals(5, subseries.size());
assertEquals(0, subseries.get(0).getBegin());
assertEquals(1, subseries.get(0).getEnd());
assertEquals(1, subseries.get(1).getBegin());
assertEquals(2, subseries.get(1).getEnd());
assertEquals(2, subseries.get(2).getBegin());
assertEquals(2, subseries.get(2).getEnd());
assertEquals(4, subseries.get(4).getBegin());
assertEquals(4, subseries.get(4).getEnd());
}
@Test
public void splitByMonthForOneWeekSubseries() {
TimeSeries series = new MockTimeSeries(
date.withMonth(04),
date.withMonth(05),
date.withMonth(07));
List<TimeSeries> subseries = series.split(Duration.ofDays(30), Duration.ofDays(7));
assertEquals(3, subseries.size());
assertEquals(0, subseries.get(0).getBegin());
assertEquals(0, subseries.get(0).getEnd());
assertEquals(1, subseries.get(1).getBegin());
assertEquals(1, subseries.get(1).getEnd());
assertEquals(2, subseries.get(2).getBegin());
assertEquals(2, subseries.get(2).getEnd());
}
@Test
public void splitByHour() {
ZonedDateTime time = ZonedDateTime.now().withHour(10).withMinute(0).withSecond(0);
TimeSeries series = new MockTimeSeries(
time,
time.plusMinutes(1),
time.plusMinutes(2),
time.plusMinutes(10),
time.plusMinutes(15),
time.plusMinutes(25),
time.plusHours(1),
time.plusHours(5),
time.plusHours(10).plusMinutes(10),
time.plusHours(10).plusMinutes(20),
time.plusHours(10).plusMinutes(30));
List<TimeSeries> subseries = series.split(Duration.ofHours(1));
assertEquals(4, subseries.size());
assertEquals(0, subseries.get(0).getBegin());
assertEquals(5, subseries.get(0).getEnd());
assertEquals(6, subseries.get(1).getBegin());
assertEquals(6, subseries.get(1).getEnd());
assertEquals(7, subseries.get(2).getBegin());
assertEquals(7, subseries.get(2).getEnd());
assertEquals(8, subseries.get(3).getBegin());
assertEquals(10, subseries.get(3).getEnd());
}
@Test
public void splitByDay() {
ZonedDateTime time = ZonedDateTime.now().withHour(10).withMinute(0).withSecond(0);
TimeSeries series = new MockTimeSeries(
time,
time.plusHours(1),
time.plusHours(2),
time.plusHours(10),
time.plusHours(15),
time.plusHours(20),
time.plusDays(1),
time.plusDays(5),
time.plusDays(10).plusHours(5),
time.plusDays(10).plusHours(10),
time.plusDays(10).plusHours(20));
List<TimeSeries> subseries = series.split(Period.ofDays(1));
assertEquals(4, subseries.size());
assertEquals(0, subseries.get(0).getBegin());
assertEquals(5, subseries.get(0).getEnd());
assertEquals(6, subseries.get(1).getBegin());
assertEquals(6, subseries.get(1).getEnd());
assertEquals(7, subseries.get(2).getBegin());
assertEquals(7, subseries.get(2).getEnd());
assertEquals(8, subseries.get(3).getBegin());
assertEquals(10, subseries.get(3).getEnd());
}
@Test
public void runOnWholeSeries() {
TimeSeries series = new MockTimeSeries(20d, 40d, 60d, 10d, 30d, 50d, 0d, 20d, 40d);
List<Trade> allTrades = series.run(strategy).getTrades();
assertEquals(2, allTrades.size());
}
@Test
public void runOnWholeSeriesWithAmount() {
TimeSeries series = new MockTimeSeries(20d, 40d, 60d, 10d, 30d, 50d, 0d, 20d, 40d);
List<Trade> allTrades = series.run(strategy,OrderType.BUY, Decimal.HUNDRED).getTrades();
assertEquals(2, allTrades.size());
assertEquals(Decimal.HUNDRED, allTrades.get(0).getEntry().getAmount());
assertEquals(Decimal.HUNDRED, allTrades.get(1).getEntry().getAmount());
}
@Test
public void runOnSlice() {
List<TimeSeries> subseries = seriesForRun.split(Duration.ofDays(365 * 2000));
TimeSeries slice = subseries.get(0);
List<Trade> trades = slice.run(strategy).getTrades();
assertEquals(2, trades.size());
assertEquals(Order.buyAt(2, slice.getTick(2).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.sellAt(4, slice.getTick(4).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
assertEquals(Order.buyAt(6, slice.getTick(6).getClosePrice(), Decimal.NaN), trades.get(1).getEntry());
assertEquals(Order.sellAt(7, slice.getTick(7).getClosePrice(), Decimal.NaN), trades.get(1).getExit());
}
@Test
public void runWithOpenEntryBuyLeft() {
List<TimeSeries> subseries = seriesForRun.split(Duration.ofDays(365));
TimeSeries slice = subseries.get(0);
Strategy aStrategy = new Strategy(new FixedRule(1), new FixedRule(3));
List<Trade> trades = slice.run(aStrategy).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.buyAt(1, slice.getTick(1).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.sellAt(3, slice.getTick(3).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
}
@Test
public void runWithOpenEntrySellLeft() {
List<TimeSeries> subseries = seriesForRun.split(Duration.ofDays(365));
TimeSeries slice = subseries.get(0);
Strategy aStrategy = new Strategy(new FixedRule(1), new FixedRule(3));
List<Trade> trades = slice.run(aStrategy, OrderType.SELL).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.sellAt(1, slice.getTick(1).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.buyAt(3, slice.getTick(3).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
}
@Test
public void runSplitted() {
List<TimeSeries> subseries = seriesForRun.split(Duration.ofDays(365));
TimeSeries slice0 = subseries.get(0);
TimeSeries slice1 = subseries.get(1);
TimeSeries slice2 = subseries.get(2);
List<Trade> trades = slice0.run(strategy).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.buyAt(2, slice0.getTick(2).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.sellAt(4, slice0.getTick(4).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
trades = slice1.run(strategy).getTrades();
assertTrue(trades.isEmpty());
trades = slice2.run(strategy).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.buyAt(6, slice2.getTick(6).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.sellAt(7, slice2.getTick(7).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
}
@Test
public void splitted(){
ZonedDateTime dateTime = ZonedDateTime.of(2000, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
TimeSeries series = new MockTimeSeries(new double[]{1d, 2d, 3d, 4d, 5d, 6d, 7d, 8d, 9d, 10d},
new ZonedDateTime[]{dateTime.withYear(2000), dateTime.withYear(2000), dateTime.withYear(2001), dateTime.withYear(2001), dateTime.withYear(2002),
dateTime.withYear(2002), dateTime.withYear(2002), dateTime.withYear(2003), dateTime.withYear(2004), dateTime.withYear(2005)});
Strategy aStrategy = new Strategy(new FixedRule(0, 3, 5, 7), new FixedRule(2, 4, 6, 9));
List<TimeSeries> subseries = series.split(Period.ofYears(1));
TimeSeries slice0 = subseries.get(0);
TimeSeries slice1 = subseries.get(1);
TimeSeries slice2 = subseries.get(2);
TimeSeries slice3 = subseries.get(3);
TimeSeries slice4 = subseries.get(4);
TimeSeries slice5 = subseries.get(5);
List<Trade> trades = slice0.run(aStrategy).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.buyAt(0, slice0.getTick(0).getClosePrice(), Decimal.NaN),trades.get(0).getEntry());
assertEquals(Order.sellAt(2, slice0.getTick(2).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
trades = slice1.run(aStrategy).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.buyAt(3, slice1.getTick(3).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.sellAt(4, slice1.getTick(4).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
trades = slice2.run(aStrategy).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.buyAt(5, slice2.getTick(5).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.sellAt(6, slice2.getTick(6).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
trades = slice3.run(aStrategy).getTrades();
assertEquals(1, trades.size());
assertEquals(Order.buyAt(7, slice3.getTick(7).getClosePrice(), Decimal.NaN), trades.get(0).getEntry());
assertEquals(Order.sellAt(9, slice3.getTick(9).getClosePrice(), Decimal.NaN), trades.get(0).getExit());
trades = slice4.run(aStrategy).getTrades();
assertTrue(trades.isEmpty());
trades = slice5.run(aStrategy).getTrades();
assertTrue(trades.isEmpty());
}
}
| 40.909605 | 164 | 0.651706 |
b0b9c1a90c2bf15c1b807325e0e0249d3762d5bf | 508 | package com.xlx.majiang.system.service;
import com.xlx.majiang.system.entity.Account;
/**
* 账户注册
*
* @author xielx at 2020/12/20 20:44
*/
public interface AccountService {
/**
* 注册账户
* @param account Account
* @return
*/
int registerAccount(Account account);
/**
* 修改密码
* @param password 新密码
* @param email
*/
void changeAccountPwdByEmail(String password,String email);
Account doLogin(String username,String password);
}
| 17.517241 | 63 | 0.61811 |
391d7ec5fa0c47438456dc789bd886b84076b6d6 | 323 | package eapli.base.app.servicosrh.console.presentation.catalogo;
import eapli.framework.actions.Action;
/**
* Menu action for adding a new catalogo to the application.
*/
public class AddCatalogoAction implements Action {
@Override
public boolean execute() {
return new AddCatalogoUI().show();
}
}
| 21.533333 | 64 | 0.724458 |
26f6a367472332b0b7a2e8c839cbe9017ce21e28 | 24,278 | /*
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package com.google.cloud.healthcare.fdamystudies.controller.tests;
import static com.google.cloud.healthcare.fdamystudies.common.EnrollAuditEvent.ENROLLMENT_TOKEN_FOUND_INVALID;
import static com.google.cloud.healthcare.fdamystudies.common.EnrollAuditEvent.PARTICIPANT_ID_RECEIVED;
import static com.google.cloud.healthcare.fdamystudies.common.EnrollAuditEvent.USER_FOUND_ELIGIBLE_FOR_STUDY;
import static com.google.cloud.healthcare.fdamystudies.common.EnrollAuditEvent.USER_FOUND_INELIGIBLE_FOR_STUDY;
import static com.google.cloud.healthcare.fdamystudies.common.ErrorCode.TOKEN_EXPIRED;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.cloud.healthcare.fdamystudies.beans.AuditLogEventRequest;
import com.google.cloud.healthcare.fdamystudies.beans.EnrollmentBean;
import com.google.cloud.healthcare.fdamystudies.common.ApiEndpoint;
import com.google.cloud.healthcare.fdamystudies.common.BaseMockIT;
import com.google.cloud.healthcare.fdamystudies.common.OnboardingStatus;
import com.google.cloud.healthcare.fdamystudies.controller.EnrollmentTokenController;
import com.google.cloud.healthcare.fdamystudies.model.ParticipantRegistrySiteEntity;
import com.google.cloud.healthcare.fdamystudies.repository.ParticipantRegistrySiteRepository;
import com.google.cloud.healthcare.fdamystudies.service.EnrollmentTokenService;
import com.google.cloud.healthcare.fdamystudies.testutils.Constants;
import com.google.cloud.healthcare.fdamystudies.testutils.TestUtils;
import com.google.cloud.healthcare.fdamystudies.util.ErrorResponseUtil.ErrorCodes;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.collections4.map.HashedMap;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.test.annotation.DirtiesContext;
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class EnrollmentTokenControllerTest extends BaseMockIT {
@Autowired private EnrollmentTokenController controller;
@Autowired private EnrollmentTokenService enrollmentTokenService;
@Autowired private ObjectMapper objectMapper;
@Autowired private ParticipantRegistrySiteRepository participantRegistrySiteRepository;
protected ObjectMapper getObjectMapper() {
return objectMapper;
}
@Test
public void contextLoads() {
assertNotNull(controller);
assertNotNull(mockMvc);
assertNotNull(enrollmentTokenService);
}
@Test
public void validateEnrollmentTokenSuccess() throws Exception {
Optional<ParticipantRegistrySiteEntity> optParticipantRegistrySite =
participantRegistrySiteRepository.findByEnrollmentToken(Constants.TOKEN);
ParticipantRegistrySiteEntity participantRegistrySite = optParticipantRegistrySite.get();
participantRegistrySite.setEnrollmentTokenExpiry(
new Timestamp(Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli()));
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
String requestJson = getEnrollmentJson(Constants.TOKEN, Constants.STUDYOF_HEALTH);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isOk());
verifyTokenIntrospectRequest();
}
@Test
public void validateEnrollmentTokenBadRequests() throws Exception {
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
verifyTokenIntrospectRequest();
// without study id
String requestJson = getEnrollmentJson(Constants.TOKEN, null);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
verifyTokenIntrospectRequest(2);
// without token
requestJson = getEnrollmentJson(null, Constants.STUDYOF_HEALTH_CLOSE);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
verifyTokenIntrospectRequest(3);
// unknown token id
requestJson = getEnrollmentJson(Constants.UNKOWN_TOKEN, Constants.STUDYOF_HEALTH);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
AuditLogEventRequest auditRequest = new AuditLogEventRequest();
auditRequest.setUserId(Constants.VALID_USER_ID);
Map<String, AuditLogEventRequest> auditEventMap = new HashedMap<>();
auditEventMap.put(ENROLLMENT_TOKEN_FOUND_INVALID.getEventCode(), auditRequest);
verifyAuditEventCall(auditEventMap, ENROLLMENT_TOKEN_FOUND_INVALID);
verifyTokenIntrospectRequest(4);
}
@Test
public void validateEnrollmentTokenForbidden() throws Exception {
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
// study id not exists
String requestJson = getEnrollmentJson(Constants.TOKEN, Constants.STUDYID_NOT_EXIST);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isForbidden());
verifyTokenIntrospectRequest();
// token already use
requestJson = getEnrollmentJson(Constants.TOKEN_ALREADY_USED, Constants.STUDYOF_HEALTH_1);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isForbidden());
verifyTokenIntrospectRequest(2);
}
@Test
public void validateEnrollmentTokenBadRequest() throws Exception {
// without userId header
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add("Authorization", VALID_BEARER_TOKEN);
String requestJson = getEnrollmentJson(Constants.TOKEN, Constants.STUDYOF_HEALTH);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
verifyTokenIntrospectRequest();
}
@Test
public void validateEnrollmentForExpiredToken() throws Exception {
Optional<ParticipantRegistrySiteEntity> optParticipantRegistrySite =
participantRegistrySiteRepository.findByEnrollmentToken(Constants.TOKEN);
ParticipantRegistrySiteEntity participantRegistrySite = optParticipantRegistrySite.get();
participantRegistrySite.setEnrollmentTokenExpiry(
new Timestamp(Instant.now().minus(1, ChronoUnit.DAYS).toEpochMilli()));
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
String requestJson = getEnrollmentJson(Constants.TOKEN, Constants.STUDYOF_HEALTH);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.VALIDATE_ENROLLMENT_TOKEN_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isGone())
.andExpect(jsonPath("$.error_description", is(TOKEN_EXPIRED.getDescription())));
verifyTokenIntrospectRequest();
}
@Test
public void enrollParticipantForExpiredToken() throws Exception {
Optional<ParticipantRegistrySiteEntity> optParticipantRegistrySite =
participantRegistrySiteRepository.findByEnrollmentToken(Constants.TOKEN_NEW);
ParticipantRegistrySiteEntity participantRegistrySite = optParticipantRegistrySite.get();
participantRegistrySite.setEnrollmentTokenExpiry(
new Timestamp(Instant.now().minus(1, ChronoUnit.DAYS).toEpochMilli()));
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
// study type close
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH_CLOSE);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isGone())
.andExpect(jsonPath("$.error_description", is(TOKEN_EXPIRED.getDescription())));
verifyTokenIntrospectRequest();
}
@Test
public void enrollParticipantSuccessStudyTypeClose() throws Exception {
Optional<ParticipantRegistrySiteEntity> optParticipantRegistrySite =
participantRegistrySiteRepository.findByEnrollmentToken(Constants.TOKEN_NEW);
ParticipantRegistrySiteEntity participantRegistrySite = optParticipantRegistrySite.get();
participantRegistrySite.setEnrollmentTokenExpiry(
new Timestamp(Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli()));
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
// study type close
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH_CLOSE);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isOk());
AuditLogEventRequest auditRequest = new AuditLogEventRequest();
auditRequest.setStudyId(Constants.STUDYOF_HEALTH_CLOSE);
auditRequest.setUserId(Constants.VALID_USER_ID);
auditRequest.setParticipantId("i4ts7dsf50c6me154sfsdfdv");
Map<String, AuditLogEventRequest> auditEventMap = new HashedMap<>();
auditEventMap.put(PARTICIPANT_ID_RECEIVED.getEventCode(), auditRequest);
verifyAuditEventCall(auditEventMap, PARTICIPANT_ID_RECEIVED);
verifyTokenIntrospectRequest();
}
@Test
public void shouldNotAllowUserForEnrollment() throws Exception {
List<ParticipantRegistrySiteEntity> participantRegistrySiteList =
participantRegistrySiteRepository.findByStudyIdAndEmail("3", "cdash936@gmail.com");
ParticipantRegistrySiteEntity participantRegistrySite = participantRegistrySiteList.get(0);
// Set onboarding status to Disabled (D)
participantRegistrySite.setOnboardingStatus("D");
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
// study type close
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH_CLOSE);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isGone())
.andExpect(jsonPath("$.error_description", is(TOKEN_EXPIRED.getDescription())));
verifyTokenIntrospectRequest();
}
@Test
public void shouldReturnUnknownTokenForEnrollment() throws Exception {
List<ParticipantRegistrySiteEntity> participantRegistrySiteList =
participantRegistrySiteRepository.findByStudyIdAndEmail("3", "cdash936@gmail.com");
ParticipantRegistrySiteEntity participantRegistrySite = participantRegistrySiteList.get(0);
// Set onboarding status to New (N)
participantRegistrySite.setOnboardingStatus(OnboardingStatus.NEW.getCode());
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
// study type close
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH_CLOSE);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.message", is(ErrorCodes.UNKNOWN_TOKEN.getValue())));
verifyTokenIntrospectRequest();
}
@Test
public void enrollParticipantSuccessForCaseInsensitiveToken() throws Exception {
Optional<ParticipantRegistrySiteEntity> optParticipantRegistrySite =
participantRegistrySiteRepository.findByEnrollmentToken(Constants.TOKEN_NEW);
ParticipantRegistrySiteEntity participantRegistrySite = optParticipantRegistrySite.get();
participantRegistrySite.setEnrollmentTokenExpiry(
new Timestamp(Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli()));
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
// study type close
String requestJson = getEnrollmentJson("6DL0pOqf", Constants.STUDYOF_HEALTH_CLOSE);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isOk());
AuditLogEventRequest auditRequest = new AuditLogEventRequest();
auditRequest.setStudyId(Constants.STUDYOF_HEALTH_CLOSE);
auditRequest.setUserId(Constants.VALID_USER_ID);
auditRequest.setParticipantId("i4ts7dsf50c6me154sfsdfdv");
Map<String, AuditLogEventRequest> auditEventMap = new HashedMap<>();
auditEventMap.put(PARTICIPANT_ID_RECEIVED.getEventCode(), auditRequest);
verifyAuditEventCall(auditEventMap, PARTICIPANT_ID_RECEIVED);
verifyTokenIntrospectRequest();
}
@Test
public void shouldFailEnrollmentForExistingParticipant() throws Exception {
Optional<ParticipantRegistrySiteEntity> optParticipantRegistrySite =
participantRegistrySiteRepository.findByEnrollmentToken(Constants.TOKEN_NEW);
ParticipantRegistrySiteEntity participantRegistrySite = optParticipantRegistrySite.get();
participantRegistrySite.setEnrollmentTokenExpiry(
new Timestamp(Instant.now().plus(1, ChronoUnit.DAYS).toEpochMilli()));
participantRegistrySiteRepository.saveAndFlush(participantRegistrySite);
// study type close
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH_CLOSE);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isOk());
AuditLogEventRequest auditRequest = new AuditLogEventRequest();
auditRequest.setStudyId(Constants.STUDYOF_HEALTH_CLOSE);
auditRequest.setUserId(Constants.VALID_USER_ID);
auditRequest.setParticipantId("i4ts7dsf50c6me154sfsdfdv");
Map<String, AuditLogEventRequest> auditEventMap = new HashedMap<>();
auditEventMap.put(PARTICIPANT_ID_RECEIVED.getEventCode(), auditRequest);
verifyAuditEventCall(auditEventMap, PARTICIPANT_ID_RECEIVED);
verifyTokenIntrospectRequest();
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isForbidden())
.andExpect(jsonPath("$.message", is("Token already in use")));
verifyTokenIntrospectRequest(2);
}
@Test
public void enrollParticipantSuccessStudyTypeOpen() throws Exception {
// study type open
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isOk());
AuditLogEventRequest auditRequest = new AuditLogEventRequest();
auditRequest.setStudyId(Constants.STUDYOF_HEALTH);
auditRequest.setUserId(Constants.VALID_USER_ID);
auditRequest.setParticipantId("i4ts7dsf50c6me154sfsdfdv");
Map<String, AuditLogEventRequest> auditEventMap = new HashedMap<>();
auditEventMap.put(USER_FOUND_ELIGIBLE_FOR_STUDY.getEventCode(), auditRequest);
verifyAuditEventCall(auditEventMap, USER_FOUND_ELIGIBLE_FOR_STUDY);
verifyTokenIntrospectRequest();
}
@Test
public void enrollParticipantSuccessNewUser() throws Exception {
// new user id
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH);
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isOk());
verifyTokenIntrospectRequest();
}
@Test
public void enrollParticipantBadRequests() throws Exception {
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
// without study id
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, null);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
AuditLogEventRequest auditRequest = new AuditLogEventRequest();
auditRequest.setUserId(Constants.VALID_USER_ID);
Map<String, AuditLogEventRequest> auditEventMap = new HashedMap<>();
auditEventMap.put(USER_FOUND_INELIGIBLE_FOR_STUDY.getEventCode(), auditRequest);
verifyAuditEventCall(auditEventMap, USER_FOUND_INELIGIBLE_FOR_STUDY);
verifyTokenIntrospectRequest();
// without token
requestJson = getEnrollmentJson(null, Constants.STUDYOF_HEALTH_CLOSE);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
verifyTokenIntrospectRequest(2);
// unknown token id
requestJson = getEnrollmentJson(Constants.UNKOWN_TOKEN, Constants.STUDYOF_HEALTH_CLOSE);
// Reset Audit Event calls
clearAuditRequests();
auditEventMap.clear();
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
verifyTokenIntrospectRequest(3);
}
@Test
public void enrollParticipantBadRequest() throws Exception {
// without userId header
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add("Authorization", VALID_BEARER_TOKEN);
String requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYOF_HEALTH);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isBadRequest());
verifyTokenIntrospectRequest();
}
@Test
public void enrollParticipantForbidden() throws Exception {
HttpHeaders headers = TestUtils.getCommonHeaders();
headers.add(Constants.USER_ID_HEADER, Constants.VALID_USER_ID);
headers.add("Authorization", VALID_BEARER_TOKEN);
// token already use
String requestJson = getEnrollmentJson(Constants.TOKEN, Constants.STUDYID_NOT_EXIST);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isForbidden());
verifyTokenIntrospectRequest();
// study id not exists
requestJson = getEnrollmentJson(Constants.TOKEN_NEW, Constants.STUDYID_NOT_EXIST);
mockMvc
.perform(
post(ApiEndpoint.ENROLL_PATH.getPath())
.headers(headers)
.content(requestJson)
.contextPath(getContextPath()))
.andDo(print())
.andExpect(status().isForbidden());
verifyTokenIntrospectRequest(2);
}
private String getEnrollmentJson(String tokenId, String studyId) throws JsonProcessingException {
EnrollmentBean enrollmentBean = new EnrollmentBean(tokenId, studyId);
return getObjectMapper().writeValueAsString(enrollmentBean);
}
}
| 38.35387 | 111 | 0.725801 |
7f8309dcdcfabe9352d09055b12f8726819fcc8a | 11,458 | /*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.archive.crawler.prefetch;
import static org.archive.modules.SchedulingConstants.HIGH;
import static org.archive.modules.SchedulingConstants.MEDIUM;
import org.apache.commons.lang.StringUtils;
import org.archive.crawler.framework.Scoper;
import org.archive.crawler.frontier.CostAssignmentPolicy;
import org.archive.crawler.frontier.QueueAssignmentPolicy;
import org.archive.crawler.frontier.SurtAuthorityQueueAssignmentPolicy;
import org.archive.crawler.frontier.UnitCostAssignmentPolicy;
import org.archive.crawler.frontier.precedence.CostUriPrecedencePolicy;
import org.archive.crawler.frontier.precedence.UriPrecedencePolicy;
import org.archive.modules.CrawlURI;
import org.archive.modules.SchedulingConstants;
import org.archive.modules.canonicalize.RulesCanonicalizationPolicy;
import org.archive.modules.canonicalize.UriCanonicalizationPolicy;
import org.archive.net.UURI;
import org.archive.spring.KeyedProperties;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Processor to preload URI with as much precalculated policy-based
* info as possible before it reaches frontier criticial sections.
*
* Frontiers also maintain a direct reference to this class, in case
* they need to perform remedial preparation for URIs that do not
* pass through this processor on the CandidateChain.
*
* @contributor gojomo
*/
public class FrontierPreparer extends Scoper {
@SuppressWarnings("unused")
private static final long serialVersionUID = 1L;
/**
* Number of hops (of any sort) from a seed up to which a URI has higher
* priority scheduling than any remaining seed. For example, if set to 1
* items one hop (link, embed, redirect, etc.) away from a seed will be
* scheduled with HIGH priority. If set to -1, no preferencing will occur,
* and a breadth-first search with seeds processed before discovered links
* will proceed. If set to zero, a purely depth-first search will proceed,
* with all discovered links processed before remaining seeds. Seed
* redirects are treated as one hop from a seed.
*/
{
setPreferenceDepthHops(-1); // no limit
}
public int getPreferenceDepthHops() {
return (Integer) kp.get("preferenceDepthHops");
}
public void setPreferenceDepthHops(int depth) {
kp.put("preferenceDepthHops",depth);
}
/** number of hops of embeds (ERX) to bump to front of host queue */
{
setPreferenceEmbedHops(1);
}
public int getPreferenceEmbedHops() {
return (Integer) kp.get("preferenceEmbedHops");
}
public void setPreferenceEmbedHops(int pref) {
kp.put("preferenceEmbedHops",pref);
}
/**
* Ordered list of url canonicalization rules. Rules are applied in the
* order listed from top to bottom.
*/
{
setCanonicalizationPolicy(new RulesCanonicalizationPolicy());
}
public UriCanonicalizationPolicy getCanonicalizationPolicy() {
return (UriCanonicalizationPolicy) kp.get("uriCanonicalizationRules");
}
@Autowired(required=false)
public void setCanonicalizationPolicy(UriCanonicalizationPolicy policy) {
kp.put("uriCanonicalizationRules",policy);
}
/**
* Defines how to assign URIs to queues. Can assign by host, by ip,
* by SURT-ordered authority, by SURT-ordered authority truncated to
* a topmost-assignable domain, and into one of a fixed set of buckets
* (1k).
*/
{
setQueueAssignmentPolicy(new SurtAuthorityQueueAssignmentPolicy());
}
public QueueAssignmentPolicy getQueueAssignmentPolicy() {
return (QueueAssignmentPolicy) kp.get("queueAssignmentPolicy");
}
@Autowired(required=false)
public void setQueueAssignmentPolicy(QueueAssignmentPolicy policy) {
kp.put("queueAssignmentPolicy",policy);
}
/** URI precedence assignment policy to use. */
{
setUriPrecedencePolicy(new CostUriPrecedencePolicy());
}
public UriPrecedencePolicy getUriPrecedencePolicy() {
return (UriPrecedencePolicy) kp.get("uriPrecedencePolicy");
}
@Autowired(required=false)
public void setUriPrecedencePolicy(UriPrecedencePolicy policy) {
kp.put("uriPrecedencePolicy",policy);
}
/** cost assignment policy to use. */
{
setCostAssignmentPolicy(new UnitCostAssignmentPolicy());
}
public CostAssignmentPolicy getCostAssignmentPolicy() {
return (CostAssignmentPolicy) kp.get("costAssignmentPolicy");
}
@Autowired(required=false)
public void setCostAssignmentPolicy(CostAssignmentPolicy policy) {
kp.put("costAssignmentPolicy",policy);
}
/* (non-Javadoc)
* @see org.archive.modules.Processor#shouldProcess(org.archive.modules.CrawlURI)
*/
@Override
protected boolean shouldProcess(CrawlURI uri) {
return true;
}
/* (non-Javadoc)
* @see org.archive.modules.Processor#innerProcess(org.archive.modules.CrawlURI)
*/
@Override
protected void innerProcess(CrawlURI curi) {
prepare(curi);
}
/**
* Apply all configured policies to CrawlURI
*
* @param curi CrawlURI
*/
public void prepare(CrawlURI curi) {
// set schedulingDirective
curi.setSchedulingDirective(getSchedulingDirective(curi));
// set canonicalized version
curi.setCanonicalString(canonicalize(curi));
// set queue key
curi.setClassKey(getClassKey(curi));
// set cost
curi.setHolderCost(getCost(curi));
// set URI precedence
getUriPrecedencePolicy().uriScheduled(curi);
}
/**
* Calculate the coarse, original 'schedulingDirective' prioritization
* for the given CrawlURI
*
* @param curi
* @return
*/
protected int getSchedulingDirective(CrawlURI curi) {
if(StringUtils.isNotEmpty(curi.getPathFromSeed())) {
char lastHop = curi.getPathFromSeed().charAt(curi.getPathFromSeed().length()-1);
if(lastHop == 'R') {
// refer
return getPreferenceDepthHops() >= 0 ? HIGH : MEDIUM;
}
}
if (getPreferenceDepthHops() == 0) {
return HIGH;
// this implies seed redirects are treated as path
// length 1, which I belive is standard.
// curi.getPathFromSeed() can never be null here, because
// we're processing a link extracted from curi
} else if (getPreferenceDepthHops() > 0 &&
curi.getPathFromSeed().length() + 1 <= getPreferenceDepthHops()) {
return HIGH;
} else {
// optionally preferencing embeds up to MEDIUM
int prefHops = getPreferenceEmbedHops();
if (prefHops > 0) {
int embedHops = curi.getTransHops();
if (embedHops > 0 && embedHops <= prefHops
&& curi.getSchedulingDirective() == SchedulingConstants.NORMAL) {
// number of embed hops falls within the preferenced range, and
// uri is not already MEDIUM -- so promote it
return MEDIUM;
}
}
// Everything else stays as previously assigned
// (probably NORMAL, at least for now)
return curi.getSchedulingDirective();
}
}
/**
* Canonicalize passed CrawlURI. This method differs from
* {@link #canonicalize(UURI)} in that it takes a look at
* the CrawlURI context possibly overriding any canonicalization effect if
* it could make us miss content. If canonicalization produces an URL that
* was 'alreadyseen', but the entry in the 'alreadyseen' database did
* nothing but redirect to the current URL, we won't get the current URL;
* we'll think we've already see it. Examples would be archive.org
* redirecting to www.archive.org or the inverse, www.netarkivet.net
* redirecting to netarkivet.net (assuming stripWWW rule enabled).
* <p>Note, this method under circumstance sets the forceFetch flag.
*
* @param cauri CrawlURI to examine.
* @return Canonicalized <code>cacuri</code>.
*/
protected String canonicalize(CrawlURI cauri) {
String canon = getCanonicalizationPolicy().canonicalize(cauri.getURI());
if (cauri.isLocation()) {
// If the via is not the same as where we're being redirected (i.e.
// we're not being redirected back to the same page, AND the
// canonicalization of the via is equal to the the current cauri,
// THEN forcefetch (Forcefetch so no chance of our not crawling
// content because alreadyseen check things its seen the url before.
// An example of an URL that redirects to itself is:
// http://bridalelegance.com/images/buttons3/tuxedos-off.gif.
// An example of an URL whose canonicalization equals its via's
// canonicalization, and we want to fetch content at the
// redirection (i.e. need to set forcefetch), is netarkivet.dk.
if (!cauri.toString().equals(cauri.getVia().toString()) &&
getCanonicalizationPolicy().canonicalize(
cauri.getVia().toCustomString()).equals(canon)) {
cauri.setForceFetch(true);
}
}
return canon;
}
/**
* @param cauri CrawlURI we're to get a key for.
* @return a String token representing a queue
*/
public String getClassKey(CrawlURI curi) {
assert KeyedProperties.overridesActiveFrom(curi);
String queueKey = getQueueAssignmentPolicy().getClassKey(curi);
return queueKey;
}
/**
* Return the 'cost' of a CrawlURI (how much of its associated
* queue's budget it depletes upon attempted processing)
*
* @param curi
* @return the associated cost
*/
protected int getCost(CrawlURI curi) {
assert KeyedProperties.overridesActiveFrom(curi);
int cost = curi.getHolderCost();
if (cost == CrawlURI.UNCALCULATED) {
cost = getCostAssignmentPolicy().costOf(curi);
}
return cost;
}
}
| 39.784722 | 93 | 0.644615 |
14c56f086851eda30e73c6486ac500c6a82234dc | 9,509 | /**
The MIT License (MIT) * Copyright (c) 2015 铭飞科技
* 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 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 NONINFRINGEMENT. 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 com.mingsoft.basic.action;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mingsoft.base.action.BaseAction;
import com.mingsoft.base.constant.e.TableEnum;
import com.mingsoft.basic.biz.IDiyFormBiz;
import com.mingsoft.basic.biz.IDiyFormFieldBiz;
import com.mingsoft.basic.constant.Const;
import com.mingsoft.basic.constant.e.DiyFormFieldEnum;
import com.mingsoft.basic.entity.DiyFormEntity;
import com.mingsoft.basic.entity.DiyFormFieldEntity;
import com.mingsoft.util.StringUtil;
/**
* 表单字段义字段管理
*
* @author 史爱华
* @version 版本号:100-000-000<br/>
* 创建日期:2015-1-10<br/>
* 历史修订:<br/>
*/
@Controller("diyFormField")
@RequestMapping("/manager/diy/formField")
public class DiyFormFieldAction extends com.mingsoft.basic.action.BaseAction {
/**
* 默认的字段id
*/
private static final String FIELD_ID = "id";
/**
* 默认的字段date
*/
private static final String FIELD_DATE = "date";
/**
* 默认的字段formId
*/
private static final String FIELD_FORMID = "formId";
/**
* 注入自定义表单字段biz
*/
@Autowired
private IDiyFormFieldBiz diyFormFieldBiz;
/**
* 注入自定义表单biz
*/
@Autowired
private IDiyFormBiz diyFormBiz;
/**
* 查询字段的列表信息
*
* @param diyFormId
* 自定义表单id
* @param request
* 请求对象
* @param response
* 响应对象
* @return 包含字段的map集合
*/
@RequestMapping("/list")
@ResponseBody
public Map list(int diyFormId, HttpServletRequest request, HttpServletResponse response) {
Map map = new HashMap();
// 查询所有的字段信息
List<DiyFormFieldEntity> fieldList = diyFormFieldBiz.queryByDiyFormId(diyFormId);
map.put("fieldList", fieldList);
// 获取字段属性
Map<Integer, String> fieldType = DiyFormFieldEnum.toMap();
map.put("fieldType", fieldType);
map.put("fieldNum", fieldType.size());
return map;
}
/**
* 添加自定义字段
*
* @param diyFormfield
* 自定义字段实体
* @param diyFormId
* 自定义表单id
* @param response
* 响应对象
*/
@RequestMapping("/{diyFormId}/save")
@ResponseBody
public void save(@ModelAttribute DiyFormFieldEntity diyFormfield, @PathVariable int diyFormId,
HttpServletResponse response) {
// 获取自定义表单实体
DiyFormEntity diyForm = (DiyFormEntity) diyFormBiz.getEntity(diyFormId);
if (diyForm == null) {
this.outJson(response, null, false, this.getResString("err.not.exist", this.getResString("diy.form")));
return;
}
// 更新前判断数据是否合法
if (!StringUtil.checkLength(diyFormfield.getDiyFormFieldTipsName(), 1, 20)) {
this.outJson(response, null, false,
getResString("err.length", this.getResString("diy.form.tips.name"), "1", "20"));
return;
}
if (!StringUtil.checkLength(diyFormfield.getDiyFormFieldFieldName(), 1, 20)) {
this.outJson(response, null, false,
getResString("err.length", this.getResString("diy.form.table.column.name"), "1", "20"));
return;
}
if (diyFormFieldBiz.getByFieldName(diyFormfield.getDiyFormFieldFormId(),
diyFormfield.getDiyFormFieldFieldName()) != null) {
this.outJson(response, null, false,
getResString("err.exist", this.getResString("diy.form.table.column.name")));
return;
}
// 动态的修改表结构
// 获取字段信息
Map<String, String> fileds = new HashMap();
// 压入字段名
fileds.put("fieldName", diyFormfield.getDiyFormFieldFieldName());
// 字段的数据类型
fileds.put("fieldType", diyFormfield.getDiyFormFieldColumnType());
fileds.put("default", diyFormfield.getDiyFormFieldDefault());
// 在表中创建字段
diyFormFieldBiz.alterTable(diyForm.getDiyFormTableName(), fileds, TableEnum.ALTER_ADD);
this.diyFormFieldBiz.saveEntity(diyFormfield);
this.outJson(response, null, true, null);
}
/**
* 获取编辑的字段实体的信息
*
* @param diyFormFieldId
* 自定义字段id
* @param request
* 请求对象
* @return 返回自定义字段的map集合
*/
@RequestMapping("/{diyFormFieldId}/edit")
@ResponseBody
public Map edit(@PathVariable int diyFormFieldId, HttpServletRequest request) {
Map mode = new HashMap();
DiyFormFieldEntity diyFormfield = (DiyFormFieldEntity) diyFormFieldBiz.getEntity(diyFormFieldId);
mode.put("diyFormfield", diyFormfield);
return mode;
}
/**
* 更新字段信息
*
* @param diyFormfield
* 要更新的字段信息的id
* @param response
* 响应对象
*/
@RequestMapping("/update")
@ResponseBody
public void update(@ModelAttribute DiyFormFieldEntity diyFormfield, HttpServletResponse response) {
// 更新前判断数据是否合法
if (!StringUtil.checkLength(diyFormfield.getDiyFormFieldTipsName(), 1, 20)) {
this.outJson(response, null, false,
getResString("err.length", this.getResString("fieldTipsName"), "1", "20"));
return;
}
if (!StringUtil.checkLength(diyFormfield.getDiyFormFieldFieldName(), 1, 20)) {
this.outJson(response, null, false,
getResString("err.length", this.getResString("fieldFieldName"), "1", "20"));
return;
}
// 获取自定义表单实体
DiyFormEntity diyForm = (DiyFormEntity) diyFormBiz.getEntity(diyFormfield.getDiyFormFieldFormId());
// 读取属性配置文件
DiyFormFieldEntity oldField = (DiyFormFieldEntity) diyFormFieldBiz.getEntity(diyFormfield.getDiyFormFieldId());
Map fields = new HashMap();
// 更改前的字段名
fields.put("fieldOldName", oldField.getDiyFormFieldFieldName());
// 新字段名
fields.put("fieldName", diyFormfield.getDiyFormFieldFieldName());
// 字段的数据类型
fields.put("fieldType", diyFormfield.getDiyFormFieldColumnType());
if (diyForm == null) {
this.outJson(response, null, false, this.getResString("err.not.exist"));
return;
}
// 更新表的字段名
diyFormFieldBiz.alterTable(diyForm.getDiyFormTableName(), fields, "modify");
diyFormFieldBiz.updateEntity(diyFormfield);
this.outJson(response, null, true, null);
}
/**
* 判断字段名是否存在重复
*
* @param diyFormFieldFieldName
* 字段名
* @param request
* 请求对象
* @return true:存在重复,false:不存在重复
*/
@RequestMapping("/{diyFormFieldFieldName}/checkFieldNameExist")
@ResponseBody
public boolean checkFieldNameExist(@PathVariable String diyFormFieldFieldName, HttpServletRequest request) {
int diyFormFieldFormId = 1;
if (request.getParameter("diyFormFieldFormId") != null) {
diyFormFieldFormId = Integer.parseInt(request.getParameter("diyFormFieldFormId"));
}
// 判断同一表单中是否存在表字段重名
if (diyFormFieldFieldName.equalsIgnoreCase(FIELD_ID) || diyFormFieldFieldName.equalsIgnoreCase(FIELD_DATE)
|| diyFormFieldFieldName.equalsIgnoreCase(FIELD_FORMID)
|| diyFormFieldBiz.getByFieldName(diyFormFieldFormId, diyFormFieldFieldName) != null) {
return true;
} else {
return false;
}
}
/**
* 删除自定义字段
*
* @param fieldId
* 表单ID
* @param request
* 请求对象
* @param response
* 响应对象
*/
@RequestMapping("/{fieldId}/delete")
public void delete(@PathVariable int fieldId, HttpServletRequest request, HttpServletResponse response) {
//
DiyFormFieldEntity diyFormField = (DiyFormFieldEntity) this.diyFormFieldBiz.getEntity(fieldId);
if (diyFormField == null) {
this.outJson(response, null, false,
this.getResString("err.not.exist", this.getResString("diy.form.field")));
return;
}
DiyFormEntity diyForm = (DiyFormEntity) this.diyFormBiz.getEntity(diyFormField.getDiyFormFieldFormId());
if (diyForm == null) {
this.outJson(response, null, false, this.getResString("err.not.exist", this.getResString("diy.form")));
return;
}
Map fields = new HashMap();
// 要删除的字段名
fields.put("fieldName", diyFormField.getDiyFormFieldFieldName());
// 删除列
diyFormFieldBiz.alterTable(diyForm.getDiyFormTableName(), fields, "drop");
diyFormFieldBiz.deleteEntity(diyFormField.getDiyFormFieldId());
this.outJson(response, null, true);
}
} | 33.364912 | 114 | 0.703123 |
fcbec162153ce025e030a76a9803298ee7e32635 | 2,748 | package com.caoyx.rpc.core.net.netty.client;
import com.caoyx.rpc.core.data.CaoyxRpcRequest;
import com.caoyx.rpc.core.data.CaoyxRpcResponse;
import com.caoyx.rpc.core.net.api.Client;
import com.caoyx.rpc.core.net.netty.codec.CaoyxRpcDecoder;
import com.caoyx.rpc.core.net.netty.codec.CaoyxRpcEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* @author caoyixiong
*/
@Slf4j
public class NettyClient implements Client {
private EventLoopGroup group;
private Channel channel;
private String host;
private int port;
@Override
public void init(String ipPort) throws InterruptedException {
group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<Channel>() {
protected void initChannel(Channel channel) throws Exception {
channel.pipeline()
.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 10, 4))
.addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS))
.addLast(new CaoyxRpcEncoder())
.addLast(new CaoyxRpcDecoder(CaoyxRpcResponse.class))
.addLast(new NettyClientHandler());
}
});
host = ipPort.split(":")[0];
port = Integer.valueOf(ipPort.split(":")[1]);
channel = bootstrap.connect(host, port).sync().channel();
}
@Override
public void doSend(CaoyxRpcRequest requestPacket) {
if (channel != null) {
try {
channel.writeAndFlush(requestPacket).sync();
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
}
}
}
@Override
public void close() {
if (channel != null) {
channel.close();
}
if (group != null) {
group.shutdownGracefully();
}
}
@Override
public boolean isValid() {
return channel != null && channel.isActive();
}
@Override
public String getHost() {
return this.host;
}
@Override
public int getPort() {
return this.port;
}
} | 29.869565 | 100 | 0.612082 |
dedb3dd5f253749c0f686b54e4b959af7a7a97d6 | 547 | package aoj;
import java.util.Scanner;
import java.util.Vector;
public class P2564DigitFib {
static Vector<Integer> f = new Vector<Integer>();
static {
f.add(0);
f.add(1);
for (int i = 3; i <= 60; i++)
f.add((f.get(f.size() - 1) + f.get(f.size() - 2)) % 10);
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
long k = cin.nextLong();
System.out.println(f.get((int) (k % 60)));
}
}
}
| 21.88 | 68 | 0.511883 |
f9a788b95073245a814d4d302365d2026f487e0e | 1,552 | package eas.com.window;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
/**
* Hello Word Print Class.
*
* @author Eduardo Alfonso Sanchez
* @since 1.0.0
*/
public class HelloWorkPrinter implements Printable, ActionListener {
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
/* The job did not successfully complete */
}
}else {
System.out.println("The printing was cancelled");
}
}
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Now we perform our rendering */
g.drawString("Hello world!", 100, 100);
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
}
| 29.283019 | 83 | 0.621134 |
e8a3fb017619313f8d67965d66ffddb012aaff5d | 731 | package com.qflow.server.usecase.queues;
import com.qflow.server.entity.Queue;
import org.springframework.beans.factory.annotation.Autowired;
public class CloseQueue {
private final CloseQueueDataBase closeQueueDatabase;
private final GetQueueByQueueId getQueueByQueueId;
public CloseQueue(CloseQueueDataBase closeQueueDatabase,
@Autowired GetQueueByQueueId getQueueByQueueId) {
this.getQueueByQueueId = getQueueByQueueId;
this.closeQueueDatabase = closeQueueDatabase;
}
public Queue execute(int idQueue) {
Queue queue = getQueueByQueueId.execute(idQueue);
closeQueueDatabase.closeQueue(queue);
return getQueueByQueueId.execute(idQueue);
}
}
| 33.227273 | 70 | 0.74829 |
f601474aec5de97f0f87a46e61aa3744405c3cf9 | 963 | package com.sadaqaworks.quranprojects.model;
import java.util.ArrayList;
/**
* Created by Sadmansamee on 7/19/15.
*/
public class AyahWord {
private ArrayList<Word> word;
private String quranArabic;
private String quranTranslate;
private Long quranVerseId;
public ArrayList<Word> getWord() {
return word;
}
public void setWord(ArrayList<Word> word) {
this.word = word;
}
public String getQuranArabic() {
return quranArabic;
}
public void setQuranArabic(String quranArabic) {
this.quranArabic = quranArabic;
}
public String getQuranTranslate() {
return quranTranslate;
}
public void setQuranTranslate(String quranTranslate) {
this.quranTranslate = quranTranslate;
}
public Long getQuranVerseId() {
return quranVerseId;
}
public void setQuranVerseId(Long quranVerseId) {
this.quranVerseId = quranVerseId;
}
}
| 20.934783 | 58 | 0.662513 |
fb0fa8420500a549e7e86d3e80811e62d16ac46a | 3,149 | /**
* 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.gst.integrationtests.common;
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gson.Gson;
import com.jayway.restassured.specification.RequestSpecification;
import com.jayway.restassured.specification.ResponseSpecification;
public class ExternalServicesConfigurationHelper {
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
public ExternalServicesConfigurationHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) {
this.requestSpec = requestSpec;
this.responseSpec = responseSpec;
}
public static ArrayList<HashMap> getExternalServicesConfigurationByServiceName(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String serviceName) {
final String GET_EXTERNAL_SERVICES_CONFIG_BY_SERVICE_NAME_URL = "/fineract-provider/api/v1/externalservice/" + serviceName + "?"
+ Utils.TENANT_IDENTIFIER;
System.out.println("------------------------ RETRIEVING GLOBAL CONFIGURATION BY ID -------------------------");
return Utils.performServerGet(requestSpec, responseSpec, GET_EXTERNAL_SERVICES_CONFIG_BY_SERVICE_NAME_URL, "");
}
public static HashMap updateValueForExternaServicesConfiguration(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String serviceName, final String name, final String value) {
final String EXTERNAL_SERVICES_CONFIG_UPDATE_URL = "/fineract-provider/api/v1/externalservice/" + serviceName + "?"
+ Utils.TENANT_IDENTIFIER;
System.out.println("---------------------------------UPDATE VALUE FOR GLOBAL CONFIG---------------------------------------------");
HashMap map = Utils.performServerPut(requestSpec, responseSpec, EXTERNAL_SERVICES_CONFIG_UPDATE_URL,
updateExternalServicesConfigUpdateValueAsJSON(name, value), "");
return (HashMap) map.get("changes");
}
public static String updateExternalServicesConfigUpdateValueAsJSON(final String name, final String value) {
final HashMap<String, String> map = new HashMap<>();
map.put(name, value);
System.out.println("map : " + map);
return new Gson().toJson(map);
}
}
| 48.446154 | 139 | 0.723722 |
e30477f9b2ddf6d33d00af05f014d2ca53bef4e0 | 1,922 | package com.atg.openssp.core.cache.broker.json;
import com.atg.openssp.common.cache.broker.DataBrokerObserver;
import com.atg.openssp.common.core.broker.dto.SiteDto;
import com.atg.openssp.common.core.cache.type.SiteDataCache;
import com.atg.openssp.common.core.system.loader.GlobalContextLoader;
import com.atg.openssp.common.logadapter.DataBrokerLogProcessor;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @author André Schmer
*
*/
public class SiteDataBrokerJson extends DataBrokerObserver {
private static final Logger log = LoggerFactory.getLogger(SiteDataBrokerJson.class);
public SiteDataBrokerJson() {}
@Override
protected boolean doCaching() {
long startTS = System.currentTimeMillis();
final Gson gson = new Gson();
try {
String environment = GlobalContextLoader.resolveEnvironment();
log.info("Environment: "+environment);
final String content = new String(Files.readAllBytes(Paths.get(environment+"site_db.json")), StandardCharsets.UTF_8);
final SiteDto dto = gson.fromJson(content, SiteDto.class);
log.info("using: "+content);
if (dto != null) {
long endTS = System.currentTimeMillis();
DataBrokerLogProcessor.instance.setLogData("SiteData", dto.getSites().size(), startTS, endTS, endTS-startTS);
log.info("sizeof site data=" + dto.getSites().size());
dto.getSites().forEach(site -> {
SiteDataCache.instance.put(site.getId(), site);
});
return true;
}
log.error("no Site data");
return false;
} catch (final IOException e) {
log.error(getClass() + ", " + e.getMessage());
}
return true;
}
@Override
protected void finalWork() {
// need to switch the intermediate cache to make the data available
SiteDataCache.instance.switchCache();
}
}
| 29.121212 | 120 | 0.736733 |
905c78b69853d170979e9616551d9a141f3417a9 | 4,196 | /*
* Copyright 2014 by the Metanome project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.metanome.algorithm_integration.results;
import com.fasterxml.jackson.annotation.JsonTypeName;
import de.metanome.algorithm_integration.ColumnCombination;
import de.metanome.algorithm_integration.ColumnIdentifier;
import de.metanome.algorithm_integration.result_receiver.CouldNotReceiveResultException;
import de.metanome.algorithm_integration.result_receiver.OmniscientResultReceiver;
import javax.xml.bind.annotation.XmlTransient;
@JsonTypeName("BasicStatistic")
public class BasicStatistic implements Result {
public static final String NAME_COLUMN_SEPARATOR = " of ";
public static final String COLUMN_VALUE_SEPARATOR = ": ";
ColumnCombination columnCombination;
String statisticName;
Object statisticValue;
/**
* Exists for serialization.
*/
protected BasicStatistic() {
this.columnCombination = new ColumnCombination();
this.statisticName = "";
}
public BasicStatistic(String statisticName, Object statisticValue,
ColumnIdentifier... columnIdentifier) {
this.columnCombination = new ColumnCombination(columnIdentifier);
this.statisticName = statisticName;
this.statisticValue = statisticValue;
}
/**
* @return the columnCombination
*/
public ColumnCombination getColumnCombination() {
return columnCombination;
}
public void setColumnCombination(ColumnCombination columnCombination) {
this.columnCombination = columnCombination;
}
/**
* @return the name of the statistic
*/
public String getStatisticName() {
return statisticName;
}
public void setStatisticName(String statisticName) {
this.statisticName = statisticName;
}
/**
* @return the value of the statistic on the columnCombination
*/
public Object getStatisticValue() {
return statisticValue;
}
public void setStatisticValue(Object statisticValue) {
this.statisticValue = statisticValue;
}
@Override
@XmlTransient
public void sendResultTo(OmniscientResultReceiver resultReceiver)
throws CouldNotReceiveResultException {
resultReceiver.receiveResult(this);
}
@Override
public String toString() {
return statisticName + NAME_COLUMN_SEPARATOR + columnCombination.toString() + COLUMN_VALUE_SEPARATOR
+ statisticValue.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((columnCombination == null) ? 0 : columnCombination.hashCode());
result = prime * result
+ ((statisticName == null) ? 0 : statisticName.hashCode());
result = prime * result
+ ((statisticValue == null) ? 0 : statisticValue.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BasicStatistic other = (BasicStatistic) obj;
if (columnCombination == null) {
if (other.columnCombination != null) {
return false;
}
} else if (!columnCombination.equals(other.columnCombination)) {
return false;
}
if (statisticName == null) {
if (other.statisticName != null) {
return false;
}
} else if (!statisticName.equals(other.statisticName)) {
return false;
}
if (statisticValue == null) {
if (other.statisticValue != null) {
return false;
}
} else if (!statisticValue.equals(other.statisticValue)) {
return false;
}
return true;
}
}
| 28.161074 | 104 | 0.698761 |
4dc6fd2925642445b04c9b26bea23a8749002fb3 | 1,602 | package com.madfree.bakingapp.data;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Index;
import androidx.room.PrimaryKey;
import static androidx.room.ForeignKey.CASCADE;
@Entity(indices = {@Index(value = "recipeId")},
foreignKeys = @ForeignKey(entity = Recipe.class,
parentColumns = "id",
childColumns = "recipeId",
onDelete = CASCADE))
public class Step {
@PrimaryKey(autoGenerate = true)
private int id;
private int stepId;
private String shortDescription;
private String description;
private String videoURL;
private String thumbnailURL;
private int recipeId;
public Step(int stepId, String shortDescription, String description, String videoURL,
String thumbnailURL, int recipeId) {
this.stepId = stepId;
this.shortDescription = shortDescription;
this.description = description;
this.videoURL = videoURL;
this.thumbnailURL = thumbnailURL;
this.recipeId = recipeId;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public int getStepId() {
return stepId;
}
public String getShortDescription() {
return shortDescription;
}
public String getDescription() {
return description;
}
public String getVideoURL() {
return videoURL;
}
public String getThumbnailURL() {
return thumbnailURL;
}
public int getRecipeId() {
return recipeId;
}
}
| 23.558824 | 89 | 0.635456 |
ff710b9e9497cc8b86e748aeb63d6a0e2662b08f | 763 | package com.cloudxhoster.api.utils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Path;
import java.util.Map;
public class IOUtilsTest {
private static final Logger LOG = LoggerFactory.getLogger(IOUtilsTest.class);
private Path workingDir;
@BeforeEach
public void init() {
this.workingDir = Path.of("src/test/resources");
}
@Test
public void getAllFilesTest() {
String webSiteSrcDir = this.workingDir.resolve("website/timeless/").toString();
Map<String, Path> allFiles = IOUtils.getAllFiles(webSiteSrcDir);
allFiles.forEach((rel, abs) -> LOG.info("{} , {}", rel, abs.toString()));
}
} | 27.25 | 87 | 0.695937 |
5eac6e791927f4ecd50ac574f7012e503627cca1 | 2,217 | package cn.linz.base.config;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.ReflectUtil;
import cn.linz.base.exception.IdGeneratorException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentityGenerator;
import org.hibernate.id.UUIDGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Objects;
import java.util.Properties;
/**
* 自定义id生成器
*
* @author taogl
* @version 1.0.0
*/
public class CustomIdentifierGenerator extends IdentityGenerator implements Configurable {
private static final UUIDGenerator UUID_GENERATOR = new UUIDGenerator();
/** {@inheritDoc} */
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
try {
Object fieldValue = ReflectUtil.getFieldValue(object, "id");
if (fieldValue != null) {
return (Serializable) fieldValue;
}
} catch (SecurityException | UtilException e) {
throw new IdGeneratorException("ID生成异常:" + e.getMessage(), e);
}
ParameterizedType superClass = (ParameterizedType) object.getClass().getGenericSuperclass();
Class<?> type = (Class<?>) superClass.getActualTypeArguments()[0];
if (Objects.equals(type, String.class)) {
return UUID_GENERATOR.generate(session, object);
} else if (Objects.equals(type, Integer.class) ||
Objects.equals(type, Long.class)) {
return super.generate(session, object);
}
throw new IdGeneratorException("ID生成异常,主键类型未配置生成器:" + type);
}
/** {@inheritDoc} */
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
if (type instanceof StringType) {
UUID_GENERATOR.configure(type, params, serviceRegistry);
}
}
}
| 35.190476 | 117 | 0.708164 |
2b5ab7ab6207f0e631c3e27b7eda185c3260a621 | 199 | package org.onap.appc.dg.common.impl;
public class VnfExecutionInternalException extends RuntimeException{
public VnfExecutionInternalException(Throwable cause) {
super(cause);
}
}
| 22.111111 | 68 | 0.763819 |
8e771f52073b95877cf016ed29322d85aa6e2a0f | 1,682 | /*
* Copyright 2010-2013 Ning, Inc.
* Copyright 2015 Groupon, Inc
* Copyright 2015 The Billing Project, LLC
*
* The Billing Project 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.killbill.billing.osgi.api;
import org.killbill.billing.KillbillApi;
import org.killbill.billing.osgi.api.config.PluginLanguage;
public interface PluginsInfoApi extends KillbillApi {
/**
*
* @return the list of plugins as seen by the OSGI registry
*/
public Iterable<PluginInfo> getPluginsInfo();
/**
* Notify OSGI component that a new plugin was installed (downloaded) on the file system.
*
* @param newState the state (currently only {@code NEW_VERSION} is allowed
* @param pluginKey the plugin key (used during install/uninstall time)
* @param pluginName the name of the plugin (as seen of the filesystem)
* @param pluginVersion the version of the plugin
* @param pluginLanguage the language (JAVA or RUBY)
*/
public void notifyOfStateChanged(PluginStateChange newState, String pluginKey, String pluginName, String pluginVersion, PluginLanguage pluginLanguage);
}
| 39.116279 | 155 | 0.727705 |
cfbef6287aea1b87460820354cbf50c45acd8200 | 2,289 | package com.airbnb.android.react.maps;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
import java.util.Map;
import javax.annotation.Nullable;
public class AirMapOverlayManager extends ViewGroupManager<AirMapOverlay> {
private final DisplayMetrics metrics;
public String getName() {
return "AIRMapOverlay";
}
public AirMapOverlayManager(ReactApplicationContext reactApplicationContext) {
if (Build.VERSION.SDK_INT >= 17) {
this.metrics = new DisplayMetrics();
((WindowManager) reactApplicationContext.getSystemService("window")).getDefaultDisplay().getRealMetrics(this.metrics);
return;
}
this.metrics = reactApplicationContext.getResources().getDisplayMetrics();
}
public AirMapOverlay createViewInstance(ThemedReactContext themedReactContext) {
return new AirMapOverlay(themedReactContext);
}
@ReactProp(name = "bounds")
public void setBounds(AirMapOverlay airMapOverlay, ReadableArray readableArray) {
airMapOverlay.setBounds(readableArray);
}
@ReactProp(defaultFloat = 1.0f, name = "zIndex")
public void setZIndex(AirMapOverlay airMapOverlay, float f) {
airMapOverlay.setZIndex(f);
}
@ReactProp(defaultFloat = 1.0f, name = "opacity")
public void setOpacity(AirMapOverlay airMapOverlay, float f) {
airMapOverlay.setTransparency(1.0f - f);
}
@ReactProp(name = "image")
public void setImage(AirMapOverlay airMapOverlay, @Nullable String str) {
airMapOverlay.setImage(str);
}
@ReactProp(defaultBoolean = false, name = "tappable")
public void setTappable(AirMapOverlay airMapOverlay, boolean z) {
airMapOverlay.setTappable(z);
}
@Nullable
public Map getExportedCustomDirectEventTypeConstants() {
return MapBuilder.m140of("onPress", MapBuilder.m140of("registrationName", "onPress"));
}
}
| 35.215385 | 130 | 0.733945 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.