hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
923cd65b4a522a8e393464d67f93259e2be8618a
29,370
java
Java
src/main/java/pokerai/game/eval/stevebrecher/HandEval.java
corintio/pokerai-eval
85ccecd1f0748c4447c5e321171c02271c877d25
[ "BSD-3-Clause" ]
4
2017-05-11T09:25:42.000Z
2021-08-16T21:43:49.000Z
src/main/java/pokerai/game/eval/stevebrecher/HandEval.java
corintio/pokerai-eval
85ccecd1f0748c4447c5e321171c02271c877d25
[ "BSD-3-Clause" ]
null
null
null
src/main/java/pokerai/game/eval/stevebrecher/HandEval.java
corintio/pokerai-eval
85ccecd1f0748c4447c5e321171c02271c877d25
[ "BSD-3-Clause" ]
3
2017-07-08T21:43:46.000Z
2020-05-20T09:26:05.000Z
37.750643
152
0.573987
1,000,067
package pokerai.game.eval.stevebrecher; /** * Non-instantiable class containing a variety of static poker hand evaluation and related utility methods. * <p> * All of the methods are thread-safe. * <p> * Each evaluation method takes a single parameter representing a hand of five to * seven cards represented in four 13-bit masks, one mask per suit, in * the low-order 52 bits of a long (64 bits). In each mask, bit 0 set * (0x0001) for a deuce, ..., bit 12 set (0x1000) for an ace. Each mask * denotes the ranks present in one of the suits. The ordering of the * 13-bit suit fields is immaterial. * <p> * A hand parameter can be built by encoding a {@link CardSet} or by bitwise * OR-ing, or adding, the encoded values of individual {@link Card}s. These * encodings are returned by an {@link #encode encode} method. * <p> * Different methods are called for high and for lowball evaluation. The * return value format below is the same except:&nbsp;&nbsp;For low evaluation, as for * wheels in high evaluation, Ace is rank 1 and its mask bit is the LS bit; * otherwise Ace is rank 14, mask bit 0x1000, and the deuce's mask bit is * the LS bit. 8-or-better low evaluation methods may also return {@link #NO_8_LOW}. * <p> * For high evaulation, if results R1 > R2 then hand 1 beats hand 2;<br> * For low evaluation, if results R1 > R2 then hand 2 beats hand 1. * <p> * Each evaluation method's return value is an int; 32 bits = 0x0VTBKKKK * where each letter refers to a 4-bit nybble:<pre> * V nybble = category code ranging from {@link HandCategory#NO_PAIR}<code>.ordinal()</code> * to {@link HandCategory#STRAIGHT_FLUSH}<code>.ordinal()</code> * T nybble = rank (2..14) of top pair for two pair, 0 otherwise * B nybble = rank (1..14) of quads or trips (including full house trips), * or rank of high card (5..14) in straight or straight flush, * or rank of bottom pair for two pair (hence the symbol "B"), * or rank of pair for one pair, * or 0 otherwise * KKKK mask = 16-bit mask with... * 5 bits set for no pair or (non-straight-)flush * 3 bits set for kickers with pair, * 2 bits set for kickers with trips, * 1 bit set for pair within full house or kicker with quads * or kicker with two pair * or 0 otherwise</pre> * @version 2008Apr27.0 * @author Steve Brecher * */ // 2008Apr27.0 // fix hand6Eval's calls to flushAndOrStraight6 // 2006Dec05.0 // original Java release, ported from C public final class HandEval { private HandEval() {} // no instances /** * Returns a value which can be used in building a parameter to one of the HandEval evaluation methods. * @param card a {@link Card} * @return a value which may be bitwise OR'ed or added to other such * values to build a parameter to one of the HandEval evaluation methods. */ public static long encode(final Card card) { return 0x1L << (card.suitOf().ordinal()*13 + card.rankOf().ordinal()); } /** * Returns a value which can be used as a parameter to one of the HandEval evaluation methods. * @param cs a {@link CardSet} * @return a value which can be used as a parameter to one of the HandEval evaluation methods. * The value may also be bitwise OR'ed or added to other such * values to build an evaluation method parameter. */ public static long encode(final CardSet cs) { long result = 0; for (Card c : cs) result |= encode(c); return result; } public static enum HandCategory { NO_PAIR, PAIR, TWO_PAIR, THREE_OF_A_KIND, STRAIGHT, FLUSH, FULL_HOUSE, FOUR_OF_A_KIND, STRAIGHT_FLUSH; } private static final int BOT_SHIFT = 16; private static final int TOP_SHIFT = BOT_SHIFT + 4; private static final int VALUE_SHIFT = TOP_SHIFT + 4; // javac doesn't propagate NO_PAIR (==0) so doesn't constant-fold it out of bitwise-or expressions // private static final int NO_PAIR = HandCategory.NO_PAIR.ordinal() << VALUE_SHIFT; private static final int PAIR = HandCategory.PAIR.ordinal() << VALUE_SHIFT; private static final int TWO_PAIR = HandCategory.TWO_PAIR.ordinal() << VALUE_SHIFT; private static final int THREE_OF_A_KIND = HandCategory.THREE_OF_A_KIND.ordinal() << VALUE_SHIFT; private static final int STRAIGHT = HandCategory.STRAIGHT.ordinal() << VALUE_SHIFT; private static final int FLUSH = HandCategory.FLUSH.ordinal() << VALUE_SHIFT; private static final int FULL_HOUSE = HandCategory.FULL_HOUSE.ordinal() << VALUE_SHIFT; private static final int FOUR_OF_A_KIND = HandCategory.FOUR_OF_A_KIND.ordinal() << VALUE_SHIFT; private static final int STRAIGHT_FLUSH = HandCategory.STRAIGHT_FLUSH.ordinal() << VALUE_SHIFT; /* Arrays for which index is bit mask of card ranks in hand: */ private static final int ARRAY_SIZE = 0x1FC0 + 1; // all combos of up to 7 of LS 13 bits on private static final int[] straightValue = new int[ARRAY_SIZE]; // STRAIGHT | (straight's high card rank (5..14) << BOT_SHIFT); 0 if no straight private static final int[] nbrOfRanks = new int[ARRAY_SIZE]; // count of bits set private static final int[] hiTopRankTWO_PAIR = new int[ARRAY_SIZE]; // TWO_PAIR | ((rank (2..kA) of the highest bit set) << TOP_SHIFT) private static final int[] hiBotRank = new int[ARRAY_SIZE]; // (rank (2..kA) of the highest bit set) << BOT_SHIFT private static final int[] hiRankMask = new int[ARRAY_SIZE]; // all bits except highest reset private static final int[] hi2RanksMask = new int[ARRAY_SIZE]; // all bits except highest 2 reset private static final int[] hi3RanksMask = new int[ARRAY_SIZE]; // all bits except highest 3 reset private static final int[] hi5RanksMask = new int[ARRAY_SIZE]; // all bits except highest 5 reset private static final int[] lo5RanksMask = new int[ARRAY_SIZE]; // all bits except lowest 5 8-or-better reset; 0 if not at least 5 8-or-better bits set private static final int[] lo3RanksMask = new int[ARRAY_SIZE]; // all bits except lowest 3 8-or-better reset; 0 if not at least 3 8-or-better bits set /** * Greater than any return value of the HandEval evaluation methods. */ public static final int NO_8_LOW = STRAIGHT_FLUSH + (1 << VALUE_SHIFT); private static final int[] loEvalOrNo8Low = new int[ARRAY_SIZE]; // 5 bits set in LS 8 bits, or NO_8_LOW */ private static int flushAndOrStraight7(final int ranks, final int c, final int d, final int h, final int s) { int i, j; if ((j = nbrOfRanks[c]) > 7 - 5) { // there's either a club flush or no flush if (j >= 5) if ((i = straightValue[c]) == 0) return FLUSH | hi5RanksMask[c]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; } else if ((j += (i = nbrOfRanks[d])) > 7 - 5) { if (i >= 5) if ((i = straightValue[d]) == 0) return FLUSH | hi5RanksMask[d]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; } else if ((j += (i = nbrOfRanks[h])) > 7 - 5) { if (i >= 5) if ((i = straightValue[h]) == 0) return FLUSH | hi5RanksMask[h]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; } else /* total cards in other suits <= 7-5: spade flush: */ if ((i = straightValue[s]) == 0) return FLUSH | hi5RanksMask[s]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; return straightValue[ranks]; } /** * Returns the value of the best 5-card high poker hand from 7 cards. * @param hand bit mask with one bit set for each of 7 cards. * @return the value of the best 5-card high poker hand. */ public static int hand7Eval(long hand) { int i, j, ranks; /* * The low-order 52 bits of hand contains four 13-bit fields, one * field per suit. The high-order 12 bits are clear. Get the * respective fields into variables. * We don't care which suit is which; we arbitrarily call them c,d,h,s. */ final int c = (int)hand & 0x1FFF; final int d = ((int)hand >>> 13) & 0x1FFF; final int h = (int)(hand >>> 26) & 0x1FFF; final int s = (int)(hand >>> 39); switch (nbrOfRanks[ranks = c | d | h | s]) { case 2: /* * quads with trips kicker */ i = c & d & h & s; /* bit for quads */ return FOUR_OF_A_KIND | hiBotRank[i] | (i ^ ranks); case 3: /* * trips and pair (full house) with non-playing pair, * or two trips (full house) with non-playing singleton, * or quads with pair and singleton */ /* bits for singleton, if any, and trips, if any: */ if (nbrOfRanks[i = c ^ d ^ h ^ s] == 3) { /* two trips (full house) with non-playing singleton */ if (nbrOfRanks[i = c & d] != 2) if (nbrOfRanks[i = c & h] != 2) if (nbrOfRanks[i = c & s] != 2) if (nbrOfRanks[i = d & h] != 2) if (nbrOfRanks[i = d & s] != 2) i = h & s; /* bits for the trips */ return FULL_HOUSE | hiBotRank[i] | (i ^ hiRankMask[i]); } if ((j = c & d & h & s) != 0) /* bit for quads */ /* quads with pair and singleton */ return FOUR_OF_A_KIND | hiBotRank[j] | (hiRankMask[ranks ^ j]); /* trips and pair (full house) with non-playing pair */ return FULL_HOUSE | hiBotRank[i] | (hiRankMask[ranks ^ i]); case 4: /* * three pair and singleton, * or trips and pair (full house) and two non-playing singletons, * or quads with singleton kicker and two non-playing singletons */ i = c ^ d ^ h ^ s; // the bit(s) of the trips, if any, and singleton(s) if (nbrOfRanks[i] == 1) { /* three pair and singleton */ j = ranks ^ i; /* the three bits for the pairs */ ranks = hiRankMask[j]; /* bit for the top pair */ j ^= ranks; /* bits for the two bottom pairs */ return hiTopRankTWO_PAIR[ranks] | hiBotRank[j] | hiRankMask[(hiRankMask[j] ^ j) | i]; } if ((j = c & d & h & s) == 0) { // trips and pair (full house) and two non-playing singletons i ^= ranks; /* bit for the pair */ if ((j = (c & d) & (~i)) == 0) j = (h & s) & (~i); /* bit for the trips */ return FULL_HOUSE | hiBotRank[j] | i; } // quads with singleton kicker and two non-playing singletons return FOUR_OF_A_KIND | hiBotRank[j] | (hiRankMask[i]); case 5: /* * flush and/or straight, * or two pair and three singletons, * or trips and four singletons */ if ((i = flushAndOrStraight7(ranks, c, d, h, s)) != 0) return i; i = c ^ d ^ h ^ s; // the bits of the trips, if any, and singletons if (nbrOfRanks[i] != 5) { /* two pair and three singletons */ j = i ^ ranks; /* the two bits for the pairs */ return hiTopRankTWO_PAIR[j] | hiBotRank[hiRankMask[j] ^ j] | hiRankMask[i]; } /* trips and four singletons */ if ((j = c & d) == 0) j = h & s; return THREE_OF_A_KIND | hiBotRank[j] | (hi2RanksMask[i ^ j]); case 6: /* * flush and/or straight, * or one pair and three kickers and two nonplaying singletons */ if ((i = flushAndOrStraight7(ranks, c, d, h, s)) != 0) return i; i = c ^ d ^ h ^ s; /* the bits of the five singletons */ return PAIR | hiBotRank[ranks ^ i] | hi3RanksMask[i]; case 7: /* * flush and/or straight or no pair */ if ((i = flushAndOrStraight7(ranks, c, d, h, s)) != 0) return i; return /* NO_PAIR | */ hi5RanksMask[ranks]; } /* end switch */ return 0; /* never reached, but avoids compiler warning */ } /** * Returns the value of the best 5-card Razz poker hand from 7 cards. * @param hand bit mask with one bit set for each of 7 cards. * @return the value of the best 5-card Razz poker hand. */ public static int handRazzEval(long hand) { // each of the following extracts a 13-bit field from hand and // rotates it left to position the ace in the least significant bit final int c = (((int)hand & 0x1FFF) << 1) + (((int)hand ^ 0x1000) >> 12); final int d = (((int)hand >> 12) & 0x3FFE) + (((int)hand ^ (0x1000 << 13)) >> 25); final int h = ((int)(hand >> 25) & 0x3FFE) + (int)((hand ^ (0x1000L << 26)) >> 38); final int s = ((int)(hand >> 38) & 0x3FFE) + (int)((hand ^ (0x1000L << 39)) >> 51); final int ranks = c | d | h | s; int i, j; switch (nbrOfRanks[ranks]) { case 2: /* AAAABBB -- full house */ i = c & d & h & s; /* bit for quads */ j = i ^ ranks; /* bit for trips */ // it can't matter in comparison of results from a 52-card deck, // but we return the correct value per relative ranks if (i > j) return FULL_HOUSE | hiBotRank[i] | (j); return FULL_HOUSE | hiBotRank[j] | (i); case 3: /* * AAABBBC -- two pair, * AAAABBC -- two pair, * AAABBCC -- two pair w/ kicker = highest rank. */ /* bits for singleton, if any, and trips, if any: */ if (nbrOfRanks[i = c ^ d ^ h ^ s] == 3) { /* odd number of each rank: AAABBBC -- two pair */ if (nbrOfRanks[i = c & d] != 2) if (nbrOfRanks[i = c & h] != 2) if (nbrOfRanks[i = c & s] != 2) if (nbrOfRanks[i = d & h] != 2) if (nbrOfRanks[i = d & s] != 2) i = h & s; /* bits for the trips */ return hiTopRankTWO_PAIR[i] | hiBotRank[i ^ hiRankMask[i]] | (ranks ^ i); } if ((j = c & d & h & s) != 0) { /* bit for quads */ /* AAAABBC -- two pair */ j = ranks ^ i; /* bits for pairs */ return hiTopRankTWO_PAIR[j] | hiBotRank[j ^ hiRankMask[j]] | i; } /* AAABBCC -- two pair w/ kicker = highest rank */ i = hiRankMask[ranks]; /* kicker bit */ j = ranks ^ i; /* pairs bits */ return hiTopRankTWO_PAIR[j] | hiBotRank[j ^ hiRankMask[j]] | i; case 4: /* * AABBCCD -- one pair (lowest of A, B, C), * AAABBCD -- one pair (A or B), * AAAABCD -- one pair (A) */ i = c ^ d ^ h ^ s; /* the bit(s) of the trips, if any, and singleton(s) */ if (nbrOfRanks[i] == 1) { /* AABBCCD -- one pair (C with ABD) */ /* D's bit is in i */ j = hi2RanksMask[ranks ^ i] | i; /* kickers */ return PAIR | hiBotRank[ranks ^ j] | j; } if ((j = c & d & h & s) == 0) { /* AAABBCD -- one pair (A or B) */ i ^= ranks; /* bit for B */ if ((j = (c & d) & (~i)) == 0) j = (h & s) & (~i); /* bit for A */ if (i < j) return PAIR | hiBotRank[i] | (ranks ^ i); return PAIR | hiBotRank[j] | (ranks ^ j); } /* AAAABCD -- one pair (A) */ return PAIR | hiBotRank[j] | i; case 5: return /* NO_PAIR | */ranks; case 6: return /* NO_PAIR | */lo5RanksMask[ranks]; case 7: return /* NO_PAIR | */lo5RanksMask[ranks]; } /* end switch */ return 0; /* never reached, but avoids compiler warning */ } private static int flushAndOrStraight6(final int ranks, final int c, final int d, final int h, final int s) { int i, j; if ((j = nbrOfRanks[c]) > 6 - 5) { // there's either a club flush or no flush if (j >= 5) if ((i = straightValue[c]) == 0) return FLUSH | hi5RanksMask[c]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; } else if ((j += (i = nbrOfRanks[d])) > 6 - 5) { if (i >= 5) if ((i = straightValue[d]) == 0) return FLUSH | hi5RanksMask[d]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; } else if ((j += (i = nbrOfRanks[h])) > 6 - 5) { if (i >= 5) if ((i = straightValue[h]) == 0) return FLUSH | hi5RanksMask[h]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; } else /* total cards in other suits <= N-5: spade flush: */ if ((i = straightValue[s]) == 0) return FLUSH | hi5RanksMask[s]; else return (STRAIGHT_FLUSH - STRAIGHT) + i; return straightValue[ranks]; } /** * Returns the value of the best 5-card high poker hand from 6 cards. * @param hand bit mask with one bit set for each of 6 cards. * @return the value of the best 5-card high poker hand. */ public static int hand6Eval(long hand) { final int c = (int)hand & 0x1FFF; final int d = ((int)hand >>> 13) & 0x1FFF; final int h = (int)(hand >>> 26) & 0x1FFF; final int s = (int)(hand >>> 39); final int ranks = c | d | h | s; int i, j, k; switch (nbrOfRanks[ranks]) { case 2: /* quads with pair kicker, or two trips (full house) */ /* bits for trips, if any: */ if ((nbrOfRanks[i = c ^ d ^ h ^ s]) != 0) /* two trips (full house) */ return FULL_HOUSE | hiBotRank[i] | (i ^ hiRankMask[i]); /* quads with pair kicker */ i = c & d & h & s; /* bit for quads */ return FOUR_OF_A_KIND | hiBotRank[i] | (i ^ ranks); case 3: /* quads with singleton kicker and non-playing singleton, or full house with non-playing singleton, or two pair with non-playing pair */ if ((c ^ d ^ h ^ s) == 0) { /* no trips or singletons: three pair */ i = hiRankMask[ranks]; /* bit for the top pair */ k = ranks ^ i; /* bits for the bottom two pairs */ j = hiRankMask[k]; /* bit for the middle pair */ return hiTopRankTWO_PAIR[i] | hiBotRank[j] | (k ^ j); } if ((i = c & d & h & s) == 0) { /* full house with singleton */ if ((i = c & d & h) == 0) if ((i = c & d & s) == 0) if ((i = c & h & s) == 0) i = d & h & s; /* bit of trips */ j = c ^ d ^ h ^ s; /* the bits of the trips and singleton */ return FULL_HOUSE | hiBotRank[i] | (j ^ ranks); } /* quads with kicker and singleton */ return FOUR_OF_A_KIND | hiBotRank[i] | (hiRankMask[i ^ ranks]); case 4: /* trips and three singletons, or two pair and two singletons */ if ((i = c ^ d ^ h ^ s) != ranks) { /* two pair and two singletons */ j = i ^ ranks; /* the two bits for the pairs */ return hiTopRankTWO_PAIR[j] | hiBotRank[hiRankMask[j] ^ j] | hiRankMask[i]; } /* trips and three singletons */ if ((i = c & d) == 0) i = h & s; /* bit of trips */ return THREE_OF_A_KIND | hiBotRank[i] | (hi2RanksMask[i ^ ranks]); case 5: /* flush and/or straight, or one pair and three kickers and one non-playing singleton */ if ((i = flushAndOrStraight6(ranks, c, d, h, s)) != 0) return i; i = c ^ d ^ h ^ s; /* the bits of the four singletons */ return PAIR | hiBotRank[ranks ^ i] | hi3RanksMask[i]; case 6: /* flush and/or straight or no pair */ if ((i = flushAndOrStraight6(ranks, c, d, h, s)) != 0) return i; return /* NO_PAIR | */ hi5RanksMask[ranks]; } /* end switch */ return 0; /* never reached, but avoids compiler warning */ } /** * Returns the value of a 5-card poker hand. * @param hand bit mask with one bit set for each of 5 cards. * @return the value of the hand. */ public static int hand5Eval(long hand) { final int c = (int)hand & 0x1FFF; final int d = ((int)hand >>> 13) & 0x1FFF; final int h = (int)(hand >>> 26) & 0x1FFF; final int s = (int)(hand >>> 39); final int ranks = c | d | h | s; int i, j; switch (nbrOfRanks[ranks]) { case 2: /* quads or full house */ i = c & d; /* any two suits */ if ((i & h & s) == 0) { /* no bit common to all suits */ i = c ^ d ^ h ^ s; /* trips bit */ return FULL_HOUSE | hiBotRank[i] | (i ^ ranks); } else /* the quads bit must be present in each suit mask, but the kicker bit in no more than one; so we need only AND any two suit masks to get the quad bit: */ return FOUR_OF_A_KIND | hiBotRank[i] | (i ^ ranks); case 3: /* trips and two kickers, or two pair and kicker */ if ((i = c ^ d ^ h ^ s) == ranks) { /* trips and two kickers */ if ((i = c & d) != 0) return THREE_OF_A_KIND | hiBotRank[i] | (i ^ ranks); if ((i = c & h) != 0) return THREE_OF_A_KIND | hiBotRank[i] | (i ^ ranks); i = d & h; return THREE_OF_A_KIND | hiBotRank[i] | (i ^ ranks); } /* two pair and kicker; i has kicker bit */ j = i ^ ranks; /* j has pairs bits */ return hiTopRankTWO_PAIR[j] | hiBotRank[j ^ hiRankMask[j]] | i; case 4: /* pair and three kickers */ i = c ^ d ^ h ^ s; /* kicker bits */ return PAIR | hiBotRank[ranks ^ i] | i; case 5: /* flush and/or straight, or no pair */ if ((i = straightValue[ranks]) == 0) i = ranks; if (c != 0) { /* if any clubs... */ if (c != ranks) /* if no club flush... */ return i; } /* return straight or no pair value */ else if (d != 0) { if (d != ranks) return i; } else if (h != 0) { if (h != ranks) return i; } /* else s == ranks: spade flush */ /* There is a flush */ if (i == ranks) /* no straight */ return FLUSH | ranks; else return (STRAIGHT_FLUSH - STRAIGHT) + i; } return 0; /* never reached, but avoids compiler warning */ } /** * Returns the Ace-to-5 value of a 5-card low poker hand. * @param hand bit mask with one bit set for each of 5 cards. * @return the Ace-to-5 low value of the hand. */ public static int hand5Ato5LoEval(long hand) { // each of the following extracts a 13-bit field from hand and // rotates it left to position the ace in the least significant bit final int c = (((int)hand & 0x1FFF) << 1) + (((int)hand ^ 0x1000) >> 12); final int d = (((int)hand >> 12) & 0x3FFE) + (((int)hand ^ (0x1000 << 13)) >> 25); final int h = ((int)(hand >> 25) & 0x3FFE) + (int)((hand ^ (0x1000L << 26)) >> 38); final int s = ((int)(hand >> 38) & 0x3FFE) + (int)((hand ^ (0x1000L << 39)) >> 51); final int ranks = c | d | h | s; int i, j; switch (nbrOfRanks[ranks]) { case 2: /* quads or full house */ i = c & d; /* any two suits */ if ((i & h & s) == 0) { /* no bit common to all suits */ i = c ^ d ^ h ^ s; /* trips bit */ return FULL_HOUSE | hiBotRank[i] | (i ^ ranks); } else /* the quads bit must be present in each suit mask, but the kicker bit in no more than one; so we need only AND any two suit masks to get the quad bit: */ return FOUR_OF_A_KIND | hiBotRank[i] | (i ^ ranks); case 3: /* trips and two kickers, or two pair and kicker */ if ((i = c ^ d ^ h ^ s) == ranks) { /* trips and two kickers */ if ((i = c & d) != 0) return THREE_OF_A_KIND | hiBotRank[i] | (i ^ ranks); if ((i = c & h) != 0) return THREE_OF_A_KIND | hiBotRank[i] | (i ^ ranks); i = d & h; return THREE_OF_A_KIND | hiBotRank[i] | (i ^ ranks); } /* two pair and kicker; i has kicker bit */ j = i ^ ranks; /* j has pairs bits */ return hiTopRankTWO_PAIR[j] | hiBotRank[j ^ hiRankMask[j]] | i; case 4: /* pair and three kickers */ i = c ^ d ^ h ^ s; /* kicker bits */ return PAIR | hiBotRank[ranks ^ i] | i; case 5: /* no pair */ return ranks; } return 0; /* never reached, but avoids compiler warning */ } /** * Returns the bitwise OR of the suit masks comprising <code>hand</code>; Ace is high. * @param hand bit mask with one bit set for each of 0 to 52 cards. * @return the bitwise OR of the suit masks comprising <code>hand</code>. */ public static int ranksMask(long hand) { return ( ((int)hand & 0x1FFF) | (((int)hand >>> 13) & 0x1FFF) | ((int)(hand >>> 26) & 0x1FFF) | (int)(hand >>> 39) ); } /** * Returns the bitwise OR of the suit masks comprising <code>hand</code>; Ace is low. * @param hand bit mask with one bit set for each of 0 to 52 cards. * @return the bitwise OR of the suit masks comprising <code>hand</code>. */ public static int ranksMaskLo(long hand) { return ( ((((int)hand & 0x1FFF) << 1) + (((int)hand ^ 0x1000) >> 12)) | ((((int)hand >> 12) & 0x3FFE) + (((int)hand ^ (0x1000 << 13)) >> 25)) | (((int)(hand >> 25) & 0x3FFE) + (int)((hand ^ (0x1000L << 26)) >> 38)) | (((int)(hand >> 38) & 0x3FFE) + (int)((hand ^ (0x1000L << 39)) >> 51)) ); } /** * Returns the 8-or-better low value of a 5-card poker hand or {@link #NO_8_LOW}. * @param hand bit mask with one bit set for each of up to 7 cards. * @return the 8-or-better low value of <code>hand</code> or {@link #NO_8_LOW}. */ public static int hand8LowEval(long hand) { return loEvalOrNo8Low[ /* rotate each 13-bit suit field left to put Ace in LS bit */ ((((int)hand & 0x1FFF) << 1) + (((int)hand ^ 0x1000) >> 12)) | ((((int)hand >> 12) & 0x3FFE) + (((int)hand ^ (0x1000 << 13)) >> 25)) | (((int)(hand >> 25) & 0x3FFE) + (int)((hand ^ (0x1000L << 26)) >> 38)) | (((int)(hand >> 38) & 0x3FFE) + (int)((hand ^ (0x1000L << 39)) >> 51)) ]; } /** * Returns the 8-or-better low value of the best hand from hole cards and 3 board cards or {@link #NO_8_LOW}. * @param holeRanks bit mask of the rank(s) of hole cards (Ace is LS bit). * @param boardRanks bit mask of the rank(s) of board cards (Ace is LS bit). * @return the 8-or-better low value of the best hand from hole cards and 3 board cards or {@link #NO_8_LOW}. * @see #ranksMaskLo */ public static int Omaha8LowEval(int holeRanks, int boardRanks) { return loEvalOrNo8Low[lo3RanksMask[boardRanks & ~holeRanks] | holeRanks]; } // The following exports of accessors to arrays used by the // evaluation routines may be uncommented if needed. // /** // * Returns the parameter with all bits except its highest-order bit cleared. // * @param mask an int in the range 0..0x1FC0 (8128). // * @return the parameter with all bits except its highest-order bit cleared. // * @throws IndexOutOfBoundsException if mask < 0 || mask > 0x1FC0. // */ // public static int hiCardMask(int mask) // { // return hiRankMask[mask]; // } // // /** // * Returns the number of bits set in mask. // * @param mask an int in the range 0..0x1FC0 (8128). // * @return the number of bits set in mask. // * @throws IndexOutOfBoundsException if mask < 0 || mask > 0x1FC0. // */ // public static int numberOfRanks(int mask) // { // return nbrOfRanks[mask]; // } // // /** // * Returns the rank (2..14) corresponding to the high-order bit set in mask. // * @param mask an int in the range 0..0x1FC0 (8128). // * @return the rank (2..14) corresponding to the high-order bit set in mask. // * @throws IndexOutOfBoundsException if mask < 0 || mask > 0x1FC0. // */ // public static int rankOfHiCard(int mask) // { // return hiBotRank[mask] >> BOT_SHIFT; // } /** ********** Initialization ********************** */ private static final int ACE_RANK = 14; private static final int WHEEL = 0x0000100F; // A5432 // initializer block static { int mask, bitCount; int shiftReg, i; int value; for (mask = 1; mask < ARRAY_SIZE; ++mask) { bitCount = 0; shiftReg = mask; for (i = ACE_RANK - 1; i > 0; --i, shiftReg <<= 1) if ((shiftReg & 0x1000) != 0) switch (++bitCount) { case 1: hiTopRankTWO_PAIR[mask] = TWO_PAIR | ((i + 1) << TOP_SHIFT); hiBotRank[mask] = (i + 1) << BOT_SHIFT; hiRankMask[mask] = 0x1000 >> (ACE_RANK - 1 - i); break; case 2: hi2RanksMask[mask] = (shiftReg & 0x03FFF000) >> (ACE_RANK - 1 - i); break; case 3: hi3RanksMask[mask] = (shiftReg & 0x03FFF000) >> (ACE_RANK - 1 - i); break; case 5: hi5RanksMask[mask] = (shiftReg & 0x03FFF000) >> (ACE_RANK - 1 - i); } nbrOfRanks[mask] = bitCount; bitCount = 0; /* rotate the 13 bits left to get ace into LS bit */ /* we don't need to mask the low 13 bits of the result */ /* as we're going to look only at the low order 8 bits */ shiftReg = (mask << 1) + ((mask ^ 0x1000) >> 12); value = 0; for (i = 0; i < 8; ++i, shiftReg >>= 1) if ((shiftReg & 1) != 0) { value |= (1 << i); /* undo previous shifts, copy bit */ if (++bitCount == 5) { lo5RanksMask[mask] = value; break; } if (bitCount == 3) lo3RanksMask[mask] = value; } loEvalOrNo8Low[mask] = (bitCount == 5) ? value : NO_8_LOW; } for (mask = 0x1F00/* A..T */; mask >= 0x001F/* 6..2 */; mask >>= 1) setStraight(mask); setStraight(WHEEL); /* A,5..2 */ } private static void setStraight(int ts) { /* must call with ts from A..T to 5..A in that order */ int es, i, j; for (i = 0x1000; i > 0; i >>= 1) for (j = 0x1000; j > 0; j >>= 1) { es = ts | i | j; /* 5 straight bits plus up to two other bits */ if (straightValue[es] == 0) if (ts == WHEEL) straightValue[es] = STRAIGHT | (5 << BOT_SHIFT); else straightValue[es] = STRAIGHT | hiBotRank[ts]; } } }
923cd7473d1bff670c0267ef85d46d77d75e933a
11,982
java
Java
src/consultation/Consultation.java
Amayas29/CabinetMedical
dd11cd0b8713f9fb4347d8c86e459bc7cdde7f03
[ "MIT" ]
null
null
null
src/consultation/Consultation.java
Amayas29/CabinetMedical
dd11cd0b8713f9fb4347d8c86e459bc7cdde7f03
[ "MIT" ]
null
null
null
src/consultation/Consultation.java
Amayas29/CabinetMedical
dd11cd0b8713f9fb4347d8c86e459bc7cdde7f03
[ "MIT" ]
null
null
null
28.802885
172
0.671507
1,000,068
package consultation; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Vector; import dataBase.ConnexionOracle; import documents.Analyse; import documents.Bilan; import documents.Bon; import documents.CertificatMedical; import documents.Medicament; import documents.Ordannance; import maladies.MaladieNonChronique; import maladies.Symptome; import patient.Patient; /** * <h1> La classe de la consultation </h1> * <p> * <ul> * <li> son code qui est une concatenation entre la date et un numero sequentiel dans la journee </li> * <li> le code du patient </li> * <li> le nom du medecin </li> * <li> Un commentaire </li> * <li> Une liste de maladies diagnostiqueeees </li> * <li> Une liste de synmptomes </li> * <li> Un bon </li> * <li> Une ordonnance </li> * <li> Un bilan </li> * <li> Un certificat medical </li> * </ul> * </p> */ public class Consultation { private long codeConsu; private int codePatient; private String nomMedcin; private Vector<MaladieNonChronique> maladies; private Bon bon; private CertificatMedical certificatMedical; private Ordannance traitement; private Bilan bilan; private Vector<Symptome> symptomes; private String commentaire; public Consultation(int codePatient, String nomMedcin, String commentaire) { codeConsu = -1; this.codePatient = codePatient; this.nomMedcin = nomMedcin; this.commentaire = commentaire; maladies = null; bon = null; certificatMedical = null; traitement = null; bilan = null; symptomes = null; } /** * Enregister le bilan demandeee * @param analyses : Le vecteur des analyses */ public void demanderBilan(Vector<Analyse> analyses) { bilan = new Bilan(codeConsu, getDateConsu(), analyses); } /** * Enregister l'ordonnance * @param medic : le vecteur de meeedicaments prescrits */ public void fournirOrdannace(Vector<Medicament> medic) { traitement = new Ordannance(codeConsu,getDateConsu(), Patient.getPatient(codePatient), medic); } /*** * Enregister le certificat meeedical * @param obs : L'observation du certificat meeedical * @param type : le type du certificat meeedical (arreeet de travail, justificatif ...) */ public void fournirCertificatMedical(String obs, String type) { certificatMedical = new CertificatMedical(codeConsu, getDateConsu(), nomMedcin, obs, type); } /*** * Enregister le bon */ public void etablirBon(double montantTotal, double montantPaye) { bon = new Bon(getCodeConsu(), getDateConsu(), getCodePatient(), montantTotal, montantPaye); } /*** * Stocker la consultation ainsi que toutes les informations relatives (bon, ordonnance ...) dans la base de donneeees */ public void stocker() { String sql = "INSERT INTO Consultation Values(?,?,?,?)"; Connection connection = ConnexionOracle.connecteBD(); PreparedStatement requete; try { requete = connection.prepareStatement(sql); setCodeConsu(Consultation.genererCode()); requete.setString(1,String.valueOf(getCodeConsu())); requete.setString(2,String.valueOf(getCodePatient())); requete.setString(3,getNomMedcin()); requete.setString(4,getCommentaire()); requete.execute(); requete.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } setDrConsu(codePatient,getDateConsu()); if(bon != null) { bon.stocker(); } if(bilan != null) { bilan.stocker(); } if(traitement != null) { traitement.stocker(); } if(certificatMedical != null) { certificatMedical.stocker(); } if(symptomes != null) { for(int i = 0; i < symptomes.size(); i++) { symptomes.get(i).stocker(); } } if(maladies != null) { for(int i = 0; i < maladies.size(); i++) { maladies.get(i).stocker(); } } } /*** * Modifier la date de la derniere consultation pour le patient consulteee * @param codePatient * @param date */ public void setDrConsu(int codePatient,String date) { String sql = "UPDATE Patient set drConsu = ? WHERE code = ?"; Connection connection = ConnexionOracle.connecteBD(); PreparedStatement requete; try { requete = connection.prepareStatement(sql); requete.setString(1,date); requete.setString(2, String.valueOf(codePatient)); requete.execute(); requete.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } /*** * Retourner toutes les consultation d'un patient donneee par son code * @param codePatient * @return Vecteur de consultations */ public static Vector<Consultation> getConsultation(int codePatient) { Vector<Consultation> vec = new Vector<Consultation>(); String sql = "SELECT * FROM Consultation Where codePatient = ?"; Connection connection = ConnexionOracle.connecteBD(); PreparedStatement requete; ResultSet resultat; try { requete = connection.prepareStatement(sql); requete.setString(1, String.valueOf(codePatient)); resultat = requete.executeQuery(); while(resultat.next()) { Consultation consu = new Consultation(codePatient, resultat.getString("nomMedcin"), resultat.getString("commentaire")); consu.setCodeConsu(Long.valueOf(resultat.getString("codeConsu"))); consu.setMaladies(MaladieNonChronique.getMaladieNonChronique(consu.getCodeConsu())); consu.setBon(Bon.getBon(consu.getCodeConsu())); consu.setBilan(Bilan.getBilan(consu.getCodeConsu())); consu.setTraitement(Ordannance.getOrdannance(consu.getCodeConsu())); consu.setCertificatMedical(CertificatMedical.getCertificatMedical(consu.getCodeConsu())); vec.add(consu); } resultat.close(); requete.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } if(vec.isEmpty()) { vec = null; } return vec; } /*** * Retourner un objet consultation depuis la base de donnes * @param codeConsu * @return Une consulation */ public static Consultation getConsultation(long codeConsu) { Consultation consu = null; String sql = "SELECT * FROM Consultation Where codeConsu = ?"; Connection connection = ConnexionOracle.connecteBD(); PreparedStatement requete; ResultSet resultat; try { requete = connection.prepareStatement(sql); requete.setString(1, String.valueOf(codeConsu)); resultat = requete.executeQuery(); while(resultat.next()) { consu = new Consultation(Integer.valueOf(resultat.getString("codePatient")), resultat.getString("nomMedcin"), resultat.getString("commentaire")); consu.setCodeConsu(codeConsu); consu.setMaladies(MaladieNonChronique.getMaladieNonChronique(consu.getCodeConsu())); consu.setBon(Bon.getBon(consu.getCodeConsu())); consu.setBilan(Bilan.getBilan(consu.getCodeConsu())); consu.setTraitement(Ordannance.getOrdannance(consu.getCodeConsu())); consu.setCertificatMedical(CertificatMedical.getCertificatMedical(consu.getCodeConsu())); } resultat.close(); requete.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } return consu; } /*** * Retourne le nombre de consultation dans une date donneeee * @param date * @return int */ public static int getNombreConsultations(String date) { String sql = "SELECT count(codeConsu) as NB FROM Consultation Where codeConsu like '".concat(date).concat("%'"); Connection connection = ConnexionOracle.connecteBD(); PreparedStatement requete; ResultSet resultat; int nb = 0; try { requete = connection.prepareStatement(sql); resultat = requete.executeQuery(); if(resultat.next()) { nb = Integer.valueOf(resultat.getString("NB")); } resultat.close(); requete.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } return nb; } /*** * Generer le code de la consultation = date + numeeero sequentiel * @return code de consultation */ public static long genererCode() { Calendar cal = Calendar.getInstance(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); String s = df.format(cal.getTime()); String date = s.substring(0,2).concat(s.substring(3,5)).concat(s.substring(6,10)); long code = 0; if(date.charAt(0) == '0') { date = date.substring(1,date.length()); } String sql = "SELECT count(codeConsu) as NB, max(codeConsu) as MAX FROM Consultation WHERE codeConsu like '".concat(date).concat("%'"); Connection connection = ConnexionOracle.connecteBD(); PreparedStatement requete; ResultSet resultat; try { requete = connection.prepareStatement(sql); resultat = requete.executeQuery(); if(resultat.next() && !resultat.getString("NB").equals("0")) { s = resultat.getString("MAX"); } else { s = date.concat("001"); return Long.valueOf(s); } resultat.close(); requete.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } s = s.substring(s.length() - 3,s.length()); code = Long.valueOf(s) + 1; s = String.valueOf(code); while(s.length() != 3) { s = "0".concat(s); } s = date.concat(s); code = Long.valueOf(s); return code; } /*** * Imprimer touts les documents generer par la consultation */ public void imprimer() { if(getBon() != null) { getBon().imprimer(this); } if(getTraitement() != null) { getTraitement().imprimer(this); } if(getBilan() != null) { getBilan().imprimer(this); } if(getCertificatMedical() != null) { getCertificatMedical().imprimer(this); } } ////////////////////////////////////////////////////////////////////////// GETTERS ET SETTERS ////////////////////////////////////////////////////////////////////////// public long getCodeConsu() {return codeConsu;} public void setCodeConsu(long codeConsu) {this.codeConsu = codeConsu;} public int getCodePatient() {return codePatient;} public void setCodePatient(int codePatient) {this.codePatient = codePatient;} public String getNomMedcin() {return nomMedcin;} public void setNomMedcin(String nomMedcin) {this.nomMedcin = nomMedcin; } public String getDateConsu() { String date = String.valueOf(codeConsu).substring(0, String.valueOf(codeConsu).length() - 3); if(date.length() != 8) { date = "0".concat(date); } date = date.substring(0,2).concat("/").concat(date.substring(2,4)).concat("/").concat(date.substring(4,8)); return date; } public Bon getMontantPaye() {return bon;} public void setMontantPaye(Bon bon) {this.bon = bon;} public String getCommentaire() { return commentaire; } public void setCommentaire(String commentaire) { this.commentaire = commentaire; } public Bilan getBilan() {return bilan;} private void setBilan(Bilan bilan) { this.bilan = bilan;} public Bon getBon() { return bon; } private void setBon(Bon bon) { this.bon = bon;} public Vector<MaladieNonChronique> getMaladies() { return maladies; } public void setMaladies(Vector<MaladieNonChronique> maladies) { this.maladies = maladies; } public Vector<Symptome> getSymptomes() { return symptomes; } public void setSymptomes(Vector<Symptome> symptomes) { this.symptomes = symptomes; } public CertificatMedical getCertificatMedical() { return certificatMedical; } private void setCertificatMedical(CertificatMedical certificatMedical) { this.certificatMedical = certificatMedical; } public Ordannance getTraitement() { return traitement; } private void setTraitement(Ordannance traitement) { this.traitement = traitement; } }
923cd784d25f52c0256d79d17b6dad8ce029b890
7,267
java
Java
src/main/java/cn/mmf/slashblade_tic/client/book/ContentBladeModifier.java
soybean1998/TinkerSlashBlade
8e918cac797c766229765ac0805afcfd83f8518a
[ "MIT" ]
9
2019-02-17T07:46:59.000Z
2020-02-02T08:21:15.000Z
src/main/java/cn/mmf/slashblade_tic/client/book/ContentBladeModifier.java
soybean1998/TinkerSlashBlade
8e918cac797c766229765ac0805afcfd83f8518a
[ "MIT" ]
9
2019-02-21T20:53:07.000Z
2022-01-18T20:17:53.000Z
src/main/java/cn/mmf/slashblade_tic/client/book/ContentBladeModifier.java
soybean1998/TinkerSlashBlade
8e918cac797c766229765ac0805afcfd83f8518a
[ "MIT" ]
5
2019-03-04T07:44:56.000Z
2020-08-15T05:13:16.000Z
37.076531
152
0.605339
1,000,069
package cn.mmf.slashblade_tic.client.book; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.gson.annotations.SerializedName; import cn.mmf.slashblade_tic.blade.SlashBladeCore; import cn.mmf.slashblade_tic.item.RegisterLoader; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.oredict.OreDictionary; import slimeknights.mantle.client.book.data.BookData; import slimeknights.mantle.client.book.data.element.ImageData; import slimeknights.mantle.client.book.data.element.TextData; import slimeknights.mantle.client.gui.book.GuiBook; import slimeknights.mantle.client.gui.book.element.BookElement; import slimeknights.mantle.client.gui.book.element.ElementImage; import slimeknights.mantle.client.gui.book.element.ElementText; import slimeknights.mantle.util.ItemStackList; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.library.book.TinkerPage; import slimeknights.tconstruct.library.book.elements.ElementTinkerItem; import slimeknights.tconstruct.library.client.CustomFontColor; import slimeknights.tconstruct.library.materials.Material; import slimeknights.tconstruct.library.modifiers.IModifier; import slimeknights.tconstruct.library.modifiers.IModifierDisplay; import slimeknights.tconstruct.tools.TinkerMaterials; import slimeknights.tconstruct.tools.TinkerModifiers; import java.util.ArrayList; import java.util.List; import static slimeknights.tconstruct.library.book.content.ContentModifier.*; public class ContentBladeModifier extends TinkerPage { public static final transient String ID = "blademodifier"; private transient IModifier modifier; private transient List<Item> blade; public TextData[] text; public String[] effects; @SerializedName("blademodifier") public String modifierName; public ContentBladeModifier() {} public ContentBladeModifier(IModifier modifier) { this.modifier = modifier; this.modifierName = modifier.getIdentifier(); } @Override public void load() { if(modifierName == null) { modifierName = parent.name; } if(modifier == null) { modifier = TinkerRegistry.getModifier(modifierName); } if(blade == null) { blade = Lists.newArrayList(); blade.add(RegisterLoader.sb); blade.add(RegisterLoader.sb_white); } } @Override public void build(BookData book, ArrayList<BookElement> list, boolean rightSide) { if(modifier == null) { TinkerModifiers.log.error("Modifier " + modifierName + " not found"); return; } int color = 0xdddddd; int inCount = 1; ItemStack[][] inputItems = null; if(modifier instanceof IModifierDisplay) { IModifierDisplay modifierDisplay = (IModifierDisplay) modifier; color = modifierDisplay.getColor(); List<List<ItemStack>> inputList = modifierDisplay.getItems(); inputItems = new ItemStack[5][]; for(int i = 0; i < 5; i++) { inputItems[i] = new ItemStack[inputList.size()]; for(int j = 0; j < inputItems[i].length; j++) { inputItems[i][j] = ItemStack.EMPTY; } } for(int i = 0; i < inputList.size(); i++) { List<ItemStack> inputs = new ArrayList<>(inputList.get(i)); if(inputs.size() > inCount) { inCount = inputs.size(); } for(int j = 0; j < inputs.size() && j < 5; j++) { ItemStack stack = inputs.get(j); if(!stack.isEmpty() && stack.getMetadata() == OreDictionary.WILDCARD_VALUE) { stack = stack.copy(); stack.setItemDamage(0); } inputItems[j][i] = stack; } } } addTitle(list, CustomFontColor.encodeColor(color) + modifier.getLocalizedName(), true); // description int h = GuiBook.PAGE_WIDTH / 3 - 10; list.add(new ElementText(10, 20, GuiBook.PAGE_WIDTH - 20, h, text)); if(effects.length > 0) { TextData head = new TextData(parent.translate("modifier.effect")); head.underlined = true; list.add(new ElementText(10, 20 + h, GuiBook.PAGE_WIDTH / 2 - 5, GuiBook.PAGE_HEIGHT - h - 20, head)); List<TextData> effectData = Lists.newArrayList(); for(String e : effects) { effectData.add(new TextData("\u25CF ")); effectData.add(new TextData(e)); effectData.add(new TextData("\n")); } list.add(new ElementText(10, 30 + h, GuiBook.PAGE_WIDTH / 2 + 5, GuiBook.PAGE_HEIGHT - h - 20, effectData)); } ImageData img; switch(inCount) { case 1: img = IMG_SLOT_1; break; case 2: img = IMG_SLOT_2; break; case 3: img = IMG_SLOT_3; break; default: img = IMG_SLOT_5; } int imgX = GuiBook.PAGE_WIDTH / 2 + 20; int imgY = GuiBook.PAGE_HEIGHT / 2 + 30; imgX = imgX + 29 - img.width / 2; imgY = imgY + 20 - img.height / 2; int[] slotX = new int[]{3, 21, 39, 12, 30}; int[] slotY = new int[]{3, 3, 3, 22, 22}; list.add(new ElementImage(imgX + (img.width - IMG_TABLE.width) / 2, imgY - 24, -1, -1, IMG_TABLE)); list.add(new ElementImage(imgX, imgY, -1, -1, img, book.appearance.slotColor)); ItemStackList demo = getDemoBlade(inputItems); ElementTinkerItem toolItem = new ElementTinkerItem(imgX + (img.width - 16) / 2, imgY - 24, 1f, demo); toolItem.noTooltip = true; list.add(toolItem); list.add(new ElementImage(imgX + (img.width - 22) / 2, imgY - 27, -1, -1, IMG_SLOT_1, 0xffffff)); if(inputItems != null) { for(int i = 0; i < inCount && i < 5; i++) { list.add(new ElementTinkerItem(imgX + slotX[i], imgY + slotY[i], 1f, inputItems[i])); } } } protected ItemStackList getDemoBlade(ItemStack[][] inputItems) { ItemStackList demo = ItemStackList.withSize(blade.size()); for(int i = 0; i < blade.size(); i++) { if(blade.get(i) instanceof SlashBladeCore) { SlashBladeCore core = (SlashBladeCore) blade.get(i); List<Material> mats = ImmutableList.of(TinkerMaterials.wood, TinkerMaterials.cobalt, TinkerMaterials.ardite, TinkerMaterials.manyullyn); mats = mats.subList(0, core.getRequiredComponents().size()); demo.set(i, ((SlashBladeCore) blade.get(i)).buildItemForRendering(mats)); } else if(blade != null) { demo.set(i, new ItemStack(blade.get(i))); } if(!demo.get(i).isEmpty()) { modifier.apply(demo.get(i)); } } return demo; } }
923cd7e14b95ffc8914f6d50d01b9580889ec831
3,493
java
Java
enhanced/archive/classlib/java6/modules/jndi/src/test/java/org/apache/harmony/jndi/tests/javax/naming/spi/mock/ldap/MockUnsolicitedNotification.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
5
2017-03-08T20:32:39.000Z
2021-07-10T10:12:38.000Z
enhanced/archive/classlib/java6/modules/jndi/src/test/java/org/apache/harmony/jndi/tests/javax/naming/spi/mock/ldap/MockUnsolicitedNotification.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
null
null
null
enhanced/archive/classlib/java6/modules/jndi/src/test/java/org/apache/harmony/jndi/tests/javax/naming/spi/mock/ldap/MockUnsolicitedNotification.java
qinFamily/freeVM
9caa0256b4089d74186f84b8fb2afc95a0afc7bc
[ "Apache-2.0" ]
4
2015-07-07T07:06:59.000Z
2018-06-19T22:38:04.000Z
26.869231
131
0.714572
1,000,070
/* * 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. */ /** * @author Hugo Beilis * @author Leonardo Soler * @author Gabriel Miretti * @version 1.0 */ package org.apache.harmony.jndi.tests.javax.naming.spi.mock.ldap; import javax.naming.NamingException; import javax.naming.event.NamingExceptionEvent; import javax.naming.ldap.Control; import javax.naming.ldap.UnsolicitedNotification; import javax.naming.ldap.UnsolicitedNotificationEvent; import javax.naming.ldap.UnsolicitedNotificationListener; /** * <p>Implementation of the interfaces UnsolicitedNotificationListener and UnsolicitedNotification. This class has the intention of * give us a notifiction or a listener to test another classes.</p> * */ public class MockUnsolicitedNotification implements UnsolicitedNotificationListener, UnsolicitedNotification { /** * @serialField Serial of the class. */ private static final long serialVersionUID = 1L; /** * <p>This flag has the intention of give us a way to know if a notification was recived.</p> */ private boolean flag; /** * <p>Constructor method of this mock, here we call the inherit constructor and also we initialized the rest of fields.</p> * */ public MockUnsolicitedNotification() { super(); flag=false;//Flag to know if a the notification was recived. } /** * <p>Here we recived the notification, so we set the flag true.</p> */ public void notificationReceived(UnsolicitedNotificationEvent arg0) { flag=true; } /** * <p>Method to see if the notitfication was recived.</p> * @return The flag of the notification. */ public boolean getFlag(){ return flag; } /** * <p>Method not implemented yet.</p> */ public void namingExceptionThrown(NamingExceptionEvent arg0) { // TODO Auto-generated method stub } /** * <p>Method not implemented yet.</p> */ public String[] getReferrals() { // TODO Auto-generated method stub return null; } /** * <p>Method not implemented yet.</p> */ public NamingException getException() { // TODO Auto-generated method stub return null; } /** * <p>Method not implemented yet.</p> */ public String getID() { // TODO Auto-generated method stub return null; } /** * <p>Method implemented for testing serialization on UnsolicitedNotificationEvent.</p> */ public long getIDSerial() { // TODO Auto-generated method stub return this.serialVersionUID; } /** * <p>Method not implemented yet.</p> */ public byte[] getEncodedValue() { // TODO Auto-generated method stub return null; } /** * <p>Method not implemented yet.</p> */ public Control[] getControls() throws NamingException { // TODO Auto-generated method stub return null; } }
923cd842ebd6f3c70ea0f2244470711724ab6dbe
513
java
Java
sdl_android/src/main/java/com/smartdevicelink/proxy/rpc/enums/TurnSignal.java
NathanYuchi/FordRealFiesta
cdf71464801267a17e5abecd94944b25ce65834e
[ "BSD-3-Clause" ]
1
2019-02-28T01:17:03.000Z
2019-02-28T01:17:03.000Z
sdl_android/src/main/java/com/smartdevicelink/proxy/rpc/enums/TurnSignal.java
NathanYuchi/FordRealFiesta
cdf71464801267a17e5abecd94944b25ce65834e
[ "BSD-3-Clause" ]
null
null
null
sdl_android/src/main/java/com/smartdevicelink/proxy/rpc/enums/TurnSignal.java
NathanYuchi/FordRealFiesta
cdf71464801267a17e5abecd94944b25ce65834e
[ "BSD-3-Clause" ]
null
null
null
14.25
69
0.633528
1,000,071
package com.smartdevicelink.proxy.rpc.enums; /** * Enumeration that describes the status of the turn light indicator. * * @since SmartDeviceLink 5.0 */ public enum TurnSignal { /** * Turn signal is OFF */ OFF, /** * Left turn signal is on */ LEFT, /** * Right turn signal is on */ RIGHT, /** * Both signals (left and right) are on. */ BOTH, ; public static TurnSignal valueForString(String value) { try{ return valueOf(value); }catch(Exception e){ return null; } } }
923cd8ed999c6739cac4a22148a4e2e1ebcc511d
4,376
java
Java
plain-java/src/main/java/be/enabling/callbackplayground/mockbin/MockbinPoller.java
Enabling/callback-playground
3b197c1e2e16048ea5c1c8e8f64077a8eef43015
[ "BSD-2-Clause" ]
null
null
null
plain-java/src/main/java/be/enabling/callbackplayground/mockbin/MockbinPoller.java
Enabling/callback-playground
3b197c1e2e16048ea5c1c8e8f64077a8eef43015
[ "BSD-2-Clause" ]
null
null
null
plain-java/src/main/java/be/enabling/callbackplayground/mockbin/MockbinPoller.java
Enabling/callback-playground
3b197c1e2e16048ea5c1c8e8f64077a8eef43015
[ "BSD-2-Clause" ]
null
null
null
34.730159
116
0.646481
1,000,072
package be.enabling.callbackplayground.mockbin; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONObject; import be.enabling.callbackplayground.dto.CallbackDataDTO; import be.enabling.callbackplayground.service.CallbackDataSaver; import be.enabling.callbackplayground.service.PropertiesHolder; import com.fasterxml.jackson.databind.ObjectMapper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; public class MockbinPoller { private static final String TIMER_NAME = "MOCKBIN_POLLER_TIMER"; private static final Log LOG = LogFactory.getLog(MockbinPoller.class); private String mockbinId; private Timer timer; private boolean initialized = false; public MockbinPoller() { this.mockbinId = PropertiesHolder.INSTANCE.getMockbinId(); // Starting timer as non-daemon keeps main thread from exiting final boolean runTimerAsDaemon = false; this.timer = new Timer(TIMER_NAME, runTimerAsDaemon); } synchronized void init() { if(initialized) { throw new IllegalStateException("Poller was already initialized"); } if (mockbinId == null) { throw new NullPointerException("MockbinId cannot be null as it is used to retrieve callback data"); } final long delay = 0L; final long periodInMs = PropertiesHolder.INSTANCE.getPollPeriodInMs(); initializeRepo(); timer.schedule(new PollTask(), delay, periodInMs); this.initialized = true; } private void initializeRepo() { final List<CallbackDataDTO> allCallbackData = getAllCallbackData(); saver.initialize(allCallbackData); } protected void poll() { final List<CallbackDataDTO> allCallbackData = getAllCallbackData(); saveData(allCallbackData); } private List<CallbackDataDTO> getAllCallbackData() { final List<CallbackDataDTO> deserializedObjects = new ArrayList<CallbackDataDTO>(); try { final HttpResponse<JsonNode> reponse = Unirest.get("http://mockbin.org/bin/{id}/log") .routeParam("id", mockbinId).asJson(); final JsonNode json = reponse.getBody(); final JSONArray entriesAsJson = json.getObject().getJSONObject("log").getJSONArray("entries"); for (int i = 0; i < entriesAsJson.length(); i++) { try { final JSONObject entryJson = entriesAsJson.getJSONObject(i); final boolean isDeserializableRequest = "POST".equals(entryJson.getJSONObject("request") .optString("method").toUpperCase()); if (!isDeserializableRequest) { continue; } // Callback data as a String is stored under // /log//entries/request/postData/text final String callbackDataAsString = entryJson.getJSONObject("request").getJSONObject("postData") .optString("text"); ObjectMapper mapper = new ObjectMapper(); final CallbackDataDTO mappedCallbackResult = mapper.readValue(callbackDataAsString, CallbackDataDTO.class); deserializedObjects.add(mappedCallbackResult); } catch (Exception ex) { LOG.error("Something went wrong when deserializing current entry at index " + i, ex); } } } catch (UnirestException e) { LOG.error("Error occurred during polling", e); } return deserializedObjects; } private void saveData(final List<CallbackDataDTO> allCallbackData) { saver.insertBulk(allCallbackData); } private class PollTask extends TimerTask { @Override public void run() { poll(); } } public void setDataSaver(CallbackDataSaver saver) { this.saver = saver; } private CallbackDataSaver saver; }
923cd8f15b3d57e196788afb472d9be41f6bb245
2,972
java
Java
core/src/sen/khyber/scramble/OptionsStage.java
kkysen/Scramble
06f89c8cb8f3706e065beef01d76597c80ef3f86
[ "Apache-2.0" ]
null
null
null
core/src/sen/khyber/scramble/OptionsStage.java
kkysen/Scramble
06f89c8cb8f3706e065beef01d76597c80ef3f86
[ "Apache-2.0" ]
null
null
null
core/src/sen/khyber/scramble/OptionsStage.java
kkysen/Scramble
06f89c8cb8f3706e065beef01d76597c80ef3f86
[ "Apache-2.0" ]
null
null
null
34.16092
95
0.621803
1,000,073
package sen.khyber.scramble; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox.CheckBoxStyle; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; /** * * * @author Khyber Sen */ public class OptionsStage extends FitStage { private final Label scrambleLabel; private final IntField boardSizeInput; private final TextButton playButton; private final CheckBox isTimedCheckBox; public OptionsStage(final Batch batch, final StageScreen<? extends OptionsStage> screen) { super(batch, screen); final Skin skin = Skins.get(); final float width = getWidth(); final float height = getHeight(); scrambleLabel = new Label("Scramble", skin.get("labelStyle", LabelStyle.class)); scrambleLabel.setBounds(width * .4f, height * .7f, width * .9f, height * .1f); addActor(scrambleLabel); boardSizeInput = new IntField("Board Size", skin.get("textFieldStyle", TextFieldStyle.class)); boardSizeInput.setBounds(width * .4f, height * .5f, width * .2f, height * .1f); addActor(boardSizeInput); playButton = new TextButton("Play", skin.get("textButtonStyle", TextButtonStyle.class)); playButton.setBounds(width * .4f, height * .3f, width * .2f, height * .1f); addActor(playButton); isTimedCheckBox = new CheckBox("Timed Game", skin.get("isTimedCheckBoxStyle", CheckBoxStyle.class)); isTimedCheckBox.setBounds(width * .4f, height * .15f, width * .2f, height * .1f); addActor(isTimedCheckBox); isTimedCheckBox.setChecked(true); System.out.println(scrambleLabel); System.out.println(boardSizeInput); System.out.println(playButton); System.out.println(isTimedCheckBox); } @Override public boolean isFinished() { return playButton.isPressed(); } public int getBoardSize() { return boardSizeInput.getInt(); } public boolean isTimed() { return isTimedCheckBox.isChecked(); } public void uncheckPlayButton() { playButton.getClickListener().cancel(); } @Override public void draw() { if (screen.getFrameNum() == 0) { System.out.println("drawing label"); batch.begin(); scrambleLabel.draw(batch, 1); batch.end(); } super.draw(); } }
923cd9183473b5834115858d7388c6042ad267d0
9,331
java
Java
acm/src/main/java/com/wuba/acm/test/Solution.java
devilsen/LittleTest
05ac9c580b6d454b28dbf0752bc9a47d65628a37
[ "Apache-2.0" ]
null
null
null
acm/src/main/java/com/wuba/acm/test/Solution.java
devilsen/LittleTest
05ac9c580b6d454b28dbf0752bc9a47d65628a37
[ "Apache-2.0" ]
null
null
null
acm/src/main/java/com/wuba/acm/test/Solution.java
devilsen/LittleTest
05ac9c580b6d454b28dbf0752bc9a47d65628a37
[ "Apache-2.0" ]
1
2020-11-05T09:30:33.000Z
2020-11-05T09:30:33.000Z
28.275758
121
0.434144
1,000,074
package com.wuba.acm.test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * desc : * date : 2018/12/10 * * @author : dongSen */ public class Solution { public static void main(String[] args) { Solution solution = new Solution(); // ListNode listNode = new ListNode(1); // listNode.next = new ListNode(2); // listNode.next.next = new ListNode(3); // listNode.next.next.next = new ListNode(4); // listNode.next.next.next.next = new ListNode(5); // int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] matrix = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} }; // int[][] matrix = { // {1, 2, 3, 4, 5, 6}, // {7, 8, 9, 10, 11, 12}, // {13, 14, 15, 16, 17, 18}, // {19, 20, 21, 22, 23, 24}, // {25, 26, 27, 28, 29, 30}, // {31, 32, 33, 34, 35, 36} // }; // solution.rotate(matrix); // String[] a = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"}; // List<List<String>> lists = solution.groupAnagrams(a); // // for (List<String> b : lists) { // for (String c : b) { // System.out.print(c + " "); // } // System.out.println(); // } int[] a = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; int v = solution.maxSubArray(a); System.out.println(v); } public int maxSubArray(int[] nums) { if (nums == null || nums.length == 0) return 0; int sum = 0, max = Integer.MIN_VALUE; for (int num: nums) { sum += num; max = Math.max(max, sum); if (sum < 0) sum = 0; } return max; } public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> map = new HashMap<>(); for (String str : strs) { String code = getCode(str); List<String> strings = map.get(code); if (strings == null) { strings = new ArrayList<>(); strings.add(str); map.put(code, strings); } else { strings.add(str); } } return new ArrayList<>(map.values()); } private String getCode(String s) { char[] ca = s.toCharArray(); Arrays.sort(ca); return String.valueOf(ca); } public void rotate(int[][] matrix) { int x = 0; int y = 0; int n = matrix[0].length - 1; int time = n; for (int j = 0; j < matrix[0].length / 2; j++) { for (int i = 0; i < time; i++) { int temp1 = matrix[x][y + i]; int temp2 = matrix[x + i][n]; int temp3 = matrix[n][n - i]; int temp4 = matrix[n - i][y]; matrix[x][y + i] = temp4; matrix[x + i][n] = temp1; matrix[n][n - i] = temp2; matrix[n - i][y] = temp3; } x++; y++; n--; time = time - 2; } } public List<List<Integer>> permute(int[] nums) { Arrays.sort(nums); ArrayList<List<Integer>> lists = new ArrayList<>(); boolean[] used = new boolean[nums.length]; dfs(nums, used, new ArrayList<Integer>(), lists); return lists; } public void dfs(int[] nums, boolean[] used, List<Integer> list, List<List<Integer>> res) { if (list.size() == nums.length) { res.add(new ArrayList<>(list)); return; } for (int i = 0; i < nums.length; i++) { // if (used[i]) continue; // if (i > 0 && nums[i - 1] == nums[i] && !used[i - 1]) continue; used[i] = true; list.add(nums[i]); dfs(nums, used, list, res); used[i] = false; list.remove(list.size() - 1); } } private void printList(String name, List<Integer> cur) { System.out.println(name); for (Integer i : cur) { System.out.print(i + " "); } System.out.println(); } public String multiply(String num1, String num2) { if ("0".equals(num1) || "0".equals(num2)) return "0"; int[] numArray1 = new int[num1.length()]; int[] numArray2 = new int[num2.length()]; for (int i = 0; i < num1.length(); i++) { int c = num1.charAt(i) - 48; numArray1[i] = c; } for (int i = 0; i < num2.length(); i++) { int c = num2.charAt(i) - 48; numArray2[i] = c; } int length = numArray1.length + numArray2.length; int[][] bList = new int[numArray1.length][length]; int aIndex = 0; for (int i = numArray1.length - 1; i >= 0; i--) { int a = numArray1[i]; int[] aList = new int[length]; int index = length - 1 - aIndex; int last = 0; for (int j = numArray2.length - 1; j >= 0; j--) { int b = numArray2[j]; int muti = a * b + last; if (muti > 9) { last = muti / 10; } else { last = 0; } aList[index] = muti % 10; index--; } if (last > 0) aList[index] = last; bList[aIndex] = aList; aIndex++; } int[] cList = new int[length]; for (int i = 0; i < bList.length; i++) { int[] integers = bList[i]; int last = 0; for (int j = integers.length - 1; j >= 0; j--) { int add = integers[j] + cList[j] + last; if (add > 9) { last = add / 10; } else { last = 0; } cList[j] = add % 10; } } StringBuilder stringBuilder = new StringBuilder(); for (int aCList : cList) { stringBuilder.append(aCList); } String result = stringBuilder.toString(); if (result.startsWith("0")) { result = result.substring(1); } return result; } public List<List<Integer>> combinationSum(int[] nums, int target) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(nums); backtrack(list, new ArrayList<Integer>(), nums, target, 0); return list; } private void backtrack(List<List<Integer>> list, ArrayList<Integer> tempList, int[] nums, int remain, int start) { if (remain < 0) return; else if (remain == 0) list.add(new ArrayList<>(tempList)); else { for (int i = start; i < nums.length; i++) { if (i > 0 && i != start && nums[i] == nums[i - 1]) continue; tempList.add(nums[i]); backtrack(list, tempList, nums, remain - nums[i], i + 1); // not i + 1 because we can reuse same elements tempList.remove(tempList.size() - 1); } } } private List<List<String>> lists = new ArrayList<>(); private int[] result; public List<List<String>> solveNQueens(int n) { result = new int[n]; nQueen(0, n); return lists; } private void nQueen(int row, int n) { if (row == n) { printList(n); return; } for (int i = 0; i < n; i++) { if (isOk(row, i, n)) { result[row] = i; nQueen(row + 1, n); } } } private void printList(int n) { ArrayList<String> temp2 = new ArrayList<>(); for (int i = 0; i < n; i++) { StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < n; j++) { if (result[i] == j) { stringBuilder.append("Q"); } else { stringBuilder.append("."); } } temp2.add(stringBuilder.toString()); } lists.add(temp2); } private boolean isOk(int row, int column, int n) { int leftUp = column - 1; int rightUp = column + 1; for (int check = row - 1; check >= 0; check--) { if (result[check] == column) { return false; } if (leftUp >= 0 && result[check] == leftUp) { return false; } if (rightUp < n && result[check] == rightUp) { return false; } leftUp--; rightUp++; } return true; } private void print(int[] nums) { for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
923cd94142de072b479d8bb80aa2ebd1374e28df
485
java
Java
src/main/java/kr/hs/entrydsm/rollsroyce/domain/user/exception/AuthCodeAlreadyVerifiedException.java
EntryDSM/Rolls-Royce
41591aab6facee222748f6fb2ae70ad68df2f152
[ "MIT" ]
1
2021-11-02T09:54:43.000Z
2021-11-02T09:54:43.000Z
src/main/java/kr/hs/entrydsm/rollsroyce/domain/user/exception/AuthCodeAlreadyVerifiedException.java
EntryDSM/Rolls-Royce
41591aab6facee222748f6fb2ae70ad68df2f152
[ "MIT" ]
113
2021-10-30T03:26:32.000Z
2022-03-30T01:48:32.000Z
src/main/java/kr/hs/entrydsm/rollsroyce/domain/user/exception/AuthCodeAlreadyVerifiedException.java
EntryDSM/Rolls-Royce
41591aab6facee222748f6fb2ae70ad68df2f152
[ "MIT" ]
null
null
null
30.3125
71
0.793814
1,000,075
package kr.hs.entrydsm.rollsroyce.domain.user.exception; import kr.hs.entrydsm.rollsroyce.global.error.exception.ErrorCode; import kr.hs.entrydsm.rollsroyce.global.error.exception.RollsException; public class AuthCodeAlreadyVerifiedException extends RollsException { public static final RollsException EXCEPTION = new AuthCodeAlreadyVerifiedException(); private AuthCodeAlreadyVerifiedException() { super(ErrorCode.AUTH_CODE_ALREADY_VERIFIED); } }
923cda39a4e695b2972a8fa3b99b9748183edd3f
84
java
Java
src/com/crazicrafter1/siege/game/team/invader/Invader.java
PeriodicSeizures/Siege
9f1e838ff97e8dfb7c635e040a37c66a373dbb49
[ "MIT" ]
null
null
null
src/com/crazicrafter1/siege/game/team/invader/Invader.java
PeriodicSeizures/Siege
9f1e838ff97e8dfb7c635e040a37c66a373dbb49
[ "MIT" ]
null
null
null
src/com/crazicrafter1/siege/game/team/invader/Invader.java
PeriodicSeizures/Siege
9f1e838ff97e8dfb7c635e040a37c66a373dbb49
[ "MIT" ]
null
null
null
10.5
50
0.77381
1,000,076
package com.crazicrafter1.siege.game.team.invader; public interface Invader { }
923cda4bb29c695ee51918c792b8179d297ffa69
1,171
java
Java
app/src/main/java/org/kazemicode/parstagram/Post.java
kazemicode/parstagram
ac5a2434014847b9d46a53d5479d498016a978c8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/org/kazemicode/parstagram/Post.java
kazemicode/parstagram
ac5a2434014847b9d46a53d5479d498016a978c8
[ "Apache-2.0" ]
1
2020-10-23T07:57:13.000Z
2020-11-01T07:32:40.000Z
app/src/main/java/org/kazemicode/parstagram/Post.java
kazemicode/parstagram
ac5a2434014847b9d46a53d5479d498016a978c8
[ "Apache-2.0" ]
null
null
null
22.960784
65
0.690863
1,000,077
package org.kazemicode.parstagram; import com.parse.ParseFile; import com.parse.ParseObject; import com.parse.ParseClassName; import com.parse.ParseUser; @ParseClassName("Post") public class Post extends ParseObject { // Ensure that your subclass has a public default constructor public static final String KEY_DESCRIPTION = "description"; public static final String KEY_USERNAME = "username"; public static final String KEY_IMAGE = "image"; public static final String KEY_CREATED_AT = "createdAt"; public Post() { } public ParseUser getUsername() { return getParseUser(KEY_USERNAME); } public String getDescription() { return getString(KEY_DESCRIPTION); } public ParseFile getImage() { return getParseFile(KEY_IMAGE); } public void setUsername(ParseUser username) { put(KEY_USERNAME, username); } public void setDescription(String description) { put(KEY_DESCRIPTION, description); } public void setImage(ParseFile image) { put(KEY_IMAGE, image); } public ParseUser getUser() { return getParseUser(KEY_USERNAME); } }
923cda92698a46fc2d24c9a30a834204b352b143
462
java
Java
src/test/java/com/sapbasu/cucumberseed/runner/CucumberSeedApplicationTests.java
saptarshibasu/cucumber-selenium-seed
4707de849e26674fa3cc4868218c949fb2fd186a
[ "Apache-2.0" ]
null
null
null
src/test/java/com/sapbasu/cucumberseed/runner/CucumberSeedApplicationTests.java
saptarshibasu/cucumber-selenium-seed
4707de849e26674fa3cc4868218c949fb2fd186a
[ "Apache-2.0" ]
null
null
null
src/test/java/com/sapbasu/cucumberseed/runner/CucumberSeedApplicationTests.java
saptarshibasu/cucumber-selenium-seed
4707de849e26674fa3cc4868218c949fb2fd186a
[ "Apache-2.0" ]
null
null
null
28.875
94
0.790043
1,000,078
package com.sapbasu.cucumberseed.runner; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions(features = "src/test/features", glue = "com.sapbasu.cucumberseed", plugin = { "pretty", "html:target/cucumber-reports"}, monochrome = true) @SpringBootTest public class CucumberSeedApplicationTests { }
923cdbcf346f946ac0604a096601fff03546fae4
772
java
Java
week4-079.NumberStatistics/src/NumberStatistics.java
Warglaive/JavaBasicsFontysVenlo
49ba0ab5e20d2c9ca86cb3cc4cdafa0eb527988c
[ "Apache-2.0" ]
null
null
null
week4-079.NumberStatistics/src/NumberStatistics.java
Warglaive/JavaBasicsFontysVenlo
49ba0ab5e20d2c9ca86cb3cc4cdafa0eb527988c
[ "Apache-2.0" ]
null
null
null
week4-079.NumberStatistics/src/NumberStatistics.java
Warglaive/JavaBasicsFontysVenlo
49ba0ab5e20d2c9ca86cb3cc4cdafa0eb527988c
[ "Apache-2.0" ]
null
null
null
20.315789
58
0.569948
1,000,079
import java.util.ArrayList; public class NumberStatistics { private int amountOfNumbers; private ArrayList<Integer> numbers; public NumberStatistics() { this.amountOfNumbers = 0; this.numbers = new ArrayList<Integer>(); } public void addNumber(int number) { this.amountOfNumbers++; this.numbers.add(number); } public int amountOfNumbers() { return this.amountOfNumbers; } public int sum() { int sum = 0; for (Integer number : numbers) { sum += number; } return sum; } public double average() { if (this.amountOfNumbers == 0) { return 0.0; } return (double) this.sum() / this.amountOfNumbers; } }
923cdbfc5a230534fd88df16d8b14d0829aba9d0
3,032
java
Java
support/pva/src/main/java/org/diirt/support/pva/adapters/PVFieldToVShortArray.java
diirt/diirt
6070306dd321e95dc6ca15e9c04903fae7b595a9
[ "MIT" ]
12
2015-03-24T19:11:36.000Z
2021-08-14T11:48:05.000Z
support/pva/src/main/java/org/diirt/support/pva/adapters/PVFieldToVShortArray.java
diirt/diirt
6070306dd321e95dc6ca15e9c04903fae7b595a9
[ "MIT" ]
36
2015-01-20T14:37:30.000Z
2022-02-16T00:55:15.000Z
support/pva/src/main/java/org/diirt/support/pva/adapters/PVFieldToVShortArray.java
diirt/diirt
6070306dd321e95dc6ca15e9c04903fae7b595a9
[ "MIT" ]
13
2015-01-13T00:17:43.000Z
2018-07-03T10:57:08.000Z
30.938776
98
0.596306
1,000,080
/** * Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.diirt.support.pva.adapters; import java.util.List; import org.epics.pvdata.pv.PVField; import org.epics.pvdata.pv.PVShortArray; import org.epics.pvdata.pv.PVStructure; import org.epics.pvdata.pv.PVUShortArray; import org.epics.pvdata.pv.ShortArrayData; import org.diirt.vtype.VShortArray; import org.diirt.vtype.VTypeToString; import org.diirt.util.array.ArrayInt; import org.diirt.util.array.ArrayShort; import org.diirt.util.array.ListInt; import org.diirt.util.array.ListShort; import org.diirt.vtype.ArrayDimensionDisplay; import org.diirt.vtype.ValueUtil; /** * @author msekoranja * */ public class PVFieldToVShortArray extends AlarmTimeDisplayExtractor implements VShortArray { private final ListInt size; private final ListShort list; public PVFieldToVShortArray(PVStructure pvField, boolean disconnected) { this("value", pvField, disconnected); } public PVFieldToVShortArray(String fieldName, PVStructure pvField, boolean disconnected) { this(pvField.getSubField(fieldName), pvField, disconnected); } public PVFieldToVShortArray(PVField field, PVStructure pvParent, boolean disconnected) { super(pvParent, disconnected); if (field instanceof PVShortArray) { PVShortArray valueField = (PVShortArray)field; ShortArrayData data = new ShortArrayData(); valueField.get(0, valueField.getLength(), data); this.size = new ArrayInt(data.data.length); this.list = new ArrayShort(data.data); } else if (field instanceof PVUShortArray) { PVUShortArray valueField = (PVUShortArray)field; ShortArrayData data = new ShortArrayData(); valueField.get(0, valueField.getLength(), data); this.size = new ArrayInt(data.data.length); this.list = new ArrayShort(data.data); } else { size = null; list = null; } } /* (non-Javadoc) * @see org.epics.pvmanager.data.Array#getSizes() */ @Override public ListInt getSizes() { return size; } /* (non-Javadoc) * @see org.epics.pvmanager.data.VShortArray#getData() */ @Override public ListShort getData() { return list; } @Override public String toString() { return VTypeToString.toString(this); } @Override public List<ArrayDimensionDisplay> getDimensionDisplay() { return ValueUtil.defaultArrayDisplay(this); } }
923cdc99ed57eed1e0ef9d5660d86bdde938e0da
3,461
java
Java
Tabla.java
Hellboy7abduzcan/Proyecto2
c8b48caf082da1bda26e9abafe36afde75914970
[ "Apache-2.0" ]
null
null
null
Tabla.java
Hellboy7abduzcan/Proyecto2
c8b48caf082da1bda26e9abafe36afde75914970
[ "Apache-2.0" ]
null
null
null
Tabla.java
Hellboy7abduzcan/Proyecto2
c8b48caf082da1bda26e9abafe36afde75914970
[ "Apache-2.0" ]
null
null
null
38.88764
116
0.645478
1,000,081
/* * 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. */ /** * * @author panfi */ public class Tabla extends javax.swing.JFrame { /** * Creates new form Tabla */ public Tabla() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 360, 200)); jButton1.setText("Regresar"); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 250, -1, -1)); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Tabla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Tabla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Tabla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Tabla.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Tabla().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
923cdc9dddf35a2fd149b109e4e09db9d843ed0d
1,387
java
Java
Moonstone/src/edu/cmu/moonstone/quickfix/QuickFixLabel.java
mkery/Moonstone-ErrorHandlingJava
88d498624c9f5fa4482e29f45e4287ca2aa4bdb4
[ "MIT" ]
null
null
null
Moonstone/src/edu/cmu/moonstone/quickfix/QuickFixLabel.java
mkery/Moonstone-ErrorHandlingJava
88d498624c9f5fa4482e29f45e4287ca2aa4bdb4
[ "MIT" ]
null
null
null
Moonstone/src/edu/cmu/moonstone/quickfix/QuickFixLabel.java
mkery/Moonstone-ErrorHandlingJava
88d498624c9f5fa4482e29f45e4287ca2aa4bdb4
[ "MIT" ]
null
null
null
26.169811
121
0.744052
1,000,082
package edu.cmu.moonstone.quickfix; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseTrackAdapter; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; /** Creates a clickable label to be used as a button in the QuickFixDialog * * @author Michael Puskas */ public class QuickFixLabel { private CLabel quickLabel; public QuickFixLabel(Composite parent, String text, Image arrow, Color highlightColor) { this(parent, SWT.NONE, SWT.COLOR_TRANSPARENT, text, arrow, highlightColor); } public QuickFixLabel(final Composite parent, int style, int color, String text, Image arrow, final Color highlightColor) { quickLabel = new CLabel(parent, style); quickLabel.setBackground(parent.getDisplay().getSystemColor(color)); quickLabel.setText(text); if (arrow != null) quickLabel.setImage(arrow); quickLabel.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseEnter(MouseEvent e) { quickLabel.setBackground(highlightColor); } @Override public void mouseExit(MouseEvent e) { quickLabel.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_TRANSPARENT)); } }); } public CLabel getLabel() { return quickLabel; } }
923cde8c0da35e46697bd8e98cbcadb69fea1651
1,933
java
Java
src/main/scala/com/builtbroken/mc/client/json/models/cube/JsonConverterModelCube.java
kmecpp/Engine
2b0e51f8e629faadf031f4c584bb535b806c2c61
[ "Net-SNMP", "Xnet" ]
15
2015-01-10T21:32:44.000Z
2017-03-29T12:56:09.000Z
src/main/scala/com/builtbroken/mc/client/json/models/cube/JsonConverterModelCube.java
kmecpp/Engine
2b0e51f8e629faadf031f4c584bb535b806c2c61
[ "Net-SNMP", "Xnet" ]
65
2015-01-09T17:01:48.000Z
2017-03-30T08:13:04.000Z
src/main/scala/com/builtbroken/mc/client/json/models/cube/JsonConverterModelCube.java
kmecpp/Engine
2b0e51f8e629faadf031f4c584bb535b806c2c61
[ "Net-SNMP", "Xnet" ]
12
2015-01-23T13:14:58.000Z
2017-03-30T08:05:18.000Z
35.796296
152
0.71702
1,000,083
package com.builtbroken.mc.client.json.models.cube; import com.builtbroken.mc.client.json.render.processor.BlockTexturedStateJsonProcessor; import com.builtbroken.mc.framework.json.conversion.JsonConverter; import com.builtbroken.mc.framework.json.conversion.data.transform.JsonConverterPos; import com.builtbroken.mc.framework.json.processors.JsonProcessor; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * Handles converting JSON data into cube data * * @see <a href="https://github.com/BuiltBrokenModding/VoltzEngine/blob/development/license.md">License</a> for what you can and can't do with the code. * Created by Dark(DarkGuardsman, Robert) on 5/2/2018. */ public class JsonConverterModelCube extends JsonConverter<BlockModelPart> { public JsonConverterModelCube() { super("model.part.cube"); } @Override public BlockModelPart convert(JsonElement element, String... args) { final JsonObject jsonData = element.getAsJsonObject(); JsonProcessor.ensureValuesExist(jsonData, "pos", "size"); BlockModelPart modelPart = new BlockModelPart(); modelPart.position = JsonConverterPos.fromJson(jsonData.get("pos")); modelPart.size = JsonConverterPos.fromJson(jsonData.get("size")); //Load global texture for the cube if (jsonData.has("texture") && jsonData.get("texture").isJsonPrimitive()) { modelPart.setTexture(jsonData.get("texture").getAsString()); } //Load textures in the same way a block would be loaded, as each model part can have textures BlockTexturedStateJsonProcessor.handleTextures(modelPart.textureID, jsonData); return modelPart; } @Override public JsonElement build(String type, Object data, String... args) { final JsonObject jsonData = new JsonObject(); //TODO implement return jsonData; } }
923cdf126a9fa33f56f95040b2ea764b95d0d58e
283
java
Java
src/main/java/com/github/sbt/avro/mojo/SchemaGenerationException.java
scala-steward/sbt-avro-1
949e8cd6287bec06b758a1e2155ac80155b8df81
[ "BSD-3-Clause" ]
68
2016-03-22T19:17:01.000Z
2021-12-30T14:31:26.000Z
src/main/java/com/github/sbt/avro/mojo/SchemaGenerationException.java
scala-steward/sbt-avro-1
949e8cd6287bec06b758a1e2155ac80155b8df81
[ "BSD-3-Clause" ]
82
2016-03-22T18:51:35.000Z
2021-12-02T10:22:31.000Z
src/main/java/com/github/sbt/avro/mojo/SchemaGenerationException.java
scala-steward/sbt-avro-1
949e8cd6287bec06b758a1e2155ac80155b8df81
[ "BSD-3-Clause" ]
50
2016-05-17T06:38:28.000Z
2022-03-07T12:09:44.000Z
21.769231
69
0.766784
1,000,084
package com.github.sbt.avro.mojo; public class SchemaGenerationException extends RuntimeException { public SchemaGenerationException(String message) { super(message); } public SchemaGenerationException(String message, Exception cause) { super(message, cause); } }
923cdf66bb3fac16a54e51dbb0d9c7fb24964619
2,878
java
Java
chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellNativeUiTest.java
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellNativeUiTest.java
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/android/javatests/src/org/chromium/chrome/browser/vr_shell/VrShellNativeUiTest.java
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
38.373333
100
0.767199
1,000,085
// Copyright 2017 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.vr_shell; import static org.chromium.chrome.browser.vr_shell.VrTestFramework.NATIVE_URLS_OF_INTEREST; import static org.chromium.chrome.browser.vr_shell.VrTestFramework.PAGE_LOAD_TIMEOUT_S; import static org.chromium.chrome.browser.vr_shell.VrTestFramework.POLL_TIMEOUT_LONG_MS; import static org.chromium.chrome.test.util.ChromeRestriction.RESTRICTION_TYPE_VIEWER_DAYDREAM; import android.support.test.filters.MediumTest; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Restriction; import org.chromium.chrome.browser.ChromeSwitches; import org.chromium.chrome.browser.vr_shell.rules.ChromeTabbedActivityVrTestRule; import org.chromium.chrome.browser.vr_shell.util.VrTransitionUtils; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import java.util.concurrent.TimeoutException; /** * End-to-end tests for native UI presentation in VR Browser mode. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE, "enable-webvr"}) @Restriction(RESTRICTION_TYPE_VIEWER_DAYDREAM) public class VrShellNativeUiTest { // We explicitly instantiate a rule here instead of using parameterization since this class // only ever runs in ChromeTabbedActivity. @Rule public ChromeTabbedActivityVrTestRule mVrTestRule = new ChromeTabbedActivityVrTestRule(); private static final String TEST_PAGE_2D_URL = VrTestFramework.getFileUrlForHtmlTestFile("test_navigation_2d_page"); @Before public void setUp() throws Exception { VrTransitionUtils.forceEnterVr(); VrTransitionUtils.waitForVrEntry(POLL_TIMEOUT_LONG_MS); } /** * Tests that URLs are not shown for native UI. */ @Test @MediumTest public void testUrlOnNativeUi() throws IllegalArgumentException, InterruptedException, TimeoutException { for (String url : NATIVE_URLS_OF_INTEREST) { mVrTestRule.loadUrl(url, PAGE_LOAD_TIMEOUT_S); Assert.assertFalse("Should not be showing URL on " + url, TestVrShellDelegate.isDisplayingUrlForTesting()); } } /** * Tests that URLs are shown for non-native UI. */ @Test @MediumTest public void testUrlOnNonNativeUi() throws IllegalArgumentException, InterruptedException, TimeoutException { mVrTestRule.loadUrl(TEST_PAGE_2D_URL, PAGE_LOAD_TIMEOUT_S); Assert.assertTrue("Should be showing URL", TestVrShellDelegate.isDisplayingUrlForTesting()); } }
923ce28d68e5295c06f9875915dfdb94511820d3
726
java
Java
LACCPlus/Hive/198_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hive/198_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
LACCPlus/Hive/198_2.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
40.333333
98
0.596419
1,000,086
//,temp,ThriftHiveMetastore.java,26170,26182,temp,TCLIService.java,2203,2215 //,3 public class xxx { public void onComplete(TGetInfoResp o) { GetInfo_result result = new GetInfo_result(); result.success = o; try { fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); } catch (org.apache.thrift.transport.TTransportException e) { _LOGGER.error("TTransportException writing to internal frame buffer", e); fb.close(); } catch (java.lang.Exception e) { _LOGGER.error("Exception writing to internal frame buffer", e); onError(e); } } };
923ce3a8fac8d7d0dc923a1a1b25856072dc59d7
13,433
java
Java
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/SharedNothingReplicationFlowControlTest.java
codrinbucur/activemq-artemis
29967bc8355b23874f10dd9176222ceee6f10d0b
[ "Apache-2.0" ]
null
null
null
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/SharedNothingReplicationFlowControlTest.java
codrinbucur/activemq-artemis
29967bc8355b23874f10dd9176222ceee6f10d0b
[ "Apache-2.0" ]
null
null
null
tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/replication/SharedNothingReplicationFlowControlTest.java
codrinbucur/activemq-artemis
29967bc8355b23874f10dd9176222ceee6f10d0b
[ "Apache-2.0" ]
null
null
null
43.054487
345
0.734683
1,000,087
/** * 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.activemq.artemis.tests.integration.replication; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.api.core.ActiveMQException; import org.apache.activemq.artemis.api.core.Interceptor; import org.apache.activemq.artemis.api.core.RoutingType; import org.apache.activemq.artemis.api.core.client.ClientMessage; import org.apache.activemq.artemis.api.core.client.ClientProducer; import org.apache.activemq.artemis.api.core.client.ClientSession; import org.apache.activemq.artemis.api.core.client.ClientSessionFactory; import org.apache.activemq.artemis.api.core.client.ServerLocator; import org.apache.activemq.artemis.core.client.impl.ServerLocatorImpl; import org.apache.activemq.artemis.core.config.ClusterConnectionConfiguration; import org.apache.activemq.artemis.core.config.Configuration; import org.apache.activemq.artemis.core.config.ha.ReplicaPolicyConfiguration; import org.apache.activemq.artemis.core.config.ha.ReplicatedPolicyConfiguration; import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl; import org.apache.activemq.artemis.core.io.SequentialFileFactory; import org.apache.activemq.artemis.core.io.mapped.MappedSequentialFileFactory; import org.apache.activemq.artemis.core.journal.LoaderCallback; import org.apache.activemq.artemis.core.journal.PreparedTransactionInfo; import org.apache.activemq.artemis.core.journal.RecordInfo; import org.apache.activemq.artemis.core.journal.impl.JournalImpl; import org.apache.activemq.artemis.core.persistence.impl.journal.JournalRecordIds; import org.apache.activemq.artemis.core.protocol.core.Packet; import org.apache.activemq.artemis.core.server.ActiveMQServer; import org.apache.activemq.artemis.core.server.ActiveMQServers; import org.apache.activemq.artemis.core.server.JournalType; import org.apache.activemq.artemis.junit.Wait; import org.apache.activemq.artemis.spi.core.protocol.RemotingConnection; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class SharedNothingReplicationFlowControlTest extends ActiveMQTestBase { ExecutorService sendMessageExecutor; @Before public void setupExecutor() { sendMessageExecutor = Executors.newCachedThreadPool(); } @After public void teardownExecutor() { sendMessageExecutor.shutdownNow(); } private static final Logger logger = Logger.getLogger(SharedNothingReplicationFlowControlTest.class); @Rule public TemporaryFolder brokersFolder = new TemporaryFolder(); @Test public void testReplicationIfFlowControlled() throws Exception { // start live Configuration liveConfiguration = createLiveConfiguration(); ActiveMQServer liveServer = addServer(ActiveMQServers.newActiveMQServer(liveConfiguration)); liveServer.start(); Wait.waitFor(() -> liveServer.isStarted()); ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616"); locator.setCallTimeout(60_000L); locator.setConnectionTTL(60_000L); final ClientSessionFactory csf = locator.createSessionFactory(); ClientSession sess = csf.createSession(); sess.createQueue("flowcontrol", RoutingType.ANYCAST, "flowcontrol", true); sess.close(); int i = 0; final int j = 100; final CountDownLatch allMessageSent = new CountDownLatch(j); // start backup Configuration backupConfiguration = createBackupConfiguration(); ActiveMQServer backupServer = addServer(ActiveMQServers.newActiveMQServer(backupConfiguration)); backupServer.start(); Wait.waitFor(() -> backupServer.isStarted()); Wait.waitFor(backupServer::isReplicaSync, 30000); TestInterceptor interceptor = new TestInterceptor(30000); // Increase latency of handling packet on backup side and flow control would work backupServer.getClusterManager().getClusterController().addIncomingInterceptorForReplication(interceptor); byte[] body = new byte[32 * 1024]; while (i < j) { sendMessageExecutor.execute(() -> { try { ClientSession session = csf.createSession(true, true); ClientProducer producer = session.createProducer("flowcontrol"); ClientMessage message = session.createMessage(true); message.writeBodyBufferBytes(body); logger.infof("try to send a message after replicated"); producer.send(message); logger.info("send message done"); producer.close(); session.close(); allMessageSent.countDown(); } catch (ActiveMQException e) { logger.error("send message", e); } }); i++; } Assert.assertTrue("all message sent", allMessageSent.await(30, TimeUnit.SECONDS)); interceptor.setSleepTime(0); csf.close(); locator.close(); Assert.assertTrue("Waiting for replica sync timeout", Wait.waitFor(liveServer::isReplicaSync, 30000)); backupServer.stop(true); liveServer.stop(true); SequentialFileFactory fileFactory; File liveJournalDir = brokersFolder.getRoot().toPath().resolve("live").resolve("data").resolve("journal").toFile(); fileFactory = new MappedSequentialFileFactory(liveConfiguration.getJournalLocation(), liveConfiguration.getJournalFileSize(), false, liveConfiguration.getJournalBufferSize_NIO(), liveConfiguration.getJournalBufferTimeout_NIO(), null); JournalImpl liveMessageJournal = new JournalImpl(liveConfiguration.getJournalFileSize(), liveConfiguration.getJournalMinFiles(), liveConfiguration.getJournalPoolFiles(), liveConfiguration.getJournalCompactMinFiles(), liveConfiguration.getJournalCompactPercentage(), fileFactory, "activemq-data", "amq", fileFactory.getMaxIO()); liveMessageJournal.start(); final AtomicInteger liveJournalCounter = new AtomicInteger(); liveMessageJournal.load(new SharedNothingReplicationFlowControlTest.AddRecordLoaderCallback() { @Override public void addRecord(RecordInfo info) { if (!(info.userRecordType == JournalRecordIds.ADD_MESSAGE_PROTOCOL)) { // ignore } logger.infof("got live message %d %d", info.id, info.userRecordType); liveJournalCounter.incrementAndGet(); } }); // read backup's journal File backupJournalDir = brokersFolder.getRoot().toPath().resolve("backup").resolve("data").resolve("journal").toFile(); fileFactory = new MappedSequentialFileFactory(backupConfiguration.getJournalLocation(), backupConfiguration.getJournalFileSize(), false, backupConfiguration.getJournalBufferSize_NIO(), backupConfiguration.getJournalBufferTimeout_NIO(), null); JournalImpl backupMessageJournal = new JournalImpl(backupConfiguration.getJournalFileSize(), backupConfiguration.getJournalMinFiles(), backupConfiguration.getJournalPoolFiles(), backupConfiguration.getJournalCompactMinFiles(), backupConfiguration.getJournalCompactPercentage(), fileFactory, "activemq-data", "amq", fileFactory.getMaxIO()); backupMessageJournal.start(); final AtomicInteger replicationCounter = new AtomicInteger(); backupMessageJournal.load(new SharedNothingReplicationFlowControlTest.AddRecordLoaderCallback() { @Override public void addRecord(RecordInfo info) { if (!(info.userRecordType == JournalRecordIds.ADD_MESSAGE_PROTOCOL)) { // ignore } logger.infof("replicated message %d", info.id); replicationCounter.incrementAndGet(); } }); logger.infof("expected %d messages, live=%d, backup=%d", j, liveJournalCounter.get(), replicationCounter.get()); Assert.assertEquals("Live lost journal record", j, liveJournalCounter.get()); Assert.assertEquals("Backup did not replicated all journal", j, replicationCounter.get()); } // Set a small call timeout and write buffer high water mark value to trigger replication flow control private Configuration createLiveConfiguration() throws Exception { Configuration conf = new ConfigurationImpl(); conf.setName("localhost::live"); File liveDir = brokersFolder.newFolder("live"); conf.setBrokerInstance(liveDir); conf.addAcceptorConfiguration("live", "tcp://localhost:61616?writeBufferHighWaterMark=2048&writeBufferLowWaterMark=2048"); conf.addConnectorConfiguration("backup", "tcp://localhost:61617"); conf.addConnectorConfiguration("live", "tcp://localhost:61616"); conf.setClusterUser("mycluster"); conf.setClusterPassword("mypassword"); ReplicatedPolicyConfiguration haPolicy = new ReplicatedPolicyConfiguration(); haPolicy.setVoteOnReplicationFailure(false); haPolicy.setCheckForLiveServer(false); conf.setHAPolicyConfiguration(haPolicy); ClusterConnectionConfiguration ccconf = new ClusterConnectionConfiguration(); ccconf.setStaticConnectors(new ArrayList<>()).getStaticConnectors().add("backup"); ccconf.setName("cluster"); ccconf.setConnectorName("live"); ccconf.setCallTimeout(4000); conf.addClusterConfiguration(ccconf); conf.setSecurityEnabled(false).setJMXManagementEnabled(false).setJournalType(JournalType.MAPPED).setJournalFileSize(1024 * 512).setConnectionTTLOverride(60_000L); return conf; } private Configuration createBackupConfiguration() throws Exception { Configuration conf = new ConfigurationImpl(); conf.setName("localhost::backup"); File backupDir = brokersFolder.newFolder("backup"); conf.setBrokerInstance(backupDir); ReplicaPolicyConfiguration haPolicy = new ReplicaPolicyConfiguration(); haPolicy.setClusterName("cluster"); conf.setHAPolicyConfiguration(haPolicy); conf.addAcceptorConfiguration("backup", "tcp://localhost:61617"); conf.addConnectorConfiguration("live", "tcp://localhost:61616"); conf.addConnectorConfiguration("backup", "tcp://localhost:61617"); conf.setClusterUser("mycluster"); conf.setClusterPassword("mypassword"); ClusterConnectionConfiguration ccconf = new ClusterConnectionConfiguration(); ccconf.setStaticConnectors(new ArrayList<>()).getStaticConnectors().add("live"); ccconf.setName("cluster"); ccconf.setConnectorName("backup"); conf.addClusterConfiguration(ccconf); /** * Set a bad url then, as a result the backup node would make a decision * of replicating from live node in the case of connection failure. * Set big check period to not schedule checking which would stop server. */ conf.setNetworkCheckPeriod(1000000).setNetworkCheckURLList("http://localhost:28787").setSecurityEnabled(false).setJMXManagementEnabled(false).setJournalType(JournalType.MAPPED).setJournalFileSize(1024 * 512).setConnectionTTLOverride(60_000L); return conf; } abstract class AddRecordLoaderCallback implements LoaderCallback { @Override public void addPreparedTransaction(PreparedTransactionInfo preparedTransaction) { } @Override public void deleteRecord(long id) { } @Override public void updateRecord(RecordInfo info) { } @Override public void failedTransaction(long transactionID, List<RecordInfo> records, List<RecordInfo> recordsToDelete) { } } public static final class TestInterceptor implements Interceptor { private long sleepTime; public TestInterceptor(long sleepTime) { this.sleepTime = sleepTime; } public void setSleepTime(long sleepTime) { this.sleepTime = sleepTime; } @Override public boolean intercept(Packet packet, RemotingConnection connection) throws ActiveMQException { try { long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < startTime + sleepTime) { Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } return true; } } }
923ce3bed032aaa525dc02bafa386c05faa50793
25,636
java
Java
main/plugins/org.talend.designer.components.libs/libs_src/salesforceCRMManagement/com/salesforce/soap/partner/PerformQuickActionRequest.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
null
null
null
main/plugins/org.talend.designer.components.libs/libs_src/salesforceCRMManagement/com/salesforce/soap/partner/PerformQuickActionRequest.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
null
null
null
main/plugins/org.talend.designer.components.libs/libs_src/salesforceCRMManagement/com/salesforce/soap/partner/PerformQuickActionRequest.java
bgunics-talend/tdi-studio-se
3f54f55acb4d214f2d02532667bae98420068170
[ "Apache-2.0" ]
null
null
null
40.821656
140
0.563621
1,000,088
/** * PerformQuickActionRequest.java * * This file was auto-generated from WSDL by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST) */ package com.salesforce.soap.partner; /** * PerformQuickActionRequest bean class */ @SuppressWarnings({ "unchecked", "unused" }) public class PerformQuickActionRequest implements org.apache.axis2.databinding.ADBBean { /* * This type was generated from the piece of schema that had name = PerformQuickActionRequest Namespace URI = * urn:partner.soap.sforce.com Namespace Prefix = ns1 */ /** * field for ContextId */ protected com.salesforce.soap.partner.ID localContextId; /** * Auto generated getter method * * @return com.salesforce.soap.partner.ID */ public com.salesforce.soap.partner.ID getContextId() { return localContextId; } /** * Auto generated setter method * * @param param ContextId */ public void setContextId(com.salesforce.soap.partner.ID param) { this.localContextId = param; } /** * field for QuickActionName */ protected java.lang.String localQuickActionName; /** * Auto generated getter method * * @return java.lang.String */ public java.lang.String getQuickActionName() { return localQuickActionName; } /** * Auto generated setter method * * @param param QuickActionName */ public void setQuickActionName(java.lang.String param) { this.localQuickActionName = param; } /** * field for Records This was an Array! */ protected com.salesforce.soap.partner.sobject.SObject[] localRecords; /* * This tracker boolean wil be used to detect whether the user called the set method for this attribute. It will be used to determine * whether to include this field in the serialized XML */ protected boolean localRecordsTracker = false; public boolean isRecordsSpecified() { return localRecordsTracker; } /** * Auto generated getter method * * @return com.salesforce.soap.partner.sobject.SObject[] */ public com.salesforce.soap.partner.sobject.SObject[] getRecords() { return localRecords; } /** * validate the array for Records */ protected void validateRecords(com.salesforce.soap.partner.sobject.SObject[] param) { } /** * Auto generated setter method * * @param param Records */ public void setRecords(com.salesforce.soap.partner.sobject.SObject[] param) { validateRecords(param); localRecordsTracker = true; this.localRecords = param; } /** * Auto generated add method for the array for convenience * * @param param com.salesforce.soap.partner.sobject.SObject */ public void addRecords(com.salesforce.soap.partner.sobject.SObject param) { if (localRecords == null) { localRecords = new com.salesforce.soap.partner.sobject.SObject[] {}; } // update the setting tracker localRecordsTracker = true; java.util.List list = org.apache.axis2.databinding.utils.ConverterUtil.toList(localRecords); list.add(param); this.localRecords = (com.salesforce.soap.partner.sobject.SObject[]) list .toArray(new com.salesforce.soap.partner.sobject.SObject[list.size()]); } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException { org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this, parentQName); return factory.createOMElement(dataSource, parentQName); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException { serialize(parentQName, xmlWriter, false); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException { java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter); if (serializeType) { java.lang.String namespacePrefix = registerPrefix(xmlWriter, "urn:partner.soap.sforce.com"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) { writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":PerformQuickActionRequest", xmlWriter); } else { writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "PerformQuickActionRequest", xmlWriter); } } if (localContextId == null) { writeStartElement(null, "urn:partner.soap.sforce.com", "contextId", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } else { localContextId.serialize(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "contextId"), xmlWriter); } namespace = "urn:partner.soap.sforce.com"; writeStartElement(null, namespace, "quickActionName", xmlWriter); if (localQuickActionName == null) { // write the nil attribute throw new org.apache.axis2.databinding.ADBException("quickActionName cannot be null!!"); } else { xmlWriter.writeCharacters(localQuickActionName); } xmlWriter.writeEndElement(); if (localRecordsTracker) { if (localRecords != null) { for (int i = 0; i < localRecords.length; i++) { if (localRecords[i] != null) { localRecords[i].serialize(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "records"), xmlWriter); } else { writeStartElement(null, "urn:partner.soap.sforce.com", "records", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } } else { writeStartElement(null, "urn:partner.soap.sforce.com", "records", xmlWriter); // write the nil attribute writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "nil", "1", xmlWriter); xmlWriter.writeEndElement(); } } xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(java.lang.String namespace) { if (namespace.equals("urn:partner.soap.sforce.com")) { return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix, java.lang.String namespace, java.lang.String attName, java.lang.String attValue, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace, attName, attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace, java.lang.String attName, java.lang.String attValue, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix, namespaceURI); } if (prefix.trim().length() > 0) { xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix, namespaceURI); } if (prefix.trim().length() > 0) { stringToWrite.append(prefix).append(":") .append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext(); while (true) { java.lang.String uri = nsContext.getNamespaceURI(prefix); if (uri == null || uri.length() == 0) { break; } prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException { java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "contextId")); elementList.add(localContextId == null ? null : localContextId); elementList.add(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "quickActionName")); if (localQuickActionName != null) { elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localQuickActionName)); } else { throw new org.apache.axis2.databinding.ADBException("quickActionName cannot be null!!"); } if (localRecordsTracker) { if (localRecords != null) { for (int i = 0; i < localRecords.length; i++) { if (localRecords[i] != null) { elementList.add(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "records")); elementList.add(localRecords[i]); } else { elementList.add(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "records")); elementList.add(null); } } } else { elementList.add(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "records")); elementList.add(localRecords); } } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory { /** * static method to create the object Precondition: If this object is an element, the current or next start element starts this * object and any intervening reader events are ignorable If this object is not an element, it is a complex type and the reader is * at the event just after the outer start element Postcondition: If this object is an element, the reader is positioned at its end * element If this object is a complex type, the reader is positioned at the end element of its outer element */ public static PerformQuickActionRequest parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception { PerformQuickActionRequest object = new PerformQuickActionRequest(); int event; java.lang.String nillableValue = null; java.lang.String prefix = ""; java.lang.String namespaceuri = ""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) { java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName != null) { java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1) { nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":")); } nsPrefix = nsPrefix == null ? "" : nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1); if (!"PerformQuickActionRequest".equals(type)) { // find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (PerformQuickActionRequest) com.salesforce.soap.partner.sobject.ExtensionMapper.getTypeObject( nsUri, type, reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); java.util.ArrayList list3 = new java.util.ArrayList(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "contextId").equals(reader.getName())) { nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)) { object.setContextId(null); reader.next(); reader.next(); } else { object.setContextId(com.salesforce.soap.partner.ID.Factory.parse(reader)); reader.next(); } } // End of if for expected property start element else { // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "quickActionName").equals(reader .getName())) { nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)) { throw new org.apache.axis2.databinding.ADBException("The element: " + "quickActionName" + " cannot be null"); } java.lang.String content = reader.getElementText(); object.setQuickActionName(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else { // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "records").equals(reader.getName())) { // Process the array and step past its final element's end. nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)) { list3.add(null); reader.next(); } else { list3.add(com.salesforce.soap.partner.sobject.SObject.Factory.parse(reader)); } // loop until we find a start element that is not part of this array boolean loopDone3 = false; while (!loopDone3) { // We should be at the end element, but make sure while (!reader.isEndElement()) reader.next(); // Step out of this element reader.next(); // Step to next element event. while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isEndElement()) { // two continuous end elements means we are exiting the xml structure loopDone3 = true; } else { if (new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "records").equals(reader.getName())) { nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)) { list3.add(null); reader.next(); } else { list3.add(com.salesforce.soap.partner.sobject.SObject.Factory.parse(reader)); } } else { loopDone3 = true; } } } // call the converter utility to convert and set the array object.setRecords((com.salesforce.soap.partner.sobject.SObject[]) org.apache.axis2.databinding.utils.ConverterUtil .convertToArray(com.salesforce.soap.partner.sobject.SObject.class, list3)); } // End of if for expected property start element else { } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }// end of factory class }
923ce3f1950201b85ea34916868918a353913045
1,026
java
Java
checker/src/main/java/org/checkerframework/checker/calledmethods/builder/BuilderFrameworkSupportUtils.java
twistedsquare/checker-framework
35b682c252a390924fefe3e12f5dcc57971cf9eb
[ "MIT" ]
877
2015-07-04T19:51:28.000Z
2022-03-25T07:40:52.000Z
checker/src/main/java/org/checkerframework/checker/calledmethods/builder/BuilderFrameworkSupportUtils.java
smonteiro/checker-framework
967490a52d69c4658b8cc2461c5dce06a016f1e7
[ "MIT" ]
2,468
2015-07-06T18:17:19.000Z
2022-03-31T16:56:39.000Z
checker/src/main/java/org/checkerframework/checker/calledmethods/builder/BuilderFrameworkSupportUtils.java
smonteiro/checker-framework
967490a52d69c4658b8cc2461c5dce06a016f1e7
[ "MIT" ]
427
2015-07-07T15:52:48.000Z
2022-03-20T21:52:22.000Z
31.090909
90
0.721248
1,000,089
package org.checkerframework.checker.calledmethods.builder; import javax.lang.model.type.TypeMirror; /** A utility class of static methods used in supporting builder-generation frameworks. */ public class BuilderFrameworkSupportUtils { /** This class is non-instantiable. */ private BuilderFrameworkSupportUtils() { throw new Error("Do not instantiate"); } /** * Returns true if the given type is one of the immutable collections defined in * com.google.common.collect. * * @param type a type * @return true if the type is a Guava immutable collection */ public static boolean isGuavaImmutableType(TypeMirror type) { return type.toString().startsWith("com.google.common.collect.Immutable"); } /** * Capitalizes the first letter of the given string. * * @param prop a String * @return the same String, but with the first character capitalized */ public static String capitalize(String prop) { return prop.substring(0, 1).toUpperCase() + prop.substring(1); } }
923ce4f9742d1bdf4249c91b40efbac342f372b9
1,264
java
Java
samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java
antkorwin/spring-cloud-contract
4d16a00ce4b8bbc07cc4f93dd989b1f2ec0e0ecc
[ "Apache-2.0" ]
1
2019-08-07T08:24:36.000Z
2019-08-07T08:24:36.000Z
samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java
antkorwin/spring-cloud-contract
4d16a00ce4b8bbc07cc4f93dd989b1f2ec0e0ecc
[ "Apache-2.0" ]
null
null
null
samples/wiremock-jetty/src/test/java/com/example/WiremockForDocsMockServerApplicationTests.java
antkorwin/spring-cloud-contract
4d16a00ce4b8bbc07cc4f93dd989b1f2ec0e0ecc
[ "Apache-2.0" ]
1
2019-05-31T07:51:10.000Z
2019-05-31T07:51:10.000Z
32.410256
82
0.808544
1,000,090
package com.example; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.contract.wiremock.WireMockRestServiceServer; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.web.client.RestTemplate; // tag::wiremock_test[] @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.NONE) public class WiremockForDocsMockServerApplicationTests { @Autowired private RestTemplate restTemplate; @Autowired private Service service; @Test public void contextLoads() throws Exception { // will read stubs classpath MockRestServiceServer server = WireMockRestServiceServer.with(this.restTemplate) .baseUrl("http://example.org").stubs("classpath:/stubs/resource.json") .build(); // We're asserting if WireMock responded properly assertThat(this.service.go()).isEqualTo("Hello World"); server.verify(); } } // end::wiremock_test[]
923ce85ba4d12b29052f92ecf88c069d2e74ad72
2,881
java
Java
src/main/java/com/web/mavenproject6/service/MailSenderService.java
exxxar/redQueen
b013facdb2b0e33f41a9b966b37c92f51c616e3e
[ "Apache-2.0" ]
1
2018-12-27T14:15:29.000Z
2018-12-27T14:15:29.000Z
src/main/java/com/web/mavenproject6/service/MailSenderService.java
exxxar/redQueen
b013facdb2b0e33f41a9b966b37c92f51c616e3e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/web/mavenproject6/service/MailSenderService.java
exxxar/redQueen
b013facdb2b0e33f41a9b966b37c92f51c616e3e
[ "Apache-2.0" ]
null
null
null
34.710843
90
0.697327
1,000,091
/* * 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 com.web.mavenproject6.service; /** * * @author Aleks */ import com.web.mavenproject6.entities.SecurityCode; import com.web.mavenproject6.entities.Users; import com.web.mavenproject6.forms.MailForm; import java.util.HashMap; import java.util.Map; import javax.mail.internet.MimeMessage; import org.apache.velocity.app.VelocityEngine; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.ui.velocity.VelocityEngineUtils; @Service public class MailSenderService { @Autowired private Environment env; @Autowired private JavaMailSender mailSender; @Autowired private VelocityEngine velocityEngine; @Autowired private MailForm mailForm; private static String CONFIRMATION_TEMPLATE = "confirm_account.html"; public JavaMailSender getMailSender() { return mailSender; } public void setMailSender(JavaMailSender mailSender) { this.mailSender = mailSender; } public VelocityEngine getVelocityEngine() { return velocityEngine; } public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } @Async public void sendAuthorizationMail(final Users user, final SecurityCode securityCode) { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setSubject(mailForm.getSubject()); message.setTo(user.getEmail()); message.setFrom(mailForm.getFrom()); Map model = new HashMap(); model.put("websiteName", mailForm.getWebsiteName()); model.put("host", mailForm.getHost()); model.put("user", user); model.put("securityCode", securityCode); model.put("projectName",env.getProperty("projectName")); System.out.println("MAIL!!:"+user.toString()); String text = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, CONFIRMATION_TEMPLATE, model); message.setText(text, true); } }; this.mailSender.send(preparator); } }
923ce87cdf928bd9cc42def1b479fca4980522cf
107
java
Java
simplified-app-shared/src/main/java/org/nypl/simplified/app/utilities/package-info.java
NYPL-Simplified/open-ebooks-android
0678b3d1f6ad5b87125f7c97194fa105b7c5ca3d
[ "Apache-2.0" ]
1
2019-05-03T17:45:18.000Z
2019-05-03T17:45:18.000Z
simplified-app-shared/src/main/java/org/nypl/simplified/app/utilities/package-info.java
NYPL-Simplified/Open-eBooks-Android
0678b3d1f6ad5b87125f7c97194fa105b7c5ca3d
[ "Apache-2.0" ]
null
null
null
simplified-app-shared/src/main/java/org/nypl/simplified/app/utilities/package-info.java
NYPL-Simplified/Open-eBooks-Android
0678b3d1f6ad5b87125f7c97194fa105b7c5ca3d
[ "Apache-2.0" ]
null
null
null
17.833333
75
0.747664
1,000,092
/** * Android utilities. */ @com.io7m.jnull.NonNullByDefault package org.nypl.simplified.app.utilities;
923ce8c58986ab8cf95ab6e5445b1d5cc416ef22
140
java
Java
src/main/java/com/assoft/ssomonitor/domain/enumeration/Secretornot.java
BulkSecurityGeneratorProject/monitorone
a00b784fda5bccf80aa1a29d813236706b9e6dcb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/assoft/ssomonitor/domain/enumeration/Secretornot.java
BulkSecurityGeneratorProject/monitorone
a00b784fda5bccf80aa1a29d813236706b9e6dcb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/assoft/ssomonitor/domain/enumeration/Secretornot.java
BulkSecurityGeneratorProject/monitorone
a00b784fda5bccf80aa1a29d813236706b9e6dcb
[ "Apache-2.0" ]
1
2020-09-18T08:01:03.000Z
2020-09-18T08:01:03.000Z
15.555556
49
0.742857
1,000,093
package com.assoft.ssomonitor.domain.enumeration; /** * The Secretornot enumeration. */ public enum Secretornot { SECRET,NOTSECRET }
923cea27c5c63e0d194a97e2b221f33f1d2dd7e8
1,085
java
Java
HotelSystem/InternetHotelReservationSystem/ServerSystem/src/main/java/dataHelper/HotelDataHelper.java
seriouszyx/software-engineering
0a961b9e38104027b0fd98e1ad36d3d118a84dd9
[ "MIT" ]
15
2019-12-12T13:45:02.000Z
2022-03-13T05:02:51.000Z
HotelSystem/InternetHotelReservationSystem/ServerSystem/src/main/java/dataHelper/HotelDataHelper.java
seriouszyx/software-engineering
0a961b9e38104027b0fd98e1ad36d3d118a84dd9
[ "MIT" ]
null
null
null
HotelSystem/InternetHotelReservationSystem/ServerSystem/src/main/java/dataHelper/HotelDataHelper.java
seriouszyx/software-engineering
0a961b9e38104027b0fd98e1ad36d3d118a84dd9
[ "MIT" ]
5
2019-12-12T12:34:03.000Z
2022-03-13T05:02:54.000Z
19.727273
60
0.710599
1,000,094
package dataHelper; import java.util.List; import po.HotelPO; import utilities.enums.ResultMessage; /** * @Description:对数据库中hotel表的操作 * @author:Harvey Gong * @time:2016年12月4日 上午10:10:46 */ public interface HotelDataHelper { /** * @author 董金玉 * @lastChangedBy 董金玉 * @updateTime 2016/11/29 * @param city 城市,circle商圈 * @return List<HotelPO> 酒店信息载体列表 */ //根据城市商圈返回位于该地区所有酒店的简介 public List<HotelPO> getHotels(String city, String circle); /** * @author 董金玉 * @lastChangedBy 董金玉 * @updateTime 2016/11/29 * @param hotelID 酒店ID * @return HotelPO 酒店信息载体 */ //根据酒店id返回该酒店的基本信息 public HotelPO getHotelInfo (String hotelID); /** * @author 董金玉 * @lastChangedBy 董金玉 * @updateTime 2016/11/29 * @param hotelPO 酒店信息载体 * @return ResultMessage 是否成功更新酒店信息 */ //根据hotelPO更新一条数据库里的po public ResultMessage updateHotelInfo(HotelPO hotelPO); /** * @author 董金玉 * @lastChangedBy 董金玉 * @updateTime 2016/11/29 * @param hotelPO 酒店信息载体 * @return ResultMessage 是否添加更新酒店信息 */ //根据hotelPO添加一条po public ResultMessage addHotelInfo(HotelPO hotelPO); }
923ceaafaa110b89e447a3c674fd1900a217747e
783
java
Java
platypus-js-web-client/src/main/java/com/eas/widgets/boxes/ImageLabel.java
marat-gainullin/platypus-js
22437b7172a3cbebe2635899608a32943fed4028
[ "Apache-2.0" ]
1
2017-05-02T14:12:15.000Z
2017-05-02T14:12:15.000Z
platypus-js-web-client/src/main/java/com/eas/widgets/boxes/ImageLabel.java
abogdanov37/platypus-js
1acd54837f9d54846c4762c8cef6858849c5d96c
[ "Apache-2.0" ]
4
2017-05-25T08:56:05.000Z
2020-06-10T07:11:05.000Z
platypus-js-web-client/src/main/java/com/eas/widgets/boxes/ImageLabel.java
abogdanov37/platypus-js
1acd54837f9d54846c4762c8cef6858849c5d96c
[ "Apache-2.0" ]
2
2017-03-15T06:22:48.000Z
2020-02-17T07:56:17.000Z
27
77
0.669221
1,000,095
package com.eas.widgets.boxes; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.resources.client.ImageResource; /** * * @author mg */ public class ImageLabel extends ImageParagraph { protected static Element createLabelContainer() { Element container = Document.get().createDivElement(); container.setAttribute("class", "label"); container.getStyle().setProperty("outline", "none"); return container; } public ImageLabel(String aTitle, boolean asHtml, ImageResource aImage) { super(createLabelContainer(), aTitle, asHtml, aImage); } public ImageLabel(String aTitle, boolean asHtml) { this(aTitle, asHtml, null); } }
923cebc25030387a8bbba209114b69b729dd5797
1,146
java
Java
src/main/java/Registration/model/Employee.java
MrDiipo/Registration-Database-In-Servlets-And-Mysql
082597f72b84b3b65414d5286849f2b7a58c9dd4
[ "MIT" ]
null
null
null
src/main/java/Registration/model/Employee.java
MrDiipo/Registration-Database-In-Servlets-And-Mysql
082597f72b84b3b65414d5286849f2b7a58c9dd4
[ "MIT" ]
null
null
null
src/main/java/Registration/model/Employee.java
MrDiipo/Registration-Database-In-Servlets-And-Mysql
082597f72b84b3b65414d5286849f2b7a58c9dd4
[ "MIT" ]
null
null
null
19.423729
48
0.623037
1,000,096
package Registration.model; public class Employee { private String firstName; private String lastName; private String username; private String password; private String address; private String contact; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } }
923cecee1804463122d0acce775946160e4bee39
745
java
Java
src/main/java/com/athome/designers/strategy/v1/startMain/GameStart.java
jointzip/zipper-design-patterns
0fabb97d0ec221ba2b5b85db27cf98ec16790388
[ "Apache-2.0" ]
null
null
null
src/main/java/com/athome/designers/strategy/v1/startMain/GameStart.java
jointzip/zipper-design-patterns
0fabb97d0ec221ba2b5b85db27cf98ec16790388
[ "Apache-2.0" ]
null
null
null
src/main/java/com/athome/designers/strategy/v1/startMain/GameStart.java
jointzip/zipper-design-patterns
0fabb97d0ec221ba2b5b85db27cf98ec16790388
[ "Apache-2.0" ]
null
null
null
26.607143
71
0.655034
1,000,097
package com.athome.designers.strategy.v1.startMain; import com.athome.designers.strategy.v1.roles.MagicRole; import com.athome.designers.strategy.v1.roles.Shooter; import java.lang.reflect.Method; /** * @Author: * @Date: 2021/7/8 12:42 * @Description: */ public class GameStart { public static void main(String[] args) { //一名法师角色 MagicRole magicRole = new MagicRole(); magicRole.display(); magicRole.attack(); magicRole.move(); // Class<Shooter> shooterClass = Shooter.class; // Method[] declaredMethods = shooterClass.getDeclaredMethods(); // for (Method declaredMethod : declaredMethods) { // System.out.println(declaredMethod.getName()); // } } }
923ceedd47581ba52d69c39b0ed5cb63c9ed1a44
26,609
java
Java
model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/formatters/TextFormatter.java
bshp/midpoint
6dfa3fecb76d1516a22eb4b7f3da04031ade04d3
[ "Apache-2.0" ]
null
null
null
model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/formatters/TextFormatter.java
bshp/midpoint
6dfa3fecb76d1516a22eb4b7f3da04031ade04d3
[ "Apache-2.0" ]
null
null
null
model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/formatters/TextFormatter.java
bshp/midpoint
6dfa3fecb76d1516a22eb4b7f3da04031ade04d3
[ "Apache-2.0" ]
null
null
null
48.030686
222
0.624488
1,000,098
/* * Copyright (c) 2010-2013 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.notifications.impl.formatters; import com.evolveum.midpoint.common.LocalizationService; import com.evolveum.midpoint.notifications.api.events.SimpleObjectRef; import com.evolveum.midpoint.notifications.impl.NotificationFunctionsImpl; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.path.*; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ValueDisplayUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import java.util.*; import static com.evolveum.midpoint.prism.polystring.PolyString.getOrig; /** * @author mederly */ @Component public class TextFormatter { @Autowired @Qualifier("cacheRepositoryService") private transient RepositoryService cacheRepositoryService; @Autowired private PrismContext prismContext; @Autowired protected NotificationFunctionsImpl functions; @Autowired private LocalizationService localizationService; private static final Trace LOGGER = TraceManager.getTrace(TextFormatter.class); @SuppressWarnings("unused") public String formatObjectModificationDelta(ObjectDelta<? extends Objectable> objectDelta, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { return formatObjectModificationDelta(objectDelta, hiddenPaths, showOperationalAttributes, null, null); } // objectOld and objectNew are used for explaining changed container values, e.g. assignment[1]/tenantRef (see MID-2047) // if null, they are ignored public String formatObjectModificationDelta(ObjectDelta<? extends Objectable> objectDelta, List<ItemPath> hiddenPaths, boolean showOperationalAttributes, PrismObject objectOld, PrismObject objectNew) { Validate.notNull(objectDelta, "objectDelta is null"); Validate.isTrue(objectDelta.isModify(), "objectDelta is not a modification delta"); PrismObjectDefinition objectDefinition; if (objectNew != null && objectNew.getDefinition() != null) { objectDefinition = objectNew.getDefinition(); } else if (objectOld != null && objectOld.getDefinition() != null) { objectDefinition = objectOld.getDefinition(); } else { objectDefinition = null; } if (LOGGER.isTraceEnabled()) { LOGGER.trace("formatObjectModificationDelta: objectDelta = " + objectDelta.debugDump() + ", hiddenPaths = " + PrettyPrinter.prettyPrint(hiddenPaths)); } StringBuilder retval = new StringBuilder(); List<ItemDelta> toBeDisplayed = filterAndOrderItemDeltas(objectDelta, hiddenPaths, showOperationalAttributes); for (ItemDelta itemDelta : toBeDisplayed) { retval.append(" - "); retval.append(getItemDeltaLabel(itemDelta, objectDefinition)); retval.append(":\n"); formatItemDeltaContent(retval, itemDelta, objectOld, hiddenPaths, showOperationalAttributes); } explainPaths(retval, toBeDisplayed, objectDefinition, objectOld, objectNew, hiddenPaths, showOperationalAttributes); return retval.toString(); } private void explainPaths(StringBuilder sb, List<ItemDelta> deltas, PrismObjectDefinition objectDefinition, PrismObject objectOld, PrismObject objectNew, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { if (objectOld == null && objectNew == null) { return; // no data - no point in trying } boolean first = true; List<ItemPath> alreadyExplained = new ArrayList<>(); for (ItemDelta itemDelta : deltas) { ItemPath pathToExplain = getPathToExplain(itemDelta); if (pathToExplain == null || ItemPathCollectionsUtil.containsSubpathOrEquivalent(alreadyExplained, pathToExplain)) { continue; // null or already processed } PrismObject source = null; Object item = null; if (objectNew != null) { item = objectNew.find(pathToExplain); source = objectNew; } if (item == null && objectOld != null) { item = objectOld.find(pathToExplain); source = objectOld; } if (item == null) { LOGGER.warn("Couldn't find {} in {} nor {}, no explanation could be created.", pathToExplain, objectNew, objectOld); continue; } if (first) { sb.append("\nNotes:\n"); first = false; } String label = getItemPathLabel(pathToExplain, itemDelta.getDefinition(), objectDefinition); // the item should be a PrismContainerValue if (item instanceof PrismContainerValue) { sb.append(" - ").append(label).append(":\n"); formatContainerValue(sb, " ", (PrismContainerValue) item, false, hiddenPaths, showOperationalAttributes); } else { LOGGER.warn("{} in {} was expected to be a PrismContainerValue; it is {} instead", pathToExplain, source, item.getClass()); if (item instanceof PrismContainer) { formatPrismContainer(sb, " ", (PrismContainer) item, false, hiddenPaths, showOperationalAttributes); } else if (item instanceof PrismReference) { formatPrismReference(sb, " ", (PrismReference) item, false); } else if (item instanceof PrismProperty) { formatPrismProperty(sb, " ", (PrismProperty) item); } else { sb.append("Unexpected item: ").append(item).append("\n"); } } alreadyExplained.add(pathToExplain); } } private void formatItemDeltaContent(StringBuilder sb, ItemDelta itemDelta, PrismObject objectOld, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { formatItemDeltaValues(sb, "ADD", itemDelta.getValuesToAdd(), false, itemDelta.getPath(), objectOld, hiddenPaths, showOperationalAttributes); formatItemDeltaValues(sb, "DELETE", itemDelta.getValuesToDelete(), true, itemDelta.getPath(), objectOld, hiddenPaths, showOperationalAttributes); formatItemDeltaValues(sb, "REPLACE", itemDelta.getValuesToReplace(), false, itemDelta.getPath(), objectOld, hiddenPaths, showOperationalAttributes); } private void formatItemDeltaValues(StringBuilder sb, String type, Collection<? extends PrismValue> values, boolean isDelete, ItemPath path, PrismObject objectOld, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { if (values != null) { for (PrismValue prismValue : values) { sb.append(" - ").append(type).append(": "); String prefix = " "; if (isDelete && prismValue instanceof PrismContainerValue) { prismValue = fixEmptyContainerValue((PrismContainerValue) prismValue, path, objectOld); } formatPrismValue(sb, prefix, prismValue, isDelete, hiddenPaths, showOperationalAttributes); if (!(prismValue instanceof PrismContainerValue)) { // container values already end with newline sb.append("\n"); } } } } private PrismValue fixEmptyContainerValue(PrismContainerValue pcv, ItemPath path, PrismObject objectOld) { if (pcv.getId() == null || CollectionUtils.isNotEmpty(pcv.getItems())) { return pcv; } PrismContainer oldContainer = objectOld.findContainer(path); if (oldContainer == null) { return pcv; } PrismContainerValue oldValue = oldContainer.getValue(pcv.getId()); return oldValue != null ? oldValue : pcv; } // todo - should each hiddenAttribute be prefixed with something like F_ATTRIBUTE? Currently it should not be. public String formatAccountAttributes(ShadowType shadowType, List<ItemPath> hiddenAttributes, boolean showOperationalAttributes) { Validate.notNull(shadowType, "shadowType is null"); StringBuilder retval = new StringBuilder(); if (shadowType.getAttributes() != null) { formatContainerValue(retval, "", shadowType.getAttributes().asPrismContainerValue(), false, hiddenAttributes, showOperationalAttributes); } if (shadowType.getCredentials() != null) { formatContainerValue(retval, "", shadowType.getCredentials().asPrismContainerValue(), false, hiddenAttributes, showOperationalAttributes); } if (shadowType.getActivation() != null) { formatContainerValue(retval, "", shadowType.getActivation().asPrismContainerValue(), false, hiddenAttributes, showOperationalAttributes); } if (shadowType.getAssociation() != null) { boolean first = true; for (ShadowAssociationType shadowAssociationType : shadowType.getAssociation()) { if (first) { first = false; retval.append("\n"); } retval.append("Association:\n"); formatContainerValue(retval, " ", shadowAssociationType.asPrismContainerValue(), false, hiddenAttributes, showOperationalAttributes); retval.append("\n"); } } return retval.toString(); } public String formatObject(PrismObject object, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { Validate.notNull(object, "object is null"); StringBuilder retval = new StringBuilder(); formatContainerValue(retval, "", object.getValue(), false, hiddenPaths, showOperationalAttributes); return retval.toString(); } private void formatPrismValue(StringBuilder sb, String prefix, PrismValue prismValue, boolean mightBeRemoved, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { if (prismValue instanceof PrismPropertyValue) { sb.append(ValueDisplayUtil.toStringValue((PrismPropertyValue) prismValue)); } else if (prismValue instanceof PrismReferenceValue) { sb.append(formatReferenceValue((PrismReferenceValue) prismValue, mightBeRemoved)); } else if (prismValue instanceof PrismContainerValue) { sb.append("\n"); formatContainerValue(sb, prefix, (PrismContainerValue) prismValue, mightBeRemoved, hiddenPaths, showOperationalAttributes); } else { sb.append("Unexpected PrismValue type: "); sb.append(prismValue); LOGGER.error("Unexpected PrismValue type: " + prismValue.getClass() + ": " + prismValue); } } private void formatContainerValue(StringBuilder sb, String prefix, PrismContainerValue containerValue, boolean mightBeRemoved, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { // sb.append("Container of type " + containerValue.getParent().getDefinition().getTypeName()); // sb.append("\n"); List<Item> toBeDisplayed = filterAndOrderItems(containerValue.getItems(), hiddenPaths, showOperationalAttributes); for (Item item : toBeDisplayed) { if (item instanceof PrismProperty) { formatPrismProperty(sb, prefix, item); } else if (item instanceof PrismReference) { formatPrismReference(sb, prefix, item, mightBeRemoved); } else if (item instanceof PrismContainer) { formatPrismContainer(sb, prefix, item, mightBeRemoved, hiddenPaths, showOperationalAttributes); } else { sb.append("Unexpected Item type: "); sb.append(item); sb.append("\n"); LOGGER.error("Unexpected Item type: " + item.getClass() + ": " + item); } } } private void formatPrismContainer(StringBuilder sb, String prefix, Item item, boolean mightBeRemoved, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { for (PrismContainerValue subContainerValue : ((PrismContainer<? extends Containerable>) item).getValues()) { String prefixSubContainer = prefix + " "; StringBuilder valueSb = new StringBuilder(); formatContainerValue(valueSb, prefixSubContainer, subContainerValue, mightBeRemoved, hiddenPaths, showOperationalAttributes); if (valueSb.length() > 0) { sb.append(prefix); sb.append(" - "); sb.append(getItemLabel(item)); if (subContainerValue.getId() != null) { sb.append(" #").append(subContainerValue.getId()); } sb.append(":\n"); sb.append(valueSb.toString()); } } } private void formatPrismReference(StringBuilder sb, String prefix, Item item, boolean mightBeRemoved) { sb.append(prefix); sb.append(" - "); sb.append(getItemLabel(item)); sb.append(": "); if (item.size() > 1) { for (PrismReferenceValue referenceValue : ((PrismReference) item).getValues()) { sb.append("\n"); sb.append(prefix).append(" - "); sb.append(formatReferenceValue(referenceValue, mightBeRemoved)); } } else if (item.size() == 1) { sb.append(formatReferenceValue(((PrismReference) item).getAnyValue(), mightBeRemoved)); } sb.append("\n"); } private void formatPrismProperty(StringBuilder sb, String prefix, Item item) { sb.append(prefix); sb.append(" - "); sb.append(getItemLabel(item)); sb.append(": "); if (item.size() > 1) { for (PrismPropertyValue propertyValue : ((PrismProperty<?>) item).getValues()) { sb.append("\n"); sb.append(prefix).append(" - "); sb.append(ValueDisplayUtil.toStringValue(propertyValue)); } } else if (item.size() == 1) { sb.append(ValueDisplayUtil.toStringValue(((PrismProperty<?>) item).getAnyValue())); } sb.append("\n"); } private String formatReferenceValue(PrismReferenceValue value, boolean mightBeRemoved) { OperationResult result = new OperationResult("dummy"); PrismObject<? extends ObjectType> object = value.getObject(); if (object == null) { object = getPrismObject(value.getOid(), mightBeRemoved, result); } String qualifier = ""; if (object != null && object.asObjectable() instanceof ShadowType) { ShadowType shadowType = (ShadowType) object.asObjectable(); ObjectReferenceType resourceRef = shadowType.getResourceRef(); PrismObject<ResourceType> resource = resourceRef.asReferenceValue().getObject(); ResourceType resourceType = null; if (resource == null) { resource = getPrismObject(resourceRef.getOid(), false, result); if (resource != null) { resourceType = (ResourceType) resource.asObjectable(); } } else { resourceType = resource.asObjectable(); } if (resourceType != null) { qualifier = " on " + resourceType.getName(); } else { qualifier = " on resource " + shadowType.getResourceRef().getOid(); } } String referredObjectIdentification; if (object != null) { referredObjectIdentification = PolyString.getOrig(object.asObjectable().getName()) + " (" + object.toDebugType() + ")" + qualifier; } else { String nameOrOid = value.getTargetName() != null ? value.getTargetName().getOrig() : value.getOid(); if (mightBeRemoved) { referredObjectIdentification = "(cannot display the actual name of " + localPart(value.getTargetType()) + ":" + nameOrOid + ", as it might be already removed)"; } else { referredObjectIdentification = localPart(value.getTargetType()) + ":" + nameOrOid; } } return value.getRelation() != null ? referredObjectIdentification + " [" + value.getRelation().getLocalPart() + "]" : referredObjectIdentification; } private <O extends ObjectType> PrismObject<O> getPrismObject(String oid, boolean mightBeRemoved, OperationResult result) { try { Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(GetOperationOptions.createReadOnly()); return (PrismObject<O>) cacheRepositoryService.getObject(ObjectType.class, oid, options, result); } catch (ObjectNotFoundException e) { if (!mightBeRemoved) { LoggingUtils.logException(LOGGER, "Couldn't resolve reference when displaying object name within a notification (it might be already removed)", e); } else { // ok, accepted } } catch (SchemaException e) { LoggingUtils.logException(LOGGER, "Couldn't resolve reference when displaying object name within a notification", e); } return null; } private String localPart(QName qname) { return qname == null ? null : qname.getLocalPart(); } // we call this on filtered list of item deltas - all of they have definition set private String getItemDeltaLabel(ItemDelta itemDelta, PrismObjectDefinition objectDefinition) { return getItemPathLabel(itemDelta.getPath(), itemDelta.getDefinition(), objectDefinition); } private String getItemPathLabel(ItemPath path, Definition deltaDefinition, PrismObjectDefinition objectDefinition) { int lastNameIndex = path.lastNameIndex(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < path.size(); i++) { Object segment = path.getSegment(i); if (ItemPath.isName(segment)) { if (sb.length() > 0) { sb.append("/"); } Definition itemDefinition; if (objectDefinition == null) { if (i == lastNameIndex) { // definition for last segment is the definition taken from delta itemDefinition = deltaDefinition; // this may be null but we don't care } else { itemDefinition = null; // definitions for previous segments are unknown } } else { // todo we could make this iterative (resolving definitions while walking down the path); but this is definitely simpler to implement and debug :) itemDefinition = objectDefinition.findItemDefinition(path.allUpToIncluding(i)); } if (itemDefinition != null && itemDefinition.getDisplayName() != null) { sb.append(resolve(itemDefinition.getDisplayName())); } else { sb.append(ItemPath.toName(segment).getLocalPart()); } } else if (ItemPath.isId(segment)) { sb.append("[").append(ItemPath.toId(segment)).append("]"); } } return sb.toString(); } private String resolve(String key) { if (key != null) { return localizationService.translate(key, null, Locale.getDefault(), key); } else { return null; } } // we call this on filtered list of item deltas - all of they have definition set private ItemPath getPathToExplain(ItemDelta itemDelta) { ItemPath path = itemDelta.getPath(); for (int i = 0; i < path.size(); i++) { Object segment = path.getSegment(i); if (ItemPath.isId(segment)) { if (i < path.size()-1 || itemDelta.isDelete()) { return path.allUpToIncluding(i); } else { // this means that the path ends with [id] segment *and* the value(s) are // only added and deleted, i.e. they are shown in the delta anyway // (actually it is questionable whether path in delta can end with [id] segment, // but we test for this case just to be sure) return null; } } } return null; } private List<ItemDelta> filterAndOrderItemDeltas(ObjectDelta<? extends Objectable> objectDelta, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { List<ItemDelta> toBeDisplayed = new ArrayList<>(objectDelta.getModifications().size()); List<QName> noDefinition = new ArrayList<>(); for (ItemDelta itemDelta: objectDelta.getModifications()) { if (itemDelta.getDefinition() != null) { if ((showOperationalAttributes || !itemDelta.getDefinition().isOperational()) && !NotificationFunctionsImpl .isAmongHiddenPaths(itemDelta.getPath(), hiddenPaths)) { toBeDisplayed.add(itemDelta); } } else { noDefinition.add(itemDelta.getElementName()); } } if (!noDefinition.isEmpty()) { LOGGER.error("ItemDeltas for {} without definition - WILL NOT BE INCLUDED IN NOTIFICATION. Containing object delta:\n{}", noDefinition, objectDelta.debugDump()); } toBeDisplayed.sort((delta1, delta2) -> { Integer order1 = delta1.getDefinition().getDisplayOrder(); Integer order2 = delta2.getDefinition().getDisplayOrder(); if (order1 != null && order2 != null) { return order1 - order2; } else if (order1 == null && order2 == null) { return 0; } else if (order1 == null) { return 1; } else { return -1; } }); return toBeDisplayed; } // we call this on filtered list of items - all of them have definition set private String getItemLabel(Item item) { return item.getDefinition().getDisplayName() != null ? resolve(item.getDefinition().getDisplayName()) : item.getElementName().getLocalPart(); } private List<Item> filterAndOrderItems(Collection<Item> items, List<ItemPath> hiddenPaths, boolean showOperationalAttributes) { if (items == null) { return new ArrayList<>(); } List<Item> toBeDisplayed = new ArrayList<>(items.size()); List<QName> noDefinition = new ArrayList<>(); for (Item item : items) { if (item.getDefinition() != null) { boolean isHidden = NotificationFunctionsImpl.isAmongHiddenPaths(item.getPath(), hiddenPaths); if (!isHidden && (showOperationalAttributes || !item.getDefinition().isOperational()) && !item.isEmpty()) { toBeDisplayed.add(item); } } else { noDefinition.add(item.getElementName()); } } if (!noDefinition.isEmpty()) { LOGGER.error("Items {} without definition - THEY WILL NOT BE INCLUDED IN NOTIFICATION.\nAll items:\n{}", noDefinition, DebugUtil.debugDump(items)); } toBeDisplayed.sort((item1, item2) -> { Integer order1 = item1.getDefinition().getDisplayOrder(); Integer order2 = item2.getDefinition().getDisplayOrder(); if (order1 != null && order2 != null) { return order1 - order2; } else if (order1 == null && order2 == null) { return 0; } else if (order1 == null) { return 1; } else { return -1; } }); return toBeDisplayed; } public String formatUserName(SimpleObjectRef ref, OperationResult result) { return formatUserName((UserType) ref.resolveObjectType(result, true), ref.getOid()); } public String formatUserName(ObjectReferenceType ref, OperationResult result) { UserType user = (UserType) functions.getObjectType(ref, true, result); return formatUserName(user, ref.getOid()); } public String formatUserName(UserType user, String oid) { if (user == null || (user.getName() == null && user.getFullName() == null)) { return oid; } if (user.getFullName() != null) { return getOrig(user.getFullName()) + " (" + getOrig(user.getName()) + ")"; } else { return getOrig(user.getName()); } } // TODO implement seriously public String formatDateTime(XMLGregorianCalendar timestamp) { //DateFormatUtils.format(timestamp.toGregorianCalendar(), DateFormatUtils.SMTP_DATETIME_FORMAT.getPattern()); return String.valueOf(XmlTypeConverter.toDate(timestamp)); } }
923cf051c12c0d0dc43e4e35f87ea89de6fe1e98
1,198
java
Java
10_api/src/main/java/work/icql/api/controller/AuthController.java
icql/icql-archive
2811d365a02ecb112d9869d237c593c5860934a5
[ "Apache-2.0" ]
2
2019-09-11T02:16:59.000Z
2019-09-20T02:20:49.000Z
10_api/src/main/java/work/icql/api/controller/AuthController.java
icql/archived-icql-sample
2811d365a02ecb112d9869d237c593c5860934a5
[ "Apache-2.0" ]
9
2019-12-02T06:22:50.000Z
2020-05-10T05:39:34.000Z
10_api/src/main/java/work/icql/api/controller/AuthController.java
icql/icql-archive
2811d365a02ecb112d9869d237c593c5860934a5
[ "Apache-2.0" ]
null
null
null
31.526316
152
0.781302
1,000,099
package work.icql.api.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import work.icql.api.common.result.Result; import work.icql.api.service.AuthService; import javax.validation.constraints.NotNull; /** * @author icql * @version 1.0 * @date 2018/12/3 17:04 * @Title AuthController * @Description AuthController */ @Api("Users接口文档") @RestController @RequestMapping("/auth") @Validated public class AuthController { @Autowired private AuthService authService; @ApiOperation("授权") @PostMapping public Result authentication(@RequestParam("account") @NotNull String account, @RequestParam("password") @NotNull String password, Integer expire) { String token = authService.auth(account, password, expire); return Result.success(token); } }
923cf0c06be6caf5138d9fd71691a7605951e646
899
java
Java
app/model/validations/FileTypeValidation.java
MiteshSharma/ContentApi
2413f69e0fe308479ae35e10b3172908e7b9c8e0
[ "MIT" ]
1
2017-08-25T16:06:14.000Z
2017-08-25T16:06:14.000Z
app/model/validations/FileTypeValidation.java
MiteshSharma/ContentApi
2413f69e0fe308479ae35e10b3172908e7b9c8e0
[ "MIT" ]
null
null
null
app/model/validations/FileTypeValidation.java
MiteshSharma/ContentApi
2413f69e0fe308479ae35e10b3172908e7b9c8e0
[ "MIT" ]
null
null
null
22.475
67
0.705228
1,000,100
package model.validations; import com.fasterxml.jackson.databind.JsonNode; import org.mongodb.morphia.annotations.Embedded; import org.mongodb.morphia.annotations.Property; /** * Created by mitesh on 12/11/16. */ @Embedded public class FileTypeValidation extends Validation { @Property("isValidationNeeded") private boolean isValidationNeeded; @Property("fileType") private long fileType; public FileTypeValidation() {} public boolean getIsValidationNeeded() { return isValidationNeeded; } public void setIsValidationNeeded(boolean isValidationNeeded) { this.isValidationNeeded = isValidationNeeded; } public long getFileType() { return fileType; } public void setFileType(long fileType) { this.fileType = fileType; } @Override public boolean isValid(JsonNode node) { return true; } }
923cf143f4e73dea12b857b619b4bc6ca14c6e28
4,775
java
Java
src/main/java/org/fredy/jugen/cli/JUGenCLI.java
GArlington/jugen
6ef83ae6231abd5e81d576e948e29e7937a7cfb3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/fredy/jugen/cli/JUGenCLI.java
GArlington/jugen
6ef83ae6231abd5e81d576e948e29e7937a7cfb3
[ "Apache-2.0" ]
null
null
null
src/main/java/org/fredy/jugen/cli/JUGenCLI.java
GArlington/jugen
6ef83ae6231abd5e81d576e948e29e7937a7cfb3
[ "Apache-2.0" ]
null
null
null
37.598425
101
0.595183
1,000,101
/* * 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.fredy.jugen.cli; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.fredy.jugen.core.Executable; import org.fredy.jugen.core.JUGen; import org.fredy.jugen.core.JUGenException; import org.fredy.jugen.core.JUGenParam; import org.fredy.jugen.core.Template; /** * JUGen command line interface. * @author fredy */ public class JUGenCLI implements Executable { private static final String JUNIT4_VERSION = "4"; private static final String JUNIT3_VERSION = "3"; private static final String OVERWRITE = "--overwrite="; private static final String EXCLUDE = "--exclude="; private static final String YES = "yes"; private static final String NO = "no"; private String projectDir; private String destinationDir; private String templateDir; private Template template; private boolean overwrite; private List<String> excludeList = new ArrayList<String>(); private JUGen jugen = new JUGen(); public JUGenCLI(String[] args) { validateArgs(args); projectDir = args[0]; destinationDir = args[1]; templateDir = args[2]; if (args.length == 5 || args.length == 6) { for (int i = 4; i < args.length; i++) { if (args[i].startsWith(OVERWRITE)) { String value = args[i].substring(OVERWRITE.length()); overwrite = (value.equals("yes")) ? true : false; } else if (args[i].startsWith(EXCLUDE)) { String value = args[i].substring(EXCLUDE.length()); excludeList = Arrays.asList(value.split(",")); } } } if (JUNIT3_VERSION.equals(args[3].trim())) { template = Template.JUNIT3; } else { template = Template.JUNIT4; } } @Override public void run() { JUGenParam param = new JUGenParam(); param.setFile(new File(projectDir)); param.setDestDir(new File(destinationDir)); param.setTemplateDir(new File(templateDir)); param.setTemplate(template); param.setOverwrite(overwrite); param.setExcludeList(excludeList); jugen.generateJUnit(param); } private void validateArgs(String[] args) { if (args.length < 4 || args.length > 6) { throw new JUGenException(getUsage()); } if (!new File(args[0]).isDirectory()) { throw new JUGenException(args[0] + " is not a directory"); } if (!new File(args[2]).isDirectory()) { throw new JUGenException(args[2] + " is not a directory"); } if (!JUNIT3_VERSION.equals(args[3].trim()) && !JUNIT4_VERSION.equals(args[3].trim())) { throw new JUGenException(args[3] + " must be either 3 or 4"); } if (args.length == 5 || args.length == 6) { for (int i = 4; i < args.length; i++) { if (args[i].startsWith(OVERWRITE)) { String value = args[i].substring(OVERWRITE.length()); if (!value.equals(YES) && !value.equals(NO)) { throw new JUGenException("--overwrite option can only have yes or no value"); } } else if (args[i].startsWith(EXCLUDE)) { String value = args[i].substring(EXCLUDE.length()).trim(); if (value.length() == 0) { throw new JUGenException("Invalid --exclude option"); } } else { throw new JUGenException("Invalid option"); } } } } private String getUsage() { return "Usage: java -jar jugen.jar <project_dir> <destination_dir> " + "<template_dir> <junit_version> [--overwrite=[yes|no]] " + "[--exclude=[comma_separated_list]]"; } }
923cf16e9186756ea077d036dc94df3ca1875c7d
5,600
java
Java
app/src/main/java/com/multicoredump/tutorial/plumtwitter/activities/ProfileActivity.java
multicoredump/PlumTwitter
485ba86d58b0b5bc08047917160e8b0908e50797
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/multicoredump/tutorial/plumtwitter/activities/ProfileActivity.java
multicoredump/PlumTwitter
485ba86d58b0b5bc08047917160e8b0908e50797
[ "Apache-2.0" ]
2
2017-03-27T08:04:21.000Z
2017-04-03T07:52:02.000Z
app/src/main/java/com/multicoredump/tutorial/plumtwitter/activities/ProfileActivity.java
multicoredump/PlumTwitter
485ba86d58b0b5bc08047917160e8b0908e50797
[ "Apache-2.0" ]
null
null
null
37.583893
109
0.708036
1,000,102
package com.multicoredump.tutorial.plumtwitter.activities; import android.content.Intent; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.bumptech.glide.Glide; import com.loopj.android.http.JsonHttpResponseHandler; import com.multicoredump.tutorial.plumtwitter.R; import com.multicoredump.tutorial.plumtwitter.adapter.TweetFragmentPagerAdapater; import com.multicoredump.tutorial.plumtwitter.databinding.ActivityProfileBinding; import com.multicoredump.tutorial.plumtwitter.fragments.BaseTimelineTabFragment; import com.multicoredump.tutorial.plumtwitter.fragments.ComposeFragment; import com.multicoredump.tutorial.plumtwitter.fragments.LikesFragment; import com.multicoredump.tutorial.plumtwitter.fragments.UserTimelineFragment; import com.multicoredump.tutorial.plumtwitter.model.User; import org.json.JSONObject; import org.parceler.Parcels; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header; public class ProfileActivity extends AppCompatActivity implements ComposeFragment.OnPostTweetListener, BaseTimelineTabFragment.TwitterCurrentUserProvider{ private static final String TAG = ProfileActivity.class.getName(); private static String PAGER_INDEX = "Pager_Index"; ActivityProfileBinding binding; private User user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_profile); //Get user argument Intent intent = getIntent(); user = Parcels.unwrap(intent.getParcelableExtra("user")); setSupportActionBar(binding.toolbar); getSupportActionBar().setDisplayUseLogoEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); //Backdrop image Glide.with(this) .load(user.getCoverImageURL()) .into(binding.backdrop); //Profile image Glide.with(this) .load(user.getProfileBiggerImageURL()) .into(binding.ivProfileImage); binding.tvUsername.setText(user.getName()); binding.tvScreenName.setText("@" + user.getScreenName()); binding.tvFollowerCount.setText(user.getFollowerCount()); binding.followingCount.setText(user.getFollowingCount()); // description if (user.getDescription() != null && !user.getDescription().isEmpty()) { binding.tvDescription.setVisibility(View.VISIBLE); binding.tvDescription.setText(user.getDescription()); } else{ binding.tvDescription.setVisibility(View.GONE); } // location if (user.getLocation() != null && !user.getLocation().isEmpty()) { binding.ivLocation.setVisibility(View.VISIBLE); binding.ivLocation.setColorFilter(getResources().getColor(R.color.colorPrimary)); binding.tvLocation.setText(user.getLocation()); } else { binding.ivLocation.setVisibility(View.GONE); binding.tvLocation.setVisibility(View.GONE); } // Set up fragments and view pager List<BaseTimelineTabFragment> fragments = new ArrayList<>(); BaseTimelineTabFragment userTimelineFragment = UserTimelineFragment.newInstance(user); BaseTimelineTabFragment favoritesFragment = LikesFragment.newInstance(user); fragments.add(userTimelineFragment.getTabPosition(), userTimelineFragment); fragments.add(favoritesFragment.getTabPosition(), favoritesFragment); ProfilePagerAdapter adapter = new ProfilePagerAdapter(getSupportFragmentManager(), fragments); binding.viewpager.setAdapter(adapter); binding.tabs.setupWithViewPager(binding.viewpager); // set FAB binding.fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ComposeFragment composeFragment = ComposeFragment.newInstance(user, null); composeFragment.show(getSupportFragmentManager(), "compose"); } }); } // To save tab position public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(PAGER_INDEX, binding.tabs.getSelectedTabPosition()); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); binding.viewpager.setCurrentItem(savedInstanceState.getInt(PAGER_INDEX)); } @Override public JsonHttpResponseHandler getJsonHttpResponseHandler() { return new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject object) { } }; } @Override public User getCurrentUser() { return user; } private class ProfilePagerAdapter extends TweetFragmentPagerAdapater { ProfilePagerAdapter(FragmentManager fm, List<BaseTimelineTabFragment> fragments) { super(fm, fragments); } @Override public CharSequence getPageTitle(int position) { return fragments.get(position).getTabTitle(); } } }
923cf1c1ae6f88be2c58beeff2968d61d193a57a
9,357
java
Java
bookkeeper-server/src/test/java/org/apache/bookkeeper/bookie/GarbageCollectorThreadTest.java
pjfanning/bookkeeper
82248121930a7a54431aae0c37ae7f96cb0d2d53
[ "Apache-2.0" ]
null
null
null
bookkeeper-server/src/test/java/org/apache/bookkeeper/bookie/GarbageCollectorThreadTest.java
pjfanning/bookkeeper
82248121930a7a54431aae0c37ae7f96cb0d2d53
[ "Apache-2.0" ]
null
null
null
bookkeeper-server/src/test/java/org/apache/bookkeeper/bookie/GarbageCollectorThreadTest.java
pjfanning/bookkeeper
82248121930a7a54431aae0c37ae7f96cb0d2d53
[ "Apache-2.0" ]
null
null
null
39.817021
93
0.701934
1,000,103
/* * * 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.bookkeeper.bookie; import static org.apache.bookkeeper.bookie.storage.EntryLogTestUtils.logIdFromLocation; import static org.apache.bookkeeper.bookie.storage.EntryLogTestUtils.makeEntry; import static org.apache.bookkeeper.bookie.storage.EntryLogTestUtils.newDirsManager; import static org.apache.bookkeeper.bookie.storage.EntryLogTestUtils.newLegacyEntryLogger; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.openMocks; import java.io.File; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.bookkeeper.bookie.storage.EntryLogger; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.conf.TestBKConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.MockLedgerManager; import org.apache.bookkeeper.slogger.Slogger; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.test.TmpDirs; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.powermock.reflect.Whitebox; /** * Unit test for {@link GarbageCollectorThread}. */ @SuppressWarnings("deprecation") public class GarbageCollectorThreadTest { private static final Slogger slog = Slogger.CONSOLE; private final TmpDirs tmpDirs = new TmpDirs(); @InjectMocks @Spy private GarbageCollectorThread mockGCThread; @Mock private LedgerManager ledgerManager; @Mock private StatsLogger statsLogger; @Mock private ScheduledExecutorService gcExecutor; private ServerConfiguration conf = spy(new ServerConfiguration().setAllowLoopback(true)); private CompactableLedgerStorage ledgerStorage = mock(CompactableLedgerStorage.class); @Before public void setUp() throws Exception { conf.setAllowLoopback(true); openMocks(this); } @After public void cleanup() throws Exception { tmpDirs.cleanup(); } @Test public void testCompactEntryLogWithException() throws Exception { AbstractLogCompactor mockCompactor = mock(AbstractLogCompactor.class); when(mockCompactor.compact(any(EntryLogMetadata.class))) .thenThrow(new RuntimeException("Unexpected compaction error")); Whitebox.setInternalState(mockGCThread, "compactor", mockCompactor); // Although compaction of an entry log fails due to an unexpected error, // the `compacting` flag should return to false AtomicBoolean compacting = Whitebox.getInternalState(mockGCThread, "compacting"); assertFalse(compacting.get()); mockGCThread.compactEntryLog(new EntryLogMetadata(9999)); assertFalse(compacting.get()); } @Test public void testCalculateUsageBucket() { // Valid range for usage is [0.0 to 1.0] final int numBuckets = 10; int[] usageBuckets = new int[numBuckets]; String[] bucketNames = new String[numBuckets]; for (int i = 0; i < numBuckets; i++) { usageBuckets[i] = 0; bucketNames[i] = String.format("%d%%", (i + 1) * 10); } int items = 10000; for (int item = 0; item <= items; item++) { double usage = ((double) item / (double) items); int index = mockGCThread.calculateUsageIndex(numBuckets, usage); assertFalse("Boundary condition exceeded", index < 0 || index >= numBuckets); slog.kv("usage", usage) .kv("index", index) .info("Mapped usage to index"); usageBuckets[index]++; } Slogger sl = slog.ctx(); for (int i = 0; i < numBuckets; i++) { sl = sl.kv(bucketNames[i], usageBuckets[i]); } sl.info("Compaction: entry log usage buckets"); int sum = 0; for (int i = 0; i < numBuckets; i++) { sum += usageBuckets[i]; } Assert.assertEquals("Incorrect number of items", items + 1, sum); } @Test public void testExtractMetaFromEntryLogsLegacy() throws Exception { File ledgerDir = tmpDirs.createNew("testExtractMeta", "ledgers"); testExtractMetaFromEntryLogs( newLegacyEntryLogger(20000, ledgerDir), ledgerDir); } private void testExtractMetaFromEntryLogs(EntryLogger entryLogger, File ledgerDir) throws Exception { MockLedgerStorage storage = new MockLedgerStorage(); MockLedgerManager lm = new MockLedgerManager(); GarbageCollectorThread gcThread = new GarbageCollectorThread( TestBKConfiguration.newServerConfiguration(), lm, newDirsManager(ledgerDir), storage, entryLogger, NullStatsLogger.INSTANCE); // Add entries. // Ledger 1 is on first entry log // Ledger 2 spans first, second and third entry log // Ledger 3 is on the third entry log (which is still active when extract meta) long loc1 = entryLogger.addEntry(1L, makeEntry(1L, 1L, 5000)); long loc2 = entryLogger.addEntry(2L, makeEntry(2L, 1L, 5000)); assertThat(logIdFromLocation(loc2), equalTo(logIdFromLocation(loc1))); long loc3 = entryLogger.addEntry(2L, makeEntry(2L, 1L, 15000)); assertThat(logIdFromLocation(loc3), greaterThan(logIdFromLocation(loc2))); long loc4 = entryLogger.addEntry(2L, makeEntry(2L, 1L, 15000)); assertThat(logIdFromLocation(loc4), greaterThan(logIdFromLocation(loc3))); long loc5 = entryLogger.addEntry(3L, makeEntry(3L, 1L, 1000)); assertThat(logIdFromLocation(loc5), equalTo(logIdFromLocation(loc4))); long logId1 = logIdFromLocation(loc2); long logId2 = logIdFromLocation(loc3); long logId3 = logIdFromLocation(loc5); entryLogger.flush(); storage.setMasterKey(1L, new byte[0]); storage.setMasterKey(2L, new byte[0]); storage.setMasterKey(3L, new byte[0]); assertThat(entryLogger.getFlushedLogIds(), containsInAnyOrder(logId1, logId2)); assertTrue(entryLogger.logExists(logId3)); // all ledgers exist, nothing should disappear final EntryLogMetadataMap entryLogMetaMap = gcThread.getEntryLogMetaMap(); gcThread.extractMetaFromEntryLogs(); assertThat(entryLogger.getFlushedLogIds(), containsInAnyOrder(logId1, logId2)); assertTrue(entryLogMetaMap.containsKey(logId1)); assertTrue(entryLogMetaMap.containsKey(logId2)); assertTrue(entryLogger.logExists(logId3)); // log 2 is 100% ledger 2, so it should disappear if ledger 2 is deleted entryLogMetaMap.clear(); storage.deleteLedger(2L); gcThread.extractMetaFromEntryLogs(); assertThat(entryLogger.getFlushedLogIds(), containsInAnyOrder(logId1)); assertTrue(entryLogMetaMap.containsKey(logId1)); assertTrue(entryLogger.logExists(logId3)); // delete all ledgers, all logs except the current should be deleted entryLogMetaMap.clear(); storage.deleteLedger(1L); storage.deleteLedger(3L); gcThread.extractMetaFromEntryLogs(); assertThat(entryLogger.getFlushedLogIds(), empty()); assertTrue(entryLogMetaMap.isEmpty()); assertTrue(entryLogger.logExists(logId3)); // add enough entries to roll log, log 3 can not be GC'd long loc6 = entryLogger.addEntry(3L, makeEntry(3L, 1L, 25000)); assertThat(logIdFromLocation(loc6), greaterThan(logIdFromLocation(loc5))); entryLogger.flush(); assertThat(entryLogger.getFlushedLogIds(), containsInAnyOrder(logId3)); entryLogMetaMap.clear(); gcThread.extractMetaFromEntryLogs(); assertThat(entryLogger.getFlushedLogIds(), empty()); assertTrue(entryLogMetaMap.isEmpty()); assertFalse(entryLogger.logExists(logId3)); } }
923cf287982768564a77a6231db0bd7ec975107a
1,721
java
Java
GoogleMarketSet/GoogleMarket/src/com/szxx/googleplay/manager/ThreadManager.java
chenjunivy/androidcode
b8ad94958a03c640f71df9edbfb6b34807e87667
[ "Apache-2.0" ]
null
null
null
GoogleMarketSet/GoogleMarket/src/com/szxx/googleplay/manager/ThreadManager.java
chenjunivy/androidcode
b8ad94958a03c640f71df9edbfb6b34807e87667
[ "Apache-2.0" ]
null
null
null
GoogleMarketSet/GoogleMarket/src/com/szxx/googleplay/manager/ThreadManager.java
chenjunivy/androidcode
b8ad94958a03c640f71df9edbfb6b34807e87667
[ "Apache-2.0" ]
null
null
null
26.075758
81
0.715863
1,000,104
package com.szxx.googleplay.manager; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; import java.util.concurrent.TimeUnit; /** * 线程管理器,管理线程池 * * @author System_ivy * */ public class ThreadManager { private static ThreadPool mthreaPool; public static ThreadPool getThreadPool() { if (mthreaPool == null) { synchronized (ThreadManager.class) { if (mthreaPool == null) { int cpuCount = Runtime.getRuntime().availableProcessors(); //获取cpu数量 System.out.println("cpu 个数是 :" + cpuCount); int threadCount = 10; mthreaPool = new ThreadPool(threadCount, threadCount, 1L); } } } return mthreaPool; } // 线程池 public static class ThreadPool { private int corePoolSize; // 核心线程数 private int maximumPoolSize; // 最大线程数 private long keepAliveTime; // 休息时间 private ThreadPoolExecutor executor; private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) { this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = keepAliveTime; } //添加线程到线程池中执行 public void executeThread(Runnable r) { /** * 参数:1.核心数 2.最大线程数 3.线程休眠时间 4.时间单位 5.线程队列 6.线程工厂 7、线程异常处理 */ if (executor == null) { executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(), Executors.defaultThreadFactory(), new AbortPolicy()); } //执行一个Runnable对象 executor.execute(r); } //将线程从线程中移除 public void removeThread(Runnable r){ executor.getQueue().remove(r); } } }
923cf2b664b718dbc57631adb3b5367cd6842437
2,193
java
Java
src/main/java/net/sb27team/centauri/explorer/FileComponent.java
SB27Team/Centauri
5b8990208fe99f1ca51afde45985ece4f47150ac
[ "MIT" ]
5
2018-05-17T11:11:55.000Z
2021-09-14T21:47:29.000Z
src/main/java/net/sb27team/centauri/explorer/FileComponent.java
SB27Team/Centauri
5b8990208fe99f1ca51afde45985ece4f47150ac
[ "MIT" ]
10
2018-05-13T14:04:30.000Z
2018-09-18T14:33:38.000Z
src/main/java/net/sb27team/centauri/explorer/FileComponent.java
SB27Team/Centauri
5b8990208fe99f1ca51afde45985ece4f47150ac
[ "MIT" ]
3
2018-05-19T17:34:06.000Z
2018-06-08T13:38:12.000Z
43
463
0.749202
1,000,105
/* * Copyright (c) 2017-2018 SB27Team (superblaubeere27, Cubixy, Xc3pt1on, SplotyCode) * * 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 net.sb27team.centauri.explorer; import net.sb27team.centauri.Centauri; import org.objectweb.asm.tree.ClassNode; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; public class FileComponent extends Component { private ZipEntry zipEntry; public FileComponent(String name, Directory parent, ZipEntry zipEntry) { super(name, parent); this.zipEntry = zipEntry; } public ZipEntry getZipEntry() { return zipEntry; } public InputStream openInputStream() throws IOException { return Centauri.INSTANCE.getInputStream(this); } public void update(byte[] newData) { Centauri.INSTANCE.updateData(this, newData); } public void setZipEntry(ZipEntry zipEntry) { this.zipEntry = zipEntry; } public ClassNode getClassNode() throws IOException { return Centauri.INSTANCE.getClassNode(this); } public void updateClassNode(ClassNode classNode) { update(Centauri.INSTANCE.classNodeToBytes(classNode)); } }
923cf2bb9d22b9100b479d0b58031b44c8d3df4b
9,979
java
Java
apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/test/java/co/elastic/apm/agent/grpc/testapp/HelloClient.java
JulienOrain/apm-agent-java
295747606ea6e5ebcbfc8993ddbe9384bd657dc2
[ "Apache-2.0" ]
1
2021-08-04T05:10:14.000Z
2021-08-04T05:10:14.000Z
apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/test/java/co/elastic/apm/agent/grpc/testapp/HelloClient.java
JulienOrain/apm-agent-java
295747606ea6e5ebcbfc8993ddbe9384bd657dc2
[ "Apache-2.0" ]
14
2021-06-14T06:59:57.000Z
2022-03-14T01:30:51.000Z
apm-agent-plugins/apm-grpc/apm-grpc-plugin/src/test/java/co/elastic/apm/agent/grpc/testapp/HelloClient.java
JulienOrain/apm-agent-java
295747606ea6e5ebcbfc8993ddbe9384bd657dc2
[ "Apache-2.0" ]
3
2021-06-04T13:35:28.000Z
2021-07-16T08:42:42.000Z
32.504886
149
0.640645
1,000,106
/*- * #%L * Elastic APM Java agent * %% * Copyright (C) 2018 - 2020 Elastic and contributors * %% * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. * #L% */ package co.elastic.apm.agent.grpc.testapp; import com.google.common.util.concurrent.ListenableFuture; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.Deadline; import io.grpc.ManagedChannel; import io.grpc.MethodDescriptor; import io.grpc.StatusRuntimeException; import io.grpc.elastic.test.TestClientCallImpl; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; public abstract class HelloClient<Req, Rep> { private static final Logger logger = LoggerFactory.getLogger(HelloClient.class); private final ManagedChannel channel; private final AtomicLong errorCount; private final AtomicReference<String> exeptionMethod; protected HelloClient(ManagedChannel channel) { this.channel = channel; this.errorCount = new AtomicLong(0); this.exeptionMethod = new AtomicReference<>(); } protected static Deadline getDeadline() { return Deadline.after(10, TimeUnit.SECONDS); } public abstract Req buildRequest(String user, int depth); public abstract Rep executeBlocking(Req request); public abstract ListenableFuture<Rep> executeAsync(Req request); public abstract String getResponseMessage(Rep response); public long getErrorCount() { return errorCount.get(); } public void setExceptionMethod(String method) { exeptionMethod.set(method); } protected ClientInterceptor getClientInterceptor() { return new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) { return new TestClientCallImpl<ReqT, RespT>(next.newCall(method, callOptions), exeptionMethod); } }; } /** * Synchronous (blocking) hello * * @param user user name * @param depth depth of nested calls, {@literal 0} for simple calls, use positive value for nesting * @return an hello statement */ public final String sayHello(String user, int depth) { Req request = buildRequest(user, depth); Rep reply; try { reply = executeBlocking(request); } catch (StatusRuntimeException e) { logger.error("server error {} {}", e.getStatus(), e.getMessage()); errorCount.incrementAndGet(); return null; } return getResponseMessage(reply); } /** * Asynchronous hello * * @param user user name * @param depth depth of nested calls, {@literal 0} for simple calls, use positive value for nesting * @return an hello statement */ public final Future<String> saysHelloAsync(String user, int depth) { Req request = buildRequest(user, depth); ListenableFuture<Rep> future = executeAsync(request); return new Future<>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { return future.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return future.isCancelled(); } @Override public boolean isDone() { return future.isDone(); } @Override public String get() throws InterruptedException, ExecutionException { // TODO : check if something is thrown when there is a server error return getResponseMessage(future.get()); } @Override public String get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { // TODO : check if something is thrown when there is a server error return getResponseMessage(future.get(timeout, unit)); } }; } /** * Client streaming hello * * @param users list of users to say hello to * @param depth number of hello that should be said * @return an hello statement */ public String sayManyHello(List<String> users, int depth) { List<Req> requests = users.stream() .map(u -> buildRequest(u, depth)) .collect(Collectors.toList()); AtomicReference<Rep> result = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); StreamObserver<Rep> responseObserver = new StreamObserver<>() { @Override public void onNext(Rep reply) { result.set(reply); } @Override public void onError(Throwable throwable) { errorCount.incrementAndGet(); throw new IllegalStateException("unexpected error", throwable); } @Override public void onCompleted() { latch.countDown(); } }; StreamObserver<Req> requestObserver = doSayManyHello(responseObserver); for (Req request : requests) { requestObserver.onNext(request); } requestObserver.onCompleted(); awaitLatch(latch); return getResponseMessage(result.get()); } protected abstract StreamObserver<Req> doSayManyHello(StreamObserver<Rep> responseObserver); /** * Server streaming hello * * @param user user name * @param depth depth of nested calls, {@literal 0} for simple calls, use positive value for nesting * @return an hello statement */ public String sayHelloMany(String user, int depth) { CountDownLatch latch = new CountDownLatch(1); Req request = buildRequest(user, depth); StringBuilder sb = new StringBuilder(); StreamObserver<Rep> streamObserver = concatenateStreamObserver(latch, sb); doSayHelloMany(request, streamObserver); awaitLatch(latch); return sb.toString(); } protected abstract void doSayHelloMany(Req request, StreamObserver<Rep> streamObserver); public String sayHelloManyMany(List<String> users, int depth) { CountDownLatch latch = new CountDownLatch(1); StringBuilder sb = new StringBuilder(); StreamObserver<Rep> streamObserver = concatenateStreamObserver(latch, sb); StreamObserver<Req> requestStream = doSayHelloManyMany(streamObserver); for (String user : users) { requestStream.onNext(buildRequest(user, depth)); } // we use a specific message to make server end the call requestStream.onNext(buildRequest("nobody", 0)); // client still needs to complete the call, otherwise server will still have a request pending which // prevents proper server shutdown. requestStream.onCompleted(); awaitLatch(latch); return sb.toString(); } protected abstract StreamObserver<Req> doSayHelloManyMany(StreamObserver<Rep> streamObserver); private static void awaitLatch(CountDownLatch latch) { try { boolean await = latch.await(1, TimeUnit.SECONDS); if (!await) { throw new IllegalStateException("giving up waiting for latch, something is wrong"); } } catch (InterruptedException e) { throw new IllegalStateException(e); } } private StreamObserver<Rep> concatenateStreamObserver(CountDownLatch latch, StringBuilder sb) { return new StreamObserver<>() { @Override public void onNext(Rep rep) { if (sb.length() > 0) { sb.append(" "); } sb.append(getResponseMessage(rep)); } @Override public void onError(Throwable throwable) { errorCount.incrementAndGet(); throw new IllegalStateException("unexpected error", throwable); } @Override public void onCompleted() { // server terminated call latch.countDown(); } }; } public final void stop() throws InterruptedException { boolean doShutdown = !channel.isShutdown(); if (doShutdown) { channel.shutdown() .awaitTermination(1, TimeUnit.SECONDS); } if (!channel.isTerminated()) { logger.warn("channel has been shut down with running calls"); } channel.awaitTermination(1, TimeUnit.SECONDS); logger.info("client channel has been properly shut down"); } }
923cf41ee72dab27d739584f296f8e869f48792d
1,011
java
Java
spring-social-microsoft/src/main/java/org/springframework/social/microsoft/config/xml/MicrosoftConfigBeanDefinitionParser.java
dmunozfer/spring-social-microsoft
54919aaebd0511f3ade1e1d556326368b00bd399
[ "Apache-2.0" ]
1
2018-07-09T20:47:16.000Z
2018-07-09T20:47:16.000Z
spring-social-microsoft/src/main/java/org/springframework/social/microsoft/config/xml/MicrosoftConfigBeanDefinitionParser.java
dmunozfer/spring-social-microsoft
54919aaebd0511f3ade1e1d556326368b00bd399
[ "Apache-2.0" ]
null
null
null
spring-social-microsoft/src/main/java/org/springframework/social/microsoft/config/xml/MicrosoftConfigBeanDefinitionParser.java
dmunozfer/spring-social-microsoft
54919aaebd0511f3ade1e1d556326368b00bd399
[ "Apache-2.0" ]
null
null
null
42.125
126
0.840752
1,000,107
package org.springframework.social.microsoft.config.xml; import org.springframework.social.config.xml.AbstractProviderConfigBeanDefinitionParser; import org.springframework.social.microsoft.config.support.MicrosoftApiHelper; import org.springframework.social.microsoft.connect.MicrosoftConnectionFactory; import org.springframework.social.microsoft.security.MicrosoftAuthenticationService; import org.springframework.social.security.provider.SocialAuthenticationService; /** * Implementation of {@link AbstractConnectionFactoryBeanDefinitionParser} that creates a {@link MicrosoftConnectionFactory}. */ public class MicrosoftConfigBeanDefinitionParser extends AbstractProviderConfigBeanDefinitionParser { public MicrosoftConfigBeanDefinitionParser() { super(MicrosoftConnectionFactory.class, MicrosoftApiHelper.class); } @Override protected Class<? extends SocialAuthenticationService<?>> getAuthenticationServiceClass() { return MicrosoftAuthenticationService.class; } }
923cf5f6b16309dde75d1dd5c1f9383374d6e65b
1,931
java
Java
Leetcode0423.java
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
1
2020-06-28T06:29:05.000Z
2020-06-28T06:29:05.000Z
Leetcode0423.java
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
null
null
null
Leetcode0423.java
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
null
null
null
24.443038
72
0.435526
1,000,108
import java.util.HashMap; import java.util.Map; /** * Created by dezhonger on 2019/12/13 */ public class Leetcode0423 { Map<Integer, String> map = new HashMap<>(); public String originalDigits(String s) { map.put(0, "zero"); map.put(1, "one"); map.put(2, "two"); map.put(3, "three"); map.put(4, "four"); map.put(5, "five"); map.put(6, "six"); map.put(7, "seven"); map.put(8, "eight"); map.put(9, "nine"); int[] cnt = new int[26]; int[] res = new int[10]; for (char ch : s.toCharArray()) { cnt[ch - 'a']++; } //only zero have letter 'z' res[0] = cnt['z' - 'a']; remove(cnt, 0, res[0]); //only six have letter 'x' res[6] = cnt['x' - 'a']; remove(cnt, 6, res[6]); //only two have letter 'w' res[2] = cnt['w' - 'a']; remove(cnt, 2, res[2]); //only four have letter 'u' res[4] = cnt['u' - 'a']; remove(cnt, 4, res[4]); //then next only five have letter 'f', four have been calculate res[5] = cnt['f' - 'a']; remove(cnt, 5, cnt[5]); //only eight have letter 'g' res[8] = cnt['g' - 'a']; remove(cnt, 8, res[8]); res[7] = cnt['v' - 'a']; remove(cnt, 7, cnt[7]); res[9] = cnt['i' - 'a']; remove(cnt, 9, cnt[9]); res[1] = cnt['o' - 'a']; remove(cnt, 1, cnt[1]); res[3] = cnt['r' - 'a']; remove(cnt, 3, cnt[3]); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { for (int j = 0; j < res[i]; j++) sb.append((char)(i + '0')); } return sb.toString(); } void remove(int[] cnt, int x, int c) { String s = map.get(x); for (char ch : s.toCharArray()) { cnt[ch - 'a'] -= c; } } }
923cf63942fe876376d80ba6203834161bdc9987
183
java
Java
src_6/org/benf/cfr/tests/DependentTautology.java
Marcono1234/cfr_tests
f043e01f14efb987a2f6b6a3c656c9d5f67635bd
[ "MIT" ]
8
2019-06-05T11:02:56.000Z
2021-04-25T01:41:18.000Z
src_6/org/benf/cfr/tests/DependentTautology.java
Marcono1234/cfr_tests
f043e01f14efb987a2f6b6a3c656c9d5f67635bd
[ "MIT" ]
9
2019-08-22T12:32:13.000Z
2022-02-24T07:09:24.000Z
src_6/org/benf/cfr/tests/DependentTautology.java
Marcono1234/cfr_tests
f043e01f14efb987a2f6b6a3c656c9d5f67635bd
[ "MIT" ]
5
2020-02-01T01:51:23.000Z
2022-02-22T15:01:33.000Z
18.3
36
0.519126
1,000,109
package org.benf.cfr.tests; public class DependentTautology { public void foo(boolean a) { if (a && a && a && a) { System.out.println("A"); } } }
923cf6cb7813848de38042fe310eee41322a617e
43,727
java
Java
src/com/dalsemi/onewire/container/OneWireContainer20.java
boangri/OneWireAPI
4a26ed8e071958d06d5bb240070396e6c681e4f3
[ "MIT" ]
null
null
null
src/com/dalsemi/onewire/container/OneWireContainer20.java
boangri/OneWireAPI
4a26ed8e071958d06d5bb240070396e6c681e4f3
[ "MIT" ]
null
null
null
src/com/dalsemi/onewire/container/OneWireContainer20.java
boangri/OneWireAPI
4a26ed8e071958d06d5bb240070396e6c681e4f3
[ "MIT" ]
null
null
null
33.026435
109
0.604844
1,000,110
/*--------------------------------------------------------------------------- * Copyright (C) 1999,2000 Maxim Integrated Products, All Rights Reserved. * * 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 MAXIM INTEGRATED PRODUCTS 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. * * Except as contained in this notice, the name of Maxim Integrated Products * shall not be used except as stated in the Maxim Integrated Products * Branding Policy. *--------------------------------------------------------------------------- */ package com.dalsemi.onewire.container; import java.util.Vector; import java.util.Enumeration; import com.dalsemi.onewire.*; import com.dalsemi.onewire.utils.*; import com.dalsemi.onewire.adapter.*; /** *<P>1-Wire&reg; container that encapsulates the functionality of the 1-Wire *family type <b>20</b> (hex), Maxim Integrated Products part number: <B> DS2450, * 1-Wire Quad A/D Converter</B>.</P> * * * <H3>Features</H3> * <UL> * <LI>Four high-impedance inputs * <LI>Programmable input range (2.56V, 5.12V), * resolution (1 to 16 bits) and alarm thresholds * <LI>5V, single supply operation * <LI>Very low power, 2.5 mW active, 25 @htmlonly &#181W @endhtmlonly idle * <LI>Unused analog inputs can serve as open * drain digital outputs for closed-loop control * <LI>Operating temperature range from -40@htmlonly &#176C @endhtmlonly to * +85@htmlonly &#176C @endhtmlonly * </UL> * * <H3>Usage</H3> * * <P>Example device setup</P> * <PRE><CODE> * byte[] state = owd.readDevice(); * owd.setResolution(OneWireContainer20.CHANNELA, 16, state); * owd.setResolution(OneWireContainer20.CHANNELB, 8, state); * owd.setRange(OneWireContainer20.CHANNELA, 5.12, state); * owd.setRange(OneWireContainer20.CHANNELB, 2.56, state); * owd.writeDevice(); * </CODE></PRE> * * <P>Example device read</P> * <PRE><CODE> * owd.doADConvert(OneWireContainer20.CHANNELA, state); * owd.doADConvert(OneWireContainer20.CHANNELB, state); * double chAVolatge = owd.getADVoltage(OneWireContainer20.CHANNELA, state); * double chBVoltage = owd.getADVoltage(OneWireContainer20.CHANNELB, state); * </CODE></PRE> * * <H3>Note</H3> * * <P>When converting analog voltages to digital, the user of the device must * gaurantee that the voltage seen by the channel of the quad A/D does not exceed * the selected input range of the device. If this happens, the device will default * to reading 0 volts. There is NO way to know if the device is reading a higher than * specified voltage or NO voltage.</P> * * <H3> DataSheet </H3> * * <A HREF="http://pdfserv.maxim-ic.com/arpdf/DS2450.pdf"> http://pdfserv.maxim-ic.com/arpdf/DS2450.pdf</A> * * @version 0.00, 28 Aug 2000 * @author JK,DSS */ public class OneWireContainer20 extends OneWireContainer implements ADContainer { //-------- //-------- Static Final Variables //-------- /** Offset of BITMAP in array returned from read state */ public static final int BITMAP_OFFSET = 24; /** Offset of ALARMS in array returned from read state */ public static final int ALARM_OFFSET = 8; /** Offset of external power offset in array returned from read state */ public static final int EXPOWER_OFFSET = 20; /** Channel A number */ public static final int CHANNELA = 0; /** Channel B number */ public static final int CHANNELB = 1; /** Channel C number */ public static final int CHANNELC = 2; /** Channel D number */ public static final int CHANNELD = 3; /** No preset value */ public static final int NO_PRESET = 0; /** Preset value to zeros */ public static final int PRESET_TO_ZEROS = 1; /** Preset value to ones */ public static final int PRESET_TO_ONES = 2; /** Number of channels */ public static final int NUM_CHANNELS = 4; /** DS2450 Convert command */ private static final byte CONVERT_COMMAND = ( byte ) 0x3C; //-------- //-------- Variables //-------- /** * Voltage readout memory bank */ private MemoryBankAD readout; /** * Control/Alarms/calibration memory banks vector */ private Vector regs; //-------- //-------- Constructors //-------- /** * Default constructor */ public OneWireContainer20 () { super(); // initialize the memory banks initMem(); } /** * Creates a container with a provided adapter object * and the address of the 1-Wire device. * * @param sourceAdapter adapter required to communicate with * this device * @param newAddress address of this 1-Wire device */ public OneWireContainer20 (DSPortAdapter sourceAdapter, byte[] newAddress) { super(sourceAdapter, newAddress); // initialize the memory banks initMem(); } /** * Creates a container with a provided adapter object * and the address of the 1-Wire device. * * @param sourceAdapter adapter required to communicate with * this device * @param newAddress address of this 1-Wire device */ public OneWireContainer20 (DSPortAdapter sourceAdapter, long newAddress) { super(sourceAdapter, newAddress); // initialize the memory banks initMem(); } /** * Creates a container with a provided adapter object * and the address of the 1-Wire device. * * @param sourceAdapter adapter required to communicate with * this device * @param newAddress address of this 1-Wire device */ public OneWireContainer20 (DSPortAdapter sourceAdapter, String newAddress) { super(sourceAdapter, newAddress); // initialize the memory banks initMem(); } //-------- //-------- Methods //-------- /** * Gets the name of this 1-Wire device. * * @return representation of this 1-Wire device's name */ public String getName () { return "DS2450"; } /** * Gets any other possible names for this 1-Wire device. * * @return representation of this 1-Wire device's other names */ public String getAlternateNames () { return "1-Wire Quad A/D Converter"; } /** * Gets a brief description of the functionality * of this 1-Wire device. * * @return description of this 1-Wire device's functionality */ public String getDescription () { return "Four high-impedance inputs for measurement of analog " + "voltages. User programable input range. Very low " + "power. Built-in multidrop controller. Channels " + "not used as input can be configured as outputs " + "through the use of open drain digital outputs. " + "Capable of use of Overdrive for fast data transfer. " + "Uses on-chip 16-bit CRC-generator to guarantee good data."; } /** * Gets the maximum speed this 1-Wire device can communicate at. * * @return maximum speed of this One-Wire device */ public int getMaxSpeed () { return DSPortAdapter.SPEED_OVERDRIVE; } /** * Gets an enumeration of memory banks. * * @return enumeration of memory banks * * @see com.dalsemi.onewire.container.MemoryBank * @see com.dalsemi.onewire.container.PagedMemoryBank * @see com.dalsemi.onewire.container.OTPMemoryBank */ public Enumeration getMemoryBanks () { Vector bank_vector = new Vector(4); // readout bank_vector.addElement(readout); // control/alarms/calibration for (int i = 0; i < 3; i++) bank_vector.addElement(regs.elementAt(i)); return bank_vector.elements(); } //-------- //-------- A/D Feature methods //-------- /** * Queries to get the number of channels supported by this A/D. * Channel specific methods will use a channel number specified * by an integer from <CODE>[0 to (getNumberChannels() - 1)]</CODE>. * * @return the number of channels */ public int getNumberADChannels () { return NUM_CHANNELS; } /** * Queries to see if this A/D measuring device has high/low * alarms. * * @return <CODE>true</CODE> if it has high/low trips */ public boolean hasADAlarms () { return true; } /** * Queries to get an array of available ranges for the specified * A/D channel. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * * @return available ranges starting * from the largest range to the smallest range */ public double[] getADRanges (int channel) { double[] ranges = new double [2]; ranges [0] = 5.12; ranges [1] = 2.56; return ranges; } /** * Queries to get an array of available resolutions based * on the specified range on the specified A/D channel. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param range specified range * * @return available resolutions */ public double[] getADResolutions (int channel, double range) { double[] res = new double [16]; for (int i = 0; i < 16; i++) res [i] = range / ( double ) (1 << (i + 1)); return res; } /** * Queries to see if this A/D supports doing multiple voltage * conversions at the same time. * * @return <CODE>true</CODE> if can do multi-channel voltage reads */ public boolean canADMultiChannelRead () { return true; } //-------- //-------- A/D IO Methods //-------- /** * Retrieves the entire A/D control/status and alarm pages. * It reads this and verifies the data with the onboard CRC generator. * Use the byte array returned from this method with static * utility methods to extract the status, alarm and other register values. * Appended to the data is 2 bytes that represent a bitmap * of changed bytes. These bytes are used in the <CODE>writeADRegisters()</CODE> * in conjuction with the 'set' methods to only write back the changed * register bytes. * * @return register page contents verified * with onboard CRC * * @throws OneWireIOException Data was not read correctly * @throws OneWireException Could not find part */ public byte[] readDevice () throws OneWireIOException, OneWireException { byte[] read_buf = new byte [27]; MemoryBankAD mb; // read the banks, control/alarm/calibration for (int i = 0; i < 3; i++) { mb = ( MemoryBankAD ) regs.elementAt(i); mb.readPageCRC(0, (i != 0), read_buf, i * 8); } // zero out the bitmap read_buf [24] = 0; read_buf [25] = 0; read_buf [26] = 0; return read_buf; } /** * Writes the bytes in the provided A/D register pages that * have been changed by the 'set' methods. It knows which state has * changed by looking at the bitmap fields appended to the * register data. Any alarm flags will be automatically * cleared. Only VCC powered indicator byte in physical location 0x1C * can be written in the calibration memory bank. * * @param state register pages * * @throws OneWireIOException Data was not written correctly * @throws OneWireException Could not find part */ public void writeDevice (byte[] state) throws OneWireIOException, OneWireException { int start_offset, len, i, bank, index; boolean got_block; MemoryBankAD mb; // Force a clear of the alarm flags for (i = 0; i < 4; i++) { // check if POR or alarm high/low flag present index = i * 2 + 1; if ((state [index] & ( byte ) 0xB0) != 0) { // clear the bits state [index] &= ( byte ) 0x0F; // set to write in bitmap Bit.arrayWriteBit(1, index, BITMAP_OFFSET, state); } } // only allow physical address 0x1C to be written in calibration bank state [BITMAP_OFFSET + 2] = ( byte ) (state [BITMAP_OFFSET + 2] & 0x10); // loop through the three memory banks collecting changes for (bank = 0; bank < 3; bank++) { start_offset = 0; len = 0; got_block = false; mb = ( MemoryBankAD ) regs.elementAt(bank); // loop through each byte in the memory bank for (i = 0; i < 8; i++) { // check to see if this byte needs writing (skip control register for now) if (Bit.arrayReadBit(bank * 8 + i, BITMAP_OFFSET, state) == 1) { // check if already in a block if (got_block) len++; // new block else { got_block = true; start_offset = i; len = 1; } // check for last byte exception, write current block if (i == 7) mb.write(start_offset, state, bank * 8 + start_offset, len); } else if (got_block) { // done with this block so write it mb.write(start_offset, state, bank * 8 + start_offset, len); got_block = false; } } } // clear out the bitmap state [24] = 0; state [25] = 0; state [26] = 0; } /** * Reads the voltage values. Must be used after a <CODE>doADConvert()</CODE> * method call. Also must include the last valid state from the * <CODE>readDevice()</CODE> method and this A/D must support multi-channel * read <CODE>canMultiChannelRead()</CODE> if there are more then 1 channel. * * @param state current state of this device returned from * <CODE>readDevice()</CODE> * * @return voltage values for all channels * * @throws OneWireIOException Data was not read correctly * @throws OneWireException Could not find part */ public double[] getADVoltage (byte[] state) throws OneWireIOException, OneWireException { byte[] read_buf = new byte [8]; double[] ret_dbl = new double [4]; // get readout page readout.readPageCRC(0, false, read_buf, 0); // convert to array of doubles for (int ch = 0; ch < 4; ch++) { ret_dbl [ch] = interpretVoltage(Convert.toLong(read_buf, ch * 2, 2), getADRange(ch, state)); } return ret_dbl; } /** * Reads a channels voltage value. Must be used after a * <CODE>doADConvert()</CODE> method call. Also must include * the last valid state from the <CODE>readDevice()</CODE> method. * Note, if more then one channel is to be read then it is more * efficient to use the <CODE>getADVoltage(byte[])</CODE> method that returns * all channel values. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @return voltage value for the specified * channel * * @throws OneWireIOException Data was not read correctly * @throws OneWireException Could not find part * @throws IllegalArgumentException Invalid channel number passed */ public double getADVoltage (int channel, byte[] state) throws OneWireIOException, OneWireException { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); // get readout page byte[] read_buf = new byte [8]; readout.readPageCRC(0, false, read_buf, 0); return interpretVoltage(Convert.toLong(read_buf, channel * 2, 2), getADRange(channel, state)); } /** * Performs voltage conversion on specified channel. The method * <CODE>getADVoltage()</CODE> can be used to read the result * of the conversion. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws OneWireIOException Data was not written correctly * @throws OneWireException Could not find part */ public void doADConvert (int channel, byte[] state) throws OneWireIOException, OneWireException { // call with set presets to 0 doADConvert(channel, PRESET_TO_ZEROS, state); } /** * Performs voltage conversion on all specified channels. The method * <CODE>getADVoltage()</CODE> can be used to read the result of the * conversion. This A/D must support multi-channel read * <CODE>canMultiChannelRead()</CODE> if there are more then 1 channel * is specified. * * @param doConvert which channels to perform conversion on. * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws OneWireIOException Data was not written correctly * @throws OneWireException Could not find part */ public void doADConvert (boolean[] doConvert, byte[] state) throws OneWireIOException, OneWireException { // call with set presets to 0 int[] presets = new int [4]; for (int i = 0; i < 4; i++) presets [i] = PRESET_TO_ZEROS; doADConvert(doConvert, presets, state); } /** * Performs voltage conversion on specified channel. The method * <CODE>getADVoltage()</CODE> can be used to read the result * of the conversion. * * @param channel 0,1,2,3 representing the channels A,B,C,D * @param preset preset value: * <CODE>NO_PRESET (0), PRESET_TO_ZEROS (1), and PRESET_TO_ONES (2)</CODE> * @param state state of this * device returned from <CODE>readDevice()</CODE> * * @throws OneWireIOException Data could not be written correctly * @throws OneWireException Could not find part * @throws IllegalArgumentException Invalid channel number passed */ public void doADConvert (int channel, int preset, byte[] state) throws OneWireIOException, OneWireException, IllegalArgumentException { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); // perform the conversion (do fixed max conversion time) doADConvert(( byte ) (0x01 << channel), ( byte ) (preset << channel), 1440, state); } /** * Performs voltage conversion on all specified channels. * The method <CODE>getADVoltage()</CODE> can be used to read the result * of the conversion. * * @param doConvert which channels to perform conversion on * @param preset preset values * <CODE>NO_PRESET (0), PRESET_TO_ZEROS (1), and PRESET_TO_ONES (2)</CODE> * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws OneWireIOException Data could not be written correctly * @throws OneWireException Could not find part */ public void doADConvert (boolean[] doConvert, int[] preset, byte[] state) throws OneWireIOException, OneWireException { byte input_select_mask = 0; byte read_out_control = 0; int time = 160; // Time required in micro Seconds to covert. // calculate the input mask, readout control, and conversion time for (int ch = 3; ch >= 0; ch--) { // input select input_select_mask <<= 1; if (doConvert [ch]) input_select_mask |= 0x01; // readout control read_out_control <<= 2; if (preset [ch] == PRESET_TO_ZEROS) read_out_control |= 0x01; else if (preset [ch] == PRESET_TO_ONES) read_out_control |= 0x02; // conversion time time += (80 * getADResolution(ch, state)); } // do the conversion doADConvert(input_select_mask, read_out_control, time, state); } //-------- //-------- A/D 'get' Methods //-------- /** * Extracts the alarm voltage value of the specified channel from the * provided state buffer. The state buffer is retrieved from the * <CODE>readDevice()</CODE> method. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param alarmType desired alarm, <CODE>ALARM_HIGH (1) or ALARM_LOW (0)</CODE> * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @return alarm value in volts * * @throws IllegalArgumentException Invalid channel number passed */ public double getADAlarm (int channel, int alarmType, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); // extract alarm value and convert to voltage long temp_long = ( long ) (state [ALARM_OFFSET + channel * 2 + alarmType] & 0x00FF) << 8; return interpretVoltage(temp_long, getADRange(channel, state)); } /** * Extracts the alarm enable value of the specified channel from * the provided state buffer. The state buffer is retrieved from * the <CODE>readDevice()</CODE> method. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param alarmType desired alarm, <CODE>ALARM_HIGH (1) * or ALARM_LOW (0)</CODE> * @param state current state of the state * returned from <CODE>readDevice()</CODE> * * @return <CODE>true</CODE> if specified alarm is enabled * * @throws IllegalArgumentException Invalid channel number passed */ public boolean getADAlarmEnable (int channel, int alarmType, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); return (Bit.arrayReadBit(2 + alarmType, channel * 2 + 1, state) == 1); } /** * Checks the alarm event value of the specified channel from the provided * state buffer. The state buffer is retrieved from the * <CODE>readDevice()</CODE> method. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param alarmType desired alarm, <CODE>ALARM_HIGH (1) * or ALARM_LOW (0)</CODE> * @param state current state of the state * returned from <CODE>readDevice()</CODE> * * @return <CODE>true</CODE> if specified alarm occurred * * @throws IllegalArgumentException Invalid channel number passed */ public boolean hasADAlarmed (int channel, int alarmType, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); return (Bit.arrayReadBit(4 + alarmType, channel * 2 + 1, state) == 1); } /** * Extracts the conversion resolution of the specified channel from the * provided state buffer expressed in volts. The state is retrieved from the * <CODE>readDevice()</CODE> method. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param state current state of the state * returned from <CODE>readDevice()</CODE> * * @return resolution of channel in volts * * @throws IllegalArgumentException Invalid channel number passed */ public double getADResolution (int channel, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); int res = state [channel * 2] & 0x0F; // return resolution, if 0 then 16 bits if (res == 0) res = 16; return getADRange(channel, state) / ( double ) (1 << res); } /** * Extracts the input voltage range of the specified channel from * the provided state buffer. The state buffer is retrieved from * the <CODE>readDevice()</CODE> method. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param state current state of the state * returned from <CODE>readDevice()</CODE> * * @return A/D input voltage range * * @throws IllegalArgumentException Invalid channel number passed */ public double getADRange (int channel, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); return (Bit.arrayReadBit(0, channel * 2 + 1, state) == 1) ? 5.12 : 2.56; } /** * Detects if the output is enabled for the specified channel from * the provided register buffer. The register buffer is retrieved * from the <CODE>readDevice()</CODE> method. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param state current state of the device * returned from <CODE>readDevice()</CODE> * * @return <CODE>true</CODE> if output is enabled on specified channel * * @throws IllegalArgumentException Invalid channel number passed */ public boolean isOutputEnabled (int channel, byte[] state) throws IllegalArgumentException { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); return (Bit.arrayReadBit(7, channel * 2, state) == 1); } /** * Detects if the output is enabled for the specified channel from * the provided register buffer. The register buffer is retrieved * from the <CODE>readDevice()</CODE> method. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param state current state of the device * returned from <CODE>readDevice()</CODE> * * @return <CODE>false</CODE> if output is conducting to ground and * <CODE>true</CODE> if not conducting * * @throws IllegalArgumentException Invalid channel number passed */ public boolean getOutputState (int channel, byte[] state) throws IllegalArgumentException { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); return (Bit.arrayReadBit(6, channel * 2, state) == 1); } /** * Detects if this device has seen a Power-On-Reset (POR). If this has * occured it may be necessary to set the state of the device to the * desired values. The register buffer is retrieved from the * <CODE>readDevice()</CODE> method. * * @param state current state of the device * returned from <CODE>readDevice()</CODE> * * @return <CODE>false</CODE> if output is conducting to ground and * <CODE>true</CODE> if not conducting */ public boolean getDevicePOR (byte[] state) { return (Bit.arrayReadBit(7, 1, state) == 1); } /** * Extracts the state of the external power indicator from the provided * register buffer. Use 'setPower' to set or clear the external power * indicator flag. The register buffer is retrieved from the * <CODE>readDevice()</CODE> method. * * @param state current state of the * device returned from <CODE>readDevice()</CODE> * * @return <CODE>true</CODE> if set to external power operation */ public boolean isPowerExternal (byte[] state) { return (state [EXPOWER_OFFSET] != 0); } //-------- //-------- A/D 'set' Methods //-------- /** * Sets the alarm voltage value of the specified channel in the * provided state buffer. The state buffer is retrieved from the * <CODE>readDevice()</CODE> method. The method <CODE>writeDevice()</CODE> * must be called to finalize these changes to the device. Note that * multiple 'set' methods can be called before one call to * <CODE>writeDevice()</CODE>. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param alarmType desired alarm, <CODE>ALARM_HIGH (1) * or ALARM_LOW (0)</CODE> * @param alarm alarm value (will be reduced to 8 bit resolution) * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws IllegalArgumentException Invalid channel number passed */ public void setADAlarm (int channel, int alarmType, double alarm, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); int offset = ALARM_OFFSET + channel * 2 + alarmType; state [offset] = ( byte ) ((voltageToInt(alarm, getADRange(channel, state)) >>> 8) & 0x00FF); // set bitmap field to indicate this register has changed Bit.arrayWriteBit(1, offset, BITMAP_OFFSET, state); } /** * Sets the alarm enable value of the specified channel in the * provided state buffer. The state buffer is retrieved from the * <CODE>readDevice()</CODE> method. The method <CODE>writeDevice()</CODE> * must be called to finalize these changes to the device. Note that * multiple 'set' methods can be called before one call to * <CODE>writeDevice()</CODE>. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param alarmType desired alarm, <CODE>ALARM_HIGH (1) * or ALARM_LOW (0)</CODE> * @param alarmEnable alarm enable value * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws IllegalArgumentException Invalid channel number passed */ public void setADAlarmEnable (int channel, int alarmType, boolean alarmEnable, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); // change alarm enable Bit.arrayWriteBit(((alarmEnable) ? 1 : 0), 2 + alarmType, channel * 2 + 1, state); // set bitmap field to indicate this register has changed Bit.arrayWriteBit(1, channel * 2 + 1, BITMAP_OFFSET, state); } /** * Sets the conversion resolution value for the specified channel in * the provided state buffer. The state buffer is retrieved from the * <CODE>readDevice()</CODE> method. The method <CODE>writeDevice()</CODE> * must be called to finalize these changes to the device. Note that * multiple 'set' methods can be called before one call to * <CODE>writeDevice()</CODE>. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param resolution resolution to use in volts * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws IllegalArgumentException Invalid channel number passed */ public void setADResolution (int channel, double resolution, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); // convert voltage resolution into bit resolution int div = ( int ) (getADRange(channel, state) / resolution); int res_bits = 0; do { div >>>= 1; res_bits++; } while (div != 0); res_bits -= 1; if (res_bits == 16) res_bits = 0; // check for valid bit resolution if ((res_bits < 0) || (res_bits > 15)) throw new IllegalArgumentException("Invalid resolution"); // clear out the resolution state [channel * 2] &= ( byte ) 0xF0; // set the resolution state [channel * 2] |= ( byte ) ((res_bits == 16) ? 0 : res_bits); // set bitmap field to indicate this register has changed Bit.arrayWriteBit(1, channel * 2, BITMAP_OFFSET, state); } /** * Sets the input range for the specified channel in the provided state * buffer. The state buffer is retrieved from the <CODE>readDevice()</CODE> * method. The method <CODE>writeDevice()</CODE> must be called to finalize * these changes to the device. Note that multiple 'set' methods can * be called before one call to <CODE>writeDevice()</CODE>. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param range max volt range, use * getRanges() method to get available ranges * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws IllegalArgumentException Invalid channel number passed */ public void setADRange (int channel, double range, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); // convert range into bit value int range_bit; if ((range > 5.00) & (range < 5.30)) range_bit = 1; else if ((range > 2.40) & (range < 2.70)) range_bit = 0; else throw new IllegalArgumentException("Invalid range"); // change range bit Bit.arrayWriteBit(range_bit, 0, channel * 2 + 1, state); // set bitmap field to indicate this register has changed Bit.arrayWriteBit(1, channel * 2 + 1, BITMAP_OFFSET, state); } /** * Sets the output enable and state for the specified channel in the * provided register buffer. The register buffer is retrieved from * the <CODE>readDevice()</CODE> method. The method <CODE>writeDevice()</CODE> * must be called to finalize these changes to the device. Note that * multiple 'set' methods can be called before one call to * <CODE>writeDevice()</CODE>. * * @param channel channel in the range * <CODE>[0 to (getNumberChannels() - 1)]</CODE> * @param outputEnable <CODE>true</CODE> if output is enabled * @param outputState <CODE>false</CODE> if output is conducting to * ground and <CODE>true</CODE> if not conducting. This * parameter is not used if <CODE>outputEnable</CODE> is * <CODE>false</CODE> * @param state current state of the * device returned from <CODE>readDevice()</CODE> */ public void setOutput (int channel, boolean outputEnable, boolean outputState, byte[] state) { // check for valid channel value if ((channel < 0) || (channel > 3)) throw new IllegalArgumentException("Invalid channel number"); // output enable bit Bit.arrayWriteBit(((outputEnable) ? 1 : 0), 7, channel * 2, state); // optionally set state if (outputEnable) Bit.arrayWriteBit(((outputState) ? 1 : 0), 6, channel * 2, state); // set bitmap field to indicate this register has changed Bit.arrayWriteBit(1, channel * 2, BITMAP_OFFSET, state); } /** * Sets or clears the external power flag in the provided register buffer. * The register buffer is retrieved from the <CODE>readDevice()</CODE> method. * The method <CODE>writeDevice()</CODE> must be called to finalize these * changes to the device. Note that multiple 'set' methods can * be called before one call to <CODE>writeDevice()</CODE>. * * @param external <CODE>true</CODE> if setting external power is used * @param state current state of this * device returned from <CODE>readDevice()</CODE> */ public void setPower (boolean external, byte[] state) { // sed the flag state [EXPOWER_OFFSET] = ( byte ) (external ? 0x40 : 0); // set bitmap field to indicate this register has changed Bit.arrayWriteBit(1, EXPOWER_OFFSET, BITMAP_OFFSET, state); } //-------- //-------- Utility methods //-------- /** * Converts a raw voltage long value for the DS2450 into a valid voltage. * Requires the max voltage value. * * @param rawVoltage raw voltage * @param range max voltage * * @return calculated voltage based on the range */ public static double interpretVoltage (long rawVoltage, double range) { return ((( double ) rawVoltage / 65535.0) * range); } /** * Converts a voltage double value to the DS2450 specific int value. * Requires the max voltage value. * * @param voltage voltage * @param range max voltage * * @return the DS2450 voltage */ public static int voltageToInt (double voltage, double range) { return ( int ) ((voltage * 65535.0) / range); } //-------- //-------- Private methods //-------- /** * Create the memory bank interface to read/write */ private void initMem () { // readout readout = new MemoryBankAD(this); // control regs = new Vector(3); MemoryBankAD temp_mb = new MemoryBankAD(this); temp_mb.bankDescription = "A/D Control and Status"; temp_mb.generalPurposeMemory = false; temp_mb.startPhysicalAddress = 8; temp_mb.readWrite = true; temp_mb.readOnly = false; regs.addElement(temp_mb); // Alarms temp_mb = new MemoryBankAD(this); temp_mb.bankDescription = "A/D Alarm Settings"; temp_mb.generalPurposeMemory = false; temp_mb.startPhysicalAddress = 16; temp_mb.readWrite = true; temp_mb.readOnly = false; regs.addElement(temp_mb); // calibration temp_mb = new MemoryBankAD(this); temp_mb.bankDescription = "A/D Calibration"; temp_mb.generalPurposeMemory = false; temp_mb.startPhysicalAddress = 24; temp_mb.readWrite = true; temp_mb.readOnly = false; regs.addElement(temp_mb); } /** * Performs voltage conversion on all specified channels. The method * <CODE>getADVoltage()</CODE> can be used to read the result of the * conversion. * * @param inputSelectMask input select mask * @param readOutControl read out control * @param timeUs time in microseconds for conversion * @param state current state of this * device returned from <CODE>readDevice()</CODE> * * @throws OneWireIOException Data was not written correctly * @throws OneWireException Could not find part * @throws IlleaglArgumentException Invalid channel number passed */ private void doADConvert (byte inputSelectMask, byte readOutControl, int timeUs, byte[] state) throws OneWireIOException, OneWireException { // check if no conversions if (inputSelectMask == 0) { throw new IllegalArgumentException( "No conversion will take place. No channel selected."); } // Create the command block to be sent. byte[] raw_buf = new byte [5]; raw_buf [0] = CONVERT_COMMAND; raw_buf [1] = inputSelectMask; raw_buf [2] = ( byte ) readOutControl; raw_buf [3] = ( byte ) 0xFF; raw_buf [4] = ( byte ) 0xFF; // calculate the CRC16 up to and including readOutControl int crc16 = CRC16.compute(raw_buf, 0, 3, 0); // Send command block. if (adapter.select(address)) { if (isPowerExternal(state)) { // good power so send the entire block (with both CRC) adapter.dataBlock(raw_buf, 0, 5); // Wait for complete of conversion try { Thread.sleep((timeUs / 1000) + 10); } catch (InterruptedException e){} ; // calculate the rest of the CRC16 crc16 = CRC16.compute(raw_buf, 3, 2, crc16); } else { // parasite power so send the all but last byte adapter.dataBlock(raw_buf, 0, 4); // setup power delivery adapter.setPowerDuration(DSPortAdapter.DELIVERY_INFINITE); adapter.startPowerDelivery(DSPortAdapter.CONDITION_AFTER_BYTE); // get the final CRC byte and start strong power delivery raw_buf [4] = ( byte ) adapter.getByte(); crc16 = CRC16.compute(raw_buf, 3, 2, crc16); // Wait for power delivery to complete the conversion try { Thread.sleep((timeUs / 1000) + 1); } catch (InterruptedException e){} ; // Turn power off. adapter.setPowerNormal(); } } else throw new OneWireException("OneWireContainer20 - Device not found."); // check the CRC result if (crc16 != 0x0000B001) throw new OneWireIOException( "OneWireContainer20 - Failure during conversion - Bad CRC"); // check if still busy if (adapter.getByte() == 0x00) throw new OneWireIOException("Conversion failed to complete."); } }
923cf762efed74baa93d029356edb874cc7daace
20,450
java
Java
app/src/main/java/com/xee/sdk/app/MainActivityJava.java
xee-lab/sdk-android
817bf96dd9d92fcd8da27c124b82314ef2c7059c
[ "Apache-2.0" ]
4
2017-11-18T20:43:38.000Z
2021-04-02T10:11:43.000Z
app/src/main/java/com/xee/sdk/app/MainActivityJava.java
xee-lab/sdk-android
817bf96dd9d92fcd8da27c124b82314ef2c7059c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/xee/sdk/app/MainActivityJava.java
xee-lab/sdk-android
817bf96dd9d92fcd8da27c124b82314ef2c7059c
[ "Apache-2.0" ]
5
2017-11-18T20:42:39.000Z
2018-12-13T22:59:02.000Z
45.444444
250
0.549291
1,000,111
/* * Copyright 2017 Xee * <p/> * 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 * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.xee.sdk.app; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.util.ArrayMap; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.xee.sdk.api.XeeApi; import com.xee.sdk.api.model.Accelerometer; import com.xee.sdk.api.model.Location; import com.xee.sdk.api.model.Status; import com.xee.sdk.api.model.Trip; import com.xee.sdk.api.model.Vehicle; import com.xee.sdk.core.auth.AuthenticationActivity; import com.xee.sdk.core.auth.AuthenticationCallback; import com.xee.sdk.core.auth.DisconnectCallback; import com.xee.sdk.core.auth.OAuth2Client; import com.xee.sdk.core.auth.RegistrationCallback; import com.xee.sdk.core.auth.SignInButton; import com.xee.sdk.core.auth.SignUpButton; import com.xee.sdk.api.model.Privacy; import com.xee.sdk.api.model.Signal; import com.xee.sdk.api.model.User; import com.xee.sdk.core.common.XeeEnv; import com.xee.sdk.core.auth.XeeAuth; import com.xee.sdk.core.common.model.Error; import com.xee.sdk.app.adapter.WebServiceAdapter; import com.xee.sdk.app.model.WS; import com.xee.sdk.app.model.WebService; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import kotlin.Unit; import kotlin.jvm.functions.Function1; /** * Java class */ public class MainActivityJava extends AppCompatActivity { private static final String TAG = MainActivityJava.class.getSimpleName(); private XeeApi xeeApi; private XeeAuth xeeAuth; private RecyclerView webServicesRecyclerView; /** * Please note that all these fields are used for all requests in the sample. * So if you fire a request with one of this field which is not filled, the request will failed * TODO: please think to fill the fields you need */ private String VEHICLE_ID = ""; private String TRIP_ID = ""; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); webServicesRecyclerView = findViewById(R.id.webServicesRecyclerView); setSupportActionBar(toolbar); List<WebService> webServiceList = Arrays.asList( new WebService("USER", true), new WebService(WS.GET_USER, "Get user"), new WebService(WS.UPDATE_USER, "Update user"), new WebService(WS.GET_USER_VEHICLES, "Get user's vehicles"), new WebService("VEHICLES", true), new WebService(WS.GET_VEHICLE, "Get a vehicle"), new WebService(WS.GET_VEHICLE_PRIVACIES, "Get the vehicle's privacies"), new WebService(WS.GET_VEHICLE_TRIPS, "Get the vehicle's trips"), new WebService(WS.GET_VEHICLE_SIGNALS, "Get the vehicle's signals"), new WebService(WS.GET_VEHICLE_LOCATIONS, "Get the vehicle's locations"), new WebService(WS.GET_VEHICLE_ACCELEROMETERS, "Get the vehicle's accelerometers"), new WebService(WS.GET_VEHICLE_STATUS, "Get the vehicle's status"), new WebService(WS.UPDATE_VEHICLE, "Update vehicle"), new WebService("TRIPS", true), new WebService(WS.GET_TRIP, "Get trip"), new WebService(WS.GET_TRIP_SIGNALS, "Get trip signals"), new WebService(WS.GET_TRIP_LOCATIONS, "Get trip locations") ); final OAuth2Client oAuthClient = new OAuth2Client.Builder() .clientId(getString(R.string.client_id)) .clientSecret(getString(R.string.client_secret)) .scopes(Arrays.asList(getResources().getStringArray(R.array.scopes))) .build(); XeeEnv xeeEnv = new XeeEnv(this, oAuthClient, getString(R.string.client_env)); xeeApi = new XeeApi(xeeEnv, BuildConfig.ENABLE_LOGS); xeeAuth = new XeeAuth(xeeEnv, BuildConfig.ENABLE_LOGS); SignInButton signInButton = findViewById(R.id.connectBtn); signInButton.setOnSignInClickResult(xeeAuth, new AuthenticationCallback() { @Override public void onError(@NotNull Throwable error) { if (error == AuthenticationActivity.BACK_PRESSED_THROWABLE) { if (BuildConfig.ENABLE_LOGS) Log.w(TAG, getString(R.string.authentication_canceled)); } else { if (BuildConfig.ENABLE_LOGS) Log.e(TAG, getString(R.string.authentication_error), error); } } @Override public void onSuccess() { Toast.makeText(MainActivityJava.this, R.string.authentication_success, Toast.LENGTH_SHORT).show(); } }); SignUpButton signUpButton = findViewById(R.id.registerBtn); signUpButton.setOnSignUpClickResult(xeeAuth, new RegistrationCallback() { @Override public void onCanceled() { if (BuildConfig.ENABLE_LOGS) Log.w(TAG, getString(R.string.registration_canceled)); Snackbar.make(webServicesRecyclerView, getString(R.string.registration_canceled), Snackbar.LENGTH_SHORT).show(); } @Override public void onError(@NotNull Throwable error) { if (BuildConfig.ENABLE_LOGS) Log.e(TAG, getString(R.string.registration_error), error); Snackbar.make(webServicesRecyclerView, getString(R.string.registration_error), Snackbar.LENGTH_SHORT).show(); } @Override public void onRegistered() { if (BuildConfig.ENABLE_LOGS) Log.i(TAG, getString(R.string.registration_success)); Toast.makeText(MainActivityJava.this, getString(R.string.registration_success), Toast.LENGTH_SHORT).show(); } @Override public void onLoggedAfterRegistration() { if (BuildConfig.ENABLE_LOGS) Log.w(TAG, getString(R.string.authentication_success)); Snackbar.make(webServicesRecyclerView, getString(R.string.authentication_success), Snackbar.LENGTH_SHORT).show(); } }); webServicesRecyclerView.setLayoutManager(new LinearLayoutManager(this)); webServicesRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); webServicesRecyclerView.setAdapter(new WebServiceAdapter(webServiceList, new Function1<WebService, Unit>() { @Override public Unit invoke(WebService webService) { onWebServiceClicked(webService); return null; } })); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_disconnect: disconnect(); break; } return super.onOptionsItemSelected(item); } private void onWebServiceClicked(final WebService ws) { switch (ws.getWs()) { case GET_USER: xeeApi.getUser() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<User>() { @Override public void accept(User user) throws Exception { showDialogSuccess(ws, user); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_USER_VEHICLES: xeeApi.getUserVehicles() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Vehicle>>() { @Override public void accept(List<Vehicle> vehicles) throws Exception { showDialogSuccess(ws, vehicles); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_VEHICLE: xeeApi.getVehicle(VEHICLE_ID) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Vehicle>() { @Override public void accept(Vehicle vehicle) throws Exception { showDialogSuccess(ws, vehicle); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_VEHICLE_PRIVACIES: xeeApi.getVehiclePrivacies(VEHICLE_ID, diff(new Date(), -2), new Date(), 10) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Privacy>>() { @Override public void accept(List<Privacy> privacies) throws Exception { showDialogSuccess(ws, privacies); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_VEHICLE_TRIPS: xeeApi.getVehicleTrips(VEHICLE_ID) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Trip>>() { @Override public void accept(List<Trip> trips) throws Exception { showDialogSuccess(ws, trips); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_VEHICLE_SIGNALS: Map<String, Object> optionalParametersSignals = new ArrayMap<>(); optionalParametersSignals.put("signals", "LockSts"); optionalParametersSignals.put("from", XeeApi.DATE_FORMATTER.format(diff(new Date(), -2))); optionalParametersSignals.put("to", XeeApi.DATE_FORMATTER.format(new Date())); xeeApi.getVehicleSignals(VEHICLE_ID, optionalParametersSignals) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Signal>>() { @Override public void accept(List<Signal> signals) throws Exception { showDialogSuccess(ws, signals); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_VEHICLE_LOCATIONS: xeeApi.getVehicleLocations(VEHICLE_ID, diff(new Date(), -30), new Date(), 20) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Location>>() { @Override public void accept(List<Location> locations) throws Exception { showDialogSuccess(ws, locations); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_VEHICLE_ACCELEROMETERS: xeeApi.getVehicleAccelerometers(VEHICLE_ID) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Accelerometer>>() { @Override public void accept(List<Accelerometer> accelerometers) throws Exception { showDialogSuccess(ws, accelerometers); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_VEHICLE_STATUS: xeeApi.getVehicleStatus(VEHICLE_ID) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Status>() { @Override public void accept(Status status) throws Exception { showDialogSuccess(ws, status); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_TRIP: xeeApi.getTrip(TRIP_ID) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Trip>() { @Override public void accept(Trip trip) throws Exception { showDialogSuccess(ws, trip); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_TRIP_SIGNALS: xeeApi.getTripSignals(TRIP_ID, diff(new Date(), -30), new Date(), null, 20) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Signal>>() { @Override public void accept(List<Signal> signals) throws Exception { showDialogSuccess(ws, signals); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; case GET_TRIP_LOCATIONS: xeeApi.getTripLocations(TRIP_ID, diff(new Date(), -30), new Date(), 20) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<List<Location>>() { @Override public void accept(List<Location> locations) throws Exception { showDialogSuccess(ws, locations); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showDialogError(ws, throwable); } }); break; } } private void showDialogSuccess(WebService ws, Object data) { new MaterialDialog.Builder(MainActivityJava.this) .title(ws.getTitle()) .titleColorRes(R.color.dialogTitleSuccess) .content(prettyJson(data)) .positiveText(android.R.string.ok) .positiveColorRes(R.color.dialogTitleSuccess) .show(); } private void showDialogError(WebService ws, Object error) { MaterialDialog.Builder errorDialog = new MaterialDialog.Builder(MainActivityJava.this); errorDialog.title(ws.getTitle()); errorDialog.titleColorRes(R.color.dialogTitleError); errorDialog.positiveText(android.R.string.ok); errorDialog.positiveColorRes(R.color.dialogTitleError); if (error instanceof Error) { CharSequence text = "• error: " + ((Error) error).getError() + "\n• error description: " + ((Error) error).getErrorDescription() + "\n• error details: " + ((Error) error).getErrorDetails() + "\n• error code: " + ((Error) error).getCode(); errorDialog.content(text); } else { errorDialog.content(error.toString()); } errorDialog.show(); } private void disconnect() { xeeAuth.disconnect(new DisconnectCallback() { @Override public void onCompleted() { Snackbar.make(webServicesRecyclerView, R.string.disconnect_success, Snackbar.LENGTH_SHORT).show(); } }); } private String prettyJson(Object data) { Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create(); return gson.toJson(data); } private Date diff(Date date, Integer days){ Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.DATE, days); return c.getTime(); } }
923cf78250ab9120bd28b83fd61d35ccfe1d2cb0
554
java
Java
app/src/main/java/org/cuieney/videolife/common/api/VeerApiService.java
daimaren/CloudPlayer
b9240c27d70760c357bb88c4f7acd4e9c529d528
[ "Naumen", "Condor-1.1", "MS-PL" ]
2
2019-10-27T17:23:21.000Z
2021-03-30T03:01:38.000Z
app/src/main/java/org/cuieney/videolife/common/api/VeerApiService.java
daimaren/CloudPlayer
b9240c27d70760c357bb88c4f7acd4e9c529d528
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
app/src/main/java/org/cuieney/videolife/common/api/VeerApiService.java
daimaren/CloudPlayer
b9240c27d70760c357bb88c4f7acd4e9c529d528
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2018-02-11T07:56:10.000Z
2018-02-11T07:56:10.000Z
23.083333
114
0.729242
1,000,112
package org.cuieney.videolife.common.api; import org.cuieney.videolife.entity.VeerListBean; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; /** * Created by cuieney on 2017/6/6. */ public interface VeerApiService { @GET("overall_featured_videos") Observable<VeerListBean> getVeer(@Query("days") String days,@Query("page") int page); @GET("categories/{id}") Observable<VeerListBean> getCatagory(@Path("id")int id,@Query("order") String order, @Query("page") int page); }
923cf794b50cade045dc47598418f6d7a28c7cc3
1,922
java
Java
component-test/src/main/java/io/mifos/template/SuiteTestEnvironment.java
crain/template
08f84198fe12b8b7547ef6c104a3be23558278be
[ "Apache-2.0" ]
null
null
null
component-test/src/main/java/io/mifos/template/SuiteTestEnvironment.java
crain/template
08f84198fe12b8b7547ef6c104a3be23558278be
[ "Apache-2.0" ]
null
null
null
component-test/src/main/java/io/mifos/template/SuiteTestEnvironment.java
crain/template
08f84198fe12b8b7547ef6c104a3be23558278be
[ "Apache-2.0" ]
1
2020-12-14T15:37:49.000Z
2020-12-14T15:37:49.000Z
41.782609
86
0.782518
1,000,113
/* * Copyright 2017 The Mifos Initiative. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.mifos.template; import io.mifos.core.test.env.TestEnvironment; import io.mifos.core.test.fixture.cassandra.CassandraInitializer; import io.mifos.core.test.fixture.mariadb.MariaDBInitializer; import org.junit.ClassRule; import org.junit.rules.RuleChain; import org.junit.rules.RunExternalResourceOnce; import org.junit.rules.TestRule; /** * This contains the database resources required by the test. They are in a separate * class so that the test suite can initialize them before the classes it calls. This * makes test runs faster and prevents tests from "stepping on each other's toes" when * initializing and de-initializing external resources. */ public class SuiteTestEnvironment { static final String APP_VERSION = "1"; static final String APP_NAME = "template-v" + APP_VERSION; static final TestEnvironment testEnvironment = new TestEnvironment(APP_NAME); static final CassandraInitializer cassandraInitializer = new CassandraInitializer(); static final MariaDBInitializer mariaDBInitializer = new MariaDBInitializer(); @ClassRule public static TestRule orderClassRules = RuleChain .outerRule(new RunExternalResourceOnce(testEnvironment)) .around(new RunExternalResourceOnce(cassandraInitializer)) .around(new RunExternalResourceOnce(mariaDBInitializer)); }
923cfaaccb42cde48b02f9211cb3615e9089ef02
1,301
java
Java
ucloud-sdk-java-uhost/src/main/java/cn/ucloud/uhost/models/CreateUHostInstanceResponse.java
ucloud/ucloud-sdk-java
23c60bcba6c60fec7f6a46b208c44378cdeb52cd
[ "Apache-2.0" ]
21
2018-11-01T11:43:48.000Z
2022-02-07T09:12:47.000Z
ucloud-sdk-java-uhost/src/main/java/cn/ucloud/uhost/models/CreateUHostInstanceResponse.java
ucloud/ucloud-sdk-java
23c60bcba6c60fec7f6a46b208c44378cdeb52cd
[ "Apache-2.0" ]
9
2018-11-09T09:30:06.000Z
2021-12-31T11:14:29.000Z
ucloud-sdk-java-uhost/src/main/java/cn/ucloud/uhost/models/CreateUHostInstanceResponse.java
ucloud/ucloud-sdk-java
23c60bcba6c60fec7f6a46b208c44378cdeb52cd
[ "Apache-2.0" ]
14
2018-10-25T07:45:24.000Z
2022-01-07T07:41:49.000Z
28.282609
99
0.697156
1,000,114
/** * Copyright 2021 UCloud Technology Co., Ltd. * * <p>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 * * <p>http://www.apache.org/licenses/LICENSE-2.0 * * <p>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 cn.ucloud.uhost.models; import cn.ucloud.common.response.Response; import com.google.gson.annotations.SerializedName; import java.util.List; public class CreateUHostInstanceResponse extends Response { /** UHost实例Id集合 */ @SerializedName("UHostIds") private List<String> uHostIds; /** 【批量创建不会返回】IP信息 */ @SerializedName("IPs") private List<String> iPs; public List<String> getUHostIds() { return uHostIds; } public void setUHostIds(List<String> uHostIds) { this.uHostIds = uHostIds; } public List<String> getIPs() { return iPs; } public void setIPs(List<String> iPs) { this.iPs = iPs; } }
923cfc2ad8482f08f3b6e0ad48ab891c847c0f93
1,946
java
Java
app/src/canary/java/com/anysoftkeyboard/canary/CanaryAnyApplication.java
nkaskov/AnySoftKeyboard
53fc32a2267dd747027bb9f33772793d95b69b1d
[ "Apache-2.0" ]
3
2019-12-06T06:34:45.000Z
2021-10-09T12:31:22.000Z
app/src/canary/java/com/anysoftkeyboard/canary/CanaryAnyApplication.java
nkaskov/AnySoftKeyboard
53fc32a2267dd747027bb9f33772793d95b69b1d
[ "Apache-2.0" ]
null
null
null
app/src/canary/java/com/anysoftkeyboard/canary/CanaryAnyApplication.java
nkaskov/AnySoftKeyboard
53fc32a2267dd747027bb9f33772793d95b69b1d
[ "Apache-2.0" ]
null
null
null
32.983051
194
0.739979
1,000,115
/* * Copyright (c) 2016 Menny Even-Danan * * 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.anysoftkeyboard.canary; import android.Manifest; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import com.anysoftkeyboard.crashlytics.NdkCrashlytics; import com.anysoftkeyboard.ui.settings.MainSettingsActivity; import com.menny.android.anysoftkeyboard.AnyApplication; import net.evendanan.chauffeur.lib.permissions.PermissionsFragmentChauffeurActivity; public class CanaryAnyApplication extends AnyApplication { private NdkCrashlytics mNdkCrashlytics; @Override protected void setupCrashHandler(SharedPreferences sp) { super.setupCrashHandler(sp); if (Build.VERSION.SDK_INT >= NdkCrashlytics.SUPPORTED_MIN_SDK) { mNdkCrashlytics = new NdkCrashlytics(this); } } @Override public void onTerminate() { super.onTerminate(); if (mNdkCrashlytics != null) { mNdkCrashlytics.destroy(); } } @Override public void onCreate() { super.onCreate(); Intent internetRequired = PermissionsFragmentChauffeurActivity.createIntentToPermissionsRequest(this, MainSettingsActivity.class, CanaryPermissionsRequestCodes.INTERNET.getRequestCode(), Manifest.permission.INTERNET); if (internetRequired != null) startActivity(internetRequired); } }
923cfdfc3db8bdaa508772b7a86cb860a97cfc5f
10,754
java
Java
app/src/main/java/com/medmanager/android/views/activities/AboutMedicationActivity.java
demistry/MedManager
4093922bd85f7caae31dcdda3bdf8d8b6db3ca3d
[ "Apache-2.0" ]
5
2018-05-18T14:42:23.000Z
2018-06-05T20:58:28.000Z
app/src/main/java/com/medmanager/android/views/activities/AboutMedicationActivity.java
demistry/MedManager
4093922bd85f7caae31dcdda3bdf8d8b6db3ca3d
[ "Apache-2.0" ]
7
2018-05-16T05:43:47.000Z
2019-03-20T15:20:11.000Z
app/src/main/java/com/medmanager/android/views/activities/AboutMedicationActivity.java
demistry/MedManager
4093922bd85f7caae31dcdda3bdf8d8b6db3ca3d
[ "Apache-2.0" ]
null
null
null
42.844622
132
0.643296
1,000,116
package com.medmanager.android.views.activities; import android.content.Intent; import android.support.v4.app.NotificationManagerCompat; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.medmanager.android.ConstantClass; import com.medmanager.android.R; import com.medmanager.android.model.storage.MedInfo; import com.medmanager.android.presenter.utils.AlertDialogCreator; import java.util.Locale; public class AboutMedicationActivity extends BaseActivity { private TextView mMedNameTextView, mMedDescriptionTextView, mMedStartDateTextView, mMedStartTimeTextView; private TextView mEndDateTextView, mEndTimeTextView, mMedicationTypeTextView, mDosageCountTextView, mDosageIntervalTextView; private ImageView mMedStatusImageView, mMedTypeImageView, mIncrementCountImageView, mDecrementCountImageView; private Button mEditButton; private MedInfo mMedInfo; private Bundle mBundle; private static int sDosage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about_medication); if(getSupportActionBar()!=null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); mMedNameTextView = findViewById(R.id.text_about_med_name); mMedDescriptionTextView = findViewById(R.id.text_about_med_description); mMedStartDateTextView = findViewById(R.id.about_med_start_date); mMedStartTimeTextView = findViewById(R.id.about_med_start_time); mEndDateTextView = findViewById(R.id.about_med_end_date); mEndTimeTextView = findViewById(R.id.about_med_end_time); mMedicationTypeTextView = findViewById(R.id.text_about_med_type); mDosageCountTextView = findViewById(R.id.text_about_dosage_count); mDosageIntervalTextView = findViewById(R.id.text_about_med_interval); mMedStatusImageView = findViewById(R.id.image_about_med_status); mMedTypeImageView = findViewById(R.id.image_about_med_type); mIncrementCountImageView = findViewById(R.id.image_increment_count); mDecrementCountImageView = findViewById(R.id.image_decrement_count); mEditButton = findViewById(R.id.btn_edit_med); mBundle = getIntent().getExtras(); mEditButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if(mMedInfo ==null){ Intent intent = new Intent(AboutMedicationActivity.this, AddMedicationActivity.class); intent.putExtra(ConstantClass.EXTRA_UPDATE_MED, adapterInterfaceDataManager.getSerializedMedifcation()); startActivity(intent); } else{ Intent intent = new Intent(AboutMedicationActivity.this, AddMedicationActivity.class); intent.putExtra(ConstantClass.EXTRA_UPDATE_MED, mMedInfo.serialize()); startActivity(intent); } } } ); mIncrementCountImageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if(mMedInfo ==null){ incrementMedicationCount(adapterInterfaceDataManager.getMedInfo()); } else{ incrementMedicationCount(mMedInfo); } } } ); mDecrementCountImageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if(mMedInfo ==null){ decrementMedicationCount(adapterInterfaceDataManager.getMedInfo()); } else{ decrementMedicationCount(mMedInfo); } } } ); } @Override protected void onStart() { super.onStart(); if(adapterInterfaceDataManager!=null){ mMedInfo = adapterInterfaceDataManager.getMedInfo(); mMedNameTextView.setText(adapterInterfaceDataManager.getMedicationName()); mMedDescriptionTextView.setText(adapterInterfaceDataManager.getMedicationDescription()); mMedStartDateTextView.setText(adapterInterfaceDataManager.getStartDate()); mMedStartTimeTextView.setText(adapterInterfaceDataManager.getStartTime()); mEndDateTextView.setText(adapterInterfaceDataManager.getEndDate()); mEndTimeTextView.setText(adapterInterfaceDataManager.getEndTime()); mMedicationTypeTextView.setText(adapterInterfaceDataManager.getMedicationType()); String test = adapterInterfaceDataManager.getMedicationType(); switch (test) { case "Pills": mMedTypeImageView.setImageResource(R.drawable.ic_pill); break; case "Injection": mMedTypeImageView.setImageResource(R.drawable.ic_injection); break; case "Syrup": mMedTypeImageView.setImageResource(R.drawable.ic_syrup); break; } if (adapterInterfaceDataManager.isMedicationStarted()) mMedStatusImageView.setImageResource(R.drawable.ic_check_circle_black_24dp); else mMedStatusImageView.setImageResource(R.drawable.ic_warning_black_24dp); mDosageCountTextView.setText(String.valueOf(adapterInterfaceDataManager.getDosageCount())); int interval = adapterInterfaceDataManager.getMedicationInterval(); if (interval == 30){ mDosageIntervalTextView.setText(String.format(Locale.getDefault(),"%d%s", interval, getString(R.string.minutes))); } else if (interval == 1){ mDosageIntervalTextView.setText(String.format(Locale.getDefault(),"%d%s", interval, getString(R.string.hour))); } else mDosageIntervalTextView.setText(String.format(Locale.getDefault(),"%d%s", interval, getString(R.string.hours))); } } @Override protected void onResume() { super.onResume(); handleNotificationClicks(getIntent().getExtras()); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_about, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_delete){ AlertDialogCreator.createDeleteDialog(this, deleteMedication, mMedInfo); } return super.onOptionsItemSelected(item); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); this.mBundle = intent.getExtras(); handleNotificationClicks(mBundle); } private void incrementMedicationCount(MedInfo medInformation) { int medicationAmount = Integer.parseInt(medInformation.getDoseNumber()); sDosage = medInformation.getDosageCount(); sDosage += medicationAmount; int returnedDosage = updateMedicationCount.updateMedicationCount(this, medInformation.getMedicationName(), sDosage); mDosageCountTextView.setText(String.valueOf(returnedDosage)); } private void decrementMedicationCount(MedInfo medInformation) { int medicationAmount = Integer.parseInt(medInformation.getDoseNumber()); sDosage = medInformation.getDosageCount(); if (sDosage !=0) sDosage -= medicationAmount; int returnedDosage = updateMedicationCount.updateMedicationCount(this, medInformation.getMedicationName(), sDosage); mDosageCountTextView.setText(String.valueOf(returnedDosage)); } private void handleNotificationClicks(Bundle bundle){ if (bundle!=null){ String notificationMedInfo = bundle.getString(ConstantClass.EXTRA_NOTIFICATION_ITEM); mMedInfo = MedInfo.create(notificationMedInfo); mMedNameTextView.setText(mMedInfo.getMedicationName()); mMedDescriptionTextView.setText(mMedInfo.getMedicationName()); mMedStartDateTextView.setText(mMedInfo.getStartDate()); mMedStartTimeTextView.setText(mMedInfo.getStartTime()); mEndDateTextView.setText(mMedInfo.getEndDate()); mEndTimeTextView.setText(mMedInfo.getEndTime()); mMedicationTypeTextView.setText(mMedInfo.getMedicationType()); switch (mMedInfo.getMedicationType()) { case "Pills": mMedTypeImageView.setImageResource(R.drawable.ic_pill); break; case "Injection": mMedTypeImageView.setImageResource(R.drawable.ic_injection); break; case "Syrup": mMedTypeImageView.setImageResource(R.drawable.ic_syrup); break; } if (mMedInfo.isMedicationStarted()) mMedStatusImageView.setImageResource(R.drawable.ic_check_circle_black_24dp); else mMedStatusImageView.setImageResource(R.drawable.ic_warning_black_24dp); mDosageCountTextView.setText(String.valueOf(mMedInfo.getDosageCount())); int interval = mMedInfo.getMedicationInterval(); if (interval == 30){ mDosageIntervalTextView.setText(String.format(Locale.getDefault(),"%d%s", interval, getString(R.string.minutes))); } else if (interval == 1){ mDosageIntervalTextView.setText(String.format(Locale.getDefault(),"%d%s", interval, getString(R.string.hour))); } else mDosageIntervalTextView.setText(String.format(Locale.getDefault(),"%d%s", interval, getString(R.string.hours))); NotificationManagerCompat.from(this).cancel(bundle.getString(ConstantClass.EXTRA_NOTIFICATION_TAG), bundle.getInt(ConstantClass.EXTRA_NOTIFICATION_ID)); incrementMedicationCount(mMedInfo); } } }
923cfe06cea5e3ea500cea5c43d35be47b4145f5
1,137
java
Java
jeecg-boot-module-system/src/main/java/org/jeecg/modules/management/workorder/service/impl/WorkOrderProgressServiceImpl.java
JIT-DevelopmentTeam/southtech_service_back
91334eaa3305460bd920bf7fbd6531cc5a6af530
[ "MIT" ]
null
null
null
jeecg-boot-module-system/src/main/java/org/jeecg/modules/management/workorder/service/impl/WorkOrderProgressServiceImpl.java
JIT-DevelopmentTeam/southtech_service_back
91334eaa3305460bd920bf7fbd6531cc5a6af530
[ "MIT" ]
9
2020-03-18T03:38:14.000Z
2022-02-27T00:59:38.000Z
jeecg-boot-module-system/src/main/java/org/jeecg/modules/management/workorder/service/impl/WorkOrderProgressServiceImpl.java
JIT-DevelopmentTeam/southtech_service_back
91334eaa3305460bd920bf7fbd6531cc5a6af530
[ "MIT" ]
null
null
null
32.485714
144
0.827617
1,000,117
package org.jeecg.modules.management.workorder.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.jeecg.modules.management.workorder.entity.WorkOrderProgress; import org.jeecg.modules.management.workorder.mapper.WorkOrderProgressMapper; import org.jeecg.modules.management.workorder.service.IWorkOrderProgressService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; /** * @Description: 工单进度 * @Author: jeecg-boot * @Date: 2020-03-16 * @Version: V1.0 */ @Service public class WorkOrderProgressServiceImpl extends ServiceImpl<WorkOrderProgressMapper, WorkOrderProgress> implements IWorkOrderProgressService { @Autowired private WorkOrderProgressMapper workOrderProgressMapper; @Override public List<WorkOrderProgress> selectByMainId(String mainId) { return workOrderProgressMapper.selectByMainId(mainId); } @Override public void updateFinishTimeById(Date finishTime, String progressId) { workOrderProgressMapper.updateFinishTimeById(finishTime, progressId); } }
923cfe2dee5dd02fff101c118c4daf80aae94de9
3,010
java
Java
src/main/java/com/onshape/configurator/services/DocumentLockService.java
ginnun/configurator-example
8c469fe05cb46ef46ab7308f015f86b53271c192
[ "MIT" ]
8
2019-09-07T13:33:44.000Z
2021-08-17T14:26:56.000Z
src/main/java/com/onshape/configurator/services/DocumentLockService.java
ginnun/configurator-example
8c469fe05cb46ef46ab7308f015f86b53271c192
[ "MIT" ]
17
2019-07-31T18:04:05.000Z
2022-03-02T04:49:45.000Z
src/main/java/com/onshape/configurator/services/DocumentLockService.java
ginnun/configurator-example
8c469fe05cb46ef46ab7308f015f86b53271c192
[ "MIT" ]
8
2019-08-08T03:46:52.000Z
2021-01-27T11:25:44.000Z
38.151899
108
0.700066
1,000,118
/* * The MIT License * * Copyright 2019 Onshape Inc. * * 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.onshape.configurator.services; import com.onshape.api.Onshape; import com.onshape.api.exceptions.OnshapeException; import com.onshape.api.types.OnshapeDocument; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * * @author Peter Harman ychag@example.com */ public class DocumentLockService { private static DocumentLockService INSTANCE; private final Onshape onshape; private final ConcurrentMap<OnshapeDocument, Lock> locks; public static DocumentLockService getInstance(Onshape onshape) { if (INSTANCE == null) { INSTANCE = new DocumentLockService(onshape); } return INSTANCE; } DocumentLockService(Onshape onshape) { this.onshape = onshape; this.locks = new ConcurrentHashMap<>(); } public OnshapeDocument getWritable(OnshapeDocument document) throws OnshapeException { try { // Does document have a Workspace? if (document.getWorkspaceId() == null) { String wid = onshape.documents().getDocument().call(document).getDefaultWorkspace().getId(); document = new OnshapeDocument(document.getDocumentId(), wid, document.getElementId()); } // Get or create a lock Lock lock = locks.computeIfAbsent(document, (doc) -> new ReentrantLock()); lock.lockInterruptibly(); return document; } catch (InterruptedException ex) { throw new OnshapeException("Failed to lock access to default Workspace", ex); } } public void release(OnshapeDocument document) { locks.computeIfPresent(document, (doc, lock) -> { lock.unlock(); return lock; }); } }
923cfecb94ccb6442575ef94dc51101c8cb14fad
1,380
java
Java
src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/DiffLineParser.java
cornelcreanga/bitbucket-rest-client
236eec596ac215869cae5dfa9150cbd158f86f28
[ "Apache-2.0" ]
11
2015-11-02T21:27:53.000Z
2021-06-30T06:37:32.000Z
src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/DiffLineParser.java
cornelcreanga/bitbucket-rest-client
236eec596ac215869cae5dfa9150cbd158f86f28
[ "Apache-2.0" ]
3
2016-09-06T20:13:26.000Z
2017-12-12T19:09:57.000Z
src/main/java/com/ccreanga/bitbucket/rest/client/http/responseparsers/DiffLineParser.java
cornelcreanga/bitbucket-rest-client
236eec596ac215869cae5dfa9150cbd158f86f28
[ "Apache-2.0" ]
4
2016-10-25T07:05:52.000Z
2020-02-25T04:44:50.000Z
33.658537
78
0.673188
1,000,119
/* * * * * * 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.ccreanga.bitbucket.rest.client.http.responseparsers; import com.ccreanga.bitbucket.rest.client.model.diff.DiffLine; import java.util.function.Function; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class DiffLineParser implements Function<JsonElement, DiffLine> { @Override public DiffLine apply(JsonElement jsonElement) { if (jsonElement == null || !jsonElement.isJsonObject()) { return null; } JsonObject json = jsonElement.getAsJsonObject(); return new DiffLine( json.get("destination").getAsInt(), json.get("line").getAsString(), json.get("source").getAsInt(), json.get("truncated").getAsBoolean()); } }
923cff392215921cdb07e428568388c82de12c6e
749
java
Java
library/src/main/java/com/cundong/recyclerview/HeaderSpanSizeLookup.java
gitHub2016218/recyclerView
1e616c955297090dafb18d27ed714beb854262c0
[ "Apache-2.0" ]
2
2016-08-12T09:59:32.000Z
2021-03-08T07:37:13.000Z
library/src/main/java/com/cundong/recyclerview/HeaderSpanSizeLookup.java
ssllkkyy/HeaderAndFooterRecyclerView
1e616c955297090dafb18d27ed714beb854262c0
[ "Apache-2.0" ]
1
2016-08-03T09:02:43.000Z
2016-08-03T09:02:43.000Z
library/src/main/java/com/cundong/recyclerview/HeaderSpanSizeLookup.java
ssllkkyy/HeaderAndFooterRecyclerView
1e616c955297090dafb18d27ed714beb854262c0
[ "Apache-2.0" ]
4
2016-05-29T05:26:20.000Z
2018-07-03T09:29:18.000Z
29.96
92
0.746328
1,000,120
package com.cundong.recyclerview; import android.support.v7.widget.GridLayoutManager; /** * Created by cundong on 2015/10/23. * <p/> * RecyclerView为GridLayoutManager时,设置了HeaderView,就会用到这个SpanSizeLookup */ public class HeaderSpanSizeLookup extends GridLayoutManager.SpanSizeLookup { private HeaderAndFooterRecyclerViewAdapter adapter; private int mSpanSize = 1; public HeaderSpanSizeLookup(HeaderAndFooterRecyclerViewAdapter adapter, int spanSize) { this.adapter = adapter; this.mSpanSize = spanSize; } @Override public int getSpanSize(int position) { boolean isHeaderOrFooter = adapter.isHeader(position) || adapter.isFooter(position); return isHeaderOrFooter ? mSpanSize : 1; } }
923cffd09700daa66d97c9e8f0e1663f6a577b6e
46,264
java
Java
common/common-lang/src/test/java/com/twelvemonkeys/lang/StringUtilTest.java
feithsystems/TwelveMonkeys
4d190892df5402938db4a7fba3b358ecadee486a
[ "BSD-3-Clause" ]
1,353
2015-01-07T07:24:42.000Z
2022-03-29T08:48:27.000Z
common/common-lang/src/test/java/com/twelvemonkeys/lang/StringUtilTest.java
feithsystems/TwelveMonkeys
4d190892df5402938db4a7fba3b358ecadee486a
[ "BSD-3-Clause" ]
564
2015-01-01T08:38:41.000Z
2022-03-14T07:02:35.000Z
common/common-lang/src/test/java/com/twelvemonkeys/lang/StringUtilTest.java
feithsystems/TwelveMonkeys
4d190892df5402938db4a7fba3b358ecadee486a
[ "BSD-3-Clause" ]
267
2015-01-13T06:14:57.000Z
2022-03-30T14:31:25.000Z
48.754478
259
0.65715
1,000,121
/* * Copyright (c) 2008, Harald Kuhr * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.twelvemonkeys.lang; import static org.junit.Assert.*; import java.awt.*; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import org.junit.Test; /** * StringUtilTestCase * * @author <a href="mailto:kenaa@example.com">Harald Kuhr</a> * @author last modified by $Author: haku $ * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/test/java/com/twelvemonkeys/lang/StringUtilTestCase.java#1 $ * */ public class StringUtilTest { final static Object TEST_OBJECT = new Object(); final static Integer TEST_INTEGER = 42; final static String TEST_STRING = "TheQuickBrownFox"; // No WS! final static String TEST_SUB_STRING = TEST_STRING.substring(2, 5); final static String TEST_DELIM_STRING = "one,two, three\n four\tfive six"; final static String[] STRING_ARRAY = {"one", "two", "three", "four", "five", "six"}; final static String TEST_INT_DELIM_STRING = "1,2, 3\n 4\t5 6"; final static int[] INT_ARRAY = {1, 2, 3, 4, 5, 6}; final static String TEST_DOUBLE_DELIM_STRING = "1.4,2.1, 3\n .4\t-5 6e5"; final static double[] DOUBLE_ARRAY = {1.4, 2.1, 3, .4, -5, 6e5}; final static String EMPTY_STRING = ""; final static String WHITESPACE_STRING = " \t \r \n "; @Test public void testValueOfObject() { assertNotNull(StringUtil.valueOf(TEST_OBJECT)); assertEquals(StringUtil.valueOf(TEST_OBJECT), TEST_OBJECT.toString()); assertEquals(StringUtil.valueOf(TEST_INTEGER), TEST_INTEGER.toString()); assertEquals(StringUtil.valueOf(TEST_STRING), TEST_STRING); assertSame(StringUtil.valueOf(TEST_STRING), TEST_STRING); assertNull(StringUtil.valueOf(null)); } @SuppressWarnings("ConstantConditions") @Test public void testToUpperCase() { String str = StringUtil.toUpperCase(TEST_STRING); assertNotNull(str); assertEquals(TEST_STRING.toUpperCase(), str); assertNull(StringUtil.toUpperCase(null)); } @SuppressWarnings("ConstantConditions") @Test public void testToLowerCase() { String str = StringUtil.toLowerCase(TEST_STRING); assertNotNull(str); assertEquals(TEST_STRING.toLowerCase(), str); assertNull(StringUtil.toLowerCase(null)); } @Test public void testIsEmpty() { assertTrue(StringUtil.isEmpty((String) null)); assertTrue(StringUtil.isEmpty(EMPTY_STRING)); assertTrue(StringUtil.isEmpty(WHITESPACE_STRING)); assertFalse(StringUtil.isEmpty(TEST_STRING)); } @Test public void testIsEmptyArray() { assertTrue(StringUtil.isEmpty((String[]) null)); assertTrue(StringUtil.isEmpty(new String[]{EMPTY_STRING})); assertTrue(StringUtil.isEmpty(new String[]{EMPTY_STRING, WHITESPACE_STRING})); assertFalse(StringUtil.isEmpty(new String[]{EMPTY_STRING, TEST_STRING})); assertFalse(StringUtil.isEmpty(new String[]{WHITESPACE_STRING, TEST_STRING})); } @SuppressWarnings("ConstantConditions") @Test public void testContains() { assertTrue(StringUtil.contains(TEST_STRING, TEST_STRING)); assertTrue(StringUtil.contains(TEST_STRING, TEST_SUB_STRING)); assertTrue(StringUtil.contains(TEST_STRING, EMPTY_STRING)); assertFalse(StringUtil.contains(TEST_STRING, WHITESPACE_STRING)); assertFalse(StringUtil.contains(TEST_SUB_STRING, TEST_STRING)); assertFalse(StringUtil.contains(EMPTY_STRING, TEST_STRING)); assertFalse(StringUtil.contains(WHITESPACE_STRING, TEST_STRING)); assertFalse(StringUtil.contains(null, TEST_STRING)); assertFalse(StringUtil.contains(null, null)); } @Test public void testContainsIgnoreCase() { assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_STRING)); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING)); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING)); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase())); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING)); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING)); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING)); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase())); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, EMPTY_STRING)); assertFalse(StringUtil.containsIgnoreCase(TEST_STRING, WHITESPACE_STRING)); assertFalse(StringUtil.containsIgnoreCase(TEST_SUB_STRING, TEST_STRING)); assertFalse(StringUtil.containsIgnoreCase(EMPTY_STRING, TEST_STRING)); assertFalse(StringUtil.containsIgnoreCase(WHITESPACE_STRING, TEST_STRING)); assertFalse(StringUtil.containsIgnoreCase(null, TEST_STRING)); assertFalse(StringUtil.containsIgnoreCase(null, null)); } @SuppressWarnings("ConstantConditions") @Test public void testContainsChar() { for (int i = 0; i < TEST_STRING.length(); i++) { assertTrue(StringUtil.contains(TEST_STRING, TEST_STRING.charAt(i))); assertFalse(StringUtil.contains(EMPTY_STRING, TEST_STRING.charAt(i))); assertFalse(StringUtil.contains(WHITESPACE_STRING, TEST_STRING.charAt(i))); assertFalse(StringUtil.contains(null, TEST_STRING.charAt(i))); } for (int i = 0; i < TEST_SUB_STRING.length(); i++) { assertTrue(StringUtil.contains(TEST_STRING, TEST_SUB_STRING.charAt(i))); } for (int i = 0; i < WHITESPACE_STRING.length(); i++) { assertFalse(StringUtil.contains(TEST_STRING, WHITESPACE_STRING.charAt(i))); } // Test all alpha-chars for (int i = 'a'; i < 'z'; i++) { if (TEST_STRING.indexOf(i) < 0) { assertFalse(TEST_STRING + " seems to contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.contains(TEST_STRING, i)); } else { assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.contains(TEST_STRING, i)); } } } @Test public void testContainsIgnoreCaseChar() { // Must contain all chars in string for (int i = 0; i < TEST_STRING.length(); i++) { assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_STRING.charAt(i))); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i))); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i))); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i)))); assertFalse(StringUtil.containsIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i))); assertFalse(StringUtil.containsIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i))); assertFalse(StringUtil.containsIgnoreCase(null, TEST_STRING.charAt(i))); } for (int i = 0; i < TEST_SUB_STRING.length(); i++) { assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i))); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i))); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i))); assertTrue(StringUtil.containsIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i))); } for (int i = 0; i < WHITESPACE_STRING.length(); i++) { assertFalse(StringUtil.containsIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i))); } // Test all alpha-chars for (int i = 'a'; i < 'z'; i++) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { assertFalse(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), StringUtil.containsIgnoreCase(TEST_STRING, i)); } else { assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), StringUtil.containsIgnoreCase(TEST_STRING, i)); } } } @Test public void testIndexOfIgnoreCase() { assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING)); assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING)); assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING)); assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase())); assertEquals(0, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase())); for (int i = 1; i < TEST_STRING.length(); i++) { assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(i))); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(i))); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(i))); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(i))); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(i))); } assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase())); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase())); for (int i = 1; i < TEST_STRING.length(); i++) { assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING)); assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING)); } assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING)); assertEquals(-1, StringUtil.indexOfIgnoreCase(null, null)); } @Test public void testIndexOfIgnoreCasePos() { assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING, 1)); assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING, 2)); assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING, 3)); assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase(), 4)); assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase(), 5)); for (int i = 1; i < TEST_STRING.length(); i++) { assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(i), i - 1)); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(i), i - 1)); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(i), i - 1)); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(i), i - 1)); assertEquals(i, StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(i), i - 1)); } assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING, 1)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING, 1)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING, 2)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase(), 1)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase(), 2)); assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING, 234)); assertEquals(-1, StringUtil.indexOfIgnoreCase(null, null, -45)); } @Test public void testLastIndexOfIgnoreCase() { assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase())); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase())); for (int i = 1; i < TEST_STRING.length(); i++) { assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(i))); assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(i))); assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(i))); assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(i))); assertEquals(i, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(i))); } assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase())); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase())); for (int i = 1; i < TEST_STRING.length(); i++) { assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.substring(i), TEST_STRING)); } assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, null)); } @Test public void testLastIndexOfIgnoreCasePos() { assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING, 1)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING, 2)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING, 3)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase(), 4)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase(), 5)); for (int i = 1; i < TEST_STRING.length(); i++) { assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.substring(0, i), i - 1)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.substring(0, i), i - 1)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.substring(0, i), i - 1)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase().substring(0, i), i - 1)); assertEquals(0, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.toLowerCase().substring(0, i), i - 1)); } assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING, TEST_SUB_STRING.length() + 3)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING, TEST_SUB_STRING.length() + 3)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING, TEST_SUB_STRING.length() + 4)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase(), TEST_SUB_STRING.length() + 3)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toLowerCase(), TEST_SUB_STRING.length() + 4)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING, 234)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, null, -45)); } @Test public void testIndexOfIgnoreCaseChar() { // Must contain all chars in string for (int i = 0; i < TEST_STRING.length(); i++) { assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i))); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i))); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i))); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i)))); assertEquals(-1, StringUtil.indexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i))); assertEquals(-1, StringUtil.indexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i))); assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING.charAt(i))); } for (int i = 0; i < TEST_SUB_STRING.length(); i++) { assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i))); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i))); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i))); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i))); } for (int i = 0; i < WHITESPACE_STRING.length(); i++) { assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i))); } // Test all alpha-chars for (int i = 'a'; i < 'z'; i++) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.indexOfIgnoreCase(TEST_STRING, i)); } else { assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i)); } } } @Test public void testIndexOfIgnoreCaseCharPos() { // Must contain all chars in string for (int i = 0; i < TEST_STRING.length(); i++) { assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i)), i)); assertEquals(-1, StringUtil.indexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i), i)); assertEquals(-1, StringUtil.indexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i), i)); assertEquals(-1, StringUtil.indexOfIgnoreCase(null, TEST_STRING.charAt(i), i)); } for (int i = 0; i < TEST_SUB_STRING.length(); i++) { assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i), i)); } for (int i = 0; i < WHITESPACE_STRING.length(); i++) { assertEquals(-1, StringUtil.indexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i), i)); } // Test all alpha-chars for (int i = 'a'; i < 'z'; i++) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0)); } else { assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.indexOfIgnoreCase(TEST_STRING, i, 0)); } } } @Test public void testLastIndexOfIgnoreCaseChar() { // Must contain all chars in string for (int i = 0; i < TEST_STRING.length(); i++) { assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i))); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i))); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i))); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i)))); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i))); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i))); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING.charAt(i))); } for (int i = 0; i < TEST_SUB_STRING.length(); i++) { assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i))); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i))); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i))); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i))); } for (int i = 0; i < WHITESPACE_STRING.length(); i++) { assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i))); } // Test all alpha-chars for (int i = 'a'; i < 'z'; i++) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i)); } else { assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i)); } } } @Test public void testLastIndexOfIgnoreCaseCharPos() { // Must contain all chars in string for (int i = 0; i < TEST_STRING.length(); i++) { assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_STRING.charAt(i), i)); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, Character.toUpperCase(TEST_STRING.charAt(i)), i)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(EMPTY_STRING, TEST_STRING.charAt(i), i)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(WHITESPACE_STRING, TEST_STRING.charAt(i), i)); assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(null, TEST_STRING.charAt(i), i)); } for (int i = 0; i < TEST_SUB_STRING.length(); i++) { assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.charAt(i), TEST_STRING.length())); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toUpperCase(), TEST_SUB_STRING.charAt(i), TEST_STRING.length())); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING.toLowerCase(), TEST_SUB_STRING.charAt(i), TEST_STRING.length())); assertTrue(0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, TEST_SUB_STRING.toUpperCase().charAt(i), TEST_STRING.length())); } for (int i = 0; i < WHITESPACE_STRING.length(); i++) { assertEquals(-1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, WHITESPACE_STRING.charAt(i), TEST_STRING.length())); } // Test all alpha-chars for (int i = 'a'; i < 'z'; i++) { if ((TEST_STRING.indexOf(i) < 0) && (TEST_STRING.indexOf(Character.toUpperCase((char) i)) < 0)) { assertEquals(TEST_STRING + " seems to contain '" + (char) i + "', at index " + Math.max(TEST_STRING.indexOf(i), TEST_STRING.indexOf(Character.toUpperCase((char) i))), -1, StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length())); } else { assertTrue(TEST_STRING + " seems to not contain '" + (char) i + "', at index " + TEST_STRING.indexOf(i), 0 <= StringUtil.lastIndexOfIgnoreCase(TEST_STRING, i, TEST_STRING.length())); } } } @Test public void testLtrim() { assertEquals(TEST_STRING, StringUtil.ltrim(TEST_STRING)); assertEquals(TEST_STRING, StringUtil.ltrim(" " + TEST_STRING)); assertEquals(TEST_STRING, StringUtil.ltrim(WHITESPACE_STRING + TEST_STRING)); assertNotEquals(TEST_STRING, StringUtil.ltrim(TEST_STRING + WHITESPACE_STRING)); // TODO: Test is not complete } @Test public void testRtrim() { assertEquals(TEST_STRING, StringUtil.rtrim(TEST_STRING)); assertEquals(TEST_STRING, StringUtil.rtrim(TEST_STRING + " ")); assertEquals(TEST_STRING, StringUtil.rtrim(TEST_STRING + WHITESPACE_STRING)); assertNotEquals(TEST_STRING, StringUtil.rtrim(WHITESPACE_STRING + TEST_STRING)); // TODO: Test is not complete } @Test public void testReplace() { assertEquals("", StringUtil.replace(TEST_STRING, TEST_STRING, "")); assertEquals("", StringUtil.replace("", "", "")); assertEquals("", StringUtil.replace("", "xyzzy", "xyzzy")); assertEquals(TEST_STRING, StringUtil.replace(TEST_STRING, "", "xyzzy")); assertEquals("aabbdd", StringUtil.replace("aabbccdd", "c", "")); assertEquals("aabbccdd", StringUtil.replace("aabbdd", "bd", "bccd")); // TODO: Test is not complete } @Test public void testReplaceIgnoreCase() { assertEquals("", StringUtil.replaceIgnoreCase(TEST_STRING, TEST_STRING.toUpperCase(), "")); assertEquals("", StringUtil.replaceIgnoreCase("", "", "")); assertEquals("", StringUtil.replaceIgnoreCase("", "xyzzy", "xyzzy")); assertEquals(TEST_STRING, StringUtil.replaceIgnoreCase(TEST_STRING, "", "xyzzy")); assertEquals("aabbdd", StringUtil.replaceIgnoreCase("aabbCCdd", "c", "")); assertEquals("aabbdd", StringUtil.replaceIgnoreCase("aabbccdd", "C", "")); assertEquals("aabbccdd", StringUtil.replaceIgnoreCase("aabbdd", "BD", "bccd")); assertEquals("aabbccdd", StringUtil.replaceIgnoreCase("aabBDd", "bd", "bccd")); // TODO: Test is not complete } @Test public void testCut() { assertEquals(TEST_STRING, StringUtil.cut(TEST_STRING, TEST_STRING.length(), "..")); assertEquals("This is a test..", StringUtil.cut("This is a test of how this works", 16, "..")); assertEquals("This is a test", StringUtil.cut("This is a test of how this works", 16, null)); assertEquals("This is a test", StringUtil.cut("This is a test of how this works", 16, "")); // TODO: Test is not complete } @Test public void testCaptialize() { assertNull(StringUtil.capitalize(null)); assertEquals(TEST_STRING.toUpperCase(), StringUtil.capitalize(TEST_STRING.toUpperCase())); assertEquals('A', StringUtil.capitalize("abc").charAt(0)); } @Test public void testCaptializePos() { assertNull(StringUtil.capitalize(null, 45)); // TODO: Should this throw IllegalArgument or StringIndexOutOfBonds? assertEquals(TEST_STRING, StringUtil.capitalize(TEST_STRING, TEST_STRING.length() + 45)); for (int i = 0; i < TEST_STRING.length(); i++) { assertTrue(Character.isUpperCase(StringUtil.capitalize(TEST_STRING, i).charAt(i))); } } @Test public void testPad() { assertEquals(TEST_STRING + "...", StringUtil.pad(TEST_STRING, TEST_STRING.length() + 3, "..", false)); assertEquals(TEST_STRING, StringUtil.pad(TEST_STRING, 4, ".", false)); assertEquals(TEST_STRING, StringUtil.pad(TEST_STRING, 4, ".", true)); assertEquals("..." + TEST_STRING, StringUtil.pad(TEST_STRING, TEST_STRING.length() + 3, "..", true)); } @Test public void testToDate() { long time = System.currentTimeMillis(); Date now = new Date(time - time % 60000); // Default format seems to have no seconds.. Date date = StringUtil.toDate(DateFormat.getInstance().format(now)); assertNotNull(date); assertEquals(now, date); } @Test public void testToDateWithFormatString() { Calendar cal = new GregorianCalendar(); cal.clear(); cal.set(1976, Calendar.MARCH, 16); // Month is 0-based Date date = StringUtil.toDate("16.03.1976", "dd.MM.yyyy"); assertNotNull(date); assertEquals(cal.getTime(), date); cal.clear(); cal.set(2004, Calendar.MAY, 13, 23, 51, 3); date = StringUtil.toDate("2004-5-13 23:51 (03)", "yyyy-MM-dd hh:mm (ss)"); assertNotNull(date); assertEquals(cal.getTime(), date); cal.clear(); cal.set(Calendar.HOUR, 1); cal.set(Calendar.MINUTE, 2); cal.set(Calendar.SECOND, 3); date = StringUtil.toDate("123", "hms"); assertNotNull(date); assertEquals(cal.getTime(), date); } @Test public void testToDateWithFormat() { Calendar cal = new GregorianCalendar(); cal.clear(); cal.set(1976, Calendar.MARCH, 16); // Month is 0-based Date date = StringUtil.toDate("16.03.1976", new SimpleDateFormat("dd.MM.yyyy")); assertNotNull(date); assertEquals(cal.getTime(), date); cal.clear(); cal.set(2004, Calendar.MAY, 13, 23, 51); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, new Locale("no", "NO")); date = StringUtil.toDate(format.format(cal.getTime()), format); assertNotNull(date); assertEquals(cal.getTime(), date); cal.clear(); cal.set(Calendar.HOUR, 1); cal.set(Calendar.MINUTE, 2); date = StringUtil.toDate("1:02 am", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US)); assertNotNull(date); assertEquals(cal.getTime(), date); } @Test public void testToTimestamp() { Calendar cal = new GregorianCalendar(); cal.clear(); cal.set(1976, Calendar.MARCH, 16, 21, 28, 4); // Month is 0-based Timestamp date = StringUtil.toTimestamp("1976-03-16 21:28:04"); assertNotNull(date); assertEquals(cal.getTime(), date); } @Test public void testToStringArray() { String[] arr = StringUtil.toStringArray(TEST_DELIM_STRING); assertNotNull(arr); assertEquals(STRING_ARRAY.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(STRING_ARRAY[i], arr[i]); } } @Test public void testToStringArrayDelim() { String[] arr = StringUtil.toStringArray("-1---2-3--4-5", "---"); String[] arr2 = {"1", "2", "3", "4", "5"}; assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } arr = StringUtil.toStringArray("1, 2, 3; 4 5", ",; "); assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } } @Test public void testToIntArray() { int[] arr = StringUtil.toIntArray(TEST_INT_DELIM_STRING); assertNotNull(arr); assertEquals(INT_ARRAY.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(INT_ARRAY[i], arr[i]); } } @Test public void testToIntArrayDelim() { int[] arr = StringUtil.toIntArray("-1---2-3--4-5", "---"); int[] arr2 = {1, 2, 3, 4, 5}; assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } arr = StringUtil.toIntArray("1, 2, 3; 4 5", ",; "); assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } } @Test public void testToIntArrayDelimBase() { int[] arr = StringUtil.toIntArray("-1___2_3__F_a", "___", 16); int[] arr2 = {-1, 2, 3, 0xf, 0xa}; assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } arr = StringUtil.toIntArray("-1, 2, 3; 17 12", ",; ", 8); assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } } @Test public void testToLongArray() { long[] arr = StringUtil.toLongArray(TEST_INT_DELIM_STRING); assertNotNull(arr); assertEquals(INT_ARRAY.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(INT_ARRAY[i], arr[i]); } } @Test public void testToLongArrayDelim() { long[] arr = StringUtil.toLongArray("-12854928752983___2_3__4_5", "___"); long[] arr2 = {-12854928752983L, 2, 3, 4, 5}; assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } arr = StringUtil.toLongArray("-12854928752983, 2, 3; 4 5", ",; "); assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i]); } } @Test public void testToDoubleArray() { double[] arr = StringUtil.toDoubleArray(TEST_DOUBLE_DELIM_STRING); assertNotNull(arr); assertEquals(DOUBLE_ARRAY.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(DOUBLE_ARRAY[i], arr[i], 0d); } } @Test public void testToDoubleArrayDelim() { double[] arr = StringUtil.toDoubleArray("-12854928752983___.2_3__4_5e4", "___"); double[] arr2 = {-12854928752983L, .2, 3, 4, 5e4}; assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i], 0d); } arr = StringUtil.toDoubleArray("-12854928752983, .2, 3; 4 5E4", ",; "); assertNotNull(arr); assertEquals(arr2.length, arr.length); for (int i = 0; i < arr.length; i++) { assertEquals(arr2[i], arr[i], 0d); } } @Test public void testTestToColor() { // Test all constants assertEquals(Color.black, StringUtil.toColor("black")); assertEquals(Color.black, StringUtil.toColor("BLACK")); assertEquals(Color.blue, StringUtil.toColor("blue")); assertEquals(Color.blue, StringUtil.toColor("BLUE")); assertEquals(Color.cyan, StringUtil.toColor("cyan")); assertEquals(Color.cyan, StringUtil.toColor("CYAN")); assertEquals(Color.darkGray, StringUtil.toColor("darkGray")); assertEquals(Color.darkGray, StringUtil.toColor("DARK_GRAY")); assertEquals(Color.gray, StringUtil.toColor("gray")); assertEquals(Color.gray, StringUtil.toColor("GRAY")); assertEquals(Color.green, StringUtil.toColor("green")); assertEquals(Color.green, StringUtil.toColor("GREEN")); assertEquals(Color.lightGray, StringUtil.toColor("lightGray")); assertEquals(Color.lightGray, StringUtil.toColor("LIGHT_GRAY")); assertEquals(Color.magenta, StringUtil.toColor("magenta")); assertEquals(Color.magenta, StringUtil.toColor("MAGENTA")); assertEquals(Color.orange, StringUtil.toColor("orange")); assertEquals(Color.orange, StringUtil.toColor("ORANGE")); assertEquals(Color.pink, StringUtil.toColor("pink")); assertEquals(Color.pink, StringUtil.toColor("PINK")); assertEquals(Color.red, StringUtil.toColor("red")); assertEquals(Color.red, StringUtil.toColor("RED")); assertEquals(Color.white, StringUtil.toColor("white")); assertEquals(Color.white, StringUtil.toColor("WHITE")); assertEquals(Color.yellow, StringUtil.toColor("yellow")); assertEquals(Color.yellow, StringUtil.toColor("YELLOW")); // System.out.println(StringUtil.deepToString(Color.yellow)); // System.out.println(StringUtil.deepToString(Color.pink, true, -1)); // Test HTML/CSS style color for (int i = 0; i < 256; i++) { int c = i; if (i < 0x10) { c = i * 16; } String colorStr = "#" + Integer.toHexString(i) + Integer.toHexString(i) + Integer.toHexString(i); String colorStrAlpha = "#" + Integer.toHexString(i) + Integer.toHexString(i) + Integer.toHexString(i) + Integer.toHexString(i); assertEquals(new Color(c, c, c), StringUtil.toColor(colorStr)); assertEquals(new Color(c, c, c, c), StringUtil.toColor(colorStrAlpha)); } // Test null // TODO: Hmmm.. Maybe reconsider this.. assertNull(StringUtil.toColor(null)); // Test try { StringUtil.toColor("illegal-color-value"); fail("toColor with illegal color value should throw IllegalArgumentException."); } catch (IllegalArgumentException e) { assertNotNull(e.getMessage()); } } @Test public void testToColorString() { assertEquals("#ff0000", StringUtil.toColorString(Color.red)); assertEquals("#00ff00", StringUtil.toColorString(Color.green)); assertEquals("#0000ff", StringUtil.toColorString(Color.blue)); assertEquals("#101010", StringUtil.toColorString(new Color(0x10, 0x10, 0x10))); for (int i = 0; i < 256; i++) { String str = (i < 0x10 ? "0" : "") + Integer.toHexString(i); assertEquals("#" + str + str + str, StringUtil.toColorString(new Color(i, i, i))); } // Test null // TODO: Hmmm.. Maybe reconsider this.. assertNull(StringUtil.toColorString(null)); } @Test public void testIsNumber() { assertTrue(StringUtil.isNumber("0")); assertTrue(StringUtil.isNumber("12345")); assertTrue(StringUtil.isNumber(TEST_INTEGER.toString())); assertTrue(StringUtil.isNumber("1234567890123456789012345678901234567890")); assertTrue(StringUtil.isNumber(String.valueOf(Long.MAX_VALUE) + Long.MAX_VALUE)); assertFalse(StringUtil.isNumber("abc")); assertFalse(StringUtil.isNumber(TEST_STRING)); } @Test public void testIsNumberNegative() { assertTrue(StringUtil.isNumber("-12345")); assertTrue(StringUtil.isNumber('-' + TEST_INTEGER.toString())); assertTrue(StringUtil.isNumber("-1234567890123456789012345678901234567890")); assertTrue(StringUtil.isNumber('-' + String.valueOf(Long.MAX_VALUE) + Long.MAX_VALUE)); assertFalse(StringUtil.isNumber("-abc")); assertFalse(StringUtil.isNumber('-' + TEST_STRING)); } @Test public void testCamelToLispNull() { try { StringUtil.camelToLisp(null); fail("should not accept null"); } catch (IllegalArgumentException iae) { assertNotNull(iae.getMessage()); } } @Test public void testCamelToLispNoConversion() { assertEquals("", StringUtil.camelToLisp("")); assertEquals("equal", StringUtil.camelToLisp("equal")); assertEquals("allready-lisp", StringUtil.camelToLisp("allready-lisp")); } @Test public void testCamelToLispSimple() { // Simple tests assertEquals("foo-bar", StringUtil.camelToLisp("fooBar")); } @Test public void testCamelToLispCase() { // Casing assertEquals("my-url", StringUtil.camelToLisp("myURL")); assertEquals("another-url", StringUtil.camelToLisp("AnotherURL")); } @Test public void testCamelToLispMulti() { // Several words assertEquals("http-request-wrapper", StringUtil.camelToLisp("HttpRequestWrapper")); String s = StringUtil.camelToLisp("HttpURLConnection"); assertEquals("http-url-connection", s); // Long and short abbre in upper case assertEquals("welcome-to-my-world", StringUtil.camelToLisp("WELCOMEToMYWorld")); } @Test public void testCamelToLispLeaveUntouched() { // Leave others untouched assertEquals("a-slightly-longer-and-more-bumpy-string?.,[]()", StringUtil.camelToLisp("ASlightlyLongerANDMoreBumpyString?.,[]()")); } @Test public void testCamelToLispNumbers() { // Numbers // TODO: FixMe String s = StringUtil.camelToLisp("my45Caliber"); assertEquals("my-45-caliber", s); assertEquals("hello-12345-world-67890", StringUtil.camelToLisp("Hello12345world67890")); assertEquals("hello-12345-my-world-67890-this-time", StringUtil.camelToLisp("HELLO12345MyWorld67890thisTime")); assertEquals("hello-12345-world-67890-too", StringUtil.camelToLisp("Hello12345WORLD67890too")); } @Test public void testLispToCamelNull() { try { StringUtil.lispToCamel(null); fail("should not accept null"); } catch (IllegalArgumentException iae) { assertNotNull(iae.getMessage()); } } @Test public void testLispToCamelNoConversion() { assertEquals("", StringUtil.lispToCamel("")); assertEquals("equal", StringUtil.lispToCamel("equal")); assertEquals("alreadyCamel", StringUtil.lispToCamel("alreadyCamel")); } @Test public void testLispToCamelSimple() { // Simple tests assertEquals("fooBar", StringUtil.lispToCamel("foo-bar")); assertEquals("myUrl", StringUtil.lispToCamel("my-URL")); assertEquals("anotherUrl", StringUtil.lispToCamel("ANOTHER-URL")); } @Test public void testLispToCamelCase() { // Casing assertEquals("Object", StringUtil.lispToCamel("object", true)); assertEquals("object", StringUtil.lispToCamel("Object", false)); } @Test public void testLispToCamelMulti() { // Several words assertEquals("HttpRequestWrapper", StringUtil.lispToCamel("http-request-wrapper", true)); } @Test public void testLispToCamelLeaveUntouched() { // Leave others untouched assertEquals("ASlightlyLongerAndMoreBumpyString?.,[]()", StringUtil.lispToCamel("a-slightly-longer-and-more-bumpy-string?.,[]()", true)); } @Test public void testLispToCamelNumber() { // Numbers assertEquals("my45Caliber", StringUtil.lispToCamel("my-45-caliber")); } }
923d0111d945f9f56dc01ab5af4c7685add401ed
1,369
java
Java
pso-flint-berlioz/src/main/java/org/pageseeder/flint/berlioz/util/SolrXMLUtils.java
pageseeder/wo-flint
678e642946be34f640211219126458f8d0774abd
[ "Apache-2.0" ]
null
null
null
pso-flint-berlioz/src/main/java/org/pageseeder/flint/berlioz/util/SolrXMLUtils.java
pageseeder/wo-flint
678e642946be34f640211219126458f8d0774abd
[ "Apache-2.0" ]
2
2017-12-18T05:13:04.000Z
2019-01-15T23:12:15.000Z
pso-flint-berlioz/src/main/java/org/pageseeder/flint/berlioz/util/SolrXMLUtils.java
pageseeder/wo-flint
678e642946be34f640211219126458f8d0774abd
[ "Apache-2.0" ]
5
2017-05-26T06:01:26.000Z
2021-10-31T16:02:43.000Z
33.390244
106
0.697589
1,000,122
package org.pageseeder.flint.berlioz.util; import java.io.IOException; import java.util.Collection; import org.apache.solr.client.solrj.response.FacetField; import org.apache.solr.client.solrj.response.FacetField.Count; import org.pageseeder.flint.solr.query.Facets; import org.pageseeder.xmlwriter.XMLWriter; public class SolrXMLUtils { public static void facetsToXML(Facets facets, XMLWriter xml) throws IOException { xml.openElement("facets"); facetFieldsToXML(facets.getFacetFields(), xml); facetFieldsToXML(facets.getFacetDates(), xml); xml.closeElement(); } private static void facetFieldsToXML(Collection<FacetField> facets, XMLWriter xml) throws IOException { if (facets == null) return; for (FacetField facet : facets) { facetFieldToXML(facet, xml); } } private static void facetFieldToXML(FacetField facet, XMLWriter xml) throws IOException { xml.openElement("facet"); xml.attribute("name", facet.getName()); xml.attribute("count", facet.getValueCount()); for (Count count : facet.getValues()) { xml.openElement("term"); xml.attribute("field", facet.getName()); xml.attribute("text", count.getName()); xml.attribute("cardinality", String.valueOf(count.getCount())); xml.closeElement(); } xml.closeElement(); } }
923d015496b34ea68fa72a408f5f35c046522015
3,189
java
Java
server/src/test/java/com/paypal/selion/utils/AuthenticationHelperTest.java
marvindoering/SeLion
28bd87fd8ade6e221e1a2dc647304ed7e8d0fb50
[ "Apache-2.0" ]
279
2015-01-09T02:33:17.000Z
2022-03-13T07:11:02.000Z
server/src/test/java/com/paypal/selion/utils/AuthenticationHelperTest.java
marvindoering/SeLion
28bd87fd8ade6e221e1a2dc647304ed7e8d0fb50
[ "Apache-2.0" ]
309
2015-01-08T19:04:36.000Z
2022-01-27T16:18:43.000Z
server/src/test/java/com/paypal/selion/utils/AuthenticationHelperTest.java
marvindoering/SeLion
28bd87fd8ade6e221e1a2dc647304ed7e8d0fb50
[ "Apache-2.0" ]
239
2015-01-02T04:05:47.000Z
2022-02-18T04:37:04.000Z
49.828125
119
0.472562
1,000,123
/*-------------------------------------------------------------------------------------------------------------------*\ | Copyright (C) 2015 PayPal | | | | 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.paypal.selion.utils; import static org.testng.Assert.*; import java.io.File; import org.testng.annotations.AfterClass; import org.testng.annotations.Test; import com.paypal.selion.SeLionConstants; public class AuthenticationHelperTest { @Test public void testAuthentication() { boolean isValidLogin = AuthenticationHelper.authenticate("admin", "admin"); assertTrue(isValidLogin); } @Test(dependsOnMethods = "testAuthentication") public void testPasswordChange() { boolean isPasswordChanged = AuthenticationHelper.changePassword("admin", "dummy"); assertTrue(isPasswordChanged); } @Test(dependsOnMethods = "testPasswordChange") public void authenticateNewPassword() { boolean val = AuthenticationHelper.authenticate("admin", "dummy"); assertTrue(val); } @Test(dependsOnMethods = "authenticateNewPassword") public void authenticateWrongPassword() { boolean isValidPassword = AuthenticationHelper.authenticate("admin", "dummy123"); assertFalse(isValidPassword); } @Test(dependsOnMethods = "authenticateWrongPassword") public void authenticateWrongUsername() { boolean isValidUser = AuthenticationHelper.authenticate("dummy", "dummy"); assertFalse(isValidUser); } @AfterClass(alwaysRun = true) public void cleanUpAuthFile() { File authFile = new File(SeLionConstants.SELION_HOME_DIR + ".authFile"); authFile.delete(); } }
923d01dbc8dcfc29ac13cb761bbcbc8c43498880
5,002
java
Java
spring-orm/src/main/java/org/springframework/orm/hibernate5/SpringSessionContext.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
null
null
null
spring-orm/src/main/java/org/springframework/orm/hibernate5/SpringSessionContext.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
null
null
null
spring-orm/src/main/java/org/springframework/orm/hibernate5/SpringSessionContext.java
yangfancoming/spring-5.1.x
db4c2cbcaf8ba58f43463eff865d46bdbd742064
[ "Apache-2.0" ]
1
2021-06-05T07:25:05.000Z
2021-06-05T07:25:05.000Z
37.328358
104
0.786885
1,000,124
package org.springframework.orm.hibernate5; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.TransactionManager; import org.apache.commons.logging.LogFactory; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.context.spi.CurrentSessionContext; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.springframework.lang.Nullable; import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Implementation of Hibernate 3.1's {@link CurrentSessionContext} interface * that delegates to Spring's {@link SessionFactoryUtils} for providing a * Spring-managed current {@link Session}. * * xmlBeanDefinitionReaderThis CurrentSessionContext implementation can also be specified in custom * SessionFactory setup through the "hibernate.current_session_context_class" * property, with the fully qualified name of this class as value. * * @since 4.2 */ @SuppressWarnings("serial") public class SpringSessionContext implements CurrentSessionContext { private final SessionFactoryImplementor sessionFactory; @Nullable private TransactionManager transactionManager; @Nullable private CurrentSessionContext jtaSessionContext; /** * Create a new SpringSessionContext for the given Hibernate SessionFactory. * @param sessionFactory the SessionFactory to provide current Sessions for */ public SpringSessionContext(SessionFactoryImplementor sessionFactory) { this.sessionFactory = sessionFactory; try { JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class); this.transactionManager = jtaPlatform.retrieveTransactionManager(); if (this.transactionManager != null) { this.jtaSessionContext = new SpringJtaSessionContext(sessionFactory); } } catch (Exception ex) { LogFactory.getLog(SpringSessionContext.class).warn( "Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex); } } /** * Retrieve the Spring-managed Session for the current thread, if any. */ @Override @SuppressWarnings("deprecation") public Session currentSession() throws HibernateException { Object value = TransactionSynchronizationManager.getResource(this.sessionFactory); if (value instanceof Session) { return (Session) value; } else if (value instanceof SessionHolder) { // HibernateTransactionManager SessionHolder sessionHolder = (SessionHolder) value; Session session = sessionHolder.getSession(); if (!sessionHolder.isSynchronizedWithTransaction() && TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session // with FlushMode.MANUAL, which needs to allow flushing within the transaction. FlushMode flushMode = SessionFactoryUtils.getFlushMode(session); if (flushMode.equals(FlushMode.MANUAL) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } return session; } else if (value instanceof EntityManagerHolder) { // JpaTransactionManager return ((EntityManagerHolder) value).getEntityManager().unwrap(Session.class); } if (this.transactionManager != null && this.jtaSessionContext != null) { try { if (this.transactionManager.getStatus() == Status.STATUS_ACTIVE) { Session session = this.jtaSessionContext.currentSession(); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization( new SpringFlushSynchronization(session)); } return session; } } catch (SystemException ex) { throw new HibernateException("JTA TransactionManager found but status check failed", ex); } } if (TransactionSynchronizationManager.isSynchronizationActive()) { Session session = this.sessionFactory.openSession(); if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.MANUAL); } SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(sessionHolder, this.sessionFactory, true)); TransactionSynchronizationManager.bindResource(this.sessionFactory, sessionHolder); sessionHolder.setSynchronizedWithTransaction(true); return session; } else { throw new HibernateException("Could not obtain transaction-synchronized Session for current thread"); } } }
923d0236b88c201d6e9d2d6f8b3e988bc10fc047
2,172
java
Java
core/src/test/java/io/techcode/logbulk/util/logging/MessageExceptionTest.java
amannocci/logbulk
30104ec15c089609b3bef7f12a488bd41571c59e
[ "MIT" ]
4
2017-02-08T13:23:51.000Z
2017-06-09T11:09:38.000Z
core/src/test/java/io/techcode/logbulk/util/logging/MessageExceptionTest.java
amannocci/logbulk
30104ec15c089609b3bef7f12a488bd41571c59e
[ "MIT" ]
17
2017-01-09T08:59:21.000Z
2017-06-09T18:33:27.000Z
core/src/test/java/io/techcode/logbulk/util/logging/MessageExceptionTest.java
amannocci/logbulk
30104ec15c089609b3bef7f12a488bd41571c59e
[ "MIT" ]
null
null
null
37.448276
80
0.735727
1,000,125
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * 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 io.techcode.logbulk.util.logging; import org.junit.Test; import static io.techcode.logbulk.util.Binder.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Test for MessageException. */ public class MessageExceptionTest { @Test(expected = NullPointerException.class) public void testConstructor1() throws Exception { throw new MessageException(null); } @Test(expected = MessageException.class) public void testConstructor2() throws Exception { throw new MessageException("foobar"); } @Test public void testGetMessage() throws Exception { MessageException exception = new MessageException("foobar"); assertEquals("foobar", exception.getMessage()); } @Test public void testGetStackTrace() throws Exception { MessageException exception = new MessageException("foobar"); assertEquals(0, exception.getStackTrace().length); } }
923d02644ac4767419334287effa8b84a08c3b73
3,847
java
Java
src/test/java/org/brackit/as/xquery/function/TestResource.java
sebbae/brackitas
9b86cd400f31fc61c1bb90eea0ccfbdb1568b8b9
[ "BSD-3-Clause" ]
null
null
null
src/test/java/org/brackit/as/xquery/function/TestResource.java
sebbae/brackitas
9b86cd400f31fc61c1bb90eea0ccfbdb1568b8b9
[ "BSD-3-Clause" ]
null
null
null
src/test/java/org/brackit/as/xquery/function/TestResource.java
sebbae/brackitas
9b86cd400f31fc61c1bb90eea0ccfbdb1568b8b9
[ "BSD-3-Clause" ]
2
2017-03-23T16:15:35.000Z
2019-03-10T20:57:29.000Z
38.079208
194
0.74675
1,000,126
/* * [New BSD License] * Copyright (c) 2011-2012, Brackit Project Team <upchh@example.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Brackit Project Team nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.brackit.as.xquery.function; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import org.brackit.as.http.HttpConnector; import org.brackit.as.xquery.ASXQuery; import org.brackit.as.xquery.compiler.ASCompileChain; import org.brackit.as.xquery.function.base.BaseASQueryContext; import org.brackit.xquery.QueryException; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * * @author Henrique Valer * */ public class TestResource extends BaseASQueryContext { private static final String FILE_NAME = "resourceTestFile.xq"; private static final String PATH = String.format("%s/%s", HttpConnector.APPS_PATH, FILE_NAME); @Before public void initFields() throws Exception { super.initFields(); new File(PATH).createNewFile(); }; @Test public void deleteResource() throws QueryException, FileNotFoundException, IOException { ASXQuery x = new ASXQuery(new ASCompileChain(metaDataMgr, tx), "if (rsc:delete(\"resourceTestFile.xq\")) then \"true\" else \"false\""); x.setPrettyPrint(true); x.serialize(ctx, buffer); assertEquals("true", buffer.toString()); } @Test public void renameResource() throws QueryException, FileNotFoundException, IOException { ASXQuery x = new ASXQuery( new ASCompileChain(metaDataMgr, tx), "if (rsc:rename('resourceTestFile.xq','resource')) then if (rsc:rename('resource','resourceTestFile.xq')) then 'true' else 'false' else 'false'"); x.setPrettyPrint(true); x.serialize(ctx, buffer); assertEquals("true", buffer.toString()); } @Test public void uploadResource() throws QueryException, FileNotFoundException, IOException { ASXQuery x = new ASXQuery( new ASCompileChain(metaDataMgr, tx), "if (rsc:upload('appServer','http://www.ebookpdf.net/screen/cover2/51fvzphaxml_aa240_.jpg')) then if (rsc:delete('appServer/51fvzphaxml_aa240_.jpg')) then 'true' else 'false' else 'false'"); x.setPrettyPrint(true); x.serialize(ctx, buffer); assertEquals("true", buffer.toString()); } @After public void removeFile() throws QueryException { new File(PATH).delete(); } }
923d037dd1d5b79a2866c26b88259bbbd9bbb579
2,708
java
Java
KalturaClient/src/main/java/com/kaltura/client/services/AnalyticsService.java
fahadnasrullah109/KalturaClient-Android
f753b968023e55b7629ccefce845e2482d2f6dae
[ "MIT" ]
null
null
null
KalturaClient/src/main/java/com/kaltura/client/services/AnalyticsService.java
fahadnasrullah109/KalturaClient-Android
f753b968023e55b7629ccefce845e2482d2f6dae
[ "MIT" ]
null
null
null
KalturaClient/src/main/java/com/kaltura/client/services/AnalyticsService.java
fahadnasrullah109/KalturaClient-Android
f753b968023e55b7629ccefce845e2482d2f6dae
[ "MIT" ]
null
null
null
36.594595
132
0.646603
1,000,127
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2018 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.services; import com.kaltura.client.types.AnalyticsFilter; import com.kaltura.client.types.FilterPager; import com.kaltura.client.types.ReportResponse; import com.kaltura.client.utils.request.RequestBuilder; /** * This class was generated using exec.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ /** * api for getting analytics data * * @param filter the analytics query filter * @param pager the analytics query result pager */ public class AnalyticsService { public static class QueryAnalyticsBuilder extends RequestBuilder<ReportResponse, ReportResponse.Tokenizer, QueryAnalyticsBuilder> { public QueryAnalyticsBuilder(AnalyticsFilter filter, FilterPager pager) { super(ReportResponse.class, "analytics", "query"); params.add("filter", filter); params.add("pager", pager); } } public static QueryAnalyticsBuilder query(AnalyticsFilter filter) { return query(filter, null); } /** * report query action allows to get a analytics data for specific query dimensions, metrics and filters. * * @param filter the analytics query filter * @param pager the analytics query result pager */ public static QueryAnalyticsBuilder query(AnalyticsFilter filter, FilterPager pager) { return new QueryAnalyticsBuilder(filter, pager); } }
923d0383af2f1d2a56cc77184f58987448284037
193
java
Java
asd.europe.org.s_series/src/main/java/s3000l/AshoreOrAfloadConditionCodeValues.java
woodkri/ec
12656601e9a98300f373dff6b201ed9c69509e31
[ "ECL-2.0", "Apache-2.0" ]
1
2017-11-03T06:59:06.000Z
2017-11-03T06:59:06.000Z
asd.europe.org.s_series/src/main/java/s3000l/AshoreOrAfloadConditionCodeValues.java
woodkri/ec
12656601e9a98300f373dff6b201ed9c69509e31
[ "ECL-2.0", "Apache-2.0" ]
61
2017-10-25T16:51:22.000Z
2021-06-25T15:43:30.000Z
asd.europe.org.s_series/src/main/java/s3000l/AshoreOrAfloadConditionCodeValues.java
woodkri/ec
12656601e9a98300f373dff6b201ed9c69509e31
[ "ECL-2.0", "Apache-2.0" ]
2
2017-10-13T20:34:43.000Z
2018-11-08T21:34:29.000Z
12.0625
50
0.678756
1,000,128
/** * * Generated by JaxbToStjsAssimilater. * Assimilation Date: Thu Sep 12 10:06:00 CDT 2019 * **/ package s3000l; public enum AshoreOrAfloadConditionCodeValues { ASH, AFL; }
923d03dcdaa9b87f2150d45501f9c7acb0f4eb58
6,972
java
Java
auxiliary-storage/persistence-jcr/src/main/java/org/talend/esb/auxiliary/storage/persistence/jcr/PersistencyJCRManager.java
Talend/tesb-rt-se
b8eed3b19fc8e3136953524b9030e1a6a62395f2
[ "Apache-2.0" ]
105
2015-04-01T12:56:53.000Z
2022-01-17T10:01:53.000Z
auxiliary-storage/persistence-jcr/src/main/java/org/talend/esb/auxiliary/storage/persistence/jcr/PersistencyJCRManager.java
Talend/tesb-rt-se
b8eed3b19fc8e3136953524b9030e1a6a62395f2
[ "Apache-2.0" ]
90
2016-11-30T13:54:22.000Z
2022-03-31T21:11:26.000Z
auxiliary-storage/persistence-jcr/src/main/java/org/talend/esb/auxiliary/storage/persistence/jcr/PersistencyJCRManager.java
Talend/tesb-rt-se
b8eed3b19fc8e3136953524b9030e1a6a62395f2
[ "Apache-2.0" ]
158
2015-01-07T17:14:52.000Z
2022-02-23T12:12:45.000Z
35.035176
128
0.613024
1,000,129
/* * ============================================================================ * * Copyright (c) 2006-2021 Talend Inc. - www.talend.com * * This source code is available under agreement available at * %InstallDIR%\license.txt * * You should have received a copy of the agreement * along with this program; if not, write to Talend SA * 5/7 rue Salomon De Rothschild, 92150 Suresnes, France * * ============================================================================ */ package org.talend.esb.auxiliary.storage.persistence.jcr; import java.util.HashMap; import java.util.logging.Level; import javax.jcr.LoginException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.Property; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.RepositoryFactory; import javax.jcr.Session; import javax.jcr.SimpleCredentials; import org.apache.jackrabbit.core.RepositoryFactoryImpl; import org.talend.esb.auxiliary.storage.common.exception.ObjectAlreadyExistsException; import org.talend.esb.auxiliary.storage.common.exception.ObjectNotFoundException; import org.talend.esb.auxiliary.storage.common.exception.InitializationException; import org.talend.esb.auxiliary.storage.common.exception.PersistencyException; import org.talend.esb.auxiliary.storage.persistence.AbstractPersistencyManager; public class PersistencyJCRManager extends AbstractPersistencyManager { public static String CONTEXT_DATA_PROPERTY_NAME = "context"; private RepositoryFactory repositoryFactory; private Repository repository; private String storageDirPath; public PersistencyJCRManager() { repositoryFactory = new RepositoryFactoryImpl(); } public void init() throws InitializationException { if (repositoryFactory == null) { String errorMessage = "Failed to initialize auxiliary storage persistency manager. JCR repository factory is null."; LOG.log(Level.SEVERE, errorMessage); throw new InitializationException(errorMessage); } HashMap<String,String> parameters = new HashMap<String, String>(); parameters.put(RepositoryFactoryImpl.REPOSITORY_HOME, storageDirPath); parameters.put(RepositoryFactoryImpl.REPOSITORY_CONF, "etc/org.talend.esb.auxiliary.repo.xml"); try { repository = repositoryFactory.getRepository(parameters); } catch (RepositoryException e) { String errorMessage = "Failed to initialize auxiliary storage persistency manager. " + "Failed to inititalize jackrabbit repository: " + e.getMessage(); LOG.log(Level.SEVERE, errorMessage); throw new InitializationException(errorMessage); } } @Override public void storeObject(String context, String key) throws PersistencyException { Session session = null; Node rootNode; Node node; synchronized (this) { try { session = getSession(); rootNode = session.getRootNode(); if (rootNode.hasNode(key)) { throw new ObjectAlreadyExistsException("Dublicated object with key {" + key + "}"); } node = rootNode.addNode(key); node.setProperty(CONTEXT_DATA_PROPERTY_NAME, context); session.save(); } catch (RepositoryException e) { LOG.log(Level.SEVERE, "Failed to sotre object. RepositoryException. Error message: " + e.getMessage()); throw new PersistencyException("Saving object failed due to error " + e.getMessage()); } finally { releaseSession(session); } } } @Override public String restoreObject(String key) throws PersistencyException { Node node = null; Property property = null; Session session=null; Node rootNode; synchronized (this) { try { session = getSession(); rootNode = session.getRootNode(); node = rootNode.getNode(key); property = node.getProperty(CONTEXT_DATA_PROPERTY_NAME); return (property == null) ? null : property.getString(); } catch (PathNotFoundException e) { return null; } catch (RepositoryException e) { LOG.log(Level.SEVERE, "Failed to resotre object. RepositoryException. Error message: " + e.getMessage()); throw new PersistencyException("Error retrieving auxiliary store node with the key " + key + " Underlying error message is:" + e.getMessage()); } finally { releaseSession(session); } } } @Override public void removeObject(String key) throws PersistencyException { synchronized (this) { Session session=null; Node rootNode; try { session = getSession(); rootNode = session.getRootNode(); Node node = rootNode.getNode(key); node.remove(); session.save(); } catch (PathNotFoundException e) { String errorMessage = "Attempt to remove non-existing object with key: " + key; LOG.log(Level.WARNING, errorMessage); throw new ObjectNotFoundException(errorMessage); } catch (RepositoryException e) { String errorMessage = "Attempt to remove object with key: " + key + " failed. " + "RepositoryException. Error message is: " + e.getMessage(); LOG.log(Level.WARNING, errorMessage); throw new PersistencyException(errorMessage); } finally { releaseSession(session); } } } public void setStorageDirPath(String storageDirPath) { this.storageDirPath = storageDirPath; } private Session getSession() { Session session = null; try { session = repository.login(new SimpleCredentials("admin", "admin".toCharArray())); return session; } catch (LoginException e) { String errorMessage = "Failed to login to jackrabbit repository: " + e.getMessage(); LOG.log(Level.SEVERE, errorMessage); throw new InitializationException(errorMessage); } catch (RepositoryException e) { String errorMessage = "Error occured during login process to jackrabbit repository: " + e.getMessage(); LOG.log(Level.SEVERE, errorMessage); throw new InitializationException(errorMessage); } } private void releaseSession(Session session) { if (session != null) { session.logout(); session = null; } } }
923d049bbec6544a087e045a4843df7164ce67b6
437
java
Java
mall-cloud-api/mall-passport-api/src/main/java/com/mall/cloud/passport/api/service/AppAuthorizeService.java
mazhilin/mall-platform
bb116cefec793718772451aa9ed221f621bce73a
[ "Apache-2.0" ]
null
null
null
mall-cloud-api/mall-passport-api/src/main/java/com/mall/cloud/passport/api/service/AppAuthorizeService.java
mazhilin/mall-platform
bb116cefec793718772451aa9ed221f621bce73a
[ "Apache-2.0" ]
null
null
null
mall-cloud-api/mall-passport-api/src/main/java/com/mall/cloud/passport/api/service/AppAuthorizeService.java
mazhilin/mall-platform
bb116cefec793718772451aa9ed221f621bce73a
[ "Apache-2.0" ]
null
null
null
29.133333
103
0.743707
1,000,130
package com.mall.cloud.passport.api.service; import com.mall.cloud.common.component.BaseApplicationAuthorize; /** * <p>封装Qicloud项目AppAuthorizeService类.<br></p> * <p>//TODO...<br></p> * * @author Powered by marklin 2020-11-12 20:21 * @version 1.0.0 * <p>Copyright © 2018-2020 Pivotal Cloud Technology Systems Incorporated. All rights reserved.<br></p> */ public interface AppAuthorizeService extends BaseApplicationAuthorize { }
923d04b55a569483e5f2535724f68c13280655f3
1,946
java
Java
back/src/main/java/com/vector/manager/wx/controller/SyncGzhUserInfoController.java
yuanjiejiahui/background_Management
523fd9bc053529eb273db8a02a4140d67064cfe6
[ "Apache-2.0" ]
null
null
null
back/src/main/java/com/vector/manager/wx/controller/SyncGzhUserInfoController.java
yuanjiejiahui/background_Management
523fd9bc053529eb273db8a02a4140d67064cfe6
[ "Apache-2.0" ]
null
null
null
back/src/main/java/com/vector/manager/wx/controller/SyncGzhUserInfoController.java
yuanjiejiahui/background_Management
523fd9bc053529eb273db8a02a4140d67064cfe6
[ "Apache-2.0" ]
null
null
null
31.387097
73
0.703494
1,000,131
package com.vector.manager.wx.controller; import cn.hutool.core.thread.ThreadUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.vector.manager.core.common.Result; import com.vector.manager.wx.entity.GzhAccount; import com.vector.manager.wx.service.IGzhAccountService; import com.vector.manager.wx.service.IGzhUserService; import com.vector.manager.wx.service.impl.SyncLock; import java.util.Arrays; @Slf4j @Api(value = "同步公众号用户信息", tags = "同步Api接口") @RestController @RequestMapping("/wx/gzh-user") public class SyncGzhUserInfoController { @Autowired private IGzhAccountService gzhAccountService; @Autowired private IGzhUserService gzhUserService; @Autowired private SyncLock syncLock; @ApiOperation(value = "选择同步微信用户信息") @RequiresPermissions("wx:gzhuser:sync") @PostMapping("/syncMore") public Result syncMoreWxUserInfo(@RequestBody Long[] ids) { gzhUserService.syncMoreWxGzhUser(Arrays.asList(ids)); return Result.ok(); } @ApiOperation(value = "同步所有微信用户信息") @RequiresPermissions("wx:gzhuser:sync:all") @GetMapping("/syncWxUserInfo") public Result syncWxUserInfo() { GzhAccount gzhAccount = gzhAccountService.getDefalutGzhAccount(); if (gzhAccount == null) { return Result.fail("未设置默认公众号"); } String lock = syncLock.getSynclock(gzhAccount); if (!syncLock.lock(lock)) { return Result.fail("正在同步中,请稍等..."); } ThreadUtil.execute(new Runnable() { @Override public void run() { gzhUserService.syncBatchWxGzhUser(gzhAccount, lock); } }); return Result.ok(); } }
923d04f78e8dbf82bed616ce4f8d13ed7444c88f
394
java
Java
springfox-demo/src/main/java/com/example/demo/App.java
twotwo/spring-boot-warmup
59013d609e2047b4c7d47ed1b20fda5d102fa9e9
[ "Apache-2.0" ]
1
2020-03-13T10:46:30.000Z
2020-03-13T10:46:30.000Z
springfox-demo/src/main/java/com/example/demo/App.java
twotwo/spring-boot-warmup
59013d609e2047b4c7d47ed1b20fda5d102fa9e9
[ "Apache-2.0" ]
null
null
null
springfox-demo/src/main/java/com/example/demo/App.java
twotwo/spring-boot-warmup
59013d609e2047b4c7d47ed1b20fda5d102fa9e9
[ "Apache-2.0" ]
1
2020-03-13T10:46:29.000Z
2020-03-13T10:46:29.000Z
30.307692
68
0.791878
1,000,132
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; @SpringBootApplication @EntityScan("com.example.demo.domain") public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
923d0557f54df8afd8f183e8415fc1a0cf93be76
4,670
java
Java
src/test/java/de/slevermann/cocktails/service/ModerationServiceTest.java
sonOfRa/cocktails
cdbfe80bbdc843f42d98a1fc3422ba514ce839a6
[ "Apache-2.0" ]
null
null
null
src/test/java/de/slevermann/cocktails/service/ModerationServiceTest.java
sonOfRa/cocktails
cdbfe80bbdc843f42d98a1fc3422ba514ce839a6
[ "Apache-2.0" ]
null
null
null
src/test/java/de/slevermann/cocktails/service/ModerationServiceTest.java
sonOfRa/cocktails
cdbfe80bbdc843f42d98a1fc3422ba514ce839a6
[ "Apache-2.0" ]
1
2021-09-28T17:56:30.000Z
2021-09-28T17:56:30.000Z
40.608696
111
0.689293
1,000,133
package de.slevermann.cocktails.service; import de.slevermann.cocktails.dao.IngredientDao; import de.slevermann.cocktails.dto.LocalizedIngredient; import de.slevermann.cocktails.dto.LocalizedIngredientType; import de.slevermann.cocktails.dto.Moderation; import de.slevermann.cocktails.exception.ModerationException; import de.slevermann.cocktails.model.db.DbIngredient; import de.slevermann.cocktails.model.db.DbIngredientType; import de.slevermann.cocktails.model.db.DbModeration; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.mockito.junit.jupiter.MockitoSettings; import org.springframework.web.server.ResponseStatusException; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import static org.springframework.http.HttpStatus.*; @MockitoSettings public class ModerationServiceTest { private final IngredientDao ingredientDao = mock(IngredientDao.class); private final ModerationService moderationService = new ModerationService(ingredientDao); private static final LocalizedIngredientType TYPE = new LocalizedIngredientType() .type("typ") .language("en") .id(UUID.randomUUID()); private static final List<LocalizedIngredient> QUEUE = List.of( new LocalizedIngredient() .id(UUID.randomUUID()) .type(TYPE) .language("en") .name("name") .description("description"), new LocalizedIngredient() .id(UUID.randomUUID()) .type(TYPE) .language("en") .name("name") .description("description") ); private static final DbIngredientType DB_TYPE = DbIngredientType.builder() .names(Map.of("de", "bla")) .uuid(UUID.randomUUID()).build(); private static DbIngredient buildIngredient(DbModeration moderation) { return DbIngredient.builder() .uuid(UUID.randomUUID()) .type(DB_TYPE) .moderation(moderation) .names(Map.of("de", "bla")) .descriptions(Map.of("de", "foo")).build(); } @Test public void testGetIngredientQueue() { when(ingredientDao.getModerationQueue(anyString())).thenReturn(QUEUE); assertEquals(QUEUE, moderationService.getIngredientQueue(Locale.GERMAN), "Service list should be equal to what the dao returns"); } @ParameterizedTest @EnumSource(Moderation.ActionEnum.class) public void testModerateIngredientNotFound(Moderation.ActionEnum action) { when(ingredientDao.getById(any())).thenReturn(null); ResponseStatusException ex = assertThrows(ResponseStatusException.class, () -> moderationService.moderateIngredient(UUID.randomUUID(), new Moderation().action(action)), "Moderating a non existing ingredient should throw an exception"); assertEquals(NOT_FOUND, ex.getStatus(), "HTTP Status should be 404"); } @ParameterizedTest @EnumSource(Moderation.ActionEnum.class) public void testModerateNoStatus(Moderation.ActionEnum action) { when(ingredientDao.getById(any())).thenReturn(buildIngredient(null)); assertThrows(ModerationException.class, () -> moderationService.moderateIngredient(UUID.randomUUID(), new Moderation().action(action)), "Missing status in db should throw an exception"); } @ParameterizedTest @EnumSource(Moderation.ActionEnum.class) public void testModerateRejected(Moderation.ActionEnum action) { when(ingredientDao.getById(any())).thenReturn(buildIngredient(DbModeration.REJECTED)); ModerationException ex = assertThrows(ModerationException.class, () -> moderationService.moderateIngredient(UUID.randomUUID(), new Moderation().action(action)), "Moderating a rejected ingredient should throw an exception"); assertTrue(ex.getMessage().contains("rejected"), "Exception message contains error cause"); } @ParameterizedTest @EnumSource(Moderation.ActionEnum.class) public void testModerateWaiting(Moderation.ActionEnum action) { when(ingredientDao.getById(any())).thenReturn(buildIngredient(DbModeration.WAITING)); moderationService.moderateIngredient(UUID.randomUUID(), new Moderation().action(action)); } }
923d059afe2a773204c33b93d6df4ebeb777ea9a
763
java
Java
annot8-testing/annot8-impl-tck/src/main/java/io/annot8/testing/tck/impl/WithIdBuilderTestUtils.java
annot8/annot8-merged
9a2cb56d5703162abe34c98cfc9157e87f805079
[ "Apache-2.0" ]
3
2020-01-22T10:49:42.000Z
2021-03-11T11:35:23.000Z
annot8-testing/annot8-impl-tck/src/main/java/io/annot8/testing/tck/impl/WithIdBuilderTestUtils.java
annot8/annot8-merged
9a2cb56d5703162abe34c98cfc9157e87f805079
[ "Apache-2.0" ]
27
2019-09-09T11:43:07.000Z
2019-09-13T08:44:35.000Z
annot8-testing/annot8-impl-tck/src/main/java/io/annot8/testing/tck/impl/WithIdBuilderTestUtils.java
annot8/annot8
4d0dfb63c615c8e559b1defe2312f44d23d60ddc
[ "Apache-2.0" ]
3
2021-01-15T07:30:27.000Z
2022-02-03T09:26:20.000Z
31.791667
84
0.735256
1,000,134
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */ package io.annot8.testing.tck.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import io.annot8.api.exceptions.IncompleteException; import io.annot8.api.helpers.WithId; import io.annot8.api.helpers.builders.WithIdBuilder; import io.annot8.api.helpers.builders.WithSave; public class WithIdBuilderTestUtils<T extends WithIdBuilder<T> & WithSave<WithId>> { public void testWithIdBuilder(T builder) { WithId withId = null; try { withId = builder.withId("test").save(); assertEquals("test", withId.getId()); } catch (IncompleteException e) { fail("Test should not throw an exception here", e); } } }
923d06bc7f2da6a88d73b1706b4884c36b9b2494
1,263
java
Java
application/src/main/java/org/thingsboard/server/service/telemetry/TelemetrySubscriptionService.java
jmhernandez-circutor/thingsboard
0ea799d8e33e1d91a4f3fcf17ea034d82fe10ea0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
application/src/main/java/org/thingsboard/server/service/telemetry/TelemetrySubscriptionService.java
jmhernandez-circutor/thingsboard
0ea799d8e33e1d91a4f3fcf17ea034d82fe10ea0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
application/src/main/java/org/thingsboard/server/service/telemetry/TelemetrySubscriptionService.java
jmhernandez-circutor/thingsboard
0ea799d8e33e1d91a4f3fcf17ea034d82fe10ea0
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
37.147059
103
0.78464
1,000,135
/** * Copyright © 2016-2018 The Thingsboard 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.thingsboard.server.service.telemetry; import org.thingsboard.rule.engine.api.RuleEngineTelemetryService; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState; /** * Created by ashvayka on 27.03.18. */ public interface TelemetrySubscriptionService extends RuleEngineTelemetryService { void addLocalWsSubscription(String sessionId, EntityId entityId, SubscriptionState sub); void cleanupLocalWsSessionSubscriptions(TelemetryWebSocketSessionRef sessionRef, String sessionId); void removeSubscription(String sessionId, int cmdId); }
923d0757e3dade0a65bd6b343c2831dc891c41f5
2,490
java
Java
src/main/java/tv/inair/airmote/DeviceListActivity.java
seespace/androidairmote
b32bff3c3eb551bd07adc856cc352116b14a5aa6
[ "Unlicense" ]
null
null
null
src/main/java/tv/inair/airmote/DeviceListActivity.java
seespace/androidairmote
b32bff3c3eb551bd07adc856cc352116b14a5aa6
[ "Unlicense" ]
null
null
null
src/main/java/tv/inair/airmote/DeviceListActivity.java
seespace/androidairmote
b32bff3c3eb551bd07adc856cc352116b14a5aa6
[ "Unlicense" ]
null
null
null
29.642857
100
0.739759
1,000,136
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tv.inair.airmote; import android.app.Activity; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import tv.inair.airmote.connection.BaseConnection; import tv.inair.airmote.connection.SocketClient; /** * This Activity appears as a dialog. It lists any paired devices and * devices detected in the area after discovery. When a device is chosen * by the user, the MAC address of the device is sent back to the parent * Activity in the result Intent. */ public class DeviceListActivity extends ListActivity implements BaseConnection.DeviceFoundListener { private ArrayAdapter<String> mAdapter; private SocketClient mClient; @Override protected void onListItemClick(ListView l, View v, int position, long id) { cancelDiscovery(); mClient.connectTo(devices.get(position)); finish(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setResult(Activity.RESULT_CANCELED); mClient = Application.getSocketClient(); mAdapter = new ArrayAdapter<>(this, R.layout.device_item); setListAdapter(mAdapter); setTitle("Scanning"); Application.notify("Scanning ...", Application.Status.NORMAL); mClient.startScanInAir(this); } @Override protected void onDestroy() { cancelDiscovery(); super.onDestroy(); } final List<BaseConnection.Device> devices = new ArrayList<>(); final List<String> mItems = new ArrayList<>(); @Override public void onDeviceFound(BaseConnection.Device device) { if (!mItems.contains(device.deviceName)) { devices.add(device); mAdapter.add(device.deviceName); } } private void cancelDiscovery() { mClient.stopScanInAir(); } }
923d0794ddcc983863850de32b57d4a44d5479ac
1,465
java
Java
src/main/java/freemarker/debug/impl/RmiDebuggerListenerImpl.java
porkbao/freemarker
451b28020bbec488d6b13065058f2382e7a62455
[ "Apache-2.0" ]
1
2021-09-06T22:51:12.000Z
2021-09-06T22:51:12.000Z
src/main/java/freemarker/debug/impl/RmiDebuggerListenerImpl.java
porkbao/freemarker
451b28020bbec488d6b13065058f2382e7a62455
[ "Apache-2.0" ]
1
2020-07-24T22:23:48.000Z
2020-07-24T22:23:48.000Z
src/main/java/freemarker/debug/impl/RmiDebuggerListenerImpl.java
porkbao/freemarker
451b28020bbec488d6b13065058f2382e7a62455
[ "Apache-2.0" ]
4
2018-08-15T12:31:05.000Z
2021-09-06T22:48:57.000Z
26.636364
91
0.686007
1,000,137
package freemarker.debug.impl; import java.rmi.NoSuchObjectException; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.rmi.server.Unreferenced; import freemarker.debug.DebuggerClient; import freemarker.debug.DebuggerListener; import freemarker.debug.EnvironmentSuspendedEvent; import freemarker.log.Logger; /** * Used by the {@link DebuggerClient} to create local * @author Attila Szegedi * @version $Id: RmiDebuggerListenerImpl.java,v 1.1.2.1 2006/11/27 07:54:49 szegedia Exp $ */ public class RmiDebuggerListenerImpl extends UnicastRemoteObject implements DebuggerListener, Unreferenced { private static final Logger logger = Logger.getLogger( "freemarker.debug.client"); private static final long serialVersionUID = 1L; private final DebuggerListener listener; public void unreferenced() { try { UnicastRemoteObject.unexportObject(this, false); } catch (NoSuchObjectException e) { logger.warn("Failed to unexport RMI debugger listener", e); } } public RmiDebuggerListenerImpl(DebuggerListener listener) throws RemoteException { this.listener = listener; } public void environmentSuspended(EnvironmentSuspendedEvent e) throws RemoteException { listener.environmentSuspended(e); } }
923d081b56e3af66143cb958016f190a732459c3
5,861
java
Java
src/main/java/com/rbkmoney/dark/api/controller/ErrorControllerAdvice.java
rbkmoney/dark-api
c58ef15b8e6777ca5d44d9e5eff268f6c2ab4389
[ "Apache-2.0" ]
3
2020-03-20T22:14:55.000Z
2021-01-25T15:58:57.000Z
src/main/java/com/rbkmoney/dark/api/controller/ErrorControllerAdvice.java
rbkmoney/dark-api
c58ef15b8e6777ca5d44d9e5eff268f6c2ab4389
[ "Apache-2.0" ]
2
2020-10-28T12:33:51.000Z
2021-07-30T12:14:13.000Z
src/main/java/com/rbkmoney/dark/api/controller/ErrorControllerAdvice.java
rbkmoney/dark-api
c58ef15b8e6777ca5d44d9e5eff268f6c2ab4389
[ "Apache-2.0" ]
3
2020-03-20T09:58:43.000Z
2021-12-07T09:07:52.000Z
40.986014
120
0.733834
1,000,138
package com.rbkmoney.dark.api.controller; import com.rbkmoney.dark.api.exceptions.client.*; import com.rbkmoney.dark.api.exceptions.client.badrequest.BadRequestException; import com.rbkmoney.dark.api.exceptions.server.DarkApi5xxException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.util.CollectionUtils; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.context.request.WebRequest; import java.net.http.HttpTimeoutException; import java.util.List; import static org.springframework.http.ResponseEntity.status; @Slf4j @RestControllerAdvice @RequiredArgsConstructor public class ErrorControllerAdvice { // ----------------- 4xx ----------------------------------------------------- @ExceptionHandler({BadRequestException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public Object handleBadRequestException(BadRequestException e) { log.warn("<- Res [400]: Not valid", e); return e.getResponse(); } @ExceptionHandler({MethodArgumentNotValidException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public void handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.warn("<- Res [400]: MethodArgument not valid", e); } @ExceptionHandler({MissingServletRequestParameterException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public void handleMissingServletRequestParameterException(MissingServletRequestParameterException e) { log.warn("<- Res [400]: Missing ServletRequestParameter", e); } @ExceptionHandler(UnauthorizedException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) public void handleUnauthorizedException(UnauthorizedException e) { log.warn("<- Res [401]: Unauthorized", e); } @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public void handleAccessDeniedException(AccessDeniedException e) { log.warn("<- Res [403]: Request denied access", e); } @ExceptionHandler(ForbiddenException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public void handleForbiddenException(ForbiddenException e) { log.warn("<- Res [403]: Request denied access", e); } @ExceptionHandler(NotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public Object handleFileNotFoundException(NotFoundException e) { log.warn("<- Res [404]: Not found", e); return e.getResponse(); } @ExceptionHandler({HttpMediaTypeNotAcceptableException.class}) @ResponseStatus(HttpStatus.NOT_ACCEPTABLE) public void handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException e) { log.warn("<- Res [406]: MediaType not acceptable", e); } @ExceptionHandler(ConflictException.class) @ResponseStatus(HttpStatus.CONFLICT) public Object handleConflictException(ConflictException e) { log.warn("<- Res [409]: Conflict", e); return e.getResponse(); } @ExceptionHandler({HttpMediaTypeNotSupportedException.class}) public ResponseEntity<?> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException e, WebRequest request) { log.warn("<- Res [415]: MediaType not supported", e); return status(HttpStatus.UNSUPPORTED_MEDIA_TYPE) .headers(httpHeaders(e)) .build(); } @ExceptionHandler({DarkApi4xxException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public void handleDarkApiClientException(DarkApi4xxException e) { log.warn("<- Res [400]: Unrecognized Error by controller", e); } // ----------------- 5xx ----------------------------------------------------- @ExceptionHandler(HttpClientErrorException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleHttpClientErrorException(HttpClientErrorException e) { log.error("<- Res [500]: Error with using inner http client, code={}, body={}", e.getStatusCode(), e.getResponseBodyAsString(), e); } @ExceptionHandler(HttpTimeoutException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleHttpTimeoutException(HttpTimeoutException e) { log.error("<- Res [500]: Timeout with using inner http client", e); } @ExceptionHandler(DarkApi5xxException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleHttpTimeoutException(DarkApi5xxException e) { log.error("<- Res [500]: Unrecognized inner error", e); } @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public void handleException(Exception e) { log.error("<- Res [500]: Unrecognized inner error", e); } private HttpHeaders httpHeaders(HttpMediaTypeNotSupportedException e) { HttpHeaders headers = new HttpHeaders(); List<MediaType> mediaTypes = e.getSupportedMediaTypes(); if (!CollectionUtils.isEmpty(mediaTypes)) { headers.setAccept(mediaTypes); } return headers; } }
923d088454e438ee2d913a318c4ac4171da4816b
3,932
java
Java
src/main/java/com/asodc/citysim/old/CityState.java
aseriesofdarkcaves/citysim
66f7472515a4c1101ff641ed2699579d338042a0
[ "MIT" ]
null
null
null
src/main/java/com/asodc/citysim/old/CityState.java
aseriesofdarkcaves/citysim
66f7472515a4c1101ff641ed2699579d338042a0
[ "MIT" ]
null
null
null
src/main/java/com/asodc/citysim/old/CityState.java
aseriesofdarkcaves/citysim
66f7472515a4c1101ff641ed2699579d338042a0
[ "MIT" ]
null
null
null
33.896552
100
0.538911
1,000,139
package com.asodc.citysim.old; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Random; class CityState { private static Tile[][] tiles; private static ArrayList<Business> businesses = new ArrayList<>(); private CityState(int width, int height) { tiles = new Tile[width][height]; } static CityState createInitialState(City city) { CityState state = null; switch (city.getType()) { case CUSTOM: state = generateCustomCity(city); break; case GUIS_ALGORITHM: state = generateGuiCity(city); break; case RANDOM: state = generateRandomCity(city); break; } return state; } private static CityState generateCustomCity(City city) { // TODO we can't know the width and height before parsing the file CityState state = new CityState(city.getWidth(), city.getHeight()); try (BufferedReader reader = new BufferedReader(new FileReader(city.getCityFile()))) { int y = 0; for (String line = reader.readLine(); line != null; line = reader.readLine()) { for (int x = 0; x < line.length(); x++) { switch (line.charAt(x)) { case 'g': tiles[x][y] = TileFactory.create(TileType.GRASS); break; case 'r': tiles[x][y] = TileFactory.create(TileType.ROAD); break; } } y++; } } catch (IOException e) { e.printStackTrace(); } return state; } private static CityState generateGuiCity(City city) { // horizontalRoads = random between 1 and width/2 // verticalRoads = random between 1 and height/2 // choose a random x coordinate and draw verticalRoads number of roads vertically // choose a random y coordinate and draw horizontalRoads number of roads horizontally // RULE: roads cannot be drawn in immediately adjacent axes // fill empty tiles with business tiles CityState state = new CityState(city.getWidth(), city.getHeight()); Random horizontalRandom = new Random(); Random verticalRandom = new Random(); int horizontalRoads = horizontalRandom.nextInt(tiles[0].length / 4) + (tiles[0].length / 4); int verticalRoads = verticalRandom.nextInt(tiles[1].length / 4) + (tiles[1].length / 4); for (int x = 0; x < tiles[0].length; x++) { int drawRoad = horizontalRandom.nextInt(2); if (drawRoad == 1 && horizontalRoads != 0) { for (int y = 0; y < tiles[1].length; y++) { // draw horizontal road tiles[x][y] = TileFactory.create(TileType.ROAD); } horizontalRoads--; } } // TODO draw vertical roads return state; } private static CityState generateRandomCity(City city) { CityState state = new CityState(city.getWidth(), city.getHeight()); for (int y = 0; y < tiles[1].length; y++) { for (int x = 0; x < tiles[0].length; x++) { Tile currentTile = TileFactory.create(TileType.random()); if (currentTile.getTileType() == TileType.BUSINESS) { businesses.add(new Business()); } tiles[x][y] = currentTile; } } return state; } Tile getTile(int x, int y) { return tiles[x][y]; } Tile[][] getTiles() { return tiles; } ArrayList<Business> getBusinesses() { return businesses; } }
923d08851aa82a54e15b42d62cf5271a6b444c23
18,723
java
Java
ctakes-patch/ctakes-core/src/main/java/org/apache/ctakes/core/nlp/tokenizer/Tokenizer.java
CDCgov/DCPC
c3fadef1bd6345e01a58afef051491d8ef6a7f93
[ "Apache-2.0" ]
6
2018-11-03T22:43:35.000Z
2022-02-15T17:51:33.000Z
ctakes-patch/ctakes-core/src/main/java/org/apache/ctakes/core/nlp/tokenizer/Tokenizer.java
CDCgov/DCPC
c3fadef1bd6345e01a58afef051491d8ef6a7f93
[ "Apache-2.0" ]
2
2019-04-08T03:42:59.000Z
2019-10-28T13:42:59.000Z
ctakes-patch/ctakes-core/src/main/java/org/apache/ctakes/core/nlp/tokenizer/Tokenizer.java
CDCgov/DCPC
c3fadef1bd6345e01a58afef051491d8ef6a7f93
[ "Apache-2.0" ]
10
2017-04-10T21:40:22.000Z
2022-02-21T16:50:10.000Z
28.584733
82
0.640656
1,000,140
/** * 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.ctakes.core.nlp.tokenizer; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A class used to break natural text into tokens. The token markup is external * to the text and is not embedded like XML. Character offset location is used * to identify the boundaries of a token. * * @author Mayo Clinic */ public class Tokenizer { private OffsetComparator iv_offsetComp = new OffsetComparator(); // key = hypenated String obj, value = freq Integer obj private Map<String, Integer> iv_hyphMap; private int iv_freqCutoff; /** * Constructor */ public Tokenizer() { } /** * Constructor * * @param hyphMap * Map where key=hyphenated string (lower cased) value=freq * Integer * * @param freqCutoff * frequency cutoff */ public Tokenizer(Map<String, Integer> hyphMap, int freqCutoff) { iv_hyphMap = hyphMap; iv_freqCutoff = freqCutoff; } /** * Validate the structure of the hyphen map. */ public static void validateHyphenMap(Map<String, Integer> hyphMap) throws Exception { Iterator<String> keyItr = hyphMap.keySet().iterator(); while (keyItr.hasNext()) { String key = keyItr.next(); Object val = hyphMap.get(key); if (val == null) { throw new Exception( "Hyphen map is missing frequency data for key=" + key); } if ((val instanceof Integer) == false) { throw new Exception( "Hyphen map has non java.lang.Integer frequency data for key=" + key); } } } /** * Tokenizes a string of text and outputs a list of Token objects in sorted * order. * * @param text * The text to tokenize. * @return A list of Token objects sorted by the order they appear in the * text. * @throws Exception * Thrown if an error occurs while tokenizing. */ public List<Token> tokenizeAndSort(String text) throws Exception { List<Token> tokenList = tokenize(text); // sort tokens by offset Collections.sort(tokenList, iv_offsetComp); return tokenList; } /** * Tokenizes a string of text and outputs a list of Token objects. The list * is not guaranteed to be sorted. * * @param text The text to tokenize. * @return A list of Token objects. */ public List<Token> tokenize(String text) throws Exception { try { List<Token> eolTokens = getEndOfLineTokens(text); // Break text into raw tokens (whitespace-delimited text) List<Token> tokens = getRawTokens(text); // Detect punctuation and symbols inside the raw tokens applyPunctSymbolRules(tokens, text); for (int i = 0; i < tokens.size(); i++) { Token token = tokens.get(i); String tokenText = text.substring(token.getStartOffset(), token .getEndOffset()); if (token.getType() != Token.TYPE_PUNCT) { if (isNumber(tokenText)) { token.setType(Token.TYPE_NUMBER); token.setIsInteger(isInteger(tokenText)); } if (token.getType() == Token.TYPE_UNKNOWN) { // token must be a word if it's not classified yet token.setType(Token.TYPE_WORD); } if (token.getType() == Token.TYPE_WORD) { applyCapitalizationRules(token, tokenText); applyWordNumRules(token, tokenText); } } } tokens.addAll(eolTokens); // set text for tokens for (int i = 0; i < tokens.size(); i++) { Token t = tokens.get(i); t.setText(text.substring(t.getStartOffset(), t.getEndOffset())); } return tokens; } catch (Exception e) { e.printStackTrace(); throw new Exception("Internal Error with Tokenizer."); } } /** * Applies punctuation/symbol rules to the given list of tokens. Tokens that * are punctuation/symbols are marked as such. Tokens that contain * punctuation/symbols inside them are split into multiple tokens, one of * which is the inner punctuation/symbol token. * * @param tokens List of tokens to apply rules to. * @param text The original text. */ private void applyPunctSymbolRules(List<Token> tokens, String text) { List<Token> newTokenList = new ArrayList<Token>(); List<Token> removeTokenList = new ArrayList<Token>(); for (int tIndex = 0; tIndex < tokens.size(); tIndex++) { Token token = tokens.get(tIndex); String tokenText = text.substring(token.getStartOffset(), token .getEndOffset()); if (tokenText.length() == 1) { char currentChar = tokenText.charAt(0); // token is only 1 character long, check if it's a symbol if (!isAlphabetLetterOrDigit(currentChar)) { if (isPunctuation(currentChar)) { token.setType(Token.TYPE_PUNCT); } else { token.setType(Token.TYPE_SYMBOL); } } continue; } // punctuation/symbol at start of token int startCnt = processStartPunctSymbol(newTokenList, token, tokenText); // adjust original token to no longer include the punctuation/symbol token.setStartOffset(token.getStartOffset() + startCnt); // punctuation at end of token tokenText = text.substring(token.getStartOffset(), token .getEndOffset()); int endCnt = processEndPunctSymbol(newTokenList, token, tokenText); // adjust original token to no longer include the punctuation/symbol token.setEndOffset(token.getEndOffset() - endCnt); // If the original token was only a punctuation or symbol, // and the start and end punctuation/symbol // has been stripped off, it's possible to now have an empty token // In that case, remove the empty token if (token.getStartOffset() == token.getEndOffset()) { removeTokenList.add(token); } // contractions tokenText = text.substring(token.getStartOffset(), token .getEndOffset()); int aposIndex = tokenText.indexOf('\''); if (aposIndex != -1) { Token cpToken = null; String afterAposStr = tokenText.substring(aposIndex + 1, tokenText.length()); if (afterAposStr.length() == 1) { // handle xxx'd (e.g. we'd) // handle xxx'm (e.g. I'm) // handle xxx's (e.g. it's) if (afterAposStr.equalsIgnoreCase("d") || afterAposStr.equalsIgnoreCase("m") || afterAposStr.equalsIgnoreCase("s")) { cpToken = new Token(token.getStartOffset() + aposIndex, token.getEndOffset()); } // handle xxxn't (e.g. won't don't) else if (afterAposStr.equalsIgnoreCase("t")) { String beforeAposChar = tokenText.substring( aposIndex - 1, aposIndex); if (beforeAposChar.equalsIgnoreCase("n")) { cpToken = new Token(token.getStartOffset() + aposIndex - 1, token.getEndOffset()); } } } else if (afterAposStr.length() == 2) { // handle xxx're (e.g. they're) // handle xxx've (e.g. they've) // handle xxx'll (e.g. they'll) if (afterAposStr.equalsIgnoreCase("re") || afterAposStr.equalsIgnoreCase("ve") || afterAposStr.equalsIgnoreCase("ll")) { cpToken = new Token(token.getStartOffset() + aposIndex, token.getEndOffset()); } } if (cpToken != null) { cpToken.setType(Token.TYPE_CONTRACTION); newTokenList.add(cpToken); // adjust original token to no longer include the // contraction // or possessive token.setEndOffset(cpToken.getStartOffset()); } } else if (tokenText.equalsIgnoreCase("cannot")) { // special case where cannot needs to be split into can & not Token notToken = new Token(token.getStartOffset() + 3, token .getEndOffset()); notToken.setType(Token.TYPE_WORD); newTokenList.add(notToken); // adjust original token to no longer include "not" token.setEndOffset(token.getStartOffset() + 3); } // punctuation inside the token tokenText = text.substring(token.getStartOffset(), token .getEndOffset()); boolean foundSomethingInside = findPunctSymbolInsideToken(tokens, token, tokenText); // sourceforge bug tracker #3072902 // if nothing left after remove the contraction, such as the line " n't " // then all of token was turned into a contraction token if (token.getEndOffset()== token.getStartOffset()) foundSomethingInside = true; if (foundSomethingInside) { removeTokenList.add(token); } } tokens.addAll(newTokenList); for (int i = 0; i < removeTokenList.size(); i++) { Token tokenToBeRemoved = removeTokenList.get(i); tokens.remove(tokenToBeRemoved); } } private int processStartPunctSymbol(List<Token> newTokenList, Token token, String tokenText) { int count = 0; for (int i = 0; i < tokenText.length(); i++) { char currentChar = tokenText.charAt(i); if (!isAlphabetLetterOrDigit(currentChar)) { Token t = new Token(token.getStartOffset() + i, token .getStartOffset() + i + 1); if (isPunctuation(currentChar)) { t.setType(Token.TYPE_PUNCT); } else { t.setType(Token.TYPE_SYMBOL); } newTokenList.add(t); count++; } else { // encountered a letter or digit, stop return count; } } return count; } private int processEndPunctSymbol(List<Token> newTokenList, Token token, String tokenText) { int count = 0; for (int i = tokenText.length() - 1; i >= 0; i--) { char currentChar = tokenText.charAt(i); if (!isAlphabetLetterOrDigit(currentChar)) { Token t = new Token(token.getStartOffset() + i, token .getStartOffset() + i + 1); if (isPunctuation(currentChar)) { t.setType(Token.TYPE_PUNCT); } else { t.setType(Token.TYPE_SYMBOL); } newTokenList.add(t); count++; } else { // encountered a letter or digit, stop return count; } } return count; } private int getFirstInsidePunctSymbol(String tokenText) { for (int i = 0; i < tokenText.length(); i++) { char currentChar = tokenText.charAt(i); if (currentChar == ',' && !isNumber(tokenText)) { return i; } if (currentChar == '.' && !isNumber(tokenText)) { return i; } if ((isAlphabetLetterOrDigit(currentChar) == false) && (currentChar != '.') && (currentChar != ',') && (currentChar != ':') && (currentChar != ';')) { return i; } } return -1; } /** * Finds punctuation/symbols located inside a token. If found, the token is * split into multiple Tokens. Note that the method is recursive. * * @param tokens * @param token * @param tokenText * @return */ private boolean findPunctSymbolInsideToken(List<Token> tokens, Token token, String tokenText) { int startOffset = token.getStartOffset(); int punctSymbolOffset = getFirstInsidePunctSymbol(tokenText); if (punctSymbolOffset != -1) { char c = tokenText.charAt(punctSymbolOffset); // logic for hypenation if (c == '-') { if ((iv_hyphMap != null) && iv_hyphMap.containsKey(tokenText.toLowerCase())) { int freq = ((Integer) iv_hyphMap.get(tokenText .toLowerCase())).intValue(); if (freq > iv_freqCutoff) { if (!tokens.contains(token)) { tokens.add(token); return true; } return false; } } } Token t = new Token(startOffset + punctSymbolOffset, startOffset + punctSymbolOffset + 1); if (isPunctuation(c)) { t.setType(Token.TYPE_PUNCT); } else { t.setType(Token.TYPE_SYMBOL); } tokens.add(t); if (startOffset != t.getStartOffset()) { Token leftToken = new Token(startOffset, t.getStartOffset()); tokens.add(leftToken); } Token rightToken = new Token(t.getEndOffset(), token.getEndOffset()); String rightTokenText = tokenText.substring(punctSymbolOffset + 1, tokenText.length()); // recurse return findPunctSymbolInsideToken(tokens, rightToken, rightTokenText); } else { if (!tokens.contains(token)) { tokens.add(token); return true; } return false; } } private boolean isPunctuation(char c) { if ((c == ';') || (c == ':') || (c == ',') || (c == '.') || (c == '(') || (c == ')') || (c == '[') || (c == ']') || (c == '{') || (c == '}') || (c == '<') || (c == '>') || (c == '\'') || (c == '"') || (c == '/') || (c == '\\') || (c == '-')) { return true; } else { return false; } } private boolean isAlphabetLetterOrDigit(char c) { if (isAlphabetLetter(c)) return true; if (isDigit(c)) return true; // otherwise return false; } public boolean isAlphabetLetter(char c) { int unicode = Character.getNumericValue(c); if ((unicode >= 10) && (unicode <= 35)) return true; else return false; } private boolean isDigit(char c) { int unicode = Character.getNumericValue(c); if ((unicode >= 0) && (unicode <= 9)) return true; else return false; } /** * Applies number rules to the given token. * * @return True if the token is a number, false otherwise. */ public static boolean isNumber(String tokenText) { final char decimalPoint = '.'; boolean foundDecimalPoint = false; int charsBeforeDecimal = 0; for (int i = tokenText.length() - 1; i >= 0; i--) { char currentChar = tokenText.charAt(i); if (Character.isDigit(currentChar) == false) { if ((currentChar == decimalPoint) && (foundDecimalPoint == false)) { foundDecimalPoint = true; charsBeforeDecimal = 0; continue; } else if (currentChar == ',') { // commas are valid only // every 3 digits if (charsBeforeDecimal % 3 == 0) { continue; } else { return false; } } // otherwise it's a letter or punct return false; } charsBeforeDecimal++; } return true; } /** * Given that the token text is a number, this method will determine if the * number is an integer or not. * * @param tokenText * @return */ private boolean isInteger(String tokenText) { if (tokenText.indexOf('.') != -1) { return false; } else { return true; } } /** * Applies capitalization rules to the given token. This should normally * only be used for tokens containing strictly text, but mixtures of * letters, numbers, and symbols are allowed too. * * @param token * @param tokenText */ private void applyCapitalizationRules(Token token, String tokenText) { // true = upper case, false = lower case boolean[] uppercaseMask = new boolean[tokenText.length()]; boolean isAllUppercase = true; boolean isAllLowercase = true; for (int i = 0; i < tokenText.length(); i++) { char currentChar = tokenText.charAt(i); uppercaseMask[i] = Character.isUpperCase(currentChar); if (uppercaseMask[i] == false) isAllUppercase = false; else isAllLowercase = false; } if (isAllLowercase) { token.setCaps(Token.CAPS_NONE); } else if (isAllUppercase) { token.setCaps(Token.CAPS_ALL); } else if (uppercaseMask[0] == true) { if (uppercaseMask.length == 1) { token.setCaps(Token.CAPS_FIRST_ONLY); return; } boolean isRestLowercase = true; for (int i = 1; i < uppercaseMask.length; i++) { if (uppercaseMask[i] == true) isRestLowercase = false; } if (isRestLowercase) { token.setCaps(Token.CAPS_FIRST_ONLY); } else { token.setCaps(Token.CAPS_MIXED); } } else { token.setCaps(Token.CAPS_MIXED); } return; } private void applyWordNumRules(Token token, String tokenText) { boolean[] digitMask = new boolean[tokenText.length()]; boolean isAllLetters = true; for (int i = 0; i < tokenText.length(); i++) { char currentChar = tokenText.charAt(i); digitMask[i] = Character.isDigit(currentChar); if (digitMask[i] == true) { isAllLetters = false; } } if (isAllLetters) { token.setNumPosition(Token.NUM_NONE); } else if (digitMask[0] == true) { token.setNumPosition(Token.NUM_FIRST); } else if (digitMask[tokenText.length() - 1]) { token.setNumPosition(Token.NUM_LAST); } else { token.setNumPosition(Token.NUM_MIDDLE); } return; } /** * Gets a list of tokens that mark end of a line. * * @param text * @return */ private List<Token> getEndOfLineTokens(String text) { final char crChar = '\r'; final char nlChar = '\n'; List<Token> eolTokens = new ArrayList<Token>(); for (int i = 0; i < text.length(); i++) { char currentChar = text.charAt(i); /** * Fixed: ID: 3307765 to handle windows CRLF \r\n new lines in Docs */ Token t = null; if (currentChar == nlChar) { t = new Token(i, i + 1); } else if (currentChar == crChar) { if ((i + 1) < text.length()) { char nextChar = text.charAt(i + 1); if (nextChar == nlChar) { t = new Token(i, i + 2); i++; } else { t = new Token(i, i + 1); } } else { t = new Token(i, i + 1); } } if (t != null) { t.setType(Token.TYPE_EOL); eolTokens.add(t); } } return eolTokens; } /** * Text is split based on whitespace into raw tokens. A raw token is defined * as a span of text with no identified type. * * @param text * @return */ private List<Token> getRawTokens(String text) { final char wsChar = ' '; final char tabChar = '\t'; final char newlineChar = '\n'; final char crChar = '\r'; boolean insideText = false; int startIndex = 0; int endIndex = 0; List<Token> rawTokens = new ArrayList<Token>(); for (int i = 0; i < text.length(); i++) { char currentChar = text.charAt(i); if ((currentChar != wsChar) && (currentChar != tabChar) && (currentChar != newlineChar) && (currentChar != crChar)) { if (insideText == false) { insideText = true; startIndex = i; } } else { if (insideText == true) { insideText = false; endIndex = i; Token t = new Token(startIndex, endIndex); rawTokens.add(t); } } } // capture last token, that may not have whitespace after it if (insideText) { insideText = false; endIndex = text.length(); Token t = new Token(startIndex, endIndex); rawTokens.add(t); } return rawTokens; } }
923d08c3a3a8d77b760670f440b61703d82f7a27
633
java
Java
src/de/gurkenlabs/litiengine/entities/CombatEntityListener.java
KvaGram/litiengine
9fab0c5a92649e1cc8b9026f0ed34f371647731d
[ "MIT" ]
null
null
null
src/de/gurkenlabs/litiengine/entities/CombatEntityListener.java
KvaGram/litiengine
9fab0c5a92649e1cc8b9026f0ed34f371647731d
[ "MIT" ]
null
null
null
src/de/gurkenlabs/litiengine/entities/CombatEntityListener.java
KvaGram/litiengine
9fab0c5a92649e1cc8b9026f0ed34f371647731d
[ "MIT" ]
null
null
null
28.772727
113
0.736177
1,000,141
package de.gurkenlabs.litiengine.entities; import java.util.EventListener; /** * This listener provides callbacks for when an <code>ICombatEntity</code> dies, was resurrected or is being hit. * * @see ICombatEntity#die() * @see ICombatEntity#resurrect() * @see ICombatEntity#hit(int) */ public interface CombatEntityListener extends CombatEntityHitListener, CombatEntityDeathListener, EventListener { /** * This method is called whenever a <code>ICombatEntity</code> was resurrected. * * @param entity * The combat entity that was resurrected. */ public void resurrect(ICombatEntity entity); }
923d09a146eaf9ece931538b668ce1b786ba262b
3,263
java
Java
src/com/thomasci/tetros/entity/EntityDropPiece.java
ChrisIThomas/Tetros
342f07488a8a1b2bd4fdfcd6dc4c997983c6ad02
[ "MIT" ]
null
null
null
src/com/thomasci/tetros/entity/EntityDropPiece.java
ChrisIThomas/Tetros
342f07488a8a1b2bd4fdfcd6dc4c997983c6ad02
[ "MIT" ]
null
null
null
src/com/thomasci/tetros/entity/EntityDropPiece.java
ChrisIThomas/Tetros
342f07488a8a1b2bd4fdfcd6dc4c997983c6ad02
[ "MIT" ]
null
null
null
23.992647
116
0.539994
1,000,142
package com.thomasci.tetros.entity; import java.util.ArrayList; import com.thomasci.tetros.Controller; import com.thomasci.tetros.screen.GameSounds; import com.thomasci.tetros.tile.Tile; import com.thomasci.tetros.world.World; public class EntityDropPiece extends Entity implements Controller { private final Tile tile; public EntityDropPiece(World world, float x, float y, Tile tile) { super(world, x, y); this.tile = tile; } @Override public void tick(float dt) { if (this.onGround) { if (Math.abs(x) % 1 <= 0.5f) move(-x % 1, 0); else move(x % 1, 0); ArrayList<Entity> ents = world.getAllEntitiesNear(x, y, 0.5f, Entity.class, this); for (Entity e: ents) { e.kill(); } onDrop(); world.getState().setController(world.getPlayer()); kill(); } else { Tile t; if (bounciness < 0) bounciness = -bounciness; float oldy = y; boolean wasOnGround = onGround; if (onGround) { vx *= 0.75f; } if (vx <= 0.01f && vx >= -0.01f) vx = 0; if (vy <= 0.01f && vy >= -0.01f) vy = 0; vy -= 19.6f * dt; if (vx > 23) vx = 23; else if (vx < -23) vx = -23; if (vy > 23) vy = 23; else if (vy < -23) vy = -23; //move out of walls move(vx * dt, 0); int height = this.height + (y - ((int) y) != 0 ? 1 : 0); if (vx < 0) { for (int i = 0; i < height; i++) { t = world.getTileAt((int) x, (int) y + i); if (!t.isAir() || t.shouldDropOn()) { x = ((int) x) + 1; vx = 0; } } } else if (vx > 0) { for (int i = 0; i < height; i++) { t = world.getTileAt((int) x + this.width, (int) y + i); if (!t.isAir() || t.shouldDropOn()) { x = (int) x; vx = 0; } } } //move out of ground / ceiling move(0, vy * dt); if (oldy != y) onGround = false; int width = this.width + (x - ((int) x) != 0 ? 1 : 0); if (vy > 0) { for (int i = 0; i < width; i++) { t = world.getTileAt((int) x + i, (int) y + this.height); if (!t.isAir() || t.shouldDropOn()) { y = ((int) y); vy *= -bounciness * 0.8f; } } } else if (vy < 0) { //falling for (int i = 0; i < width; i++) { t = world.getTileAt((int) x + i, (int) y); if (!t.isAir() || t.shouldDropOn()) { y = ((int) y) + 1; vy *= -bounciness * 0.8f; onGround = true; if (vy <= 0.98f) vy = 0; } } } //make sure if the entity tries to move up but is stopped by a ceiling they are still considered "on the ground". if (oldy == y && wasOnGround) onGround = true; vy = -5.0f; vx = 0; } } protected void onDrop() { world.setTileAt((int) x, (int) y, tile); GameSounds.getSound("place").play(); } public Tile getTile() { return tile; } @Override public void keyPress(int key) {} @Override public void keyRelease(int key) {} @Override public void keyDown(int key, long time) { if (key == 37) { //Left if (!this.onGround) this.push(-5, 0); } else if (key == 39) { //Right if (!this.onGround) this.push(5, 0); } else if (key == 38) { //Up this.vy = -1.75f; } else if (key == 40) { //Down this.vy = -10.0f; } } @Override public float getViewX() { return getX(); } @Override public float getViewY() { return getY(); } }
923d09a21718111ecdc3f7189fc83f75871fe31e
1,105
java
Java
src/main/java/com/gregor0410/ptlib/rng/AccessibleRandom.java
Gregor0410/PTLib
906f01fdb7650d1107346f5d4b728a54513d4cfb
[ "MIT" ]
null
null
null
src/main/java/com/gregor0410/ptlib/rng/AccessibleRandom.java
Gregor0410/PTLib
906f01fdb7650d1107346f5d4b728a54513d4cfb
[ "MIT" ]
null
null
null
src/main/java/com/gregor0410/ptlib/rng/AccessibleRandom.java
Gregor0410/PTLib
906f01fdb7650d1107346f5d4b728a54513d4cfb
[ "MIT" ]
null
null
null
25.697674
62
0.624434
1,000,143
package com.gregor0410.ptlib.rng; import java.util.Random; import java.util.concurrent.atomic.AtomicLong; //random class with accessible seed public class AccessibleRandom extends Random { public final AtomicLong seed; private static final long multiplier = 0x5DEECE66DL; private static final long addend = 0xBL; private static final long mask = (1L << 48) - 1; public AccessibleRandom(){ super(); this.seed = new AtomicLong(new Random().nextLong()); } public AccessibleRandom(long seed){ super(seed); this.seed = new AtomicLong(seed); } protected int next(int bits) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) & mask; } while (!seed.compareAndSet(oldseed, nextseed)); return (int)(nextseed >>> (48 - bits)); } public long getSeed(){ return this.seed.get(); } public static long initialScramble(long seed) { return (seed ^ multiplier) & mask; } }
923d09b39104ba6a2c37f2a15eb36c4e1eba44c2
309
java
Java
study-notes/j2ee-collection/architecture/02-分布式事务/xa-trans-demo/src/main/java/com/sq/demo/xatransdemo/mapper/gonghang/GhAccountMapper.java
coderZsq/coderZsq.practice.server
f789ee4b43b4a8dee5d8872e86c04ca2fe139b68
[ "MIT" ]
1
2020-06-14T12:43:47.000Z
2020-06-14T12:43:47.000Z
study-notes/j2ee-collection/architecture/02-分布式事务/xa-trans-demo/src/main/java/com/sq/demo/xatransdemo/mapper/gonghang/GhAccountMapper.java
coderZsq/coderZsq.practice.server
f789ee4b43b4a8dee5d8872e86c04ca2fe139b68
[ "MIT" ]
88
2020-03-03T15:16:28.000Z
2022-01-04T16:44:37.000Z
study-notes/j2ee-collection/architecture/02-分布式事务/xa-trans-demo/src/main/java/com/sq/demo/xatransdemo/mapper/gonghang/GhAccountMapper.java
coderZsq/coderZsq.practice.server
f789ee4b43b4a8dee5d8872e86c04ca2fe139b68
[ "MIT" ]
1
2021-09-08T06:34:11.000Z
2021-09-08T06:34:11.000Z
28.090909
78
0.763754
1,000,144
package com.sq.demo.xatransdemo.mapper.gonghang; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Update; @Mapper public interface GhAccountMapper { @Update("UPDATE t_account SET amount = amount + #{amount} WHERE id=#{id}") void tranIn(Integer id,Integer amount); }
923d0a0d7c16bd429521693323c9ee0c7ef711be
937
java
Java
twwade-common/twwade-common-core/src/main/java/com/wadex/common/core/constant/ScheduleConstants.java
tengyz/wade-cloud
be374ba709e2f2c7672a66f866fc4776b774978d
[ "MIT" ]
3
2021-04-23T03:52:17.000Z
2022-02-15T07:49:59.000Z
twwade-common/twwade-common-core/src/main/java/com/wadex/common/core/constant/ScheduleConstants.java
tengyz/wade-cloud
be374ba709e2f2c7672a66f866fc4776b774978d
[ "MIT" ]
null
null
null
twwade-common/twwade-common-core/src/main/java/com/wadex/common/core/constant/ScheduleConstants.java
tengyz/wade-cloud
be374ba709e2f2c7672a66f866fc4776b774978d
[ "MIT" ]
1
2021-04-23T02:17:04.000Z
2021-04-23T02:17:04.000Z
18.372549
67
0.545358
1,000,145
package com.wadex.common.core.constant; /** * 任务调度通用常量 * * @author twwade */ public class ScheduleConstants { public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME"; /** 执行目标key */ public static final String TASK_PROPERTIES = "TASK_PROPERTIES"; /** 默认 */ public static final String MISFIRE_DEFAULT = "0"; /** 立即触发执行 */ public static final String MISFIRE_IGNORE_MISFIRES = "1"; /** 触发一次执行 */ public static final String MISFIRE_FIRE_AND_PROCEED = "2"; /** 不触发立即执行 */ public static final String MISFIRE_DO_NOTHING = "3"; public enum Status { /** * 正常 */ NORMAL("0"), /** * 暂停 */ PAUSE("1"); private String value; private Status(String value) { this.value = value; } public String getValue() { return value; } } }
923d0ac2f1471fa7dca9f769e7c5bb5a9089e685
64
java
Java
crop/src/main/java/me/ningsk/crop/image/JRImageCropper.java
chongbo2013/MediaPickerInstagram
df3af109a648ab85df8444b3a56cc7cf14f77e84
[ "Apache-2.0" ]
null
null
null
crop/src/main/java/me/ningsk/crop/image/JRImageCropper.java
chongbo2013/MediaPickerInstagram
df3af109a648ab85df8444b3a56cc7cf14f77e84
[ "Apache-2.0" ]
null
null
null
crop/src/main/java/me/ningsk/crop/image/JRImageCropper.java
chongbo2013/MediaPickerInstagram
df3af109a648ab85df8444b3a56cc7cf14f77e84
[ "Apache-2.0" ]
1
2021-07-23T12:51:28.000Z
2021-07-23T12:51:28.000Z
10.666667
29
0.765625
1,000,146
package me.ningsk.crop.image; public class JRImageCropper { }
923d0ae1e9a55da718b7342d3ac94a88e2fec268
1,733
java
Java
unimall-data/src/main/java/com/iotechn/unimall/data/domain/CouponDO.java
iotechn/unimall-App-H5
75b5cf3350ee3ada9a9666166edae6a2e4f71382
[ "Apache-2.0" ]
41
2019-11-20T08:56:20.000Z
2020-01-07T15:25:41.000Z
unimall-data/src/main/java/com/iotechn/unimall/data/domain/CouponDO.java
iotechn/unimall-App-H5
75b5cf3350ee3ada9a9666166edae6a2e4f71382
[ "Apache-2.0" ]
null
null
null
unimall-data/src/main/java/com/iotechn/unimall/data/domain/CouponDO.java
iotechn/unimall-App-H5
75b5cf3350ee3ada9a9666166edae6a2e4f71382
[ "Apache-2.0" ]
20
2019-11-19T07:33:36.000Z
2020-01-07T06:47:22.000Z
23.106667
59
0.69071
1,000,147
package com.iotechn.unimall.data.domain; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.dobbinsoft.fw.core.annotation.doc.ApiEntity; import com.dobbinsoft.fw.core.annotation.doc.ApiField; import com.dobbinsoft.fw.support.domain.SuperDO; import com.iotechn.unimall.data.enums.CouponType; import com.iotechn.unimall.data.enums.StatusType; import lombok.Data; import java.util.Date; /** * Created by rize on 2019/7/4. */ @Data @ApiEntity(description = "优惠券领域模型") @TableName("unimall_coupon") public class CouponDO extends SuperDO { @ApiField(description = "优惠券标题") private String title; @ApiField(description = "类型", enums = CouponType.class) private Integer type; /** * 是否是vip专享 * 0:不是,1:是 */ @ApiField(description = "是否是vip专享") private Integer isVip; @ApiField(description = "优惠券描述") private String description; @ApiField(description = "总共发的数量") private Integer total; @ApiField(description = "剩余的数量") private Integer surplus; @ApiField(description = "每个用户限制领取数量") @TableField("`limit`") private Integer limit; @ApiField(description = "折扣") private Integer discount; @ApiField(description = "最低使用价格,单位分") @TableField("`min`") private Integer min; /** * 0:下架 * 1: 正常 */ @ApiField(description = "状态", enums = StatusType.class) private Integer status; @ApiField(description = "指定仅这个类目可用") private Long categoryId; @ApiField(description = "有效期多少天") private Integer days; @ApiField(description = "可领取开始时间") private Date gmtStart; @ApiField(description = "可领取结束时间") private Date gmtEnd; }
923d0bf59901aa2a993ad62fd1e69934a1debcb6
842
java
Java
src/nodes/MakeNode.java
ChadCoviel/SLogo
cfb8981d3de27c9221f0ee40d2eaafbd0506b5fb
[ "MIT" ]
null
null
null
src/nodes/MakeNode.java
ChadCoviel/SLogo
cfb8981d3de27c9221f0ee40d2eaafbd0506b5fb
[ "MIT" ]
null
null
null
src/nodes/MakeNode.java
ChadCoviel/SLogo
cfb8981d3de27c9221f0ee40d2eaafbd0506b5fb
[ "MIT" ]
null
null
null
25.515152
95
0.654394
1,000,148
package nodes; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.List; import turtle.Turtle; public class MakeNode extends AbstractNode { public MakeNode (List<Turtle> turtles) { super(turtles); } @Override public double evaluate () throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException, IOException { return this.getLeftNode().evaluate(); } @Override public boolean allowsTwoChildren () { return false; } @Override public boolean allowsMoreThanTwoChildren () { return false; } }
923d0c3b7a90a1c5a5b8accd28180d7cf2b8b93e
51,785
java
Java
core/src/main/java/org/jruby/internal/runtime/methods/JavaMethod.java
lukefx/jruby
be5e7f19d20edd114e55f7a78a0e3d2e3e55417e
[ "Ruby", "Apache-2.0" ]
47
2015-11-05T15:32:43.000Z
2022-02-04T05:39:19.000Z
core/src/main/java/org/jruby/internal/runtime/methods/JavaMethod.java
lukefx/jruby
be5e7f19d20edd114e55f7a78a0e3d2e3e55417e
[ "Ruby", "Apache-2.0" ]
2
2015-12-05T17:22:58.000Z
2015-12-15T13:19:19.000Z
core/src/main/java/org/jruby/internal/runtime/methods/JavaMethod.java
lukefx/jruby
be5e7f19d20edd114e55f7a78a0e3d2e3e55417e
[ "Ruby", "Apache-2.0" ]
3
2015-12-18T09:37:31.000Z
2018-03-21T00:06:14.000Z
46.779584
180
0.694506
1,000,149
/***** BEGIN LICENSE BLOCK ***** * Version: EPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * License Version 1.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.eclipse.org/legal/epl-v10.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.internal.runtime.methods; import org.jruby.RubyModule; import org.jruby.parser.StaticScope; import org.jruby.runtime.Arity; import org.jruby.runtime.Block; import org.jruby.runtime.RubyEvent; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; /** */ public abstract class JavaMethod extends DynamicMethod implements Cloneable, MethodArgs2 { protected Arity arity = Arity.OPTIONAL; private String javaName; private boolean isSingleton; protected StaticScope staticScope; private String parameterDesc; private String[] parameterList; private CallConfiguration callerRequirement = CallConfiguration.FrameNoneScopeNone; private static String[] ONE_REQ = new String[] { "q" }; private static String[] TWO_REQ = new String[] { "q", "q" }; private static String[] THREE_REQ = new String[] { "q", "q", "q" }; public static final Class[][] METHODS = { {JavaMethodZero.class, JavaMethodZeroOrOne.class, JavaMethodZeroOrOneOrTwo.class, JavaMethodZeroOrOneOrTwoOrThree.class}, {null, JavaMethodOne.class, JavaMethodOneOrTwo.class, JavaMethodOneOrTwoOrThree.class}, {null, null, JavaMethodTwo.class, JavaMethodTwoOrThree.class}, {null, null, null, JavaMethodThree.class}, }; public static final Class[][] REST_METHODS = { {JavaMethodZeroOrN.class, JavaMethodZeroOrOneOrN.class, JavaMethodZeroOrOneOrTwoOrN.class, JavaMethodZeroOrOneOrTwoOrThreeOrN.class}, {null, JavaMethodOneOrN.class, JavaMethodOneOrTwoOrN.class, JavaMethodOneOrTwoOrThreeOrN.class}, {null, null, JavaMethodTwoOrN.class, JavaMethodTwoOrThreeOrN.class}, {null, null, null, JavaMethodThreeOrN.class}, }; public static final Class[][] BLOCK_METHODS = { {JavaMethodZeroBlock.class, JavaMethodZeroOrOneBlock.class, JavaMethodZeroOrOneOrTwoBlock.class, JavaMethodZeroOrOneOrTwoOrThreeBlock.class}, {null, JavaMethodOneBlock.class, JavaMethodOneOrTwoBlock.class, JavaMethodOneOrTwoOrThreeBlock.class}, {null, null, JavaMethodTwoBlock.class, JavaMethodTwoOrThreeBlock.class}, {null, null, null, JavaMethodThreeBlock.class}, }; public static final Class[][] BLOCK_REST_METHODS = { {JavaMethodZeroOrNBlock.class, JavaMethodZeroOrOneOrNBlock.class, JavaMethodZeroOrOneOrTwoOrNBlock.class, JavaMethodZeroOrOneOrTwoOrThreeOrNBlock.class}, {null, JavaMethodOneOrNBlock.class, JavaMethodOneOrTwoOrNBlock.class, JavaMethodOneOrTwoOrThreeOrNBlock.class}, {null, null, JavaMethodTwoOrNBlock.class, JavaMethodTwoOrThreeOrNBlock.class}, {null, null, null, JavaMethodThreeOrNBlock.class}, }; public JavaMethod(RubyModule implementationClass, Visibility visibility) { this(implementationClass, visibility, CallConfiguration.FrameFullScopeNone); } public JavaMethod(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public JavaMethod(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig, String name) { super(implementationClass, visibility, callConfig, name); } protected JavaMethod() {} public void init(RubyModule implementationClass, Arity arity, Visibility visibility, StaticScope staticScope, CallConfiguration callConfig) { this.staticScope = staticScope; this.arity = arity; super.init(implementationClass, visibility, callConfig); } public DynamicMethod dup() { try { return (JavaMethod) super.clone(); } catch (CloneNotSupportedException ex) { throw new AssertionError(ex); } } protected final void preFrameAndScope(ThreadContext context, IRubyObject self, String name, Block block) { context.preMethodFrameAndScope(implementationClass, name, self, block, staticScope); } protected final void preFrameAndDummyScope(ThreadContext context, IRubyObject self, String name, Block block) { context.preMethodFrameAndDummyScope(implementationClass, name, self, block, staticScope); } protected final void preFrameOnly(ThreadContext context, IRubyObject self, String name, Block block) { context.preMethodFrameOnly(implementationClass, name, self, block); } protected final void preScopeOnly(ThreadContext context) { context.preMethodScopeOnly(staticScope); } protected final void preNoFrameDummyScope(ThreadContext context) { context.preMethodNoFrameAndDummyScope(staticScope); } protected final void preBacktraceOnly(ThreadContext context, String name) { context.preMethodBacktraceOnly(name); } protected final void preBacktraceDummyScope(ThreadContext context, String name) { context.preMethodBacktraceDummyScope(name, staticScope); } protected final void preBacktraceAndScope(ThreadContext context, String name) { context.preMethodBacktraceAndScope(name, staticScope); } protected final void preNoop() {} protected final static void postFrameAndScope(ThreadContext context) { context.postMethodFrameAndScope(); } protected final static void postFrameOnly(ThreadContext context) { context.postMethodFrameOnly(); } protected final static void postScopeOnly(ThreadContext context) { context.postMethodScopeOnly(); } protected final static void postNoFrameDummyScope(ThreadContext context) { context.postMethodScopeOnly(); } protected final static void postBacktraceOnly(ThreadContext context) { context.postMethodBacktraceOnly(); } protected final static void postBacktraceDummyScope(ThreadContext context) { context.postMethodBacktraceDummyScope(); } protected final static void postBacktraceAndScope(ThreadContext context) { context.postMethodBacktraceAndScope(); } protected final static void postNoop(ThreadContext context) {} protected final void callTrace(ThreadContext context, boolean enabled, String name) { if (enabled) context.trace(RubyEvent.C_CALL, name, getImplementationClass()); } protected final void returnTrace(ThreadContext context, boolean enabled, String name) { if (enabled) context.trace(RubyEvent.C_RETURN, name, getImplementationClass()); } protected final void callTraceCompiled(ThreadContext context, boolean enabled, String name, String file, int line) { if (enabled) context.trace(RubyEvent.CALL, name, getImplementationClass(), file, line); } protected final void returnTraceCompiled(ThreadContext context, boolean enabled, String name) { if (enabled) context.trace(RubyEvent.RETURN, name, getImplementationClass()); } public void setArity(Arity arity) { this.arity = arity; } @Override public Arity getArity() { return arity; } public void setJavaName(String javaName) { this.javaName = javaName; } public String getJavaName() { return javaName; } public void setSingleton(boolean isSingleton) { this.isSingleton = isSingleton; } public boolean isSingleton() { return isSingleton; } @Override public boolean isNative() { return true; } public StaticScope getStaticScope() { return staticScope; } public void setParameterDesc(String parameterDesc) { this.parameterDesc = parameterDesc; this.parameterList = null; } public void setParameterList(String[] parameterList) { this.parameterDesc = null; this.parameterList = parameterList; } public String[] getParameterList() { if (parameterList == null) { if (parameterDesc != null && parameterDesc.length() > 0) { parameterList = parameterDesc.split(";"); } else { parameterList = new String[0]; } } return parameterList; } /** * Return a CallConfiguration representing what *callers* to this method must prepare (scope/frame). */ public CallConfiguration getCallerRequirement() { return callerRequirement; } /** * Set a CallConfiguration indicating what callers to this method must prepare (scope/frame). */ public void setCallerRequirement(CallConfiguration callerRequirement) { this.callerRequirement = callerRequirement; } protected static IRubyObject raiseArgumentError(JavaMethod method, ThreadContext context, String name, int given, int min, int max) { Arity.raiseArgumentError(context.runtime, name, given, min, max); throw new AssertionError("expected to throw ArgumentError"); // never reached } protected static void checkArgumentCount(JavaMethod method, ThreadContext context, String name, IRubyObject[] args, int num) { if (args.length != num) raiseArgumentError(method, context, name, args.length, num, num); } // promise to implement N with block public static abstract class JavaMethodNBlock extends JavaMethod { public JavaMethodNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public JavaMethodNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig, String name) { super(implementationClass, visibility, callConfig, name); } } // promise to implement zero to N with block public static abstract class JavaMethodZeroOrNBlock extends JavaMethodNBlock { public JavaMethodZeroOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name) { return call(context, self, clazz, name, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, Block block); } public static abstract class JavaMethodZeroOrOneOrNBlock extends JavaMethodZeroOrNBlock { public JavaMethodZeroOrOneOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0) { return call(context, self, clazz, name, arg0, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg, Block block); } public static abstract class JavaMethodZeroOrOneOrTwoOrNBlock extends JavaMethodZeroOrOneOrNBlock { public JavaMethodZeroOrOneOrTwoOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwoOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1) { return call(context, self, clazz, name, arg0, arg1, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block); } public static abstract class JavaMethodZeroOrOneOrTwoOrThreeOrNBlock extends JavaMethodZeroOrOneOrTwoOrNBlock { public JavaMethodZeroOrOneOrTwoOrThreeOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwoOrThreeOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { return call(context, self, clazz, name, arg0, arg1, arg2, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block); } // promise to implement one to N with block public static abstract class JavaMethodOneOrNBlock extends JavaMethodNBlock { public JavaMethodOneOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0) { return call(context, self, clazz, name, arg0, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg, Block block); } public static abstract class JavaMethodOneOrTwoOrNBlock extends JavaMethodOneOrNBlock { public JavaMethodOneOrTwoOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwoOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1) { return call(context, self, clazz, name, arg0, arg1, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block); } public static abstract class JavaMethodOneOrTwoOrThreeOrNBlock extends JavaMethodOneOrTwoOrNBlock { public JavaMethodOneOrTwoOrThreeOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwoOrThreeOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { return call(context, self, clazz, name, arg0, arg1, arg2, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block); } // promise to implement two to N with block public static abstract class JavaMethodTwoOrNBlock extends JavaMethodNBlock { public JavaMethodTwoOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodTwoOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1) { return call(context, self, clazz, name, arg0, arg1, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block); } public static abstract class JavaMethodTwoOrThreeOrNBlock extends JavaMethodTwoOrNBlock { public JavaMethodTwoOrThreeOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodTwoOrThreeOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { return call(context, self, clazz, name, arg0, arg1, arg2, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3, Block block); } // promise to implement three to N with block public static abstract class JavaMethodThreeOrNBlock extends JavaMethodNBlock { public JavaMethodThreeOrNBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodThreeOrNBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2) { return call(context, self, clazz, name, arg0, arg1, arg2, Block.NULL_BLOCK); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg1, IRubyObject arg2, IRubyObject arg3, Block block); } // promise to implement zero to three with block public static abstract class JavaMethodZeroBlock extends JavaMethodZeroOrNBlock { public JavaMethodZeroBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { if (args.length != 0) return raiseArgumentError(this, context, name, args.length, 0, 0); return call(context, self, clazz, name, block); } } public static abstract class JavaMethodZeroOrOneBlock extends JavaMethodZeroOrOneOrNBlock { public JavaMethodZeroOrOneBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { switch (args.length) { case 0: return call(context, self, clazz, name, block); case 1: return call(context, self, clazz, name, args[0], block); default: return raiseArgumentError(this, context, name, args.length, 0, 1); } } } public static abstract class JavaMethodZeroOrOneOrTwoBlock extends JavaMethodZeroOrOneOrTwoOrNBlock { public JavaMethodZeroOrOneOrTwoBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwoBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { switch (args.length) { case 0: return call(context, self, clazz, name, block); case 1: return call(context, self, clazz, name, args[0], block); case 2: return call(context, self, clazz, name, args[0], args[1], block); default: return raiseArgumentError(this, context, name, args.length, 0, 2); } } } public static abstract class JavaMethodZeroOrOneOrTwoOrThreeBlock extends JavaMethodZeroOrOneOrTwoOrThreeOrNBlock { public JavaMethodZeroOrOneOrTwoOrThreeBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwoOrThreeBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { switch (args.length) { case 0: return call(context, self, clazz, name, block); case 1: return call(context, self, clazz, name, args[0], block); case 2: return call(context, self, clazz, name, args[0], args[1], block); case 3: return call(context, self, clazz, name, args[0], args[1], args[2], block); default: return raiseArgumentError(this, context, name, args.length, 0, 3); } } } // promise to implement one to three with block public static abstract class JavaMethodOneBlock extends JavaMethodOneOrNBlock { public JavaMethodOneBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { if (args.length != 1) return raiseArgumentError(this, context, name, args.length, 1, 1); return call(context, self, clazz, name, args[0], block); } @Override public Arity getArity() { return Arity.ONE_ARGUMENT; } } public static abstract class JavaMethodOneOrTwoBlock extends JavaMethodOneOrTwoOrNBlock { public JavaMethodOneOrTwoBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwoBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { switch (args.length) { case 1: return call(context, self, clazz, name, args[0], block); case 2: return call(context, self, clazz, name, args[0], args[1], block); default: return raiseArgumentError(this, context, name, args.length, 1, 2); } } } public static abstract class JavaMethodOneOrTwoOrThreeBlock extends JavaMethodOneOrTwoOrThreeOrNBlock { public JavaMethodOneOrTwoOrThreeBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwoOrThreeBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { switch (args.length) { case 1: return call(context, self, clazz, name, args[0], block); case 2: return call(context, self, clazz, name, args[0], args[1], block); case 3: return call(context, self, clazz, name, args[0], args[1], args[2], block); default: return raiseArgumentError(this, context, name, args.length, 1, 3); } } } // promise to implement two to three with block public static abstract class JavaMethodTwoBlock extends JavaMethodTwoOrNBlock { public JavaMethodTwoBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodTwoBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { if (args.length != 2) return raiseArgumentError(this, context, name, args.length, 2, 2); return call(context, self, clazz, name, args[0], args[1], block); } } public static abstract class JavaMethodTwoOrThreeBlock extends JavaMethodTwoOrThreeOrNBlock { public JavaMethodTwoOrThreeBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodTwoOrThreeBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { switch (args.length) { case 2: return call(context, self, clazz, name, args[0], args[1], block); case 3: return call(context, self, clazz, name, args[0], args[1], args[2], block); default: return raiseArgumentError(this, context, name, args.length, 2, 3); } } } // promise to implement three with block public static abstract class JavaMethodThreeBlock extends JavaMethodThreeOrNBlock { public JavaMethodThreeBlock(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodThreeBlock(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { if (args.length != 3) return raiseArgumentError(this, context, name, args.length, 3, 3); return call(context, self, clazz, name, args[0], args[1], args[2], block); } } // promise to implement N public static abstract class JavaMethodN extends JavaMethodNBlock { public JavaMethodN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public JavaMethodN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig, String name) { super(implementationClass, visibility, callConfig, name); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args); // Normally we could leave these to fall back on the superclass, but // since it dispatches through the [] version below, which may // dispatch through the []+block version, we can save it a couple hops // by overriding these here. @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, Block block) { return call(context, self, clazz, name, IRubyObject.NULL_ARRAY); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, Block block) { return call(context, self, clazz, name, new IRubyObject[] {arg0}); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block) { return call(context, self, clazz, name, new IRubyObject[] {arg0, arg1}); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) { return call(context, self, clazz, name, new IRubyObject[] {arg0, arg1, arg2}); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args, Block block) { return call(context, self, clazz, name, args); } } // promise to implement zero to N public static abstract class JavaMethodZeroOrN extends JavaMethodN { public JavaMethodZeroOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public JavaMethodZeroOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig, String name) { super(implementationClass, visibility, callConfig, name); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, Block block) { return call(context, self, clazz, name); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name); } public static abstract class JavaMethodZeroOrOneOrN extends JavaMethodZeroOrN { public JavaMethodZeroOrOneOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, Block block) { return call(context, self, clazz, name, arg0); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg); } public static abstract class JavaMethodZeroOrOneOrTwoOrN extends JavaMethodZeroOrOneOrN { public JavaMethodZeroOrOneOrTwoOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwoOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block) { return call(context, self, clazz, name, arg0, arg1); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1); } public static abstract class JavaMethodZeroOrOneOrTwoOrThreeOrN extends JavaMethodZeroOrOneOrTwoOrN { public JavaMethodZeroOrOneOrTwoOrThreeOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwoOrThreeOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) { return call(context, self, clazz, name, arg0, arg1, arg2); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2); } // promise to implement one to N public static abstract class JavaMethodOneOrN extends JavaMethodN { public JavaMethodOneOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public JavaMethodOneOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig, String name) { super(implementationClass, visibility, callConfig, name); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, Block block) { return call(context, self, clazz, name, arg0); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0); } public static abstract class JavaMethodOneOrTwoOrN extends JavaMethodOneOrN { public JavaMethodOneOrTwoOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwoOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block) { return call(context, self, clazz, name, arg0, arg1); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1); } public static abstract class JavaMethodOneOrTwoOrThreeOrN extends JavaMethodOneOrTwoOrN { public JavaMethodOneOrTwoOrThreeOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwoOrThreeOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) { return call(context, self, clazz, name, arg0, arg1, arg2); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2); } // promise to implement two to N public static abstract class JavaMethodTwoOrN extends JavaMethodN { public JavaMethodTwoOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodTwoOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, Block block) { return call(context, self, clazz, name, arg0, arg1); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1); } public static abstract class JavaMethodTwoOrThreeOrN extends JavaMethodTwoOrN { public JavaMethodTwoOrThreeOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodTwoOrThreeOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) { return call(context, self, clazz, name, arg0, arg1, arg2); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2); } // promise to implement three to N public static abstract class JavaMethodThreeOrN extends JavaMethodN { public JavaMethodThreeOrN(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodThreeOrN(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2, Block block) { return call(context, self, clazz, name, arg0, arg1, arg2); } @Override public abstract IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject arg0, IRubyObject arg1, IRubyObject arg2); } // promise to implement zero to three public static abstract class JavaMethodZero extends JavaMethodZeroOrN { public JavaMethodZero(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZero(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public JavaMethodZero(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig, String name) { super(implementationClass, visibility, callConfig, name); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { if (args.length != 0) return raiseArgumentError(this, context, name, args.length, 0, 0); return call(context, self, clazz, name); } @Override public Arity getArity() { return Arity.NO_ARGUMENTS; } } public static abstract class JavaMethodZeroOrOne extends JavaMethodZeroOrOneOrN { public JavaMethodZeroOrOne(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOne(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { switch (args.length) { case 0: return call(context, self, clazz, name); case 1: return call(context, self, clazz, name, args[0]); default: return raiseArgumentError(this, context, name, args.length, 0, 1); } } } public static abstract class JavaMethodZeroOrOneOrTwo extends JavaMethodZeroOrOneOrTwoOrN { public JavaMethodZeroOrOneOrTwo(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwo(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } @Override public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { switch (args.length) { case 0: return call(context, self, clazz, name); case 1: return call(context, self, clazz, name, args[0]); case 2: return call(context, self, clazz, name, args[0], args[1]); default: return raiseArgumentError(this, context, name, args.length, 0, 2); } } } public static abstract class JavaMethodZeroOrOneOrTwoOrThree extends JavaMethodZeroOrOneOrTwoOrThreeOrN { public JavaMethodZeroOrOneOrTwoOrThree(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodZeroOrOneOrTwoOrThree(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { switch (args.length) { case 0: return call(context, self, clazz, name); case 1: return call(context, self, clazz, name, args[0]); case 2: return call(context, self, clazz, name, args[0], args[1]); case 3: return call(context, self, clazz, name, args[0], args[1], args[2]); default: return raiseArgumentError(this, context, name, args.length, 0, 3); } } } // promise to implement one to three public static abstract class JavaMethodOne extends JavaMethodOneOrN { public JavaMethodOne(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); setParameterList(ONE_REQ); } public JavaMethodOne(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); setParameterList(ONE_REQ); } public JavaMethodOne(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig, String name) { super(implementationClass, visibility, callConfig, name); setParameterList(ONE_REQ); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { if (args.length != 1) return raiseArgumentError(this, context, name, args.length, 1, 1); return call(context, self, clazz, name, args[0]); } @Override public Arity getArity() { return Arity.ONE_ARGUMENT; } } public static abstract class JavaMethodOneOrTwo extends JavaMethodOneOrTwoOrN { public JavaMethodOneOrTwo(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwo(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { switch (args.length) { case 1: return call(context, self, clazz, name, args[0]); case 2: return call(context, self, clazz, name, args[0], args[1]); default: return raiseArgumentError(this, context, name, args.length, 1, 2); } } } public static abstract class JavaMethodOneOrTwoOrThree extends JavaMethodOneOrTwoOrThreeOrN { public JavaMethodOneOrTwoOrThree(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodOneOrTwoOrThree(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { switch (args.length) { case 1: return call(context, self, clazz, name, args[0]); case 2: return call(context, self, clazz, name, args[0], args[1]); case 3: return call(context, self, clazz, name, args[0], args[1], args[2]); default: return raiseArgumentError(this, context, name, args.length, 1, 3); } } } // promise to implement two to three public static abstract class JavaMethodTwo extends JavaMethodTwoOrN { public JavaMethodTwo(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); setParameterList(TWO_REQ); } public JavaMethodTwo(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); setParameterList(TWO_REQ); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { if (args.length != 2) return raiseArgumentError(this, context, name, args.length, 2, 2); return call(context, self, clazz, name, args[0], args[1]); } @Override public Arity getArity() { return Arity.TWO_ARGUMENTS; } } public static abstract class JavaMethodTwoOrThree extends JavaMethodTwoOrThreeOrN { public JavaMethodTwoOrThree(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); } public JavaMethodTwoOrThree(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { switch (args.length) { case 2: return call(context, self, clazz, name, args[0], args[1]); case 3: return call(context, self, clazz, name, args[0], args[1], args[2]); default: return raiseArgumentError(this, context, name, args.length, 2, 3); } } } // promise to implement three public static abstract class JavaMethodThree extends JavaMethodThreeOrN { public JavaMethodThree(RubyModule implementationClass, Visibility visibility) { super(implementationClass, visibility); setParameterList(THREE_REQ); } public JavaMethodThree(RubyModule implementationClass, Visibility visibility, CallConfiguration callConfig) { super(implementationClass, visibility, callConfig); setParameterList(THREE_REQ); } public IRubyObject call(ThreadContext context, IRubyObject self, RubyModule clazz, String name, IRubyObject[] args) { if (args.length != 3) return raiseArgumentError(this, context, name, args.length, 3, 3); return call(context, self, clazz, name, args[0], args[1], args[2]); } @Override public Arity getArity() { return Arity.THREE_ARGUMENTS; } } }
923d0cc4c6061f25f3a438be544791c17dd2a954
3,907
java
Java
src/main/java/org/motechproject/mots/repository/custom/impl/VillageRepositoryImpl.java
Telli/mots
cd35d81da0efd4eefbd062410f16b30faaf6792f
[ "Apache-2.0" ]
null
null
null
src/main/java/org/motechproject/mots/repository/custom/impl/VillageRepositoryImpl.java
Telli/mots
cd35d81da0efd4eefbd062410f16b30faaf6792f
[ "Apache-2.0" ]
null
null
null
src/main/java/org/motechproject/mots/repository/custom/impl/VillageRepositoryImpl.java
Telli/mots
cd35d81da0efd4eefbd062410f16b30faaf6792f
[ "Apache-2.0" ]
null
null
null
35.844037
96
0.704377
1,000,150
package org.motechproject.mots.repository.custom.impl; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.motechproject.mots.domain.Village; import org.motechproject.mots.repository.custom.VillageRepositoryCustom; import org.motechproject.mots.web.LocationController; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; public class VillageRepositoryImpl extends BaseRepositoryImpl implements VillageRepositoryCustom { /** * Finds Villages matching all of the provided parameters. * If there are no parameters, return all Villages. */ @Override public Page<Village> search(String villageName, String parentFacility, String sectorName, String districtName, Pageable pageable) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Village> query = builder.createQuery(Village.class); query = prepareQuery(query, villageName, parentFacility, sectorName, districtName, false, pageable); CriteriaQuery<Long> countQuery = builder.createQuery(Long.class); countQuery = prepareQuery(countQuery, villageName, parentFacility, sectorName, districtName, true, pageable); Long count = entityManager.createQuery(countQuery).getSingleResult(); int pageSize = getPageSize(pageable); int firstResult = getFirstResult(pageable, pageSize); List<Village> villages = entityManager.createQuery(query) .setMaxResults(pageSize) .setFirstResult(firstResult) .getResultList(); return new PageImpl<>(villages, pageable, count); } private <T> CriteriaQuery<T> prepareQuery(CriteriaQuery<T> query, String villageName, String parentFacility, String sectorName, String districtName, boolean count, Pageable pageable) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); Root<Village> root = query.from(Village.class); if (count) { CriteriaQuery<Long> countQuery = (CriteriaQuery<Long>) query; query = (CriteriaQuery<T>) countQuery.select(builder.count(root)); } Predicate predicate = builder.conjunction(); if (villageName != null) { predicate = builder.and(predicate, builder.like(root.get(NAME), '%' + villageName.trim() + '%')); } if (parentFacility != null) { predicate = builder.and(predicate, builder.like(root.get(FACILITY).get(NAME), '%' + parentFacility.trim() + '%')); } if (sectorName != null) { predicate = builder.and( predicate, builder.like(root.get(FACILITY).get(SECTOR).get(NAME), '%' + sectorName.trim() + '%') ); } if (districtName != null) { predicate = builder.and( predicate, builder.like(root.get(FACILITY).get(SECTOR).get(DISTRICT).get(NAME), '%' + districtName.trim() + '%') ); } query.where(predicate); if (!count && pageable != null && pageable.getSort() != null) { query = addSortProperties(query, root, pageable); } return query; } @Override protected Path getPath(Root root, Sort.Order order) { Path path; if (order.getProperty().equals(LocationController.PARENT_PARAM)) { path = root.get(FACILITY).get(NAME); } else if (order.getProperty().equals(LocationController.SECTOR_NAME_PARAM)) { path = root.get(FACILITY).get(SECTOR).get(NAME); } else if (order.getProperty().equals(LocationController.DISTRICT_NAME_PARAM)) { path = root.get(FACILITY).get(SECTOR).get(DISTRICT).get(NAME); } else { path = root.get(order.getProperty()); } return path; } }
923d0cd6a63ed6511354436ed9544b6375b11b73
27,118
java
Java
m3/src/main/java/com/uber/m3/tally/m3/M3Reporter.java
longquanzheng/tally
565fa3d8c8911689aedd016fde045d639f72f9b3
[ "MIT" ]
null
null
null
m3/src/main/java/com/uber/m3/tally/m3/M3Reporter.java
longquanzheng/tally
565fa3d8c8911689aedd016fde045d639f72f9b3
[ "MIT" ]
null
null
null
m3/src/main/java/com/uber/m3/tally/m3/M3Reporter.java
longquanzheng/tally
565fa3d8c8911689aedd016fde045d639f72f9b3
[ "MIT" ]
1
2021-04-08T00:43:39.000Z
2021-04-08T00:43:39.000Z
35.587927
120
0.626632
1,000,151
// Copyright (c) 2017 Uber Technologies, Inc. // // 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.uber.m3.tally.m3; import com.uber.m3.tally.BucketPair; import com.uber.m3.tally.BucketPairImpl; import com.uber.m3.tally.Buckets; import com.uber.m3.tally.Capabilities; import com.uber.m3.tally.CapableOf; import com.uber.m3.tally.StatsReporter; import com.uber.m3.tally.m3.thrift.TCalcTransport; import com.uber.m3.tally.m3.thrift.TMultiUdpClient; import com.uber.m3.tally.m3.thrift.TUdpClient; import com.uber.m3.thrift.gen.CountValue; import com.uber.m3.thrift.gen.GaugeValue; import com.uber.m3.thrift.gen.M3; import com.uber.m3.thrift.gen.Metric; import com.uber.m3.thrift.gen.MetricBatch; import com.uber.m3.thrift.gen.MetricTag; import com.uber.m3.thrift.gen.MetricValue; import com.uber.m3.thrift.gen.TimerValue; import com.uber.m3.util.Duration; import com.uber.m3.util.ImmutableMap; import org.apache.thrift.TException; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.protocol.TProtocolFactory; import org.apache.thrift.transport.TTransport; import java.net.InetAddress; import java.net.SocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Phaser; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.thrift.transport.TTransportException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * An M3 implementation of a {@link StatsReporter}. */ public class M3Reporter implements StatsReporter, AutoCloseable { public static final String SERVICE_TAG = "service"; public static final String ENV_TAG = "env"; public static final String HOST_TAG = "host"; public static final String DEFAULT_TAG_VALUE = "default"; public static final String DEFAULT_HISTOGRAM_BUCKET_ID_NAME = "bucketid"; public static final String DEFAULT_HISTOGRAM_BUCKET_NAME = "bucket"; public static final int DEFAULT_HISTOGRAM_BUCKET_TAG_PRECISION = 6; private static final Logger LOG = LoggerFactory.getLogger(M3Reporter.class); private static final int MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS = 1000; private static final int DEFAULT_METRIC_SIZE = 100; private static final int DEFAULT_MAX_QUEUE_SIZE = 4096; private static final int DEFAULT_MAX_PACKET_SIZE = 1440; private static final int THREAD_POOL_SIZE = 10; private static final int EMIT_METRIC_BATCH_OVERHEAD = 19; private static final int MIN_METRIC_BUCKET_ID_TAG_LENGTH = 4; private M3.Client client; // calcLock protects both calc and calcProtocol private final Object calcLock = new Object(); private TCalcTransport calc; private TProtocol calcProtocol; private int maxProcessorWaitUntilFlushMillis; private int freeBytes; private String bucketIdTagName; private String bucketTagName; private String bucketValFmt; // Holds metrics to be flushed private final BlockingQueue<SizedMetric> metricQueue; // The service used to execute metric flushes private ExecutorService executor; // Used to keep track of how many processors are in progress in // order to wait for them to finish before closing private Phaser phaser = new Phaser(1); private TTransport transport; // Use inner Builder class to construct an M3Reporter private M3Reporter(Builder builder) { try { // Builder verifies non-null, non-empty socketAddresses SocketAddress[] socketAddresses = builder.socketAddresses; TProtocolFactory protocolFactory = new TCompactProtocol.Factory(); if (socketAddresses.length > 1) { transport = new TMultiUdpClient(socketAddresses); } else { transport = new TUdpClient(socketAddresses[0]); } transport.open(); client = new M3.Client(protocolFactory.getProtocol(transport)); calcProtocol = new TCompactProtocol.Factory().getProtocol(new TCalcTransport()); calc = (TCalcTransport) calcProtocol.getTransport(); freeBytes = calculateFreeBytes(builder.maxPacketSizeBytes, builder.metricTagSet); maxProcessorWaitUntilFlushMillis = builder.maxProcessorWaitUntilFlushMillis; bucketIdTagName = builder.histogramBucketIdName; bucketTagName = builder.histogramBucketName; bucketValFmt = String.format("%%.%df", builder.histogramBucketTagPrecision); metricQueue = new LinkedBlockingQueue<>(builder.maxQueueSize); executor = builder.executor; addAndRunProcessor(builder.metricTagSet); } catch (TTransportException | SocketException e) { throw new RuntimeException("Exception creating M3Reporter", e); } } private int calculateFreeBytes(int maxPacketSizeBytes, Set<MetricTag> commonTags) { MetricBatch metricBatch = new MetricBatch(); metricBatch.setCommonTags(commonTags); metricBatch.setMetrics(new ArrayList<Metric>()); int size; try { metricBatch.write(calcProtocol); size = calc.getSizeAndReset(); } catch (TException e) { LOG.warn("Unable to calculate metric batch size. Defaulting to: {}", DEFAULT_METRIC_SIZE); size = DEFAULT_METRIC_SIZE; } int numOverheadBytes = EMIT_METRIC_BATCH_OVERHEAD + size; freeBytes = maxPacketSizeBytes - numOverheadBytes; if (freeBytes <= 0) { throw new IllegalArgumentException("Common tags serialized size exceeds packet size"); } return freeBytes; } private static String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { LOG.warn("Unable to determine hostname. Defaulting to: {}", DEFAULT_TAG_VALUE); return DEFAULT_TAG_VALUE; } } private void addAndRunProcessor(Set<MetricTag> commonTags) { phaser.register(); executor.execute(new Processor(commonTags)); } @Override public Capabilities capabilities() { return CapableOf.REPORTING_TAGGING; } @Override public void flush() { try { metricQueue.put(SizedMetric.FLUSH); } catch (InterruptedException e) { LOG.warn("Interrupted while trying to queue flush sentinel"); } } private void flush(List<Metric> metrics, Set<MetricTag> commonTags) { if (metrics.isEmpty()) { return; } MetricBatch metricBatch = new MetricBatch(); metricBatch.setCommonTags(commonTags); metricBatch.setMetrics(metrics); try { client.emitMetricBatch(metricBatch); } catch (TException tException) { LOG.warn("Failed to flush metrics: " + tException.getMessage()); } metricBatch.setMetrics(null); metrics.clear(); } @Override public void close() { // Put sentinal value in queue so that processors know to disregard anything that comes after it. queueSizedMetric(SizedMetric.CLOSE); // Important to use `shutdownNow` instead of `shutdown` to interrupt processor // thread(s) or else they will block forever executor.shutdownNow(); // Wait a maximum of `MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS` for all processors // to return from flushing try { phaser.awaitAdvanceInterruptibly( phaser.arrive(), MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS, TimeUnit.MILLISECONDS ); } catch (TimeoutException e) { LOG.warn( "M3Reporter closing before Processors complete after waiting timeout of {}ms!", MAX_PROCESSOR_WAIT_ON_CLOSE_MILLIS ); } catch (InterruptedException e) { LOG.warn("M3Reporter closing before Processors complete due to being interrupted!"); } transport.close(); } private static Set<MetricTag> toMetricTagSet(Map<String, String> tags) { Set<MetricTag> metricTagSet = new HashSet<>(); if (tags == null) { return metricTagSet; } for (Map.Entry<String, String> tag : tags.entrySet()) { metricTagSet.add(createMetricTag(tag.getKey(), tag.getValue())); } return metricTagSet; } private static MetricTag createMetricTag(String tagName, String tagValue) { MetricTag metricTag = new MetricTag(tagName); if (tagValue != null && !tagValue.isEmpty()) { metricTag.setTagValue(tagValue); } return metricTag; } private int calculateSize(Metric metric) { try { synchronized (calcLock) { metric.write(calcProtocol); return calc.getSizeAndReset(); } } catch (TException e) { LOG.warn("Unable to calculate metric batch size. Defaulting to: " + DEFAULT_METRIC_SIZE); return DEFAULT_METRIC_SIZE; } } private String valueBucketString(double bucketBound) { if (bucketBound == Double.MAX_VALUE) { return "infinity"; } if (bucketBound == -Double.MAX_VALUE) { return "-infinity"; } return String.format(bucketValFmt, bucketBound); } private String durationBucketString(Duration bucketBound) { if (Duration.ZERO.equals(bucketBound)) { return "0"; } if (Duration.MAX_VALUE.equals(bucketBound)) { return "infinity"; } if (Duration.MIN_VALUE.equals(bucketBound)) { return "-infinity"; } return bucketBound.toString(); } @Override public void reportCounter(String name, Map<String, String> tags, long value) { reportCounterInternal(name, tags, value); } @Override public void reportGauge(String name, Map<String, String> tags, double value) { GaugeValue gaugeValue = new GaugeValue(); gaugeValue.setDValue(value); MetricValue metricValue = new MetricValue(); metricValue.setGauge(gaugeValue); Metric metric = newMetric(name, tags, metricValue); queueSizedMetric(new SizedMetric(metric, calculateSize(metric))); } @Override public void reportTimer(String name, Map<String, String> tags, Duration interval) { TimerValue timerValue = new TimerValue(); timerValue.setI64Value(interval.getNanos()); MetricValue metricValue = new MetricValue(); metricValue.setTimer(timerValue); Metric metric = newMetric(name, tags, metricValue); queueSizedMetric(new SizedMetric(metric, calculateSize(metric))); } @Override public void reportHistogramValueSamples( String name, Map<String, String> tags, Buckets buckets, double bucketLowerBound, double bucketUpperBound, long samples ) { // Append histogram bucket-specific tags int bucketIdLen = String.valueOf(buckets.size()).length(); bucketIdLen = Math.max(bucketIdLen, MIN_METRIC_BUCKET_ID_TAG_LENGTH); String bucketIdFmt = String.format("%%0%sd", bucketIdLen); BucketPair[] bucketPairs = BucketPairImpl.bucketPairs(buckets); if (tags == null) { // We know that the HashMap will only contain two items at this point, // therefore initialCapacity of 2 and loadFactor of 1. tags = new HashMap<>(2, 1); } else { // Copy over the map since it might be unmodifiable and, even if it's // not, we don't want to modify it. tags = new HashMap<>(tags); } for (int i = 0; i < bucketPairs.length; i++) { // Look for the first pair with an upper bound greater than or equal // to the given upper bound. if (bucketPairs[i].upperBoundValue() >= bucketUpperBound) { String idTagValue = String.format(bucketIdFmt, i); tags.put(bucketIdTagName, idTagValue); tags.put(bucketTagName, String.format("%s-%s", valueBucketString(bucketPairs[i].lowerBoundValue()), valueBucketString(bucketPairs[i].upperBoundValue()) ) ); break; } } reportCounterInternal(name, tags, samples); } @Override public void reportHistogramDurationSamples( String name, Map<String, String> tags, Buckets buckets, Duration bucketLowerBound, Duration bucketUpperBound, long samples ) { // Append histogram bucket-specific tags int bucketIdLen = String.valueOf(buckets.size()).length(); bucketIdLen = Math.max(bucketIdLen, MIN_METRIC_BUCKET_ID_TAG_LENGTH); String bucketIdFmt = String.format("%%0%sd", bucketIdLen); BucketPair[] bucketPairs = BucketPairImpl.bucketPairs(buckets); if (tags == null) { // We know that the HashMap will only contain two items at this point, // therefore initialCapacity of 2 and loadFactor of 1. tags = new HashMap<>(2, 1); } else { // Copy over the map since it might be unmodifiable and, even if it's // not, we don't want to modify it. tags = new HashMap<>(tags); } for (int i = 0; i < bucketPairs.length; i++) { // Look for the first pair with an upper bound greater than or equal // to the given upper bound. if (bucketPairs[i].upperBoundDuration().compareTo(bucketUpperBound) >= 0) { String idTagValue = String.format(bucketIdFmt, i); tags.put(bucketIdTagName, idTagValue); tags.put(bucketTagName, String.format("%s-%s", durationBucketString(bucketPairs[i].lowerBoundDuration()), durationBucketString(bucketPairs[i].upperBoundDuration()) ) ); break; } } reportCounterInternal(name, tags, samples); } // Relies on the calling function to provide guarantees of the reporter being open private void reportCounterInternal(String name, Map<String, String> tags, long value) { CountValue countValue = new CountValue(); countValue.setI64Value(value); MetricValue metricValue = new MetricValue(); metricValue.setCount(countValue); Metric metric = newMetric(name, tags, metricValue); queueSizedMetric(new SizedMetric(metric, calculateSize(metric))); } private Metric newMetric(String name, Map<String, String> tags, MetricValue metricValue) { Metric metric = new Metric(name); metric.setTags(toMetricTagSet(tags)); metric.setTimestamp(System.currentTimeMillis() * Duration.NANOS_PER_MILLI); metric.setMetricValue(metricValue); return metric; } private void queueSizedMetric(SizedMetric sizedMetric) { try { metricQueue.put(sizedMetric); } catch (InterruptedException e) { LOG.warn(String.format("Interrupted queueing metric: {}", sizedMetric.getMetric().getName())); } } private class Processor implements Runnable { final Set<MetricTag> commonTags; List<Metric> pendingMetrics = new ArrayList<>(freeBytes / 10); int metricsSize = 0; Processor(Set<MetricTag> commonTags) { this.commonTags = commonTags; } @Override public void run() { try { while (!executor.isShutdown()) { // This `poll` call will block for at most the specified duration to take an item // off the queue. If we get an item, we append it to the queue to be flushed, // otherwise we flush what we have so far. // When this reporter is closed, shutdownNow will be called on the executor, // which will interrupt this thread and proceed to the `InterruptedException` // catch block. SizedMetric sizedMetric = metricQueue.poll(maxProcessorWaitUntilFlushMillis, TimeUnit.MILLISECONDS); // Drop metrics that came in after close if (sizedMetric == SizedMetric.CLOSE) { metricQueue.clear(); break; } if (sizedMetric != null) { flushMetricIteration(sizedMetric); continue; } // If we don't get any new metrics after waiting the specified time, // flush what we have so far. if (!pendingMetrics.isEmpty()) { flushMetricIteration(SizedMetric.FLUSH); } } } catch (InterruptedException e) { // Don't care if we get interrupted - the finally block will clean up } finally { flushRemainingMetrics(); // Always arrive at phaser to prevent deadlock phaser.arrive(); } } private void flushMetricIteration(SizedMetric sizedMetric) { Metric metric = sizedMetric.getMetric(); if (sizedMetric == SizedMetric.FLUSH) { flush(pendingMetrics, commonTags); return; } int size = sizedMetric.getSize(); if (metricsSize + size > freeBytes) { flush(pendingMetrics, commonTags); metricsSize = 0; } pendingMetrics.add(metric); metricsSize += size; } private void flushRemainingMetrics() { while (!metricQueue.isEmpty()) { SizedMetric sizedMetric = metricQueue.remove(); // Don't care about metrics that came in after close if (sizedMetric == SizedMetric.CLOSE) { break; } flushMetricIteration(sizedMetric); } flush(pendingMetrics, commonTags); } } /** * Builder pattern to construct an {@link M3Reporter}. */ public static class Builder { protected SocketAddress[] socketAddresses; protected String service; protected String env; protected ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE); // Non-generic EMPTY ImmutableMap will never contain any elements @SuppressWarnings("unchecked") protected ImmutableMap<String, String> commonTags = ImmutableMap.EMPTY; protected boolean includeHost = true; protected int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE; protected int maxPacketSizeBytes = DEFAULT_MAX_PACKET_SIZE; protected int maxProcessorWaitUntilFlushMillis = 10_000; protected String histogramBucketIdName = DEFAULT_HISTOGRAM_BUCKET_ID_NAME; protected String histogramBucketName = DEFAULT_HISTOGRAM_BUCKET_NAME; protected int histogramBucketTagPrecision = DEFAULT_HISTOGRAM_BUCKET_TAG_PRECISION; private Set<MetricTag> metricTagSet; /** * Constructs a {@link Builder}. Having at least one {@code SocketAddress} is required. * @param socketAddresses the array of {@code SocketAddress}es for this {@link M3Reporter} */ public Builder(SocketAddress[] socketAddresses) { if (socketAddresses == null || socketAddresses.length == 0) { throw new IllegalArgumentException("Must specify at least one SocketAddress"); } this.socketAddresses = socketAddresses; } /** * Constructs a {@link Builder}. Having at least one {@code SocketAddress} is required. * @param socketAddress the {@code SocketAddress} for this {@link M3Reporter} */ public Builder(SocketAddress socketAddress) { this(new SocketAddress[]{socketAddress}); } /** * Configures the service of this {@link Builder}. * @param service the value to set * @return this {@link Builder} with the new value set */ public Builder service(String service) { this.service = service; return this; } /** * Configures the env of this {@link Builder}. * @param env the value to set * @return this {@link Builder} with the new value set */ public Builder env(String env) { this.env = env; return this; } /** * Configures the executor of this {@link Builder}. * @param executor the value to set * @return this {@link Builder} with the new value set */ public Builder executor(ExecutorService executor) { this.executor = executor; return this; } /** * Configures the common tags of this {@link Builder}. * @param commonTags the value to set * @return this {@link Builder} with the new value set */ public Builder commonTags(ImmutableMap<String, String> commonTags) { this.commonTags = commonTags; return this; } /** * Configures whether to include the host tag of this {@link Builder}. * @param includeHost the value to set * @return this {@link Builder} with the new value set */ public Builder includeHost(boolean includeHost) { this.includeHost = includeHost; return this; } /** * Configures the maximum queue size of this {@link Builder}. * @param maxQueueSize the value to set * @return this {@link Builder} with the new value set */ public Builder maxQueueSize(int maxQueueSize) { this.maxQueueSize = maxQueueSize; return this; } /** * Configures the maximum packet size in bytes of this {@link Builder}. * @param maxPacketSizeBytes the value to set * @return this {@link Builder} with the new value set */ public Builder maxPacketSizeBytes(int maxPacketSizeBytes) { this.maxPacketSizeBytes = maxPacketSizeBytes; return this; } /** * Configures the maximum wait time in milliseconds size in bytes of this {@link Builder}. * @param maxProcessorWaitUntilFlushMillis the value to set * @return this {@link Builder} with the new value set */ public Builder maxProcessorWaitUntilFlushMillis(int maxProcessorWaitUntilFlushMillis) { this.maxProcessorWaitUntilFlushMillis = maxProcessorWaitUntilFlushMillis; return this; } /** * Configures the histogram bucket ID name of this {@link Builder}. * @param histogramBucketIdName the value to set * @return this {@link Builder} with the new value set */ public Builder histogramBucketIdName(String histogramBucketIdName) { this.histogramBucketIdName = histogramBucketIdName; return this; } /** * Configures the histogram bucket name of this {@link Builder}. * @param histogramBucketName the value to set * @return this {@link Builder} with the new value set */ public Builder histogramBucketName(String histogramBucketName) { this.histogramBucketName = histogramBucketName; return this; } /** * Configures the histogram bucket tag precision of this {@link Builder}. * @param histogramBucketTagPrecision the value to set * @return this {@link Builder} with the new value set */ public Builder histogramBucketTagPrecision(int histogramBucketTagPrecision) { this.histogramBucketTagPrecision = histogramBucketTagPrecision; return this; } /** * Builds and returns an {@link M3Reporter} with the configured paramters. * @return a new {@link M3Reporter} instance with the configured paramters */ public M3Reporter build() { metricTagSet = toMetricTagSet(commonTags); // Set and ensure required tags if (!commonTags.containsKey(SERVICE_TAG)) { if (service == null || service.isEmpty()) { throw new IllegalArgumentException(String.format("Common tag [%s] is required", SERVICE_TAG)); } metricTagSet.add(createMetricTag(SERVICE_TAG, service)); } if (!commonTags.containsKey(ENV_TAG)) { if (env == null || env.isEmpty()) { throw new IllegalArgumentException(String.format("Common tag [%s] is required", ENV_TAG)); } metricTagSet.add(createMetricTag(ENV_TAG, env)); } if (includeHost && !commonTags.containsKey(HOST_TAG)) { metricTagSet.add(createMetricTag(HOST_TAG, getHostName())); } return new M3Reporter(this); } } }
923d0ce4c0d11a557ec7d441eb97afeb15ee0421
412
java
Java
xm/chat/WeChatBill_Single/app/src/main/java/net/lightbody/bmp/core/har/PageRefFilteredHar.java
ming1991/kmxm
f3cbf8e5bb5fe1b6e7ae4090cf9e44f9d592bc56
[ "Apache-2.0" ]
4,184
2016-10-17T07:19:02.000Z
2022-03-31T16:17:47.000Z
app/src/main/java/net/lightbody/bmp/core/har/PageRefFilteredHar.java
jxzhung/AndroidHttpCapture
c5cadb148e32dd3ec1646f07964971b7960da96d
[ "MIT" ]
87
2016-10-24T05:58:18.000Z
2022-03-21T08:36:58.000Z
app/src/main/java/net/lightbody/bmp/core/har/PageRefFilteredHar.java
jxzhung/AndroidHttpCapture
c5cadb148e32dd3ec1646f07964971b7960da96d
[ "MIT" ]
832
2016-10-18T01:07:30.000Z
2022-03-31T02:40:06.000Z
24.235294
64
0.696602
1,000,152
package net.lightbody.bmp.core.har; import java.util.Set; /** * Created by Darkal on 2016/9/2. */ public class PageRefFilteredHar extends Har { public PageRefFilteredHar(Har har, Set<String> pageRef) { super(new PageRefFilteredHarLog(har.getLog(), pageRef)); } public PageRefFilteredHar(Har har, String pageRef) { super(new PageRefFilteredHarLog(har.getLog(), pageRef)); } }
923d0d3ee54f5fd781510f3b05c7ffc149d7dd20
12,970
java
Java
src/main/java/jp/co/sony/csl/dcoes/apis/common/util/vertx/ApisLauncher.java
SonyCSL/apis-common
fc1e072aac8f633e30e960e4c6d67a7938b8f920
[ "Apache-2.0" ]
2
2020-12-01T04:30:28.000Z
2020-12-02T00:56:09.000Z
src/main/java/jp/co/sony/csl/dcoes/apis/common/util/vertx/ApisLauncher.java
SonyCSL/apis-common
fc1e072aac8f633e30e960e4c6d67a7938b8f920
[ "Apache-2.0" ]
null
null
null
src/main/java/jp/co/sony/csl/dcoes/apis/common/util/vertx/ApisLauncher.java
SonyCSL/apis-common
fc1e072aac8f633e30e960e4c6d67a7938b8f920
[ "Apache-2.0" ]
null
null
null
37.270115
158
0.711025
1,000,153
package jp.co.sony.csl.dcoes.apis.common.util.vertx; import io.vertx.core.Launcher; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.file.impl.FileResolver; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.core.net.PemKeyCertOptions; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; 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.stream.Stream; import jp.co.sony.csl.dcoes.apis.common.util.EncryptionUtil; /** * This is the common startup class for APIS programs. * It carries out tricks around encryption. * It is specified by maven-shade-plugin's {@literal <Main-Verticle>} in pom.xml. * APIS プログラム共通の起動クラス. * 暗号化まわりの細工をするため. * pom.xml の maven-shade-plugin の {@literal <Main-Class>} で指定してある. * @author OES Project */ public class ApisLauncher extends Launcher { private static final Logger log = LoggerFactory.getLogger(ApisLauncher.class); /** * Sets suffix to key of entry encrypted in CONFIG. * Sets suffix to encrypted file name. * The value is {@value}. * CONFIG 中の暗号化されたエントリのキー接尾辞. * 暗号化されたファイルのファイル名接尾辞. * 値は {@value}. */ private static final String SUFFIX_TO_DECRYPT = ".encrypted"; /** * Keeps {@link Path} to delete decrypted files later. * 復号した暗号化ファイルを後で削除するため {@link Path} を保持しておく. */ private List<Path> decryptedPaths_ = new ArrayList<>(); /** * Follows {@link Launcher#main(String[])} pattern. * @param args the user command line arguments. * {@link Launcher#main(String[])} を踏襲. * @param args the user command line arguments. */ public static void main(String[] args) { new ApisLauncher().dispatch(args); } /** * Follows {@link Launcher#executeCommand(String, String...)} pattern. * @param cmd the command * @param args the arguments * {@link Launcher#executeCommand(String, String...)} を踏襲. * @param cmd the command * @param args the arguments */ public static void executeCommand(String cmd, String... args) { new ApisLauncher().execute(cmd, args); } //// /** * Called after reading CONFIG files. * Decrypts encrypted strings in CONFIG. * Decrypts encrypted files * @param config {@inheritDoc} * CONFIG ファイル読み込み後に呼び出される. * CONFIG 中の暗号化された文字列を復号する. * 暗号化された各種ファイルを復号する. * @param config {@inheritDoc} */ @Override public void afterConfigParsed(JsonObject config) { VertxConfig.config.setJsonObject(config); initVertxCacheDirBase_(); initEncryption_(); decryptConfig_(); decryptFiles_(); } /** * Called before starting the vertx instance. * Configures SSL for EventBus message communication. * @param options {@inheritDoc} * vertx インスタンスの起動前に呼び出される. * EventBus メッセージ通信の SSL 化を設定する. * @param options {@inheritDoc} */ @Override public void beforeStartingVertx(VertxOptions options) { doSecureCluster_(options); } /** * Called after starting vertx instance. * Deletes decrypted files. * @param vertx {@inheritDoc} * vertx インスタンスの起動後に呼び出される. * 復号した暗号化ファイルを削除する. * @param vertx {@inheritDoc} */ @Override public void afterStartingVertx(Vertx vertx) { deleteDecryptedFiles_(); } /** * Called before stopping vertx instance. * Deletes decrypted files. * @param vertx {@inheritDoc} * vertx インスタンス停止前に呼ばれる. * 復号した暗号化ファイルを削除する. * @param vertx {@inheritDoc} */ @Override public void beforeStoppingVertx(Vertx vertx) { deleteDecryptedFiles_(); } /** * Called after stopping vertx instance. * Deletes decrytped files. * vertx インスタンス停止後に呼ばれる. * 復号した暗号化ファイルを削除する. */ @Override public void afterStoppingVertx() { deleteDecryptedFiles_(); } //// /** * Changes the location and name of vertx-cache directory. * The default behavior of Vert.x is {@code /tmp/vertx-cache}. * {IllegalStateException: Failed to create cache dir} occurs when multiple apis-main for running the gateway unit are started in different accounts. * To avoid this, path is included in the account string. * vertx-cache ディレクトリの場所と名前を変更する. * Vert.x のデフォルト動作は {@code /tmp/vertx-cache} である. * ゲイトウェイユニット運用のため複数の apis-main を異なるアカウントで起動すると {@code java.lang.IllegalStateException: Failed to create cache dir} が起きる. * これを避けるためパスにアカウント文字列を含めるようにした. */ private void initVertxCacheDirBase_() { String tmpdir = System.getProperty("java.io.tmpdir", "."); String name = System.getProperty("user.name", "unknown"); String base = tmpdir + File.separator + "vertx-cache." + name; if (log.isDebugEnabled()) log.debug(FileResolver.CACHE_DIR_BASE_PROP_NAME + " : " + base); System.setProperty(FileResolver.CACHE_DIR_BASE_PROP_NAME, base); } /** * Carries out {initialization of {@link EncryptionUtil#initialize(io.vertx.core.Handler) EncryptionUtil}. * @throws RuntimeException initialization failure * {@link EncryptionUtil#initialize(io.vertx.core.Handler) EncryptionUtil を初期化}する. * @throws RuntimeException 初期化失敗 */ private void initEncryption_() { EncryptionUtil.initialize(r -> { if (r.succeeded()) { } else { throw new RuntimeException("encryption initialization failed", r.cause()); } }); } /** * Decrypts encrypted strings in CONFIG ( {@link JsonObject} ) entries. * For the encryption marker, key ends with suffix {@value #SUFFIX_TO_DECRYPT}. * After decryption, registers using key without suffix. * Processes recursively if value is {@link JsonArray} or {@link JsonObject}. * CONFIG ( {@link JsonObject} ) のエントリのうち暗号化された文字列を復号する. * 暗号化の目印はキーが接尾辞 {@value #SUFFIX_TO_DECRYPT} で終わっていること. * 復号したのち接尾辞を除いたキーで登録する. * 値が {@link JsonArray} や {@link JsonObject} の場合は再帰的に処理する. */ private void decryptConfig_() { JsonObject src = VertxConfig.config.jsonObject(); if (src != null) { JsonObject result = decrypt_(src, false); VertxConfig.config.setJsonObject(result); } } /** * Decrypts encrypted strings by recursively traversing {@link JsonObject}. * @param obj jsonobject object to be decrypted * @param needDecrypt decryption flag. * This is needed because child elements of entry with encryption marker {@value #SUFFIX_TO_DECRYPT} need to be decrypted recursively. * @return decrypted jsonobject object * {@link JsonObject} を再帰的に辿って暗号化された文字列を復号する. * @param obj 復号対象 jsonobject オブジェクト * @param needDecrypt 復号フラグ. * 暗号化の目印 {@value #SUFFIX_TO_DECRYPT} が着いたエントリの子孫要素は再帰的に復号する必要があるため. * @return 復号済みの jsonobject オブジェクト */ private JsonObject decrypt_(JsonObject obj, boolean needDecrypt) { JsonObject result = new JsonObject(); obj.forEach(kv -> { String k = kv.getKey(); boolean needDecrypt_ = needDecrypt; if (k.endsWith(SUFFIX_TO_DECRYPT)) { needDecrypt_ = true; k = k.substring(0, k.length() - SUFFIX_TO_DECRYPT.length()); } result.put(k, decrypt_(kv.getValue(), needDecrypt_)); }); return result; } /** * Decrypts encrypted strings by recursively traversing {@link JsonArray}. * @param ary jsonarray object to be decrypted * @param needDecrypt decryption flag. * This is needed because child elements of entry with encryption marker {@value #SUFFIX_TO_DECRYPT} need to be decrypted recursively. * @return decrypted jsonarray object * {@link JsonArray} を再帰的に辿って暗号化された文字列を復号する. * @param ary 復号対象 jsonarray オブジェクト * @param needDecrypt 復号フラグ. * 暗号化の目印 {@value #SUFFIX_TO_DECRYPT} が着いたエントリの子孫要素は再帰的に復号する必要があるため. * @return 復号済みの jsonarray オブジェクト */ private JsonArray decrypt_(JsonArray ary, boolean needDecrypt) { JsonArray result = new JsonArray(); ary.forEach(v -> { result.add(decrypt_(v, needDecrypt)); }); return result; } /** * Decrypts encrypted strings by recursively traversing {@link JsonArray}. * @param v object to be decrypted. * If string, decrypts as needed in accordance with {@code needDecrypt}. * If {@link JsonObject}, calls {@link #decrypt_(JsonObject, boolean)}. * If {@link JsonArray}, calls {@link #decrypt_(JsonArray, boolean)}. * @param needDecrypt decryption flag. * This is needed because child elements of entry with encryption marker {@value #SUFFIX_TO_DECRYPT} need to be decrypted recursively. * @return Decrypted object * {@link JsonArray} を再帰的に辿って暗号化された文字列を復号する. * @param v 復号対象オブジェクト. * 文字列の場合は {@code needDecrypt} に従って必要に応じて復号する. * {@link JsonObject} の場合は {@link #decrypt_(JsonObject, boolean)} を呼ぶ. * {@link JsonArray} の場合は {@link #decrypt_(JsonArray, boolean)} を呼ぶ. * @param needDecrypt 復号フラグ. * 暗号化の目印 {@value #SUFFIX_TO_DECRYPT} が着いたエントリの子孫要素は再帰的に復号する必要があるため. * @return 復号済みのオブジェクト */ private Object decrypt_(Object v, boolean needDecrypt) { if (v instanceof String && needDecrypt) { if (log.isDebugEnabled()) log.debug("decrypting string : " + v); try { return EncryptionUtil.decrypt((String) v); } catch (Exception e) { log.error(e); throw new RuntimeException("string decryption failed : " + v, e); } } else if (v instanceof JsonObject) { return decrypt_((JsonObject) v, needDecrypt); } else if (v instanceof JsonArray) { return decrypt_((JsonArray) v, needDecrypt); } else { return v; } } /** * Decrypts encrypted files that exist in the current directory. * For the encryption marker, the file name ends in {@value #SUFFIX_TO_DECRYPT}. * After decryption, registers using the file name without suffix. * Keeps decrypted files in {@link #decryptedPaths_} to delete later.  * @throws RuntimeException decryption failure * カレントディレクトリに存在する暗号化されたファイルを復号する. * 暗号化の目印はファイル名が {@value #SUFFIX_TO_DECRYPT} で終わっていること. * 復号したのち接尾辞を除いたファイル名で登録する. * 復号したファイルは後ほど削除するため {@link #decryptedPaths_} に保持しておく.  * @throws RuntimeException 復号失敗 */ private void decryptFiles_() { try (Stream<Path> paths = Files.list(Paths.get(""))) { paths.filter(path -> !Files.isDirectory(path) && path.getFileName() != null && path.getFileName().toString().endsWith(SUFFIX_TO_DECRYPT)).forEach(path -> { String encryptedFilename = path.getFileName().toString(); String decryptedFilename = encryptedFilename.substring(0, encryptedFilename.length() - SUFFIX_TO_DECRYPT.length()); if (log.isDebugEnabled()) log.debug("decrypting file : " + encryptedFilename); try { List<String> lines = Files.readAllLines(path); String encrypted = String.join("", lines); String decrypted = EncryptionUtil.decrypt(encrypted); Path decryptedPath = Paths.get("", decryptedFilename); Files.write(decryptedPath, decrypted.getBytes(StandardCharsets.UTF_8)); if (log.isDebugEnabled()) log.debug("file decrypted : " + decryptedFilename); decryptedPaths_.add(decryptedPath); } catch (Exception e) { log.error(e); throw new RuntimeException("file decryption failed : " + encryptedFilename, e); } }); } catch (IOException e) { throw new RuntimeException("file decryption failed", e); } } /** * Deletes decrypted files. * Refers to {@link #decryptedPaths_} for files to be deleted. * @throws RuntimeException deletion failure * 復号した暗号化ファイルを削除する. * 削除対象ファイルは {@link #decryptedPaths_} を参照する. * @throws RuntimeException 削除失敗 */ private void deleteDecryptedFiles_() { for (Path decryptedPath : decryptedPaths_) { if (log.isDebugEnabled()) log.debug("deleting file : " + decryptedPath); try { boolean deleted = Files.deleteIfExists(decryptedPath); if (deleted) { if (log.isDebugEnabled()) log.debug("file deleted : " + decryptedPath); } else { if (log.isDebugEnabled()) log.debug("no such file : " + decryptedPath); } } catch (Exception e) { log.error(e); throw new RuntimeException("file deletion failed : " + decryptedPath, e); } } } /** * Configures SSL for EventBus message communication. * Does nothing if {@link VertxConfig#securityEnabled()} is {@code false}. * @param options the configured Vert.x options. Modify them to customize the Vert.x instance. * EventBus メッセージ通信の SSL 化を設定する. * {@link VertxConfig#securityEnabled()} が {@code false} なら何もしない. * @param options the configured Vert.x options. Modify them to customize the Vert.x instance. */ private void doSecureCluster_(VertxOptions options) { if (VertxConfig.securityEnabled()) { if (log.isInfoEnabled()) log.info("EventBus will be secured"); String keyFilePath = VertxConfig.securityPemKeyFile(); String certFilePath = VertxConfig.securityPemCertFile(); if (log.isDebugEnabled()) log.debug("pem key file : " + keyFilePath); if (log.isDebugEnabled()) log.debug("pem cert file : " + certFilePath); options.getEventBusOptions().setSsl(true).setPemKeyCertOptions(new PemKeyCertOptions().addKeyPath(keyFilePath).addCertPath(certFilePath)); } } }
923d0d99fff91ade472cc2ca4091c56d688c6f01
3,706
java
Java
src/main/java/org/mbari/m3/vars/annotation/commands/DuplicateAnnotationsCmd.java
Jinksi/vars-annotation
fd4fc42c94a9a1180a3d6db991884a5839d16849
[ "Apache-2.0" ]
null
null
null
src/main/java/org/mbari/m3/vars/annotation/commands/DuplicateAnnotationsCmd.java
Jinksi/vars-annotation
fd4fc42c94a9a1180a3d6db991884a5839d16849
[ "Apache-2.0" ]
null
null
null
src/main/java/org/mbari/m3/vars/annotation/commands/DuplicateAnnotationsCmd.java
Jinksi/vars-annotation
fd4fc42c94a9a1180a3d6db991884a5839d16849
[ "Apache-2.0" ]
null
null
null
38.206186
106
0.633297
1,000,154
package org.mbari.m3.vars.annotation.commands; import org.mbari.m3.vars.annotation.UIToolBox; import org.mbari.m3.vars.annotation.events.AnnotationsAddedEvent; import org.mbari.m3.vars.annotation.events.AnnotationsRemovedEvent; import org.mbari.m3.vars.annotation.events.AnnotationsSelectedEvent; import org.mbari.m3.vars.annotation.model.Annotation; import org.mbari.m3.vars.annotation.model.Association; import org.mbari.m3.vars.annotation.model.Media; import java.time.Duration; import java.time.Instant; import java.util.Collection; import java.util.UUID; import java.util.stream.Collectors; /** * @author Brian Schlining * @since 2017-07-20T22:23:00 */ public class DuplicateAnnotationsCmd implements Command { private final Collection<Annotation> duplicateAnnotations; private final boolean selectAnnotations; public DuplicateAnnotationsCmd(String user, String activity, Collection<Annotation> sourceAnnotations, boolean selectAnnotations) { this.duplicateAnnotations = sourceAnnotations.stream() .map(a -> makeDuplicate(a, user, activity)) .collect(Collectors.toList()); this.selectAnnotations = selectAnnotations; } public Annotation makeDuplicate(Annotation annotation, String user, String activity) { Annotation duplicate = new Annotation(annotation); duplicate.setObservationUuid(null); duplicate.setObservationTimestamp(Instant.now()); duplicate.setObserver(user); duplicate.setActivity(activity); // if we don't null the associations uuid, it will fail to insert due to // a duplicate primary key clash. duplicate.getAssociations().forEach(Association::resetUuid); return duplicate; } @Override public void apply(UIToolBox toolBox) { Media media = toolBox.getData().getMedia(); if (media.getStartTimestamp() != null ) { duplicateAnnotations.forEach(annotation -> { Duration elapsedTime = annotation.getElapsedTime(); // Calculate timestamp from media start time and annotation elapsed time if (elapsedTime != null) { Instant recordedDate = media.getStartTimestamp().plus(elapsedTime); annotation.setRecordedTimestamp(recordedDate); } }); } toolBox.getServices() .getAnnotationService() .createAnnotations(duplicateAnnotations) .thenAccept(annos -> { // Replace our existing dups with the ones with the correct observation uuids duplicateAnnotations.clear(); duplicateAnnotations.addAll(annos); toolBox.getEventBus() .send(new AnnotationsAddedEvent(annos)); if (selectAnnotations) { toolBox.getEventBus() .send(new AnnotationsSelectedEvent(annos)); } }); } @Override public void unapply(UIToolBox toolBox) { final Collection<UUID> uuids = duplicateAnnotations.stream() .map(Annotation::getObservationUuid) .collect(Collectors.toList()); toolBox.getServices() .getAnnotationService() .deleteAnnotations(uuids) .thenAccept(v -> toolBox.getEventBus() .send(new AnnotationsRemovedEvent(duplicateAnnotations))); } @Override public String getDescription() { return "Duplicate Annotations"; } }
923d0d9cc7ec69743817f8ea80aaa2f75350158e
3,486
java
Java
samples/social/src/main/java/org/springframework/social/showcase/config/SocialConfig.java
keesun/spring-security-javaconfig
24a1a45afcbff70bc1d07738a9f09fbd9a56c733
[ "Apache-2.0" ]
1
2022-03-27T18:08:40.000Z
2022-03-27T18:08:40.000Z
samples/social/src/main/java/org/springframework/social/showcase/config/SocialConfig.java
keesun/spring-security-javaconfig
24a1a45afcbff70bc1d07738a9f09fbd9a56c733
[ "Apache-2.0" ]
null
null
null
samples/social/src/main/java/org/springframework/social/showcase/config/SocialConfig.java
keesun/spring-security-javaconfig
24a1a45afcbff70bc1d07738a9f09fbd9a56c733
[ "Apache-2.0" ]
null
null
null
41.011765
144
0.820138
1,000,155
/* * Copyright 2012 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.springframework.social.showcase.config; import javax.inject.Inject; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.core.env.Environment; import org.springframework.social.UserIdSource; import org.springframework.social.config.annotation.EnableJdbcConnectionRepository; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.social.connect.ConnectionRepository; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.social.connect.web.ConnectController; import org.springframework.social.facebook.config.annotation.EnableFacebook; import org.springframework.social.facebook.web.DisconnectController; import org.springframework.social.linkedin.config.annotation.EnableLinkedIn; import org.springframework.social.security.AuthenticationNameUserIdSource; import org.springframework.social.showcase.facebook.PostToWallAfterConnectInterceptor; import org.springframework.social.showcase.twitter.TweetAfterConnectInterceptor; import org.springframework.social.twitter.config.annotation.EnableTwitter; /** * Spring Social Configuration. * * This configuration is demonstrating the use of the simplified Spring Social configuration options from Spring Social 1.1. * It will only be used when the "simple" profile is active. * The more complex/explicit configuration is still available in ExplicitSocialConfig.java and will be used if the "explicit" profile is active. * * @author Craig Walls */ @Configuration @Profile("simple") @EnableJdbcConnectionRepository @EnableTwitter(appId="${twitter.consumerKey}", appSecret="${twitter.consumerSecret}") @EnableFacebook(appId="${facebook.clientId}", appSecret="${facebook.clientSecret}") @EnableLinkedIn(appId="${linkedin.consumerKey}", appSecret="${linkedin.consumerSecret}") public class SocialConfig { @Inject private Environment environment; @Inject private ConnectionFactoryLocator connectionFactoryLocator; @Inject private ConnectionRepository connectionRepository; @Inject private UsersConnectionRepository usersConnectionRepository; @Bean public ConnectController connectController() { ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository); connectController.addInterceptor(new PostToWallAfterConnectInterceptor()); connectController.addInterceptor(new TweetAfterConnectInterceptor()); return connectController; } @Bean public DisconnectController disconnectController() { return new DisconnectController(usersConnectionRepository, environment.getProperty("facebook.clientSecret")); } @Bean public UserIdSource userIdSource() { return new AuthenticationNameUserIdSource(); } }
923d0dd9d2c64b2b5d6e504a92170e0ce2ffef5d
667
java
Java
example/src/main/java/com/zyhang/musicWave/example/MainActivity.java
yuhangjiayou/MusicWave
3ccf85a5c429619285af8687156ed9183f5d33b8
[ "Apache-2.0" ]
1
2019-07-10T04:21:13.000Z
2019-07-10T04:21:13.000Z
example/src/main/java/com/zyhang/musicWave/example/MainActivity.java
yuhangjiayou/MusicWave
3ccf85a5c429619285af8687156ed9183f5d33b8
[ "Apache-2.0" ]
null
null
null
example/src/main/java/com/zyhang/musicWave/example/MainActivity.java
yuhangjiayou/MusicWave
3ccf85a5c429619285af8687156ed9183f5d33b8
[ "Apache-2.0" ]
null
null
null
23.821429
56
0.661169
1,000,156
package com.zyhang.musicWave.example; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { private View layout1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); layout1 = findViewById(R.id.layout1); } public void hide(View view) { View v = layout1; if (v.getVisibility() == View.VISIBLE) { v.setVisibility(View.GONE); } else { v.setVisibility(View.VISIBLE); } } }
923d0f61de528fcce057f58d76f12eaa1a5a419b
1,997
java
Java
cosmic-core/server/src/main/java/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java
sanderv32/cosmic
9a9d86500b67255a1c743a9438a05c0d969fd210
[ "Apache-2.0" ]
64
2016-01-30T13:31:00.000Z
2022-02-21T02:13:25.000Z
cosmic-core/server/src/main/java/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java
sanderv32/cosmic
9a9d86500b67255a1c743a9438a05c0d969fd210
[ "Apache-2.0" ]
525
2016-01-22T10:46:31.000Z
2022-02-23T11:08:01.000Z
cosmic-core/server/src/main/java/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java
sanderv32/cosmic
9a9d86500b67255a1c743a9438a05c0d969fd210
[ "Apache-2.0" ]
25
2016-01-13T16:46:46.000Z
2021-07-23T15:22:27.000Z
36.981481
121
0.745618
1,000,157
package com.cloud.api.query.dao; import com.cloud.api.ApiResponseHelper; import com.cloud.api.query.vo.InstanceGroupJoinVO; import com.cloud.api.response.InstanceGroupResponse; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.vm.InstanceGroup; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class InstanceGroupJoinDaoImpl extends GenericDaoBase<InstanceGroupJoinVO, Long> implements InstanceGroupJoinDao { public static final Logger s_logger = LoggerFactory.getLogger(InstanceGroupJoinDaoImpl.class); private final SearchBuilder<InstanceGroupJoinVO> vrIdSearch; protected InstanceGroupJoinDaoImpl() { vrIdSearch = createSearchBuilder(); vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); vrIdSearch.done(); this._count = "select count(distinct id) from instance_group_view WHERE "; } @Override public InstanceGroupResponse newInstanceGroupResponse(final InstanceGroupJoinVO group) { final InstanceGroupResponse groupResponse = new InstanceGroupResponse(); groupResponse.setId(group.getUuid()); groupResponse.setName(group.getName()); groupResponse.setCreated(group.getCreated()); ApiResponseHelper.populateOwner(groupResponse, group); groupResponse.setObjectName("instancegroup"); return groupResponse; } @Override public InstanceGroupJoinVO newInstanceGroupView(final InstanceGroup group) { final SearchCriteria<InstanceGroupJoinVO> sc = vrIdSearch.create(); sc.setParameters("id", group.getId()); final List<InstanceGroupJoinVO> grps = searchIncludingRemoved(sc, null, null, false); assert grps != null && grps.size() == 1 : "No vm group found for group id " + group.getId(); return grps.get(0); } }
923d0fd1030231654d382ac0793694153f0134d2
370
java
Java
src/main/java/se/citerus/dddsample/domain/model/location/LocationRepository.java
wowojyc/dddsample-core
1dd4a74cf35f18d89a61c7cbba6969d8d047900b
[ "MIT" ]
4,184
2015-02-05T03:05:30.000Z
2022-03-31T08:56:07.000Z
src/main/java/se/citerus/dddsample/domain/model/location/LocationRepository.java
chengUFO/dddsample-core
3576f879858f3ea5348a9e62c8f4ad296ff659f7
[ "MIT" ]
22
2015-09-18T10:34:04.000Z
2022-03-04T22:49:31.000Z
src/main/java/se/citerus/dddsample/domain/model/location/LocationRepository.java
chengUFO/dddsample-core
3576f879858f3ea5348a9e62c8f4ad296ff659f7
[ "MIT" ]
1,354
2015-09-18T11:25:55.000Z
2022-03-31T16:55:45.000Z
16.086957
51
0.659459
1,000,158
package se.citerus.dddsample.domain.model.location; import java.util.List; public interface LocationRepository { /** * Finds a location using given unlocode. * * @param unLocode UNLocode. * @return Location. */ Location find(UnLocode unLocode); /** * Finds all locations. * * @return All locations. */ List<Location> findAll(); }
923d1038beb2dc7768f86cf801d2910300ffd919
3,306
java
Java
Batch/org.egovframe.rte.bat.core/src/main/java/org/egovframe/rte/bat/exception/EgovBatchException.java
Pinepond/egovframe-runtime
1dd7aaaf859243030c545c251e848a6c145ee4be
[ "Apache-2.0" ]
8
2021-02-16T10:31:42.000Z
2022-03-28T02:16:09.000Z
Batch/org.egovframe.rte.bat.core/src/main/java/org/egovframe/rte/bat/exception/EgovBatchException.java
Pinepond/egovframe-runtime
1dd7aaaf859243030c545c251e848a6c145ee4be
[ "Apache-2.0" ]
17
2020-11-11T08:15:14.000Z
2022-01-04T16:48:47.000Z
Batch/org.egovframe.rte.bat.core/src/main/java/org/egovframe/rte/bat/exception/EgovBatchException.java
Pinepond/egovframe-runtime
1dd7aaaf859243030c545c251e848a6c145ee4be
[ "Apache-2.0" ]
29
2021-02-16T10:32:01.000Z
2022-03-30T03:56:58.000Z
29.517857
127
0.734725
1,000,159
/* * Copyright 2014 MOSPA(Ministry of Security and Public Administration). * * 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.egovframe.rte.bat.exception; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.egovframe.rte.fdl.cmmn.exception.BaseRuntimeException; /** * EgovBatchException 클래스 * 표준프레임워크 베치에서 Database 기반에서 Exception Code 기반으로 에러 메세지 기반으로 Exception을 처리하는 class * * @author 장동한 * @since 2017.12.01 * @version 1.0 * <pre> * 개정이력(Modification Information) * * 수정일 수정자 수정내용 * ---------------------------------------------- * 2017.12.01 장동한 최초 생성 * 2017.12.17 장동한 sql 설정 기능 추가(생성자 파라미터 방식) * </pre> */ public class EgovBatchException extends BaseRuntimeException { /** serial id */ private static final long serialVersionUID = -7642174304081691230L; /** sql */ private String sEXCEPTION_MESSAGE_SQL = "SELECT EX_MESSAGE FROM BATCH_EXCEPTION_MESSAGE WHERE EX_KEY = ?"; /** * 에러코드 코드 SQL Getter * @return String EXCEPTION MESSAGE SQL */ public String getExceptionMessageSql() { return sEXCEPTION_MESSAGE_SQL; } /** * 에러코드 코드 SQL Setter * @param sEXCEPTION_MESSAGE_SQL EXCEPTION MESSAGE SQL */ public void setExceptionMessageSql(String sEXCEPTION_MESSAGE_SQL) { this.sEXCEPTION_MESSAGE_SQL = sEXCEPTION_MESSAGE_SQL; } /** * EgovBatchException 생성자. * @param dataSource 데이터소스 * @param messageKey 메세지키 */ public EgovBatchException(DataSource dataSource, String messageKey) { this.messageKey = messageKey; this.message = getExceptionMessageSelect(dataSource); this.messageParameters = null; this.wrappedException = null; } /** * EgovBatchException 생성자. * @param dataSource 데이터소스 * @param messageKey 메세지키 * @param messageSql 사용자 정의 SQL */ public EgovBatchException(DataSource dataSource, String messageKey, String messageSql) { this.messageKey = messageKey; this.sEXCEPTION_MESSAGE_SQL = messageSql; this.message = getExceptionMessageSelect(dataSource); this.messageParameters = null; this.wrappedException = null; } /** * EgovBatchException 생성자. * @param dataSource 데이터소스 * @param messageKey 메세지키 * @param wrappedException 에러객체 */ public EgovBatchException(DataSource dataSource, String messageKey, Exception wrappedException) { this.messageKey = messageKey; this.message = getExceptionMessageSelect(dataSource); this.wrappedException = wrappedException; this.messageParameters = null; this.wrappedException = null; } /** * 데이터베이스에서 코드에대한 메세지를 가져온다. * @param dataSource 데이터소스 * @return String 에러메세지 */ private String getExceptionMessageSelect(DataSource dataSource){ return (String)(new JdbcTemplate(dataSource)).queryForObject(sEXCEPTION_MESSAGE_SQL, new Object[]{messageKey}, String.class); } }
923d10c300846d913554cc21781dfac7778ddff3
599
java
Java
common/src/main/java/org/kakara/core/common/annotations/Environment.java
kakaragame/core
495d5037e3eebc0c3c8a55218cbf1aaaac49e959
[ "MIT" ]
4
2020-01-27T01:25:10.000Z
2020-02-10T01:20:24.000Z
common/src/main/java/org/kakara/core/common/annotations/Environment.java
kakaragame/core
495d5037e3eebc0c3c8a55218cbf1aaaac49e959
[ "MIT" ]
29
2020-03-05T23:33:56.000Z
2022-02-09T10:44:15.000Z
common/src/main/java/org/kakara/core/common/annotations/Environment.java
kakaragame/core
495d5037e3eebc0c3c8a55218cbf1aaaac49e959
[ "MIT" ]
4
2020-11-28T11:35:13.000Z
2021-01-17T19:48:36.000Z
28.52381
88
0.744574
1,000,160
package org.kakara.core.common.annotations; import org.kakara.core.common.EnvType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * This will state that this method/class only works on a specific GameType. * Not all classes or methods are compatible with this, check the classes documentation. */ @Retention(RetentionPolicy.RUNTIME) public @interface Environment { /** * @return the GameType which the applied-to method supports. * If this value is null, the applied-to method will work on all game types. */ EnvType value(); }
923d117e9c7e4c1b7ea58ce8fb2db8ad0c417c75
8,379
java
Java
halyard-config/src/main/java/com/netflix/spinnaker/halyard/config/model/v1/providers/kubernetes/KubernetesAccount.java
titirigaiulian/halyard
e29305ef0165a630eccd23a897ebaba5be6bfb90
[ "Apache-2.0" ]
307
2016-09-28T00:30:04.000Z
2022-03-15T10:58:41.000Z
halyard-config/src/main/java/com/netflix/spinnaker/halyard/config/model/v1/providers/kubernetes/KubernetesAccount.java
titirigaiulian/halyard
e29305ef0165a630eccd23a897ebaba5be6bfb90
[ "Apache-2.0" ]
789
2016-09-28T13:09:58.000Z
2022-03-11T01:38:54.000Z
halyard-config/src/main/java/com/netflix/spinnaker/halyard/config/model/v1/providers/kubernetes/KubernetesAccount.java
titirigaiulian/halyard
e29305ef0165a630eccd23a897ebaba5be6bfb90
[ "Apache-2.0" ]
855
2016-09-26T18:05:20.000Z
2022-03-28T18:34:05.000Z
32.988189
100
0.736365
1,000,161
/* * Copyright 2016 Google, 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.netflix.spinnaker.halyard.config.model.v1.providers.kubernetes; import com.fasterxml.jackson.annotation.JsonProperty; import com.netflix.spinnaker.halyard.config.config.v1.ArtifactSourcesConfig; import com.netflix.spinnaker.halyard.config.model.v1.node.DeploymentConfiguration; import com.netflix.spinnaker.halyard.config.model.v1.node.LocalFile; import com.netflix.spinnaker.halyard.config.model.v1.node.SecretFile; import com.netflix.spinnaker.halyard.config.model.v1.node.ValidForSpinnakerVersion; import com.netflix.spinnaker.halyard.config.model.v1.providers.containers.ContainerAccount; import java.util.ArrayList; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; import org.apache.commons.lang3.StringUtils; @Data @EqualsAndHashCode(callSuper = true) public class KubernetesAccount extends ContainerAccount implements Cloneable { @ValidForSpinnakerVersion( lowerBound = "", tooLowMessage = "", upperBound = "1.21.0", tooHighMessage = "The legacy (V1) Kubernetes provider is now deprecated. All accounts will " + "now be wired as standard (V2) accounts, and providerVersion can be removed from " + "all configured accounts.") ProviderVersion providerVersion = ProviderVersion.V2; String context; String cluster; String user; @ValidForSpinnakerVersion( lowerBound = "1.5.0", tooLowMessage = "Spinnaker does not support configuring this behavior before that version.") Boolean configureImagePullSecrets; Boolean serviceAccount; int cacheThreads = 1; Long cacheIntervalSeconds; List<String> namespaces = new ArrayList<>(); List<String> omitNamespaces = new ArrayList<>(); @ValidForSpinnakerVersion( lowerBound = "1.7.0", tooLowMessage = "Configuring kind caching behavior is not supported yet.") List<String> kinds = new ArrayList<>(); @ValidForSpinnakerVersion( lowerBound = "1.7.0", tooLowMessage = "Configuring kind caching behavior is not supported yet.") List<String> omitKinds = new ArrayList<>(); @ValidForSpinnakerVersion( lowerBound = "1.6.0", tooLowMessage = "Custom kinds and resources are not supported yet.") List<CustomKubernetesResource> customResources = new ArrayList<>(); @ValidForSpinnakerVersion( lowerBound = "1.8.0", tooLowMessage = "Caching policies are not supported yet.") List<KubernetesCachingPolicy> cachingPolicies = new ArrayList<>(); @LocalFile @SecretFile String kubeconfigFile; String kubeconfigContents; String kubectlPath; Integer kubectlRequestTimeoutSeconds; Boolean checkPermissionsOnStartup; RawResourcesEndpointConfig rawResourcesEndpointConfig = new RawResourcesEndpointConfig(); Boolean cacheAllApplicationRelationships; @ValidForSpinnakerVersion( lowerBound = "1.12.0", tooLowMessage = "Live manifest mode not available prior to 1.12.0.", upperBound = "1.23.0", tooHighMessage = "Live manifest mode no longer necessary as of 1.23.0.") Boolean liveManifestCalls; // Without the annotations, these are written as `oauthServiceAccount` and `oauthScopes`, // respectively. @JsonProperty("oAuthServiceAccount") @LocalFile @SecretFile String oAuthServiceAccount; @JsonProperty("oAuthScopes") List<String> oAuthScopes; String namingStrategy; String skin; @JsonProperty("onlySpinnakerManaged") Boolean onlySpinnakerManaged; Boolean debug; public boolean usesServiceAccount() { return serviceAccount != null && serviceAccount; } public String getKubeconfigFile() { if (usesServiceAccount()) { return null; } if (kubeconfigFile == null || kubeconfigFile.isEmpty()) { return System.getProperty("user.home") + "/.kube/config"; } else { return kubeconfigFile; } } @Override public void makeBootstrappingAccount(ArtifactSourcesConfig artifactSourcesConfig) { super.makeBootstrappingAccount(artifactSourcesConfig); DeploymentConfiguration deploymentConfiguration = parentOfType(DeploymentConfiguration.class); String location = StringUtils.isEmpty(deploymentConfiguration.getDeploymentEnvironment().getLocation()) ? "spinnaker" : deploymentConfiguration.getDeploymentEnvironment().getLocation(); // These changes are only surfaced in the account used by the bootstrapping clouddriver, // the user's clouddriver will be unchanged. if (!namespaces.isEmpty() && !namespaces.contains(location)) { namespaces.add(location); } if (!omitNamespaces.isEmpty() && omitNamespaces.contains(location)) { omitNamespaces.remove(location); } } @Data public static class CustomKubernetesResource { String kubernetesKind; String spinnakerKind; boolean versioned = false; } @Data public static class KubernetesCachingPolicy { String kubernetesKind; int maxEntriesPerAgent; } @Data public static class RawResourcesEndpointConfig { @JsonProperty("kindExpressions") List<String> kindExpressions; @JsonProperty("omitKindExpressions") List<String> omitKindExpressions; @JsonProperty("kindExpressions") public List<String> getKindExpressions() { return this.kindExpressions; } public void setKindExpressions(List<String> expressions) { this.kindExpressions = expressions; } @JsonProperty("omitKindExpressions") public List<String> getOmitKindExpressions() { return this.omitKindExpressions; } public void setOmitKindExpressions(List<String> expressions) { this.omitKindExpressions = expressions; } } @JsonProperty("rawResourcesEndpointConfig") public RawResourcesEndpointConfig getRawResourcesEndpointConfig() { return rawResourcesEndpointConfig; } // These six methods exist for backwards compatibility. Versions of Halyard prior to 1.22 would // write this field out twice: to 'oAuthScopes' and to 'oauthScopes'. Whichever came last in the // file would end up taking precedence. These methods replicate that behavior during parsing, but // will only write out 'oAuthScopes' during serialization. They can be deleted after a few months // (at which point Lombok will generate the first four automatically). If you're reading this in // 2020 or later, you can definitely delete these (and also: whoah, the future is probably so fun, // how are those flying cars working out?) @JsonProperty("oAuthScopes") public List<String> getOAuthScopes() { return oAuthScopes; } @JsonProperty("oAuthScopes") public void setOAuthScopes(List<String> oAuthScopes) { this.oAuthScopes = oAuthScopes; } @JsonProperty("oAuthServiceAccount") public String getOAuthServiceAccount() { return oAuthServiceAccount; } @JsonProperty("oAuthServiceAccount") public void setOAuthServiceAccount(String oAuthServiceAccount) { this.oAuthServiceAccount = oAuthServiceAccount; } @JsonProperty("oauthScopes") public void setOauthScopes(List<String> oAuthScopes) { this.oAuthScopes = oAuthScopes; } @JsonProperty("oauthServiceAccount") public void setOauthServiceAccount(String oAuthServiceAccount) { this.oAuthServiceAccount = oAuthServiceAccount; } /** * @deprecated All ProviderVersion-related logic will be removed from Clouddriver by Spinnaker * 1.22. We will continue to support this enum in Halyard so that we can notify users with * this field configured that it is no longer read. */ @Deprecated public enum ProviderVersion { V1("v1"), V2("v2"); private final String name; ProviderVersion(String name) { this.name = name; } @Override public String toString() { return this.name; } } }
923d12394b3542d82d8ab84392bb8d708f6e220a
373
java
Java
gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/SkuImagesMapper.java
Tobeeey9426/gmall
1082d7f4662f30f1923bbc26b616baf18e328091
[ "Apache-2.0" ]
null
null
null
gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/SkuImagesMapper.java
Tobeeey9426/gmall
1082d7f4662f30f1923bbc26b616baf18e328091
[ "Apache-2.0" ]
null
null
null
gmall-pms/src/main/java/com/atguigu/gmall/pms/mapper/SkuImagesMapper.java
Tobeeey9426/gmall
1082d7f4662f30f1923bbc26b616baf18e328091
[ "Apache-2.0" ]
null
null
null
20.722222
70
0.764075
1,000,162
package com.atguigu.gmall.pms.mapper; import com.atguigu.gmall.pms.entity.SkuImagesEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * sku图片 * * @author Tobeey * @email lyhxr@example.com * @date 2020-12-08 13:47:26 */ @Mapper public interface SkuImagesMapper extends BaseMapper<SkuImagesEntity> { }
923d137f295e6854060a26fe1e19501266c56b2e
7,118
java
Java
src/main/java/dev/cheun/daos/AppUserDaoPostgres.java
dcheun/2102GCP-P1
b5f446b1f64c68861160a3af4362d009e77023be
[ "MIT" ]
null
null
null
src/main/java/dev/cheun/daos/AppUserDaoPostgres.java
dcheun/2102GCP-P1
b5f446b1f64c68861160a3af4362d009e77023be
[ "MIT" ]
null
null
null
src/main/java/dev/cheun/daos/AppUserDaoPostgres.java
dcheun/2102GCP-P1
b5f446b1f64c68861160a3af4362d009e77023be
[ "MIT" ]
null
null
null
41.383721
95
0.548188
1,000,163
package dev.cheun.daos; import dev.cheun.entities.AppUser; import dev.cheun.exceptions.NotAuthenticatedException; import dev.cheun.exceptions.NotFoundException; import dev.cheun.utils.AppUtil; import dev.cheun.utils.ConnectionUtil; import org.apache.log4j.Logger; import java.sql.*; import java.util.HashSet; import java.util.Set; public class AppUserDaoPostgres implements AppUserDAO { private static final Logger logger = Logger.getLogger(AppUserDaoPostgres.class.getName()); @Override public AppUser createAppUser(AppUser appUser) { // Try with resources syntax. // Java will always close the object to prevent resource leaks. try (Connection conn = ConnectionUtil.createConnection()) { String sql = "INSERT INTO app_user " + "(fname, lname, email, user_role, pw) " + "VALUES (?, ?, ?, ?, " + "crypt(?, gen_salt('bf')))"; PreparedStatement ps = conn.prepareStatement( sql, Statement.RETURN_GENERATED_KEYS); // Set the field params. ps.setString(1, appUser.getFname()); ps.setString(2, appUser.getLname()); ps.setString(3, appUser.getEmail()); ps.setInt(4, appUser.getRoleId()); ps.setString(5, appUser.getPw()); ps.execute(); // Return the val of the generated keys. ResultSet rs = ps.getGeneratedKeys(); rs.next(); int key = rs.getInt("id"); appUser.setId(key); logger.info("createAppUser: " + appUser); return appUser; } catch (SQLException e) { AppUtil.logException(logger, e, "createAppUser: Unable to create"); return null; } } @Override public Set<AppUser> getAllAppUsers() { try (Connection conn = ConnectionUtil.createConnection()) { String sql = "SELECT * FROM app_user"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); Set<AppUser> appUsers = new HashSet<>(); // While there exist records, create a new instance and store // the information into the new instance. while (rs.next()) { AppUser appUser = new AppUser(); appUser.setId(rs.getInt("id")); appUser.setFname(rs.getString("fname")); appUser.setLname(rs.getString("lname")); appUser.setEmail(rs.getString("email")); appUser.setRoleId(rs.getInt("user_role")); appUsers.add(appUser); } logger.info("getAllAppUsers: size=" + appUsers.size()); return appUsers; } catch (SQLException e) { AppUtil.logException(logger, e, "getAllAppUsers: Unable to retrieve"); return null; } } @Override public AppUser getAppUserById(int id) { try (Connection conn = ConnectionUtil.createConnection()) { String sql = "SELECT * FROM app_user WHERE id = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (!rs.next()) { throw new NotFoundException("No such user exists"); } AppUser appUser = new AppUser(); appUser.setId(rs.getInt("id")); appUser.setFname(rs.getString("fname")); appUser.setLname(rs.getString("lname")); appUser.setEmail(rs.getString("email")); appUser.setRoleId(rs.getInt("user_role")); logger.info("getAppUserById: id=" + id); return appUser; } catch (SQLException e) { AppUtil.logException(logger, e, "getAppUserById: Unable to get record with id=" + id); return null; } } @Override public AppUser authenticate(AppUser appUser) { try(Connection conn = ConnectionUtil.createConnection()) { String sql = "SELECT * FROM app_user WHERE email = ? and " + "pw = crypt(?, pw)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, appUser.getEmail()); ps.setString(2, appUser.getPw()); ResultSet rs = ps.executeQuery(); if (!rs.next()) { logger.warn("authenticate: Failed to authenticate: " + appUser); throw new NotAuthenticatedException("Failed to authenticate user"); } AppUser authedUser = new AppUser(); authedUser.setId(rs.getInt("id")); authedUser.setFname(rs.getString("fname")); authedUser.setLname(rs.getString("lname")); authedUser.setEmail(rs.getString("email")); authedUser.setRoleId(rs.getInt("user_role")); logger.info("authenticate: " + appUser); return authedUser; } catch (SQLException e) { AppUtil.logException(logger, e, "authenticate: Unable to authenticate user"); return null; } } @Override public AppUser updateAppUser(AppUser appUser) { try (Connection conn = ConnectionUtil.createConnection()) { String sql = "UPDATE app_user " + "SET fname = ?, lname = ?, email = ?, user_role = ? " + "WHERE id = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, appUser.getFname()); ps.setString(2, appUser.getLname()); ps.setString(3, appUser.getEmail()); ps.setInt(4, appUser.getRoleId()); ps.setInt(5, appUser.getId()); int rowCount = ps.executeUpdate(); if (rowCount == 0) { throw new NotFoundException("No such user exists"); } logger.info("updateAppUser: " + appUser); return appUser; } catch (SQLException e) { AppUtil.logException(logger, e, "updateAppUser: Unable to update user"); return null; } } @Override public boolean deleteAppUserById(int id) { try (Connection conn = ConnectionUtil.createConnection()) { String sql = "DELETE FROM app_user WHERE id = ?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, id); int rowCount = ps.executeUpdate(); if (rowCount == 0) { throw new NotFoundException("Unable to delete: No such user exists"); } logger.info("deleteAppUserById: id=" + id); return true; } catch (SQLException e) { AppUtil.logException(logger, e, "deleteAppUserById: Unable to delete user with id=" + id); return false; } } }
923d13cd5ec14863c99974bc8ebec49772cb29f7
23,389
java
Java
modules/interface-java-jaxws/src/main/java/org/apache/tuscany/sca/interfacedef/java/jaxws/BaseBeanGenerator.java
apache/tuscany-sca-2.x
89f2d366d4b0869a4e42ff265ccf4503dda4dc8b
[ "Apache-2.0" ]
18
2015-01-17T17:09:47.000Z
2021-11-10T16:04:56.000Z
modules/interface-java-jaxws/src/main/java/org/apache/tuscany/sca/interfacedef/java/jaxws/BaseBeanGenerator.java
apache/tuscany-sca-2.x
89f2d366d4b0869a4e42ff265ccf4503dda4dc8b
[ "Apache-2.0" ]
null
null
null
modules/interface-java-jaxws/src/main/java/org/apache/tuscany/sca/interfacedef/java/jaxws/BaseBeanGenerator.java
apache/tuscany-sca-2.x
89f2d366d4b0869a4e42ff265ccf4503dda4dc8b
[ "Apache-2.0" ]
18
2015-08-26T15:18:06.000Z
2021-11-10T16:04:45.000Z
41.033333
137
0.583009
1,000,164
/* * 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.tuscany.sca.interfacedef.java.jaxws; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import javax.xml.bind.annotation.XmlAttachmentRef; import javax.xml.bind.annotation.XmlList; import javax.xml.bind.annotation.XmlMimeType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.ws.Holder; import org.apache.tuscany.sca.databinding.jaxb.XMLAdapterExtensionPoint; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; public abstract class BaseBeanGenerator implements Opcodes { private static final Map<String, String> COLLECTION_CLASSES = new HashMap<String, String>(); static { COLLECTION_CLASSES.put("Ljava/util/Collection;", "java/util/ArrayList"); COLLECTION_CLASSES.put("Ljava/util/List;", "java/util/ArrayList"); COLLECTION_CLASSES.put("Ljava/util/Set;", "java/util/HashSet"); COLLECTION_CLASSES.put("Ljava/util/Queue;", "java/util/LinkedList"); } private final static Class[] KNOWN_JAXB_ANNOTATIONS = {XmlAttachmentRef.class, XmlMimeType.class, XmlJavaTypeAdapter.class, XmlList.class}; private static final Map<String, String> JAVA_KEYWORDS = new HashMap<String, String>(); static { JAVA_KEYWORDS.put("abstract", "_abstract"); JAVA_KEYWORDS.put("assert", "_assert"); JAVA_KEYWORDS.put("boolean", "_boolean"); JAVA_KEYWORDS.put("break", "_break"); JAVA_KEYWORDS.put("byte", "_byte"); JAVA_KEYWORDS.put("case", "_case"); JAVA_KEYWORDS.put("catch", "_catch"); JAVA_KEYWORDS.put("char", "_char"); JAVA_KEYWORDS.put("class", "_class"); JAVA_KEYWORDS.put("const", "_const"); JAVA_KEYWORDS.put("continue", "_continue"); JAVA_KEYWORDS.put("default", "_default"); JAVA_KEYWORDS.put("do", "_do"); JAVA_KEYWORDS.put("double", "_double"); JAVA_KEYWORDS.put("else", "_else"); JAVA_KEYWORDS.put("extends", "_extends"); JAVA_KEYWORDS.put("false", "_false"); JAVA_KEYWORDS.put("final", "_final"); JAVA_KEYWORDS.put("finally", "_finally"); JAVA_KEYWORDS.put("float", "_float"); JAVA_KEYWORDS.put("for", "_for"); JAVA_KEYWORDS.put("goto", "_goto"); JAVA_KEYWORDS.put("if", "_if"); JAVA_KEYWORDS.put("implements", "_implements"); JAVA_KEYWORDS.put("import", "_import"); JAVA_KEYWORDS.put("instanceof", "_instanceof"); JAVA_KEYWORDS.put("int", "_int"); JAVA_KEYWORDS.put("interface", "_interface"); JAVA_KEYWORDS.put("long", "_long"); JAVA_KEYWORDS.put("native", "_native"); JAVA_KEYWORDS.put("new", "_new"); JAVA_KEYWORDS.put("null", "_null"); JAVA_KEYWORDS.put("package", "_package"); JAVA_KEYWORDS.put("private", "_private"); JAVA_KEYWORDS.put("protected", "_protected"); JAVA_KEYWORDS.put("public", "_public"); JAVA_KEYWORDS.put("return", "_return"); JAVA_KEYWORDS.put("short", "_short"); JAVA_KEYWORDS.put("static", "_static"); JAVA_KEYWORDS.put("strictfp", "_strictfp"); JAVA_KEYWORDS.put("super", "_super"); JAVA_KEYWORDS.put("switch", "_switch"); JAVA_KEYWORDS.put("synchronized", "_synchronized"); JAVA_KEYWORDS.put("this", "_this"); JAVA_KEYWORDS.put("throw", "_throw"); JAVA_KEYWORDS.put("throws", "_throws"); JAVA_KEYWORDS.put("transient", "_transient"); JAVA_KEYWORDS.put("true", "_true"); JAVA_KEYWORDS.put("try", "_try"); JAVA_KEYWORDS.put("void", "_void"); JAVA_KEYWORDS.put("volatile", "_volatile"); JAVA_KEYWORDS.put("while", "_while"); JAVA_KEYWORDS.put("enum", "_enum"); } protected static final Map<Object, WeakReference<Class<?>>> generatedClasses = Collections.synchronizedMap(new WeakHashMap<Object, WeakReference<Class<?>>>()); protected XMLAdapterExtensionPoint xmlAdapters; public byte[] defineClass(ClassWriter cw, String classDescriptor, String classSignature, String namespace, String name, BeanProperty[] properties) { // Declare the class declareClass(cw, classDescriptor); // Compute the propOrder String[] propOrder = null; if (properties != null && properties.length > 0) { int size = properties.length; propOrder = new String[size]; for (int i = 0; i < size; i++) { propOrder[i] = getFieldName(properties[i].getName()); } } // Annotate the class annotateClass(cw, name, namespace, propOrder); // Declare the default constructor declareConstructor(cw, classSignature); if (properties != null) { for (BeanProperty p : properties) { boolean isElement = p.isElement() && (!Map.class.isAssignableFrom(p.getType())); String xmlAdapterClassSignature = null; if (xmlAdapters != null) { Class<?> adapterClass = xmlAdapters.getAdapter(p.getType()); if (adapterClass != null) { xmlAdapterClassSignature = CodeGenerationHelper.getSignature(adapterClass); } } declareProperty(cw, classDescriptor, classSignature, p.getName(), p.getSignature(), p .getGenericSignature(), isElement, p.isNillable(), xmlAdapterClassSignature, p.getJaxbAnnotaions()); } } // Close the generation cw.visitEnd(); return cw.toByteArray(); } protected static boolean isHolder(java.lang.reflect.Type type) { if (type instanceof ParameterizedType) { Class<?> cls = CodeGenerationHelper.getErasure(type); return cls == Holder.class; } return false; } protected static java.lang.reflect.Type getHolderValueType(java.lang.reflect.Type paramType) { if (paramType instanceof ParameterizedType) { ParameterizedType p = (ParameterizedType)paramType; Class<?> cls = CodeGenerationHelper.getErasure(p); if (cls == Holder.class) { return p.getActualTypeArguments()[0]; } } return paramType; } protected void declareProperty(ClassWriter cw, String classDescriptor, String classSignature, String propName, String propClassSignature, String propTypeSignature, boolean isElement, boolean isNillable, String xmlAdapterClassSignature, List<Annotation> jaxbAnnotations) { if (propClassSignature.equals(propTypeSignature)) { propTypeSignature = null; } declareField(cw, propName, propClassSignature, propTypeSignature, isElement, isNillable, xmlAdapterClassSignature, jaxbAnnotations); decalreGetter(cw, classDescriptor, classSignature, propName, propClassSignature, propTypeSignature); declareSetter(cw, classDescriptor, classSignature, propName, propClassSignature, propTypeSignature); } protected String getFieldName(String propName) { String name = JAVA_KEYWORDS.get(propName); return name != null ? name : propName; } protected void declareField(ClassWriter cw, String propName, String propClassSignature, String propTypeSignature, boolean isElement, boolean isNillable, String xmlAdapterClassSignature, List<Annotation> jaxbAnnotations) { FieldVisitor fv; AnnotationVisitor av0; fv = cw.visitField(ACC_PROTECTED, getFieldName(propName), propClassSignature, propTypeSignature, null); // For Map property, we cannot have the XmlElement annotation if (isElement && xmlAdapterClassSignature == null) { av0 = fv.visitAnnotation("Ljavax/xml/bind/annotation/XmlElement;", true); av0.visit("name", propName); av0.visit("namespace", ""); // TUSCANY-3283 - force not nillable if it isn't if (isNillable) { av0.visit("nillable", Boolean.TRUE); } else { av0.visit("nillable", Boolean.FALSE); } // FIXME: // av0.visit("required", Boolean.FALSE); av0.visitEnd(); } if (xmlAdapterClassSignature != null) { av0 = fv.visitAnnotation("Ljavax/xml/bind/annotation/XmlAnyElement;", true); av0.visit("lax", Boolean.TRUE); av0.visitEnd(); av0 = fv.visitAnnotation("Ljavax/xml/bind/annotation/adapters/XmlJavaTypeAdapter;", true); av0.visit("value", org.objectweb.asm.Type.getType(xmlAdapterClassSignature)); av0.visitEnd(); } for (Annotation ann : jaxbAnnotations) { if (ann instanceof XmlMimeType) { AnnotationVisitor mime = fv.visitAnnotation("Ljavax/xml/bind/annotation/XmlMimeType;", true); mime.visit("value", ((XmlMimeType)ann).value()); mime.visitEnd(); } else if (ann instanceof XmlJavaTypeAdapter) { AnnotationVisitor ada = fv.visitAnnotation("Ljavax/xml/bind/annotation/adapters/XmlJavaTypeAdapter;", true); ada.visit("value", org.objectweb.asm.Type.getType(((XmlJavaTypeAdapter)ann).value())); ada.visit("type", org.objectweb.asm.Type.getType(((XmlJavaTypeAdapter)ann).type())); ada.visitEnd(); } else if (ann instanceof XmlAttachmentRef) { AnnotationVisitor att = fv.visitAnnotation("Ljavax/xml/bind/annotation/XmlAttachmentRef;", true); att.visitEnd(); } else if (ann instanceof XmlList) { AnnotationVisitor list = fv.visitAnnotation("Ljavax/xml/bind/annotation/XmlList;", true); list.visitEnd(); } } fv.visitEnd(); } protected void declareSetter(ClassWriter cw, String classDescriptor, String classSignature, String propName, String propClassSignature, String propTypeSignature) { if ("Ljava/util/List;".equals(propClassSignature)) { return; } MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "set" + capitalize(propName), "(" + propClassSignature + ")V", propTypeSignature == null ? null : "(" + propTypeSignature + ")V", null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); // mv.visitLineNumber(57, l0); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(CodeGenerationHelper.getLoadOPCode(propClassSignature), 1); mv.visitFieldInsn(PUTFIELD, classDescriptor, getFieldName(propName), propClassSignature); Label l1 = new Label(); mv.visitLabel(l1); // mv.visitLineNumber(58, l1); mv.visitInsn(RETURN); Label l2 = new Label(); mv.visitLabel(l2); mv.visitLocalVariable("this", classSignature, null, l0, l2, 0); mv.visitLocalVariable(getFieldName(propName), propClassSignature, propTypeSignature, l0, l2, 1); mv.visitMaxs(3, 3); mv.visitEnd(); } protected void decalreGetter(ClassWriter cw, String classDescriptor, String classSignature, String propName, String propClassSignature, String propTypeSignature) { String collectionImplClass = COLLECTION_CLASSES.get(propClassSignature); if (collectionImplClass != null) { decalreCollectionGetter(cw, classDescriptor, classSignature, propName, propClassSignature, propTypeSignature, collectionImplClass); return; } String getterName = ("Z".equals(propClassSignature) ? "is" : "get") + capitalize(propName); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, getterName, "()" + propClassSignature, propTypeSignature == null ? null : "()" + propTypeSignature, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); // mv.visitLineNumber(48, l0); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classDescriptor, getFieldName(propName), propClassSignature); mv.visitInsn(CodeGenerationHelper.getReturnOPCode(propClassSignature)); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", classSignature, null, l0, l1, 0); mv.visitMaxs(2, 1); mv.visitEnd(); } protected void decalreCollectionGetter(ClassWriter cw, String classDescriptor, String classSignature, String propName, String propClassSignature, String propTypeSignature, String collectionImplClass) { String getterName = "get" + capitalize(propName); String fieldName = getFieldName(propName); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, getterName, "()" + propClassSignature, propTypeSignature == null ? null : "()" + propTypeSignature, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitLineNumber(63, l0); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classDescriptor, fieldName, propClassSignature); Label l1 = new Label(); mv.visitJumpInsn(IFNONNULL, l1); Label l2 = new Label(); mv.visitLabel(l2); mv.visitLineNumber(64, l2); mv.visitVarInsn(ALOAD, 0); mv.visitTypeInsn(NEW, collectionImplClass); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, collectionImplClass, "<init>", "()V"); mv.visitFieldInsn(PUTFIELD, classDescriptor, fieldName, propClassSignature); mv.visitLabel(l1); mv.visitLineNumber(66, l1); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, classDescriptor, fieldName, propClassSignature); mv.visitInsn(ARETURN); Label l3 = new Label(); mv.visitLabel(l3); mv.visitLocalVariable("this", classSignature, null, l0, l3, 0); mv.visitMaxs(3, 1); mv.visitEnd(); } protected static String capitalize(String name) { if (name == null || name.length() == 0) { return name; } else { return Character.toUpperCase(name.charAt(0)) + name.substring(1); } } protected void declareConstructor(ClassWriter cw, String classSignature) { MethodVisitor mv; mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); // mv.visitLineNumber(37, l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitInsn(RETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", classSignature, null, l0, l1, 0); mv.visitMaxs(1, 1); mv.visitEnd(); } protected void declareClass(ClassWriter cw, String classDescriptor) { cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, classDescriptor, null, "java/lang/Object", null); } protected void annotateClass(ClassWriter cw, String name, String namespace, String[] propOrder) { AnnotationVisitor av0; // @XmlRootElement av0 = cw.visitAnnotation("Ljavax/xml/bind/annotation/XmlRootElement;", true); av0.visit("name", name); av0.visit("namespace", namespace); av0.visitEnd(); // @XmlAccessorType av0 = cw.visitAnnotation("Ljavax/xml/bind/annotation/XmlAccessorType;", true); av0.visitEnum("value", "Ljavax/xml/bind/annotation/XmlAccessType;", "FIELD"); av0.visitEnd(); // @XmlType av0 = cw.visitAnnotation("Ljavax/xml/bind/annotation/XmlType;", true); av0.visit("name", name); av0.visit("namespace", namespace); if (propOrder != null) { AnnotationVisitor pv = av0.visitArray("propOrder"); for (String p : propOrder) { pv.visit(null, p); } pv.visitEnd(); } av0.visitEnd(); } public Class<?> generate(String classDescriptor, String classSignature, String namespace, String name, BeanProperty[] properties, GeneratedClassLoader classLoader) { // The reflection code here allows for toleration of older versions of ASM. ClassWriter cw; try { Constructor<ClassWriter> c = ClassWriter.class.getConstructor(new Class[] {int.class}); Field f = ClassWriter.class.getField("COMPUTE_MAXS"); cw = c.newInstance(f.get(null)); } catch ( Exception ex ) { try { Constructor<ClassWriter> c = ClassWriter.class.getConstructor(new Class[] {boolean.class}); cw = c.newInstance(true); } catch ( Exception ex2 ) { throw new IllegalArgumentException(ex2); } } byte[] byteCode = defineClass(cw, classDescriptor, classSignature, namespace, name, properties); String className = classDescriptor.replace('/', '.'); Class<?> generated = classLoader.getGeneratedClass(className, byteCode); return generated; } public static class BeanProperty { private Class<?> type; private String namespace; private String name; private String signature; private String genericSignature; private List<Annotation> jaxbAnnotaions = new ArrayList<Annotation>(); private boolean element; private boolean nillable; public BeanProperty(String namespace, String name, Class<?> javaClass, Type type, boolean isElement) { super(); this.namespace = namespace; this.name = name; this.signature = CodeGenerationHelper.getJAXWSSignature(javaClass); this.type = javaClass; this.genericSignature = CodeGenerationHelper.getJAXWSSignature(type); this.element = isElement; // FIXME: How to test nillable? // this.nillable = (type instanceof GenericArrayType) || Collection.class.isAssignableFrom(javaClass) || javaClass.isArray(); // TUSCANY-2389: Set the nillable consistent with what wsgen produces this.nillable = javaClass.isArray(); } public String getName() { return name; } public String getSignature() { return signature; } public String getGenericSignature() { return genericSignature; } public Class<?> getType() { return type; } public List<Annotation> getJaxbAnnotaions() { return jaxbAnnotaions; } public String getNamespace() { return namespace; } public boolean isElement() { return element; } public boolean isNillable() { return nillable; } } public XMLAdapterExtensionPoint getXmlAdapters() { return xmlAdapters; } public void setXmlAdapters(XMLAdapterExtensionPoint xmlAdapters) { this.xmlAdapters = xmlAdapters; } protected static <T extends Annotation> T findAnnotation(Annotation[] anns, Class<T> annotationClass) { for (Annotation a : anns) { if (a.annotationType() == annotationClass) { return annotationClass.cast(a); } } return null; } protected static List<Annotation> findJAXBAnnotations(Annotation[] anns) { List<Annotation> jaxbAnnotation = new ArrayList<Annotation>(); for (Class<? extends Annotation> c : KNOWN_JAXB_ANNOTATIONS) { Annotation a = findAnnotation(anns, c); if (a != null) { jaxbAnnotation.add(a); } } return jaxbAnnotation; } protected List<Annotation> findJAXBAnnotations(Method method) { List<Annotation> anns = new ArrayList<Annotation>(); for (Class<? extends Annotation> c : KNOWN_JAXB_ANNOTATIONS) { Annotation ann = method.getAnnotation(c); if (ann != null) { anns.add(ann); } } return anns; } }
923d13d34fec19c82abe6662500c1023826a9c05
2,285
java
Java
addressbook-web-tests/src/test/java/ru/stq/java/addressbook/tests/ContactPhoneTest.java
Ovchinnickova2016/JAVA
c7c83c9bb72f6285fee131cf9ba664fbf1e97cb7
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stq/java/addressbook/tests/ContactPhoneTest.java
Ovchinnickova2016/JAVA
c7c83c9bb72f6285fee131cf9ba664fbf1e97cb7
[ "Apache-2.0" ]
null
null
null
addressbook-web-tests/src/test/java/ru/stq/java/addressbook/tests/ContactPhoneTest.java
Ovchinnickova2016/JAVA
c7c83c9bb72f6285fee131cf9ba664fbf1e97cb7
[ "Apache-2.0" ]
null
null
null
38.2
120
0.724695
1,000,165
package ru.stq.java.addressbook.tests; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stq.java.addressbook.model.ContactsData; import ru.stq.java.addressbook.model.Groups; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class ContactPhoneTest extends TestBase { Groups groups = app.db().groups(); @BeforeMethod public void ensurePreconditions(){ if (app.db().contacts().size()==0){ app.contact().gotoContactPage(); app.contact().create(new ContactsData().withEmail("anpch@example.com").withEmail2("upchh@example.com") .withEmail3("dycjh@example.com").withFirstName("nastya").withLastName("Ovchinnickova").withMobilePhone("44423422") .withWorkPhone("231").withHomePhone("3232").withAddress("2 dd 3").inGroup(groups.iterator().next())); } } @Test public void testContactPhones(){ app.goTo().goToHomePage(); ContactsData contact = app.contact().all().iterator().next(); ContactsData contactInfoFromEditForm = app.contact().infoFromEditForm(contact); assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm))); assertThat(contact.getAllEmailes(), equalTo(mergeEmailes(contactInfoFromEditForm))); assertThat(contact.getAddress(), equalTo((contactInfoFromEditForm.getAddress()))); } private String mergePhones(ContactsData contact) { return Arrays.asList(contact.getHomePhone(), contact.getMobilePhone(), contact.getWorkPhone()) .stream().filter((s)->!s.equals("")) .map(ContactPhoneTest::cleaned) .collect(Collectors.joining("\n")); } private String mergeEmailes(ContactsData contact) { return Arrays.asList(contact.getEmail(), contact.getEmail2(), contact.getEmail3()) .stream().filter((s)->!s.equals("")) .map(ContactPhoneTest::cleanedEmailes) .collect(Collectors.joining("\n")); } public static String cleaned(String phone){ return phone.replaceAll("\\s", "").replaceAll("[-()]", ""); } public static String cleanedEmailes(String email){ return email.replaceAll("\\s", ""); } }
923d13f68f73ce168de3bfa275c98d76101873da
2,448
java
Java
app/src/main/java/com/sba/covid_19tracker/News/NewsAdapter.java
saif191020/covid-19-Tracker-
3b7852690047339f72a59dd9b903cf76b0669439
[ "Apache-2.0" ]
3
2020-05-16T23:37:50.000Z
2021-01-28T01:12:03.000Z
app/src/main/java/com/sba/covid_19tracker/News/NewsAdapter.java
saif191020/covid-19-Tracker-
3b7852690047339f72a59dd9b903cf76b0669439
[ "Apache-2.0" ]
1
2021-08-23T16:36:02.000Z
2021-08-23T18:21:28.000Z
app/src/main/java/com/sba/covid_19tracker/News/NewsAdapter.java
saif191020/covid-19-Tracker-App
3b7852690047339f72a59dd9b903cf76b0669439
[ "Apache-2.0" ]
null
null
null
30.6
97
0.690768
1,000,166
package com.sba.covid_19tracker.News; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.sba.covid_19tracker.News.model.Article; import com.sba.covid_19tracker.R; import java.util.List; public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> { Context context; List<Article> newsList; public NewsAdapter(Context context, List<Article> newsList) { this.context = context; this.newsList = newsList; } @NonNull @Override public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.news_list_item, parent, false); return new NewsViewHolder(view); } @Override public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) { final Article news = newsList.get(position); holder.source.setText(news.getSource().getName()); holder.title.setText(news.getTitle()); holder.decription.setText(news.getDescription()); Glide .with(context) .load(news.getUrlToImage()) .into(holder.newsImage); holder.readMore.setOnClickListener(view -> { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(news.getUrl())); context.startActivity(browserIntent); }); } @Override public int getItemCount() { return newsList.size(); } static class NewsViewHolder extends RecyclerView.ViewHolder { public TextView source, title, decription; public Button readMore; public ImageView newsImage; public NewsViewHolder(@NonNull View itemView) { super(itemView); source = itemView.findViewById(R.id.news_source_text); title = itemView.findViewById(R.id.news_title_text); decription = itemView.findViewById(R.id.news_description); readMore = itemView.findViewById(R.id.full_story_btn); newsImage = itemView.findViewById(R.id.news_img); } } }