blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c5e0b78a8e130012ea5ffe9539a0b07c0ed05bbd | 019690e6b657650164159f09c08ecd2cdf15a38c | /app/src/main/java/com/example/khwajabilal/structural_a8/AnalyzedModelView.java | b8e43bd0aaf27b5e90d6b1a71e64b98a4043a2ac | [] | no_license | khwajabilal/Structural-Analyst-App | d848bd5d35e824f5aa5f010ffa1895044161226a | 3d97c7bcab1ba07d28c3571ef690c9db95ccf864 | refs/heads/master | 2020-05-29T14:37:13.400977 | 2016-08-16T13:27:44 | 2016-08-16T13:27:44 | 65,821,884 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 852 | java | package com.example.khwajabilal.structural_a8;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import com.example.khwajabilal.structural_a8.Beam.Joint;
/**
* Created by KhwajaBilal on 7/16/2016.
*/
public class AnalyzedModelView extends View {
Paint paint1 = new Paint();
Paint paint2 = new Paint();
Paint paint3 = new Paint();
Paint paint4 = new Paint();
Coordinates modelCordinates;
Joint modelJointList;
public AnalyzedModelView(Context context) {
super(context);
paint1.setColor(Color.BLACK);
paint2.setColor(Color.RED);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawLine(0, 0, 20, 20, paint1);
canvas.drawLine(20, 0, 0, 20, paint1);
}
}
| [
"khw.bilal.93@gmail.com"
] | khw.bilal.93@gmail.com |
2241aee55521a29a68d59d8fd01106e8ad823ce6 | 11babced1f48d7a4d9353da64f278b25384d5acd | /CSEIII/StockHubWeb/src/VO/marketVO/SimpleInvestVO.java | 40d23ee00de9cca227398ddaa63d8263c279adfd | [] | no_license | Apocalpyse/NJU-SE3 | 08daf05f9f98569b892fa41cd706f7445eb9baf2 | 27ae6915830a4087d2eb9350257fb5513c6d8692 | refs/heads/master | 2020-03-11T02:04:58.892123 | 2018-04-16T08:43:37 | 2018-04-16T08:43:37 | 129,316,413 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 710 | java | package VO.marketVO;
/**
* Created by chenjin on 2017/6/8.
*/
public class SimpleInvestVO {
private String investID;
private String title;
private String author;
public SimpleInvestVO() {
}
public SimpleInvestVO(String investID, String title, String author) {
this.investID = investID;
this.title = title;
this.author = author;
}
public String getInvestID() {
return investID;
}
public void setInvestID(String investID) {
this.investID = investID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
| [
"2578931175@qq.com"
] | 2578931175@qq.com |
1e39724ebfd7df63dba19888f900b2a1d0f17245 | 6fc69fcdf2b1cb41ae2804e1a0a7a519ea10455c | /com/google/android/gms/internal/zzsa.java | 2b3c0bf2347e7c31b00cf0825a8ca5a60759cd27 | [] | no_license | earlisreal/aPPwareness | 2c168843f0bd32e3c885f9bab68917dd324991f0 | f538ef69f16099a85c2f1a8782d977a5715d65f4 | refs/heads/master | 2021-01-13T14:44:54.007944 | 2017-01-19T17:17:14 | 2017-01-19T17:17:14 | 79,504,981 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 29,911 | java | package com.google.android.gms.internal;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri.Builder;
import android.os.Build.VERSION;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.text.TextUtils;
import com.github.paolorotolo.appintro.BuildConfig;
import com.google.android.gms.common.internal.zzac;
import com.google.android.gms.common.util.zzn;
import java.io.Closeable;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
class zzsa extends zzru implements Closeable {
private static final String zzadt;
private static final String zzadu;
private final zza zzadv;
private final zztd zzadw;
private final zztd zzadx;
class zza extends SQLiteOpenHelper {
final /* synthetic */ zzsa zzady;
zza(zzsa com_google_android_gms_internal_zzsa, Context context, String str) {
this.zzady = com_google_android_gms_internal_zzsa;
super(context, str, null, 1);
}
private void zza(SQLiteDatabase sQLiteDatabase) {
int i = 1;
Set zzb = zzb(sQLiteDatabase, "hits2");
String[] strArr = new String[]{"hit_id", "hit_string", "hit_time", "hit_url"};
int i2 = 0;
while (i2 < 4) {
Object obj = strArr[i2];
if (zzb.remove(obj)) {
i2++;
} else {
String str = "Database hits2 is missing required column: ";
String valueOf = String.valueOf(obj);
throw new SQLiteException(valueOf.length() != 0 ? str.concat(valueOf) : new String(str));
}
}
if (zzb.remove("hit_app_id")) {
i = 0;
}
if (!zzb.isEmpty()) {
throw new SQLiteException("Database hits2 has extra columns");
} else if (i != 0) {
sQLiteDatabase.execSQL("ALTER TABLE hits2 ADD COLUMN hit_app_id INTEGER");
}
}
private boolean zza(SQLiteDatabase sQLiteDatabase, String str) {
Object e;
Throwable th;
Cursor cursor = null;
Cursor query;
try {
SQLiteDatabase sQLiteDatabase2 = sQLiteDatabase;
query = sQLiteDatabase2.query("SQLITE_MASTER", new String[]{"name"}, "name=?", new String[]{str}, null, null, null);
try {
boolean moveToFirst = query.moveToFirst();
if (query == null) {
return moveToFirst;
}
query.close();
return moveToFirst;
} catch (SQLiteException e2) {
e = e2;
try {
this.zzady.zzc("Error querying for table", str, e);
if (query != null) {
query.close();
}
return false;
} catch (Throwable th2) {
th = th2;
cursor = query;
if (cursor != null) {
cursor.close();
}
throw th;
}
}
} catch (SQLiteException e3) {
e = e3;
query = null;
this.zzady.zzc("Error querying for table", str, e);
if (query != null) {
query.close();
}
return false;
} catch (Throwable th3) {
th = th3;
if (cursor != null) {
cursor.close();
}
throw th;
}
}
private Set<String> zzb(SQLiteDatabase sQLiteDatabase, String str) {
Set<String> hashSet = new HashSet();
Cursor rawQuery = sQLiteDatabase.rawQuery(new StringBuilder(String.valueOf(str).length() + 22).append("SELECT * FROM ").append(str).append(" LIMIT 0").toString(), null);
try {
String[] columnNames = rawQuery.getColumnNames();
for (Object add : columnNames) {
hashSet.add(add);
}
return hashSet;
} finally {
rawQuery.close();
}
}
private void zzb(SQLiteDatabase sQLiteDatabase) {
int i = 0;
Set zzb = zzb(sQLiteDatabase, "properties");
String[] strArr = new String[]{"app_uid", "cid", "tid", "params", "adid", "hits_count"};
while (i < 6) {
Object obj = strArr[i];
if (zzb.remove(obj)) {
i++;
} else {
String str = "Database properties is missing required column: ";
String valueOf = String.valueOf(obj);
throw new SQLiteException(valueOf.length() != 0 ? str.concat(valueOf) : new String(str));
}
}
if (!zzb.isEmpty()) {
throw new SQLiteException("Database properties table has extra columns");
}
}
public SQLiteDatabase getWritableDatabase() {
if (this.zzady.zzadx.zzz(3600000)) {
SQLiteDatabase writableDatabase;
try {
writableDatabase = super.getWritableDatabase();
} catch (SQLiteException e) {
this.zzady.zzadx.start();
this.zzady.zzbS("Opening the database failed, dropping the table and recreating it");
this.zzady.getContext().getDatabasePath(this.zzady.zznV()).delete();
try {
writableDatabase = super.getWritableDatabase();
this.zzady.zzadx.clear();
} catch (SQLiteException e2) {
this.zzady.zze("Failed to open freshly created database", e2);
throw e2;
}
}
return writableDatabase;
}
throw new SQLiteException("Database open failed");
}
public void onCreate(SQLiteDatabase sQLiteDatabase) {
zzsp.zzbZ(sQLiteDatabase.getPath());
}
public void onOpen(SQLiteDatabase sQLiteDatabase) {
if (VERSION.SDK_INT < 15) {
Cursor rawQuery = sQLiteDatabase.rawQuery("PRAGMA journal_mode=memory", null);
try {
rawQuery.moveToFirst();
} finally {
rawQuery.close();
}
}
if (zza(sQLiteDatabase, "hits2")) {
zza(sQLiteDatabase);
} else {
sQLiteDatabase.execSQL(zzsa.zzadt);
}
if (zza(sQLiteDatabase, "properties")) {
zzb(sQLiteDatabase);
} else {
sQLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS properties ( app_uid INTEGER NOT NULL, cid TEXT NOT NULL, tid TEXT NOT NULL, params TEXT NOT NULL, adid INTEGER NOT NULL, hits_count INTEGER NOT NULL, PRIMARY KEY (app_uid, cid, tid)) ;");
}
}
public void onUpgrade(SQLiteDatabase sQLiteDatabase, int i, int i2) {
}
}
static {
zzadt = String.format("CREATE TABLE IF NOT EXISTS %s ( '%s' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, '%s' INTEGER NOT NULL, '%s' TEXT NOT NULL, '%s' TEXT NOT NULL, '%s' INTEGER);", new Object[]{"hits2", "hit_id", "hit_time", "hit_url", "hit_string", "hit_app_id"});
zzadu = String.format("SELECT MAX(%s) FROM %s WHERE 1;", new Object[]{"hit_time", "hits2"});
}
zzsa(zzrw com_google_android_gms_internal_zzrw) {
super(com_google_android_gms_internal_zzrw);
this.zzadw = new zztd(zznq());
this.zzadx = new zztd(zznq());
this.zzadv = new zza(this, com_google_android_gms_internal_zzrw.getContext(), zznV());
}
private static String zzS(Map<String, String> map) {
zzac.zzw(map);
Builder builder = new Builder();
for (Entry entry : map.entrySet()) {
builder.appendQueryParameter((String) entry.getKey(), (String) entry.getValue());
}
String encodedQuery = builder.build().getEncodedQuery();
return encodedQuery == null ? BuildConfig.FLAVOR : encodedQuery;
}
private long zza(String str, String[] strArr, long j) {
Cursor cursor = null;
try {
cursor = getWritableDatabase().rawQuery(str, strArr);
if (cursor.moveToFirst()) {
j = cursor.getLong(0);
if (cursor != null) {
cursor.close();
}
} else if (cursor != null) {
cursor.close();
}
return j;
} catch (SQLiteException e) {
zzd("Database error", str, e);
throw e;
} catch (Throwable th) {
if (cursor != null) {
cursor.close();
}
}
}
private long zzb(String str, String[] strArr) {
Cursor cursor = null;
try {
cursor = getWritableDatabase().rawQuery(str, strArr);
if (cursor.moveToFirst()) {
long j = cursor.getLong(0);
if (cursor != null) {
cursor.close();
}
return j;
}
throw new SQLiteException("Database returned empty set");
} catch (SQLiteException e) {
zzd("Database error", str, e);
throw e;
} catch (Throwable th) {
if (cursor != null) {
cursor.close();
}
}
}
private String zzd(zzst com_google_android_gms_internal_zzst) {
return com_google_android_gms_internal_zzst.zzps() ? zzns().zzoJ() : zzns().zzoK();
}
private static String zze(zzst com_google_android_gms_internal_zzst) {
zzac.zzw(com_google_android_gms_internal_zzst);
Builder builder = new Builder();
for (Entry entry : com_google_android_gms_internal_zzst.zzfz().entrySet()) {
String str = (String) entry.getKey();
if (!("ht".equals(str) || "qt".equals(str) || "AppUID".equals(str))) {
builder.appendQueryParameter(str, (String) entry.getValue());
}
}
String encodedQuery = builder.build().getEncodedQuery();
return encodedQuery == null ? BuildConfig.FLAVOR : encodedQuery;
}
private void zznU() {
int zzoT = zzns().zzoT();
long zznL = zznL();
if (zznL > ((long) (zzoT - 1))) {
List zzs = zzs((zznL - ((long) zzoT)) + 1);
zzd("Store full, deleting hits to make room, count", Integer.valueOf(zzs.size()));
zzr(zzs);
}
}
private String zznV() {
return zzns().zzoV();
}
public void beginTransaction() {
zznA();
getWritableDatabase().beginTransaction();
}
public void close() {
try {
this.zzadv.close();
} catch (SQLiteException e) {
zze("Sql error closing database", e);
} catch (IllegalStateException e2) {
zze("Error closing database", e2);
}
}
public void endTransaction() {
zznA();
getWritableDatabase().endTransaction();
}
SQLiteDatabase getWritableDatabase() {
try {
return this.zzadv.getWritableDatabase();
} catch (SQLiteException e) {
zzd("Error opening database", e);
throw e;
}
}
boolean isEmpty() {
return zznL() == 0;
}
public void setTransactionSuccessful() {
zznA();
getWritableDatabase().setTransactionSuccessful();
}
public long zza(long j, String str, String str2) {
zzac.zzdv(str);
zzac.zzdv(str2);
zznA();
zzmq();
return zza("SELECT hits_count FROM properties WHERE app_uid=? AND cid=? AND tid=?", new String[]{String.valueOf(j), str, str2}, 0);
}
public void zza(long j, String str) {
zzac.zzdv(str);
zznA();
zzmq();
int delete = getWritableDatabase().delete("properties", "app_uid=? AND cid<>?", new String[]{String.valueOf(j), str});
if (delete > 0) {
zza("Deleted property records", Integer.valueOf(delete));
}
}
public void zzb(zzry com_google_android_gms_internal_zzry) {
zzac.zzw(com_google_android_gms_internal_zzry);
zznA();
zzmq();
SQLiteDatabase writableDatabase = getWritableDatabase();
String zzS = zzS(com_google_android_gms_internal_zzry.zzfz());
ContentValues contentValues = new ContentValues();
contentValues.put("app_uid", Long.valueOf(com_google_android_gms_internal_zzry.zznI()));
contentValues.put("cid", com_google_android_gms_internal_zzry.zzlX());
contentValues.put("tid", com_google_android_gms_internal_zzry.zznJ());
contentValues.put("adid", Integer.valueOf(com_google_android_gms_internal_zzry.zznK() ? 1 : 0));
contentValues.put("hits_count", Long.valueOf(com_google_android_gms_internal_zzry.zznL()));
contentValues.put("params", zzS);
try {
if (writableDatabase.insertWithOnConflict("properties", null, contentValues, 5) == -1) {
zzbS("Failed to insert/update a property (got -1)");
}
} catch (SQLiteException e) {
zze("Error storing a property", e);
}
}
Map<String, String> zzbT(String str) {
if (TextUtils.isEmpty(str)) {
return new HashMap(0);
}
try {
if (!str.startsWith("?")) {
String str2 = "?";
String valueOf = String.valueOf(str);
str = valueOf.length() != 0 ? str2.concat(valueOf) : new String(str2);
}
return zzn.zza(new URI(str), "UTF-8");
} catch (URISyntaxException e) {
zze("Error parsing hit parameters", e);
return new HashMap(0);
}
}
Map<String, String> zzbU(String str) {
if (TextUtils.isEmpty(str)) {
return new HashMap(0);
}
try {
String str2 = "?";
String valueOf = String.valueOf(str);
return zzn.zza(new URI(valueOf.length() != 0 ? str2.concat(valueOf) : new String(str2)), "UTF-8");
} catch (URISyntaxException e) {
zze("Error parsing property parameters", e);
return new HashMap(0);
}
}
public void zzc(zzst com_google_android_gms_internal_zzst) {
zzac.zzw(com_google_android_gms_internal_zzst);
zzmq();
zznA();
String zze = zze(com_google_android_gms_internal_zzst);
if (zze.length() > AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD) {
zznr().zza(com_google_android_gms_internal_zzst, "Hit length exceeds the maximum allowed size");
return;
}
zznU();
SQLiteDatabase writableDatabase = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("hit_string", zze);
contentValues.put("hit_time", Long.valueOf(com_google_android_gms_internal_zzst.zzpq()));
contentValues.put("hit_app_id", Integer.valueOf(com_google_android_gms_internal_zzst.zzpo()));
contentValues.put("hit_url", zzd(com_google_android_gms_internal_zzst));
try {
long insert = writableDatabase.insert("hits2", null, contentValues);
if (insert == -1) {
zzbS("Failed to insert a hit (got -1)");
} else {
zzb("Hit saved to database. db-id, hit", Long.valueOf(insert), com_google_android_gms_internal_zzst);
}
} catch (SQLiteException e) {
zze("Error storing a hit", e);
}
}
protected void zzmr() {
}
public long zznL() {
zzmq();
zznA();
return zzb("SELECT COUNT(*) FROM hits2", null);
}
public void zznQ() {
zzmq();
zznA();
getWritableDatabase().delete("hits2", null, null);
}
public void zznR() {
zzmq();
zznA();
getWritableDatabase().delete("properties", null, null);
}
public int zznS() {
zzmq();
zznA();
if (!this.zzadw.zzz(86400000)) {
return 0;
}
this.zzadw.start();
zzbO("Deleting stale hits (if any)");
int delete = getWritableDatabase().delete("hits2", "hit_time < ?", new String[]{Long.toString(zznq().currentTimeMillis() - 2592000000L)});
zza("Deleted stale hits, count", Integer.valueOf(delete));
return delete;
}
public long zznT() {
zzmq();
zznA();
return zza(zzadu, null, 0);
}
public void zzr(List<Long> list) {
zzac.zzw(list);
zzmq();
zznA();
if (!list.isEmpty()) {
int i;
StringBuilder stringBuilder = new StringBuilder("hit_id");
stringBuilder.append(" in (");
for (i = 0; i < list.size(); i++) {
Long l = (Long) list.get(i);
if (l == null || l.longValue() == 0) {
throw new SQLiteException("Invalid hit id");
}
if (i > 0) {
stringBuilder.append(",");
}
stringBuilder.append(l);
}
stringBuilder.append(")");
String stringBuilder2 = stringBuilder.toString();
try {
SQLiteDatabase writableDatabase = getWritableDatabase();
zza("Deleting dispatched hits. count", Integer.valueOf(list.size()));
i = writableDatabase.delete("hits2", stringBuilder2, null);
if (i != list.size()) {
zzb("Deleted fewer hits then expected", Integer.valueOf(list.size()), Integer.valueOf(i), stringBuilder2);
}
} catch (SQLiteException e) {
zze("Error deleting hits", e);
throw e;
}
}
}
public List<Long> zzs(long j) {
Object e;
Throwable th;
Cursor cursor = null;
zzmq();
zznA();
if (j <= 0) {
return Collections.emptyList();
}
SQLiteDatabase writableDatabase = getWritableDatabase();
List<Long> arrayList = new ArrayList();
Cursor query;
try {
query = writableDatabase.query("hits2", new String[]{"hit_id"}, null, null, null, null, String.format("%s ASC", new Object[]{"hit_id"}), Long.toString(j));
try {
if (query.moveToFirst()) {
do {
arrayList.add(Long.valueOf(query.getLong(0)));
} while (query.moveToNext());
}
if (query != null) {
query.close();
}
} catch (SQLiteException e2) {
e = e2;
try {
zzd("Error selecting hit ids", e);
if (query != null) {
query.close();
}
return arrayList;
} catch (Throwable th2) {
th = th2;
cursor = query;
if (cursor != null) {
cursor.close();
}
throw th;
}
}
} catch (SQLiteException e3) {
e = e3;
query = null;
zzd("Error selecting hit ids", e);
if (query != null) {
query.close();
}
return arrayList;
} catch (Throwable th3) {
th = th3;
if (cursor != null) {
cursor.close();
}
throw th;
}
return arrayList;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public java.util.List<com.google.android.gms.internal.zzst> zzt(long r14) {
/*
r13 = this;
r0 = 1;
r1 = 0;
r9 = 0;
r2 = 0;
r2 = (r14 > r2 ? 1 : (r14 == r2 ? 0 : -1));
if (r2 < 0) goto L_0x008f;
L_0x0009:
com.google.android.gms.common.internal.zzac.zzas(r0);
r13.zzmq();
r13.zznA();
r0 = r13.getWritableDatabase();
r1 = "hits2";
r2 = 5;
r2 = new java.lang.String[r2]; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r3 = 0;
r4 = "hit_id";
r2[r3] = r4; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r3 = 1;
r4 = "hit_time";
r2[r3] = r4; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r3 = 2;
r4 = "hit_string";
r2[r3] = r4; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r3 = 3;
r4 = "hit_url";
r2[r3] = r4; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r3 = 4;
r4 = "hit_app_id";
r2[r3] = r4; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r3 = 0;
r4 = 0;
r5 = 0;
r6 = 0;
r7 = "%s ASC";
r8 = 1;
r8 = new java.lang.Object[r8]; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r10 = 0;
r11 = "hit_id";
r8[r10] = r11; Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r7 = java.lang.String.format(r7, r8); Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r8 = java.lang.Long.toString(r14); Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r9 = r0.query(r1, r2, r3, r4, r5, r6, r7, r8); Catch:{ SQLiteException -> 0x0092, all -> 0x00a2 }
r10 = new java.util.ArrayList; Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r10.<init>(); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r0 = r9.moveToFirst(); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
if (r0 == 0) goto L_0x0089;
L_0x0059:
r0 = 0;
r6 = r9.getLong(r0); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r0 = 1;
r3 = r9.getLong(r0); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r0 = 2;
r0 = r9.getString(r0); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r1 = 3;
r1 = r9.getString(r1); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r2 = 4;
r8 = r9.getInt(r2); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r2 = r13.zzbT(r0); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r5 = com.google.android.gms.internal.zztg.zzci(r1); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r0 = new com.google.android.gms.internal.zzst; Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r1 = r13;
r0.<init>(r1, r2, r3, r5, r6, r8); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r10.add(r0); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
r0 = r9.moveToNext(); Catch:{ SQLiteException -> 0x00a4, all -> 0x00a2 }
if (r0 != 0) goto L_0x0059;
L_0x0089:
if (r9 == 0) goto L_0x008e;
L_0x008b:
r9.close();
L_0x008e:
return r10;
L_0x008f:
r0 = r1;
goto L_0x0009;
L_0x0092:
r0 = move-exception;
r1 = r9;
L_0x0094:
r2 = "Error loading hits from the database";
r13.zze(r2, r0); Catch:{ all -> 0x009a }
throw r0; Catch:{ all -> 0x009a }
L_0x009a:
r0 = move-exception;
r9 = r1;
L_0x009c:
if (r9 == 0) goto L_0x00a1;
L_0x009e:
r9.close();
L_0x00a1:
throw r0;
L_0x00a2:
r0 = move-exception;
goto L_0x009c;
L_0x00a4:
r0 = move-exception;
r1 = r9;
goto L_0x0094;
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.internal.zzsa.zzt(long):java.util.List<com.google.android.gms.internal.zzst>");
}
public void zzu(long j) {
zzmq();
zznA();
List arrayList = new ArrayList(1);
arrayList.add(Long.valueOf(j));
zza("Deleting hit, id", Long.valueOf(j));
zzr(arrayList);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public java.util.List<com.google.android.gms.internal.zzry> zzv(long r14) {
/*
r13 = this;
r13.zznA();
r13.zzmq();
r0 = r13.getWritableDatabase();
r9 = 0;
r1 = 5;
r2 = new java.lang.String[r1]; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = 0;
r3 = "cid";
r2[r1] = r3; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = 1;
r3 = "tid";
r2[r1] = r3; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = 2;
r3 = "adid";
r2[r1] = r3; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = 3;
r3 = "hits_count";
r2[r1] = r3; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = 4;
r3 = "params";
r2[r1] = r3; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = r13.zzns(); Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r10 = r1.zzoU(); Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r8 = java.lang.String.valueOf(r10); Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r3 = "app_uid=?";
r1 = 1;
r4 = new java.lang.String[r1]; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = 0;
r5 = java.lang.String.valueOf(r14); Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r4[r1] = r5; Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r1 = "properties";
r5 = 0;
r6 = 0;
r7 = 0;
r9 = r0.query(r1, r2, r3, r4, r5, r6, r7, r8); Catch:{ SQLiteException -> 0x00ba, all -> 0x00b8 }
r11 = new java.util.ArrayList; Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r11.<init>(); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r0 = r9.moveToFirst(); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
if (r0 == 0) goto L_0x008b;
L_0x0053:
r0 = 0;
r3 = r9.getString(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r0 = 1;
r4 = r9.getString(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r0 = 2;
r0 = r9.getInt(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
if (r0 == 0) goto L_0x009c;
L_0x0064:
r5 = 1;
L_0x0065:
r0 = 3;
r0 = r9.getInt(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r6 = (long) r0; Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r0 = 4;
r0 = r9.getString(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r8 = r13.zzbU(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r0 = android.text.TextUtils.isEmpty(r3); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
if (r0 != 0) goto L_0x0080;
L_0x007a:
r0 = android.text.TextUtils.isEmpty(r4); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
if (r0 == 0) goto L_0x009e;
L_0x0080:
r0 = "Read property with empty client id or tracker id";
r13.zzc(r0, r3, r4); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
L_0x0085:
r0 = r9.moveToNext(); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
if (r0 != 0) goto L_0x0053;
L_0x008b:
r0 = r11.size(); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
if (r0 < r10) goto L_0x0096;
L_0x0091:
r0 = "Sending hits to too many properties. Campaign report might be incorrect";
r13.zzbR(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
L_0x0096:
if (r9 == 0) goto L_0x009b;
L_0x0098:
r9.close();
L_0x009b:
return r11;
L_0x009c:
r5 = 0;
goto L_0x0065;
L_0x009e:
r0 = new com.google.android.gms.internal.zzry; Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r1 = r14;
r0.<init>(r1, r3, r4, r5, r6, r8); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
r11.add(r0); Catch:{ SQLiteException -> 0x00a8, all -> 0x00b8 }
goto L_0x0085;
L_0x00a8:
r0 = move-exception;
r1 = r9;
L_0x00aa:
r2 = "Error loading hits from the database";
r13.zze(r2, r0); Catch:{ all -> 0x00b0 }
throw r0; Catch:{ all -> 0x00b0 }
L_0x00b0:
r0 = move-exception;
r9 = r1;
L_0x00b2:
if (r9 == 0) goto L_0x00b7;
L_0x00b4:
r9.close();
L_0x00b7:
throw r0;
L_0x00b8:
r0 = move-exception;
goto L_0x00b2;
L_0x00ba:
r0 = move-exception;
r1 = r9;
goto L_0x00aa;
*/
throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.internal.zzsa.zzv(long):java.util.List<com.google.android.gms.internal.zzry>");
}
}
| [
"earl.savadera@lpunetwork.edu.ph"
] | earl.savadera@lpunetwork.edu.ph |
e2663c23da10a3d2f99bc390ccc701ed1c590fa7 | 82723b8e1bb0fca74f6e2798804cf8612c16fbf8 | /T-RPG Creator/src/maker/vista/editor/Importar/Filtros/ImageFilter.java | 1eac3c306c3c16a9d44377398485d1db40dfbec2 | [] | no_license | BackupTheBerlios/proyiaic | bd943db55f89e277c7ae0b443265d44c269b2a6f | 0c287e001799e02b79a0f4b8896447e4fd5a2aca | refs/heads/master | 2020-05-19T15:54:19.613180 | 2008-07-08T22:41:17 | 2008-07-08T22:41:17 | 40,052,050 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,024 | java | package maker.vista.editor.Importar.Filtros;
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class ImageFilter extends FileFilter
{
public boolean accept(File archivo)
{
if (archivo.isDirectory()) //El archivo es un directorio.
return true;
else //No es un directorio.
{
// Cogemos el nombre del archivo.
String cadena = archivo.getAbsolutePath();
int ext = cadena.lastIndexOf('.'); //Última posición de un punto en el nombre.
if (ext < cadena.length() || ext >= 1) //Hay algún punto
{
String extension = cadena.substring(ext+1); //Cogemos la extensión del archivo.
if (extension.equals("png") || extension.equals("gif") || extension.equals("jpg"))
return true;
}
}
return false;
}
/** Método que devuelve una descripción acerca de los archivos que acepta el método
* accept(File archivo)
* @return La descripción de los archivos aceptados.*/
public String getDescription()
{
return "Archivos de imagen (.png, .jpg, .gif)";
}
}
| [
"darthguado"
] | darthguado |
f14c2ea337b1018a8c8fe910b6eff648eae9bbc1 | f864728685559b78b568c6a5d56481899cb4fd66 | /myCodingTactics/src/structuredBinarySearch/createtheList.java | 29aada2f9ddb8cc87d7fd9f0067a7e51fc6e9830 | [] | no_license | bulentmalgaz/eclipse-workspace | f3676b8a6f6e676fac7930bd5cec0fee5dca7ab3 | c3010401bef5743e6b05daabfde9598cb61290db | refs/heads/master | 2020-03-27T17:28:25.118191 | 2018-09-16T21:22:43 | 2018-09-16T21:22:43 | 146,741,293 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,493 | java | package structuredBinarySearch;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class createtheList {
private static Scanner scanner;
static List<Integer> enteries = new ArrayList<Integer>();
public static void createList (String[] args)
{
// enter a row of numbers
System.out.println("Enter your own amount of numbers to a list. Press 'enter' after every number. ");
System.out.println("Letters will be ignored. Type 'ready' if you are ready. ");
scanner = new Scanner(System.in);
String number;
int inumber;
do
{
number = scanner.nextLine();
// check if they are numbers instead of other values, add as numbers
if (isStringInt(number))
{
inumber = Integer.parseInt(number);
enteries.add(inumber);
}
else
{
if (!number.equalsIgnoreCase("ready"))
{ System.out.println("Sorry only numbers allowed.");}
}
}
while (!number.equalsIgnoreCase("ready"));
System.out.println("thank you; numbers are added and row is made.");
// sort the list
Collections.sort(enteries);
// show that its correct
System.out.println("these are the enteries:" + enteries);
}
public static boolean isStringInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
}
| [
"33319033+bulentmalgaz@users.noreply.github.com"
] | 33319033+bulentmalgaz@users.noreply.github.com |
9918365623cc1f22561ca756c552af55fe609458 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/26/26_cc4b75d4857e66e1efaf3dc6f7d7bcc4216cb95f/SessionMonitor/26_cc4b75d4857e66e1efaf3dc6f7d7bcc4216cb95f_SessionMonitor_s.java | 55e008f051cab042e80c16490ec0bc0e888fa5e6 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 2,402 | java | /*******************************************************************************
* Copyright (c) 2012 Google, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Google, Inc. - initial API and implementation
*******************************************************************************/
package com.windowtester.eclipse.ui.session;
import java.util.ArrayList;
import java.util.List;
import com.windowtester.codegen.ExecutionProfile;
import com.windowtester.recorder.ISemanticEventProvider;
import com.windowtester.ui.internal.core.recorder.NullRecorder;
public class SessionMonitor implements ISessionMonitor {
public static final ISession NULL_SESSION = new ISession() {
public ISemanticEventProvider getRecorder() {
return new NullRecorder();
}
public ExecutionProfile getExecutionProfile() {
// TODO Auto-generated method stub
return null;
}
};
private ISession session = nullSession();
private final List<ISessionListener> listeners = new ArrayList<ISessionListener>();
public ISession getCurrent() {
return session;
}
public boolean inSession() {
return getCurrent() != nullSession();
}
public void sessionEnded(ISession session) {
for (ISessionListener listener: getListeners()) {
listener.ended(session);
}
setSession(nullSession());
}
private static ISession nullSession() {
return NULL_SESSION;
}
public void sessionStarted(ISession session) {
setSession(session);
for (ISessionListener listener: getListeners()) {
listener.started(session);
}
}
private void setSession(ISession session) {
assertNotNull(session);
this.session = session;
}
public void addListener(ISessionListener listener) {
assertNotNull(listener);
getListeners().add(listener);
}
private void assertNotNull(Object param) {
if (param == null)
throw new IllegalArgumentException("argument cannot be null");
}
public void removeListener(ISessionListener listener) {
assertNotNull(listener);
getListeners().remove(listener);
}
private List<ISessionListener> getListeners() {
return listeners;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
9ae26b3f08ba59fcf00de06494caa0d9264050a1 | 8280aa15b503f5c8fa0aa404218fae1b7a77afe9 | /app/src/main/java/com/amandarover/dogormuffin/HighScoresActivity.java | 3305ac4ff2d90471d4bcef9683743c562acce072 | [] | no_license | amandarover/DogOrMuffin | d1a93f1c33f6e98199dfb2a027eae5f26efbf4ef | 7625423106f6f3a4205e5e316e7a3a3313b23cfe | refs/heads/master | 2021-08-23T02:57:20.405644 | 2017-12-02T18:55:59 | 2017-12-02T18:55:59 | 109,057,761 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,468 | java | package com.amandarover.dogormuffin;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.amandarover.dogormuffin.data.AppDatabase;
import com.amandarover.dogormuffin.data.Score;
import com.amandarover.dogormuffin.data.ScoreDao;
import java.util.List;
public class HighScoresActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high_scores);
findViewById(R.id.buttonBack).setOnClickListener(this);
ScoreDao scoreDao = AppDatabase.getInstance(this).scoreDao();
List<Score> highScoreList = scoreDao.fetchAll();
ListView highScoreListView = findViewById(R.id.listViewHigsScores);
ArrayAdapter<Score> highScoreAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, highScoreList);
highScoreListView.setAdapter(highScoreAdapter);
}
@Override
public void onClick(View clickedButtonView) {
switch (clickedButtonView.getId()) {
case R.id.buttonBack:
Intent startActivity = new Intent(this, StartActivity.class);
startActivity(startActivity);
finish();
break;
}
}
}
| [
"rover.amanda@gmail.com"
] | rover.amanda@gmail.com |
5be00b9f45207fd5f908d0c7d63d58f7cf8acd68 | a172503f33fb0852a2794e3b008485b836b3d828 | /code/accumilation/src/main/java/com/codev/accumilation/rest/GenericHedaer.java | 6cd25eabc00db10717ce40def33a648f0eb2fb4e | [] | no_license | natias/neemanut | 2ec22c848fa15e5022fe645fbb7dd9f44ec7ea62 | 912e5fd4aa4a4d7a12678b54f2dae95e5caaddca | refs/heads/master | 2023-02-01T02:32:25.260529 | 2020-12-20T16:58:22 | 2020-12-20T16:58:22 | 319,389,909 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 219 | java | package com.codev.accumilation.rest;
import java.time.LocalDateTime;
import lombok.Builder;
import lombok.Data;
@Data
public class GenericHedaer {
String clientId;
LocalDateTime timeStamp;
String requestId;
}
| [
"nati.ashush@gmail.com"
] | nati.ashush@gmail.com |
fd420b35f2701eb2ab44190d9605626ab1f4bf87 | 44d8aa309f709422f32d4815490a3eec05544489 | /build/src/main/java/com/mypurecloud/sdk/v2/model/EdgeChangeTopicEdge.java | 5d9a3b509174c31f47ade83288f0a1bb48831cd1 | [
"MIT"
] | permissive | MyPureCloud/platform-client-sdk-java | a25146f15a0ef96f5c0c4655af3dc8aa77e48843 | 250d47418a9642fce5c7d6697f87d978ec39a257 | refs/heads/master | 2023-08-17T01:42:17.287918 | 2023-08-15T07:03:28 | 2023-08-15T07:03:28 | 86,601,855 | 7 | 14 | MIT | 2023-02-27T14:26:49 | 2017-03-29T15:56:50 | HTML | UTF-8 | Java | false | false | 3,959 | java | package com.mypurecloud.sdk.v2.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.util.Objects;
import java.util.ArrayList;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* EdgeChangeTopicEdge
*/
public class EdgeChangeTopicEdge implements Serializable {
private String id = null;
private static class OnlineStatusEnumDeserializer extends StdDeserializer<OnlineStatusEnum> {
public OnlineStatusEnumDeserializer() {
super(OnlineStatusEnumDeserializer.class);
}
@Override
public OnlineStatusEnum deserialize(JsonParser jsonParser, DeserializationContext ctxt)
throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
return OnlineStatusEnum.fromString(node.toString().replace("\"", ""));
}
}
/**
* Gets or Sets onlineStatus
*/
@JsonDeserialize(using = OnlineStatusEnumDeserializer.class)
public enum OnlineStatusEnum {
OUTDATEDSDKVERSION("OutdatedSdkVersion"),
ONLINE("ONLINE"),
OFFLINE("OFFLINE");
private String value;
OnlineStatusEnum(String value) {
this.value = value;
}
@JsonCreator
public static OnlineStatusEnum fromString(String key) {
if (key == null) return null;
for (OnlineStatusEnum value : OnlineStatusEnum.values()) {
if (key.equalsIgnoreCase(value.toString())) {
return value;
}
}
return OnlineStatusEnum.values()[0];
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
}
private OnlineStatusEnum onlineStatus = null;
/**
**/
public EdgeChangeTopicEdge id(String id) {
this.id = id;
return this;
}
@ApiModelProperty(example = "null", value = "")
@JsonProperty("id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
**/
public EdgeChangeTopicEdge onlineStatus(OnlineStatusEnum onlineStatus) {
this.onlineStatus = onlineStatus;
return this;
}
@ApiModelProperty(example = "null", value = "")
@JsonProperty("onlineStatus")
public OnlineStatusEnum getOnlineStatus() {
return onlineStatus;
}
public void setOnlineStatus(OnlineStatusEnum onlineStatus) {
this.onlineStatus = onlineStatus;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EdgeChangeTopicEdge edgeChangeTopicEdge = (EdgeChangeTopicEdge) o;
return Objects.equals(this.id, edgeChangeTopicEdge.id) &&
Objects.equals(this.onlineStatus, edgeChangeTopicEdge.onlineStatus);
}
@Override
public int hashCode() {
return Objects.hash(id, onlineStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EdgeChangeTopicEdge {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" onlineStatus: ").append(toIndentedString(onlineStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"purecloud-jenkins@ininica.com"
] | purecloud-jenkins@ininica.com |
9d68f3f4a4a219773df8d99319bd1731ddd9bda9 | b08bfd464080ba2704e69464fcbeaa4b31b2947e | /src/main/java/Foto_Service/Point_one/App.java | 277ebcef5860b2650c06c995477ae8c44aa92025 | [] | no_license | Shimadzusan/Point_one | 8a44896297fb7a0cc78328bbd34da8d2ca89aece | 859d33f797562d41c20c1c322d822c918adcb2d0 | refs/heads/master | 2022-07-11T07:56:57.462578 | 2019-12-25T09:07:49 | 2019-12-25T09:07:49 | 195,543,260 | 0 | 0 | null | 2022-06-17T02:33:02 | 2019-07-06T13:36:30 | Java | UTF-8 | Java | false | false | 202 | java | package Foto_Service.Point_one;
/**
* Hello world!
*
*/
public class App {
public static void main( String[] args ) {
System.out.println(String.format("Hello %s!", Target.NAME));
}
} | [
"nix_olympica@tut.by"
] | nix_olympica@tut.by |
c1fd02871ed16d01a5b1e8a314f39836760133e8 | e79c62c4f0392880b899ea23a690ba08b40b35d1 | /src/main/java/com/ass/repositories/UserRepository.java | 0f16c21b9506343e81bfa7239d490ed4dbb44b28 | [] | no_license | NguyenTrungKien172001/Spring-boot-java5-ass | 531cf339c100714fa90050c683d16ffd8b6aa234 | 3952bc380c6b39b7273339a577f1768a585f6fa3 | refs/heads/master | 2023-06-03T23:21:06.604485 | 2021-06-27T02:38:04 | 2021-06-27T02:38:04 | 380,634,143 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | package com.ass.repositories;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.ass.entity.User;
public interface UserRepository extends JpaRepository<User, Integer> {
@Query("select entity from User entity where email=:email and activated=1")
public User findByEmail(@Param("email") String email);
@Query("select entity from User entity where activated=0")
public Page<User> findByActivated(Pageable pageable);
@Query("select entity from User entity where activated=1")
public Page<User> findByActivated1(Pageable pageable);
}
| [
"oppofly60@gmail.com"
] | oppofly60@gmail.com |
fa6b3b945607ae0587b6c8ba9067169d273d38a8 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_8087df41557bf1243624ceacf3208af03e9b0144/ResourceDelta/2_8087df41557bf1243624ceacf3208af03e9b0144_ResourceDelta_t.java | 0b3b97dcb055a154c438f6600cdea1b17d043f66 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 15,908 | java | /**********************************************************************
* Copyright (c) 2000,2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
**********************************************************************/
package org.eclipse.core.internal.events;
import java.util.*;
import org.eclipse.core.internal.resources.*;
import org.eclipse.core.internal.utils.Assert;
import org.eclipse.core.internal.watson.ElementTree;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
/**
* Concrete implementation of the IResourceDelta interface. Each ResourceDelta
* object represents changes that have occurred between two states of the
* resource tree.
*/
public class ResourceDelta extends PlatformObject implements IResourceDelta {
protected IPath path;
protected ResourceDeltaInfo deltaInfo;
protected int status;
protected ResourceInfo oldInfo;
protected ResourceInfo newInfo;
protected IResourceDelta[] children;
// don't agressively set this, but cache it if called once
protected IResource cachedResource;
//
protected static int KIND_MASK = 0xFF;
private static IMarkerDelta[] EMPTY_MARKER_DELTAS = new IMarkerDelta[0];
protected ResourceDelta(IPath path, ResourceDeltaInfo deltaInfo) {
super();
this.path = path;
this.deltaInfo = deltaInfo;
}
/*
* @see IResourceDelta#accept(IResourceDeltaVisitor)
*/
public void accept(IResourceDeltaVisitor visitor) throws CoreException {
// forward to central method
accept(visitor, 0);
}
/*
* @see IResourceDelta#accept(IResourceDeltaVisitor, boolean)
*/
public void accept(IResourceDeltaVisitor visitor, boolean includePhantoms) throws CoreException {
// forward to central method
accept(visitor, includePhantoms ? IContainer.INCLUDE_PHANTOMS : 0);
}
/*
* @see IResourceDelta#accept(IResourceDeltaVisitor, int)
*/
public void accept(IResourceDeltaVisitor visitor, int memberFlags) throws CoreException {
final boolean includePhantoms = (memberFlags & IContainer.INCLUDE_PHANTOMS) != 0;
int mask = includePhantoms ? ALL_WITH_PHANTOMS : REMOVED | ADDED | CHANGED;
if ((getKind() | mask) == 0)
return;
if (!visitor.visit(this))
return;
//recurse over children
for (int i = 0; i < children.length; i++) {
IResourceDelta childDelta = children[i];
// quietly exclude team-private members unless explicitly included
if ((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) != 0
|| !((ResourceDelta)childDelta).isTeamPrivate())
childDelta.accept(visitor, memberFlags);
}
}
/**
* Check for marker deltas, and set the appropriate change flag if there are any.
*/
protected void checkForMarkerDeltas() {
if (deltaInfo.getMarkerDeltas() == null)
return;
int kind = getKind();
// Only need to check for added and removed, or for changes on the workspace.
// For changed, the bit is set in the comparator.
if (path.isRoot() || kind == ADDED || kind == REMOVED) {
MarkerSet changes = (MarkerSet) deltaInfo.getMarkerDeltas().get(path);
if (changes != null && changes.size() > 0) {
status |= MARKERS;
// If there have been marker changes, then ensure kind is CHANGED (if not ADDED or REMOVED).
// See 1FV9K20: ITPUI:WINNT - severe - task list - add or delete not working
if (kind == 0) {
status |= CHANGED;
}
}
}
}
/**
* @see IResourceDelta#findMember(IPath)
*/
public IResourceDelta findMember(IPath path) {
int segmentCount = path.segmentCount();
if (segmentCount == 0)
return this;
//iterate over the path and find matching child delta
ResourceDelta current = this;
segments: for (int i = 0; i < segmentCount; i++) {
IResourceDelta[] currentChildren = current.children;
for (int j = 0, jmax = currentChildren.length; j < jmax; j++) {
if (currentChildren[j].getFullPath().lastSegment().equals(path.segment(i))) {
current = (ResourceDelta)currentChildren[j];
continue segments;
}
}
//matching child not found, return
return null;
}
return current;
}
/**
* Delta information on moves and on marker deltas can only be computed after
* the delta has been built. This method fixes up the delta to accurately
* reflect moves (setting MOVED_FROM and MOVED_TO), and marker changes on
* added and removed resources.
*/
protected void fixMovesAndMarkers(ElementTree oldTree) {
NodeIDMap nodeIDMap = deltaInfo.getNodeIDMap();
if (!path.isRoot() && !nodeIDMap.isEmpty()) {
int kind = getKind();
switch (kind) {
case ADDED :
case CHANGED :
long nodeID = newInfo.getNodeId();
IPath oldPath = (IPath) nodeIDMap.getOldPath(nodeID);
if (oldPath != null && !oldPath.equals(path)) {
//get the old info from the old tree
oldInfo = (ResourceInfo)oldTree.getElementData(oldPath);
// Replace change flags by comparing old info with new info,
// Note that we want to retain the kind flag, but replace all other flags
// This is done only for MOVED_FROM, not MOVED_TO, since a resource may be both.
status = (status & KIND_MASK) | (deltaInfo.getComparator().compare(oldInfo, newInfo) & ~KIND_MASK);
status |= MOVED_FROM;
}
}
switch (kind) {
case CHANGED :
case REMOVED :
long nodeID = oldInfo.getNodeId();
IPath newPath = (IPath) nodeIDMap.getNewPath(nodeID);
if (newPath != null && !newPath.equals(path)) {
status |= MOVED_TO;
}
}
}
//check for marker deltas -- this is affected by move computation
//so must happen afterwards
checkForMarkerDeltas();
//recurse on children
for (int i = 0; i < children.length; i++) {
((ResourceDelta)children[i]).fixMovesAndMarkers(oldTree);
}
}
/**
* @see IResourceDelta#getAffectedChildren
*/
public IResourceDelta[] getAffectedChildren() {
return getAffectedChildren(ADDED | REMOVED | CHANGED, IResource.NONE);
}
/**
* @see IResourceDelta#getAffectedChildren(int)
*/
public IResourceDelta[] getAffectedChildren(int kindMask) {
return getAffectedChildren(kindMask, IResource.NONE);
}
/*
* @see IResourceDelta#getAffectedChildren(int, int)
*/
public IResourceDelta[] getAffectedChildren(int kindMask, int memberFlags) {
int numChildren = children.length;
//if there are no children, they all match
if (numChildren == 0) {
return children;
}
if ((memberFlags & IContainer.INCLUDE_PHANTOMS) != 0) {
// reduce INCLUDE_PHANTOMS member flag to kind mask
kindMask |= ADDED_PHANTOM | REMOVED_PHANTOM;
}
//first count the number of matches so we can allocate the exact array size
int matching = 0;
for (int i = 0; i < numChildren; i++) {
if ((children[i].getKind() & kindMask) == 0) {
// child has wrong kind
continue;
}
if ((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) == 0
&& ((ResourceDelta)children[i]).isTeamPrivate()) {
// child has is a team-private member which are not included
continue;
}
matching++;
}
//use arraycopy if all match
if (matching == numChildren) {
IResourceDelta[] result = new IResourceDelta[children.length];
System.arraycopy(children, 0, result, 0, children.length);
return result;
}
//create the appropriate sized array and fill it
IResourceDelta[] result = new IResourceDelta[matching];
int nextPosition = 0;
for (int i = 0; i < numChildren; i++) {
if ((children[i].getKind() & kindMask) == 0) {
// child has wrong kind
continue;
}
if ((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) == 0
&& ((ResourceDelta)children[i]).isTeamPrivate()) {
// child has is a team-private member which are not included
continue;
}
result[nextPosition++] = children[i];
}
return result;
}
protected ResourceDeltaInfo getDeltaInfo() {
return deltaInfo;
}
/**
* @see IResourceDelta#getFlags
*/
public int getFlags() {
return status & ~KIND_MASK;
}
/**
* @see IResourceDelta#getFullPath
*/
public IPath getFullPath() {
return path;
}
/**
* @see IResourceDelta#getKind
*/
public int getKind() {
return status & KIND_MASK;
}
/**
* @see IResourceDelta#getMarkerDeltas
*/
public IMarkerDelta[] getMarkerDeltas() {
Map markerDeltas = deltaInfo.getMarkerDeltas();
if (markerDeltas == null)
return EMPTY_MARKER_DELTAS;
if (path == null)
path = Path.ROOT;
MarkerSet changes = (MarkerSet) markerDeltas.get(path);
if (changes == null)
return EMPTY_MARKER_DELTAS;
IMarkerSetElement[] elements = changes.elements();
IMarkerDelta[] result = new IMarkerDelta[elements.length];
for (int i = 0; i < elements.length; i++)
result[i] = (IMarkerDelta) elements[i];
return result;
}
/**
* @see IResourceDelta#getMovedFromPath
*/
public IPath getMovedFromPath() {
if ((status & MOVED_FROM) != 0) {
return deltaInfo.getNodeIDMap().getOldPath(newInfo.getNodeId());
}
return null;
}
/**
* @see IResourceDelta#getMovedToPath
*/
public IPath getMovedToPath() {
if ((status & MOVED_TO) != 0) {
return deltaInfo.getNodeIDMap().getNewPath(oldInfo.getNodeId());
}
return null;
}
/**
* @see IResourceDelta#getProjectRelativePath
*/
public IPath getProjectRelativePath() {
IPath full = getFullPath();
int count = full.segmentCount();
if (count < 0)
return null;
if (count <= 1) // 0 or 1
return Path.EMPTY;
return full.removeFirstSegments(1);
}
/**
* @see IResourceDelta#getResource
*/
public IResource getResource() {
// return a cached copy if we have one
if (cachedResource != null)
return cachedResource;
// if this is a delta for the root then return the root resource
if (path.segmentCount() == 0)
return deltaInfo.getWorkspace().getRoot();
// if the delta is a remove then we have to look for the old info to find the type
// of resource to create.
ResourceInfo info = null;
if ((getKind() & (REMOVED | REMOVED_PHANTOM)) != 0)
info = oldInfo;
else
info = newInfo;
Assert.isNotNull(info, "Do not have resource info for resource in delta"); //$NON-NLS-1$
cachedResource = deltaInfo.getWorkspace().newResource(path, info.getType());
return cachedResource;
}
/**
* @see IResourceDelta#hasAffectedChildren
*/
public boolean hasAffectedChildren() {
return children.length > 0;
}
/**
* Returns true if this delta represents a team private member, and false
* otherwise.
*/
protected boolean isTeamPrivate() {
//use old info for removals, and new info for added or changed
if ((status & (REMOVED | REMOVED_PHANTOM)) != 0)
return ResourceInfo.isSet(oldInfo.getFlags(), ICoreConstants.M_TEAM_PRIVATE_MEMBER);
else
return ResourceInfo.isSet(newInfo.getFlags(), ICoreConstants.M_TEAM_PRIVATE_MEMBER);
}
protected void setChildren(IResourceDelta[] children) {
this.children = children;
}
protected void setNewInfo(ResourceInfo newInfo) {
this.newInfo = newInfo;
}
protected void setOldInfo(ResourceInfo oldInfo) {
this.oldInfo = oldInfo;
}
protected void setStatus(int status) {
this.status = status;
}
/**
* Returns a string representation of this delta's
* immediate structure suitable for debug purposes.
*/
public String toDebugString() {
final StringBuffer buffer = new StringBuffer();
writeDebugString(buffer);
return buffer.toString();
}
/**
* Returns a string representation of this delta's
* deep structure suitable for debug purposes.
*/
public String toDeepDebugString() {
final StringBuffer buffer = new StringBuffer("\n"); //$NON-NLS-1$
writeDebugString(buffer);
for (int i = 0; i < children.length; ++i) {
ResourceDelta delta = (ResourceDelta) children[i];
buffer.append(delta.toDeepDebugString());
}
return buffer.toString();
}
/**
* For debugging only
*/
public String toString() {
return "ResourceDelta(" + path + ")"; //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Provides a new set of markers for the delta. This is used
* when the delta is reused in cases where the only changes
* are marker changes.
*/
public void updateMarkers(Map markers) {
deltaInfo.setMarkerDeltas(markers);
}
/**
* Writes a string representation of this delta's
* immediate structure on the given string buffer.
*/
public void writeDebugString(StringBuffer buffer) {
buffer.append(getFullPath());
buffer.append("["); //$NON-NLS-1$
switch (getKind()) {
case ADDED :
buffer.append('+');
break;
case ADDED_PHANTOM :
buffer.append('>');
break;
case REMOVED :
buffer.append('-');
break;
case REMOVED_PHANTOM :
buffer.append('<');
break;
case CHANGED :
buffer.append('*');
break;
case NO_CHANGE :
buffer.append('~');
break;
default :
buffer.append('?');
break;
}
buffer.append("]: {"); //$NON-NLS-1$
int changeFlags = getFlags();
boolean prev = false;
if ((changeFlags & CONTENT) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("CONTENT"); //$NON-NLS-1$
prev = true;
}
if ((changeFlags & MOVED_FROM) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("MOVED_FROM(" + getMovedFromPath() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
prev = true;
}
if ((changeFlags & MOVED_TO) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("MOVED_TO(" + getMovedToPath() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
prev = true;
}
if ((changeFlags & OPEN) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("OPEN"); //$NON-NLS-1$
prev = true;
}
if ((changeFlags & TYPE) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("TYPE"); //$NON-NLS-1$
prev = true;
}
if ((changeFlags & SYNC) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("SYNC"); //$NON-NLS-1$
prev = true;
}
if ((changeFlags & MARKERS) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("MARKERS"); //$NON-NLS-1$
writeMarkerDebugString(buffer);
prev = true;
}
if ((changeFlags & REPLACED) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("REPLACED"); //$NON-NLS-1$
prev = true;
}
if ((changeFlags & DESCRIPTION) != 0) {
if (prev)
buffer.append(" | "); //$NON-NLS-1$
buffer.append("DESCRIPTION"); //$NON-NLS-1$
prev = true;
}
buffer.append("}"); //$NON-NLS-1$
if (isTeamPrivate())
buffer.append(" (team private)");
}
public void writeMarkerDebugString(StringBuffer buffer) {
buffer.append("["); //$NON-NLS-1$
for (Iterator e = deltaInfo.getMarkerDeltas().keySet().iterator(); e.hasNext();) {
IPath key = (IPath) e.next();
if (getResource().getFullPath().equals(key)) {
IMarkerSetElement[] deltas = ((MarkerSet) deltaInfo.getMarkerDeltas().get(key)).elements();
boolean addComma = false;
for (int i = 0; i < deltas.length; i++) {
IMarkerDelta delta = (IMarkerDelta) deltas[i];
if (addComma)
buffer.append(","); //$NON-NLS-1$
switch (delta.getKind()) {
case IResourceDelta.ADDED :
buffer.append("+"); //$NON-NLS-1$
break;
case IResourceDelta.REMOVED :
buffer.append("-"); //$NON-NLS-1$
break;
case IResourceDelta.CHANGED :
buffer.append("*"); //$NON-NLS-1$
break;
}
buffer.append(delta.getId());
addComma = true;
}
}
}
buffer.append("]"); //$NON-NLS-1$
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
209c532e05c82a15834cd737fb5517c1bbd8bad2 | dc5730d7c35254ea37db8ffe1d67fde331c9c0ac | /OOP Java/Labs/Lab 4/NewWorker.java | 279dbad23ffb063bde9192224f5ad164832bc758 | [] | no_license | shahiro770/Misc | 3cb9414a8dbfac7dc66d3d09b1b529b4f39ed83f | 0b5f4f985d5ed1e519d3cc3ae8081a6d3ec362ca | refs/heads/master | 2021-05-10T09:34:55.112086 | 2018-02-23T14:00:31 | 2018-02-23T14:00:31 | 118,927,968 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,126 | java | /*
* Shahir Chowdhury
* 2016-06-11
* NewWorker.java
*
* This program creates a NewWorker object, a child class of Person. In addition to Person's contents, the NewWorker keeps track
* of their salary, supervisor, when they joined the company, and even what number worker they are with respect to other workers.
*/
public class NewWorker extends Person{
private static int howManyWorkers = 1; //total number of workers
private int workerNumber;
private double salary;
private NewWorker supervisor;
private MyDate dateJoiningCompany;
//sets personName, dateJoiningCompany, and salary
public NewWorker(String nameString, String dateString, double startSalary){
super(nameString);
this.dateJoiningCompany = new MyDate(dateString);
this.salary = startSalary;
this.workerNumber = howManyWorkers;
howManyWorkers++;
}
//sets personName and dateJoiningCompany, defaulting salary to 0
public NewWorker(String nameString, String dateString){
super(nameString);
this.dateJoiningCompany = new MyDate(dateString);
this.salary = 0;
this.workerNumber = howManyWorkers;
howManyWorkers++;
}
//mutator for salary
public void setSalary(double newSalary){
salary = newSalary;
}
//accessor for salary
public double getSalary(){
return salary;
}
//mutator for supervisor
public void setSupervisor(NewWorker newSuper){
supervisor = newSuper;
}
//accessor for supervisor
public Name getSupervisor(){
if (supervisor != null){
return new Name(supervisor.getPersonName());
}
else{
return null;
}
}
//displays all of the NewWorker's information in a clean format
public String toString(){
String result = "";
result += "Worker Number " + workerNumber + "\nWorker Name " + this.getPersonName() + "\n";
result += "Date Joined: " + dateJoiningCompany + "\n";
if (supervisor != null){
result += "Supervisor: " + supervisor.getPersonName() + "\n";
}
else{
result += "No supervisor\n";
}
result += "Salary: $" + salary;
return result;
}
//accessor for the total number of workers
public static int getHowManyWorkers(){
return howManyWorkers;
}
} | [
"shahirchowdhury@Shahirs-MacBook-Pro.local"
] | shahirchowdhury@Shahirs-MacBook-Pro.local |
de0f53f9b1cf34445f80452a2e005445ffdf7c93 | 9dc021a12764bbe352b85c7cbc1f47d76ee1312f | /app/src/main/java/lk/ac/sjp/aurora/phasetwo/FrameMetadata.java | 33c14e914a9c52487088fc09b082cfd5ef39d484 | [] | no_license | janithwanni/aurora-phase-two-mobile | b3751c90a50a92416c8a7a2de08badacfe628926 | 6eb79b906cca20eaeefa63c8d0d376c80f9989c6 | refs/heads/master | 2020-03-27T16:45:25.319414 | 2018-09-09T03:20:16 | 2018-09-09T03:20:16 | 146,804,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,100 | java | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lk.ac.sjp.aurora.phasetwo;
/**
* Describing a frame info.
*/
public class FrameMetadata {
private final int width;
private final int height;
private final int rotation;
private final int cameraFacing;
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getRotation() {
return rotation;
}
public int getCameraFacing() {
return cameraFacing;
}
private FrameMetadata(int width, int height, int rotation, int facing) {
this.width = width;
this.height = height;
this.rotation = rotation;
cameraFacing = facing;
}
/**
* Builder of {@link FrameMetadata}.
*/
public static class Builder {
private int width;
private int height;
private int rotation;
private int cameraFacing;
public Builder setWidth(int width) {
this.width = width;
return this;
}
public Builder setHeight(int height) {
this.height = height;
return this;
}
public Builder setRotation(int rotation) {
this.rotation = rotation;
return this;
}
public Builder setCameraFacing(int facing) {
cameraFacing = facing;
return this;
}
public FrameMetadata build() {
return new FrameMetadata(width, height, rotation, cameraFacing);
}
}
}
| [
"r.t.doram@gmail.com"
] | r.t.doram@gmail.com |
98ebebd2f48e02d158caf9e893d2f92975ba21d6 | c5bded5b54464eec7c77905240632a547253d91b | /hotmail-register/src/main/java/cn/juns/hotmail/Main.java | 31b574f506dc0bdb8aba3c07cceb54dfda462bf6 | [] | no_license | yuanjunliu/hotchpotch | a90f2a74dd447d6db7f2d72b4269d5bb95cb5b97 | a566d088f9c68911e71bbeb874f01875452baf7a | refs/heads/master | 2018-11-08T08:45:29.164516 | 2018-08-23T00:57:04 | 2018-08-23T00:57:04 | 115,017,720 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 838 | java | package cn.juns.hotmail;
/**
* Created by 01380763 on 2018/8/17.
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
String[] proxyIps = RegisterUtil.getProxyIPs(1);
if (proxyIps == null) {
System.out.println("未获取到IP");
return;
}
int len = proxyIps.length;
Thread[] threads = new Thread[len];
for (int i = 0; i < len; i++) {
System.out.println(proxyIps[i] + "======================");
threads[i] = new Thread(new IpTester(proxyIps[i]));
// threads[i] = new Thread(new Register(proxyIps[i]));
}
for (int i = 0; i < len; i++) {
threads[i].join();
}
for (int i = 0; i < len; i++) {
threads[i].start();
}
}
}
| [
"01380763@sf.com"
] | 01380763@sf.com |
af5194a89623e6af524f5f84c849690bec4b594f | b2ffbff108e53ab05f4b51255e15cc54e9a2a55e | /java/jupiter/common/source/jupiter/common/struct/table/FloatTable.java | 3f6f9dc89dde5a46d76060bc80bd116fddb26963 | [
"MIT"
] | permissive | b-io/io.barras | 0fcfc53d842ae987c6a73ff2eca9f034fd103179 | 26645f0f804811fc2324407de02c97a1a58b5fac | refs/heads/master | 2023-06-11T22:04:08.441214 | 2023-06-04T22:06:23 | 2023-06-04T22:06:23 | 144,495,919 | 6 | 1 | MIT | 2022-10-09T20:48:11 | 2018-08-12T19:43:13 | Java | UTF-8 | Java | false | false | 7,296 | java | /*
* The MIT License (MIT)
*
* Copyright © 2013-2022 Florian Barras <https://barras.io> (florian@barras.io)
*
* 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 jupiter.common.struct.table;
import java.io.IOException;
import jupiter.common.map.parser.IParsers;
import jupiter.common.model.ICloneable;
import jupiter.common.util.Floats;
/**
* {@link FloatTable} is the {@link NumberTable} of {@link Float}.
*/
public class FloatTable
extends NumberTable<Float> {
////////////////////////////////////////////////////////////////////////////////////////////////
// CONSTANTS
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* The generated serial version ID.
*/
private static final long serialVersionUID = 1L;
////////////////////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructs a {@link FloatTable} with the specified numbers of rows and columns.
* <p>
* @param rowCount the number of rows
* @param columnCount the number of columns
*/
public FloatTable(final int rowCount, final int columnCount) {
super(Float.class, rowCount, columnCount);
}
/**
* Constructs a {@link FloatTable} with the specified header and numbers of rows and columns.
* <p>
* @param header an array of {@link String} (may be {@code null})
* @param rowCount the number of rows
* @param columnCount the number of columns
*/
public FloatTable(final String[] header, final int rowCount, final int columnCount) {
super(Float.class, header, rowCount, columnCount);
}
/**
* Constructs a {@link FloatTable} with the specified index, header and numbers of rows and
* columns.
* <p>
* @param index an array of {@link Object} (may be {@code null})
* @param header an array of {@link String} (may be {@code null})
* @param rowCount the number of rows
* @param columnCount the number of columns
*/
public FloatTable(final Object[] index, final String[] header, final int rowCount,
final int columnCount) {
super(Float.class, index, header, rowCount, columnCount);
}
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructs a {@link FloatTable} with the specified {@code float} values.
* <p>
* @param values a 2D {@code float} array
*/
public FloatTable(final float[]... values) {
this(Floats.toArray2D(values));
}
/**
* Constructs a {@link FloatTable} with the specified elements.
* <p>
* @param elements a 2D array of {@link Float}
*/
public FloatTable(final Float[]... elements) {
super(Float.class, elements);
}
/**
* Constructs a {@link FloatTable} with the specified header and values.
* <p>
* @param header an array of {@link String}
* @param values a 2D {@code float} array
*/
public FloatTable(final String[] header, final float[]... values) {
this(header, Floats.toArray2D(values));
}
/**
* Constructs a {@link FloatTable} with the specified header and elements.
* <p>
* @param header an array of {@link String}
* @param elements a 2D array of {@link Float}
*/
public FloatTable(final String[] header, final Float[]... elements) {
super(Float.class, header, elements);
}
/**
* Constructs a {@link FloatTable} with the specified index, header and values.
* <p>
* @param index an array of {@link Object} (may be {@code null})
* @param header an array of {@link String}
* @param values a 2D {@code float} array
*/
public FloatTable(final Object[] index, final String[] header, final float[]... values) {
this(index, header, Floats.toArray2D(values));
}
/**
* Constructs a {@link FloatTable} with specified index, header and elements.
* <p>
* @param index an array of {@link Object} (may be {@code null})
* @param header an array of {@link String}
* @param elements a 2D array of {@link Float}
*/
public FloatTable(final Object[] index, final String[] header, final Float[]... elements) {
super(Float.class, index, header, elements);
}
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructs a {@link FloatTable} loaded from the file denoted by the specified path.
* <p>
* @param path the path to the file to load
* @param hasHeader the flag specifying whether the file has a header
* <p>
* @throws IOException if there is a problem with reading the file denoted by {@code path}
*/
public FloatTable(final String path, final boolean hasHeader)
throws IOException {
super(IParsers.FLOAT_PARSER, path, hasHeader);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// CONVERTERS
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Returns a {@code float} array containing all the elements of {@code this} in the same order,
* or {@code null} if {@code this} is empty.
* <p>
* @return a {@code float} array containing all the elements of {@code this} in the same order,
* or {@code null} if {@code this} is empty
*
* @see Floats#toPrimitiveArray(Object[][])
*/
public float[] toPrimitiveArray() {
return Floats.toPrimitiveArray(elements);
}
/**
* Returns a 2D {@code float} array containing all the elements of {@code this} in the same
* order, or {@code null} if {@code this} is empty.
* <p>
* @return a 2D {@code float} array containing all the elements of {@code this} in the same
* order, or {@code null} if {@code this} is empty
*
* @see Floats#toPrimitiveArray2D(Object[][])
*/
public float[][] toPrimitiveArray2D() {
return Floats.toPrimitiveArray2D(elements);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// OBJECT
////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Clones {@code this}.
* <p>
* @return a clone of {@code this}
*
* @see ICloneable
*/
@Override
public FloatTable clone() {
return (FloatTable) super.clone();
}
}
| [
"florian@barras.io"
] | florian@barras.io |
3a1e278f61c33e766659e80276b498f193543677 | c0b37a664fde6a57ae61c4af635e6dea28d7905e | /Helpful dev stuff/AeriesMobilePortal_v1.2.0_apkpure.com_source_from_JADX/android/support/v4/content/SharedPreferencesCompat.java | 3766422aab313a080fe75ee1c8a854927dea9eaa | [] | no_license | joshkmartinez/Grades | a21ce8ede1371b9a7af11c4011e965f603c43291 | 53760e47f808780d06c4fbc2f74028a2db8e2942 | refs/heads/master | 2023-01-30T13:23:07.129566 | 2020-12-07T18:20:46 | 2020-12-07T18:20:46 | 131,549,535 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,543 | java | package android.support.v4.content;
import android.content.SharedPreferences.Editor;
import android.support.annotation.NonNull;
public final class SharedPreferencesCompat {
public static final class EditorCompat {
private static EditorCompat sInstance;
private final Helper mHelper = new Helper();
private static class Helper {
Helper() {
}
public void apply(@android.support.annotation.NonNull android.content.SharedPreferences.Editor r1) {
/* JADX: method processing error */
/*
Error: java.lang.NullPointerException
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.searchTryCatchDominators(ProcessTryCatchRegions.java:75)
at jadx.core.dex.visitors.regions.ProcessTryCatchRegions.process(ProcessTryCatchRegions.java:45)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.postProcessRegions(RegionMakerVisitor.java:63)
at jadx.core.dex.visitors.regions.RegionMakerVisitor.visit(RegionMakerVisitor.java:58)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:31)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:14)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:14)
at jadx.core.ProcessClass.process(ProcessClass.java:37)
at jadx.core.ProcessClass.processDependencies(ProcessClass.java:59)
at jadx.core.ProcessClass.process(ProcessClass.java:42)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:306)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
at jadx.api.JadxDecompiler$1.run(JadxDecompiler.java:199)
*/
/*
r0 = this;
r1.apply(); Catch:{ AbstractMethodError -> 0x0004 }
goto L_0x0007;
L_0x0004:
r1.commit();
L_0x0007:
return;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.content.SharedPreferencesCompat.EditorCompat.Helper.apply(android.content.SharedPreferences$Editor):void");
}
}
private EditorCompat() {
}
public static EditorCompat getInstance() {
if (sInstance == null) {
sInstance = new EditorCompat();
}
return sInstance;
}
public void apply(@NonNull Editor editor) {
this.mHelper.apply(editor);
}
}
private SharedPreferencesCompat() {
}
}
| [
"joshkmartinez@gmail.com"
] | joshkmartinez@gmail.com |
ac072c64df2fd221f3289b8e19ecf7e979965003 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_69a0d8db9ed071d1a6d1bd060975f6281dfc1f0f/DatastoreImpl/20_69a0d8db9ed071d1a6d1bd060975f6281dfc1f0f_DatastoreImpl_t.java | c25ecdc1e45466503d25b636cf24c7bf40256334 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 36,479 | java | package com.google.code.morphia;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.google.code.morphia.annotations.CappedAt;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Index;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.annotations.Indexes;
import com.google.code.morphia.annotations.PostPersist;
import com.google.code.morphia.annotations.Reference;
import com.google.code.morphia.annotations.Serialized;
import com.google.code.morphia.annotations.Version;
import com.google.code.morphia.logging.Logr;
import com.google.code.morphia.logging.MorphiaLoggerFactory;
import com.google.code.morphia.mapping.MappedClass;
import com.google.code.morphia.mapping.MappedField;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.mapping.MappingException;
import com.google.code.morphia.mapping.cache.EntityCache;
import com.google.code.morphia.mapping.lazy.DatastoreHolder;
import com.google.code.morphia.mapping.lazy.proxy.ProxiedEntityReference;
import com.google.code.morphia.mapping.lazy.proxy.ProxyHelper;
import com.google.code.morphia.query.FilterOperator;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryException;
import com.google.code.morphia.query.QueryImpl;
import com.google.code.morphia.query.UpdateException;
import com.google.code.morphia.query.UpdateOperations;
import com.google.code.morphia.query.UpdateOpsImpl;
import com.google.code.morphia.query.UpdateResults;
import com.google.code.morphia.utils.IndexDirection;
import com.google.code.morphia.utils.IndexFieldDef;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;
/**
* A generic (type-safe) wrapper around mongodb collections
*
* @author Scott Hernandez
*/
@SuppressWarnings({"unchecked", "deprecation" })
public class DatastoreImpl implements Datastore, AdvancedDatastore {
private static final Logr log = MorphiaLoggerFactory.get(DatastoreImpl.class);
// final protected Morphia morphia;
final protected Mapper mapr;
final protected Mongo mongo;
final protected DB db;
protected WriteConcern defConcern = WriteConcern.SAFE;
public DatastoreImpl(Morphia morphia, Mongo mongo) {
this(morphia, mongo, null);
}
public DatastoreImpl(Morphia morphia, Mongo mongo, String dbName, String username, char[] password) {
// this.morphia = morphia;
this.mapr = morphia.getMapper();
this.mongo = mongo;
this.db = mongo.getDB(dbName);
if (username != null)
this.db.authenticate(username, password);
// VERY discussable
DatastoreHolder.getInstance().set(this);
}
public DatastoreImpl(Morphia morphia, Mongo mongo, String dbName) {
this(morphia, mongo, dbName, null, null);
}
public <T, V> DBRef createRef(Class<T> clazz, V id) {
if (id == null)
throw new MappingException("Could not get id for " + clazz.getName());
return new DBRef(getDB(), getCollection(clazz).getName(), id);
}
public <T> DBRef createRef(T entity) {
entity = ProxyHelper.unwrap(entity);
Object id = getId(entity);
if (id == null)
throw new MappingException("Could not get id for " + entity.getClass().getName());
return createRef(entity.getClass(), id);
}
public <T> Key<T> getKey(T entity) {
if (entity instanceof ProxiedEntityReference) {
ProxiedEntityReference proxy = (ProxiedEntityReference) entity;
return (Key<T>) proxy.__getKey();
}
entity = ProxyHelper.unwrap(entity);
if (entity instanceof Key)
return (Key<T>) entity;
Object id = getId(entity);
if (id == null)
throw new MappingException("Could not get id for " + entity.getClass().getName());
return new Key<T>((Class<T>) entity.getClass(), id);
}
protected <T, V> void delete(DBCollection dbColl, V id, WriteConcern wc) {
WriteResult wr;
if (wc == null)
wr = dbColl.remove(BasicDBObjectBuilder.start().add(Mapper.ID_KEY, id).get());
else
wr = dbColl.remove(BasicDBObjectBuilder.start().add(Mapper.ID_KEY, id).get(), wc);
throwOnError(wc, wr);
}
public <T> void delete(String kind, T id) {
DBCollection dbColl = getCollection(kind);
delete(dbColl, id, defConcern);
}
public <T, V> void delete(Class<T> clazz, V id, WriteConcern wc) {
DBCollection dbColl = getCollection(clazz);
delete(dbColl, id, wc);
}
public <T, V> void delete(Class<T> clazz, V id) {
delete(clazz, id, getWriteConcern(clazz));
}
public <T, V> void delete(Class<T> clazz, Iterable<V> ids) {
Query<T> q = find(clazz).disableValidation().filter(Mapper.ID_KEY + " in", ids);
delete(q);
}
public <T> void delete(T entity) {
delete(entity, getWriteConcern(entity));
}
public <T> void delete(T entity, WriteConcern wc) {
entity = ProxyHelper.unwrap(entity);
if (entity instanceof Class<?>)
throw new MappingException("Did you mean to delete all documents? -- delete(ds.createQuery(???.class))");
try {
Object id = getId(entity);
delete(entity.getClass(), id, wc);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <T> void delete(Query<T> query) {
delete(query, getWriteConcern(query.getEntityClass()));
}
public <T> void delete(Query<T> query, WriteConcern wc) {
QueryImpl<T> q = (QueryImpl<T>) query;
DBCollection dbColl = getCollection(q.getEntityClass());
WriteResult wr;
if (q.getSortObject() != null || q.getOffset() != 0 || q.getLimit() > 0)
throw new QueryException("Delete does not allow sort/offset/limit query options.");
if (q.getQueryObject() != null)
if (wc == null)
wr = dbColl.remove(q.getQueryObject());
else
wr = dbColl.remove(q.getQueryObject(), wc);
else
if (wc == null)
wr = dbColl.remove(new BasicDBObject());
else
wr = dbColl.remove(new BasicDBObject(), wc);
throwOnError(wc, wr);
}
public <T> void ensureIndex(Class<T> type, String fields) {
ensureIndex(type, null, fields, false, false);
}
public <T> void ensureIndex(Class<T> clazz, String name, IndexFieldDef[] defs, boolean unique, boolean dropDupsOnCreate) {
ensureIndex(clazz, name, defs, unique, dropDupsOnCreate, false);
}
public <T> void ensureIndex(Class<T> clazz, String name, String fields, boolean unique, boolean dropDupsOnCreate) {
ensureIndex(clazz, name, QueryImpl.parseSortString(fields), unique, dropDupsOnCreate, false, false);
}
public <T> void ensureIndex(Class<T> clazz, String name, String fields, boolean unique, boolean dropDupsOnCreate, boolean background) {
ensureIndex(clazz, name, QueryImpl.parseSortString(fields), unique, dropDupsOnCreate, background, false);
}
protected <T> void ensureIndex(Class<T> clazz, String name, BasicDBObject fields, boolean unique, boolean dropDupsOnCreate, boolean background, boolean sparse) {
//validate field names and translate them to the stored values
BasicDBObject keys = new BasicDBObject();
for(Entry<String, Object> entry : fields.entrySet()){
StringBuffer sb = new StringBuffer(entry.getKey());
Mapper.validate(clazz, mapr, sb, FilterOperator.IN, "", true, false);
keys.put(sb.toString(), entry.getValue());
}
BasicDBObjectBuilder keyOpts = new BasicDBObjectBuilder();
if (name != null && name.length() > 0) {
keyOpts.add("name", name);
}
if (unique) {
keyOpts.add("unique", true);
if (dropDupsOnCreate)
keyOpts.add("dropDups", true);
}
if (background)
keyOpts.add("background", true);
if (sparse)
keyOpts.add("sparse", true);
DBCollection dbColl = getCollection(clazz);
BasicDBObject opts = (BasicDBObject) keyOpts.get();
if (opts.isEmpty()) {
log.debug("Ensuring index for " + dbColl.getName() + " with keys:" + keys);
dbColl.ensureIndex(keys);
} else {
log.debug("Ensuring index for " + dbColl.getName() + " with keys:" + keys + " and opts:" + opts);
dbColl.ensureIndex(keys, opts);
}
//TODO: remove this once using 2.4 driver does this in ensureIndex
CommandResult cr = dbColl.getDB().getLastError();
cr.throwOnError();
}
@SuppressWarnings({ "rawtypes"})
public void ensureIndex(Class clazz, String name, IndexFieldDef[] defs, boolean unique, boolean dropDupsOnCreate, boolean background) {
BasicDBObjectBuilder keys = BasicDBObjectBuilder.start();
for (IndexFieldDef def : defs) {
String fieldName = def.getField();
IndexDirection dir = def.getDirection();
keys.add(fieldName, dir.toIndexValue());
}
ensureIndex(clazz, name, (BasicDBObject) keys.get(), unique, dropDupsOnCreate, background, false);
}
public <T> void ensureIndex(Class<T> type, String name, IndexDirection dir) {
ensureIndex(type, new IndexFieldDef(name, dir));
}
public <T> void ensureIndex(Class<T> type, IndexFieldDef... fields) {
ensureIndex(type, null, fields, false, false);
}
public <T> void ensureIndex(Class<T> type, boolean background, IndexFieldDef... fields) {
ensureIndex(type, null, fields, false, false, background);
}
protected void ensureIndexes(MappedClass mc, boolean background) {
ensureIndexes(mc, background, new ArrayList<MappedClass>(), new ArrayList<MappedField>());
}
protected void ensureIndexes(MappedClass mc, boolean background, ArrayList<MappedClass> parentMCs, ArrayList<MappedField> parentMFs) {
if (parentMCs.contains(mc))
return;
//skip embedded types
if (mc.getEmbeddedAnnotation() != null && (parentMCs == null || parentMCs.isEmpty()))
return;
//Ensure indexes from class annotation
Indexes idxs = (Indexes) mc.getAnnotation(Indexes.class);
if (idxs != null && idxs.value() != null && idxs.value().length > 0)
for(Index index : idxs.value()) {
BasicDBObject fields = QueryImpl.parseSortString(index.value());
ensureIndex(mc.getClazz(), index.name(), fields, index.unique(), index.dropDups(), index.background() ? index.background() : background, index.sparse() ? index.sparse() : false );
}
//Ensure indexes from field annotations, and embedded entities
for (MappedField mf : mc.getPersistenceFields()) {
if (mf.hasAnnotation(Indexed.class)) {
Indexed index = mf.getAnnotation(Indexed.class);
StringBuilder field = new StringBuilder();
Class<?> indexedClass = (parentMCs.isEmpty() ? mc : parentMCs.get(0)).getClazz();
if (!parentMCs.isEmpty())
for(MappedField pmf : parentMFs)
field.append(pmf.getNameToStore()).append(".");
field.append(mf.getNameToStore());
ensureIndex(indexedClass, index.name(), new BasicDBObject(field.toString(), index.value().toIndexValue()), index.unique(), index.dropDups(), index.background() ? index.background() : background , index.sparse() ? index.sparse() : false);
}
if (!mf.isTypeMongoCompatible() && !mf.hasAnnotation(Reference.class) && !mf.hasAnnotation(Serialized.class)) {
ArrayList<MappedClass> newParentClasses = (ArrayList<MappedClass>) parentMCs.clone();
ArrayList<MappedField> newParents = (ArrayList<MappedField>) parentMFs.clone();
newParentClasses.add(mc);
newParents.add(mf);
ensureIndexes(mapr.getMappedClass(mf.isSingleValue() ? mf.getType() : mf.getSubClass()), background, newParentClasses, newParents);
}
}
}
public <T> void ensureIndexes(Class<T> clazz) {
ensureIndexes(clazz, false);
}
public <T> void ensureIndexes(Class<T> clazz, boolean background) {
MappedClass mc = mapr.getMappedClass(clazz);
ensureIndexes(mc, background);
}
public void ensureIndexes() {
ensureIndexes(false);
}
public void ensureIndexes(boolean background) {
// loops over mappedClasses and call ensureIndex for each @Entity object
// (for now)
for (MappedClass mc : mapr.getMappedClasses()) {
ensureIndexes(mc, background);
}
}
public void ensureCaps() {
for (MappedClass mc : mapr.getMappedClasses())
if (mc.getEntityAnnotation() != null && mc.getEntityAnnotation().cap().value() > 0) {
CappedAt cap = mc.getEntityAnnotation().cap();
String collName = mapr.getCollectionName(mc.getClazz());
BasicDBObjectBuilder dbCapOpts = BasicDBObjectBuilder.start("capped", true);
if (cap.value() > 0)
dbCapOpts.add("size", cap.value());
if (cap.count() > 0)
dbCapOpts.add("max", cap.count());
DB db = getDB();
if (db.getCollectionNames().contains(collName)) {
DBObject dbResult = db.command(BasicDBObjectBuilder.start("collstats", collName).get());
if (dbResult.containsField("capped")) {
// TODO: check the cap options.
log.warning("DBCollection already exists is cap'd already; doing nothing. " + dbResult);
} else {
log.warning("DBCollection already exists with same name(" + collName
+ ") and is not cap'd; not creating cap'd version!");
}
} else {
getDB().createCollection(collName, dbCapOpts.get());
log.debug("Created cap'd DBCollection (" + collName + ") with opts " + dbCapOpts);
}
}
}
public <T> Query<T> createQuery(Class<T> clazz) {
return new QueryImpl<T>(clazz, getCollection(clazz), this);
}
public <T> Query<T> createQuery(Class<T> kind, DBObject q) {
return new QueryImpl<T>(kind, getCollection(kind), this, q);
}
public <T> Query<T> find(String kind, Class<T> clazz) {
return new QueryImpl<T>(clazz, getCollection(kind), this);
}
public <T> Query<T> find(Class<T> clazz) {
return createQuery(clazz);
}
public <T, V> Query<T> find(Class<T> clazz, String property, V value) {
Query<T> query = createQuery(clazz);
return query.filter(property, value);
}
public <T, V> Query<T> find(String kind, Class<T> clazz, String property, V value, int offset, int size) {
Query<T> query = find(kind, clazz);
query.offset(offset);
query.limit(size);
return query.filter(property, value);
}
public <T, V> Query<T> find(Class<T> clazz, String property, V value, int offset, int size) {
Query<T> query = createQuery(clazz);
query.offset(offset);
query.limit(size);
return query.filter(property, value);
}
public <T> T get(Class<T> clazz, DBRef ref) {
return (T)mapr.fromDBObject(clazz, ref.fetch(), createCache());
}
public <T, V> Query<T> get(Class<T> clazz, Iterable<V> ids) {
return find(clazz).disableValidation().filter(Mapper.ID_KEY + " in", ids);
}
/** Queries the server to check for each DBRef */
public <T> List<Key<T>> getKeysByRefs(List<DBRef> refs) {
ArrayList<Key<T>> tempKeys = new ArrayList<Key<T>>(refs.size());
Map<String, List<DBRef>> kindMap = new HashMap<String, List<DBRef>>();
for (DBRef ref : refs) {
if (kindMap.containsKey(ref.getRef()))
kindMap.get(ref.getRef()).add(ref);
else
kindMap.put(ref.getRef(), new ArrayList<DBRef>(Collections.singletonList((DBRef) ref)));
}
for (String kind : kindMap.keySet()) {
List<Object> objIds = new ArrayList<Object>();
List<DBRef> kindRefs = kindMap.get(kind);
for (DBRef key : kindRefs) {
objIds.add(key.getId());
}
List<Key<T>> kindResults = this.<T>find(kind, null).disableValidation().filter("_id in", objIds).asKeyList();
tempKeys.addAll(kindResults);
}
//put them back in order, minus the missing ones.
ArrayList<Key<T>> keys = new ArrayList<Key<T>>(refs.size());
for (DBRef ref : refs) {
Key<T> testKey = mapr.refToKey(ref);
if (tempKeys.contains(testKey))
keys.add(testKey);
}
return keys;
}
public <T> List<T> getByKeys(Iterable<Key<T>> keys) {
return this.getByKeys((Class<T>) null, keys);
}
@SuppressWarnings("rawtypes")
public <T> List<T> getByKeys(Class<T> clazz, Iterable<Key<T>> keys) {
Map<String, List<Key>> kindMap = new HashMap<String, List<Key>>();
List<T> entities = new ArrayList<T>();
// String clazzKind = (clazz==null) ? null :
// getMapper().getCollectionName(clazz);
for (Key<?> key : keys) {
mapr.updateKind(key);
// if (clazzKind != null && !key.getKind().equals(clazzKind))
// throw new IllegalArgumentException("Types are not equal (" +
// clazz + "!=" + key.getKindClass() +
// ") for key and method parameter clazz");
//
if (kindMap.containsKey(key.getKind()))
kindMap.get(key.getKind()).add(key);
else
kindMap.put(key.getKind(), new ArrayList<Key>(Collections.singletonList((Key) key)));
}
for (String kind : kindMap.keySet()) {
List<Object> objIds = new ArrayList<Object>();
List<Key> kindKeys = kindMap.get(kind);
for (Key key : kindKeys) {
objIds.add(key.getId());
}
List kindResults = find(kind, null).disableValidation().filter("_id in", objIds).asList();
entities.addAll(kindResults);
}
//TODO: order them based on the incoming Keys.
return entities;
}
public <T, V> T get(String kind, Class<T> clazz, V id) {
List<T> results = find(kind, clazz, Mapper.ID_KEY, id, 0, 1).asList();
if (results == null || results.size() == 0)
return null;
return results.get(0);
}
public <T, V> T get(Class<T> clazz, V id) {
return find(getCollection(clazz).getName(), clazz, Mapper.ID_KEY, id, 0, 1).get();
}
public <T> T getByKey(Class<T> clazz, Key<T> key) {
String kind = mapr.getCollectionName(clazz);
String keyKind = mapr.updateKind(key);
if (!kind.equals(keyKind))
throw new RuntimeException("collection names don't match for key and class: " + kind + " != " + keyKind);
return get(clazz, key.getId());
}
public <T> T get(T entity) {
entity = ProxyHelper.unwrap(entity);
Object id = getId(entity);
if (id == null)
throw new MappingException("Could not get id for " + entity.getClass().getName());
return (T) get(entity.getClass(), id);
}
public Key<?> exists(Object entityOrKey) {
entityOrKey = ProxyHelper.unwrap(entityOrKey);
Key<?> key = getKey(entityOrKey);
Object id = key.getId();
if (id == null)
throw new MappingException("Could not get id for " + entityOrKey.getClass().getName());
return find(key.getKind(), key.getKindClass()).filter(Mapper.ID_KEY, key.getId()).getKey();
}
@SuppressWarnings("rawtypes")
public DBCollection getCollection(Class clazz) {
String collName = mapr.getCollectionName(clazz);
DBCollection dbC = getDB().getCollection(collName);
return dbC;
}
public DBCollection getCollection(Object obj) {
if (obj == null) return null;
return getCollection(obj.getClass());
}
protected DBCollection getCollection(String kind) {
if (kind == null) return null;
return getDB().getCollection(kind);
}
public <T> long getCount(T entity) {
entity = ProxyHelper.unwrap(entity);
return getCollection(entity).getCount();
}
public <T> long getCount(Class<T> clazz) {
return getCollection(clazz).getCount();
}
public long getCount(String kind) {
return getCollection(kind).getCount();
}
public <T> long getCount(Query<T> query) {
return query.countAll();
}
public Mongo getMongo() {
return this.mongo;
}
public DB getDB() {
return db;
}
protected Object getId(Object entity) {
entity = ProxyHelper.unwrap(entity);
// String keyClassName = entity.getClass().getName();
MappedClass mc = mapr.getMappedClass(entity.getClass());
//
// if (mapr.getMappedClasses().containsKey(keyClassName))
// mc = mapr.getMappedClasses().get(keyClassName);
// else
// mc = new MappedClass(entity.getClass(), getMapper());
//
try {
return mc.getIdField().get(entity);
} catch (Exception e) {
return null;
}
}
public Mapper getMapper() {
return mapr;
}
public <T> Iterable<Key<T>> insert(Iterable<T> entities) {
//TODO: try not to create two iterators...
Object first = entities.iterator().next();
return insert(entities, getWriteConcern(first));
}
public <T> Iterable<Key<T>> insert(Iterable<T> entities, WriteConcern wc) {
ArrayList<DBObject> ents = entities instanceof List ? new ArrayList<DBObject>(((List<T>)entities).size()) : new ArrayList<DBObject>();
Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
T lastEntity = null;
for (T ent : entities) {
ents.add(entityToDBObj(ent, involvedObjects));
lastEntity = ent;
}
DBCollection dbColl = getCollection(lastEntity);
WriteResult wr = null;
DBObject[] dbObjs = new DBObject[ents.size()];
dbColl.insert(ents.toArray(dbObjs), wc);
throwOnError(wc, wr);
ArrayList<Key<T>> savedKeys = new ArrayList<Key<T>>();
Iterator<T> entitiesIT = entities.iterator();
Iterator<DBObject> dbObjsIT = ents.iterator();
while (entitiesIT.hasNext()) {
T entity = entitiesIT.next();
DBObject dbObj = dbObjsIT.next();
savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
}
return savedKeys;
}
public <T> Iterable<Key<T>> insert(T...entities) {
return insert(Arrays.asList(entities), getWriteConcern(entities[0]));
}
public <T> Key<T> insert(T entity) {
return insert(entity, getWriteConcern(entity));
}
public <T> Key<T> insert(T entity, WriteConcern wc) {
entity = ProxyHelper.unwrap(entity);
DBCollection dbColl = getCollection(entity);
return insert(dbColl, entity, wc);
}
public <T> Key<T> insert(String kind, T entity) {
entity = ProxyHelper.unwrap(entity);
DBCollection dbColl = getCollection(kind);
return insert(dbColl, entity, getWriteConcern(entity));
}
public <T> Key<T> insert(String kind, T entity, WriteConcern wc) {
entity = ProxyHelper.unwrap(entity);
DBCollection dbColl = getCollection(kind);
return insert(dbColl, entity, wc);
}
protected <T> Key<T> insert(DBCollection dbColl, T entity, WriteConcern wc) {
LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
DBObject dbObj = entityToDBObj(entity, involvedObjects);
WriteResult wr;
if (wc == null)
wr = dbColl.insert(dbObj);
else
wr = dbColl.insert(dbObj, wc);
throwOnError(wc, wr);
return postSaveGetKey(entity, dbObj, dbColl, involvedObjects);
}
protected DBObject entityToDBObj(Object entity, Map<Object, DBObject> involvedObjects) {
entity = ProxyHelper.unwrap(entity);
DBObject dbObj = mapr.toDBObject(entity, involvedObjects);
return dbObj;
}
/** call postSaveOperations and returns Key for entity */
protected <T> Key<T> postSaveGetKey(T entity, DBObject dbObj, DBCollection dbColl, Map<Object, DBObject> involvedObjects){
if (dbObj.get(Mapper.ID_KEY) == null)
throw new MappingException("Missing _id after save!");
postSaveOperations(entity, dbObj, dbColl, involvedObjects);
Key<T> key = new Key<T>(dbColl.getName(), getId(entity));
key.setKindClass((Class<? extends T>) entity.getClass());
return key;
}
public <T> Iterable<Key<T>> save(Iterable<T> entities) {
Object first = null;
try {
first = entities.iterator().next();
} catch (Exception e) {
//do nothing
}
return save(entities, getWriteConcern(first));
}
public <T> Iterable<Key<T>> save(Iterable<T> entities, WriteConcern wc) {
ArrayList<Key<T>> savedKeys = new ArrayList<Key<T>>();
for (T ent : entities)
savedKeys.add(save(ent, wc));
return savedKeys;
}
public <T> Iterable<Key<T>> save(T... entities) {
ArrayList<Key<T>> savedKeys = new ArrayList<Key<T>>();
for (T ent : entities)
savedKeys.add(save(ent));
return savedKeys;
}
protected <T> Key<T> save(DBCollection dbColl, T entity, WriteConcern wc) {
MappedClass mc = mapr.getMappedClass(entity);
WriteResult wr = null;
//involvedObjects is used not only as a cache but also as a list of what needs to be called for life-cycle methods at the end.
LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
DBObject dbObj = entityToDBObj(entity, involvedObjects);
//try to do an update if there is a @Version field
wr = tryVersionedUpdate(dbColl, entity, dbObj, wc, db, mc);
if(wr == null)
if (wc == null)
wr = dbColl.save(dbObj);
else
wr = dbColl.save(dbObj, wc);
throwOnError(wc, wr);
return postSaveGetKey(entity, dbObj, dbColl, involvedObjects);
}
protected <T> WriteResult tryVersionedUpdate(DBCollection dbColl, T entity, DBObject dbObj, WriteConcern wc, DB db, MappedClass mc) {
WriteResult wr = null;
if (mc.getFieldsAnnotatedWith(Version.class).isEmpty())
return wr;
MappedField mfVersion = mc.getFieldsAnnotatedWith(Version.class).get(0);
String versionKeyName = mfVersion.getNameToStore();
Long oldVersion = (Long) mfVersion.getFieldValue(entity);
long newVersion = VersionHelper.nextValue(oldVersion);
dbObj.put(versionKeyName, newVersion);
if (oldVersion != null && oldVersion > 0) {
Object idValue = dbObj.get(Mapper.ID_KEY);
UpdateResults<T> res = update( find((Class<T>) entity.getClass(), Mapper.ID_KEY, idValue).filter(versionKeyName, oldVersion),
dbObj,
false,
false,
wc);
wr = res.getWriteResult();
if (res.getUpdatedCount() != 1)
throw new ConcurrentModificationException("Entity of class " + entity.getClass().getName()
+ " (id='" + idValue + "',version='" + oldVersion + "') was concurrently updated.");
} else
if (wc == null)
wr = dbColl.save(dbObj);
else
wr = dbColl.save(dbObj, wc);
//update the version.
mfVersion.setFieldValue(entity, newVersion);
return wr;
}
protected void throwOnError(WriteConcern wc, WriteResult wr) {
if ( wc == null && wr.getLastConcern() == null) {
CommandResult cr = wr.getLastError();
if (cr != null && cr.getErrorMessage() != null && cr.getErrorMessage().length() > 0)
cr.throwOnError();
}
}
private void firePostPersistForChildren(Map<Object, DBObject> involvedObjects) {
for (Map.Entry<Object, DBObject> e : involvedObjects.entrySet()) {
Object entity = e.getKey();
DBObject dbObj = e.getValue();
MappedClass mc = mapr.getMappedClass(entity);
mc.callLifecycleMethods(PostPersist.class, entity, dbObj, mapr);
}
}
public <T> Key<T> save(String kind, T entity) {
entity = ProxyHelper.unwrap(entity);
DBCollection dbColl = getCollection(kind);
return save(dbColl, entity, getWriteConcern(entity));
}
public <T> Key<T> save(T entity) {
return save(entity, getWriteConcern(entity));
}
public <T> Key<T> save(T entity, WriteConcern wc) {
entity = ProxyHelper.unwrap(entity);
DBCollection dbColl = getCollection(entity);
return save(dbColl, entity, wc);
}
public <T> UpdateOperations<T> createUpdateOperations(Class<T> clazz) {
return new UpdateOpsImpl<T>(clazz, getMapper());
}
public <T> UpdateOperations<T> createUpdateOperations(Class<T> kind, DBObject ops) {
UpdateOpsImpl<T> upOps = (UpdateOpsImpl<T>) createUpdateOperations(kind);
upOps.setOps(ops);
return upOps;
}
public <T> UpdateResults<T> update(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing) {
return update(query, ops, createIfMissing, getWriteConcern(query.getEntityClass()));
}
public <T> UpdateResults<T> update(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing, WriteConcern wc) {
return update(query, ops, createIfMissing, false);
}
public <T> UpdateResults<T> update(T ent, UpdateOperations<T> ops) {
MappedClass mc = mapr.getMappedClass(ent);
Query<T> q = (Query<T>) createQuery(mc.getClazz());
q.disableValidation().filter(Mapper.ID_KEY, getId(ent));
if (mc.getFieldsAnnotatedWith(Version.class).size() > 0) {
MappedField versionMF = mc.getFieldsAnnotatedWith(Version.class).get(0);
Long oldVer = (Long)versionMF.getFieldValue(ent);
q.filter(versionMF.getNameToStore(), oldVer);
ops.set(versionMF.getNameToStore(), VersionHelper.nextValue(oldVer));
}
return update(q, ops);
}
public <T> UpdateResults<T> update(Key<T> key, UpdateOperations<T> ops) {
Class<T> clazz = (Class<T>) key.getKindClass();
if (clazz == null)
clazz = (Class<T>) mapr.getClassFromKind(key.getKind());
return updateFirst(createQuery(clazz).disableValidation().filter(Mapper.ID_KEY, key.getId()), ops);
}
public <T> UpdateResults<T> update(Query<T> query, UpdateOperations<T> ops) {
return update(query, ops, false, true);
}
public <T> UpdateResults<T> updateFirst(Query<T> query, UpdateOperations<T> ops) {
return update(query, ops, false, false);
}
public <T> UpdateResults<T> updateFirst(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing) {
return update(query, ops, createIfMissing, getWriteConcern(query.getEntityClass()));
}
public <T> UpdateResults<T> updateFirst(Query<T> query, UpdateOperations<T> ops, boolean createIfMissing, WriteConcern wc) {
return update(query, ops, createIfMissing, false, wc);
}
public <T> UpdateResults<T> updateFirst(Query<T> query, T entity, boolean createIfMissing) {
LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
DBObject dbObj = mapr.toDBObject(entity, involvedObjects);
UpdateResults<T> res = update(query, dbObj, createIfMissing, false, getWriteConcern(entity));
//update _id field
CommandResult gle = res.getWriteResult().getCachedLastError();
if(gle != null && res.getInsertedCount() > 0)
dbObj.put(Mapper.ID_KEY, res.getNewId());
postSaveOperations(entity, dbObj, getCollection(entity), involvedObjects);
return res;
}
public <T> Key<T> merge(T entity) {
return merge(entity, getWriteConcern(entity));
}
public <T> Key<T> merge(T entity, WriteConcern wc) {
LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
DBObject dbObj = mapr.toDBObject(entity, involvedObjects);
Key<T> key = getKey(entity);
entity = ProxyHelper.unwrap(entity);
Object id = getId(entity);
if (id == null)
throw new MappingException("Could not get id for " + entity.getClass().getName());
Query<T> query = (Query<T>) createQuery(entity.getClass()).filter(Mapper.ID_KEY, id);
UpdateResults<T> res = update(query, new BasicDBObject("$set", dbObj), false, false, wc);
//check for updated count if we have a gle
CommandResult gle = res.getWriteResult().getCachedLastError();
if(gle != null && res.getUpdatedCount() == 0)
throw new UpdateException("Not updated: " + gle);
postSaveOperations(entity, dbObj, getCollection(entity), involvedObjects);
return key;
}
private <T> void postSaveOperations(Object entity, DBObject dbObj, DBCollection dbColl,
Map<Object, DBObject> involvedObjects) {
MappedClass mc = mapr.getMappedClass(entity);
mapr.updateKeyInfo(entity, dbObj, createCache());
firePostPersistForChildren(involvedObjects);
mc.callLifecycleMethods(PostPersist.class, entity, dbObj, mapr);
}
@SuppressWarnings("rawtypes")
private <T> UpdateResults<T> update(Query<T> query, UpdateOperations ops, boolean createIfMissing, boolean multi, WriteConcern wc) {
DBObject u = ((UpdateOpsImpl) ops).getOps();
if (((UpdateOpsImpl) ops).isIsolated()) {
Query<T> q = query.clone();
q.disableValidation().filter("$atomic", true);
return update(q, u, createIfMissing, multi, wc);
}
return update(query, u, createIfMissing, multi, wc);
}
@SuppressWarnings("rawtypes")
private <T> UpdateResults<T> update(Query<T> query, UpdateOperations ops, boolean createIfMissing, boolean multi) {
return update(query, ops, createIfMissing, multi, getWriteConcern(query.getEntityClass()));
}
private <T> UpdateResults<T> update(Query<T> query, DBObject u, boolean createIfMissing, boolean multi, WriteConcern wc) {
DBCollection dbColl = getCollection(((QueryImpl<T>) query).getEntityClass());
QueryImpl<T> qImpl= (QueryImpl<T>) query;
if ( qImpl.getSortObject() != null && qImpl.getSortObject().keySet() != null && !qImpl.getSortObject().keySet().isEmpty())
throw new QueryException("sorting is not allowed for updates.");
if ( qImpl.getOffset() > 0)
throw new QueryException("a query offset is not allowed for updates.");
if ( qImpl.getLimit() > 0)
throw new QueryException("a query limit is not allowed for updates.");
DBObject q = qImpl.getQueryObject();
if (q == null)
q = new BasicDBObject();
if (log.isTraceEnabled())
log.trace("Executing update(" + dbColl.getName() + ") for query: " + q + ", ops: " + u + ", multi: " + multi + ", upsert: " + createIfMissing);
WriteResult wr;
if (wc == null)
wr = dbColl.update(q, u, createIfMissing, multi);
else
wr = dbColl.update(q, u, createIfMissing, multi, wc);
throwOnError(wc, wr);
return new UpdateResults<T>(wr);
}
public <T> T findAndDelete(Query<T> query) {
DBCollection dbColl = getCollection(((QueryImpl<T>) query).getEntityClass());
QueryImpl<T> qi = ((QueryImpl<T>) query);
EntityCache cache = createCache();
if (log.isTraceEnabled())
log.trace("Executing findAndModify(" + dbColl.getName() + ") with delete ...");
DBObject result = dbColl.findAndModify(qi.getQueryObject(), qi.getFieldsObject(), qi.getSortObject(), true, null, false, false);
if (result != null) {
T entity = (T) mapr.fromDBObject(qi.getEntityClass(), result, cache);
return entity;
}
return null;
}
public <T> T findAndModify(Query<T> q, UpdateOperations<T> ops) {
return findAndModify(q, ops, false);
}
public <T> T findAndModify(Query<T> query, UpdateOperations<T> ops, boolean oldVersion) {
return findAndModify(query,ops,oldVersion, false);
}
public <T> T findAndModify(Query<T> query, UpdateOperations<T> ops, boolean oldVersion, boolean createIfMissing) {
DBCollection dbColl = getCollection(((QueryImpl<T>) query).getEntityClass());
QueryImpl<T> qi = ((QueryImpl<T>) query);
if (log.isTraceEnabled())
log.info("Executing findAndModify(" + dbColl.getName() + ") with update ");
DBObject res = dbColl.findAndModify(qi.getQueryObject(),
qi.getFieldsObject(),
qi.getSortObject(),
false,
((UpdateOpsImpl<T>) ops).getOps(), !oldVersion,
createIfMissing);
if (res == null)
return null;
else
return (T) mapr.fromDBObject(qi.getEntityClass(), res, createCache());
}
/** Converts a list of keys to refs */
public static <T> List<DBRef> keysAsRefs(List<Key<T>> keys, Mapper mapr){
ArrayList<DBRef> refs = new ArrayList<DBRef>(keys.size());
for(Key<T> key : keys)
refs.add(mapr.keyToRef(key));
return refs;
}
/** Converts a list of refs to keys */
public static <T> List<Key<T>> refsToKeys(Mapper mapr, List<DBRef> refs, Class<T> c) {
ArrayList<Key<T>> keys = new ArrayList<Key<T>>(refs.size());
for(DBRef ref : refs) {
keys.add((Key<T>)mapr.refToKey(ref));
}
return keys;
}
private EntityCache createCache() {
return mapr.createEntityCache();
}
/** Gets the write concern for entity or returns the default write concern for this datastore */
public WriteConcern getWriteConcern(Object clazzOrEntity) {
if (clazzOrEntity != null) {
Entity entityAnn = getMapper().getMappedClass(clazzOrEntity).getEntityAnnotation();
if(entityAnn != null && entityAnn.concern() != null && entityAnn.concern() != "" )
return WriteConcern.valueOf(entityAnn.concern());
}
return defConcern;
}
public WriteConcern getDefaultWriteConcern() {return defConcern;}
public void setDefaultWriteConcern(WriteConcern wc) {defConcern = wc;}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
12c98d59e0ad0fdd391499d98defd577113ae48a | 4da9f2ffd12d2f23654344eded70702373251093 | /src/main/java/code/tianmao/h5/domain/sys/Role.java | 2c9b2d25e1284a027d760a3962afb735320bb543 | [] | no_license | yangmain/houtai | 3b18543da4c0e5803d2f7e20e8bc17e8992fd49a | 931b41eea9e4472d4deae621ee92d19a3cdf2e80 | refs/heads/master | 2020-09-13T23:24:01.421011 | 2016-12-19T08:39:38 | 2016-12-19T08:39:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 617 | java | package code.tianmao.h5.domain.sys;
import code.tianmao.h5.domain.base.BaseDomain;
import javax.persistence.Table;
@Table(name = "sys_role")
public class Role extends BaseDomain<Long, Long> {
private static final long serialVersionUID = -5524318932380869754L;
private String name;
private String valid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getValid() {
return valid;
}
public void setValid(String valid) {
this.valid = valid;
}
} | [
"250765908@qq.com"
] | 250765908@qq.com |
1902a04374b556c87cabf408dc4b96a4c549afaf | de96fae935f388afb2eb131fd155b5684df88c2f | /sys-provider/src/main/java/com/kerry/datasource/DruidStatFilter.java | 245b99853c93781ba72c42dd85ec708d5676a2e0 | [] | no_license | rongliang/estatePlatform | 9502697112fd8b53d3c56494fc76e606b4e6de57 | b938070cedbe8a8946c563eb713290096b65c7de | refs/heads/master | 2021-01-20T05:41:14.288450 | 2017-08-14T08:49:35 | 2017-08-14T08:49:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 491 | java | package com.kerry.datasource;
import com.alibaba.druid.support.http.WebStatFilter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
* Created by wangshen on 2017/7/26.
*/
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
})
public class DruidStatFilter extends WebStatFilter {
}
| [
"280232086@qq.com"
] | 280232086@qq.com |
418ef5189812af28d8860e33bc0f5e41836797cb | a0caa255f3dbe524437715adaee2094ac8eff9df | /src/main/java/p000/bgx.java | 3f69668ee159ab34d380b0cd16ea6690ed4e7885 | [] | no_license | AndroidTVDeveloper/com.google.android.tvlauncher | 16526208b5b48fd48931b09ed702fe606fe7d694 | 0f959c41bbb5a93e981145f371afdec2b3e207bc | refs/heads/master | 2021-01-26T07:47:23.091351 | 2020-02-26T20:58:19 | 2020-02-26T20:58:19 | 243,363,961 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,397 | java | package p000;
import android.view.View;
import android.widget.TextView;
/* renamed from: bgx */
/* compiled from: PG */
final class bgx implements View.OnClickListener, aks, bhf {
/* renamed from: a */
private final /* synthetic */ bgz f3877a;
public /* synthetic */ bgx(bgz bgz) {
this.f3877a = bgz;
}
/* renamed from: a */
public final void mo466a() {
}
/* renamed from: b */
public final void mo468b() {
}
/* renamed from: d */
public final void mo471d() {
}
/* renamed from: e */
public final void mo472e() {
}
/* renamed from: f */
public final void mo473f() {
}
/* renamed from: g */
public final void mo474g() {
}
/* renamed from: k */
public final void mo478k() {
}
public final void onClick(View view) {
bgz bgz = this.f3877a;
akt akt = bgz.f3900m;
if (akt == null) {
return;
}
if (bgz.f3890c == view) {
bgz.mo1903c(akt);
} else if (bgz.f3889b == view) {
bgz.mo1900b(akt);
} else if (bgz.f3893f == view) {
bgz.mo1909e(akt);
} else if (bgz.f3894g != view) {
int i = 1;
if (bgz.f3891d == view) {
if (akt.mo392f() != 1 && akt.mo392f() == 4) {
bgz.m3192a(akt, akt.mo397k(), -9223372036854775807L);
}
this.f3877a.f3901n.mo374a(akt, true);
} else if (bgz.f3892e == view) {
bgz.f3901n.mo374a(akt, false);
} else if (bgz.f3895h == view) {
int i2 = akt.mo395i();
while (true) {
if (i <= 2) {
int i3 = (i2 + i) % 3;
if (i3 == 0) {
i2 = i3;
break;
}
i++;
} else {
break;
}
}
ald ald = (ald) akt;
ald.mo523u();
ajy ajy = ald.f644b;
if (ajy.f484i != i2) {
ajy.f484i = i2;
ajy.f479d.f516a.mo2041a(12, i2).sendToTarget();
ajy.mo386a(new ajj());
}
} else if (bgz.f3896i == view) {
boolean z = !akt.mo396j();
ald ald2 = (ald) akt;
ald2.mo523u();
ajy ajy2 = ald2.f644b;
if (ajy2.f485j != z) {
ajy2.f485j = z;
ajy2.f479d.f516a.mo2041a(13, z ? 1 : 0).sendToTarget();
ajy2.mo386a(new ajk());
}
}
} else {
bgz.mo1905d(akt);
}
}
/* renamed from: c */
public final void mo470c() {
this.f3877a.mo1914j();
}
/* renamed from: b */
public final void mo469b(int i) {
this.f3877a.mo1908e();
this.f3877a.mo1914j();
}
/* renamed from: h */
public final void mo475h() {
this.f3877a.mo1910f();
this.f3877a.mo1913i();
}
/* renamed from: i */
public final void mo476i() {
this.f3877a.mo1911g();
this.f3877a.mo1910f();
}
/* renamed from: a */
public final void mo1892a(long j) {
bgz bgz = this.f3877a;
TextView textView = bgz.f3897j;
if (textView != null) {
textView.setText(blm.m3639a(bgz.f3898k, bgz.f3899l, j));
}
}
/* renamed from: b */
public final void mo1894b(long j) {
bgz bgz = this.f3877a;
bgz.f3902o = true;
TextView textView = bgz.f3897j;
if (textView != null) {
textView.setText(blm.m3639a(bgz.f3898k, bgz.f3899l, j));
}
}
/* renamed from: a */
public final void mo1893a(long j, boolean z) {
akt akt;
bgz bgz = this.f3877a;
bgz.f3902o = false;
if (!z && (akt = bgz.f3900m) != null) {
akt.mo404r();
bgz.m3192a(akt, akt.mo397k(), j);
}
}
/* renamed from: j */
public final void mo477j() {
this.f3877a.mo1912h();
this.f3877a.mo1910f();
}
/* renamed from: a */
public final void mo467a(alh alh) {
this.f3877a.mo1910f();
this.f3877a.mo1913i();
}
}
| [
"eliminater74@gmail.com"
] | eliminater74@gmail.com |
2420137c67819da47847a9b604daabee42a0a5a6 | 7fbd4d3baf5dc491cefb1c640ddec38de298f676 | /lesson5/src/main/java/ru/kalantyr/java/lesson5/Car.java | 707a30ecee5ae58c8b581be54827653520aefe70 | [] | no_license | kalantyr/gb_lessons | b6cc1cafba562326664dcf4bbe8588e7ae537122 | ffb839688be6cb53144db566bf8fec9db2bf38e8 | refs/heads/main | 2023-06-10T03:20:15.162293 | 2021-06-23T05:55:16 | 2021-06-23T05:55:16 | 366,443,179 | 0 | 0 | null | 2021-06-30T06:13:59 | 2021-05-11T16:11:26 | Java | UTF-8 | Java | false | false | 905 | java | package ru.kalantyr.java.lesson5;
public class Car implements Runnable {
private static int CARS_COUNT;
private Race race;
private int speed;
private String name;
public String getName() {
return name;
}
public int getSpeed() {
return speed;
}
public Car(Race race, int speed) {
this.race = race;
this.speed = speed;
CARS_COUNT++;
this.name = "Участник #" + CARS_COUNT;
}
@Override
public void run() {
try {
System.out.println(this.name + " готовится");
Thread.sleep(500 + (int)(Math.random() * 800));
System.out.println(this.name + " готов");
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < race.getStages().size(); i++) {
race.getStages().get(i).go(this);
}
}
} | [
"kalantyr@yandex.ru"
] | kalantyr@yandex.ru |
f63e08c926056fe05c7a148a9b3f9afd6166e62f | efdb580ea584d655e33edf6fc65d03ea21a2e9a3 | /02267/code/TravelGoodRESTTest/src/ws/dtu/model/HotelBooking.java | 110ecd93cc1f819684ee73417cfea236053c9b54 | [] | no_license | rostgaard/dtu-course-work-archive | 51736253dd4796bcefa86cfe531fd8b0fa7d90a0 | 97eb8b1fc10f51b7e649acd7cdd49c1fc4fc3b0b | refs/heads/master | 2021-01-16T18:51:04.162416 | 2015-04-15T18:57:02 | 2015-04-15T18:57:02 | 33,773,701 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,136 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ws.dtu.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import ws.dtu.niceview.types.HotelInformation;
@XmlRootElement
public class HotelBooking {
public enum HotelBookingState {
UNCONFIRMED, CONFIRMED, CANCELLED
}
public HotelBooking() {
}
public HotelBooking(HotelInformation hotel) {
this.hotelInformation = hotel;
}
private HotelInformation hotelInformation;
private HotelBookingState bookingState = HotelBookingState.UNCONFIRMED;
@XmlElement
public HotelInformation getHotelInformation() {
return hotelInformation;
}
@XmlElement
public HotelBookingState getBookingState() {
return bookingState;
}
public void setHotelInformation(HotelInformation hotelInformation) {
this.hotelInformation = hotelInformation;
}
public void setBookingState(HotelBookingState bookingState) {
this.bookingState = bookingState;
}
}
| [
"peter@shapehq.com"
] | peter@shapehq.com |
8cf4d0966b54c233cee0bc770578cb55217a27c1 | e8fbca7a6851b82c9ae3f805234c840e11f7c261 | /modules/thirdparty/batik/sources/org/apache/flex/forks/batik/ext/awt/image/codec/tiff/TIFFFaxDecoder.java | 14a001e541fe735633287b07e0bc8f01cad5efaf | [
"Apache-2.0",
"W3C",
"LicenseRef-scancode-proprietary-license",
"MPL-1.1",
"MPL-1.0",
"BSD-3-Clause"
] | permissive | teramura/flex-sdk | 6772f7c729bb5fde5a080f5bed4df53280043024 | c281c4f248f9adc8f10910be5e070149477d9216 | refs/heads/develop | 2023-05-13T21:26:18.785749 | 2023-04-28T15:10:59 | 2023-04-28T15:10:59 | 91,769,399 | 0 | 0 | Apache-2.0 | 2018-06-27T10:44:03 | 2017-05-19T05:38:06 | ActionScript | UTF-8 | Java | false | false | 54,574 | java | /*
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.flex.forks.batik.ext.awt.image.codec.tiff;
/**
*
* @version $Id: TIFFFaxDecoder.java 498740 2007-01-22 18:35:57Z dvholten $
*/
class TIFFFaxDecoder {
private int bitPointer, bytePointer;
private byte[] data;
private int w, h;
private int fillOrder;
// Data structures needed to store changing elements for the previous
// and the current scanline
private int changingElemSize = 0;
private int[] prevChangingElems;
private int[] currChangingElems;
// Element at which to start search in getNextChangingElement
private int lastChangingElement = 0;
private int compression = 2;
// Variables set by T4Options
private int uncompressedMode = 0;
private int fillBits = 0;
private int oneD;
static int[] table1 = {
0x00, // 0 bits are left in first byte - SHOULD NOT HAPPEN
0x01, // 1 bits are left in first byte
0x03, // 2 bits are left in first byte
0x07, // 3 bits are left in first byte
0x0f, // 4 bits are left in first byte
0x1f, // 5 bits are left in first byte
0x3f, // 6 bits are left in first byte
0x7f, // 7 bits are left in first byte
0xff // 8 bits are left in first byte
};
static int[] table2 = {
0x00, // 0
0x80, // 1
0xc0, // 2
0xe0, // 3
0xf0, // 4
0xf8, // 5
0xfc, // 6
0xfe, // 7
0xff // 8
};
// Table to be used when fillOrder = 2, for flipping bytes.
static byte[] flipTable = {
0, -128, 64, -64, 32, -96, 96, -32,
16, -112, 80, -48, 48, -80, 112, -16,
8, -120, 72, -56, 40, -88, 104, -24,
24, -104, 88, -40, 56, -72, 120, -8,
4, -124, 68, -60, 36, -92, 100, -28,
20, -108, 84, -44, 52, -76, 116, -12,
12, -116, 76, -52, 44, -84, 108, -20,
28, -100, 92, -36, 60, -68, 124, -4,
2, -126, 66, -62, 34, -94, 98, -30,
18, -110, 82, -46, 50, -78, 114, -14,
10, -118, 74, -54, 42, -86, 106, -22,
26, -102, 90, -38, 58, -70, 122, -6,
6, -122, 70, -58, 38, -90, 102, -26,
22, -106, 86, -42, 54, -74, 118, -10,
14, -114, 78, -50, 46, -82, 110, -18,
30, -98, 94, -34, 62, -66, 126, -2,
1, -127, 65, -63, 33, -95, 97, -31,
17, -111, 81, -47, 49, -79, 113, -15,
9, -119, 73, -55, 41, -87, 105, -23,
25, -103, 89, -39, 57, -71, 121, -7,
5, -123, 69, -59, 37, -91, 101, -27,
21, -107, 85, -43, 53, -75, 117, -11,
13, -115, 77, -51, 45, -83, 109, -19,
29, -99, 93, -35, 61, -67, 125, -3,
3, -125, 67, -61, 35, -93, 99, -29,
19, -109, 83, -45, 51, -77, 115, -13,
11, -117, 75, -53, 43, -85, 107, -21,
27, -101, 91, -37, 59, -69, 123, -5,
7, -121, 71, -57, 39, -89, 103, -25,
23, -105, 87, -41, 55, -73, 119, -9,
15, -113, 79, -49, 47, -81, 111, -17,
31, -97, 95, -33, 63, -65, 127, -1,
};
// The main 10 bit white runs lookup table
static short[] white = {
// 0 - 7
6430, 6400, 6400, 6400, 3225, 3225, 3225, 3225,
// 8 - 15
944, 944, 944, 944, 976, 976, 976, 976,
// 16 - 23
1456, 1456, 1456, 1456, 1488, 1488, 1488, 1488,
// 24 - 31
718, 718, 718, 718, 718, 718, 718, 718,
// 32 - 39
750, 750, 750, 750, 750, 750, 750, 750,
// 40 - 47
1520, 1520, 1520, 1520, 1552, 1552, 1552, 1552,
// 48 - 55
428, 428, 428, 428, 428, 428, 428, 428,
// 56 - 63
428, 428, 428, 428, 428, 428, 428, 428,
// 64 - 71
654, 654, 654, 654, 654, 654, 654, 654,
// 72 - 79
1072, 1072, 1072, 1072, 1104, 1104, 1104, 1104,
// 80 - 87
1136, 1136, 1136, 1136, 1168, 1168, 1168, 1168,
// 88 - 95
1200, 1200, 1200, 1200, 1232, 1232, 1232, 1232,
// 96 - 103
622, 622, 622, 622, 622, 622, 622, 622,
// 104 - 111
1008, 1008, 1008, 1008, 1040, 1040, 1040, 1040,
// 112 - 119
44, 44, 44, 44, 44, 44, 44, 44,
// 120 - 127
44, 44, 44, 44, 44, 44, 44, 44,
// 128 - 135
396, 396, 396, 396, 396, 396, 396, 396,
// 136 - 143
396, 396, 396, 396, 396, 396, 396, 396,
// 144 - 151
1712, 1712, 1712, 1712, 1744, 1744, 1744, 1744,
// 152 - 159
846, 846, 846, 846, 846, 846, 846, 846,
// 160 - 167
1264, 1264, 1264, 1264, 1296, 1296, 1296, 1296,
// 168 - 175
1328, 1328, 1328, 1328, 1360, 1360, 1360, 1360,
// 176 - 183
1392, 1392, 1392, 1392, 1424, 1424, 1424, 1424,
// 184 - 191
686, 686, 686, 686, 686, 686, 686, 686,
// 192 - 199
910, 910, 910, 910, 910, 910, 910, 910,
// 200 - 207
1968, 1968, 1968, 1968, 2000, 2000, 2000, 2000,
// 208 - 215
2032, 2032, 2032, 2032, 16, 16, 16, 16,
// 216 - 223
10257, 10257, 10257, 10257, 12305, 12305, 12305, 12305,
// 224 - 231
330, 330, 330, 330, 330, 330, 330, 330,
// 232 - 239
330, 330, 330, 330, 330, 330, 330, 330,
// 240 - 247
330, 330, 330, 330, 330, 330, 330, 330,
// 248 - 255
330, 330, 330, 330, 330, 330, 330, 330,
// 256 - 263
362, 362, 362, 362, 362, 362, 362, 362,
// 264 - 271
362, 362, 362, 362, 362, 362, 362, 362,
// 272 - 279
362, 362, 362, 362, 362, 362, 362, 362,
// 280 - 287
362, 362, 362, 362, 362, 362, 362, 362,
// 288 - 295
878, 878, 878, 878, 878, 878, 878, 878,
// 296 - 303
1904, 1904, 1904, 1904, 1936, 1936, 1936, 1936,
// 304 - 311
-18413, -18413, -16365, -16365, -14317, -14317, -10221, -10221,
// 312 - 319
590, 590, 590, 590, 590, 590, 590, 590,
// 320 - 327
782, 782, 782, 782, 782, 782, 782, 782,
// 328 - 335
1584, 1584, 1584, 1584, 1616, 1616, 1616, 1616,
// 336 - 343
1648, 1648, 1648, 1648, 1680, 1680, 1680, 1680,
// 344 - 351
814, 814, 814, 814, 814, 814, 814, 814,
// 352 - 359
1776, 1776, 1776, 1776, 1808, 1808, 1808, 1808,
// 360 - 367
1840, 1840, 1840, 1840, 1872, 1872, 1872, 1872,
// 368 - 375
6157, 6157, 6157, 6157, 6157, 6157, 6157, 6157,
// 376 - 383
6157, 6157, 6157, 6157, 6157, 6157, 6157, 6157,
// 384 - 391
-12275, -12275, -12275, -12275, -12275, -12275, -12275, -12275,
// 392 - 399
-12275, -12275, -12275, -12275, -12275, -12275, -12275, -12275,
// 400 - 407
14353, 14353, 14353, 14353, 16401, 16401, 16401, 16401,
// 408 - 415
22547, 22547, 24595, 24595, 20497, 20497, 20497, 20497,
// 416 - 423
18449, 18449, 18449, 18449, 26643, 26643, 28691, 28691,
// 424 - 431
30739, 30739, -32749, -32749, -30701, -30701, -28653, -28653,
// 432 - 439
-26605, -26605, -24557, -24557, -22509, -22509, -20461, -20461,
// 440 - 447
8207, 8207, 8207, 8207, 8207, 8207, 8207, 8207,
// 448 - 455
72, 72, 72, 72, 72, 72, 72, 72,
// 456 - 463
72, 72, 72, 72, 72, 72, 72, 72,
// 464 - 471
72, 72, 72, 72, 72, 72, 72, 72,
// 472 - 479
72, 72, 72, 72, 72, 72, 72, 72,
// 480 - 487
72, 72, 72, 72, 72, 72, 72, 72,
// 488 - 495
72, 72, 72, 72, 72, 72, 72, 72,
// 496 - 503
72, 72, 72, 72, 72, 72, 72, 72,
// 504 - 511
72, 72, 72, 72, 72, 72, 72, 72,
// 512 - 519
104, 104, 104, 104, 104, 104, 104, 104,
// 520 - 527
104, 104, 104, 104, 104, 104, 104, 104,
// 528 - 535
104, 104, 104, 104, 104, 104, 104, 104,
// 536 - 543
104, 104, 104, 104, 104, 104, 104, 104,
// 544 - 551
104, 104, 104, 104, 104, 104, 104, 104,
// 552 - 559
104, 104, 104, 104, 104, 104, 104, 104,
// 560 - 567
104, 104, 104, 104, 104, 104, 104, 104,
// 568 - 575
104, 104, 104, 104, 104, 104, 104, 104,
// 576 - 583
4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107,
// 584 - 591
4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107,
// 592 - 599
4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107,
// 600 - 607
4107, 4107, 4107, 4107, 4107, 4107, 4107, 4107,
// 608 - 615
266, 266, 266, 266, 266, 266, 266, 266,
// 616 - 623
266, 266, 266, 266, 266, 266, 266, 266,
// 624 - 631
266, 266, 266, 266, 266, 266, 266, 266,
// 632 - 639
266, 266, 266, 266, 266, 266, 266, 266,
// 640 - 647
298, 298, 298, 298, 298, 298, 298, 298,
// 648 - 655
298, 298, 298, 298, 298, 298, 298, 298,
// 656 - 663
298, 298, 298, 298, 298, 298, 298, 298,
// 664 - 671
298, 298, 298, 298, 298, 298, 298, 298,
// 672 - 679
524, 524, 524, 524, 524, 524, 524, 524,
// 680 - 687
524, 524, 524, 524, 524, 524, 524, 524,
// 688 - 695
556, 556, 556, 556, 556, 556, 556, 556,
// 696 - 703
556, 556, 556, 556, 556, 556, 556, 556,
// 704 - 711
136, 136, 136, 136, 136, 136, 136, 136,
// 712 - 719
136, 136, 136, 136, 136, 136, 136, 136,
// 720 - 727
136, 136, 136, 136, 136, 136, 136, 136,
// 728 - 735
136, 136, 136, 136, 136, 136, 136, 136,
// 736 - 743
136, 136, 136, 136, 136, 136, 136, 136,
// 744 - 751
136, 136, 136, 136, 136, 136, 136, 136,
// 752 - 759
136, 136, 136, 136, 136, 136, 136, 136,
// 760 - 767
136, 136, 136, 136, 136, 136, 136, 136,
// 768 - 775
168, 168, 168, 168, 168, 168, 168, 168,
// 776 - 783
168, 168, 168, 168, 168, 168, 168, 168,
// 784 - 791
168, 168, 168, 168, 168, 168, 168, 168,
// 792 - 799
168, 168, 168, 168, 168, 168, 168, 168,
// 800 - 807
168, 168, 168, 168, 168, 168, 168, 168,
// 808 - 815
168, 168, 168, 168, 168, 168, 168, 168,
// 816 - 823
168, 168, 168, 168, 168, 168, 168, 168,
// 824 - 831
168, 168, 168, 168, 168, 168, 168, 168,
// 832 - 839
460, 460, 460, 460, 460, 460, 460, 460,
// 840 - 847
460, 460, 460, 460, 460, 460, 460, 460,
// 848 - 855
492, 492, 492, 492, 492, 492, 492, 492,
// 856 - 863
492, 492, 492, 492, 492, 492, 492, 492,
// 864 - 871
2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059,
// 872 - 879
2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059,
// 880 - 887
2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059,
// 888 - 895
2059, 2059, 2059, 2059, 2059, 2059, 2059, 2059,
// 896 - 903
200, 200, 200, 200, 200, 200, 200, 200,
// 904 - 911
200, 200, 200, 200, 200, 200, 200, 200,
// 912 - 919
200, 200, 200, 200, 200, 200, 200, 200,
// 920 - 927
200, 200, 200, 200, 200, 200, 200, 200,
// 928 - 935
200, 200, 200, 200, 200, 200, 200, 200,
// 936 - 943
200, 200, 200, 200, 200, 200, 200, 200,
// 944 - 951
200, 200, 200, 200, 200, 200, 200, 200,
// 952 - 959
200, 200, 200, 200, 200, 200, 200, 200,
// 960 - 967
232, 232, 232, 232, 232, 232, 232, 232,
// 968 - 975
232, 232, 232, 232, 232, 232, 232, 232,
// 976 - 983
232, 232, 232, 232, 232, 232, 232, 232,
// 984 - 991
232, 232, 232, 232, 232, 232, 232, 232,
// 992 - 999
232, 232, 232, 232, 232, 232, 232, 232,
// 1000 - 1007
232, 232, 232, 232, 232, 232, 232, 232,
// 1008 - 1015
232, 232, 232, 232, 232, 232, 232, 232,
// 1016 - 1023
232, 232, 232, 232, 232, 232, 232, 232,
};
// Additional make up codes for both White and Black runs
static short[] additionalMakeup = {
28679, 28679, 31752, (short)32777,
(short)33801, (short)34825, (short)35849, (short)36873,
(short)29703, (short)29703, (short)30727, (short)30727,
(short)37897, (short)38921, (short)39945, (short)40969
};
// Initial black run look up table, uses the first 4 bits of a code
static short[] initBlack = {
// 0 - 7
3226, 6412, 200, 168, 38, 38, 134, 134,
// 8 - 15
100, 100, 100, 100, 68, 68, 68, 68
};
//
static short[] twoBitBlack = {292, 260, 226, 226}; // 0 - 3
// Main black run table, using the last 9 bits of possible 13 bit code
static short[] black = {
// 0 - 7
62, 62, 30, 30, 0, 0, 0, 0,
// 8 - 15
0, 0, 0, 0, 0, 0, 0, 0,
// 16 - 23
0, 0, 0, 0, 0, 0, 0, 0,
// 24 - 31
0, 0, 0, 0, 0, 0, 0, 0,
// 32 - 39
3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225,
// 40 - 47
3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225,
// 48 - 55
3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225,
// 56 - 63
3225, 3225, 3225, 3225, 3225, 3225, 3225, 3225,
// 64 - 71
588, 588, 588, 588, 588, 588, 588, 588,
// 72 - 79
1680, 1680, 20499, 22547, 24595, 26643, 1776, 1776,
// 80 - 87
1808, 1808, -24557, -22509, -20461, -18413, 1904, 1904,
// 88 - 95
1936, 1936, -16365, -14317, 782, 782, 782, 782,
// 96 - 103
814, 814, 814, 814, -12269, -10221, 10257, 10257,
// 104 - 111
12305, 12305, 14353, 14353, 16403, 18451, 1712, 1712,
// 112 - 119
1744, 1744, 28691, 30739, -32749, -30701, -28653, -26605,
// 120 - 127
2061, 2061, 2061, 2061, 2061, 2061, 2061, 2061,
// 128 - 135
424, 424, 424, 424, 424, 424, 424, 424,
// 136 - 143
424, 424, 424, 424, 424, 424, 424, 424,
// 144 - 151
424, 424, 424, 424, 424, 424, 424, 424,
// 152 - 159
424, 424, 424, 424, 424, 424, 424, 424,
// 160 - 167
750, 750, 750, 750, 1616, 1616, 1648, 1648,
// 168 - 175
1424, 1424, 1456, 1456, 1488, 1488, 1520, 1520,
// 176 - 183
1840, 1840, 1872, 1872, 1968, 1968, 8209, 8209,
// 184 - 191
524, 524, 524, 524, 524, 524, 524, 524,
// 192 - 199
556, 556, 556, 556, 556, 556, 556, 556,
// 200 - 207
1552, 1552, 1584, 1584, 2000, 2000, 2032, 2032,
// 208 - 215
976, 976, 1008, 1008, 1040, 1040, 1072, 1072,
// 216 - 223
1296, 1296, 1328, 1328, 718, 718, 718, 718,
// 224 - 231
456, 456, 456, 456, 456, 456, 456, 456,
// 232 - 239
456, 456, 456, 456, 456, 456, 456, 456,
// 240 - 247
456, 456, 456, 456, 456, 456, 456, 456,
// 248 - 255
456, 456, 456, 456, 456, 456, 456, 456,
// 256 - 263
326, 326, 326, 326, 326, 326, 326, 326,
// 264 - 271
326, 326, 326, 326, 326, 326, 326, 326,
// 272 - 279
326, 326, 326, 326, 326, 326, 326, 326,
// 280 - 287
326, 326, 326, 326, 326, 326, 326, 326,
// 288 - 295
326, 326, 326, 326, 326, 326, 326, 326,
// 296 - 303
326, 326, 326, 326, 326, 326, 326, 326,
// 304 - 311
326, 326, 326, 326, 326, 326, 326, 326,
// 312 - 319
326, 326, 326, 326, 326, 326, 326, 326,
// 320 - 327
358, 358, 358, 358, 358, 358, 358, 358,
// 328 - 335
358, 358, 358, 358, 358, 358, 358, 358,
// 336 - 343
358, 358, 358, 358, 358, 358, 358, 358,
// 344 - 351
358, 358, 358, 358, 358, 358, 358, 358,
// 352 - 359
358, 358, 358, 358, 358, 358, 358, 358,
// 360 - 367
358, 358, 358, 358, 358, 358, 358, 358,
// 368 - 375
358, 358, 358, 358, 358, 358, 358, 358,
// 376 - 383
358, 358, 358, 358, 358, 358, 358, 358,
// 384 - 391
490, 490, 490, 490, 490, 490, 490, 490,
// 392 - 399
490, 490, 490, 490, 490, 490, 490, 490,
// 400 - 407
4113, 4113, 6161, 6161, 848, 848, 880, 880,
// 408 - 415
912, 912, 944, 944, 622, 622, 622, 622,
// 416 - 423
654, 654, 654, 654, 1104, 1104, 1136, 1136,
// 424 - 431
1168, 1168, 1200, 1200, 1232, 1232, 1264, 1264,
// 432 - 439
686, 686, 686, 686, 1360, 1360, 1392, 1392,
// 440 - 447
12, 12, 12, 12, 12, 12, 12, 12,
// 448 - 455
390, 390, 390, 390, 390, 390, 390, 390,
// 456 - 463
390, 390, 390, 390, 390, 390, 390, 390,
// 464 - 471
390, 390, 390, 390, 390, 390, 390, 390,
// 472 - 479
390, 390, 390, 390, 390, 390, 390, 390,
// 480 - 487
390, 390, 390, 390, 390, 390, 390, 390,
// 488 - 495
390, 390, 390, 390, 390, 390, 390, 390,
// 496 - 503
390, 390, 390, 390, 390, 390, 390, 390,
// 504 - 511
390, 390, 390, 390, 390, 390, 390, 390,
};
static byte[] twoDCodes = {
// 0 - 7
80, 88, 23, 71, 30, 30, 62, 62,
// 8 - 15
4, 4, 4, 4, 4, 4, 4, 4,
// 16 - 23
11, 11, 11, 11, 11, 11, 11, 11,
// 24 - 31
11, 11, 11, 11, 11, 11, 11, 11,
// 32 - 39
35, 35, 35, 35, 35, 35, 35, 35,
// 40 - 47
35, 35, 35, 35, 35, 35, 35, 35,
// 48 - 55
51, 51, 51, 51, 51, 51, 51, 51,
// 56 - 63
51, 51, 51, 51, 51, 51, 51, 51,
// 64 - 71
41, 41, 41, 41, 41, 41, 41, 41,
// 72 - 79
41, 41, 41, 41, 41, 41, 41, 41,
// 80 - 87
41, 41, 41, 41, 41, 41, 41, 41,
// 88 - 95
41, 41, 41, 41, 41, 41, 41, 41,
// 96 - 103
41, 41, 41, 41, 41, 41, 41, 41,
// 104 - 111
41, 41, 41, 41, 41, 41, 41, 41,
// 112 - 119
41, 41, 41, 41, 41, 41, 41, 41,
// 120 - 127
41, 41, 41, 41, 41, 41, 41, 41,
};
/**
* @param fillOrder The fill order of the compressed data bytes.
*/
public TIFFFaxDecoder(int fillOrder, int w, int h) {
this.fillOrder = fillOrder;
this.w = w;
this.h = h;
this.bitPointer = 0;
this.bytePointer = 0;
this.prevChangingElems = new int[w];
this.currChangingElems = new int[w];
}
// One-dimensional decoding methods
public void decode1D(byte[] buffer, byte[] compData,
int startX, int height) {
this.data = compData;
int lineOffset = 0;
int scanlineStride = (w + 7)/8;
bitPointer = 0;
bytePointer = 0;
for (int i = 0; i < height; i++) {
decodeNextScanline(buffer, lineOffset, startX);
lineOffset += scanlineStride;
}
}
public void decodeNextScanline(byte[] buffer,
int lineOffset, int bitOffset) {
int bits = 0, code = 0, isT = 0;
int current, entry, twoBits;
boolean isWhite = true;
// Initialize starting of the changing elements array
changingElemSize = 0;
// While scanline not complete
while (bitOffset < w) {
while (isWhite) {
// White run
current = nextNBits(10);
entry = white[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x0f;
if (bits == 12) { // Additional Make up code
// Get the next 2 bits
twoBits = nextLesserThan8Bits(2);
// Consolidate the 2 new bits and last 2 bits into 4 bits
current = ((current << 2) & 0x000c) | twoBits;
entry = additionalMakeup[current];
bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111
code = (entry >>> 4) & 0x0fff; // 12 bits
bitOffset += code; // Skip white run
updatePointer(4 - bits);
} else if (bits == 0) { // ERROR
throw new Error("TIFFFaxDecoder0");
} else if (bits == 15) { // EOL
throw new Error("TIFFFaxDecoder1");
} else {
// 11 bits - 0000 0111 1111 1111 = 0x07ff
code = (entry >>> 5) & 0x07ff;
bitOffset += code;
updatePointer(10 - bits);
if (isT == 0) {
isWhite = false;
currChangingElems[changingElemSize++] = bitOffset;
}
}
}
// Check whether this run completed one width, if so
// advance to next byte boundary for compression = 2.
if (bitOffset == w) {
if (compression == 2) {
advancePointer();
}
break;
}
while ( ! isWhite ) {
// Black run
current = nextLesserThan8Bits(4);
entry = initBlack[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x000f;
code = (entry >>> 5) & 0x07ff;
if (code == 100) {
current = nextNBits(9);
entry = black[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x000f;
code = (entry >>> 5) & 0x07ff;
if (bits == 12) {
// Additional makeup codes
updatePointer(5);
current = nextLesserThan8Bits(4);
entry = additionalMakeup[current];
bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111
code = (entry >>> 4) & 0x0fff; // 12 bits
setToBlack(buffer, lineOffset, bitOffset, code);
bitOffset += code;
updatePointer(4 - bits);
} else if (bits == 15) {
// EOL code
throw new Error("TIFFFaxDecoder2");
} else {
setToBlack(buffer, lineOffset, bitOffset, code);
bitOffset += code;
updatePointer(9 - bits);
if (isT == 0) {
isWhite = true;
currChangingElems[changingElemSize++] = bitOffset;
}
}
} else if (code == 200) {
// Is a Terminating code
current = nextLesserThan8Bits(2);
entry = twoBitBlack[current];
code = (entry >>> 5) & 0x07ff;
bits = (entry >>> 1) & 0x0f;
setToBlack(buffer, lineOffset, bitOffset, code);
bitOffset += code;
updatePointer(2 - bits);
isWhite = true;
currChangingElems[changingElemSize++] = bitOffset;
} else {
// Is a Terminating code
setToBlack(buffer, lineOffset, bitOffset, code);
bitOffset += code;
updatePointer(4 - bits);
isWhite = true;
currChangingElems[changingElemSize++] = bitOffset;
}
}
// Check whether this run completed one width
if (bitOffset == w) {
if (compression == 2) {
advancePointer();
}
break;
}
}
currChangingElems[changingElemSize++] = bitOffset;
}
// Two-dimensional decoding methods
public void decode2D(byte[] buffer,
byte[] compData,
int startX,
int height,
long tiffT4Options) {
this.data = compData;
compression = 3;
bitPointer = 0;
bytePointer = 0;
int scanlineStride = (w + 7)/8;
int a0, a1, b1, b2;
int[] b = new int[2];
int entry, code, bits;
boolean isWhite;
int currIndex = 0;
int[] temp;
// fillBits - dealt with this in readEOL
// 1D/2D encoding - dealt with this in readEOL
// uncompressedMode - haven't dealt with this yet.
oneD = (int)(tiffT4Options & 0x01);
uncompressedMode = (int)((tiffT4Options & 0x02) >> 1);
fillBits = (int)((tiffT4Options & 0x04) >> 2);
// The data must start with an EOL code
if (readEOL() != 1) {
throw new Error("TIFFFaxDecoder3");
}
int lineOffset = 0;
int bitOffset;
// Then the 1D encoded scanline data will occur, changing elements
// array gets set.
decodeNextScanline(buffer, lineOffset, startX);
lineOffset += scanlineStride;
for (int lines = 1; lines < height; lines++) {
// Every line must begin with an EOL followed by a bit which
// indicates whether the following scanline is 1D or 2D encoded.
if (readEOL() == 0) {
// 2D encoded scanline follows
// Initialize previous scanlines changing elements, and
// initialize current scanline's changing elements array
temp = prevChangingElems;
prevChangingElems = currChangingElems;
currChangingElems = temp;
currIndex = 0;
// a0 has to be set just before the start of this scanline.
a0 = -1;
isWhite = true;
bitOffset = startX;
lastChangingElement = 0;
while (bitOffset < w) {
// Get the next changing element
getNextChangingElement(a0, isWhite, b);
b1 = b[0];
b2 = b[1];
// Get the next seven bits
entry = nextLesserThan8Bits(7);
// Run these through the 2DCodes table
entry = (int)(twoDCodes[entry] & 0xff);
// Get the code and the number of bits used up
code = (entry & 0x78) >>> 3;
bits = entry & 0x07;
if (code == 0) {
if (!isWhite) {
setToBlack(buffer, lineOffset, bitOffset,
b2 - bitOffset);
}
bitOffset = a0 = b2;
// Set pointer to consume the correct number of bits.
updatePointer(7 - bits);
} else if (code == 1) {
// Horizontal
updatePointer(7 - bits);
// identify the next 2 codes.
int number;
if (isWhite) {
number = decodeWhiteCodeWord();
bitOffset += number;
currChangingElems[currIndex++] = bitOffset;
number = decodeBlackCodeWord();
setToBlack(buffer, lineOffset, bitOffset, number);
bitOffset += number;
currChangingElems[currIndex++] = bitOffset;
} else {
number = decodeBlackCodeWord();
setToBlack(buffer, lineOffset, bitOffset, number);
bitOffset += number;
currChangingElems[currIndex++] = bitOffset;
number = decodeWhiteCodeWord();
bitOffset += number;
currChangingElems[currIndex++] = bitOffset;
}
a0 = bitOffset;
} else if (code <= 8) {
// Vertical
a1 = b1 + (code - 5);
currChangingElems[currIndex++] = a1;
// We write the current color till a1 - 1 pos,
// since a1 is where the next color starts
if (!isWhite) {
setToBlack(buffer, lineOffset, bitOffset,
a1 - bitOffset);
}
bitOffset = a0 = a1;
isWhite = !isWhite;
updatePointer(7 - bits);
} else {
throw new Error("TIFFFaxDecoder4");
}
}
// Add the changing element beyond the current scanline for the
// other color too
currChangingElems[currIndex++] = bitOffset;
changingElemSize = currIndex;
} else {
// 1D encoded scanline follows
decodeNextScanline(buffer, lineOffset, startX);
}
lineOffset += scanlineStride;
}
}
public synchronized void decodeT6(byte[] buffer,
byte[] compData,
int startX,
int height,
long tiffT6Options) {
this.data = compData;
compression = 4;
bitPointer = 0;
bytePointer = 0;
int scanlineStride = (w + 7)/8;
int a0, a1, b1, b2;
int entry, code, bits;
boolean isWhite;
int currIndex;
int[] temp;
// Return values from getNextChangingElement
int[] b = new int[2];
// uncompressedMode - have written some code for this, but this
// has not been tested due to lack of test images using this optional
uncompressedMode = (int)((tiffT6Options & 0x02) >> 1);
// Local cached reference
int[] cce = currChangingElems;
// Assume invisible preceding row of all white pixels and insert
// both black and white changing elements beyond the end of this
// imaginary scanline.
changingElemSize = 0;
cce[changingElemSize++] = w;
cce[changingElemSize++] = w;
int lineOffset = 0;
int bitOffset;
for (int lines = 0; lines < height; lines++) {
// a0 has to be set just before the start of the scanline.
a0 = -1;
isWhite = true;
// Assign the changing elements of the previous scanline to
// prevChangingElems and start putting this new scanline's
// changing elements into the currChangingElems.
temp = prevChangingElems;
prevChangingElems = currChangingElems;
cce = currChangingElems = temp;
currIndex = 0;
// Start decoding the scanline at startX in the raster
bitOffset = startX;
// Reset search start position for getNextChangingElement
lastChangingElement = 0;
// Till one whole scanline is decoded
while (bitOffset < w) {
// Get the next changing element
getNextChangingElement(a0, isWhite, b);
b1 = b[0];
b2 = b[1];
// Get the next seven bits
entry = nextLesserThan8Bits(7);
// Run these through the 2DCodes table
entry = (int)(twoDCodes[entry] & 0xff);
// Get the code and the number of bits used up
code = (entry & 0x78) >>> 3;
bits = entry & 0x07;
if (code == 0) { // Pass
// We always assume WhiteIsZero format for fax.
if (!isWhite) {
setToBlack(buffer, lineOffset, bitOffset,
b2 - bitOffset);
}
bitOffset = a0 = b2;
// Set pointer to only consume the correct number of bits.
updatePointer(7 - bits);
} else if (code == 1) { // Horizontal
// Set pointer to only consume the correct number of bits.
updatePointer(7 - bits);
// identify the next 2 alternating color codes.
int number;
if (isWhite) {
// Following are white and black runs
number = decodeWhiteCodeWord();
bitOffset += number;
cce[currIndex++] = bitOffset;
number = decodeBlackCodeWord();
setToBlack(buffer, lineOffset, bitOffset, number);
bitOffset += number;
cce[currIndex++] = bitOffset;
} else {
// First a black run and then a white run follows
number = decodeBlackCodeWord();
setToBlack(buffer, lineOffset, bitOffset, number);
bitOffset += number;
cce[currIndex++] = bitOffset;
number = decodeWhiteCodeWord();
bitOffset += number;
cce[currIndex++] = bitOffset;
}
a0 = bitOffset;
} else if (code <= 8) { // Vertical
a1 = b1 + (code - 5);
cce[currIndex++] = a1;
// We write the current color till a1 - 1 pos,
// since a1 is where the next color starts
if (!isWhite) {
setToBlack(buffer, lineOffset, bitOffset,
a1 - bitOffset);
}
bitOffset = a0 = a1;
isWhite = !isWhite;
updatePointer(7 - bits);
} else if (code == 11) {
if (nextLesserThan8Bits(3) != 7) {
throw new Error("TIFFFaxDecoder5");
}
int zeros = 0;
boolean exit = false;
while (!exit) {
while (nextLesserThan8Bits(1) != 1) {
zeros++;
}
if (zeros > 5) {
// Exit code
// Zeros before exit code
zeros = zeros - 6;
if (!isWhite && (zeros > 0)) {
cce[currIndex++] = bitOffset;
}
// Zeros before the exit code
bitOffset += zeros;
if (zeros > 0) {
// Some zeros have been written
isWhite = true;
}
// Read in the bit which specifies the color of
// the following run
if (nextLesserThan8Bits(1) == 0) {
if (!isWhite) {
cce[currIndex++] = bitOffset;
}
isWhite = true;
} else {
if (isWhite) {
cce[currIndex++] = bitOffset;
}
isWhite = false;
}
exit = true;
}
if (zeros == 5) {
if (!isWhite) {
cce[currIndex++] = bitOffset;
}
bitOffset += zeros;
// Last thing written was white
isWhite = true;
} else {
bitOffset += zeros;
cce[currIndex++] = bitOffset;
setToBlack(buffer, lineOffset, bitOffset, 1);
++bitOffset;
// Last thing written was black
isWhite = false;
}
}
} else {
throw new Error("TIFFFaxDecoder5");
}
}
// Add the changing element beyond the current scanline for the
// other color too
cce[currIndex++] = bitOffset;
// Number of changing elements in this scanline.
changingElemSize = currIndex;
lineOffset += scanlineStride;
}
}
private void setToBlack(byte[] buffer,
int lineOffset, int bitOffset,
int numBits) {
int bitNum = 8*lineOffset + bitOffset;
int lastBit = bitNum + numBits;
int byteNum = bitNum >> 3;
// Handle bits in first byte
int shift = bitNum & 0x7;
if (shift > 0) {
int maskVal = 1 << (7 - shift);
byte val = buffer[byteNum];
while (maskVal > 0 && bitNum < lastBit) {
val |= maskVal;
maskVal >>= 1;
++bitNum;
}
buffer[byteNum] = val;
}
// Fill in 8 bits at a time
byteNum = bitNum >> 3;
while (bitNum < lastBit - 7) {
buffer[byteNum++] = (byte)255;
bitNum += 8;
}
// Fill in remaining bits
while (bitNum < lastBit) {
byteNum = bitNum >> 3;
buffer[byteNum] |= 1 << (7 - (bitNum & 0x7));
++bitNum;
}
}
// Returns run length
private int decodeWhiteCodeWord() {
int current, entry, bits, isT, twoBits, code = -1;
int runLength = 0;
boolean isWhite = true;
while (isWhite) {
current = nextNBits(10);
entry = white[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x0f;
if (bits == 12) { // Additional Make up code
// Get the next 2 bits
twoBits = nextLesserThan8Bits(2);
// Consolidate the 2 new bits and last 2 bits into 4 bits
current = ((current << 2) & 0x000c) | twoBits;
entry = additionalMakeup[current];
bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111
code = (entry >>> 4) & 0x0fff; // 12 bits
runLength += code;
updatePointer(4 - bits);
} else if (bits == 0) { // ERROR
throw new Error("TIFFFaxDecoder0");
} else if (bits == 15) { // EOL
throw new Error("TIFFFaxDecoder1");
} else {
// 11 bits - 0000 0111 1111 1111 = 0x07ff
code = (entry >>> 5) & 0x07ff;
runLength += code;
updatePointer(10 - bits);
if (isT == 0) {
isWhite = false;
}
}
}
return runLength;
}
// Returns run length
private int decodeBlackCodeWord() {
int current, entry, bits, isT, code = -1;
int runLength = 0;
boolean isWhite = false;
while (!isWhite) {
current = nextLesserThan8Bits(4);
entry = initBlack[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x000f;
code = (entry >>> 5) & 0x07ff;
if (code == 100) {
current = nextNBits(9);
entry = black[current];
// Get the 3 fields from the entry
isT = entry & 0x0001;
bits = (entry >>> 1) & 0x000f;
code = (entry >>> 5) & 0x07ff;
if (bits == 12) {
// Additional makeup codes
updatePointer(5);
current = nextLesserThan8Bits(4);
entry = additionalMakeup[current];
bits = (entry >>> 1) & 0x07; // 3 bits 0000 0111
code = (entry >>> 4) & 0x0fff; // 12 bits
runLength += code;
updatePointer(4 - bits);
} else if (bits == 15) {
// EOL code
throw new Error("TIFFFaxDecoder2");
} else {
runLength += code;
updatePointer(9 - bits);
if (isT == 0) {
isWhite = true;
}
}
} else if (code == 200) {
// Is a Terminating code
current = nextLesserThan8Bits(2);
entry = twoBitBlack[current];
code = (entry >>> 5) & 0x07ff;
runLength += code;
bits = (entry >>> 1) & 0x0f;
updatePointer(2 - bits);
isWhite = true;
} else {
// Is a Terminating code
runLength += code;
updatePointer(4 - bits);
isWhite = true;
}
}
return runLength;
}
private int readEOL() {
if (fillBits == 0) {
if (nextNBits(12) != 1) {
throw new Error("TIFFFaxDecoder6");
}
} else if (fillBits == 1) {
// First EOL code word xxxx 0000 0000 0001 will occur
// As many fill bits will be present as required to make
// the EOL code of 12 bits end on a byte boundary.
int bitsLeft = 8 - bitPointer;
if (nextNBits(bitsLeft) != 0) {
throw new Error("TIFFFaxDecoder8");
}
// If the number of bitsLeft is less than 8, then to have a 12
// bit EOL sequence, two more bytes are certainly going to be
// required. The first of them has to be all zeros, so ensure
// that.
if (bitsLeft < 4) {
if (nextNBits(8) != 0) {
throw new Error("TIFFFaxDecoder8");
}
}
// There might be a random number of fill bytes with 0s, so
// loop till the EOL of 0000 0001 is found, as long as all
// the bytes preceding it are 0's.
int n;
while ((n = nextNBits(8)) != 1) {
// If not all zeros
if (n != 0) {
throw new Error("TIFFFaxDecoder8");
}
}
}
// If one dimensional encoding mode, then always return 1
if (oneD == 0) {
return 1;
} else {
// Otherwise for 2D encoding mode,
// The next one bit signifies 1D/2D encoding of next line.
return nextLesserThan8Bits(1);
}
}
private void getNextChangingElement(int a0, boolean isWhite, int[] ret) {
// Local copies of instance variables
int[] pce = this.prevChangingElems;
int ces = this.changingElemSize;
// If the previous match was at an odd element, we still
// have to search the preceeding element.
// int start = lastChangingElement & ~0x1;
int start = lastChangingElement > 0 ? lastChangingElement - 1 : 0;
if (isWhite) {
start &= ~0x1; // Search even numbered elements
} else {
start |= 0x1; // Search odd numbered elements
}
int i = start;
for (; i < ces; i += 2) {
int temp = pce[i];
if (temp > a0) {
lastChangingElement = i;
ret[0] = temp;
break;
}
}
if (i + 1 < ces) {
ret[1] = pce[i + 1];
}
}
private int nextNBits(int bitsToGet) {
byte b, next, next2next;
int l = data.length - 1;
int bp = this.bytePointer;
if (fillOrder == 1) {
b = data[bp];
if (bp == l) {
next = 0x00;
next2next = 0x00;
} else if ((bp + 1) == l) {
next = data[bp + 1];
next2next = 0x00;
} else {
next = data[bp + 1];
next2next = data[bp + 2];
}
} else if (fillOrder == 2) {
b = flipTable[data[bp] & 0xff];
if (bp == l) {
next = 0x00;
next2next = 0x00;
} else if ((bp + 1) == l) {
next = flipTable[data[bp + 1] & 0xff];
next2next = 0x00;
} else {
next = flipTable[data[bp + 1] & 0xff];
next2next = flipTable[data[bp + 2] & 0xff];
}
} else {
throw new Error("TIFFFaxDecoder7");
}
int bitsLeft = 8 - bitPointer;
int bitsFromNextByte = bitsToGet - bitsLeft;
int bitsFromNext2NextByte = 0;
if (bitsFromNextByte > 8) {
bitsFromNext2NextByte = bitsFromNextByte - 8;
bitsFromNextByte = 8;
}
bytePointer++;
int i1 = (b & table1[bitsLeft]) << (bitsToGet - bitsLeft);
int i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte);
int i3 = 0;
if (bitsFromNext2NextByte != 0) {
i2 <<= bitsFromNext2NextByte;
i3 = (next2next & table2[bitsFromNext2NextByte]) >>>
(8 - bitsFromNext2NextByte);
i2 |= i3;
bytePointer++;
bitPointer = bitsFromNext2NextByte;
} else {
if (bitsFromNextByte == 8) {
bitPointer = 0;
bytePointer++;
} else {
bitPointer = bitsFromNextByte;
}
}
int i = i1 | i2;
return i;
}
private int nextLesserThan8Bits(int bitsToGet) {
byte b, next;
int l = data.length - 1;
int bp = this.bytePointer;
if (fillOrder == 1) {
b = data[bp];
if (bp == l) {
next = 0x00;
} else {
next = data[bp + 1];
}
} else if (fillOrder == 2) {
b = flipTable[data[bp] & 0xff];
if (bp == l) {
next = 0x00;
} else {
next = flipTable[data[bp + 1] & 0xff];
}
} else {
throw new Error("TIFFFaxDecoder7");
}
int bitsLeft = 8 - bitPointer;
int bitsFromNextByte = bitsToGet - bitsLeft;
int shift = bitsLeft - bitsToGet;
int i1, i2;
if (shift >= 0) {
i1 = (b & table1[bitsLeft]) >>> shift;
bitPointer += bitsToGet;
if (bitPointer == 8) {
bitPointer = 0;
bytePointer++;
}
} else {
i1 = (b & table1[bitsLeft]) << (-shift);
i2 = (next & table2[bitsFromNextByte]) >>> (8 - bitsFromNextByte);
i1 |= i2;
bytePointer++;
bitPointer = bitsFromNextByte;
}
return i1;
}
// Move pointer backwards by given amount of bits
private void updatePointer(int bitsToMoveBack) {
int i = bitPointer - bitsToMoveBack;
if (i < 0) {
bytePointer--;
bitPointer = 8 + i;
} else {
bitPointer = i;
}
}
// Move to the next byte boundary
private boolean advancePointer() {
if (bitPointer != 0) {
bytePointer++;
bitPointer = 0;
}
return true;
}
}
| [
"cframpton@apache.org"
] | cframpton@apache.org |
4b33fa383ed8dfc3098ed6ac2a929d46498181c6 | 52b219f3fcbb88982bc98b95d27c09cc646cdb1d | /WalletAcctManager/src/test/java/T.java | c14ef2da8f1a178982ac0ead25d3d3d0a53c06d0 | [] | no_license | jiangqiang520/xyfProjects | d65d9f144522bbbbf492dba4a847afd0784b84ac | ab348de96b5c0c6a4f46d609720e189c274a4b26 | refs/heads/master | 2020-09-06T14:12:31.464210 | 2019-09-23T09:52:08 | 2019-09-23T09:52:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 81 | java | /**
* @author XRZ
* @date 2019/8/23
* @Description :
*/
public class T {
}
| [
"294442437@qq.com"
] | 294442437@qq.com |
fa13429c3cba747e6bae368bb991bd3c99a9a782 | ca18e171f678ff0dcf512e076a5f8ea46d618a66 | /boot-security/src/main/java/boot/system/service/ISysLogService.java | f722090dc7341f4b111ba53a631b9499981595b6 | [] | no_license | javahyy/boot-demo | 0dab779d5c727ae3472d89bc34f4113023d57747 | dfb45cd839bebb02b2e9e46f20b9461ebf958742 | refs/heads/master | 2022-07-17T01:37:48.604081 | 2019-12-19T16:16:02 | 2019-12-19T16:16:02 | 222,850,147 | 0 | 0 | null | 2022-06-17T02:38:53 | 2019-11-20T04:24:26 | Java | UTF-8 | Java | false | false | 1,089 | java | /*
* Copyright (c) 2019-2029, Dreamlu 卢春梦 (596392912@qq.com & www.dreamlu.net).
*
* 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 boot.system.service;
import boot.system.model.SystemLog;
import boot.system.model.syslog.SysLogEvent;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* 系统日志 服务类
*/
public interface ISysLogService extends IService<SystemLog> {
void saveSysLog(SysLogEvent sysLogEvent);
void findPage(Page<SystemLog> pages, SystemLog sysLog);
}
| [
"yangyang.huang@guanaitong.com"
] | yangyang.huang@guanaitong.com |
331bbc684128aed4fbfefa0007f6e6081575eb77 | 7728512fa05c36cb6b59ecbe7c858a00de80d06e | /acyuta-services-boot/src/main/java/com/mroads/acyuta/repository/InterviewPositionsRepository.java | 82ecad45a4fa91c8fbe07431a4f189f674047b2a | [] | no_license | UdaySaiTyada/Acyuta-services-Boot | 305aa2beedd13974635cb0f87fdd184854240049 | 9bb98eb5ead0ae3d26a8c35df8a81e8e9bc0c5be | refs/heads/master | 2022-05-31T03:57:56.986028 | 2020-01-28T09:05:01 | 2020-01-28T09:05:01 | 236,693,649 | 0 | 0 | null | 2022-05-20T21:24:58 | 2020-01-28T08:54:47 | Java | UTF-8 | Java | false | false | 1,389 | java | /*
* Copyright (c) 2017 mRoads LLC. All Rights Reserved.
* mailto:support@mroads.com
* This computer program is the confidential information and proprietary trade
* secret of mRoads LLC. Possessions and use of this program must conform
* strictly to the license agreement between the user and mRoads LLC,
* and receipt or possession does not convey any rights to divulge, reproduce,
* or allow others to use this program without specific written authorization
* of mRoads LLC.
*/
package com.mroads.acyuta.repository;
import java.math.BigInteger;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.mroads.acyuta.model.InterviewPositions;
/**
*
* @author Sreekanth
*
*/
@Repository
public interface InterviewPositionsRepository extends JpaRepository<InterviewPositions, BigInteger>{
@Query("SELECT p FROM InterviewPositions p WHERE p.positionStatus = :positionStatus and p.organizationId=:organizationId")
public List<InterviewPositions> findByOrganizationIdAndPositionStatus(@Param("positionStatus") String positionStatus, @Param("organizationId") BigInteger organizationId);
public InterviewPositions findByInterviewPositionId(BigInteger organizationId);
}
| [
"udaysai2551998@gmail.com"
] | udaysai2551998@gmail.com |
cb052d2824f5b6e32dbb59ee34aa1b5f88a1a449 | d6dff4133efe2df2e6fc7a06dc6a65d25f9a018c | /android/kaixin100/app/src/main/java/com/mgc/letobox/happy/domain/TTResultBean.java | 610d614c6e55a0a3b614016a690b1be8a10c579e | [
"Apache-2.0"
] | permissive | sanshao27/lebox | 276183336254e7d3a8a1e26b2abbd7d4c2f82489 | e343ec752f7827a238acdb60b0cc61b1455d1483 | refs/heads/master | 2020-04-14T23:22:34.931767 | 2019-01-04T04:42:11 | 2019-01-04T04:42:11 | 164,200,219 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 663 | java | package com.mgc.letobox.happy.domain;
/**
* Created by liu hong liang on 2016/11/11.
*/
public class TTResultBean {
public float getBalance() {
return balance;
}
public void setBalance(float balance) {
this.balance = balance;
}
public float getBalance_rmb() {
return balance_rmb;
}
public void setBalance_rmb(float balance_rmb) {
this.balance_rmb = balance_rmb;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public float balance;
public float balance_rmb;
public String symbol;
}
| [
"feiyun145@163.com"
] | feiyun145@163.com |
2d1630ed88af4c90aa3e7f5d3bfd13a576ff3fcf | f0e885e4e1e67641dda43397b02cbb9abf542b44 | /src/main/java/com/cultome/bizlang/language/BizlangExpression.java | 3b841a314bd3ac12e8bc4fa6d795be39cf1b19de | [
"MIT"
] | permissive | cultome/bizlang-language | 06ecc09ef8d89e7c9ce91031a8a46b5125cc1108 | efa2c232867369ba8adca20937f7aab0f0362cc3 | refs/heads/master | 2020-05-17T21:37:16.614467 | 2014-02-25T23:45:34 | 2014-02-25T23:45:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,037 | java | package com.cultome.bizlang.language;
import java.util.logging.Logger;
import com.cultomebizlang.language.interpreter.Bindings;
import com.cultomebizlang.language.interpreter.ExecutionListener;
public abstract class BizlangExpression {
protected static final Logger LOGGER = Logger.getAnonymousLogger();
protected String name;
protected int definedAt;
public BizlangExpression(String fnctName, int srcLineDefinedAt) {
this.name = fnctName;
this.definedAt = srcLineDefinedAt;
}
public abstract Object getValue(Bindings bindings) throws BizlangException;
public Object execute(Bindings bindings) throws BizlangException {
LOGGER.info("[ENTER] " + getClass().getSimpleName());
ExecutionListener.enterExpression(this, bindings);
Object returnValue = getValue(bindings);
ExecutionListener.leaveExpression(this, returnValue);
LOGGER.info("[EXIT] " + getClass().getSimpleName());
return returnValue;
}
public String getName() {
return name;
}
public int getDefinedAt() {
return definedAt;
}
}
| [
"cultome@gmail.com"
] | cultome@gmail.com |
5b88ce87a5ac97586831975b01115dc08f3066e7 | 39f380b0f7ffa091f1a2eba7a91b5a126f384f2f | /TangoTabV1.7/src/com/tangotab/localNotification/receiver/LocalNotificationReceiver.java | f453bf7d27900a67e59d51a87ac94221061d6e42 | [] | no_license | ankitvyas85/TangoTabv1.7 | 94584ff1bd508850673c3de5a1d52cfa8de70500 | 7e020f1112a8e411b69fd50dbad85e46e4e7e4fb | refs/heads/master | 2021-01-25T10:29:18.663668 | 2013-04-17T07:33:38 | 2013-04-17T07:33:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,383 | java | package com.tangotab.localNotification.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.tangotab.core.constant.AppConstant;
import com.tangotab.localNotification.activity.LocalNotificationActivity;
import com.tangotab.myOffers.Vo.OffersDetailsVo;
/**
* This class will receive the alarm intent from broad cast and send it to Local notification.
*
* @author Dillip.Lenka
*
*/
public class LocalNotificationReceiver extends BroadcastReceiver
{
private OffersDetailsVo offersDetailsVo;
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
Bundle bundle = intent.getExtras();
offersDetailsVo= (OffersDetailsVo)bundle.getParcelable("selectOffers");
// Handle the alarm broadcast
if (AppConstant.ALARM_ACTION_NAME.equals(action))
{
/**
* Put the consumer deals object into alarm intent.
*/
Bundle b = new Bundle();
b.putParcelable("selectOffers", offersDetailsVo);
Intent alarmIntent = new Intent("android.intent.action.MAIN");
alarmIntent.putExtras(b);
alarmIntent.setClass(context, LocalNotificationActivity.class);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarmIntent);
}
}
} | [
"ankit.vyas@valtech.co.in"
] | ankit.vyas@valtech.co.in |
982421a44184602ff551b1f1551d67836cf9debb | 3735a07d455d7b40613c3c4160aa8b1cb1b3472a | /java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/types/DfLongConstantType.java | 99cdad181216a6d0040068a837b95b3fc8c23666 | [
"Apache-2.0"
] | permissive | caofanCPU/intellij-community | ede9417fc4ccb4b5efefb099906e4abe6871f3b4 | 5ad3e2bdf3c83d86e7c4396f5671929768d76999 | refs/heads/master | 2023-02-27T21:38:33.416107 | 2021-02-05T06:37:40 | 2021-02-05T06:37:40 | 321,209,485 | 1 | 0 | Apache-2.0 | 2021-02-05T06:37:41 | 2020-12-14T02:22:32 | null | UTF-8 | Java | false | false | 700 | java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.dataFlow.types;
import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet;
import com.intellij.psi.PsiPrimitiveType;
import org.jetbrains.annotations.NotNull;
class DfLongConstantType extends DfConstantType<Long> implements DfLongType {
DfLongConstantType(long value) {
super(value);
}
@NotNull
@Override
public PsiPrimitiveType getPsiType() {
return DfLongType.super.getPsiType();
}
@NotNull
@Override
public LongRangeSet getRange() {
return LongRangeSet.point(getValue());
}
}
| [
"intellij-monorepo-bot-no-reply@jetbrains.com"
] | intellij-monorepo-bot-no-reply@jetbrains.com |
baf1137d06a22983b4c97a7eec4aa045ee7087af | fc5c8f84009063ee5245b9bcbea482e900c1977a | /src/main/java/com/getjavajob/training/KarpovN/concurency/lesson08/Matrix.java | 316e35ed2401d569be56092d8b6b9ecbf529c102 | [] | no_license | djcrgr/init-concurency | 1cadee0a6540dd660afd77bead0c4dcbc89c1a9f | c8c8e4c08b9a41f220b59d1547ed34646166de46 | refs/heads/master | 2023-03-14T00:31:01.386122 | 2021-03-12T09:22:24 | 2021-03-12T09:22:24 | 347,008,826 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,270 | java | package com.getjavajob.training.KarpovN.concurency.lesson08;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Integer.parseInt;
public class Matrix {
public static void main(String[] args) throws IOException {
int[][] matrix1 = matrixRead("matrix1.txt");
int[][] matrix2 = matrixRead("matrix2.txt");
matrixWrite(multiply(matrix1, matrix2));
}
public static int[][] matrixRead(String matrixName) throws IOException {
List<String> lines;
try (BufferedReader br = new BufferedReader(new FileReader(matrixName))) {
lines = new ArrayList<>();
while (br.ready()) {
lines.add(br.readLine());
}
}
int matrixWidth = lines.get(0).split(" ").length;
int matrixHeight = lines.size();
int[][] matrix = new int[matrixHeight][matrixWidth];
for (int i = 0; i < matrixHeight; i++) {
for (int j = 0; j < matrixWidth; j++) {
String[] line = lines.get(i).split(" ");
matrix[i][j] = parseInt(line[j]);
}
}
return matrix;
}
public static void matrixWrite(int[][] matrix) throws IOException {
try (BufferedWriter bw = new BufferedWriter(
new FileWriter(
"resultMatrix.txt"))) {
for (int[] ints : matrix) {
for (int anInt : ints) {
String res = anInt + " ";
bw.write(res);
}
bw.newLine();
}
}
}
public static int[][] multiply(int[][] matrix1, int[][] matrix2) {
if (matrix1[0].length != matrix2.length) {
throw new UnsupportedOperationException();
}
int resultRows = matrix1.length;
int resultColumns = matrix2[0].length;
int[][] result = new int[resultRows][resultColumns];
int columns = matrix1[0].length;
for (int i = 0; i < resultRows; i++) {
for (int j = 0; j < resultColumns; j++) {
for (int k = 0; k < columns; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
} | [
"djcrgr@gmail.com"
] | djcrgr@gmail.com |
ad08b05bc8617c81e4f373e49dec4e40adb62552 | ae2906fa1a2ec0750bed9ac28696871f5838dc91 | /cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/organizationquotadefinitions/_GetOrganizationQuotaDefinitionResponse.java | c29ed8dcb9314ef64d9ef3000671ae365a219d44 | [
"Apache-2.0"
] | permissive | theghost5800/cf-java-client | ca8e2c0073fa1b8fd0441177d93d713ab3856f55 | 07a34c646a2f982e9405a49db2122ef461462af0 | refs/heads/master | 2022-11-15T08:17:10.162327 | 2019-10-29T15:48:42 | 2019-10-29T15:48:42 | 219,698,354 | 0 | 0 | Apache-2.0 | 2019-11-05T08:48:37 | 2019-11-05T08:48:36 | null | UTF-8 | Java | false | false | 1,030 | java | /*
* Copyright 2013-2019 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.cloudfoundry.client.v2.organizationquotadefinitions;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;
/**
* The response payload for the Retrieve a Particular Organization Quota Definition operation
*/
@JsonDeserialize
@Value.Immutable
abstract class _GetOrganizationQuotaDefinitionResponse extends AbstractOrganizationQuotaDefinition {
}
| [
"bhale@pivotal.io"
] | bhale@pivotal.io |
5e0e0dc1638abb7711de248e81338b3ac517acb2 | ec58b9b8b43bc75b8bee2f2e079e55af9da0dcae | /AIPdesign.diagram/src/AIP/diagram/navigator/AIPNavigatorSorter.java | ec42360c4c9f9c12947608bace8c92731cd01907 | [] | no_license | kouvelas/ASEME | b31b4a37f21ed20840393b309612eacda92b608b | 996acaaf5209fb6ec1dfbc2762d6baeff58b751d | refs/heads/master | 2021-03-12T23:12:15.441118 | 2013-06-13T19:22:09 | 2013-06-13T19:22:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 537 | java | package AIP.diagram.navigator;
import org.eclipse.jface.viewers.ViewerSorter;
import AIP.diagram.part.AIPVisualIDRegistry;
/**
* @generated
*/
public class AIPNavigatorSorter extends ViewerSorter {
/**
* @generated
*/
private static final int GROUP_CATEGORY = 4004;
/**
* @generated
*/
public int category(Object element) {
if (element instanceof AIPNavigatorItem) {
AIPNavigatorItem item = (AIPNavigatorItem) element;
return AIPVisualIDRegistry.getVisualID(item.getView());
}
return GROUP_CATEGORY;
}
}
| [
"nikos@science.tuc.gr"
] | nikos@science.tuc.gr |
7080e57a8f9e9175ae99154513f4079845373ff8 | 76abd218a9fda53805057ec7cb26697e94154d7e | /app/src/main/java/com/onetono/onetono/dummy/NoticesDummyContent.java | 837840f90423e532dbc025652a4bfb91029065e3 | [] | no_license | stevenandrewcarter/Onetono | 93382d7bcc71d2406d8e3850adef2ca23ee0935c | 4222435d457adfeb163580c685981e551bcff7d6 | refs/heads/master | 2020-12-24T21:22:38.667572 | 2016-05-09T12:08:04 | 2016-05-09T12:08:04 | 56,601,809 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,950 | java | package com.onetono.onetono.dummy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p/>
* TODO: Replace all uses of this class before publishing your app.
*/
public class NoticesDummyContent {
/**
* An array of sample (dummy) items.
*/
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
private static final int COUNT = 25;
static {
// Add some sample items.
for (int i = 1; i <= COUNT; i++) {
addItem(createDummyItem(i));
}
}
private static void addItem(DummyItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
private static DummyItem createDummyItem(int position) {
return new DummyItem(String.valueOf(position), "Notice " + position, makeDetails(position));
}
private static String makeDetails(int position) {
StringBuilder builder = new StringBuilder();
builder.append("Details about Item: ").append(position);
for (int i = 0; i < position; i++) {
builder.append("\nMore details information here.");
}
return builder.toString();
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String content;
public final String details;
public DummyItem(String id, String content, String details) {
this.id = id;
this.content = content;
this.details = details;
}
@Override
public String toString() {
return content;
}
}
}
| [
"stonemason@gmail.com"
] | stonemason@gmail.com |
c57673338ab071438e9541cd2c78c572418e76b4 | f3f87f69999ed930fc338456a72379fa331e3bdf | /app/src/main/java/xyz/homapay/hampay/mobile/android/util/Connectivity.java | 8cc1b35bdcc2cbfbd0beba00d9874cbc17d22981 | [] | no_license | gitlab-jenkins/mobile | 0d14fa1bc1f2c29ad0d988749a605b1ab7c28595 | dfaab81a5e33fb4c0aea5441eddced1e4ee88cd7 | refs/heads/master | 2021-01-11T14:27:41.406151 | 2017-02-07T12:06:32 | 2017-02-07T12:06:32 | 81,426,110 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,830 | java | package xyz.homapay.hampay.mobile.android.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.telephony.TelephonyManager;
/**
* Created by mohammad on 7/4/2016 AD.
*/
public class Connectivity {
/**
* Get the network info
*
* @param context
* @return
*/
public static NetworkInfo getNetworkInfo(@NonNull Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
/**
* Check if there is any connectivity
*
* @param context
* @return
*/
public static boolean isConnected(@NonNull Context context) {
NetworkInfo info = Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected());
}
public static boolean isOnline() {
try {
Process p1 = Runtime.getRuntime().exec("ping -c 1 " + Constants.NETWORK.PING_TEST_URL);
int returnVal = p1.waitFor();
boolean reachable = (returnVal == 0);
return reachable;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* Check if there is any connectivity to a Wifi network
*
* @param context
* @return
*/
public static boolean isConnectedWifi(@NonNull Context context) {
NetworkInfo info = Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
/**
* Check if there is any connectivity to a mobile network
*
* @param context
* @return
*/
public static boolean isConnectedMobile(@NonNull Context context) {
NetworkInfo info = Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
/**
* Check if there is fast connectivity
*
* @param context
* @return
*/
public static boolean isConnectedFast(@NonNull Context context) {
NetworkInfo info = Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(), info.getSubtype()));
}
/**
* Check if the connection is fast
*
* @param type
* @param subType
* @return
*/
public static boolean isConnectionFast(int type, int subType) {
if (type == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (type == ConnectivityManager.TYPE_MOBILE) {
switch (subType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
/*
* Above API level 7, make sure to set android:targetSdkVersion
* to appropriate level to use these
*/
case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11
return true; // ~ 1-2 Mbps
case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
return true; // ~ 5 Mbps
case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
return true; // ~ 10-20 Mbps
case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
return false; // ~25 kbps
case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
return true; // ~ 10+ Mbps
// Unknown
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
default:
return false;
}
} else {
return false;
}
}
}
| [
"m.moradyar@homapay.com"
] | m.moradyar@homapay.com |
ebdaef61538e6fbdee905f0122039b89f66e988b | e19ca77b8725551e5c806dfbae02b8f44b4a6c6f | /processor/src/test/java/spritz/support/processor/AbstractSpritzProcessorTest.java | 60e7c01b55db9cd336f65f70b979a0787dd75721 | [
"Apache-2.0"
] | permissive | spritz/spritz | a0ffcac27cfe50dff0f468d6165eaf599bc5ddbd | 49ba61517b5c023e521c6775e4a16f8da5034371 | refs/heads/master | 2022-05-15T17:24:32.597278 | 2022-04-29T05:05:55 | 2022-04-29T05:05:55 | 149,194,146 | 4 | 0 | Apache-2.0 | 2019-04-24T06:37:35 | 2018-09-17T22:08:56 | Java | UTF-8 | Java | false | false | 6,175 | java | package spritz.support.processor;
import com.google.common.collect.ImmutableList;
import com.google.testing.compile.Compilation;
import com.google.testing.compile.Compiler;
import com.google.testing.compile.JavaFileObjects;
import com.google.testing.compile.JavaSourcesSubjectFactory;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nonnull;
import javax.tools.JavaFileObject;
import static com.google.common.truth.Truth.*;
import static org.testng.Assert.*;
abstract class AbstractSpritzProcessorTest
{
void assertSuccessfulCompile( @Nonnull final String classname )
throws Exception
{
final String[] elements = classname.contains( "." ) ? classname.split( "\\." ) : new String[]{ classname };
final StringBuilder input = new StringBuilder();
final StringBuilder docFile = new StringBuilder();
input.append( "input" );
docFile.append( "expected" );
for ( final String element : elements )
{
input.append( '/' );
input.append( element );
docFile.append( '/' );
docFile.append( element );
}
input.append( ".java" );
docFile.append( ".doc.json" );
final ArrayList<String> expectedOutputs = new ArrayList<>();
expectedOutputs.add( docFile.toString() );
// The annotations have been copied into test directory as they are not part of the API
// but they are part of our mechanism for validating the project. We MUST keep these
// aligned else bad things will happen.
assertSuccessfulCompile( Arrays.asList( fixture( "input/spritz/DocCategory.java" ),
fixture( "input/spritz/MetaDataSource.java" ),
fixture( "input/spritz/SourceCategory.java" ),
fixture( input.toString() ) ),
expectedOutputs );
}
private void assertSuccessfulCompile( @Nonnull final List<JavaFileObject> inputs,
@Nonnull final List<String> outputs )
throws Exception
{
if ( outputFiles() )
{
final Compilation compilation =
Compiler.javac().withProcessors( new SpritzProcessor() ).compile( inputs );
final Compilation.Status status = compilation.status();
if ( Compilation.Status.SUCCESS != status )
{
/*
* Ugly hackery that marks the compile as successful so we can emit output onto filesystem. This could
* result in java code that is not compilable emitted to filesystem. This re-running determining problems
* a little easier even if it does make re-running tests from IDE a little harder
*/
final Field field = compilation.getClass().getDeclaredField( "status" );
field.setAccessible( true );
field.set( compilation, Compilation.Status.SUCCESS );
}
final ImmutableList<JavaFileObject> fileObjects = compilation.generatedFiles();
for ( final JavaFileObject fileObject : fileObjects )
{
if ( fileObject.getKind() != JavaFileObject.Kind.CLASS )
{
final Path target =
fixtureDir().resolve( "expected/" + fileObject.getName().replace( "/SOURCE_OUTPUT/", "" ) );
final File dir = target.getParent().toFile();
if ( !dir.exists() )
{
assertTrue( dir.mkdirs() );
}
if ( Files.exists( target ) )
{
final byte[] existing = Files.readAllBytes( target );
final InputStream generated = fileObject.openInputStream();
final byte[] data = new byte[ generated.available() ];
assertEquals( generated.read( data ), data.length );
if ( Arrays.equals( existing, data ) )
{
/*
* If the data on the filesystem is identical to data generated then do not write
* to filesystem. The writing can be slow and it can also trigger the IDE or other
* tools to recompile code which is problematic.
*/
continue;
}
Files.delete( target );
}
Files.copy( fileObject.openInputStream(), target );
}
}
if ( Compilation.Status.SUCCESS != status )
{
// Restore old status
final Field field = compilation.getClass().getDeclaredField( "status" );
field.setAccessible( true );
field.set( compilation, status );
// This next line will generate an error
//noinspection ResultOfMethodCallIgnored
compilation.generatedSourceFiles();
}
}
final JavaFileObject firstExpected = fixture( outputs.get( 0 ) );
final JavaFileObject[] restExpected =
outputs.stream().skip( 1 ).map( this::fixture ).toArray( JavaFileObject[]::new );
assert_().
about( JavaSourcesSubjectFactory.javaSources() ).
that( inputs ).
processedWith( new SpritzProcessor() ).
compilesWithoutError().
and().
generatesFiles( firstExpected, restExpected );
}
@Nonnull
private JavaFileObject fixture( @Nonnull final String path )
{
final Path outputFile = fixtureDir().resolve( path );
if ( !Files.exists( outputFile ) )
{
fail( "Fixture file " + outputFile + " does not exist. Thus can not compare against it." );
}
try
{
return JavaFileObjects.forResource( outputFile.toUri().toURL() );
}
catch ( final MalformedURLException e )
{
throw new IllegalStateException( e );
}
}
@Nonnull
private Path fixtureDir()
{
final String fixtureDir = System.getProperty( "spritz.fixture_dir" );
assertNotNull( fixtureDir, "Expected System.getProperty( \"spritz.fixture_dir\" ) to return fixture directory" );
return new File( fixtureDir ).toPath();
}
private boolean outputFiles()
{
return System.getProperty( "spritz.output_fixture_data", "false" ).equals( "true" );
}
}
| [
"peter@realityforge.org"
] | peter@realityforge.org |
ab8464b7848f0dc9ec674e9bec7f60784136783d | 09e7b259be6331ba63e36ea6c2aa0c0b92e79685 | /src/main/java/io/github/zukkari/sonar/java/model/expression/ArrayAccessExpressionTreeImpl.java | d0fc54fdcbea69d9f938e12587c2f7f1ddae8a79 | [] | no_license | Zukkari/sonar-java-extracted | fb0a5d3162b7d7c71f76629e2f7efc464d07d038 | 1a15552ac9cb0d8e1f7b8fba50f207a34f42535a | refs/heads/master | 2022-04-02T00:08:59.602969 | 2020-02-18T08:22:14 | 2020-02-18T08:22:14 | 237,046,879 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,215 | java | /*
* SonarQube Java
* Copyright (C) 2012-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package io.github.zukkari.sonar.java.model.expression;
import com.google.common.collect.Lists;
import io.github.zukkari.sonar.java.model.AbstractTypedTree;
import org.sonar.plugins.java.api.tree.ArrayAccessExpressionTree;
import org.sonar.plugins.java.api.tree.ArrayDimensionTree;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.TreeVisitor;
public class ArrayAccessExpressionTreeImpl extends AbstractTypedTree implements ArrayAccessExpressionTree {
private ExpressionTree expression;
private final ArrayDimensionTree dimension;
public ArrayAccessExpressionTreeImpl(ArrayDimensionTree dimension) {
super(Kind.ARRAY_ACCESS_EXPRESSION);
this.dimension = dimension;
}
public ArrayAccessExpressionTreeImpl complete(ExpressionTree expression) {
this.expression = expression;
return this;
}
@Override
public Kind kind() {
return Kind.ARRAY_ACCESS_EXPRESSION;
}
@Override
public ExpressionTree expression() {
return expression;
}
@Override
public void accept(TreeVisitor visitor) {
visitor.visitArrayAccessExpression(this);
}
@Override
public ArrayDimensionTree dimension() {
return dimension;
}
@Override
public Iterable<Tree> children() {
return Lists.newArrayList(expression, dimension);
}
}
| [
"stanislav.myshkovski@gmail.com"
] | stanislav.myshkovski@gmail.com |
7c4e9c0659118057b88b3cf4edf51cd4f2c727fb | c5f2920836a4cdb9ac27f74f38aa944d77f6f459 | /AlarmSystem/src/tests/SirenTest.java | d882cb331a126319435c2a26a08e54dd9670cbe3 | [] | no_license | mbragg02/MacroCommand | df24f53c14a33ca6f7b34a38baf615461af343a1 | 9469403bc7491dc7f8655b52377079c40fa0c4f9 | refs/heads/master | 2020-05-29T12:26:29.112998 | 2014-02-25T15:34:40 | 2014-02-25T15:34:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 215 | java | package tests;
import org.junit.Test;
import code.Siren;
public class SirenTest {
@Test
public void test() {
Siren siren = new Siren();
siren.turnOnSiren();
siren.turnOffSiren();
}
}
| [
"oded@dcs.bbk.ac.uk"
] | oded@dcs.bbk.ac.uk |
ca35412864880cf1d1872fe0d2f34d87654cf8f2 | 970f39168f65aa806299732eb826fa6f550e3e14 | /azure-event-hub-transport/src/main/java/com/esri/geoevent/transport/azure/AzureEventHubInboundTransportService.java | c3ecaf97540fc01da606ab3fc3022af29c0acc4d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Esri/azure-for-geoevent | 517fb3c9b8f046bce89070fcda64781ecfec0019 | 749ee5d816145e21b4ce66d8fb4dbff364072c6b | refs/heads/master | 2023-08-22T03:10:38.447843 | 2022-11-29T19:18:31 | 2022-11-29T19:18:31 | 61,133,892 | 7 | 10 | Apache-2.0 | 2022-11-29T19:18:32 | 2016-06-14T15:23:40 | Java | UTF-8 | Java | false | false | 1,366 | java | /*
Copyright 1995-2017 Esri
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.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373
email: contracts@esri.com
*/
package com.esri.geoevent.transport.azure;
import com.esri.ges.core.component.ComponentException;
import com.esri.ges.transport.Transport;
import com.esri.ges.transport.TransportServiceBase;
public class AzureEventHubInboundTransportService extends TransportServiceBase {
public AzureEventHubInboundTransportService() {
definition = new AzureEventHubInboundTransportDefinition();
}
@Override
public Transport createTransport() throws ComponentException {
return new AzureEventHubInboundTransport(definition);
}
}
| [
"hkalmanovich@esri.com"
] | hkalmanovich@esri.com |
42c9d5d7e0109d1b1c371821c3f54723ff3bfd3f | d310d95f8040d6c71ac711643fcb3bca9d5a74e3 | /InstanceVariables/src/apples.java | 819caef539f5f06146e9797e0b4529effad07883 | [] | no_license | faithfem/newBoston | 9a9c4272faef3abd3744c8fdd73d50bb1f27e85b | d00ca3146fca5ead1e7b06c4e331c9a5df4d24ee | refs/heads/master | 2021-05-02T08:11:02.536182 | 2018-03-22T03:46:19 | 2018-03-22T03:46:19 | 120,846,011 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 355 | java | import java.util.Scanner;
public class apples {
public static void main(String[] args){
Scanner gonyo = new Scanner(System.in);
tuna tunaObject = new tuna();
System.out.println("Enter name here: ");
String temp = gonyo.nextLine();
tunaObject.setItinariri(temp);
tunaObject.methodIsShiku();
}
}
| [
"fmugure@intracitygeeks.org"
] | fmugure@intracitygeeks.org |
8de48c406d1069d3be4c6117123960c252d5bb38 | d7018d9baf4abfcf3f695b46131085a753c9017c | /agency-model/src/main/java/com/agency/repository/ThoCongViecRepository.java | 0e6ba1c54261b2f346631cb25d341e7816366369 | [] | no_license | zondz/AgencyManagementSystem | 837980e076ee3efd89e82eda0853c77dd4628231 | a730e527464ed82e1afa82dc6f25519785c52301 | refs/heads/master | 2023-06-24T16:36:50.248625 | 2021-07-20T10:00:34 | 2021-07-20T10:00:34 | 381,571,855 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 325 | java | package com.agency.repository;
import java.util.List;
import com.agency.model.ThoCongViec;
public interface ThoCongViecRepository extends GenericRepository<Integer , ThoCongViec>{
void updateThoCongViecChoMotCongViec(List<ThoCongViec> thoCongViecList);
List<ThoCongViec> getListThoCongViecByIdCongViec(Integer id);
}
| [
"1801040203@s.hanu.edu.vn"
] | 1801040203@s.hanu.edu.vn |
05f2041d34aa7aaca0ef6a44b519f1d4f238c544 | 700f24cea1825614066258c468527ef40d940e7c | /RentCar/src/Servlet/UpdateInventoryServlet.java | 755fb6c0c7ca47b2350fd387740ff8924629266c | [] | no_license | AhmedAmeer1/ITP_GROUP_03 | ad020ed22a79315b0d41d2a9efe38f08fadadcf4 | 139b1ac17d417cc7cfa9a86cacc5b08ac60ace21 | refs/heads/master | 2023-01-04T12:45:55.219965 | 2020-10-24T06:04:09 | 2020-10-24T06:04:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,103 | java | package Servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Inventory;
import service.IInventoryService;
import service.InventoryServiceimpl;
/**
* Servlet implementation class UpdateInventoryServlet
*/
@WebServlet("/UpdateInventoryServlet")
public class UpdateInventoryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpdateInventoryServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
Inventory inventory = new Inventory();
inventory.setCarID(request.getParameter("cardid"));
System.out.println(request.getParameter("cardid"));
inventory.setModel(request.getParameter("model"));
inventory.setDescription(request.getParameter("description"));
inventory.setNoOfPassengers(Integer.parseInt(request.getParameter("noOfpass")));
inventory.setUrl(request.getParameter("url"));
IInventoryService iinventoryService = new InventoryServiceimpl();
iinventoryService.updateInventory(inventory);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/view_inventories.jsp");
dispatcher.forward(request, response);
}
}
| [
"ahmedameer1999421@gmail.com"
] | ahmedameer1999421@gmail.com |
1b13d3048642ddc4eeda21bec1e1361c2f27092a | 2a8dc0f277b966e152c894057e79af2bf246da39 | /service/src/main/java/com/sohlman/liferay/foo/service/persistence/impl/FooPersistenceImpl.java | 381dddbd8f392527049f25c6551f785245bca76c | [
"Apache-2.0"
] | permissive | sammso/arquillian-liferay-example | 423edc70b8205c1275e71b53b9c8fe86a7febcf1 | 5da27d7e362d5fa0daea32543c50701b8b0dcd5c | refs/heads/master | 2021-08-06T19:19:58.096017 | 2017-11-06T22:05:11 | 2017-11-06T22:05:11 | 109,719,217 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 99,229 | java | /**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.sohlman.liferay.foo.service.persistence.impl;
import aQute.bnd.annotation.ProviderType;
import com.liferay.portal.kernel.dao.orm.EntityCache;
import com.liferay.portal.kernel.dao.orm.FinderCache;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextThreadLocal;
import com.liferay.portal.kernel.service.persistence.CompanyProvider;
import com.liferay.portal.kernel.service.persistence.CompanyProviderWrapper;
import com.liferay.portal.kernel.service.persistence.impl.BasePersistenceImpl;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.ReflectionUtil;
import com.liferay.portal.kernel.util.SetUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
import com.liferay.portal.spring.extender.service.ServiceReference;
import com.sohlman.liferay.foo.exception.NoSuchFooException;
import com.sohlman.liferay.foo.model.Foo;
import com.sohlman.liferay.foo.model.impl.FooImpl;
import com.sohlman.liferay.foo.model.impl.FooModelImpl;
import com.sohlman.liferay.foo.service.persistence.FooPersistence;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* The persistence implementation for the foo service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author Brian Wing Shun Chan
* @see FooPersistence
* @see com.sohlman.liferay.foo.service.persistence.FooUtil
* @generated
*/
@ProviderType
public class FooPersistenceImpl extends BasePersistenceImpl<Foo>
implements FooPersistence {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. Always use {@link FooUtil} to access the foo persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
*/
public static final String FINDER_CLASS_NAME_ENTITY = FooImpl.class.getName();
public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List1";
public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List2";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByUuid",
new String[] {
String.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid",
new String[] { String.class.getName() },
FooModelImpl.UUID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid",
new String[] { String.class.getName() });
/**
* Returns all the foos where uuid = ?.
*
* @param uuid the uuid
* @return the matching foos
*/
@Override
public List<Foo> findByUuid(String uuid) {
return findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the foos where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @return the range of matching foos
*/
@Override
public List<Foo> findByUuid(String uuid, int start, int end) {
return findByUuid(uuid, start, end, null);
}
/**
* Returns an ordered range of all the foos where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByUuid(String uuid, int start, int end,
OrderByComparator<Foo> orderByComparator) {
return findByUuid(uuid, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the foos where uuid = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByUuid(String uuid, int start, int end,
OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID;
finderArgs = new Object[] { uuid, start, end, orderByComparator };
}
List<Foo> list = null;
if (retrieveFromCache) {
list = (List<Foo>)finderCache.getResult(finderPath, finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (Foo foo : list) {
if (!Objects.equals(uuid, foo.getUuid())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
if (!pagination) {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start,
end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first foo in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByUuid_First(String uuid,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByUuid_First(uuid, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the first foo in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByUuid_First(String uuid,
OrderByComparator<Foo> orderByComparator) {
List<Foo> list = findByUuid(uuid, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last foo in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByUuid_Last(String uuid,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByUuid_Last(uuid, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the last foo in the ordered set where uuid = ?.
*
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByUuid_Last(String uuid,
OrderByComparator<Foo> orderByComparator) {
int count = countByUuid(uuid);
if (count == 0) {
return null;
}
List<Foo> list = findByUuid(uuid, count - 1, count, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the foos before and after the current foo in the ordered set where uuid = ?.
*
* @param fooId the primary key of the current foo
* @param uuid the uuid
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next foo
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo[] findByUuid_PrevAndNext(long fooId, String uuid,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = findByPrimaryKey(fooId);
Session session = null;
try {
session = openSession();
Foo[] array = new FooImpl[3];
array[0] = getByUuid_PrevAndNext(session, foo, uuid,
orderByComparator, true);
array[1] = foo;
array[2] = getByUuid_PrevAndNext(session, foo, uuid,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected Foo getByUuid_PrevAndNext(Session session, Foo foo, String uuid,
OrderByComparator<Foo> orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(foo);
for (Object value : values) {
qPos.add(value);
}
}
List<Foo> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the foos where uuid = ? from the database.
*
* @param uuid the uuid
*/
@Override
public void removeByUuid(String uuid) {
for (Foo foo : findByUuid(uuid, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
null)) {
remove(foo);
}
}
/**
* Returns the number of foos where uuid = ?.
*
* @param uuid the uuid
* @return the number of matching foos
*/
@Override
public int countByUuid(String uuid) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID;
Object[] finderArgs = new Object[] { uuid };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_UUID_2);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_UUID_1 = "foo.uuid IS NULL";
private static final String _FINDER_COLUMN_UUID_UUID_2 = "foo.uuid = ?";
private static final String _FINDER_COLUMN_UUID_UUID_3 = "(foo.uuid IS NULL OR foo.uuid = '')";
public static final FinderPath FINDER_PATH_FETCH_BY_UUID_G = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_ENTITY, "fetchByUUID_G",
new String[] { String.class.getName(), Long.class.getName() },
FooModelImpl.UUID_COLUMN_BITMASK |
FooModelImpl.GROUPID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID_G = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUUID_G",
new String[] { String.class.getName(), Long.class.getName() });
/**
* Returns the foo where uuid = ? and groupId = ? or throws a {@link NoSuchFooException} if it could not be found.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByUUID_G(String uuid, long groupId)
throws NoSuchFooException {
Foo foo = fetchByUUID_G(uuid, groupId);
if (foo == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchFooException(msg.toString());
}
return foo;
}
/**
* Returns the foo where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
}
/**
* Returns the foo where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found, optionally using the finder cache.
*
* @param uuid the uuid
* @param groupId the group ID
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByUUID_G(String uuid, long groupId,
boolean retrieveFromCache) {
Object[] finderArgs = new Object[] { uuid, groupId };
Object result = null;
if (retrieveFromCache) {
result = finderCache.getResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, this);
}
if (result instanceof Foo) {
Foo foo = (Foo)result;
if (!Objects.equals(uuid, foo.getUuid()) ||
(groupId != foo.getGroupId())) {
result = null;
}
}
if (result == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_SELECT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_G_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_G_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_G_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(groupId);
List<Foo> list = q.list();
if (list.isEmpty()) {
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, list);
}
else {
Foo foo = list.get(0);
result = foo;
cacheResult(foo);
if ((foo.getUuid() == null) || !foo.getUuid().equals(uuid) ||
(foo.getGroupId() != groupId)) {
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
finderArgs, foo);
}
}
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
if (result instanceof List<?>) {
return null;
}
else {
return (Foo)result;
}
}
/**
* Removes the foo where uuid = ? and groupId = ? from the database.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the foo that was removed
*/
@Override
public Foo removeByUUID_G(String uuid, long groupId)
throws NoSuchFooException {
Foo foo = findByUUID_G(uuid, groupId);
return remove(foo);
}
/**
* Returns the number of foos where uuid = ? and groupId = ?.
*
* @param uuid the uuid
* @param groupId the group ID
* @return the number of matching foos
*/
@Override
public int countByUUID_G(String uuid, long groupId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_G;
Object[] finderArgs = new Object[] { uuid, groupId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_G_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_G_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_G_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_G_GROUPID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(groupId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_G_UUID_1 = "foo.uuid IS NULL AND ";
private static final String _FINDER_COLUMN_UUID_G_UUID_2 = "foo.uuid = ? AND ";
private static final String _FINDER_COLUMN_UUID_G_UUID_3 = "(foo.uuid IS NULL OR foo.uuid = '') AND ";
private static final String _FINDER_COLUMN_UUID_G_GROUPID_2 = "foo.groupId = ?";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByUuid_C",
new String[] {
String.class.getName(), Long.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C =
new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByUuid_C",
new String[] { String.class.getName(), Long.class.getName() },
FooModelImpl.UUID_COLUMN_BITMASK |
FooModelImpl.COMPANYID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_UUID_C = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByUuid_C",
new String[] { String.class.getName(), Long.class.getName() });
/**
* Returns all the foos where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @return the matching foos
*/
@Override
public List<Foo> findByUuid_C(String uuid, long companyId) {
return findByUuid_C(uuid, companyId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the foos where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @return the range of matching foos
*/
@Override
public List<Foo> findByUuid_C(String uuid, long companyId, int start,
int end) {
return findByUuid_C(uuid, companyId, start, end, null);
}
/**
* Returns an ordered range of all the foos where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByUuid_C(String uuid, long companyId, int start,
int end, OrderByComparator<Foo> orderByComparator) {
return findByUuid_C(uuid, companyId, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the foos where uuid = ? and companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param uuid the uuid
* @param companyId the company ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByUuid_C(String uuid, long companyId, int start,
int end, OrderByComparator<Foo> orderByComparator,
boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C;
finderArgs = new Object[] { uuid, companyId };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_UUID_C;
finderArgs = new Object[] {
uuid, companyId,
start, end, orderByComparator
};
}
List<Foo> list = null;
if (retrieveFromCache) {
list = (List<Foo>)finderCache.getResult(finderPath, finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (Foo foo : list) {
if (!Objects.equals(uuid, foo.getUuid()) ||
(companyId != foo.getCompanyId())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(4);
}
query.append(_SQL_SELECT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
if (!pagination) {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start,
end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first foo in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByUuid_C_First(String uuid, long companyId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByUuid_C_First(uuid, companyId, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the first foo in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByUuid_C_First(String uuid, long companyId,
OrderByComparator<Foo> orderByComparator) {
List<Foo> list = findByUuid_C(uuid, companyId, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last foo in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByUuid_C_Last(String uuid, long companyId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByUuid_C_Last(uuid, companyId, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the last foo in the ordered set where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByUuid_C_Last(String uuid, long companyId,
OrderByComparator<Foo> orderByComparator) {
int count = countByUuid_C(uuid, companyId);
if (count == 0) {
return null;
}
List<Foo> list = findByUuid_C(uuid, companyId, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the foos before and after the current foo in the ordered set where uuid = ? and companyId = ?.
*
* @param fooId the primary key of the current foo
* @param uuid the uuid
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next foo
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo[] findByUuid_C_PrevAndNext(long fooId, String uuid,
long companyId, OrderByComparator<Foo> orderByComparator)
throws NoSuchFooException {
Foo foo = findByPrimaryKey(fooId);
Session session = null;
try {
session = openSession();
Foo[] array = new FooImpl[3];
array[0] = getByUuid_C_PrevAndNext(session, foo, uuid, companyId,
orderByComparator, true);
array[1] = foo;
array[2] = getByUuid_C_PrevAndNext(session, foo, uuid, companyId,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected Foo getByUuid_C_PrevAndNext(Session session, Foo foo,
String uuid, long companyId, OrderByComparator<Foo> orderByComparator,
boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(5 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(4);
}
query.append(_SQL_SELECT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(foo);
for (Object value : values) {
qPos.add(value);
}
}
List<Foo> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the foos where uuid = ? and companyId = ? from the database.
*
* @param uuid the uuid
* @param companyId the company ID
*/
@Override
public void removeByUuid_C(String uuid, long companyId) {
for (Foo foo : findByUuid_C(uuid, companyId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null)) {
remove(foo);
}
}
/**
* Returns the number of foos where uuid = ? and companyId = ?.
*
* @param uuid the uuid
* @param companyId the company ID
* @return the number of matching foos
*/
@Override
public int countByUuid_C(String uuid, long companyId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_UUID_C;
Object[] finderArgs = new Object[] { uuid, companyId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(3);
query.append(_SQL_COUNT_FOO_WHERE);
boolean bindUuid = false;
if (uuid == null) {
query.append(_FINDER_COLUMN_UUID_C_UUID_1);
}
else if (uuid.equals(StringPool.BLANK)) {
query.append(_FINDER_COLUMN_UUID_C_UUID_3);
}
else {
bindUuid = true;
query.append(_FINDER_COLUMN_UUID_C_UUID_2);
}
query.append(_FINDER_COLUMN_UUID_C_COMPANYID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
if (bindUuid) {
qPos.add(uuid);
}
qPos.add(companyId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_UUID_C_UUID_1 = "foo.uuid IS NULL AND ";
private static final String _FINDER_COLUMN_UUID_C_UUID_2 = "foo.uuid = ? AND ";
private static final String _FINDER_COLUMN_UUID_C_UUID_3 = "(foo.uuid IS NULL OR foo.uuid = '') AND ";
private static final String _FINDER_COLUMN_UUID_C_COMPANYID_2 = "foo.companyId = ?";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_GROUP = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByGroup",
new String[] {
Long.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUP = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByGroup",
new String[] { Long.class.getName() },
FooModelImpl.GROUPID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_GROUP = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByGroup",
new String[] { Long.class.getName() });
/**
* Returns all the foos where groupId = ?.
*
* @param groupId the group ID
* @return the matching foos
*/
@Override
public List<Foo> findByGroup(long groupId) {
return findByGroup(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the foos where groupId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param groupId the group ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @return the range of matching foos
*/
@Override
public List<Foo> findByGroup(long groupId, int start, int end) {
return findByGroup(groupId, start, end, null);
}
/**
* Returns an ordered range of all the foos where groupId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param groupId the group ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByGroup(long groupId, int start, int end,
OrderByComparator<Foo> orderByComparator) {
return findByGroup(groupId, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the foos where groupId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param groupId the group ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByGroup(long groupId, int start, int end,
OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUP;
finderArgs = new Object[] { groupId };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_GROUP;
finderArgs = new Object[] { groupId, start, end, orderByComparator };
}
List<Foo> list = null;
if (retrieveFromCache) {
list = (List<Foo>)finderCache.getResult(finderPath, finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (Foo foo : list) {
if ((groupId != foo.getGroupId())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_FOO_WHERE);
query.append(_FINDER_COLUMN_GROUP_GROUPID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (!pagination) {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start,
end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first foo in the ordered set where groupId = ?.
*
* @param groupId the group ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByGroup_First(long groupId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByGroup_First(groupId, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("groupId=");
msg.append(groupId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the first foo in the ordered set where groupId = ?.
*
* @param groupId the group ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByGroup_First(long groupId,
OrderByComparator<Foo> orderByComparator) {
List<Foo> list = findByGroup(groupId, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last foo in the ordered set where groupId = ?.
*
* @param groupId the group ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByGroup_Last(long groupId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByGroup_Last(groupId, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("groupId=");
msg.append(groupId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the last foo in the ordered set where groupId = ?.
*
* @param groupId the group ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByGroup_Last(long groupId,
OrderByComparator<Foo> orderByComparator) {
int count = countByGroup(groupId);
if (count == 0) {
return null;
}
List<Foo> list = findByGroup(groupId, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the foos before and after the current foo in the ordered set where groupId = ?.
*
* @param fooId the primary key of the current foo
* @param groupId the group ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next foo
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo[] findByGroup_PrevAndNext(long fooId, long groupId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = findByPrimaryKey(fooId);
Session session = null;
try {
session = openSession();
Foo[] array = new FooImpl[3];
array[0] = getByGroup_PrevAndNext(session, foo, groupId,
orderByComparator, true);
array[1] = foo;
array[2] = getByGroup_PrevAndNext(session, foo, groupId,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected Foo getByGroup_PrevAndNext(Session session, Foo foo,
long groupId, OrderByComparator<Foo> orderByComparator, boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_FOO_WHERE);
query.append(_FINDER_COLUMN_GROUP_GROUPID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(foo);
for (Object value : values) {
qPos.add(value);
}
}
List<Foo> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the foos where groupId = ? from the database.
*
* @param groupId the group ID
*/
@Override
public void removeByGroup(long groupId) {
for (Foo foo : findByGroup(groupId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null)) {
remove(foo);
}
}
/**
* Returns the number of foos where groupId = ?.
*
* @param groupId the group ID
* @return the number of matching foos
*/
@Override
public int countByGroup(long groupId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_GROUP;
Object[] finderArgs = new Object[] { groupId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_FOO_WHERE);
query.append(_FINDER_COLUMN_GROUP_GROUPID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_GROUP_GROUPID_2 = "foo.groupId = ?";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_COMPANY = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByCompany",
new String[] {
Long.class.getName(),
Integer.class.getName(), Integer.class.getName(),
OrderByComparator.class.getName()
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_COMPANY =
new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, FooImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByCompany",
new String[] { Long.class.getName() },
FooModelImpl.COMPANYID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_COMPANY = new FinderPath(FooModelImpl.ENTITY_CACHE_ENABLED,
FooModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByCompany",
new String[] { Long.class.getName() });
/**
* Returns all the foos where companyId = ?.
*
* @param companyId the company ID
* @return the matching foos
*/
@Override
public List<Foo> findByCompany(long companyId) {
return findByCompany(companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
null);
}
/**
* Returns a range of all the foos where companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param companyId the company ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @return the range of matching foos
*/
@Override
public List<Foo> findByCompany(long companyId, int start, int end) {
return findByCompany(companyId, start, end, null);
}
/**
* Returns an ordered range of all the foos where companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param companyId the company ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByCompany(long companyId, int start, int end,
OrderByComparator<Foo> orderByComparator) {
return findByCompany(companyId, start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the foos where companyId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param companyId the company ID
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of matching foos
*/
@Override
public List<Foo> findByCompany(long companyId, int start, int end,
OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_COMPANY;
finderArgs = new Object[] { companyId };
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_COMPANY;
finderArgs = new Object[] { companyId, start, end, orderByComparator };
}
List<Foo> list = null;
if (retrieveFromCache) {
list = (List<Foo>)finderCache.getResult(finderPath, finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (Foo foo : list) {
if ((companyId != foo.getCompanyId())) {
list = null;
break;
}
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 2));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_FOO_WHERE);
query.append(_FINDER_COLUMN_COMPANY_COMPANYID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else
if (pagination) {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(companyId);
if (!pagination) {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start,
end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Returns the first foo in the ordered set where companyId = ?.
*
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByCompany_First(long companyId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByCompany_First(companyId, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the first foo in the ordered set where companyId = ?.
*
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByCompany_First(long companyId,
OrderByComparator<Foo> orderByComparator) {
List<Foo> list = findByCompany(companyId, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last foo in the ordered set where companyId = ?.
*
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo
* @throws NoSuchFooException if a matching foo could not be found
*/
@Override
public Foo findByCompany_Last(long companyId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = fetchByCompany_Last(companyId, orderByComparator);
if (foo != null) {
return foo;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("companyId=");
msg.append(companyId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchFooException(msg.toString());
}
/**
* Returns the last foo in the ordered set where companyId = ?.
*
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching foo, or <code>null</code> if a matching foo could not be found
*/
@Override
public Foo fetchByCompany_Last(long companyId,
OrderByComparator<Foo> orderByComparator) {
int count = countByCompany(companyId);
if (count == 0) {
return null;
}
List<Foo> list = findByCompany(companyId, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the foos before and after the current foo in the ordered set where companyId = ?.
*
* @param fooId the primary key of the current foo
* @param companyId the company ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next foo
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo[] findByCompany_PrevAndNext(long fooId, long companyId,
OrderByComparator<Foo> orderByComparator) throws NoSuchFooException {
Foo foo = findByPrimaryKey(fooId);
Session session = null;
try {
session = openSession();
Foo[] array = new FooImpl[3];
array[0] = getByCompany_PrevAndNext(session, foo, companyId,
orderByComparator, true);
array[1] = foo;
array[2] = getByCompany_PrevAndNext(session, foo, companyId,
orderByComparator, false);
return array;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
protected Foo getByCompany_PrevAndNext(Session session, Foo foo,
long companyId, OrderByComparator<Foo> orderByComparator,
boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(4 +
(orderByComparator.getOrderByConditionFields().length * 3) +
(orderByComparator.getOrderByFields().length * 3));
}
else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_FOO_WHERE);
query.append(_FINDER_COLUMN_COMPANY_COMPANYID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
}
else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
}
else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
}
else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
}
else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
}
else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(FooModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(companyId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(foo);
for (Object value : values) {
qPos.add(value);
}
}
List<Foo> list = q.list();
if (list.size() == 2) {
return list.get(1);
}
else {
return null;
}
}
/**
* Removes all the foos where companyId = ? from the database.
*
* @param companyId the company ID
*/
@Override
public void removeByCompany(long companyId) {
for (Foo foo : findByCompany(companyId, QueryUtil.ALL_POS,
QueryUtil.ALL_POS, null)) {
remove(foo);
}
}
/**
* Returns the number of foos where companyId = ?.
*
* @param companyId the company ID
* @return the number of matching foos
*/
@Override
public int countByCompany(long companyId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_COMPANY;
Object[] finderArgs = new Object[] { companyId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_FOO_WHERE);
query.append(_FINDER_COLUMN_COMPANY_COMPANYID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(companyId);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
private static final String _FINDER_COLUMN_COMPANY_COMPANYID_2 = "foo.companyId = ?";
public FooPersistenceImpl() {
setModelClass(Foo.class);
try {
Field field = ReflectionUtil.getDeclaredField(BasePersistenceImpl.class,
"_dbColumnNames");
Map<String, String> dbColumnNames = new HashMap<String, String>();
dbColumnNames.put("uuid", "uuid_");
field.set(this, dbColumnNames);
}
catch (Exception e) {
if (_log.isDebugEnabled()) {
_log.debug(e, e);
}
}
}
/**
* Caches the foo in the entity cache if it is enabled.
*
* @param foo the foo
*/
@Override
public void cacheResult(Foo foo) {
entityCache.putResult(FooModelImpl.ENTITY_CACHE_ENABLED, FooImpl.class,
foo.getPrimaryKey(), foo);
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
new Object[] { foo.getUuid(), foo.getGroupId() }, foo);
foo.resetOriginalValues();
}
/**
* Caches the foos in the entity cache if it is enabled.
*
* @param foos the foos
*/
@Override
public void cacheResult(List<Foo> foos) {
for (Foo foo : foos) {
if (entityCache.getResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, foo.getPrimaryKey()) == null) {
cacheResult(foo);
}
else {
foo.resetOriginalValues();
}
}
}
/**
* Clears the cache for all foos.
*
* <p>
* The {@link EntityCache} and {@link FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache() {
entityCache.clearCache(FooImpl.class);
finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
/**
* Clears the cache for the foo.
*
* <p>
* The {@link EntityCache} and {@link FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache(Foo foo) {
entityCache.removeResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, foo.getPrimaryKey());
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
clearUniqueFindersCache((FooModelImpl)foo, true);
}
@Override
public void clearCache(List<Foo> foos) {
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
for (Foo foo : foos) {
entityCache.removeResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, foo.getPrimaryKey());
clearUniqueFindersCache((FooModelImpl)foo, true);
}
}
protected void cacheUniqueFindersCache(FooModelImpl fooModelImpl) {
Object[] args = new Object[] {
fooModelImpl.getUuid(), fooModelImpl.getGroupId()
};
finderCache.putResult(FINDER_PATH_COUNT_BY_UUID_G, args,
Long.valueOf(1), false);
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G, args, fooModelImpl,
false);
}
protected void clearUniqueFindersCache(FooModelImpl fooModelImpl,
boolean clearCurrent) {
if (clearCurrent) {
Object[] args = new Object[] {
fooModelImpl.getUuid(), fooModelImpl.getGroupId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);
}
if ((fooModelImpl.getColumnBitmask() &
FINDER_PATH_FETCH_BY_UUID_G.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
fooModelImpl.getOriginalUuid(),
fooModelImpl.getOriginalGroupId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_G, args);
finderCache.removeResult(FINDER_PATH_FETCH_BY_UUID_G, args);
}
}
/**
* Creates a new foo with the primary key. Does not add the foo to the database.
*
* @param fooId the primary key for the new foo
* @return the new foo
*/
@Override
public Foo create(long fooId) {
Foo foo = new FooImpl();
foo.setNew(true);
foo.setPrimaryKey(fooId);
String uuid = PortalUUIDUtil.generate();
foo.setUuid(uuid);
foo.setCompanyId(companyProvider.getCompanyId());
return foo;
}
/**
* Removes the foo with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param fooId the primary key of the foo
* @return the foo that was removed
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo remove(long fooId) throws NoSuchFooException {
return remove((Serializable)fooId);
}
/**
* Removes the foo with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param primaryKey the primary key of the foo
* @return the foo that was removed
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo remove(Serializable primaryKey) throws NoSuchFooException {
Session session = null;
try {
session = openSession();
Foo foo = (Foo)session.get(FooImpl.class, primaryKey);
if (foo == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchFooException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(foo);
}
catch (NoSuchFooException nsee) {
throw nsee;
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
}
@Override
protected Foo removeImpl(Foo foo) {
foo = toUnwrappedModel(foo);
Session session = null;
try {
session = openSession();
if (!session.contains(foo)) {
foo = (Foo)session.get(FooImpl.class, foo.getPrimaryKeyObj());
}
if (foo != null) {
session.delete(foo);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
if (foo != null) {
clearCache(foo);
}
return foo;
}
@Override
public Foo updateImpl(Foo foo) {
foo = toUnwrappedModel(foo);
boolean isNew = foo.isNew();
FooModelImpl fooModelImpl = (FooModelImpl)foo;
if (Validator.isNull(foo.getUuid())) {
String uuid = PortalUUIDUtil.generate();
foo.setUuid(uuid);
}
ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();
Date now = new Date();
if (isNew && (foo.getCreateDate() == null)) {
if (serviceContext == null) {
foo.setCreateDate(now);
}
else {
foo.setCreateDate(serviceContext.getCreateDate(now));
}
}
if (!fooModelImpl.hasSetModifiedDate()) {
if (serviceContext == null) {
foo.setModifiedDate(now);
}
else {
foo.setModifiedDate(serviceContext.getModifiedDate(now));
}
}
Session session = null;
try {
session = openSession();
if (foo.isNew()) {
session.save(foo);
foo.setNew(false);
}
else {
foo = (Foo)session.merge(foo);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
if (!FooModelImpl.COLUMN_BITMASK_ENABLED) {
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
else
if (isNew) {
Object[] args = new Object[] { fooModelImpl.getUuid() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
args = new Object[] {
fooModelImpl.getUuid(), fooModelImpl.getCompanyId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
args);
args = new Object[] { fooModelImpl.getGroupId() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_GROUP, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUP,
args);
args = new Object[] { fooModelImpl.getCompanyId() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_COMPANY, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_COMPANY,
args);
finderCache.removeResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL,
FINDER_ARGS_EMPTY);
}
else {
if ((fooModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID.getColumnBitmask()) != 0) {
Object[] args = new Object[] { fooModelImpl.getOriginalUuid() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
args = new Object[] { fooModelImpl.getUuid() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID,
args);
}
if ((fooModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
fooModelImpl.getOriginalUuid(),
fooModelImpl.getOriginalCompanyId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
args);
args = new Object[] {
fooModelImpl.getUuid(), fooModelImpl.getCompanyId()
};
finderCache.removeResult(FINDER_PATH_COUNT_BY_UUID_C, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_UUID_C,
args);
}
if ((fooModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUP.getColumnBitmask()) != 0) {
Object[] args = new Object[] { fooModelImpl.getOriginalGroupId() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_GROUP, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUP,
args);
args = new Object[] { fooModelImpl.getGroupId() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_GROUP, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_GROUP,
args);
}
if ((fooModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_COMPANY.getColumnBitmask()) != 0) {
Object[] args = new Object[] { fooModelImpl.getOriginalCompanyId() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_COMPANY, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_COMPANY,
args);
args = new Object[] { fooModelImpl.getCompanyId() };
finderCache.removeResult(FINDER_PATH_COUNT_BY_COMPANY, args);
finderCache.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_COMPANY,
args);
}
}
entityCache.putResult(FooModelImpl.ENTITY_CACHE_ENABLED, FooImpl.class,
foo.getPrimaryKey(), foo, false);
clearUniqueFindersCache(fooModelImpl, false);
cacheUniqueFindersCache(fooModelImpl);
foo.resetOriginalValues();
return foo;
}
protected Foo toUnwrappedModel(Foo foo) {
if (foo instanceof FooImpl) {
return foo;
}
FooImpl fooImpl = new FooImpl();
fooImpl.setNew(foo.isNew());
fooImpl.setPrimaryKey(foo.getPrimaryKey());
fooImpl.setUuid(foo.getUuid());
fooImpl.setFooId(foo.getFooId());
fooImpl.setGroupId(foo.getGroupId());
fooImpl.setCompanyId(foo.getCompanyId());
fooImpl.setUserId(foo.getUserId());
fooImpl.setUserName(foo.getUserName());
fooImpl.setCreateDate(foo.getCreateDate());
fooImpl.setModifiedDate(foo.getModifiedDate());
fooImpl.setPayload(foo.getPayload());
return fooImpl;
}
/**
* Returns the foo with the primary key or throws a {@link com.liferay.portal.kernel.exception.NoSuchModelException} if it could not be found.
*
* @param primaryKey the primary key of the foo
* @return the foo
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo findByPrimaryKey(Serializable primaryKey)
throws NoSuchFooException {
Foo foo = fetchByPrimaryKey(primaryKey);
if (foo == null) {
if (_log.isDebugEnabled()) {
_log.debug(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchFooException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return foo;
}
/**
* Returns the foo with the primary key or throws a {@link NoSuchFooException} if it could not be found.
*
* @param fooId the primary key of the foo
* @return the foo
* @throws NoSuchFooException if a foo with the primary key could not be found
*/
@Override
public Foo findByPrimaryKey(long fooId) throws NoSuchFooException {
return findByPrimaryKey((Serializable)fooId);
}
/**
* Returns the foo with the primary key or returns <code>null</code> if it could not be found.
*
* @param primaryKey the primary key of the foo
* @return the foo, or <code>null</code> if a foo with the primary key could not be found
*/
@Override
public Foo fetchByPrimaryKey(Serializable primaryKey) {
Serializable serializable = entityCache.getResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, primaryKey);
if (serializable == nullModel) {
return null;
}
Foo foo = (Foo)serializable;
if (foo == null) {
Session session = null;
try {
session = openSession();
foo = (Foo)session.get(FooImpl.class, primaryKey);
if (foo != null) {
cacheResult(foo);
}
else {
entityCache.putResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
entityCache.removeResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, primaryKey);
throw processException(e);
}
finally {
closeSession(session);
}
}
return foo;
}
/**
* Returns the foo with the primary key or returns <code>null</code> if it could not be found.
*
* @param fooId the primary key of the foo
* @return the foo, or <code>null</code> if a foo with the primary key could not be found
*/
@Override
public Foo fetchByPrimaryKey(long fooId) {
return fetchByPrimaryKey((Serializable)fooId);
}
@Override
public Map<Serializable, Foo> fetchByPrimaryKeys(
Set<Serializable> primaryKeys) {
if (primaryKeys.isEmpty()) {
return Collections.emptyMap();
}
Map<Serializable, Foo> map = new HashMap<Serializable, Foo>();
if (primaryKeys.size() == 1) {
Iterator<Serializable> iterator = primaryKeys.iterator();
Serializable primaryKey = iterator.next();
Foo foo = fetchByPrimaryKey(primaryKey);
if (foo != null) {
map.put(primaryKey, foo);
}
return map;
}
Set<Serializable> uncachedPrimaryKeys = null;
for (Serializable primaryKey : primaryKeys) {
Serializable serializable = entityCache.getResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, primaryKey);
if (serializable != nullModel) {
if (serializable == null) {
if (uncachedPrimaryKeys == null) {
uncachedPrimaryKeys = new HashSet<Serializable>();
}
uncachedPrimaryKeys.add(primaryKey);
}
else {
map.put(primaryKey, (Foo)serializable);
}
}
}
if (uncachedPrimaryKeys == null) {
return map;
}
StringBundler query = new StringBundler((uncachedPrimaryKeys.size() * 2) +
1);
query.append(_SQL_SELECT_FOO_WHERE_PKS_IN);
for (Serializable primaryKey : uncachedPrimaryKeys) {
query.append((long)primaryKey);
query.append(StringPool.COMMA);
}
query.setIndex(query.index() - 1);
query.append(StringPool.CLOSE_PARENTHESIS);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
for (Foo foo : (List<Foo>)q.list()) {
map.put(foo.getPrimaryKeyObj(), foo);
cacheResult(foo);
uncachedPrimaryKeys.remove(foo.getPrimaryKeyObj());
}
for (Serializable primaryKey : uncachedPrimaryKeys) {
entityCache.putResult(FooModelImpl.ENTITY_CACHE_ENABLED,
FooImpl.class, primaryKey, nullModel);
}
}
catch (Exception e) {
throw processException(e);
}
finally {
closeSession(session);
}
return map;
}
/**
* Returns all the foos.
*
* @return the foos
*/
@Override
public List<Foo> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the foos.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @return the range of foos
*/
@Override
public List<Foo> findAll(int start, int end) {
return findAll(start, end, null);
}
/**
* Returns an ordered range of all the foos.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of foos
*/
@Override
public List<Foo> findAll(int start, int end,
OrderByComparator<Foo> orderByComparator) {
return findAll(start, end, orderByComparator, true);
}
/**
* Returns an ordered range of all the foos.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link FooModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
* </p>
*
* @param start the lower bound of the range of foos
* @param end the upper bound of the range of foos (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @param retrieveFromCache whether to retrieve from the finder cache
* @return the ordered range of foos
*/
@Override
public List<Foo> findAll(int start, int end,
OrderByComparator<Foo> orderByComparator, boolean retrieveFromCache) {
boolean pagination = true;
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
pagination = false;
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
finderArgs = FINDER_ARGS_EMPTY;
}
else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
finderArgs = new Object[] { start, end, orderByComparator };
}
List<Foo> list = null;
if (retrieveFromCache) {
list = (List<Foo>)finderCache.getResult(finderPath, finderArgs, this);
}
if (list == null) {
StringBundler query = null;
String sql = null;
if (orderByComparator != null) {
query = new StringBundler(2 +
(orderByComparator.getOrderByFields().length * 2));
query.append(_SQL_SELECT_FOO);
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
sql = query.toString();
}
else {
sql = _SQL_SELECT_FOO;
if (pagination) {
sql = sql.concat(FooModelImpl.ORDER_BY_JPQL);
}
}
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
if (!pagination) {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start,
end, false);
Collections.sort(list);
list = Collections.unmodifiableList(list);
}
else {
list = (List<Foo>)QueryUtil.list(q, getDialect(), start, end);
}
cacheResult(list);
finderCache.putResult(finderPath, finderArgs, list);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return list;
}
/**
* Removes all the foos from the database.
*
*/
@Override
public void removeAll() {
for (Foo foo : findAll()) {
remove(foo);
}
}
/**
* Returns the number of foos.
*
* @return the number of foos
*/
@Override
public int countAll() {
Long count = (Long)finderCache.getResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY, this);
if (count == null) {
Session session = null;
try {
session = openSession();
Query q = session.createQuery(_SQL_COUNT_FOO);
count = (Long)q.uniqueResult();
finderCache.putResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY,
count);
}
catch (Exception e) {
finderCache.removeResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
}
@Override
public Set<String> getBadColumnNames() {
return _badColumnNames;
}
@Override
protected Map<String, Integer> getTableColumnsMap() {
return FooModelImpl.TABLE_COLUMNS_MAP;
}
/**
* Initializes the foo persistence.
*/
public void afterPropertiesSet() {
}
public void destroy() {
entityCache.removeCache(FooImpl.class.getName());
finderCache.removeCache(FINDER_CLASS_NAME_ENTITY);
finderCache.removeCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
@ServiceReference(type = CompanyProviderWrapper.class)
protected CompanyProvider companyProvider;
@ServiceReference(type = EntityCache.class)
protected EntityCache entityCache;
@ServiceReference(type = FinderCache.class)
protected FinderCache finderCache;
private static final String _SQL_SELECT_FOO = "SELECT foo FROM Foo foo";
private static final String _SQL_SELECT_FOO_WHERE_PKS_IN = "SELECT foo FROM Foo foo WHERE fooId IN (";
private static final String _SQL_SELECT_FOO_WHERE = "SELECT foo FROM Foo foo WHERE ";
private static final String _SQL_COUNT_FOO = "SELECT COUNT(foo) FROM Foo foo";
private static final String _SQL_COUNT_FOO_WHERE = "SELECT COUNT(foo) FROM Foo foo WHERE ";
private static final String _ORDER_BY_ENTITY_ALIAS = "foo.";
private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Foo exists with the primary key ";
private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Foo exists with the key {";
private static final Log _log = LogFactoryUtil.getLog(FooPersistenceImpl.class);
private static final Set<String> _badColumnNames = SetUtil.fromArray(new String[] {
"uuid"
});
} | [
"sampsa@sohlman.com"
] | sampsa@sohlman.com |
98952097998bf2070b924168ab0c4c55c1bc7f4f | bc8c36c3caac051826fa1971a77d7f1334b0308a | /src/test/java/Library/LibraryShould.java | 78cd567528f157ddc8ef733aa12f595a1d7b203a | [] | no_license | domke159/java-developer-task | 1624c916d4a75ed5550c80c79067b9cbcc2bf208 | 0976719a8c92b5f87cd5657832512dd8cf9b9706 | refs/heads/master | 2023-06-05T02:51:34.275011 | 2021-06-22T07:41:53 | 2021-06-22T07:41:53 | 379,182,657 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,260 | java | package Library;
import JavaDeveloperTask.Book.Book;
import JavaDeveloperTask.Library.Library;
import JavaDeveloperTask.Person.Author.Author;
import JavaDeveloperTask.Person.Customer.Customer;
import org.junit.Before;
import org.junit.Test;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
public class LibraryShould {
private Library library;
@Before
public void initialise() {
library = new Library("The National Library", "The famous street, 1");
}
@Test
public void changeName() {
library.setName("The Local Library");
assertEquals("The Local Library", library.getName());
}
@Test
public void changeAddress() {
library.setAddress("The infamous street, 2");
assertEquals("The infamous street, 2", library.getAddress());
}
@Test
public void changePeriodLimit() {
library.setPeriodLimit(5);
assertEquals(5, library.getPeriodLimit());
}
@Test
public void addCustomer() {
Customer customer = new Customer(12345678911L, "James Jameson");
library.getCustomers().add(customer);
assertSame(customer, library.getCustomers().get(0));
}
@Test
public void removeCustomer() {
Customer customer = new Customer(12345678911L, "James Jameson");
library.getCustomers().add(customer);
assertSame(customer, library.getCustomers().get(0));
library.getCustomers().remove(customer);
assertEquals(0, library.getCustomers().size());
}
@Test
public void findCustomer() {
Customer customer = new Customer(12345678911L, "James Jameson");
library.getCustomers().add(customer);
assertSame(customer, library.findCustomer("James Jameson"));
}
@Test
public void notFindCustomerWithWrongName() {
Customer customer = new Customer(12345678911L, "James Jameson");
library.getCustomers().add(customer);
assertSame(null, library.findCustomer("John Jameson"));
}
@Test
public void addBook() {
Author author = new Author("John Baker");
Book book = new Book(author, "The Dark Side", "Fantasy", "English",
LocalDate.parse("2021-05-04", DateTimeFormatter.ofPattern("yyyy-MM-dd")),
"918-2-13-148410-5", "1414e7d3-1d74-452e-9451-f6ebf8549b3a");
library.getBookList().add(book);
assertSame(book, library.getBookList().get(0));
}
@Test
public void deleteBook() {
Author author = new Author("John Baker");
Book book = new Book(author, "The Dark Side", "Fantasy", "English",
LocalDate.parse("2021-05-04", DateTimeFormatter.ofPattern("yyyy-MM-dd")),
"918-2-13-148410-5", "1414e7d3-1d74-452e-9451-f6ebf8549b3a");
library.getBookList().add(book);
assertSame(book, library.getBookList().get(0));
library.getBookList().remove(book);
assertEquals(0, library.getBookList().size());
}
@Test
public void changeBookLimit() {
library.setBookLimit(5);
assertEquals(5, library.getBookLimit());
}
}
| [
"mickeviciusdom@gmail.com"
] | mickeviciusdom@gmail.com |
56ca368c2d34ecb2cad31207ba93df894932a450 | d77663283fd139bddaac7e4e38359785b41fd702 | /src/main/java/com/example/demo/ServletInitializer.java | 41179f5d1789f1709480db1265ffee8e7fb155cd | [] | no_license | aniruddhadhal/MyFirstWeb | 0c944e24904f31441a085447556f332a735f319b | a0ee51a41ab42331bf26a5ab818f9ac33fef0562 | refs/heads/master | 2021-12-23T17:18:45.622037 | 2017-11-19T07:15:57 | 2017-11-19T07:15:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 402 | java | package com.example.demo;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyFirstWebApplication.class);
}
}
| [
"abhdutta3981@gmail.com"
] | abhdutta3981@gmail.com |
ce47c9cfbe420984576c0943c92fb9ce7461b268 | 0ce7c60f26daaf62ef4569fb654c0f5722317f2d | /src/labor1/vorbeitung/bestOf/Intersection.java | 890ce99693c72cebaa565efbca1535fbada97847 | [] | no_license | llehman1/Algo | 2552237da4ed702e31b669d149c4a5faa8e8fe12 | 434b369f17e8ebd1db5c183cb2eecd7aa67dab18 | refs/heads/master | 2020-03-31T10:32:23.309744 | 2019-01-20T09:50:55 | 2019-01-20T09:50:55 | 152,138,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,655 | java | package labor1.vorbeitung.bestOf;
public class Intersection implements IComparsionPeople {
private ISort sort;
public Intersection(ISort sort) {
super();
this.sort = sort;
}
@Override
public void findSuspects() {
String[] result = null;
this.sort.sortStart();
String[][] peopleArray = (String[][]) this.sort.getNames();
try {
result = getIntersection(peopleArray[0], peopleArray[1]);
if (peopleArray.length > 2) {
for (int index = 2; index < peopleArray.length; index++) {
result = getIntersection(result, peopleArray[index]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
this.toStringName(result);
}
public String[] getIntersection(String[] first, String[] second) throws Exception {
String[] result;
if (first == null || second == null) {
throw new Exception("in the two-dimensional-Array attribute peopleAray is a String Array NULL : "
+ this.sort.toString());
}
if (first.length > second.length) {
result = new String[second.length];
} else {
result = new String[first.length];
}
int indexResult = 0;
for (String name : first) {
for (String name2 : second) {
if (name == name2) {
result[indexResult] = name;
indexResult++;
}
}
}
return result;
}
private void toStringName(String[] name) {
String stringName = "Name der Verdächtigen: ";
if (name[0] == null) {
stringName += "keine Schnittmenge gefunden";
} else {
stringName += name[0];
for (int index = 1; name.length > index; index++) {
if (name[index] != null) {
stringName += ", " + name[index];
}
}
}
System.out.println(stringName);
}
}
| [
"llehman1@stud.hs-offenburg.de"
] | llehman1@stud.hs-offenburg.de |
5e6a729bb13c7cd97e2300709db2257d504b9fa8 | b385bd957858c6f9c53d3fe036c5adbe834ef7fc | /src/TreciaPaskaita/MyMainApp12.java | 1d572d5a05ac064a7c725f451df9e798c70890f8 | [] | no_license | AndrMint/JAVA_KURSAI | b23bf78408d1087fd91973669606c03a3936c6d3 | 744ac2e018189169e7b3cefccbb2635cabb6a637 | refs/heads/master | 2021-01-25T07:48:56.829425 | 2017-06-14T18:38:43 | 2017-06-14T18:38:43 | 93,650,780 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 757 | java | package TreciaPaskaita;
import java.util.Arrays;
public class MyMainApp12 {
public static void main(String[] args) {
int[] mas = {12, 4, 65, 7, 12, 56, 3};
System.out.println(getMaxNumber(mas));
System.out.println(getMaxNumb2(mas));
System.out.println(getMinNumber(mas));
}
private static int getMaxNumber(int[] mas) {
int temp = 0;
for (Integer numb : mas) {
if (numb > temp) {
temp = numb;
}
}
return 0;
}
private static int getMaxNumb2(int[] mas){
Arrays.sort(mas);
return mas[mas.length - 1];
}
private static int getMinNumber(int[] mas){
Arrays.sort(mas);
return mas[0];
}
}
| [
"dileta.darbinis@gmail.com"
] | dileta.darbinis@gmail.com |
e4530e0f6e8ad85795b4fc76bacdebcd8f3c7858 | acc926907d32e70d0707306cccd3bfd8b2ddb9e0 | /RocketMultimeterAndOscilloscope/app/src/main/java/com/example/saik/rocketmultimeterandoscilloscope/VoltmeterActivity.java | 34b92f625a72762306f5979aba58a6ef7885327e | [] | no_license | mattdrag/Voltmeter | 0968c73fedd0cd20f0bf78fc2210f7576f913b27 | cd369f0c3387c9db934eeb3f59ac6246ca978d85 | refs/heads/master | 2020-03-18T14:56:45.411034 | 2018-05-25T15:52:54 | 2018-05-25T15:52:54 | 134,876,803 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,887 | java | package com.example.saik.rocketmultimeterandoscilloscope;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import java.text.DecimalFormat;
import static com.example.saik.rocketmultimeterandoscilloscope.MainActivity.RECEIVE_JSON;
public class VoltmeterActivity extends AppCompatActivity {
int voltDataBT;
TextView display;
boolean isVoltmeterOn = true;
Handler handler;
private LineGraphSeries<DataPoint> series;
private float lastX = 0;
private static final String TAG = "rocket";
BTService btService;
boolean isBound = false;
BtDataListener btDataListener = null;
private static String incomingData = "";
LocalBroadcastManager broadcastManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_voltmeter);
display = (TextView) findViewById(R.id.voltmeter);
voltDataBT = 0;
display.setText(new DecimalFormat("##.##").format(calculateVoltageValue()) + " V");
final Button voltTog = (Button) findViewById(R.id.ampmeterButton);
voltTog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isVoltmeterOn){
isVoltmeterOn = false;
voltTog.setText("Resume");
}
else{
isVoltmeterOn = true;
voltTog.setText("Pause");
}
}
});
final Runnable updater = new Runnable() {
@Override
public void run() {
if (isVoltmeterOn) {
display.setText(new DecimalFormat("##.##").format(calculateVoltageValue()) + " V");
addEntry();
handler.postDelayed(this, 100); //100ms delay
}
else {
handler.postDelayed(this, 100); //100ms delay
}
}
};
handler.post(updater);
//setup graph
// we get graph view instance
GraphView graph = (GraphView) findViewById(R.id.ampmeter);
// data
series = new LineGraphSeries<>();
graph.addSeries(series);
//style
// styling series
series.setTitle("Oscilloscope");
series.setColor(Color.YELLOW);
series.setThickness(2);
// customize a little bit viewport
Viewport viewport = graph.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setMinY(0);
viewport.setMaxY(6);
viewport.setScrollable(true);
viewport.setXAxisBoundsManual(true);
viewport.setMinX(0);
viewport.setMaxX(10);
graph.getGridLabelRenderer().setGridColor(Color.WHITE);
graph.getGridLabelRenderer().setVerticalAxisTitle("Voltage");
graph.getGridLabelRenderer().setVerticalAxisTitleColor(Color.WHITE);
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.WHITE);
graph.getGridLabelRenderer().setHorizontalAxisTitle("Time");
graph.getGridLabelRenderer().setHorizontalAxisTitleColor(Color.WHITE);
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.WHITE);
}
@Override
protected void onPause() {
super.onPause();
tryUnregisteringReceiver();
btDataListener.cancel(true);
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "MenuActivity:onResume: Binding Service, Registering Receiver");
bindServiceAndRegisterReceiver();
btDataListener = new BtDataListener();
btDataListener.execute();
}
public void onBackPressed()
{
Log.d(TAG, "MenuActivity: onBackPressed: Go back to previous activity since back button is pressed.");
cleanup();
btService.sendBtMessage(BTService.BtMessageOut.BT_MESSAGE_OUT_EXIT.getValue());
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "VoltmeterActivity: onDestroy: calling cleanup");
cleanup();
}
private void cleanup()
{
tryUnregisteringReceiver();
if(btDataListener != null)
{
btDataListener.cancel(true);
}
}
//For graphing points
private void addEntry() {
if (lastX < 10.0){
series.appendData(new DataPoint(lastX, calculateVoltageValue()), false, 10000); // we can store 10000 values at a time
}
else{
series.appendData(new DataPoint(lastX, calculateVoltageValue()), true, 10000); // we can store 10000 values at a time
}
lastX+= 0.1;
}
private double calculateVoltageValue(){
if (voltDataBT !=0){
return voltDataBT/204.8;
}
return 0;
}
//-----------------------------------------------------------------------------//
//-------------Broadcast receiver and service binder stuff---------------------//
//-----------------------------------------------------------------------------//
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
Log.d(TAG, "remoteControlBubbleWall: mServiceConnection: onServiceConnected");
btService = ((BTService.MyLocalBinder) service).getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d(TAG, "remoteControlBubbleWall: mServiceConnection: onServiceDisconnected");
btService = null;
isBound = false;
}
};
private class BtDataListener extends AsyncTask<Void, Void, Void> {
String completeMessage = "";
String startSymbol = "*";
String endSymbol = "|";
@Override
protected Void doInBackground(Void... devices)
{
while(!isCancelled())
{
if(btService != null)
{
incomingData += btService.checkIncomingBtData();
int start = incomingData.indexOf(startSymbol);
int end = incomingData.indexOf(endSymbol);
int extraStartSymbol = incomingData.substring(start+1, incomingData.length()).indexOf(startSymbol);
if(start == -1 && end != -1)
{
incomingData = incomingData.substring(end + 1, incomingData.length());
}
else if(start != -1 && end != -1 && start > end)
{
incomingData = incomingData.substring(start, incomingData.length());
}
else if(start != -1 && end != -1 && (extraStartSymbol != -1 && extraStartSymbol < end))
{
incomingData = incomingData.substring(extraStartSymbol + 1, incomingData.length());
}
else if(start != -1 && end != -1)
{
completeMessage = incomingData.substring(start+1,end);
incomingData = incomingData.substring(end + 1,incomingData.length());
}
if(!completeMessage.equals("") && !completeMessage.contains("$") && !completeMessage.contains(","))
{
//Log.d(TAG, "MenuActivity: BtDataListener: Received data messages " + voltDataBT);
voltDataBT = Integer.parseInt(completeMessage);
completeMessage = "";
}
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
private final BroadcastReceiver btBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(RECEIVE_JSON)) {
String serviceJsonString = intent.getStringExtra("btConnectionStatusUpdate");
if(serviceJsonString.equals("ConnectionLost")) {
Log.d(TAG, "MenuActivity: btBroadcastReceiver: We lost connection with BT");
Toast.makeText(getApplicationContext(), "Connection with BT was lost", Toast.LENGTH_LONG).show();
cleanup();
//Restarts the application
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
}
};
void tryUnregisteringReceiver() {
try {
unregisterReceiver(btBroadcastReceiver);
}
catch(IllegalArgumentException e) {
Log.e(TAG, "Receiver was already unregistered");
}
if(isBound){
unbindService(mServiceConnection);
}
isBound = false;
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(RECEIVE_JSON);
return intentFilter;
}
void bindServiceAndRegisterReceiver() {
Intent gattServiceIntent = new Intent(VoltmeterActivity.this, BTService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
registerReceiver(btBroadcastReceiver, makeGattUpdateIntentFilter());
broadcastManager = LocalBroadcastManager.getInstance(this);
broadcastManager.registerReceiver(btBroadcastReceiver, makeGattUpdateIntentFilter());
}
} | [
"matthewdragotto@gmail.com"
] | matthewdragotto@gmail.com |
f5963f3e1eb3615038ece333948aa82c5d6300a2 | dbda4749ad2b35bf98d1adeedebab0ab98010e88 | /app/src/main/java/com/greattone/greattone/Listener/BaseUiListener.java | c20ed0bf306e3db3077c709ca400696e5217e5f7 | [] | no_license | makaifeng/greattone2 | b7d771c50b2466e7718b4194dee952a7a3325170 | 7eddff6be1007d9264813e920ba46780a9bac59f | refs/heads/master | 2020-12-24T10:03:40.334376 | 2017-04-26T06:29:25 | 2017-04-26T06:29:25 | 73,248,461 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 903 | java | package com.greattone.greattone.Listener;
import org.json.JSONObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
public class BaseUiListener implements IUiListener {
@Override
public void onComplete(Object response) {
if (null == response) {
//"返回为空", "登录失败"
return;
}
JSONObject jsonResponse = (JSONObject) response;
if (null != jsonResponse && jsonResponse.length() == 0) {
//"返回为空", "登录失败"
return;
}
//登录成功
doComplete((JSONObject)response);
}
protected void doComplete(JSONObject values) {
}
@Override
public void onError(UiError e) {
// LogUtil.e("onError==>code:" + e.errorCode + ", msg:"
// + e.errorMessage + ", detail:" + e.errorDetail);
}
@Override
public void onCancel() {
// LogUtil.e("onCancel==>");
}
}
| [
"707584319@qq.com"
] | 707584319@qq.com |
5cf54e03539d397157284c047c10047ab1ce1931 | 1ce518b09521578e26e79a1beef350e7485ced8c | /source/app/src/main/java/com/google/android/gms/internal/w.java | b929aca0feb9afd5e8e2b80f666ee8a749a5704c | [] | no_license | yash2710/AndroidStudioProjects | 7180eb25e0f83d3f14db2713cd46cd89e927db20 | e8ba4f5c00664f9084f6154f69f314c374551e51 | refs/heads/master | 2021-01-10T01:15:07.615329 | 2016-04-03T09:19:01 | 2016-04-03T09:19:01 | 55,338,306 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,666 | java | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.internal;
import android.os.Parcel;
import com.google.android.gms.common.internal.safeparcel.a;
import com.google.android.gms.common.internal.safeparcel.b;
// Referenced classes of package com.google.android.gms.internal:
// v
public class w
implements android.os.Parcelable.Creator
{
public w()
{
}
static void a(v v1, Parcel parcel, int i)
{
int j = com.google.android.gms.common.internal.safeparcel.b.C(parcel);
com.google.android.gms.common.internal.safeparcel.b.c(parcel, 1, v1.versionCode);
com.google.android.gms.common.internal.safeparcel.b.a(parcel, 2, v1.lb);
com.google.android.gms.common.internal.safeparcel.b.a(parcel, 3, v1.ld);
com.google.android.gms.common.internal.safeparcel.b.G(parcel, j);
}
public v a(Parcel parcel)
{
boolean flag = false;
int i = com.google.android.gms.common.internal.safeparcel.a.B(parcel);
boolean flag1 = false;
int j = 0;
do
{
if (parcel.dataPosition() < i)
{
int k = com.google.android.gms.common.internal.safeparcel.a.A(parcel);
switch (com.google.android.gms.common.internal.safeparcel.a.ar(k))
{
default:
com.google.android.gms.common.internal.safeparcel.a.b(parcel, k);
break;
case 1: // '\001'
j = com.google.android.gms.common.internal.safeparcel.a.g(parcel, k);
break;
case 2: // '\002'
flag1 = com.google.android.gms.common.internal.safeparcel.a.c(parcel, k);
break;
case 3: // '\003'
flag = com.google.android.gms.common.internal.safeparcel.a.c(parcel, k);
break;
}
} else
if (parcel.dataPosition() != i)
{
throw new com.google.android.gms.common.internal.safeparcel.a.a((new StringBuilder("Overread allowed size end=")).append(i).toString(), parcel);
} else
{
return new v(j, flag1, flag);
}
} while (true);
}
public v[] b(int i)
{
return new v[i];
}
public Object createFromParcel(Parcel parcel)
{
return a(parcel);
}
public Object[] newArray(int i)
{
return b(i);
}
}
| [
"13bce123@nirmauni.ac.in"
] | 13bce123@nirmauni.ac.in |
6b471574acdae1331836d0f8ea58138d6c079a7b | 0b09691e3cffb2bcf0cc733b4dd20693814733ff | /src/com/domain/Admins.java | b9a32038afa863e877712457c766f8f7709edfe0 | [] | no_license | BruceZhang54110/shop | 7248c404783d8255f18dbdfd0edfce5b5583b367 | 09a2db194c848274b885c4fa85f571a579bd33b8 | refs/heads/master | 2022-04-27T09:41:09.501001 | 2022-03-29T02:22:35 | 2022-03-29T02:22:35 | 84,023,285 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 493 | java | package com.domain;
public class Admins {
private String adminName;
private String adminPass;
private int id;
public Admins() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAdminName() {
return adminPass;
}
public void setAdminName(String adminName) {
adminPass = adminName;
}
public String getAdminPass() {
return adminName;
}
public void setAdminPass(String adminPass) {
adminName = adminPass;
}
}
| [
"zhw54110@163.com"
] | zhw54110@163.com |
a4e06f55456a7bca7b3daccd23e1a1a5d476fd67 | 3ec740784b754780b6083fc6cde6d87904ebc8ab | /tm-tool/textmapper/src/org/textmapper/tool/parser/ast/TmaBracketsDirective.java | e51ea94a5820931de9bde9afc3799bd9483f6de7 | [
"Apache-2.0"
] | permissive | takamori/textmapper | b83da7f30c43868e16de18aea7e21e456ceb3803 | 3c9ec01f17db9f9e3d3914c984f8ccd4496913fb | refs/heads/master | 2020-04-02T10:03:39.409821 | 2018-10-23T13:18:03 | 2018-10-23T13:18:03 | 154,322,486 | 0 | 0 | null | 2018-10-23T12:15:59 | 2018-10-23T12:15:58 | null | UTF-8 | Java | false | false | 1,373 | java | /**
* Copyright 2002-2017 Evgeny Gryaznov
*
* 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.textmapper.tool.parser.ast;
import org.textmapper.tool.parser.TMTree.TextSource;
public class TmaBracketsDirective extends TmaNode implements ITmaLexerPart {
private final TmaSymref opening;
private final TmaSymref closing;
public TmaBracketsDirective(TmaSymref opening, TmaSymref closing, TextSource source, int line, int offset, int endoffset) {
super(source, line, offset, endoffset);
this.opening = opening;
this.closing = closing;
}
public TmaSymref getOpening() {
return opening;
}
public TmaSymref getClosing() {
return closing;
}
@Override
public void accept(TmaVisitor v) {
if (!v.visit(this)) {
return;
}
if (opening != null) {
opening.accept(v);
}
if (closing != null) {
closing.accept(v);
}
}
}
| [
"egryaznov@gmail.com"
] | egryaznov@gmail.com |
d6882dde0232487943c3cf5ba6b20e7ff1913fe1 | c770c49e2a91260abad58fd451d9524b790d7b20 | /sentinel-agent/sentinel-agent-client/src/main/java/com/alibaba/acm/shaded/org/codehaus/jackson/map/jsontype/impl/StdTypeResolverBuilder.java | 10caf478321090f64fdeba033e84c5dadd619fb2 | [
"Apache-2.0"
] | permissive | ddreaml/Sentinel-ali | d45e941e537d26628151f9c87dccdca16ef329a7 | 33721158794f9a713057abccbb4f4b89dfaaa644 | refs/heads/master | 2023-04-24T13:20:07.505656 | 2019-10-21T11:24:43 | 2019-10-21T11:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,978 | java | package com.alibaba.acm.shaded.org.codehaus.jackson.map.jsontype.impl;
import java.util.Collection;
import com.alibaba.acm.shaded.org.codehaus.jackson.annotate.JsonTypeInfo;
import com.alibaba.acm.shaded.org.codehaus.jackson.map.*;
import com.alibaba.acm.shaded.org.codehaus.jackson.map.jsontype.NamedType;
import com.alibaba.acm.shaded.org.codehaus.jackson.map.jsontype.TypeIdResolver;
import com.alibaba.acm.shaded.org.codehaus.jackson.map.jsontype.TypeResolverBuilder;
import com.alibaba.acm.shaded.org.codehaus.jackson.type.JavaType;
/**
* Default {@link TypeResolverBuilder} implementation.
*
* @author tatu
* @since 1.5
*/
public class StdTypeResolverBuilder
implements TypeResolverBuilder<StdTypeResolverBuilder>
{
// Configuration settings:
protected JsonTypeInfo.Id _idType;
protected JsonTypeInfo.As _includeAs;
protected String _typeProperty;
/**
* @since 1.9
*/
protected Class<?> _defaultImpl;
// Objects
protected TypeIdResolver _customIdResolver;
/*
/**********************************************************
/* Accessors
/**********************************************************
*/
@Override
public Class<?> getDefaultImpl() {
return _defaultImpl;
}
/*
/**********************************************************
/* Construction, initialization, actual building
/**********************************************************
*/
public StdTypeResolverBuilder() { }
public static StdTypeResolverBuilder noTypeInfoBuilder() {
return new StdTypeResolverBuilder().init(JsonTypeInfo.Id.NONE, null);
}
@Override
public StdTypeResolverBuilder init(JsonTypeInfo.Id idType, TypeIdResolver idRes)
{
// sanity checks
if (idType == null) {
throw new IllegalArgumentException("idType can not be null");
}
_idType = idType;
_customIdResolver = idRes;
// Let's also initialize property name as per idType default
_typeProperty = idType.getDefaultPropertyName();
return this;
}
@Override
public TypeSerializer buildTypeSerializer(SerializationConfig config,
JavaType baseType, Collection<NamedType> subtypes, BeanProperty property)
{
if (_idType == JsonTypeInfo.Id.NONE) {
return null;
}
TypeIdResolver idRes = idResolver(config, baseType, subtypes, true, false);
switch (_includeAs) {
case WRAPPER_ARRAY:
return new AsArrayTypeSerializer(idRes, property);
case PROPERTY:
return new AsPropertyTypeSerializer(idRes, property, _typeProperty);
case WRAPPER_OBJECT:
return new AsWrapperTypeSerializer(idRes, property);
case EXTERNAL_PROPERTY:
return new AsExternalTypeSerializer(idRes, property, _typeProperty);
}
throw new IllegalStateException("Do not know how to construct standard type serializer for inclusion type: "+_includeAs);
}
@Override
public TypeDeserializer buildTypeDeserializer(DeserializationConfig config,
JavaType baseType, Collection<NamedType> subtypes, BeanProperty property)
{
if (_idType == JsonTypeInfo.Id.NONE) {
return null;
}
TypeIdResolver idRes = idResolver(config, baseType, subtypes, false, true);
// First, method for converting type info to type id:
switch (_includeAs) {
case WRAPPER_ARRAY:
return new AsArrayTypeDeserializer(baseType, idRes, property, _defaultImpl);
case PROPERTY:
return new AsPropertyTypeDeserializer(baseType, idRes, property,
_defaultImpl, _typeProperty);
case WRAPPER_OBJECT:
return new AsWrapperTypeDeserializer(baseType, idRes, property, _defaultImpl);
case EXTERNAL_PROPERTY:
return new AsExternalTypeDeserializer(baseType, idRes, property,
_defaultImpl, _typeProperty);
}
throw new IllegalStateException("Do not know how to construct standard type serializer for inclusion type: "+_includeAs);
}
/*
/**********************************************************
/* Construction, configuration
/**********************************************************
*/
@Override
public StdTypeResolverBuilder inclusion(JsonTypeInfo.As includeAs) {
if (includeAs == null) {
throw new IllegalArgumentException("includeAs can not be null");
}
_includeAs = includeAs;
return this;
}
/**
* Method for constructing an instance with specified type property name
* (property name to use for type id when using "as-property" inclusion).
*/
@Override
public StdTypeResolverBuilder typeProperty(String typeIdPropName)
{
// ok to have null/empty; will restore to use defaults
if (typeIdPropName == null || typeIdPropName.length() == 0) {
typeIdPropName = _idType.getDefaultPropertyName();
}
_typeProperty = typeIdPropName;
return this;
}
@Override
public StdTypeResolverBuilder defaultImpl(Class<?> defaultImpl)
{
_defaultImpl = defaultImpl;
return this;
}
/*
/**********************************************************
/* Accessors
/**********************************************************
*/
public String getTypeProperty() { return _typeProperty; }
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
/**
* Helper method that will either return configured custom
* type id resolver, or construct a standard resolver
* given configuration.
*/
protected TypeIdResolver idResolver(MapperConfig<?> config,
JavaType baseType, Collection<NamedType> subtypes,
boolean forSer, boolean forDeser)
{
// Custom id resolver?
if (_customIdResolver != null) {
return _customIdResolver;
}
if (_idType == null) {
throw new IllegalStateException("Can not build, 'init()' not yet called");
}
switch (_idType) {
case CLASS:
return new ClassNameIdResolver(baseType, config.getTypeFactory());
case MINIMAL_CLASS:
return new MinimalClassNameIdResolver(baseType, config.getTypeFactory());
case NAME:
return TypeNameIdResolver.construct(config, baseType, subtypes, forSer, forDeser);
case NONE: // hmmh. should never get this far with 'none'
return null;
case CUSTOM: // need custom resolver...
}
throw new IllegalStateException("Do not know how to construct standard type id resolver for idType: "+_idType);
}
}
| [
"418294249@qq.com"
] | 418294249@qq.com |
d86b86c9717b524015830921778df9d3dd1a7d3e | 9329071c7a74c2bf206b7bdf7edd984748d205b3 | /src/main/java/io/sporkpgm/module/builder/BuilderContext.java | b655d927626420062f0e318add4d6ae9aa18d412 | [] | no_license | simba3rcks/SporkPGM | c102e0ee55dcab5ef59360b79d3e9caf39029942 | a32f017f579967e9ae66e11e2edf614bcce0d700 | refs/heads/master | 2021-01-18T06:05:10.373516 | 2014-06-10T21:49:24 | 2014-06-10T21:49:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,780 | java | package io.sporkpgm.module.builder;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import io.sporkpgm.Spork;
import io.sporkpgm.map.SporkLoader;
import io.sporkpgm.map.SporkMap;
import io.sporkpgm.match.Match;
import io.sporkpgm.util.ClassUtils;
import io.sporkpgm.util.Log;
import org.jdom2.Document;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class BuilderContext {
private Document document;
private SporkLoader loader;
private SporkMap map;
private Match match;
public BuilderContext(Object... fields) {
Preconditions.checkArgument(fields.length > 0, "Contexts require at least 1 field");
List<Object> passed = new ArrayList<>();
for(Object field : fields) {
passed.add(field);
if(field instanceof Document) {
document = (Document) field;
continue;
} else if(field instanceof SporkLoader) {
loader = (SporkLoader) field;
continue;
} else if(field instanceof SporkMap) {
map = (SporkMap) field;
continue;
} else if(field instanceof Match) {
match = (Match) field;
continue;
}
passed.remove(field);
}
Preconditions.checkState(passed.size() > 0, "Contexts require at acceptable least 1 field");
}
public Document getDocument() {
return document;
}
public SporkLoader getLoader() {
return loader;
}
public SporkMap getMap() {
return map;
}
public Match getMatch() {
return match;
}
public boolean all(String... fields) {
return all(Lists.newArrayList(fields));
}
public boolean all(List<String> fields) {
for(String string : fields) {
try {
Field field = getClass().getDeclaredField(string);
field.setAccessible(true);
if(!has(field.getName())) {
return false;
}
} catch(Exception e) {
if(Spork.isDebug()) {
e.printStackTrace();
}
return false;
}
}
return true;
}
public boolean only(String... fields) {
return only(Lists.newArrayList(fields));
}
public boolean only(List<String> fields) {
List<String> available = new ArrayList<>();
for(Field field : getClass().getDeclaredFields()) {
if(has(field.getName())) {
available.add(field.getName());
}
}
// Log.debug("Checking " + fields + " against " + available);
if(fields.size() != available.size()) {
return false;
}
for(String string : available) {
if(!fields.contains(string)) {
return false;
}
}
return true;
}
public boolean has(String field) {
switch(field) {
case "document": return document != null;
case "loader": return loader != null;
case "map": return map != null;
case "match": return match != null;
}
return false;
}
@Override
public String toString() {
return ClassUtils.build(this);
}
}
| [
"harry.fox.ic@icloud.com"
] | harry.fox.ic@icloud.com |
6927bb365e9aa789f4a5ff206c6862d4a014bebc | 77ed4f7dc2289ced4ebb7e77b46b92c926fddbc3 | /app/src/main/java/com/test/gambit/fragments/GamesFragment.java | d516572dfb43da4a0ec2674379bf8f77feeb3a4f | [] | no_license | sunilparmar04/GameBitTask | d8a6732790c65865b67187268ec8585c851e9b0c | 8115a626632e3666756f03b1135bfbc3dfc24a4d | refs/heads/master | 2020-05-17T15:30:23.765978 | 2019-04-28T04:35:58 | 2019-04-28T04:35:58 | 183,792,485 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,562 | java | package com.test.gambit.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.test.gambit.R;
import com.test.gambit.model.GameResponse;
import com.test.gambit.utils.AppConstants;
import com.test.gambit.utils.CommonUtils;
import com.test.gambit.utils.NetworkUtils;
import com.test.gambit.utils.RecyclerViewEndlessScrollListener;
import com.test.gambit.views.HomeActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import in.myvolley.NetworkCall;
import in.myvolley.interfaces.NetworkCallback;
/**
* Created by sunilparmar on 4/27/2019.
*/
public class GamesFragment extends Fragment {
private View mView;
private RecyclerView mGameRecycleView;
private GameAdapter mAdapter;
private ArrayList<GameResponse.Data> gameArrayList = new ArrayList<>();
private int mPage = 0;
private RecyclerViewEndlessScrollListener recyclerViewEndlessScrollListener;
private LinearLayoutManager mLayoutManager;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_games, container, false);
initViews();
gameArrayList.clear();
initAdapter();
getGame();
initListener();
return mView;
}
private void initViews() {
mLayoutManager=new LinearLayoutManager(getActivity());
mGameRecycleView = mView.findViewById(R.id.gameRecyclerView);
}
private void initListener() {
recyclerViewEndlessScrollListener = new RecyclerViewEndlessScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
Log.d("scroll_listener", "load_more:");
if (!NetworkUtils.isNetworkConnected(getActivity())) {
CommonUtils.getInstance().showRedToast(getString(R.string.no_internet), getActivity(), 112);
return;
}
++mPage;
getGame();
}
};
mGameRecycleView.addOnScrollListener(recyclerViewEndlessScrollListener);
}
private void initAdapter() {
mAdapter = new GameAdapter();
mGameRecycleView.setLayoutManager(mLayoutManager);
mGameRecycleView.setAdapter(mAdapter);
}
private void getGame() {
if (!NetworkUtils.isNetworkConnected(getActivity())) {
CommonUtils.getInstance().showRedToast(getString(R.string.no_internet), getActivity(), 112);
return;
}
NetworkCallback<GameResponse> networkCallback = new NetworkCallback<GameResponse>() {
@Override
public void onSuccess(GameResponse response) {
parseData(response);
}
@Override
public void onError(VolleyError error) {
}
};
Map<String, String> params = new HashMap<>();
params.put(AppConstants.PARAMS_PAGE, "" + mPage);
NetworkCall<GameResponse> networkCall = new NetworkCall<>(AppConstants.GAMES_URL, new HashMap<String, String>(), Request.Method.GET, networkCallback, GameResponse.class);
if (mPage>0) {
networkCall.initiateCall("Getting games...", getActivity().getSupportFragmentManager());
}else {
networkCall.initiateCall();
}
}
private void parseData(GameResponse response) {
if (response.getData().size() > 0) {
gameArrayList.addAll(response.getData());
mAdapter.notifyDataSetChanged();
updateTabText();
}
}
class GameAdapter extends RecyclerView.Adapter<GameAdapter.MyViewHolder> {
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView homeTeamAbbreviationTextView, visitorTeamAbbreviationTextView,
homeTeamFullNameTextView, visitorTeamFullNameíTextView;
public MyViewHolder(View view) {
super(view);
homeTeamAbbreviationTextView = view.findViewById(R.id.homeTeamAbbreviationTextView);
visitorTeamAbbreviationTextView = view.findViewById(R.id.visitorTeamAbbreviationTextView);
homeTeamFullNameTextView = view.findViewById(R.id.homeTeamFullNameTextView);
visitorTeamFullNameíTextView = view.findViewById(R.id.visitorTeamFullNameíTextView);
}
}
public GameAdapter() {
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_game, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
GameResponse.Data dataModel = gameArrayList.get(position);
holder.homeTeamAbbreviationTextView.setText(dataModel.getHome_team().getAbbreviation());
holder.visitorTeamAbbreviationTextView.setText(dataModel.getVisitor_team().getAbbreviation());
holder.homeTeamFullNameTextView.setText(dataModel.getHome_team().getName());
holder.visitorTeamFullNameíTextView.setText(dataModel.getVisitor_team().getName());
}
@Override
public int getItemCount() {
return gameArrayList.size();
}
}
public void updateTabText() {
try {
View view = ((HomeActivity) getActivity()).mTabLayout.getTabAt(1).getCustomView();
View badgeContainer = view.findViewById(R.id.badgeCotainer);
TextView countTextView = view.findViewById(R.id.badge);
if (gameArrayList.size() > 0) {
badgeContainer.setVisibility(View.VISIBLE);
countTextView.setText(gameArrayList.size() + "");
} else {
badgeContainer.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"parmarsunil09@gmail.com"
] | parmarsunil09@gmail.com |
edd38e77c03793019c7208744f979fbb44d659c3 | 52f1ac7e03aa4dcbf44dda909652450cbf3cf961 | /activivemq-demo-parent/active-mq-demo1-consumer/src/main/java/com/demo/activemq/JMSQueueProducer.java | d4ee934b8e380233137c4cfd9b754e65c807cb24 | [] | no_license | wei2qiang2/gupao-demo-project | c97246ead3ec5564d43f942c8136ecabf35dfdce | 07af017ef606c0602e7ca315994784306ac23264 | refs/heads/master | 2022-12-25T06:32:32.318160 | 2020-01-17T02:00:22 | 2020-01-17T02:00:22 | 234,448,005 | 0 | 2 | null | 2022-12-16T08:58:36 | 2020-01-17T01:46:40 | Java | UTF-8 | Java | false | false | 690 | java | package com.demo.activemq;
import com.demo.active.common.ConnectionUtils;
import javax.jms.*;
/**
* 消息发送端
*/
public class JMSQueueProducer {
public static void main(String[] args) throws JMSException {
Session session = ConnectionUtils.getSession();
//创建目的地
Destination queue = session.createQueue("first-queue");
//创建发送者
MessageProducer producer = session.createProducer(queue);
//创建消息
TextMessage textMessage = session.createTextMessage("hello , this is first producer");
//发送
producer.send(textMessage);
session.commit();
session.close();
}
}
| [
"wei.qiang@successinfo.com.cn"
] | wei.qiang@successinfo.com.cn |
77c80751516c4da20b3557f7fb6510a8b2f5440c | b98e3c9cc6566656d3eca425b5b219cf98e58be9 | /src/repository/TeacherRepository.java | 7790b97474a62f4947ce045830b615a288b67c66 | [] | no_license | danielsociu/PAO_project | d75c2d9456cead8e5a2f5569996fbe962ea64f9f | 96cfdc1d957d7e138c5a3e2d89e13a73fcc90c92 | refs/heads/master | 2023-05-03T03:27:49.370287 | 2021-05-26T05:59:40 | 2021-05-26T05:59:40 | 352,908,934 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,212 | java | package repository;
import config.DatabaseConnection;
import models.*;
import models.Class;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class TeacherRepository {
public void addTeacher(School school, Teacher teacher) {
String sql = "insert into teacher (pid_teacher, id_school, first_name, last_name, birth_date) " +
"values (?, ?, ?, ?, ?)";
try (PreparedStatement statement = DatabaseConnection.getConnection().prepareStatement(
sql,
Statement.RETURN_GENERATED_KEYS
)) {
statement.setString(1, teacher.getPid());
statement.setInt(2, school.getIdSchool());
statement.setString(3, teacher.getFirstName());
statement.setString(4, teacher.getLastName());
statement.setDate(5, new java.sql.Date(teacher.getBirthDate().getTime()));
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void removeTeacher(School school, Teacher teacher) {
String sql = "delete from teacher where pid_teacher = ? and id_school = ?";
try (PreparedStatement statement = DatabaseConnection.getConnection().prepareStatement(sql)) {
statement.setString(1, teacher.getPid());
statement.setInt(2, school.getIdSchool());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Teacher> getTeachers(School school) {
String sql = "select * from teacher where id_school = ?";
try (PreparedStatement statement = DatabaseConnection.getConnection().prepareStatement(sql)) {
statement.setInt(1, school.getIdSchool());
ResultSet rs = statement.executeQuery();
ArrayList<Teacher> teachers = new ArrayList<>();
while (rs.next()) {
teachers.add(new Teacher(
rs.getString("first_name"),
rs.getString("last_name"),
rs.getDate("birth_date"),
rs.getString("pid_teacher")
));
System.out.println(teachers.get(teachers.size() -1));
}
return teachers;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public void getTeacherClasses(Teacher teacher, List<models.Class> classes, List<Subject> subjects) {
String sqlQuery = "select * from class_subjects where pid_teacher = ?";
try (PreparedStatement statementQuery = DatabaseConnection.getConnection().prepareStatement(
sqlQuery
)) {
statementQuery.setString(1, teacher.getPid());
ResultSet existentClasses = statementQuery.executeQuery();
while (existentClasses.next()) {
int idClass = existentClasses.getInt("id_class");
int idSubject = existentClasses.getInt("id_subject");
models.Class foundClass = null;
for (models.Class myClass: classes) {
if (myClass.getIdClass() == idClass) {
Set<Class> teacherClasses = teacher.getClasses();
foundClass = myClass;
teacherClasses.add(myClass);
break;
}
}
if (foundClass != null) {
for (Subject subject: subjects) {
if (subject.getIdSubject() == idSubject) {
HashMap<Subject, Teacher> classSubjects = foundClass.getSubjects();
classSubjects.put(subject, teacher);
foundClass.setSubjects(classSubjects);
break;
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// public void addTeacherClasses(Teacher teacher) {
// String sqlQuery = "select * from teacher_classes where pid_teacher = ?";
// String sqlAdd = "insert into teacher_classes (pid_teacher, id_class) " +
// "values (?, ?)";
// try (
// PreparedStatement statementQuery = DatabaseConnection.getConnection().prepareStatement(
// sqlQuery,
// ResultSet.TYPE_SCROLL_INSENSITIVE,
// ResultSet.CONCUR_READ_ONLY
// );
// PreparedStatement statementAdd = DatabaseConnection.getConnection().prepareStatement(sqlAdd)
// ) {
// statementQuery.setString(1, teacher.getPid());
// ResultSet existentClasses = statementQuery.executeQuery();
// for (models.Class myClass: teacher.getClasses()) {
// boolean ok = true;
// while (existentClasses.next()) {
// if (existentClasses.getInt("id_class") == myClass.getIdClass()) {
// existentClasses.beforeFirst();
// ok = false;
// break;
// }
// }
// if (ok) {
// statementAdd.setString(1, teacher.getPid());
// statementAdd.setInt(2, myClass.getIdClass());
// statementAdd.addBatch();
// }
// }
// statementAdd.executeUpdate();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
// public void addTeacherClass(Teacher teacher, models.Class myClass) {
// String sql = "insert into teacher_classes (pid_teacher, id_class) " +
// "values (?, ?)";
// try (PreparedStatement statement = DatabaseConnection.getConnection().prepareStatement(sql)) {
// statement.setString(1, teacher.getPid());
// statement.setInt(2, myClass.getIdClass());
// statement.executeUpdate();
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
}
| [
"danielsociu00@gmail.com"
] | danielsociu00@gmail.com |
5a0a3612313906f56e2ee21afb5f664c3284a574 | 6355770c6d883d1557c3047c4808172d52985f06 | /src/main/java/model/xml/ActivityCodeAssignment.java | 5099caca617df57209b8e0f107353831a741dbda | [] | no_license | bremlin/acda | 804f39e8a457a9fc56ddde47956015999b02ef55 | eda0e3e03e04780287068830698ecc181048610a | refs/heads/master | 2021-06-27T02:58:49.394379 | 2017-09-15T22:17:07 | 2017-09-15T22:17:07 | 103,706,006 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 661 | java | package model.xml;
import org.jdom2.Element;
public class ActivityCodeAssignment {
private int activityObjectId;
private int activityCodeObjectId;
public ActivityCodeAssignment(Element activityCodeAssignmentElement) {
this.activityObjectId = Integer.parseInt(activityCodeAssignmentElement.getChild(XMLTypes.ACTIVITY_ID).getText());
this.activityCodeObjectId = Integer.parseInt(activityCodeAssignmentElement.getChild(XMLTypes.ACTIVITY_CODE_ID).getText());
}
public int getActivityObjectId() {
return activityObjectId;
}
public int getActivityCodeObjectId() {
return activityCodeObjectId;
}
}
| [
"shmakov.s.s@gmail.com"
] | shmakov.s.s@gmail.com |
68de5011fcf688dcf759b4045cfe54c99baf1b98 | 092bf5027a510b29a52d593c8e1c89e4544d6ce3 | /jdbcDemo/src/main/java/com/hand/servlet/ShowServlet.java | 3f59c7f109355afcb8b12328bc129a8a42af0ba4 | [] | no_license | lijy163/Exam1 | 6c60eb85c6de564281f528e4b2d851ab79053ca7 | 079cec74e933af0a8d02647fdd9d3881fb2266ef | refs/heads/master | 2020-03-26T07:26:02.044129 | 2018-08-14T11:23:54 | 2018-08-14T11:23:54 | 144,654,200 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 958 | java | package com.hand.servlet;
import com.hand.dto.Admin;
import com.hand.dto.AdminDao;
import com.hand.pojo.addpojo;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class ShowServlet extends HttpServlet{ //显示全部数据
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
AdminDao dao = new AdminDao();
List<addpojo> list = dao.getAllAdmin();
req.setAttribute("list", list);
req.getRequestDispatcher("index.jsp").forward(req, resp);
}
} | [
"809578891@qq.com"
] | 809578891@qq.com |
8f41c56f4ef85b729a58253968d2d8a28ec06d44 | 426cc8f622d70656f951fa795d18e72a6485a438 | /src/main/java/spring/boot/webflu/ms/cuenta/banco/app/service/ProductoService.java | d2bfb4acdcde51da4ec0b563e408f86fcd330afa | [
"MIT"
] | permissive | jean-dep-tb/ms-cuenta-banco | dd0e2b74ca326906de8cb8d723b905ac19519107 | d43d6847767d287f80d8ada3d0888f6dc8c0c6b2 | refs/heads/master | 2020-12-22T00:31:31.683355 | 2020-02-06T20:56:24 | 2020-02-06T20:56:24 | 236,614,902 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 999 | java | package spring.boot.webflu.ms.cuenta.banco.app.service;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import spring.boot.webflu.ms.cuenta.banco.app.documents.CurrentAccount;
public interface ProductoService {
Flux<CurrentAccount> findAllProductoBanco();
Mono<CurrentAccount> findByIdProductoBanco(String id); //findByIdProducto
Mono<CurrentAccount> saveProductoBanco(CurrentAccount producto); //saveProducto
Flux<CurrentAccount> findAllProductoByDniCliente(String dniCliente);
//Flux<CurrentAccount> saveProductoList(List<CurrentAccount> producto);
Flux<CurrentAccount> saveProductoBancoCliente(CurrentAccount producto); //saveProductoList
Mono<CurrentAccount> listProdNumTarj(String num, String codigo_bancario);
Mono<CurrentAccount> retiro(Double monto, String numTarjeta, Double comision, String codigo_bancario);
Mono<CurrentAccount> depositos(Double monto, String numTarjeta, Double comision, String codigo_bancario);
}
| [
"59699335+jean-dep-tb@users.noreply.github.com"
] | 59699335+jean-dep-tb@users.noreply.github.com |
417d8a32bac01e7df41122e15e4cf03434d46132 | ed3ef5780a710db9ce02842f3fef0b6d2568fad1 | /java/com/grocery/form/ReportJsonMapper.java | 69d02f9cad8f275ef73ba6b07a369689d6ae3289 | [] | no_license | Gaurav8397/Grocery-Project | 090b95d3d990c64ec897dbba90ca34bfe2096aef | a43524bb5316741f45d99b0cde9559bfb76363eb | refs/heads/master | 2023-01-21T10:44:49.362753 | 2020-11-30T16:27:49 | 2020-11-30T16:27:49 | 316,992,230 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 302 | java | package com.grocery.form;
import java.util.List;
import com.grocery.entity.DailyReport1;
public class ReportJsonMapper {
List<DailyReport1> report;
public List<DailyReport1> getReport() {
return report;
}
public void setReport(List<DailyReport1> report) {
this.report = report;
}
}
| [
"60641185+Gaurav8397@users.noreply.github.com"
] | 60641185+Gaurav8397@users.noreply.github.com |
44f32eee4311203c84fcb308b325d3d0b58d3c45 | 20eb62855cb3962c2d36fda4377dfd47d82eb777 | /IntroClassJava/dataset/grade/bfad6d21d636def8e9e72910c3eb0815f5747669e3a60fb10c6f7f421082d18e548dcfc5d4717bb6da075c36f067b37858d11528ce796b3226ae33719c5007ce/001/mutations/84/grade_bfad6d21_001.java | e53b71c300aca2b62525cc1060003f37566511f4 | [] | no_license | ozzydong/CapGen | 356746618848065cce4e253e5d3c381baa85044a | 0ba0321b6b1191443276021f1997833342f02515 | refs/heads/master | 2023-03-18T20:12:02.923428 | 2020-08-21T03:08:28 | 2020-08-21T03:08:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,685 | java | package introclassJava;
class IntObj {
public int value;
public IntObj () {
} public IntObj (int i) {
value = i;
}
}
class FloatObj {
public float value;
public FloatObj () {
} public FloatObj (float i) {
value = i;
}
}
class LongObj {
public long value;
public LongObj () {
} public LongObj (long i) {
value = i;
}
}
class DoubleObj {
public double value;
public DoubleObj () {
} public DoubleObj (double i) {
value = i;
}
}
class CharObj {
public char value;
public CharObj () {
} public CharObj (char i) {
value = i;
}
}
public class grade_bfad6d21_001 {
public java.util.Scanner scanner;
public String output = "";
public static void main (String[]args) throws Exception {
grade_bfad6d21_001 mainClass = new grade_bfad6d21_001 ();
String output;
if (args.length > 0) {
mainClass.scanner = new java.util.Scanner (args[0]);
} else {
mainClass.scanner = new java.util.Scanner (System.in);
}
mainClass.exec ();
System.out.println (mainClass.output);
}
public void exec () throws Exception {
FloatObj thresha = new FloatObj (), threshb = new FloatObj (), threshc =
new FloatObj (), threshd = new FloatObj (), stuscore = new FloatObj ();
output +=
(String.format
("Enter thresholds for A, B, C, D\nin that order, decreasing percentages > "));
thresha.value = scanner.nextFloat ();
threshb.value = scanner.nextFloat ();
threshc.value = scanner.nextFloat ();
threshd.value = scanner.nextFloat ();
output +=
(String.format ("Thank you. Now enter student score (percent) >"));
stuscore.value = scanner.nextFloat ();
if (stuscore.value > thresha.value) {
output += (String.format ("Student has an A grade\n"));
}
if ((stuscore.value < thresha.value) && (stuscore.value >= threshb.value)) {
output += (String.format ("Student has an B grade\n"));
}
if ((stuscore.value < threshb.value) && (stuscore.value >= threshc.value)) {
output += (String.format ("Student has an C grade\n"));
}
if ((stuscore.value) < (threshc.value)) && ((stuscore.value) >= (threshd.value) && (stuscore.value >= threshd.value)) {
output += (String.format ("Student has an D grade\n"));
}
if (stuscore.value < threshd.value) {
output += (String.format ("Student has failed the course\n"));
}
if (true)
return;;
}
}
| [
"justinwm@163.com"
] | justinwm@163.com |
af529efaa3a306beab88d29f69e5c802fe0e2722 | 2f9acd75e2671e4908a80e163a562c7b85ccee8f | /src/test/java/net/kyou/pack/param/expr/endpoint/PlainIntegerExprTest.java | 8c2799b61275f22b8bbe4378dda9f39ce407c6cc | [] | no_license | stone014/kyou | 8346626632a065f9c104f3ed474b1754a79bd982 | c89121e8ccaf93818b913a252d1c4bfa007ea22f | refs/heads/master | 2020-12-24T13:53:28.728443 | 2012-06-22T04:20:14 | 2012-06-22T04:20:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,850 | java | /* Copyright - Apache License 2.0
*
* The project "kyou" is
* 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 net.kyou.pack.param.expr.endpoint;
import org.junit.Assert;
import org.junit.Test;
public class PlainIntegerExprTest {
@Test
public void test() {
try {
String expr = "1";
PlainIntegerExpr param = new PlainIntegerExpr(expr, null, null);
Assert.assertEquals(1L, param.__eval(null));
} finally {
}
try {
String expr = "-1";
PlainIntegerExpr param = new PlainIntegerExpr(expr, null, null);
Assert.assertEquals(-1L, param.__eval(null));
} finally {
}
try {
String expr = "1000000";
PlainIntegerExpr param = new PlainIntegerExpr(expr, null, null);
Assert.assertEquals(1000000L, param.__eval(null));
} finally {
}
}
@Test
public void testEx() {
try {
new PlainIntegerExpr("a", null, null);
Assert.fail();
} catch (NumberFormatException ex) {
}
try {
new PlainIntegerExpr("1111111111111111111111", null, null);
Assert.fail();
} catch (NumberFormatException ex) {
}
}
}
| [
"nuclearg@163.com"
] | nuclearg@163.com |
7a5b025c83af7b51d4a1450ec4c49f6ef9fc8ad6 | 360e7040f82fe046f0d7278048ecdcbe29581190 | /app/src/test/java/com/example/lolaabudu/cat_sqlite/ExampleUnitTest.java | 84c85c2b3404564c9c048a551b6d0b9fe9af198b | [] | no_license | LolaAbudu/Cat-SQLite | 8713dff3459d202b9c6185cf1f95d33391df3b54 | 3f670123f1f19ff9acb73452eebd83e79a1a44ba | refs/heads/master | 2020-04-17T00:57:02.460207 | 2019-01-16T16:05:29 | 2019-01-16T16:05:29 | 166,069,226 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 393 | java | package com.example.lolaabudu.cat_sqlite;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"lolaabudu1589@gmail.com"
] | lolaabudu1589@gmail.com |
10ee92c53e40e19aac0c7377aa0f7b237c2e6c27 | b9344e04983335a10227947ddae14a71999524ce | /src/com/example/command/PrioritizedCommandParser.java | ab8abfcbd12ced796a850579b3ff5ab14ff0cbb0 | [] | no_license | dux134/VoiceAssistant | 4509994899d3f3a2e770e2197f11e17a5192c115 | fcd7d8c7ee6723ea7fabcf9c39120f8dc7688f60 | refs/heads/master | 2020-03-14T16:48:53.800294 | 2014-05-25T14:16:26 | 2014-05-25T14:16:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 636 | java | /**
*
*/
package com.example.command;
/**
* @author yuechuan
*
*/
public interface PrioritizedCommandParser extends CommandParser {
public final int PRIORITY_HIGH = 1;
public final int PRIORITY_MIDIUM= 2;
public final int PRIORITY_LOW= 3;
/**
* set the priority level of a command (that exist already in
* the execution queue) to the priorityLevel defined by
* priorityLevel.
* @param command
* @param priorityLevel
*/
public void setpriority(CommandActions command , int priorityLevel);
/**
* get the priority level of a command
* @param command
*/
public void getpriority(CommandActions command );
}
| [
"yuechuan20@gmail.com"
] | yuechuan20@gmail.com |
0d9d1e9720994e7310f28e7fe1fa3efbd161e058 | f3d47a6efea00ed34c5516f0aa84034f6276408c | /JSP-CMPP220-Workshop7/src/java/customer/BookingDetail.java | fc0f9d281b67a24aadccb4c82c88dda7bd3d4256 | [] | no_license | adamadu/Team-2--Java-JSP-Group-Project | bbce041cd76f50dbfa40bf9821707ef789555aee | 7e893d93c63670f6833ebc8724882ef30c4d0cf9 | refs/heads/master | 2021-01-17T17:07:18.016368 | 2015-10-09T04:28:34 | 2015-10-09T04:28:34 | 41,172,905 | 1 | 0 | null | 2015-08-31T22:16:56 | 2015-08-21T19:10:50 | null | UTF-8 | Java | false | false | 1,246 | java | package customer;
import java.util.Date;
public class BookingDetail {
private int bookingDetailId;
private int itineraryNo;
private Date tripStart;
private Date tripEnd;
private String description;
private String destination;
private double basePrice;
public int getBookingDetailId() {
return bookingDetailId;
}
public void setBookingDetailId(int bookingDetailId) {
this.bookingDetailId = bookingDetailId;
}
public int getItineraryNo() {
return itineraryNo;
}
public void setItineraryNo(int itineraryNo) {
this.itineraryNo = itineraryNo;
}
public Date getTripStart() {
return tripStart;
}
public void setTripStart(Date tripStart) {
this.tripStart = tripStart;
}
public Date getTripEnd() {
return tripEnd;
}
public void setTripEnd(Date tripEnd) {
this.tripEnd = tripEnd;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public double getBasePrice() {
return basePrice;
}
public void setBasePrice(double basePrice) {
this.basePrice = basePrice;
}
}
| [
"Geetham15@gmail.com"
] | Geetham15@gmail.com |
9b5d4d51f4bc084eda26f031bb1be6abc17bccd8 | b3a09568bf57e992d5665a41d54ae5117b6a769b | /app/src/main/java/com/shikeclass/app/debug/MyBbxCrashHandler.java | b142f09e3bab3837b71be8b1088bb1f9aeb2c53b | [] | no_license | Ca1vinLu/TimeClass | d2674e63090b448dc509dc29d96103aef90a0e15 | 5c9a08df1245ddd7fcfbac3781667ab5fce7a206 | refs/heads/master | 2021-10-24T22:02:00.799546 | 2018-11-25T15:27:06 | 2018-11-25T15:27:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,999 | java | package com.shikeclass.app.debug;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import com.blankj.utilcode.util.LogUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
public class MyBbxCrashHandler implements UncaughtExceptionHandler {
private static final String BBX_FILES = "MyAndroid";
private static final String SD_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator;
private static final String BBX_PATH = SD_PATH + BBX_FILES + File.separator;
private static final String LOG_TXT = "bbxClientText";
private static final String LOG_PATH = BBX_PATH;
/**
* Debug Log Tag
*/
public static final String TAG = "MyBbxCrashHandler";
// public static final boolean IS_SAVE_LOCALFILE = true;
/**
* CrashHandler实例
*/
private static MyBbxCrashHandler INSTANCE;
/**
* 程序的Context对象
*/
private Context mContext;
/**
* 系统默认的UncaughtException处理类
*/
private UncaughtExceptionHandler mDefaultHandler;
/**
* 错误信息
*/
private String mErrInfo = "";
/**
* 错误类型
*/
private String mErrorType = "";
/**
* 保证只有一个CrashHandler实例
*/
private MyBbxCrashHandler() {
}
/**
* 获取CrashHandler实例 ,单例模式
*/
public static MyBbxCrashHandler getInstance() {
if (INSTANCE == null)
INSTANCE = new MyBbxCrashHandler();
return INSTANCE;
}
public interface OnCatch {
public void onError();
}
/**
* 初始化,注册Context对象, 获取系统默认的UncaughtException处理器, 设置该CrashHandler为程序的默认处理器
*
* @param ctx
*/
public void init(Context ctx) {
mContext = ctx;
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
OnCatch onCatch;
public void init(Context ctx, OnCatch onCatch) {
init(ctx);
this.onCatch = onCatch;
}
/**
* 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
stop();
}
if (onCatch != null) {
onCatch.onError();
}
}
private synchronized void stop() {
// ToastUtil.cancelToast();
// for (int i = 0; i < BaseActivity.activityList.size(); i++) {
// Activity activity = BaseActivity.activityList.get(i);
// activity.finish();
// }
// MobclickAgent.onKillProcess(mContext);
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return true;
}
// 获取错误信息
mErrInfo += saveCrashInfoToFile(ex);
// 收集设备信息
collectCrashDeviceInfo(mContext);
// Timer mTimer = new Timer();
// mTimer.schedule(new TimerTask() {
// // 4秒钟后若因为网络问题还没发送成功 强制退出
// @Override
// public void run() {
// DebugUtil.printDebugInfo("!!!!!!!错误信息未发送成功");
// stop();
// }
//// }, 40000);
// if (DebugUtil.isDebug) {
saveLogFile();
// }
//
// LogUtils.debug(TimeUtil.getTime() + mErrInfo);
// MobclickAgent.reportError(mContext, TimeUtil.getTime() + mErrInfo);
// DebugUtil.printDebugInfo(mErrInfo);
// LogUtils.e("flag--", "handleException(MyBbxCrashHandler.java:156)-->>异常" + "\n" + mErrInfo);
// 发送错误报告到服务器
// ErrRecordPostNetWork net = new ErrRecordPostNetWork(mContext,
// mErrInfo, mErrorType, false);
return true;
}
/**
* 收集程序崩溃的设备信息
*
* @param ctx context
*/
public void collectCrashDeviceInfo(Context ctx) {
// 使用反射来收集设备信息.在Build类中包含各种设备信息,
// 例如: 系统版本号,设备生产商 等帮助调试程序的有用信息
// 返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
// setAccessible(boolean flag)
// 将此对象的 accessible 标志设置为指示的布尔值。
// 通过设置Accessible属性为true,才能对私有变量进行访问,不然会得到一个IllegalAccessException的异常
field.setAccessible(true);
mErrInfo += "[" + field.getName() + ":" + field.get(null) + "]";
// if (DebugUtil.isDebug) {
// LogUtils.d(TAG, field.getName() + " : " + field.get(null));
// }
} catch (Exception e) {
LogUtils.e(TAG, "Error while collect crash info", e);
}
}
}
/**
* 保存错误信息到文件中
*
* @param ex
* @return
*/
private String saveCrashInfoToFile(Throwable ex) {
Writer info = new StringWriter();
PrintWriter printWriter = new PrintWriter(info);
// 将此 throwable 及其追踪输出到指定的 PrintWriter
ex.printStackTrace(printWriter);
// getCause() 返回此 throwable 的 cause;如果 cause 不存在或未知,则返回 null。
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
mErrorType = cause.toString();
// DebugUtil.printDebugInfo("FIND_ERROR_COUSE cause = " + mErrorType + "\\\\\\\\\\endClass--cause");
cause = cause.getCause();
}
// toString() 以字符串的形式返回该缓冲区的当前值。
String result = info.toString();
printWriter.close();
int index = 0;
for (int i = 0; i < result.length(); i++) {
char temp = result.charAt(i);
if (temp == ':') {
index = i;
// DebugUtil.printDebugInfo("i = " + i);
break;
}
}
mErrorType = result.substring(0, index);
return result;
}
private void saveLogFile() {
String path = null;
if (mDefaultHandler != null) {
String state = Environment.getExternalStorageState();
// 判断SdCard是否存在并且是可用的
if (Environment.MEDIA_MOUNTED.equals(state)) {
/*path = SystemUtil.getSDCardPath() + "/"
+ mContext.getPackageName();*/
path = LOG_PATH;
// 创建一个logcat目录
// path = UPDATA_PATH + "log";
// path="/sdcard/a/log/";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
if (file.exists()) {
System.out.println("mk success!");
} else {
System.out.println("mk fail!");
}
}
// deleteOldFile(path);
String time = com.blankj.utilcode.util.TimeUtils.getNowString();
// DebugUtil.printDebugInfo("local full time = " + time);
// String fileName = time.substring(0, 10);
// String fileName = time;
File myFile = new File(path + "/" + "LogRecord.log");
// SDK.GetSDK().setServiceLogPath(path + "/" + "clientsdklog.log");
String str = "\n****" + Build.BRAND + "****" + "\n"
+ time + "-->" + "[\n" + mErrInfo + "\n]";
try {
FileWriter fw = new FileWriter(myFile, true);
fw.write(str);
fw.flush();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} | [
"q751264263@vip.qq.com"
] | q751264263@vip.qq.com |
4321d3f54b80e524a13e03d754052a42b6a8f789 | 43dc0c0291179e04267a3c45a3dae106423c07f5 | /src/main/java/edu/drexel/TrainDemo/models/State.java | 3310faf5dd5a50c61d5a4c1444ab331a338037ba | [] | no_license | Lambof3/SE577 | cf2bb1d32fb18ae59856da0d759a5e390774b8b5 | 1c3b3859976124e4562da250f55b4e17a5805329 | refs/heads/master | 2021-03-30T04:22:54.758083 | 2020-03-17T10:56:55 | 2020-03-17T10:56:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 729 | java | package edu.drexel.TrainDemo.models;
public enum State
{
AL,
AK,
AR,
AZ,
CA,
CO,
CT,
DC,
DE,
FL,
GA,
HI,
IA,
ID,
IL,
IN,
KS,
KY,
LA,
MA,
MD,
ME,
MI,
MN,
MO,
MS,
MT,
NC,
ND,
NE,
NH,
NJ,
NM,
NV,
NY,
OK,
OH,
OR,
PA,
RI,
SC,
SD,
TN,
TX,
UT,
VA,
VT,
WA,
WI,
WV,
WY
} | [
"cmshoenberger@gmail.com"
] | cmshoenberger@gmail.com |
baf8efb653081f05cda127b2c77c0ba2e54049d5 | f7baab8b6883184b0c6d177a7db65843f0e676bf | /src/hallelulajah/Hallelulajah.java | 4e0ae3db83b95a5a64118218e445550dc3af6cc3 | [] | no_license | asburr/bigIsland | c2be662d520371fb9143bf24c698df8e19c395c1 | 3b0061697df75b15ac9ae2c648e8be09fc5924ac | refs/heads/master | 2023-07-06T02:11:15.207961 | 2023-06-29T13:50:13 | 2023-06-29T13:50:13 | 93,284,886 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 24,518 | java | package hallelulajah;
import java.io.File;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.util.concurrent.ConcurrentSkipListMap;
import magpie.Server;
import magpie.Client;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.UUID;
import java.util.ArrayList;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
// TODO make a pool of reusable JMRecord so GC is not so busy.
// TODO make a pool of LinkedList<JMRecord>, for the same reasons.
class JMRecord implements Comparable<JMRecord> {
public long ts;
public char cmd;
public String key,data,tablename;
public JMRecord(long ts,char cmd, String key, String data, String tablename) {
this.ts=ts; this.cmd=cmd; this.key=key; this.data=data; this.tablename=tablename;
}
public JMRecord(JMRecord o) {
this.ts=o.ts; this.cmd=o.cmd; this.key=o.key; this.data=o.data; this.tablename=o.tablename;
}
@Override public int compareTo(JMRecord o) {
long d=this.ts - o.ts;
if (d<0) return -1;
if (d>0) return 1;
return 0;
}
public int compareTo(long ts) {
long d=this.ts - ts;
if (d<0) return -1;
if (d>0) return 1;
return 0;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof JMRecord)) return false;
return (this.compareTo((JMRecord)o)==0);
}
@Override public int hashCode() {
return Objects.hash(getSigFields());
}
private Object[] getSigFields() {
Object[] result = { ts, cmd, key, data };
return result;
}
}
class JournalM { // To Memory.
LinkedList<JMRecord> m=new LinkedList<JMRecord>();
public JournalM() { }
boolean getting=false; // Hall calls get() which sets this, write() then gets the journals for Hall.
public void write(char cmd, String key, String row, String tablename) {
long ts=System.nanoTime();
if (this.getting) this.getting();
// Jah sends blank (B) commands every 50ms, the purpose being to look for any get requests from Hall.
if (cmd!='B') this.m.add(new JMRecord(ts,cmd,key,row,tablename));
}
// g is the journals being passed back to Hall, see get().
LinkedList<JMRecord> g=new LinkedList<JMRecord>();
// upto is the timestamp that Hall sets before calling get(), to requesting journals upto the timestamp.
long upto=0L;
// getting() is called from ,tablenamewritei), to get the journals for Hall.
private void getting() {
this.g.clear(); // Swap g and m, first clear anything that remain in g.
LinkedList<JMRecord> x=this.g; this.g=this.m; this.m=x; // Swap g and m.
JMRecord r=this.g.peekLast(); // Newest journal.
while (r.compareTo(this.upto)>0) { // journal newer than upto.
r=this.g.removeLast(); // Dont pass newer journal to Hall.
this.m.offerFirst(r); // Add journal back to the journaling.
r=this.g.peekLast(); // Next newest journal.
}
// See if the journaling has the table name, otherwise copy it back into journalling.
r=this.g.peekFirst();
if (r==null || // Nothing in journalling, need table name in journalling.
(r.cmd!='+' && r.cmd!='c')) // Last journal is not table name, need table name.
{ // Copy the table name back to the journalling.
Iterator<JMRecord> i = this.g.descendingIterator();
while (i.hasNext()) {
r=i.next();
if (r.cmd=='+' || r.cmd=='c') { // this is a table event, with the table name!
r=new JMRecord(r); // Duplicate the journal.
r.cmd='c'; // Change journal type to connect (c).
this.m.offerFirst(r); // Add journal to journalling.
break;
}
}
}
this.getting=false;
}
// Hall calls get(), Hall blocks here until the Jah gets the journal.
public LinkedList<JMRecord> get(long until) {
if (this.m.size()==0) return null;
this.upto=until;
this.getting=true;
while (this.getting) try { Thread.sleep(10); } catch(Exception e) {}
if (this.g.size()==0) return null;
return this.g;
}
public void close() { // Make sure memory journalling has been written to disk before closing.
while (this.m.size()>0) {
if (this.getting) this.getting();
try { Thread.sleep(50); } catch(Exception e) {}
}
}
public void commit(Hallelulajah hall) { // Make sure memory journalling has been written to disk.
while (this.m.size()>0) { // Journalling still in memory, wait for Hall to get it.
if (this.getting) { this.getting(); break; }
try { Thread.sleep(50); } catch(Exception e) {}
}
// If Hall is writing a commit to disk, wait for that to finish.
while (!hall.committed) try { Thread.sleep(50); } catch(Exception e) {}
}
}
class JournalO {
private File journal=null;
private RandomAccessFile j=null;
public JournalO(File f,boolean append) {
try {
this.journal=f;
this.j=new RandomAccessFile(this.journal,"rwd");
// Append is the following seek!
if (append) this.j.seek(this.j.length());
// Otherwise, no append, and truncate the file by setting the length.
else this.j.setLength(0);
} catch (Exception e) {
e.printStackTrace();
}
}
private String empty="";
private String tablename=null;
public void write(char cmd, String key, String row, String tablename) {
try {
if (this.tablename==null || !this.tablename.equals(tablename)) {
this.tablename=tablename;
this.j.writeChar('c');
this.j.writeUTF(this.tablename);
this.j.writeUTF(this.empty);
}
this.j.writeChar(cmd);
this.j.writeUTF(key);
if (row==null) this.j.writeUTF(this.empty);
else this.j.writeUTF(row);
} catch(Exception e) {
e.printStackTrace();
this.close();
}
}
public long size() { try { return j.length(); } catch(Exception e) { e.printStackTrace(); return -1; } }
public void close() {
try {
this.journal=null;
this.j.close();
this.j=null;
} catch (Exception e) {
}
}
}
class JournalI {
private File journal=null;
private RandomAccessFile j=null;
public JournalI(File file) {
this.journal=file;
try {
this.j=new RandomAccessFile(this.journal,"r");
} catch(Exception e) {
e.printStackTrace();
}
}
public long time;
public char cmd='?';
public String key=null;
public String row=new String("");
public boolean eof=false;
public boolean next() {
try {
this.cmd=this.j.readChar();
this.key=this.j.readUTF();
this.row=this.j.readUTF();
return true;
} catch (EOFException e) {
this.eof=true;
return false;
} catch (IOException e) {
e.printStackTrace();
this.eof=true;
return false;
}
}
// compare < 0, when this started before i
// compare > 0, when this started after i
// compare = 0, when this started at the same time at i.
public long compare(JournalI i) {
return this.time - i.time;
}
public void close() {
try { this.j.close(); } catch (Exception e) { e.printStackTrace(); }
this.j=null;
}
}
class Yahweh implements Runnable {
private Client client=null;
private Hallelulajah hall=null;
private JournalM j=null;
public LinkedList<JMRecord> get(long until) { return this.j.get(until); }
public Yahweh(Client client,Hallelulajah hall) {
this.client=client;
this.hall=hall;
this.j=new JournalM();
}
private String tablename=null;
private Table table=null;
private Table d_table=null;
private String row=null;
private String key=null;
private boolean parseKeyData(String cmd, String usage) {
if (cmd.charAt(1) != ',') {
this.client.sendBuf_String("fail : Usage : "+usage+"\n");
return false;
}
this.key=null;
this.row=null;
boolean escaped=false;
for (int j=2;j<cmd.length();j++) {
if (escaped) {
escaped=false;
} else {
if (cmd.charAt(j)=='\\') {
escaped=true;
} else {
if (cmd.charAt(j)==',') {
// Remove escaping of coma and the escape itself.
this.key=cmd.substring(2,j).replace("\\\\","{doubelescape}").replace("\\","").replace("{doubelescape}","\\");
j++;
if (j<cmd.length()) this.row=cmd.substring(j);
break;
}
}
}
}
if (this.key==null || this.row==null) {
this.client.sendBuf_String("fail : usage : "+usage+"\n");
return false;
}
return true;
}
private boolean parseKey(String cmd, String usage) {
if (cmd.charAt(1) != ',' || cmd.length()<3) {
this.client.sendBuf_String("fail : Usage : "+usage+"\n");
return false;
}
this.key=cmd.substring(2).replace("\\\\","{doubelescape}").replace("\\","").replace("{doubelescape}","\\");
return true;
}
private boolean parseTable(String cmd, String usage) {
if (cmd.charAt(1) != ',' || cmd.length() < 3) {
this.client.sendBuf_String("Fail : Usage : "+usage+"\n");
return false;
}
this.tablename=cmd.substring(2);
return true;
}
public void run() {
boolean human=true;
while (!this.client.shutdown) {
if (!client.read(50,TimeUnit.MILLISECONDS)) {
this.j.write('B',null,null,null); // Send blank event, to service any get of the journaling by Hall.
continue;
}
String cmd=this.client.recvBuf_GetString(-1);
if (cmd.length()==0) continue;
switch (cmd.charAt(0)) {
case 'x': {
this.j.close();
if (human) this.client.sendBuf_String("Success : exiting connection\n");
else this.client.sendBuf_String("");
return;
}
case 'M': {
human=false;
this.client.sendBuf_String("");
continue;
}
case 'H': {
human=true;
this.client.sendBuf_String("Hallelulajah\n");
continue;
}
case 's': {
this.j.commit(this.hall);
if (human)
this.client.sendBuf_String("Success : volatile changes are persistent\n");
else
this.client.sendBuf_String("");
continue;
}
case 'c': { // Connect to table
this.table=null;
if (cmd.length()==1) {
if (human) {
if (this.table==null)
this.client.sendBuf_String("Not connected to any table\n");
else
this.client.sendBuf_String("Connected to table name "+this.table.name+"\n");
} else
this.client.sendBuf_String(this.table.name);
continue;
}
if (!this.parseTable(cmd,"t,<tablename>")) continue;
this.table=hall.getTable(this.tablename);
if (this.table==null)
this.client.sendBuf_String("Fail : no such table "+this.tablename+"\n");
else if (human)
this.client.sendBuf_String("Success : connected to table name "+this.table.name+"\n");
else
this.client.sendBuf_String("");
break;
}
case '+': { // Add table
this.table=null;
if (!this.parseTable(cmd,"+,<tablename>")) continue;
this.table=hall.addTable(this.tablename);
if (this.table==null)
this.client.sendBuf_String("Fail : to add table "+this.tablename+"\n");
else {
if (human)
this.client.sendBuf_String("Success : added table "+this.tablename+"\n");
else
this.client.sendBuf_String("");
if (hall.backingUp) this.d_table=hall.d_addTable(this.tablename);
this.j.write('+',this.tablename,null,this.tablename);
}
break;
}
case '-': { // Delete table
if (cmd.length() > 1) {
this.client.sendBuf_String("Fail : usage : -\n");
continue;
}
if (this.table==null) {
if (human)
this.client.sendBuf_String("Fail : no table connected\n");
else
this.client.sendBuf_String("");
continue;
}
if (!this.hall.delTable(this.table.name,this.table)) {
if (human)
this.client.sendBuf_String("Fail : Table does not exist could already be deleted "+this.table.name+"\n");
else
this.client.sendBuf_String("");
this.table=null;
continue;
}
this.j.write('-',this.table.name,null,null);
if (human)
this.client.sendBuf_String("Success : table "+this.table.name+" deleted\n");
else
this.client.sendBuf_String("");
if (this.hall.backingUp) {
this.hall.d_addTable(this.table.name);
this.d_table=null;
}
this.table=null;
break;
}
case 'a': { // Add row
if (!this.parseKeyData(cmd,"a,<key>,<data>")) continue;
if (this.table==null) {
this.client.sendBuf_String("Fail : please connect (c) to a table\n");
continue;
}
String r=this.table.addRow(this.key,this.row);
if (r!=null) {
this.client.sendBuf_String("Fail : row exists already at this key\n");
} else {
this.j.write('a',this.key,this.row,this.table.name);
if (human)
this.client.sendBuf_String("Success : row added\n");
else
this.client.sendBuf_String("");
if (this.hall.backingUp) {
if (this.d_table==null) this.d_table=hall.d_addTable(this.tablename);
this.d_table.addRow(this.key,null); // Add null for a new row.
}
}
break;
}
case 'd': { // Delete row
if (!this.parseKey(cmd,"d,<key>")) continue;
if (this.table==null) {
this.client.sendBuf_String("Fail : please connect (c) to a table\n");
continue;
}
this.row=this.table.delRow(this.key);
if (this.row==null) {
this.client.sendBuf_String("Fail : row does not exist\n");
continue;
}
if (this.hall.backingUp) {
if (this.d_table==null) this.d_table=hall.d_addTable(this.table.name);
this.d_table.addRow(this.key,this.row);
}
this.j.write('d',this.key,null,this.table.name);
this.row=null;
if (human)
this.client.sendBuf_String("Success : deleted row at "+this.key+"\n");
break;
}
case 'r': { // Replace row
if (!this.parseKeyData(cmd,"r,<key>,<data>")) continue;
if (this.table==null) {
this.client.sendBuf_String("Fail : please connect (c) to a table\n");
continue;
}
String oldRow=this.table.replaceRow(this.key,this.row);
if (oldRow==null) {
this.client.sendBuf_String("Fail : row does not exist\n");
continue;
}
if (this.hall.backingUp) {
if (this.d_table==null) this.d_table=hall.d_addTable(this.table.name);
this.d_table.addRow(this.key,oldRow);
}
this.j.write('r',this.key,this.row,this.table.name);
if (human)
this.client.sendBuf_String("Success : replace row at "+this.key+"\n");
else
this.client.sendBuf_String("");
break;
}
case 'q': { // Query table
this.parseKey(cmd,"q,<key>");
if (this.table==null) { this.client.sendBuf_String("Fail : please connect to a table\n"); continue; }
this.row=this.table.getRow(this.key);
if (human) {
if (this.row!=null) this.client.sendBuf_String(this.row+"\n");
else this.client.sendBuf_String("Fail : no such row\n");
} else {
if (this.row!=null) this.client.sendBuf_String(this.row);
else this.client.sendBuf_String("");
}
break;
}
default: {
this.client.sendBuf_String("Usage: [x,c,+,-,a,d,q]\nDescription:"+
"\nx : exit :"+
"\nc,<table name> : connect to table : table must already exist"+
"\n+,<table name> : add table : no error when table already exists"+
"\n- : remove table : connect(c)"+
"\na,<key>,<data> : add row : connect(c)"+
"\nd,<key> : deletes row and returns row data : connect(c)"+
"\nq,<key> : return row data : connect(c)"+
"\n"
);
break;
}
}
}
}
}
class Table {
public String name=null;
ConcurrentSkipListMap<String,String> rows=new ConcurrentSkipListMap<String,String>();
public Table(String name) { this.name=name; }
public String addRow(String key,String row) {
return this.rows.putIfAbsent(key,new String(row));
}
// Add the row, or replaces existing row.
public void addXRow(String key,String row) {
this.rows.put(key,new String(row));
}
public String delRow(String key) {
return this.rows.remove(key);
}
public String replaceRow(String key,String row) {
return this.rows.replace(key,row);
}
public String getRow(String key) {
return this.rows.get(key);
}
}
class Persistent implements Runnable {
Hallelulajah hall=null;
public Persistent(Hallelulajah hall) {
this.hall=hall;
}
public void run() {
long jbefore=System.currentTimeMillis();
long bbefore=System.currentTimeMillis()-hall.backupPeriod; // Trigger a backup.
if (this.hall.backupFile.exists()) bbefore=this.hall.backupFile.lastModified(); // Unless there's a backup already, then use that timestamp.
while (!this.hall.shutdown) {
long jafter=System.currentTimeMillis();
if ((jafter-jbefore) > 150) {
this.hall.journal(); // Write journals to file.
jbefore=jafter;
long bafter=System.currentTimeMillis();
if ((bafter-bbefore) > this.hall.backupPeriod) {
bbefore=bafter;
this.hall.mergeJournalWithBackup(); // Create a new backup file.
}
}
try { Thread.sleep(1000); } catch(Exception e) {}
}
}
}
public class Hallelulajah {
Server server=null;
public long journalMaxSize=10000L;
public File dir=null;
public File backupFile=null;
public File newBackupFile=null;
public File oldBackupFile=null;
public File journalFile=null;
public JournalO j=null;
public int backupPeriod=60*60*1000;
public Hallelulajah(String host, int port, String dir, int backupPeriod) {
this.backupPeriod=backupPeriod*60*1000;
this.server=new Server(port,100,0xffee);
this.dir=new File(dir);
if (!this.dir.exists()) {
if (!this.dir.mkdir()) {
System.err.println("Fail : cannot create dir "+dir);
System.exit(0);
}
} else if (!this.dir.isDirectory()) {
System.err.println("Fail : "+dir+" exists but is not a directory");
System.exit(0);
}
this.journalFile=new File(this.dir+File.separator+"Journal");
this.j=new JournalO(this.journalFile,true);
this.backupFile=new File(this.dir+File.separator+"Backup");
this.newBackupFile=new File(this.dir+File.separator+"NewBackup");
this.oldBackupFile=new File(this.dir+File.separator+"OldBackup");
this.readFile(this.backupFile);
this.readFile(this.journalFile);
}
private void readFile(File f) {
if (!f.exists()) return;
JournalI i=new JournalI(f);
Table table=null;
while (i.next()) {
switch (i.cmd) {
case 'c': { table=this.addTable(i.key); break; }
case '+': { table=this.addTable(i.key); break; }
case '-': { this.delTable(i.key,table); table=null; break; }
case 'a': { table.addRow(i.key,i.row); break; }
case 'd': { table.delRow(i.key); break; }
case 'r': { table.addXRow(i.key,i.row); break; }
default: { System.err.println("Fail : journal command "+i.cmd); return; }
}
}
}
LinkedList<Yahweh> jahs=new LinkedList<Yahweh>();
public boolean shutdown=false;
public void start() {
ExecutorService pool=Executors.newCachedThreadPool();
pool.execute(new Persistent(this));
while (!this.shutdown) {
Client client=server.accept(100);
if (client!=null) {
System.out.println("Server accepted connection from "+client.addresses());
Yahweh jah=new Yahweh(client,this);
this.jahs.add(jah);
pool.execute(jah);
}
}
pool.shutdown();
}
// committed implements the save(s) command.
public boolean committed=false;
private Map<Long,LinkedList<JMRecord>> jmap=new TreeMap<Long,LinkedList<JMRecord>>();
// journal() writes journals to file which is also the save(s) command.
private void listforeach(LinkedList<JMRecord> l) {
for (JMRecord r: l)
this.j.write(r.cmd,r.key,r.data,r.tablename);
}
// Write Jah memory journals to file.
public void journal() {
long until=System.nanoTime();
this.committed=false;
for (Yahweh jah: this.jahs) {
LinkedList<JMRecord> l=jah.get(until);
if (l==null) continue;
for (JMRecord r: l) {
LinkedList<JMRecord> ls=this.jmap.get(r.ts);
if (ls==null) { ls=new LinkedList<JMRecord>(); this.jmap.put(r.ts,ls); }
ls.add(r);
}
}
this.jmap.forEach((k, v) -> this.listforeach(v));
this.committed=true; // For the save(s) command.
this.jmap.clear();
}
// dtables holds original key/data pairs when backup in progress and key/data pair was changed.
ConcurrentSkipListMap<String,Table> dtables=new ConcurrentSkipListMap<String,Table>();
// backingUp is true when backup is in progress.
boolean backingUp=false;
// mergeJournalWithBackup() - creates a new backup file from the old backup and the journal file.
public void mergeJournalWithBackup() {
if (this.journalFile.length()==0) return; // Nothing to backup.
this.backingUp=true;
this.j.close();
this.j=new JournalO(this.newBackupFile,false);
JournalI i=null;
if (this.backupFile.exists()) {
i=new JournalI(this.backupFile);
this.backup(i);
i.close();
}
i=new JournalI(this.journalFile);
this.backup(i);
i.close();
this.j.close();
this.backingUp=false;
this.dtables.clear();
this.j=new JournalO(this.journalFile,false);
// Move Backup to OldBackup.
if (this.backupFile.exists()) {
this.oldBackupFile.delete();
this.backupFile.renameTo(this.oldBackupFile);
}
// Move NewBackup to Backup
this.newBackupFile.renameTo(this.backupFile);
}
// Select which journal commands to write to file.
private void backup(JournalI i) {
String tableName=null;
Table table=null;
while (i.next()) {
switch (i.cmd) {
case 'c':
case '+':
tableName=i.key;
table=this.getTable(tableName);
if (table==null) tableName=null;
break;
case 'r':
case 'a':
if (tableName!=null) {
String row=null;
// Query dtable for original value that has changed during the backup.
Table dtable=this.d_getTable(tableName);
if (dtable!=null) row=dtable.getRow(i.key);
if (row==null) {
// Query table for the value.
row=table.getRow(i.key);
// Query again dtable, use this value if we now find it.
dtable=this.d_getTable(tableName);
if (dtable!=null) { String x=dtable.getRow(i.key); if (x!=null) row=x; }
}
if (row!=null) {
this.j.write('r',i.key,row,tableName);
}
}
break;
}
}
}
ConcurrentSkipListMap<String,Table> tables=new ConcurrentSkipListMap<String,Table>();
public Table d_getTable(String name) { return this.dtables.get(name); }
public Table getTable(String name) { return this.tables.get(name); }
public Table addTable(String name) {
Table n=new Table(name);
Table t=this.tables.putIfAbsent(name,n);
if (t!=null) return t;
return n;
}
public Table d_addTable(String tablename) {
return this.tables.putIfAbsent(tablename,null);
}
public boolean delTable(String name,Table table) { return this.tables.remove(name,table); }
public static void main(String[] args) { try {
if (args.length != 4) {
System.out.println("Usage: <listening host> <listening port> <directory> <minutes in between backups>\ni.e. localhost 9001 db_dir 60");
return;
}
Hallelulajah h=new Hallelulajah(args[0],Integer.parseInt(args[1]),args[2],Integer.parseInt(args[3]));
h.start();
} catch(Exception e) {
e.printStackTrace();
}
}
}
| [
"asburr@hotmail.com"
] | asburr@hotmail.com |
98c9809b994526e56d6b2a50a8567123b860513e | dfddeabd6792faec8f7bb4c17c2b19affe01ec3f | /rmiCommandPattern/src/client/Client.java | d5e6f54e76a0737c011358e989a307eea9299eb9 | [] | no_license | gfrassl/DezSys04-RMI | 743575647a3ae512b7a34ec63bcf03154b8167a0 | a3bc03729554a44aaa7fb3f64727d5f82f266dbc | refs/heads/master | 2021-05-30T23:13:01.580850 | 2016-03-30T09:11:39 | 2016-03-30T09:11:39 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,477 | java | package client;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import remoteService.DoSomethingService;
import server.commands.CalculationCommand;
import server.commands.Command;
import server.commands.RegisterCommand;
import server.commands.LoginCommand;
/**
* Clientklasse die auf ein Remoteobjekt zugreifft und mehrere Commands mit diesem remoteobjekt ausführt.
* @author Gabriel
*
*/
public class Client {
/**
* anfragen der Registry, erstellen einer "Verbindung" zum Remote Objekt und ausführen verschiedener Commands
* @param args cli argumente - anzahl der Stellen von Pi
*/
public static void main(String[] args) {
//if(System.getSecurityManager() == null) {
//System.setSecurityManager(new SecurityManager());
//}
try {
Registry registry = LocateRegistry.getRegistry(1233);
DoSomethingService uRemoteObject = (DoSomethingService) registry.lookup("Service");
System.out.println("Service found");
Command rc = new RegisterCommand();
Command lc = new LoginCommand();
Command cc = new CalculationCommand();
uRemoteObject.doSomething(rc);
uRemoteObject.doSomething(lc);
uRemoteObject.doSomething(cc);
} catch (RemoteException re) {
System.err.println("Service not found?" + " Check your RMI-Registry!");
System.exit(1);
} catch (Exception e) {
System.err.println("Service exception:");
e.printStackTrace();
System.exit(1);
}
}
}
| [
"gabrielfrassl98@gmail.com"
] | gabrielfrassl98@gmail.com |
851c2060be2d13598db05bff733dfee71071c80c | 778e2e70b4bb02f7819937feea8ae52ce5215d96 | /app/src/test/java/ru/tohaman/rubicsguide/ExampleUnitTest.java | 8436f9edcad6b9b356c655f560e1b5b26d3da5a6 | [] | no_license | Tohaman/RubicsGuide.Java | f0975ac01cb79ccd17bb68833fdcc142dc5d1827 | 4c874f83bf684659d3265269a71e555577898a46 | refs/heads/master | 2021-09-15T16:51:06.320758 | 2018-06-07T08:37:52 | 2018-06-07T08:37:52 | 93,378,193 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 400 | java | package ru.tohaman.rubicsguide;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"avrozovu@yandex.ru"
] | avrozovu@yandex.ru |
29b43c1b3692ecd4280751c654f1b0da8c7e0dbf | 33ea30180d24784c5b730bf31694e8077ca00b89 | /ihrm_company/src/main/java/com/ihrm/company/service/CompanyService.java | 4986685634fbef411abec67b253dfc00a93c1af4 | [] | no_license | ZhangDi-d/ihrm_parent | 10e7744c5b8c8a6edf4847930ee80392dc942b3a | 911f4924a5abb491f3d8e8f70c5de889cc1be3af | refs/heads/master | 2022-06-23T00:38:51.299356 | 2020-03-15T01:37:30 | 2020-03-15T01:37:30 | 241,554,690 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package com.ihrm.company.service;
import com.ihrm.domain.company.Company;
import java.util.List;
public interface CompanyService {
public Company add(Company company);
public Company update(Company company);
public Company findById(String id);
public void deleteById(String id);
public List<Company> findAll();
}
| [
"zhangdiryze@gmail.com"
] | zhangdiryze@gmail.com |
4d1c323bc129c2da0cf2de742f6c4eddfcf65796 | 42031b6488d52c9fc41cf6362633be8a514039f6 | /TravelfactoryTest/src/main/java/TravelfactoryTest/dto/CampaignDTO.java | 3febf0c8dcd37d612619b393b5ce39dcdebdd775 | [] | no_license | GrigKG/RepoTest | 1365eebd52b379043588da51c53a5bc8ebd26459 | 0b22f8f40b4edfa79d73f553fbfa18e41929743e | refs/heads/master | 2023-02-20T06:15:24.054587 | 2021-01-23T17:48:42 | 2021-01-23T17:48:42 | 332,265,396 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 304 | java | package TravelfactoryTest.dto;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CampaignDTO {
String campaignName;
List<String> mandatoryFields;
}
| [
"38141067+GrigKG@users.noreply.github.com"
] | 38141067+GrigKG@users.noreply.github.com |
d5c16e67fa406f3a12386774c78c0d6a5673e26d | 0015f7f641e5f01ccd1fce6cf987fd762f5338b7 | /hwteststudent/src/main/java/ru/otus/dao/AnswerDaoFileImpl.java | 608cf23c06c17783281bfec279db8c8f1f286b44 | [] | no_license | thefirstbornson/otus_spring_2019_02_artem_poskrebyshev | 93d6cf794f9cfafdc07923dde472facf93b6aab2 | ff5ce9454ddaf081696113b5bb5e27fc1c24e74f | refs/heads/master | 2020-04-25T04:49:19.480769 | 2019-03-18T10:12:19 | 2019-03-18T10:12:19 | 172,523,116 | 0 | 0 | null | 2019-03-18T10:12:20 | 2019-02-25T14:38:51 | Java | UTF-8 | Java | false | false | 2,052 | java | package ru.otus.dao;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import ru.otus.domain.Answer;
import ru.otus.service.SequenceService;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AnswerDaoFileImpl extends DaoFileImpl<Answer> implements DAO<Answer> {
final SequenceService answerSequenceService;
public AnswerDaoFileImpl(String fileName,SequenceService answerSequenceService) {
super(Answer.class, fileName);
this.answerSequenceService = answerSequenceService;
}
@Override
public List<Answer> parseCSV() throws IOException {
CSVReader aReader = new CSVReader(
new InputStreamReader(getClass().getClassLoader().getResourceAsStream(fileName)));
List<Answer> answs = new ArrayList<>();
String[] record = null;
int aStart =0;
while ((record = aReader.readNext()) != null) {
aStart = Arrays.asList(record).indexOf("#ans");
if (aStart>0){
try {
for (int i=aStart+1;i<record.length-1;i++) {
Answer answ = new Answer(answerSequenceService.getID()
,Integer.valueOf(record[0])
,record[i]
,Integer.valueOf(record[record.length - 1]) == i-aStart ? true : false);
answs.add(answ);
}
} catch (NumberFormatException e){
e.printStackTrace();
}
}
}
aReader.close();
return answs;
}
}
| [
"thefirstbornson@gmail.com"
] | thefirstbornson@gmail.com |
afade031d9b2821d1fdfc58cc0151998401d9176 | fed04590cd8a58ecb41a53a85c14884f53448b53 | /app/src/main/java/com/mitkonsultan/palembangmengaji/hari/Ahad.java | e253eea2e0d2620d0858ec8e2bb8dd036b584f05 | [] | no_license | gintoki05/PalembangMengaji | c0f8d0082ac3812fdbd41c25ede59f140b4e1685 | 809a5a59fb85a996def816207225f5b540f00e71 | refs/heads/master | 2020-03-26T01:52:30.026508 | 2018-08-11T13:18:01 | 2018-08-11T13:18:01 | 144,386,755 | 0 | 1 | null | 2018-10-04T10:08:48 | 2018-08-11T13:18:51 | Java | UTF-8 | Java | false | false | 8,049 | java | package com.mitkonsultan.palembangmengaji.hari;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.mitkonsultan.palembangmengaji.R;
import com.mitkonsultan.palembangmengaji.haridataadapter.AhadDataAdapter;
import com.mitkonsultan.palembangmengaji.hariviewadapter.AhadViewAdapter;
import com.mitkonsultan.palembangmengaji.menu.AlarmAhad;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;
public class Ahad extends AppCompatActivity {
ProgressBar progressBar;
private List<AhadDataAdapter> lostList = new ArrayList<>();
private RecyclerView recyclerView;
private AhadViewAdapter mAdapter;
private ArrayList<AhadDataAdapter> posts;
private ImageView imgHeader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ahad);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
imgHeader = (ImageView) findViewById(R.id.backdrop);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle("");
Glide.with(getApplicationContext()).load("http://palembangmengaji.forkismapalembang.com/gambar/hari/ahad.png")
.thumbnail(0.5f)
.transition(withCrossFade())
.into(imgHeader);
RequestOptions options = new RequestOptions()
.diskCacheStrategy(DiskCacheStrategy.ALL);
initUi();
loadLost();
}
private void initUi(){
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewahad);
mAdapter = new AhadViewAdapter((ArrayList<AhadDataAdapter>) lostList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}
private void loadLost(){
String url2 = "http://palembangmengaji.forkismapalembang.com/api.php?hari=ahad";
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Method.GET,
url2, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i <response.length() ; i++) {
JSONObject kajian = response.getJSONObject(i);
String masjid = kajian.getString("masjid");
String waktu = kajian.getString("waktu");
String pengisi = kajian.getString("pengisi");
String tema = kajian.getString("tema");
String tanggal = kajian.getString("tanggal");
String kategori = kajian.getString("kategori");
AhadDataAdapter lostItem = new AhadDataAdapter(
masjid, waktu, pengisi, tema, tanggal, kategori
);
lostList.add(lostItem);
mAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString), cacheEntry);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException e) {
return Response.error(new ParseError(e));
}
}
@Override
protected void deliverResponse(JSONArray response) {
super.deliverResponse(response);
}
@Override
public void deliverError(VolleyError error) {
super.deliverError(error);
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
return super.parseNetworkError(volleyError);
}
};
Volley.newRequestQueue(this).add(jsonObjReq);
}
public boolean onCreateOptionsMenu (Menu menu){
// menambahkan icon menu pada toolbar
getMenuInflater().inflate(R.menu.alarm, menu);
return true;
}
public boolean onOptionsItemSelected (MenuItem item){
int id = item.getItemId();
//memberi aksi menu
if (id == R.id.action_alarm) {
Intent intent = new Intent(this, AlarmAhad.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"ajieprastyo@gmail.com"
] | ajieprastyo@gmail.com |
1d1c2b11df9e664dfb03b6074231b7167fcf30b7 | ffcfb9d41ba5ff10527552b6f3cd17c1753495ce | /src/server/model/Model.java | 70c2113543ef23cc0ff9f0ab9484d992628b08b3 | [] | no_license | pulkit24/MonsterGame | fd0de08843363ec633f6154a6b04b675df347007 | db81ee9d251f6fa8698846d6c5f198dcd2d22e02 | refs/heads/master | 2021-01-23T15:53:19.495099 | 2012-10-13T02:09:48 | 2012-10-13T02:09:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,999 | java | /**@Cetin and Pulkit
* All database calls here.
* Usage:
* 1. To add a user: add(...)
* 2. To check if a user's login details exist: exists(...)
* 3. To get score: getScore(...)
* 4. To set score: updateScore(...)
*/
package server.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import components.Debug;
import components.model.User;
public class Model{
private Connection connection;
public Model(){
// Load the Oracle JDBC driver
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@emu.cs.rmit.edu.au:1521:GENERAL";
connection = DriverManager.getConnection(url, "csatici", "ZERYA12");
}catch(ClassNotFoundException e){
// TODO Auto-generated catch block
System.err.println("Model: JDBC driver not found " + e.toString());
}catch(SQLException e){
// TODO Auto-generated catch block
System.err.println("Model: Could not connect to the database " + e.toString());
}
}
public boolean add(User user){
/* Adds the user to the db */
String query = "insert into Usertable values(?, ?, ?, ?, ?, ?, ?)";
try{
/* Use prepared statement to execute the sql query */
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, user.getFirstName());
ps.setString(2, user.getSurname());
ps.setString(3, user.getAddress());
ps.setString(4, user.getPhone());
ps.setString(5, user.getUsername());
ps.setString(6, user.getPassword());
ps.setInt(7, 0);
Debug.log("Model","adding with usr: "+user.getUsername()+" pwd: "+user.getPassword());
ps.execute();
}catch(SQLException e){
// TODO Auto-generated catch block
System.err.println("Model: bad SQL in 'add()'" + e.toString());
return false;
}
return true;
}
public boolean exists(User user){
/* Checks if the user exists */
Debug.log("Model","Checking for login details");
return exists(user.getUsername(), user.getPassword());
}
public boolean exists(String username, String password){
/* Checks if the user exists */
String query = "select username from Usertable where username=? and password=?";
PreparedStatement ps;
try{
ps = connection.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);
Debug.log("Model","connecting with usr: "+username+" pwd: "+password);
ResultSet rs = ps.executeQuery();
if(rs.next()) return true;
// a user with those login details was found
}catch(SQLException e){
// TODO Auto-generated catch block
System.err.println("Model: bad SQL in 'exists()'" + e.toString());
}
return false;
}
public void updateScore(User user, int score){
/* Adds the new score to the user's existing score */
updateScore(user.getUsername(), score);
}
public void updateScore(String username, int score){
/* Adds the new score to the user's existing score */
String query = "update Usertable SET scores=? WHERE username = ?";
PreparedStatement ps;
try{
ps = connection.prepareStatement(query);
ps.setInt(1, score);
ps.setString(2, username);
ps.executeUpdate();
}catch(SQLException e){
// TODO Auto-generated catch block
System.err.println("Model: bad SQL in 'update()'" + e.toString());
}
}
public int getScore(User user){
/* Returns the current score of the user */
return getScore(user.getUsername());
}
public int getScore(String username){
/* Returns the current score of the user */
String query = "select scores from Usertable where username=?";
PreparedStatement ps;
try{
ps = connection.prepareStatement(query);
ps.setString(1, username);
ResultSet rs = ps.executeQuery();
if(rs.next()){
return rs.getInt(1);
}
// a user with those login details was found
}catch(SQLException e){
// TODO Auto-generated catch block
System.err.println("Model: bad SQL in 'exists()'" + e.toString());
}
return 0;
}
}
| [
"pulkitkarwal@gmail.com"
] | pulkitkarwal@gmail.com |
c48c24e7ef54d4c60632bf1881e845f73d066c9e | 53353da47dcc7a2925cd6e9f0c5e4564121a7620 | /src/com/servlet/TestServlet2.java | 15efa80cbb7523c795d311d3dbb4e1d95af1cbd8 | [] | no_license | sazxv1124/JSPBasic | 2b614f9f98be9db6d9d9f9e20b07f17cbd5af28e | f74319aad172256a84ee84e026f4a234761b21c2 | refs/heads/master | 2023-01-12T10:28:56.275744 | 2020-11-11T02:24:32 | 2020-11-11T02:24:32 | 311,839,759 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 848 | java | package com.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//2. web.xml에 선언하는 방식으로 연결
public class TestServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestServlet2() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("web.xml에 설정방식");
//인터넷의 주소에서 변수값이 눈에 보인다.
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
| [
"sazxv1124@naver.com"
] | sazxv1124@naver.com |
292048948950e1f7d8820fc21c7ead146a810433 | fc44ec04d6cf6bfe6d1d827cb3ac710100646bc9 | /src/com/code/course/command/CommandPatternTest.java | eb2c392913e48bfa53fd922aa6e34feebf24bee7 | [] | no_license | t-c-y/DesignPattern | d07df2835cb82c6d4270f88b4cb9510cbc1b139c | 9e5646fc41dfe63f2744e7114688b2ee7a11f40c | refs/heads/master | 2023-04-19T13:59:10.212726 | 2021-05-08T03:51:45 | 2021-05-08T03:51:45 | 322,167,729 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,250 | java | package com.code.course.command;
/**
* 命令模式
* @author tongchengyu
*/
public class CommandPatternTest {
public interface Command {
void execute();
}
public static class CommandA implements Command {
@Override
public void execute() {
System.out.println("A逻辑");
}
}
public static class CommandB implements Command {
@Override
public void execute() {
System.out.println("B逻辑");
}
}
public static class Invoker {
private Command command;
public Command getCommand() {
return command;
}
public void setCommand(Command command) {
this.command = command;
}
public void execute() {
System.out.println("执行命令之前");
command.execute();
System.out.println("执行命令之后");
}
}
public static void main(String[] args) {
Command commandA = new CommandA();
Command commandB = new CommandB();
Invoker invoker = new Invoker();
invoker.setCommand(commandA);
invoker.execute();
invoker.setCommand(commandB);
invoker.execute();
}
}
| [
"1429920627@qq.com"
] | 1429920627@qq.com |
e4d57bd4f56f9a264f714fbe645a51cd4209d10e | 93fea2295193c18903a1fdbffd847508f42d11c8 | /app/Global.java | 53bf269187c4d3d4f8a9e11e3a32d6c6ba6ac51d | [
"Apache-2.0"
] | permissive | gtrefs/majug-play | 579b02b50dba8ad9a3319651bde76f5fb97bac5d | a425cbb0eabfa12f95bac9664d672a7efb57ce5b | refs/heads/master | 2020-12-30T14:56:14.302549 | 2015-02-09T18:56:34 | 2015-02-14T23:39:38 | 30,801,350 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 606 | java | import models.Entry;
import play.Application;
import play.GlobalSettings;
public class Global extends GlobalSettings {
@Override
public void onStart(Application appliction) {
if(firstRun()){
addSeedEntries();
}
super.onStart(appliction);
}
private boolean firstRun() {
return Entry.isEmpty();
}
private void addSeedEntries() {
saveEntry("First entry", "New blog. A lot of fun.");
saveEntry("Second: Talk about play", "A lot of technical details.");
}
private void saveEntry(String title, String message) {
final Entry entry = new Entry(title, message);
entry.save();
}
}
| [
"Gregor.Trefs@gmail.com"
] | Gregor.Trefs@gmail.com |
f1fe0807cfb5b156077244de8e4d5defbf377c11 | ba7a30d323033dd3d1fffb91f35b982df734f49b | /app/src/main/java/saberapplications/pawpads/databinding/BindableDouble.java | 589b0b758198fe0cdf36d46bcd9cb3e8ca4ec181 | [] | no_license | castaway2000/PawpadsAndroid | 2daad91d5f3dcddae876ab22e635d26e4df489b2 | 3be32fa322e983176cc9a186b8cf6b0a61095ec5 | refs/heads/master | 2021-09-03T15:24:26.986369 | 2018-01-10T03:12:28 | 2018-01-10T03:12:28 | 77,206,201 | 3 | 0 | null | 2018-01-10T03:51:02 | 2016-12-23T07:14:11 | Java | UTF-8 | Java | false | false | 2,887 | java | package saberapplications.pawpads.databinding;
import android.databinding.BaseObservable;
import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import saberapplications.pawpads.R;
/**
* Created by Stanislav Volnjanskij on 25.08.16.
*/
public class BindableDouble extends BaseObservable {
private Double value;
private String format="%f";
public Double get() {
return value;
}
public void set(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
notifyChange();
}
}
public void setSilent(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
}
}
public BindableDouble(double value) {
super();
this.value = value;
}
public BindableDouble() {
super();
}
@BindingConversion
public static String convertIntegerToString(BindableDouble value) {
if (value != null && value.get()!=null)
return String.format(value.getFormat(), value.get());
else {
return null;
}
}
@BindingAdapter({"binding2way"})
public static void bindEditText(EditText view,
final BindableDouble bindableDouble) {
if (view.getTag(R.id.BIND_ID) == null) {
view.setTag(R.id.BIND_ID, true);
view.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
bindableDouble.setSilent(Double.parseDouble(s.toString()));
} catch (Exception e) {
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
//initial value
if (bindableDouble == null) return;
Double newValue = bindableDouble.get();
if (newValue == null) return;
String strValue= String.format(bindableDouble.getFormat(),newValue);
if (!view.getText().toString().equals(strValue) ) {
view.setText(strValue);
}
}
/**
* Number format to display in text field
* @return
*/
public String getFormat() {
return format;
}
/**
*Set number format to display in text field
* @param format
*/
public void setFormat(String format) {
this.format = format;
}
}
| [
"stas@kultprosvet.net"
] | stas@kultprosvet.net |
0451694e4076e597e73f37b69f74ca1ad635468b | 8cbc6d13b05e4ccfde845fd2962ed3cb57da209a | /src/Entorno/Entorno.java | 3b61564cc9da377e6a10e1ad3ea3dffb920958db | [] | no_license | EdsonArmando/OLC2-Proyecto_1 | 7667e599984edf3e0130b81da84879efa3c3d300 | 7aecd29dba9ac52464fcec93fcd6136f5ec20565 | refs/heads/master | 2023-03-10T17:01:47.451362 | 2020-04-01T05:01:56 | 2020-04-01T05:01:56 | 242,906,444 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,364 | java | /*
* 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 Entorno;
import Estructuras.Singleton;
import Instruccion.Funcion;
import Views.Inicio;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
/**
*
* @author EG
*/
public class Entorno {
Entorno anterior;
public HashMap<String,Simbolo> tabla;
public Entorno(Entorno anterior){
this.tabla=new HashMap<>();
this.anterior=anterior;
}
public void insertar(String nombre, Simbolo valor){
if (this.tabla.containsKey(nombre)) {
modificarVariable(nombre,valor);
return;
}
this.tabla.put(nombre, valor);
}
public boolean existeVariable(String nombre,Entorno ent){
boolean existe = false;
if(ent.tabla.containsKey(nombre)){
return true;
}else if(ent.anterior!=null){
existe = existeVariable(nombre,ent.anterior);
return existe;
}
return existe;
}
public Simbolo obtener(String nombre,Entorno ent){
Simbolo sim =null;
if (ent.tabla.containsKey(nombre)) {
sim = ent.tabla.get(nombre);
return sim;
}else if(ent.anterior!=null){
sim =obtener(nombre,ent.anterior);
}else{
Inicio.salidaConsola.append("No existe la variable");
}
return sim;
}
public void modificarVariable(String nombre, Simbolo valor){
tabla.put(nombre, valor);
}
public void graficarTabla() throws IOException{
FileWriter archivo = new FileWriter("Entorno.html");
HashMap<String,Funcion> funciones=Singleton.getInstance().getTabla();
int cont=1;
archivo.write("<html>");
archivo.write("<head>");
archivo.write("<style>"
+ "table{"
+ " font-family: arial, sans-serif; border-collapse: collapse; width: 100%;}"
+ "td, th{"
+ "border: 1px solid #dddddd;text-align: left; padding: 8px;}"
+ "tr:nth-child(even){"
+ " background-color: #dddddd;}"
+ "</style>");
archivo.write("</head>");
archivo.write("<body>");
archivo.write("<H1>Tabla de Simbolos</H1>");
archivo.write("<br><br>");
archivo.write("<table>");
archivo.write("<tr><th>No</th><th>Nombre</th><th>Tipo</th><th>Ambito</th><th>Tamaño</th></tr>");
for (String key : tabla.keySet()) {
Simbolo sim = tabla.get(key);
archivo.write("<tr><td>" + cont + "</td><td>" + key + "</td><td>" + sim.tipo.toString() + "</td><td>" + "Global" + "</td><td>" + String.valueOf(sim.valor.hashCode()) + "</td></tr>" );
cont++;
}
for(String key : funciones.keySet()){
Funcion func = funciones.get(key);
archivo.write("<tr><td>" + cont + "</td><td>" + key + "</td><td>" + func.tipo.toString() + "</td><td>" + "Global" + "</td><td>" + func.tipo.toString() + "</td></tr>" );
cont++;
}
archivo.write("</table>");
archivo.write("</body>");
archivo.write("</html>");
archivo.close();
}
}
| [
"guixarmando@gmail.com"
] | guixarmando@gmail.com |
8dabfe560d2820ab6d6a563cf96a777736756cb4 | 1eaa888c955c4467e52984aa8ffde5fee6fba53f | /src/com/xl/voteapp/base/BaseListFragment.java | b86f6f926afa724897694b0aa84da469cfbe8047 | [
"Apache-2.0"
] | permissive | ahucsxl/voteApppushsocial910 | ed4da814f65e4efb58d6279f06f5360c7230ecb2 | 31c7a2918ea1d570d2529aba5c75a5bd079e6336 | refs/heads/master | 2021-01-02T09:38:04.884734 | 2015-09-08T00:58:54 | 2015-09-08T00:58:54 | 42,081,301 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,301 | java | package com.xl.voteapp.base;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.http.Header;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.SwipeRefreshLayout;
//import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import butterknife.ButterKnife;
import butterknife.InjectView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.qq.xgdemo.common.NotificationService;
import com.qq.xgdemo.receiver.MessageReceiver;
import com.tencent.android.tpush.XGPushBaseReceiver;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushRegisterResult;
import com.tencent.android.tpush.XGPushShowedResult;
import com.tencent.android.tpush.XGPushTextMessage;
import com.xl.voteapp.R;
import com.xl.voteapp.adapter.AllVoteAdapter;
import com.xl.voteapp.bean.Entity;
import com.xl.voteapp.bean.Item;
import com.xl.voteapp.bean.RecData;
import com.xl.voteapp.bean.User;
import com.xl.voteapp.bean.Vote;
import com.xl.voteapp.cache.CacheManager;
import com.xl.voteapp.common.BroadcastController;
import com.xl.voteapp.common.Contanst;
import com.xl.voteapp.ui.empty.EmptyLayout;
import com.xl.voteapp.upload.DownloadOptionInformation;
import com.xl.voteapp.util.DateUtil;
import com.xl.voteapp.util.GsonRequest;
import com.xl.voteapp.util.TDevice;
import com.xl.voteapp.util.UIHelper;
@SuppressLint("NewApi")
public abstract class BaseListFragment<T extends Entity> extends BaseFragment
implements SwipeRefreshLayout.OnRefreshListener, OnItemClickListener, OnScrollListener {
private ProgressDialog mLoginProgressDialog;
public static final int MESSAGE_STATE_ERROR = -1;
public static final int MESSAGE_STATE_EMPTY = 0;
public static final int MESSAGE_STATE_MORE = 1;
public static final int MESSAGE_STATE_FULL = 2;
public static final int LISTVIEW_ACTION_NONE = -1;// 没有状态
public static final int LISTVIEW_ACTION_UPDATE = 0; // 更新状态,不显示toast
public static final int LISTVIEW_ACTION_INIT = 1;// 初始化时,加载缓存状态
public static final int LISTVIEW_ACTION_REFRESH = 2;// 刷新状态,显示toast
public static final int LISTVIEW_ACTION_SCROLL = 3;// 下拉到底部时,获取下一页的状态
private int mSumData;// 当前页面已加载的数据总和
private int mState = STATE_NONE;// 当前加载状态
private int mListViewAction = LISTVIEW_ACTION_NONE;// UI状态
private int mMessageState = MESSAGE_STATE_MORE;// 当前数据状态,如果是已经全部加载,则不再执行滚动到底部就加载的情况
static final int STATE_NONE = -1;
static final int STATE_LOADING = 0;
static final int STATE_LOADED = 1;
protected EmptyLayout mErrorLayout;
public static final String BUNDLE_KEY_CATALOG = "BUNDLE_KEY_CATALOG";
protected SwipeRefreshLayout mSwipeRefreshLayout;
protected ListView mListView;
private View mFooterView;
private View mFooterProgressBar;
private TextView mFooterTextView;
protected ArrayAdapter<T> mAdapter;
List<Vote> voteList = new ArrayList<Vote>();;
ArrayList<Item> optionList;
private static final int REFRESH_COMPLETE = 0X110;
protected int mStoreEmptyState = -1;
protected int mCurrentPage = 1;
protected int mCatalog = 1;
private User user;
private int uno;
private String messagefull = "false";
private String loading = "false";
private boolean haveCacheData = false;
private final static String APP_CONFIG = "config";
private MsgReceiver updateListViewReceiver;
private MsgClickReceiver updateListViewClickReceiver;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
@SuppressWarnings("unchecked")
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case REFRESH_COMPLETE:
if (!TDevice.hasInternet()) {
Toast.makeText(getActivity(), "无可用网络", Toast.LENGTH_SHORT).show();
return;
}
// requestData(true);
getVoteList(1, LISTVIEW_ACTION_REFRESH);
mAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
break;
case 0:
loading = "false";
RecData recdata = (RecData) msg.obj;
List<Vote> result = recdata.getListvote();
messagefull = recdata.getStateFull();
if (messagefull.equals("true")) {
setFooterFullState();
}
if (msg.arg2 == 1) {
voteList = result;
mAdapter = (ArrayAdapter<T>) new AllVoteAdapter(getActivity(), R.layout.list_cell_news2, voteList);
mListView.setAdapter(mAdapter);
mSumData = result.size();
mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
} else {
mSumData += result.size();
voteList.addAll(result);
}
mAdapter.notifyDataSetChanged();
break;
case 1:
UIHelper.showVoteActivity(getActivity(), voteList.get(msg.arg1).getV_id(),
voteList.get(msg.arg1).getV_title(), voteList.get(msg.arg1).getV_content(), uno, optionList);
break;
case 2:
mErrorLayout.setErrorType(EmptyLayout.NODATA);
break;
}
};
};
private BroadcastReceiver mUserChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (!AppContext.login) {
user = null;
return;
}
new AsyncTask<Void, Void, User>() {
@Override
protected User doInBackground(Void... params) {
user = getLoginInfo();
return user;
}
@Override
protected void onPostExecute(User user) {
uno = user.getU_no();
}
}.execute();
}
};
/**
* 获取登录信息
*
* @return
*/
public User getLoginInfo() {
User user = new User();
user.setU_no(Integer.valueOf(getProperty(Contanst.PROP_KEY_UNO)));
user.setU_name(getProperty(Contanst.PROP_KEY_UNAME));
user.setU_pwd(getProperty(Contanst.PROP_KEY_UPWD));
user.setU_email(getProperty(Contanst.ROP_KEY_UEMAIL));
user.setU_tel(getProperty(Contanst.ROP_KEY_UTEL));
user.set_portrait(getProperty(Contanst.ROP_KEY_PORTRAIT));
return user;
}
public String getProperty(String key) {
String res = get(key);
return res;
}
public String get(String key) {
Properties props = get();
return (props != null) ? props.getProperty(key) : null;
}
public Properties get() {
FileInputStream fis = null;
Properties props = new Properties();
try {
File dirConf = getActivity().getApplication().getDir(APP_CONFIG, Context.MODE_PRIVATE);
fis = new FileInputStream(dirConf.getPath() + File.separator + APP_CONFIG);
props.load(fis);
} catch (Exception e) {
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
return props;
}
@Override
protected int getLayoutId() {
return R.layout.fragment_pull_refresh_listview;
}
@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mFooterView = inflater.inflate(R.layout.list_cell_footer, null);
mFooterProgressBar = mFooterView.findViewById(R.id.progressbar);
mFooterTextView = (TextView) mFooterView.findViewById(R.id.listview_foot_more);
View view = inflater.inflate(getLayoutId(), container, false);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.inject(this, view);
mErrorLayout = (EmptyLayout) view.findViewById(R.id.error_layout);
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefreshlayout);
mListView = (ListView) view.findViewById(R.id.listview);
mListView.setOnScrollListener(this);
mListView.setOnItemClickListener(this);
mListView.addFooterView(mFooterView);
initView(view);
requestData(false);
}
@Override
public void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
mCatalog = args.getInt(BUNDLE_KEY_CATALOG, 0);
}
// 0.注册数据更新监听器
updateListViewReceiver = new MsgReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.qq.xgdemo.activity.UPDATE_LISTVIEW");
getActivity().registerReceiver(updateListViewReceiver, intentFilter);
// 1.注册数据点击监听器
updateListViewClickReceiver = new MsgClickReceiver();
IntentFilter intentFilterclick = new IntentFilter();
intentFilterclick.addAction("com.qq.xgdemo.activity.UPDATE_LISTVIEW_CLICK");
getActivity().registerReceiver(updateListViewClickReceiver, intentFilterclick);
}
@Override
public void initView(View view) {
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.swiperefresh_color1, R.color.swiperefresh_color2,
R.color.swiperefresh_color3, R.color.swiperefresh_color4);
mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// mState = STATE_REFRESH;
// Log.i("mErrorLayout", "mErrorLayoutclick");
mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
if (TDevice.hasInternet()) {
getVoteList(1, LISTVIEW_ACTION_INIT);
} else
mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
}
});
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
BroadcastController.registerUserChangeReceiver(activity, mUserChangeReceiver);
}
@Override
public void onDetach() {
super.onDetach();
BroadcastController.unregisterReceiver(getActivity(), mUserChangeReceiver);
getActivity().unregisterReceiver(updateListViewReceiver);
getActivity().unregisterReceiver(updateListViewClickReceiver);
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroy() {
super.onDestroy();
}
protected abstract ArrayAdapter<T> getListAdapter();
// 下拉刷新数据
@Override
public void onRefresh() {
mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 2000);
}
protected boolean requestDataIfViewCreated() {
return true;
}
protected String getCacheKeyPrefix() {
String type = "AllVote";
return type;
}
public void beforeLoading(int action) {
// 开始加载
mState = STATE_LOADING;
if (action == LISTVIEW_ACTION_REFRESH) {
// setSwipeRefreshLoadingState();
} else if (action == LISTVIEW_ACTION_SCROLL) {
setFooterLoadingState();
}
}
private String getCacheKey() {
return new StringBuilder(getCacheKeyPrefix()).append("_").append(mCurrentPage).toString();
}
/***
* 判断是否需要读取缓存的数据
*
* @author 火蚁 2015-2-10 下午2:41:02
*
* @return boolean
* @param refresh
* @return
*/
protected boolean isReadCacheData(boolean refresh) {
String key = getCacheKey();
if (!TDevice.hasInternet()) {
return true;
}
// 第一页若不是主动刷新,缓存存在,优先取缓存的
if (CacheManager.isExistDataCache(getActivity(), key) && !refresh && mCurrentPage == 1) {
return true;
}
// 其他页数的,缓存存在以及还没有失效,优先取缓存的
if (CacheManager.isExistDataCache(getActivity(), key) && !CacheManager.isCacheDataFailure(getActivity(), key)
&& mCurrentPage != 1) {
return true;
}
return false;
}
private class SaveCacheTask extends AsyncTask<Void, Void, RecData> {
private final WeakReference<Context> mContext;
private final Serializable seri;
private final String key;
private SaveCacheTask(Context context, Serializable seri, String key) {
mContext = new WeakReference<Context>(context);
this.seri = seri;
this.key = key;
}
@Override
protected RecData doInBackground(Void... params) {
CacheManager.saveObject(mContext.get(), seri, key);
return null;
}
}
private class CacheTask extends AsyncTask<String, Void, Void> {
private final WeakReference<Context> mContext;
private CacheTask(Context context) {
mContext = new WeakReference<Context>(context);
}
@Override
protected Void doInBackground(String... params) {
return null;
}
@Override
protected void onPostExecute(Void list) {
}
}
public void getVoteList(final int page, final int action) {
beforeLoading(action);
@SuppressWarnings("unused")
boolean refresh = true;
if (action == LISTVIEW_ACTION_INIT) {
refresh = false;
}
GsonRequest<RecData> gsonObjRequest;
final String url = Contanst.URLPATH + "ReceiveVote";
Map<String, String> appendHeader = new HashMap<String, String>();
appendHeader.put("u_no", String.valueOf(0));
appendHeader.put("pageNo", String.valueOf(page));
AppContext.getInstance().addSessionCookie(appendHeader);
gsonObjRequest = new GsonRequest<RecData>(Request.Method.POST, url, RecData.class, null,
new Response.Listener<RecData>() {
@Override
public void onResponse(RecData response) {
try {
RecData recdata = response;
if (recdata == null) {
mHandler.sendEmptyMessage(2);
} else {
new SaveCacheTask(getActivity(), recdata, getCacheKey()).execute();
Message m = new Message();
m.obj = recdata;
m.arg1 = action;
m.arg2 = page;
m.what = 0;
mHandler.sendMessage(m);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading = "fasle";
RecData recdata = null;
try {
String jsonString = new String(
RequestQueueSingleton.getInstance(getActivity()).getRequestQueue().getCache()
.get(url + page).data,
HttpHeaderParser.parseCharset(RequestQueueSingleton.getInstance(getActivity())
.getRequestQueue().getCache().get(url + page).responseHeaders));
Gson mGson = new Gson();
recdata = mGson.fromJson(jsonString, RecData.class);
} catch (Exception e) {
e.printStackTrace();
}
if (recdata == null) {
if (!TDevice.hasInternet()) {
if (haveCacheData) {
setFooterNoInternet();
return;
} else
mErrorLayout.setErrorType(EmptyLayout.NODATA);
}
} else {
haveCacheData = true;
Message m = new Message();
m.obj = recdata;
m.arg1 = action;
m.arg2 = page;
m.what = 0;
mHandler.sendMessage(m);
}
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}
}
}, appendHeader);
RequestQueueSingleton.getInstance(getActivity()).addToRequestQueue(gsonObjRequest);
}
public void getOptionList(final int v_id, final String v_title, final int position) {
if (mLoginProgressDialog == null) {
mLoginProgressDialog = new ProgressDialog(getActivity());
mLoginProgressDialog.setCancelable(true);
mLoginProgressDialog.setCanceledOnTouchOutside(false);
mLoginProgressDialog.setMessage("正在加载投票信息...");
}
if (mLoginProgressDialog != null) {
mLoginProgressDialog.show();
}
optionList = new ArrayList<Item>();
new Thread() {
public void run() {
try {
optionList = DownloadOptionInformation.save(v_title, v_id);
mLoginProgressDialog.dismiss();
Message m = new Message();
m.arg1 = position;
m.what = 1;
mHandler.sendMessage(m);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!TDevice.hasInternet()) {
UIHelper.showVoteActivity(getActivity(), 0, null, null, 0, optionList);
return;
}
if (position < voteList.size())
getOptionList(voteList.get(position).getV_id(), voteList.get(position).getV_title(), position);
}
// 是否需要自动刷新
protected boolean needAutoRefresh() {
return true;
}
/***
* 获取列表数据
*
*
* @author 火蚁 2015-2-9 下午3:16:12
*
* @return void
* @param refresh
*/
protected void requestData(boolean refresh) {
String key = getCacheKey();
if (isReadCacheData(refresh)) {
readCacheData(key);
} else {
// 取新的数据
sendRequestData();
}
}
private void readCacheData(String cacheKey) {
RecData recdata = (RecData) CacheManager.readObject(getActivity(), getCacheKey());
if (recdata == null) {
if (!TDevice.hasInternet()) {
if (!haveCacheData)
mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
}
} else {
Message m = new Message();
m.obj = recdata;
// m.arg1 = action;
m.arg2 = 1;
m.what = 0;
mHandler.sendMessage(m);
}
}
/***
* 自动刷新的时间
*
* 默认:自动刷新的时间为半天时间
*
* @author 火蚁 2015-2-9 下午5:55:11
*
* @return long
* @return
*/
protected long getAutoRefreshTime() {
return 12 * 60 * 60;
}
@Override
public void onResume() {
super.onResume();
}
protected void sendRequestData() {
getVoteList(1, LISTVIEW_ACTION_INIT);
}
/**
* 是否需要隐藏listview,显示无数据状态
*
* @author 火蚁 2015-1-27 下午6:18:59
*
*/
protected boolean needShowEmptyNoData() {
return true;
}
protected boolean compareTo(List<? extends Entity> data, Entity enity) {
int s = data.size();
if (enity != null) {
for (int i = 0; i < s; i++) {
if (enity.getId() == data.get(i).getId()) {
return true;
}
}
}
return false;
}
protected void onRefreshNetworkSuccess() {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mAdapter == null || mAdapter.getCount() == 0) {
return;
}
if (messagefull.equals("true") || loading.equals("true"))
return;
boolean scrollEnd = false;
try {
if (view.getPositionForView(mFooterView) == view.getLastVisiblePosition()) {
scrollEnd = true;
}
} catch (Exception e) {
scrollEnd = false;
}
if (scrollEnd) {
onLoadNextPage();
}
}
/** 加载下一页 */
protected void onLoadNextPage() {
int pageIndex = mSumData / 20 + 1;
mCurrentPage = pageIndex;
loadList(pageIndex, LISTVIEW_ACTION_SCROLL);
}
/**
* 加载数据
*
* @param page
* 页码
* @param action
* 加载的触发事件
*/
void loadList(int page, int action) {
mListViewAction = action;
getVoteList(page, action);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
/** 设置底部已加载全部的状态 */
void setFooterFullState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.GONE);
mFooterTextView.setText(R.string.load_full);
}
}
/** 设置底部无数据的状态 */
void setFooterNoMoreState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.GONE);
mFooterTextView.setText(R.string.load_empty);
}
}
/** 设置底部加载中的状态 */
void setFooterLoadingState() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.VISIBLE);
mFooterTextView.setText(R.string.load_ing);
loading = "true";
}
}
/** 设置底部无网络连接的状态 */
void setFooterNoInternet() {
if (mFooterView != null) {
mFooterProgressBar.setVisibility(View.GONE);
mFooterTextView.setText(R.string.tip_network_error);
}
}
public class MsgReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 0);
}
}
public class MsgClickReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
}
| [
"ahucsxl@126.com"
] | ahucsxl@126.com |
ba11b0dfd4280e8c5a5528e165079c521ddda4cb | 86b3cc076b5f92c409b5a0d56da945c44eea8ca8 | /app/src/main/java/g2evolution/Boutique/entit/Cancelled_Orders_List.java | 9cdfe0f693c73ed4c581e3123d73ad7185d8f5e1 | [] | no_license | G2EvolutionNarayana/ZigziVendor | edb5e0008ba0a256e78dea4f8f0377d63c8ae58a | 0711d1e166cac149de829979e76d441da290ab10 | refs/heads/master | 2022-12-13T00:20:25.118682 | 2020-06-24T05:13:50 | 2020-06-24T05:13:50 | 274,578,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,116 | java | package g2evolution.Boutique.entit;
public class Cancelled_Orders_List {
String id;
String name;
String order_number;
String order_date;
String delivery_date;
Integer image;
public String getOrder_number() {
return order_number;
}
public void setOrder_number(String order_number) {
this.order_number = order_number;
}
public String getOrder_date() {
return order_date;
}
public void setOrder_date(String order_date) {
this.order_date = order_date;
}
public String getDelivery_date() {
return delivery_date;
}
public void setDelivery_date(String delivery_date) {
this.delivery_date = delivery_date;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getImage() {
return image;
}
public void setImage(Integer image) {
this.image = image;
}
}
| [
"janardhan.srit@gmail.com"
] | janardhan.srit@gmail.com |
6c6f9273432394ebdee349c6576fcf5b43ff42b8 | 2389c74db73c2b7f3cab5bacf8a54ea481139eff | /Music_player/app/build/generated/source/r/debug/android/support/v4/R.java | cbdcfd6d7b52f94718be0a7d67a86d1d9ba76735 | [] | no_license | Rajatverma8960/Android_Programs | dd4ae4e3775827a49eb060a3aa85632a90cbc58d | 3a55a1c4c0379be57eda195d1879f2d3be6b179a | refs/heads/master | 2020-04-13T04:26:06.507099 | 2018-12-24T07:25:24 | 2018-12-24T07:25:24 | 162,961,550 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,585 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.v4;
public final class R {
public static final class attr {
public static final int font = 0x7f020070;
public static final int fontProviderAuthority = 0x7f020072;
public static final int fontProviderCerts = 0x7f020073;
public static final int fontProviderFetchStrategy = 0x7f020074;
public static final int fontProviderFetchTimeout = 0x7f020075;
public static final int fontProviderPackage = 0x7f020076;
public static final int fontProviderQuery = 0x7f020077;
public static final int fontStyle = 0x7f020078;
public static final int fontWeight = 0x7f020079;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f030000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f04003e;
public static final int notification_icon_bg_color = 0x7f04003f;
public static final int notification_material_background_media_default_color = 0x7f040040;
public static final int primary_text_default_material_dark = 0x7f040045;
public static final int ripple_material_light = 0x7f04004a;
public static final int secondary_text_default_material_dark = 0x7f04004b;
public static final int secondary_text_default_material_light = 0x7f04004c;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f05004a;
public static final int compat_button_inset_vertical_material = 0x7f05004b;
public static final int compat_button_padding_horizontal_material = 0x7f05004c;
public static final int compat_button_padding_vertical_material = 0x7f05004d;
public static final int compat_control_corner_material = 0x7f05004e;
public static final int notification_action_icon_size = 0x7f050058;
public static final int notification_action_text_size = 0x7f050059;
public static final int notification_big_circle_margin = 0x7f05005a;
public static final int notification_content_margin_start = 0x7f05005b;
public static final int notification_large_icon_height = 0x7f05005c;
public static final int notification_large_icon_width = 0x7f05005d;
public static final int notification_main_column_padding_top = 0x7f05005e;
public static final int notification_media_narrow_margin = 0x7f05005f;
public static final int notification_right_icon_size = 0x7f050060;
public static final int notification_right_side_padding_top = 0x7f050061;
public static final int notification_small_icon_background_padding = 0x7f050062;
public static final int notification_small_icon_size_as_large = 0x7f050063;
public static final int notification_subtext_size = 0x7f050064;
public static final int notification_top_pad = 0x7f050065;
public static final int notification_top_pad_large_text = 0x7f050066;
}
public static final class drawable {
public static final int notification_action_background = 0x7f060058;
public static final int notification_bg = 0x7f060059;
public static final int notification_bg_low = 0x7f06005a;
public static final int notification_bg_low_normal = 0x7f06005b;
public static final int notification_bg_low_pressed = 0x7f06005c;
public static final int notification_bg_normal = 0x7f06005d;
public static final int notification_bg_normal_pressed = 0x7f06005e;
public static final int notification_icon_background = 0x7f06005f;
public static final int notification_template_icon_bg = 0x7f060060;
public static final int notification_template_icon_low_bg = 0x7f060061;
public static final int notification_tile_bg = 0x7f060062;
public static final int notify_panel_notification_icon_bg = 0x7f060063;
}
public static final class id {
public static final int action0 = 0x7f070007;
public static final int action_container = 0x7f07000f;
public static final int action_divider = 0x7f070011;
public static final int action_image = 0x7f070012;
public static final int action_text = 0x7f070018;
public static final int actions = 0x7f070019;
public static final int async = 0x7f07001f;
public static final int blocking = 0x7f070022;
public static final int cancel_action = 0x7f070025;
public static final int chronometer = 0x7f070028;
public static final int end_padder = 0x7f070032;
public static final int forever = 0x7f070035;
public static final int icon = 0x7f070038;
public static final int icon_group = 0x7f070039;
public static final int info = 0x7f07003c;
public static final int italic = 0x7f07003d;
public static final int line1 = 0x7f07003e;
public static final int line3 = 0x7f07003f;
public static final int media_actions = 0x7f070044;
public static final int normal = 0x7f07004a;
public static final int notification_background = 0x7f07004b;
public static final int notification_main_column = 0x7f07004c;
public static final int notification_main_column_container = 0x7f07004d;
public static final int right_icon = 0x7f070055;
public static final int right_side = 0x7f070056;
public static final int status_bar_latest_event_content = 0x7f070072;
public static final int text = 0x7f070077;
public static final int text2 = 0x7f070078;
public static final int time = 0x7f07007b;
public static final int title = 0x7f07007c;
}
public static final class integer {
public static final int cancel_button_image_alpha = 0x7f080002;
public static final int status_bar_notification_info_maxnum = 0x7f080004;
}
public static final class layout {
public static final int notification_action = 0x7f09001c;
public static final int notification_action_tombstone = 0x7f09001d;
public static final int notification_media_action = 0x7f09001e;
public static final int notification_media_cancel_action = 0x7f09001f;
public static final int notification_template_big_media = 0x7f090020;
public static final int notification_template_big_media_custom = 0x7f090021;
public static final int notification_template_big_media_narrow = 0x7f090022;
public static final int notification_template_big_media_narrow_custom = 0x7f090023;
public static final int notification_template_custom_big = 0x7f090024;
public static final int notification_template_icon_group = 0x7f090025;
public static final int notification_template_lines_media = 0x7f090026;
public static final int notification_template_media = 0x7f090027;
public static final int notification_template_media_custom = 0x7f090028;
public static final int notification_template_part_chronometer = 0x7f090029;
public static final int notification_template_part_time = 0x7f09002a;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0c0021;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f0d00fa;
public static final int TextAppearance_Compat_Notification_Info = 0x7f0d00fb;
public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f0d00fc;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0d00fd;
public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f0d00fe;
public static final int TextAppearance_Compat_Notification_Media = 0x7f0d00ff;
public static final int TextAppearance_Compat_Notification_Time = 0x7f0d0100;
public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f0d0101;
public static final int TextAppearance_Compat_Notification_Title = 0x7f0d0102;
public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f0d0103;
public static final int Widget_Compat_NotificationActionContainer = 0x7f0d016b;
public static final int Widget_Compat_NotificationActionText = 0x7f0d016c;
}
public static final class styleable {
public static final int[] FontFamily = { 0x7f020072, 0x7f020073, 0x7f020074, 0x7f020075, 0x7f020076, 0x7f020077 };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x7f020070, 0x7f020078, 0x7f020079 };
public static final int FontFamilyFont_font = 0;
public static final int FontFamilyFont_fontStyle = 1;
public static final int FontFamilyFont_fontWeight = 2;
}
}
| [
"rajat@kritter.in"
] | rajat@kritter.in |
8158137ce4b8f1b4302c7fd6ecfb09351353a4ba | 5a509a102c6532f471f99a4de7dd9eb5411b8de1 | /src/section4Statements/AreaCalculator.java | 5aca19f6c4ad399518edbd80d10e311af53524d6 | [] | no_license | Gunasekar006/javahandson | f3a396e81c71073ef2306300a0ac33c0a5e30cd9 | 8a7b1688a6a9bb9322814419d39b7a9d4cf4b496 | refs/heads/master | 2020-06-10T21:35:58.840940 | 2019-07-22T11:57:04 | 2019-07-22T11:57:04 | 193,757,403 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 678 | java | package section4Statements;
public class AreaCalculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(area(5.0));
System.out.println(area(-1.0));
System.out.println(area(4.0,5.0));
System.out.println(area(-1.0,8));
}
public static double area(double radius){
if(radius>=0){
double pi=Math.PI;
double cicrleArea=radius*radius*pi;
return cicrleArea;
}
return -1;
}
public static double area(double x,double y){
if(x>=0 && y>=0) {
return x*y;
}
return -1;
}
}
| [
"gkumarasamy@altimetrik.com"
] | gkumarasamy@altimetrik.com |
1b2b8e15e1857d0091136988ecb9306bf681d3ec | 066fedb6ddeafd9828aa2793e14665c072a2f192 | /src/main/java/com/gqcp/common/wechat/menu/RuleMenu.java | ef051fbb96aa292dd0dea6343ae38ddcdaae621a | [] | no_license | wyqtomorrow/ybsd_web_framework | f78698bb9211fea793e25cf9f600dc2cf87c02ca | 36e712efa0f74395c7a0b1609f1ad5493c887b77 | refs/heads/master | 2021-01-22T19:08:54.080913 | 2017-03-23T11:06:18 | 2017-03-23T11:06:18 | 85,166,810 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 629 | java | package com.gqcp.common.wechat.menu;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* 个性化菜单
* @borball on 6/7/2016.
*/
public class RuleMenu extends Menu {
@JsonProperty("matchrule")
private Rule rule;
public Rule getRule() {
return rule;
}
public void setRule(Rule rule) {
this.rule = rule;
}
@JsonProperty("menuid")
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public RuleMenu rule(Rule rule) {
this.setRule(rule);
return this;
}
}
| [
"wyq_tomorrow@163.com"
] | wyq_tomorrow@163.com |
683560c8527434d63fa46de6ec541750661614d9 | d6d31438d841f0c0e01356cbd4fd5c3fe906cd78 | /src/main/java/com/logicalsapien/joan/model/CategoryDto.java | 003141d31bd75461def5cdc8847bb52ba9d52eb9 | [
"MIT"
] | permissive | LogicalSapien/JoAn | 32c4ec1d84e161b82dd8af2a0be78639c84a36ab | 7942feb0da95dc02f4f9c87cf2ecba53e734b220 | refs/heads/master | 2023-06-13T23:04:17.785282 | 2021-07-09T12:00:54 | 2021-07-09T12:00:54 | 277,667,597 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 219 | java | package com.logicalsapien.joan.model;
import lombok.Data;
/**
* Category Details.
*/
@Data
public class CategoryDto {
/**
* Tag.
*/
private String tag;
/**
* Label.
*/
private String label;
}
| [
"elmoyeldo@gmail.com"
] | elmoyeldo@gmail.com |
ca837fe8d0049aa459088a37a35be5bd8bfaaea6 | 0e3abed308e8ab896732e56ccdfca5e0937f60d8 | /src/healthyhome/bean/Role.java | 96393ce9e25a44d0bc6c67cfec7bbf2f33c80c68 | [] | no_license | luofuyun/healthy_home | 4102cd8a2940278b4205125450716175ff96a87d | 6cef0e8ab518515c7e6e2eebd5f8f48c0dbf220d | refs/heads/master | 2021-01-18T23:43:01.332760 | 2016-07-23T00:37:53 | 2016-07-23T00:37:53 | 53,680,228 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 934 | java | package healthyhome.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@Entity
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Table(name = "role")
public class Role extends BaseEntity {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "role_name")
private String roleName;
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
}
| [
"asus@user"
] | asus@user |
37f52114133df3fee5cfe0e96f49233a3fda41aa | 41b843030fda5e84c7764bb41fd1a81738e51f01 | /testVipCustomer.java | 7b3642d6da80d4707e1b9010ca40bbdfc3a82774 | [] | no_license | AshwinBhatSuri/JavaLearning_archive | 02ba07bc5dd6fd7d3b695d6e515374c14f898d33 | 58309aa8b40e47ed64589174afa090559840e35b | refs/heads/master | 2022-12-30T15:55:45.365655 | 2020-10-24T08:43:10 | 2020-10-24T08:43:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 628 | java | public class testVipCustomer {
private String name;
private long limit;
private String email;
public testVipCustomer() {
this("Ashwin",100000,"ashwin@email.com");
}
public testVipCustomer(long limit, String email) {
this("Ashwin",limit,email);
}
public testVipCustomer(String name, long limit, String email) {
this.name = name;
this.limit = limit;
this.email = email;
}
public String getName() {
return name;
}
public long getLimit() {
return limit;
}
public String getEmail() {
return email;
}
}
| [
"ashwinbhatsuri@Ashwins-MacBook-Pro.local"
] | ashwinbhatsuri@Ashwins-MacBook-Pro.local |
2f67a7e6fe5eee9318a79e94578d6f465921b344 | 32c387fc3e714a40574573dc0281ad3281d709df | /src/main/java/org/hibernate/sqm/query/predicate/InPredicate.java | 65f337a8da8a76db85b6fde82d20ac5b83b8f83c | [
"Apache-2.0"
] | permissive | avijra/hibernate-semantic-query | 1e9070c01ca04368df88215544333adf425c648e | d5b8e165fb7b64fe179835e6b65ede4532562225 | refs/heads/master | 2021-01-15T12:25:05.246292 | 2016-03-09T18:52:02 | 2016-03-09T18:52:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 430 | java | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: Apache License, Version 2.0
* See the LICENSE file in the root directory or visit http://www.apache.org/licenses/LICENSE-2.0
*/
package org.hibernate.sqm.query.predicate;
import org.hibernate.sqm.query.expression.Expression;
/**
* @author Steve Ebersole
*/
public interface InPredicate extends NegatablePredicate {
Expression getTestExpression();
}
| [
"steve@hibernate.org"
] | steve@hibernate.org |
597bd7db80ce68394ceaa1160e9af47f4d65e086 | f03450c2e5d5c1eb01a14144b2788a12e9914ae7 | /pet-clinic-data/src/main/java/guru/springframework/sfgpetclinic/model/Pet.java | d949db5361205a27f686a5be3833bf7657769887 | [] | no_license | khalifax2/sfg-pet-clinic | 625a3ce26d1a82e7b04488a7a3662afd566e2e2e | 282599f1d1ef4244bc55fa7253fc4576877d8213 | refs/heads/master | 2023-02-05T19:46:32.582128 | 2020-10-05T00:27:28 | 2020-10-05T00:27:28 | 290,727,462 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,341 | java | package guru.springframework.sfgpetclinic.model;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "pets")
public class Pet extends BaseEntity{
@Column(name = "name")
private String name;
@ManyToOne
@JoinColumn(name = "type_id")
private PetType petType;
@ManyToOne
@JoinColumn(name = "owner_id")
private Owner owner;
@Column(name = "birth_date")
private LocalDate birthDate;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "pet")
private Set<Visit> visits = new HashSet<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PetType getPetType() {
return petType;
}
public void setPetType(PetType petType) {
this.petType = petType;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public Set<Visit> getVisits() {
return visits;
}
public void setVisits(Set<Visit> visits) {
this.visits = visits;
}
}
| [
"echocastro18@gmail.com"
] | echocastro18@gmail.com |
b91889a71139d806f7669576d83ec9b222470127 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/10/10_2b56bc11eba9ae94da8800300ebec138a4b3f926/OrderedListUpdater/10_2b56bc11eba9ae94da8800300ebec138a4b3f926_OrderedListUpdater_s.java | e61af07f60f89df4be00ebddf62312d4c631ce17 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 13,743 | java | package com.todoroo.astrid.subtasks;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import com.todoroo.andlib.data.Property.IntegerProperty;
import com.todoroo.andlib.data.Property.LongProperty;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.core.PluginServices;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.Task;
abstract public class OrderedListUpdater<LIST> {
public OrderedListUpdater() {
DependencyInjectionService.getInstance().inject(this);
}
public interface OrderedListIterator {
public void processTask(long taskId, Metadata metadata);
}
// --- abstract and empty
abstract protected Metadata getTaskMetadata(LIST list, long taskId);
abstract protected IntegerProperty indentProperty();
abstract protected LongProperty orderProperty();
abstract protected LongProperty parentProperty();
abstract protected void iterateThroughList(Filter filter, LIST list, OrderedListIterator iterator);
abstract protected Metadata createEmptyMetadata(LIST list, long taskId);
/**
* @param list
* @param filter
*/
protected void initialize(LIST list, Filter filter) {
//
}
/**
* @param list
*/
protected void beforeIndent(LIST list) {
//
}
/**
* @param list
* @param taskId
* @param metadata
* @param indent
* @param order
*/
protected void beforeSaveIndent(LIST list, long taskId, Metadata metadata, int indent, int order) {
//
}
// --- task indenting
/**
* Indent a task and all its children
*/
public void indent(final Filter filter, final LIST list, final long targetTaskId, final int delta) {
if(list == null)
return;
beforeIndent(list);
final AtomicInteger targetTaskIndent = new AtomicInteger(-1);
final AtomicInteger previousIndent = new AtomicInteger(-1);
final AtomicLong previousTask = new AtomicLong(-1);
final AtomicLong globalOrder = new AtomicLong(-1);
iterateThroughList(filter, list, new OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
if(!metadata.isSaved())
metadata = createEmptyMetadata(list, taskId);
int indent = metadata.containsNonNullValue(indentProperty()) ?
metadata.getValue(indentProperty()) : 0;
long order = globalOrder.incrementAndGet();
metadata.setValue(orderProperty(), order);
if(targetTaskId == taskId) {
// if indenting is warranted, indent me and my children
if(indent + delta <= previousIndent.get() + 1 && indent + delta >= 0) {
targetTaskIndent.set(indent);
metadata.setValue(indentProperty(), indent + delta);
if(parentProperty() != null) {
long newParent = computeNewParent(filter, list,
taskId, indent + delta - 1);
if (newParent == taskId)
metadata.setValue(parentProperty(), Task.NO_ID);
else
metadata.setValue(parentProperty(), newParent);
}
saveAndUpdateModifiedDate(metadata, taskId);
}
} else if(targetTaskIndent.get() > -1) {
// found first task that is not beneath target
if(indent <= targetTaskIndent.get())
targetTaskIndent.set(-1);
else {
metadata.setValue(indentProperty(), indent + delta);
saveAndUpdateModifiedDate(metadata, taskId);
}
} else {
previousIndent.set(indent);
previousTask.set(taskId);
}
if(!metadata.isSaved())
saveAndUpdateModifiedDate(metadata, taskId);
}
});
}
/**
* Helper function to iterate through a list and compute a new parent for the target task
* based on the target parent's indent
* @param list
* @param targetTaskId
* @param newIndent
* @return
*/
private long computeNewParent(Filter filter, LIST list, long targetTaskId, int targetParentIndent) {
final AtomicInteger desiredParentIndent = new AtomicInteger(targetParentIndent);
final AtomicLong targetTask = new AtomicLong(targetTaskId);
final AtomicLong lastPotentialParent = new AtomicLong(-1);
final AtomicBoolean computedParent = new AtomicBoolean(false);
iterateThroughList(filter, list, new OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
if (targetTask.get() == taskId) {
computedParent.set(true);
}
int indent = metadata.getValue(indentProperty());
if (!computedParent.get() && indent == desiredParentIndent.get()) {
lastPotentialParent.set(taskId);
}
}
});
if (lastPotentialParent.get() == -1) return Task.NO_ID;
return lastPotentialParent.get();
}
// --- task moving
/**
* Move a task and all its children to the position right above
* taskIdToMoveto. Will change the indent level to match taskIdToMoveTo.
*
* @param newTaskId task we will move above. if -1, moves to end of list
*/
public void moveTo(Filter filter, LIST list, final long targetTaskId,
final long moveBeforeTaskId) {
if(list == null)
return;
Node root = buildTreeModel(filter, list);
Node target = findNode(root, targetTaskId);
if(target != null && target.parent != null) {
if(moveBeforeTaskId == -1) {
target.parent.children.remove(target);
root.children.add(target);
target.parent = root;
} else {
Node sibling = findNode(root, moveBeforeTaskId);
if(sibling != null && !ancestorOf(target, sibling)) {
int index = sibling.parent.children.indexOf(sibling);
if(target.parent == sibling.parent &&
target.parent.children.indexOf(target) < index)
index--;
target.parent.children.remove(target);
sibling.parent.children.add(index, target);
target.parent = sibling.parent;
}
}
}
traverseTreeAndWriteValues(list, root, new AtomicLong(0), -1);
}
private boolean ancestorOf(Node ancestor, Node descendant) {
if(descendant.parent == ancestor)
return true;
if(descendant.parent == null)
return false;
return ancestorOf(ancestor, descendant.parent);
}
protected static class Node {
public final long taskId;
public Node parent;
public final ArrayList<Node> children = new ArrayList<Node>();
public Node(long taskId, Node parent) {
this.taskId = taskId;
this.parent = parent;
}
}
protected void traverseTreeAndWriteValues(LIST list, Node node, AtomicLong order, int indent) {
if(node.taskId != -1) {
Metadata metadata = getTaskMetadata(list, node.taskId);
if(metadata == null)
metadata = createEmptyMetadata(list, node.taskId);
metadata.setValue(orderProperty(), order.getAndIncrement());
metadata.setValue(indentProperty(), indent);
if(parentProperty() != null)
metadata.setValue(parentProperty(), node.parent.taskId);
saveAndUpdateModifiedDate(metadata, node.taskId);
}
for(Node child : node.children) {
traverseTreeAndWriteValues(list, child, order, indent + 1);
}
}
protected Node findNode(Node node, long taskId) {
if(node.taskId == taskId)
return node;
for(Node child : node.children) {
Node found = findNode(child, taskId);
if(found != null)
return found;
}
return null;
}
protected Node buildTreeModel(Filter filter, LIST list) {
final Node root = new Node(-1, null);
final AtomicInteger previoustIndent = new AtomicInteger(-1);
final AtomicReference<Node> currentNode = new AtomicReference<Node>(root);
iterateThroughList(filter, list, new OrderedListIterator() {
@Override
public void processTask(long taskId, Metadata metadata) {
int indent = metadata.getValue(indentProperty());
int previousIndentValue = previoustIndent.get();
if(indent == previousIndentValue) { // sibling
Node parent = currentNode.get().parent;
currentNode.set(new Node(taskId, parent));
parent.children.add(currentNode.get());
} else if(indent > previousIndentValue) { // child
Node parent = currentNode.get();
currentNode.set(new Node(taskId, parent));
parent.children.add(currentNode.get());
} else { // in a different tree
Node node = currentNode.get().parent;
for(int i = indent; i < previousIndentValue; i++)
node = node.parent;
if(node == null)
node = root;
currentNode.set(new Node(taskId, node));
node.children.add(currentNode.get());
}
previoustIndent.set(indent);
}
});
return root;
}
protected final Task taskContainer = new Task();
protected void saveAndUpdateModifiedDate(Metadata metadata, long taskId) {
if(metadata.getSetValues().size() == 0)
return;
PluginServices.getMetadataService().save(metadata);
taskContainer.setId(taskId);
taskContainer.setValue(Task.MODIFICATION_DATE, DateUtilities.now());
taskContainer.setValue(Task.DETAILS_DATE, DateUtilities.now());
PluginServices.getTaskService().save(taskContainer);
}
// --- task cascading operations
public interface OrderedListNodeVisitor {
public void visitNode(Node node);
}
/**
* Apply an operation only to the children of the task
*/
public void applyToChildren(Filter filter, LIST list, long targetTaskId,
OrderedListNodeVisitor visitor) {
Node root = buildTreeModel(filter, list);
Node target = findNode(root, targetTaskId);
if(target != null)
for(Node child : target.children)
applyVisitor(child, visitor);
}
private void applyVisitor(Node node, OrderedListNodeVisitor visitor) {
visitor.visitNode(node);
for(Node child : node.children)
applyVisitor(child, visitor);
}
/**
* Removes a task from the order hierarchy and un-indent children
* @param filter
* @param list
* @param targetTaskId
*/
public void onDeleteTask(Filter filter, LIST list, final long targetTaskId) {
if(list == null)
return;
Node root = buildTreeModel(filter, list);
Node target = findNode(root, targetTaskId);
if(target != null && target.parent != null) {
int targetIndex = target.parent.children.indexOf(target);
target.parent.children.remove(targetIndex);
for(Node node : target.children)
target.parent.children.add(targetIndex++, node);
}
traverseTreeAndWriteValues(list, root, new AtomicLong(0), -1);
}
// --- utility
public void debugPrint(Filter filter, LIST list) {
iterateThroughList(filter, list, new OrderedListIterator() {
public void processTask(long taskId, Metadata metadata) {
System.err.format("id %d: order %d, indent:%d, parent:%d\n", taskId, //$NON-NLS-1$
metadata.getValue(orderProperty()),
metadata.getValue(indentProperty()),
parentProperty() == null ? -1 : metadata.getValue(parentProperty()));
}
});
}
@SuppressWarnings("nls")
public void debugPrint(Node root, int depth) {
for(int i = 0; i < depth; i++) System.err.print(" + ");
System.err.format("%03d", root.taskId);
System.err.print("\n");
for(int i = 0; i < root.children.size(); i++)
debugPrint(root.children.get(i), depth + 1);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
92070dfac72b2989bcc7c63affb3d89decc0aa2d | c2681d99601ad758dc616ef509b059fda8a99df2 | /src/Operator.java | dd2dde147be0fd4a6d8fee126f941ee8a1c3bf72 | [] | no_license | NguyenQuangAnh5598/Introduction-to-Java | cb901f044e9d88c54cb31c117d8313233a31d076 | 532d99c0e352c1d605527ce31804bb49e4cdef1a | refs/heads/master | 2023-08-11T19:43:12.504698 | 2021-09-17T07:51:01 | 2021-09-17T07:51:01 | 407,452,518 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 444 | java | import java.util.Scanner;
public class Operator {
public static void main(String[] args) {
float width;
float height;
Scanner scanner = new Scanner(System.in);
System.out.println("Nhập width");
width = scanner.nextFloat();
System.out.println("Nhập height");
height = scanner.nextFloat();
float area = width * height;
System.out.println("Area is " + area);
}
}
| [
"quanganh050598@gmail.com"
] | quanganh050598@gmail.com |
09b5943e10f090d784584d78f257dca4ef16b9e3 | 871775fd919023687ed60c54b56bd99ef2f6c88c | /src/netd/async/act/BlockAction.java | 3348a289e99b4ceeae84a0d0702f291908099dfa | [] | no_license | infinity0/netd-utils | 3f7e1935e5e5711f0bbeeeb68007c305dc4aa057 | bab24c4e3479ce083c3b15c7044d45fd90ee8003 | refs/heads/master | 2020-04-07T16:46:36.039578 | 2012-05-24T23:48:37 | 2012-05-24T23:48:37 | 1,658,485 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 984 | java | package netd.async.act;
/**
** An action whose only purpose is to block its parent action from finishing.
**
** This class should only be used by code that handles execution and actions,
** not by user-implemented Task-related code.
**
** TODO(infinity0): if the block takes too long, the Executor may forcibly
** delete it with a TimeoutException.
**
** @see netd.async.task.ExternalTask
*/
class BlockAction extends EternalAction {
BlockAction() {
super();
}
// TODO enforce single parent
// TODO enforce auto-timeout (re-enable delete)
///////////////////////////////////////////////////////////////////////////
// abstract public class Act
///////////////////////////////////////////////////////////////////////////
@Override
public void attach(BaseAction child) {
throw new IllegalStateException("cannot attach() on BlockAction");
}
@Override
public void detach(BaseAction child) {
throw new IllegalStateException("cannot detach() on BlockAction");
}
}
| [
"infinity0@gmx.com"
] | infinity0@gmx.com |
f0fdd88e140f4c684dbc0f32ccff2eee3aaad055 | cdf0c3a99a641073f844f8c83b4b221f96de9266 | /teamcity-plugin-jmh-common/src/main/java/com/presidentio/teamcity/jmh/runner/common/cons/RunFromConst.java | ff11bc4ef53006cefda9b13000043afc2e80f299 | [
"Apache-2.0"
] | permissive | Argonaught/teamcity-plugin-jmh | 0b73fdd040da25fafe1fbbf228ff937694963731 | 2a128ef4e3a3ac12a721ecea2ab5d61ee0e18c79 | refs/heads/master | 2020-12-24T12:40:44.210411 | 2016-06-12T15:15:18 | 2016-06-12T15:15:18 | 61,282,536 | 0 | 0 | null | 2016-06-16T10:04:59 | 2016-06-16T10:04:59 | null | UTF-8 | Java | false | false | 1,206 | java | package com.presidentio.teamcity.jmh.runner.common.cons;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Created by presidentio on 10/28/15.
*/
public class RunFromConst {
public static final String MAVEN = "maven";
public static final String GRADLE = "gradle";
public static final String JAR = "jar";
public static final List<String> RUN_FROMS = Arrays.asList(MAVEN, JAR);
public static final Map<String, String> RUN_FROMS_WITH_DESCRIPTION = new LinkedHashMap<>();
static {
RUN_FROMS_WITH_DESCRIPTION.put(MAVEN, "maven");
RUN_FROMS_WITH_DESCRIPTION.put(GRADLE, "gradle");
RUN_FROMS_WITH_DESCRIPTION.put(JAR, "jar");
}
public String name(String mode) {
return RUN_FROMS_WITH_DESCRIPTION.get(mode);
}
public String getMAVEN() {
return MAVEN;
}
public String getJAR() {
return JAR;
}
public String getGRADLE() {
return GRADLE;
}
public List<String> getRUN_FROMS() {
return RUN_FROMS;
}
public Map<String, String> getRUN_FROMS_WITH_DESCRIPTION() {
return RUN_FROMS_WITH_DESCRIPTION;
}
}
| [
"vgergel@intropro.com"
] | vgergel@intropro.com |
fd2947ad8b9cf45230fcc7e381f9b845b0b6411e | 9851edc7e1c37849f3812e1c27ea3c4c8f7ef86d | /backend/src/main/java/model/AnswerBean.java | 39c73b5b812e7371733754ff5589f25e198b393f | [] | no_license | Daniel700/piVote | bf3dfd37bfecea2706158bc6baf2ff1d725c68f2 | 8a736ca17e3f996defc6121b77f758d8527f2800 | refs/heads/master | 2021-01-25T10:21:06.832696 | 2016-10-27T10:37:37 | 2016-10-27T10:37:37 | 39,636,295 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 692 | java | package model;
import com.googlecode.objectify.annotation.Container;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Subclass;
/**
* Created by Daniel on 07.08.2015.
*/
public class AnswerBean {
private String answerText;
private int answerVotes;
public String getAnswerText() {
return answerText;
}
public void setAnswerText(String answerText) {
this.answerText = answerText;
}
public int getAnswerVotes() {
return answerVotes;
}
public void setAnswerVotes(int answerVotes) {
this.answerVotes = answerVotes;
}
}
| [
"d.baeuml@hotmail.de"
] | d.baeuml@hotmail.de |
99f0fd2e14e61a1f374ac1c922ed884ac5ca6454 | 181c0ce94f31efed2f3a6b9c99b8869e247d7fee | /src/main/java/JavaPractice/leetcode/ValidSquare/Solution.java | c1c4a298f88fe51dace0f06ac640576c6a901fcc | [] | no_license | zizixin/leetcode | 66e6ab85a898adaadfc0f07d2235d3ed8a1887d5 | 247b85ce1b9b328743b67627dc7e28db98302121 | refs/heads/master | 2021-08-19T02:51:18.714738 | 2017-11-24T14:53:24 | 2017-11-24T14:53:24 | 110,817,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,947 | java | package JavaPractice.leetcode.ValidSquare;
public class Solution {
public int[] pointOne;
public int[] pointTwo;
public int[] pointThree;
public int[] pointFour;
public Solution(){
}
public Solution(int[] pointOne,int[] pointTwo,int[] pointThree,int[] pointFour){
this.pointOne = pointOne;
this.pointTwo = pointTwo;
this.pointThree = pointThree;
this.pointFour = pointFour;
}
public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
return new Solution(p1, p2, p3, p4).isValild();
}
public boolean isValild(){
Line[] lines = new Line[6];
lines[0] = new Line(this.pointOne,this.pointTwo);
lines[1] = new Line(this.pointOne,this.pointThree);
lines[2] = new Line(this.pointOne,this.pointFour);
lines[3] = new Line(this.pointTwo,this.pointThree);
lines[4] = new Line(this.pointTwo,this.pointFour);
lines[5] = new Line(this.pointThree,this.pointFour);
double tempLine = lines[0].instance;
double tempDiagonal;
double[] lineArray = new double[6];
for(int i=0;i<lineArray.length;i++){
lineArray[i] = lines[i].instance;
if(lineArray[i]==0.0){
return false;
}
}
double maxLine = lineArray[0];
double odinaryLine = lineArray[1];
for(int i=0;i<5;i++){
if(lineArray[i]<lineArray[i+1]){
maxLine = lineArray[i+1];
odinaryLine = lineArray[i];
break;
}
}
int countMax = 0;
int countOdinarLine = 0;
for(int i=0;i<6;i++){
if(lineArray[i]==maxLine){
countMax++;
}else if(lineArray[i]==odinaryLine){
countOdinarLine++;
}else{
return false;
}
}
System.out.println(countMax);
System.out.println(countOdinarLine);
return true;
}
public static void main(String[] args) {
new Solution().validSquare(new int[]{-1,-1}, new int[]{-1,1}, new int[]{1,-1}, new int[]{1,1});
}
static class Line{
private int [] pointOne;
private int [] pointTwo;
public double instance;
public Line(int [] pointOne,int [] pointTwo){
this.pointOne = pointOne;
this.pointTwo = pointTwo;
this.instance = Math.sqrt(Math.pow(this.pointTwo[0]-this.pointOne[0],2)+Math.pow(this.pointTwo[1]-this.pointOne[1], 2));
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*
*/
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Line)){
return false;
}else{
Line targetLine = (Line)obj;
if(targetLine.pointOne[0]==this.pointOne[0]&&targetLine.pointOne[1]==this.pointOne[1]){
if(targetLine.pointTwo[0]==this.pointTwo[0]&&targetLine.pointTwo[1]==this.pointTwo[1]){
return true;
}else{
return false;
}
}else if(targetLine.pointOne[0]==this.pointOne[0]&&targetLine.pointTwo[1]==this.pointTwo[1]){
if(targetLine.pointTwo[0]==this.pointOne[0]&&targetLine.pointTwo[1]==this.pointOne[1]){
return true;
}else{
return false;
}
}else{
return false;
}
}
}
}
}
| [
"noemail@thankyou.com"
] | noemail@thankyou.com |
90f69b6c51709cd8f812cbe663a6f3be60254d36 | 7523091caca5618c2e4475caf63d6869045de604 | /ime/app/src/main/java/com/anysoftkeyboard/ui/tutorials/VersionChangeLogs.java | b6e2a0926af3a8153a2e239b022aed9936bf0944 | [
"Apache-2.0"
] | permissive | glemco/AnySoftKeyboard | fefc52480350b027d5d22109cba9e5fa0a64410e | 15c52feb5e7e8574886cecc541d4ae4812d65397 | refs/heads/master | 2022-06-24T01:50:57.820437 | 2022-03-20T14:36:09 | 2022-03-21T08:12:27 | 244,155,198 | 0 | 0 | null | 2020-03-01T13:34:34 | 2020-03-01T13:34:34 | null | UTF-8 | Java | false | false | 22,442 | java | package com.anysoftkeyboard.ui.tutorials;
import android.net.Uri;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class VersionChangeLogs {
static List<VersionChangeLog> createChangeLog() {
final List<VersionChangeLog> log = new ArrayList<>();
log.add(
new VersionChangeLog(
1,
11,
"r2",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/94"),
"Several fixes to the settings app navigation.",
"Vibration fixes.",
"Suggestions pick and order fixes.",
"Fixes to pop-up keys order.",
"Gesture-typing supports user-dictionary.",
"Reduced installation size (for supporting devices).",
"Updated translations from the community (at crowdin.net)."));
log.add(
new VersionChangeLog(
1,
11,
"r1",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/93"),
"Minimum Android version is 4.0.3 (ICS, API level 15).",
"Basic support for OS field auto-fill.",
"Better vibration control for newer OS versions.",
"Fixes around permission requests.",
"Fixes for colorized nav-bar.",
"A few small gesture-typing fixes.",
"Other bug fixes.",
"Updated translations from the community."));
log.add(
new VersionChangeLog(
1,
10,
"r4",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/92"),
"Keep safe! #covid19 \uD83D\uDE37",
"Updated emoji to version 13.1 - Android 8.1+",
"So, you just copied some text? Let me suggest pasting it.",
"Wrapping selected text with \"'<>(){}[]*-_`~.",
"Finally, you can decide where the settings backup file should be.",
"People spotted bugs. We slayed them!",
"YABTU.",
"Updated translations from the community."));
log.add(
new VersionChangeLog(
1,
10,
"r3",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/91"),
"Colorized nav-bar on supported devices.",
"Gesture-Typing fixes and improvements.",
"Various fixes around theme setting.",
"Updated build tools.",
"Updated translations."));
log.add(
new VersionChangeLog(
1,
10,
"r2",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/90"),
"Support for image/gif insertion. This is an option in the Emoji popup.",
"Update Emojis to v12.0.",
"Improvements for Gesture-Typing. Thanks to Philipp Fischbeck.",
"New themes.",
"Updated localization: AR, DE, ES-MX, EU, KMR, LT, RU, TR, UK"));
log.add(
new VersionChangeLog(
1,
10,
"r1",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/89"),
"Keyboard colors will adapt to used app. Enable this in Themes settings.",
"Night Mode - if enabled, keyboard and app will use dark theme.",
"Power Saving mode tweaks.",
"Updated build-tools (smaller binary now).",
"Halmak layout for English.",
"Updated localization: AR, BE, BG, DE, EO, EU, ES, ES-MX, FR, IT, IW (HE), KMR, KU, NB, PT, SC, SK, TR."));
log.add(
new VersionChangeLog(
1,
9,
"r6",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/88"),
"➿ Gesture-Typing is here! As BETA. You'll need to enable it in Settings if you want to try it out.",
"Honoring IME_FLAG_NO_PERSONALIZED_LEARNING and PASSWORD as Incognito - if an app ask us not to remember stuff, we'll do it.",
"Updated localization: BE, CKB, EU, FR, IT, NB, SC."));
log.add(
new VersionChangeLog(
1,
9,
"r5",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/87"),
"Power-Saving mode improvements - you can pick which features to include in Power-Saving.",
"Also, we allow switching to dark, simple theme in Power-Saving mode. But this is optional.",
"New Workman layout, Terminal generic-top-row and long-press fixes. Done by Alex Griffin.",
"Updated localization: AR, BE, EU, FR, HU, IT, KA, KN, KU, LT, NB, NL, PT, RO, RU, SC, UK."));
log.add(
new VersionChangeLog(
1,
9,
"r4",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/86"),
"Power-Saving mode - when battery is low, we will not do animations or dictionary look ups.",
"A few UI/UX changes.",
"A few bug fixes.",
"Updated localization: CA, IT, RO."));
log.add(
new VersionChangeLog(
1,
9,
"r3",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/85"),
"You can now set the default skin-tone for emojis #expressYourself. Android 7+.",
"Clipboard is now synced with outside changes. Long-press PASTE for list.",
"Various bug fixes.",
"Updated localization: BE, CA, EU, LT, NB, RU, SC, TR, UK."));
log.add(
new VersionChangeLog(
1,
9,
"r2",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/84"),
"Completely rewrote backup and restore mechanism. Now you can backup words, abbr, next-word and all-app settings.",
"New Kaomoji emoji group.",
"Pressing shift will change caps of selected text.",
"A few bug fixes.",
"Updated localization: AR, BE, BG, DU, EU, FI, FIL, FR, HU, KA, KMR, KU, LT, NB, PT-rBR, RU, SC, TR, UK."));
log.add(
new VersionChangeLog(
1,
9,
"r1",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/83"),
"New Settings UI bottom navigation.",
"Also, new Setup Wizard UI.",
"And many new settings all around.",
"Localization update: AR, BE, pt-rBR, ES, EU, FR, FIL, HU, KU, LT, MY, SC, TR, RU, UK.",
"YABTU and also will only work with Android 2.2 \uD83C\uDF6A or newer."));
log.add(
new VersionChangeLog(
1,
8,
"r12",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/82"),
"Fine-tuned icon to match Android's design.",
"Updated emojis for Android-O.",
"Long-pressing SHIFT will lock. Or unlock..",
"Incognito Mode! Long-press ENTER to start.",
"YABTU",
"Localization update: FR, EU, NL, IW."));
log.add(
new VersionChangeLog(
1,
8,
"r11",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/81"),
"All languages are equal! You can now reorder keyboards. In keyboard selection page - long press an enabled keyboard and drag it.",
"Now you can use multiple dictionaries on a given keyboard. Long-press ENTER for options.",
"Brought alternative layouts: DVORAK, COLEMAK, Terminal, and Compact English.",
"New theme by Algimantas",
"YABTU",
"Localization update: too many to mention."));
log.add(
new VersionChangeLog(
1,
8,
"r10",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r10"),
"Some bug fixes.",
"In tweaks: You can now force a locale inside AnySoftKeyboard.",
"YABTU",
"Localization update: BE, DE, CA, EU, FR."));
log.add(
new VersionChangeLog(
1,
8,
"r9",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r9"),
"New Initial Setup Wizard. For clearer activation.",
"Seems like we did not include words with accents in suggestions. We do now!",
"Better Emoji-Search experience. Type a : to start searching.",
"Yet more bugs squashed.",
"Localization update: BE, NL, FR, SL, DE, NO, EU."));
log.add(
new VersionChangeLog(
1,
8,
"r8",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r8"),
"Much improved English dictionary.",
"More than a few bug fixes.",
"Localization update: FR, SL, BE and all new EU (Basque)."));
log.add(
new VersionChangeLog(
1,
8,
"r7.1",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestone/78"),
"Bringing back missing Alphabet keys from some layouts.",
"Getting the hint if you say no to contacts."));
log.add(
new VersionChangeLog(
1,
8,
"r7",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r7"),
"Language key will now show only if you actually have more than one layout enabled.",
"For Android 7.1 - you now have Launcher shortcuts.",
"A few changes to the dictionary loading mechanism.",
"Some bug fixes.",
"Emojis are no longer popups, but their own keyboard. Plus, long press to get various skin tones (if available).",
"YABTU",
"Localization update: BE, UK, FR, TR, and SL."));
log.add(
new VersionChangeLog(
1,
8,
"r6",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r6"),
"Quite a few bug fixes, some related to shift states.",
"Some English dictionary tuning.",
"Now showing Greek alphabets in long-press popups.",
"Localization update: FR, BE."));
log.add(
new VersionChangeLog(
1,
8,
"r5",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r5"),
"Many bug fixes",
"Now you can \uD83D\uDD0D for emojis! Just start your search with a colon, like this - ':magnifying",
"Long-press an emoji to find out its assigned tags.",
"A massive rewrite of long-press interactions. I hope I didn't break anything (major).",
"When in a password field, numbers will show up at the top of the keyboard, because strong passwords and such.",
"Also, pressing SHIFT, will switch the numbers-row to symbols, because strong passwords and such.",
"YABTU.",
"Localization update: KN, KU, PT-BR."));
log.add(
new VersionChangeLog(
1,
8,
"r4",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r4"),
"Updated Emoticon emoji listing - presentation is everything \uD83D\uDE0E!",
"Also, flags \uD83C\uDFC1 were also added to the emoji list.",
"Merged People and Gestures, and added a bunch \uD83D\uDE4B.",
"Unfortunately - to make sure emojis are full supported - it is only available for Android 6.0 devices \uD83D\uDE22."));
log.add(
new VersionChangeLog(
1,
8,
"r3",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r3"),
"New Dark-Gray theme.",
"Bugs squashing, including an under-the-radar RTL issue.",
"Localization update: SL."));
log.add(
new VersionChangeLog(
1,
8,
"r2",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r2"),
"Better keyboard preview when selecting addons (themes, language, etc.).",
"Now tells you about clipboard copy.",
"A few bug fixes here and there.",
"YABTU.",
"Localization update: FR, SL."));
log.add(
new VersionChangeLog(
1,
8,
"r1",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8-r1"),
"Improvements on the keyboard preview. Now demos typing.",
"Several crash and bug fixes.",
"Localization update: FR (100%)."));
log.add(
new VersionChangeLog(
1,
8,
"",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.8"),
"New keyboard preview - now showing EXACTLY how the keyboard should look.",
"New launcher icon - first iteration. Ya ya, it's not perfect.",
"Spellchecker fix, and other bug fixes.",
"Build-tools update.",
"Localization: DE (complete), SL (complete), MY."));
log.add(
new VersionChangeLog(
1,
7,
"r7",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7-r7"),
"A few more bug fixes.",
"Localization: FR, NL, NO, RU, UK."));
log.add(
new VersionChangeLog(
1,
7,
"r6",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7-r6"),
"Status-bar icon fix. It is not a setting.",
"Swipe from Backspace will delete a whole word for'ya.",
"Update to the English auto-complete dictionary. Way overdue.."));
log.add(
new VersionChangeLog(
1,
7,
"r5",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7-r5"),
"Punctuation and space swapping magic.",
"Bug fixes all around."));
log.add(
new VersionChangeLog(
1,
7,
"r4",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7-r4"),
"Fix for a weird bug with manually picked words, plus some crashers."));
log.add(
new VersionChangeLog(
1,
7,
"r3",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7-r3"),
"Even more bugs crashed!",
"The utility box (swipe up from space-bar) now has SELECT-ALL key. Pro tip: long-press that key and then use left&right arrows to precisely select characters.",
"Talking about space-bar. Try double-spacing.",
"And, yes, YABTU.",
"Localization update: LT (100% complete!), KU."));
log.add(
new VersionChangeLog(
1,
7,
"r2",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7-r2"),
"Bugs, bugs, bugs. Squashed.",
"A better way to load auto-complete dictionary.",
"Localization update: FR, LT, IT, KU."));
log.add(
new VersionChangeLog(
1,
7,
"r1",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7-r1"),
"Marshmallow Permissions support - now we can annoy you with even more dialogs!",
"Bugs squashing all around. Thanks for the reports!",
"Localization update: DE, SL, FR, PT. And awesome note: German, Slovenian and French have been completely translated!",
"YABTU"));
log.add(
new VersionChangeLog(
1,
7,
"",
Uri.parse(
"https://github.com/AnySoftKeyboard/AnySoftKeyboard/milestones/1.7"),
"Printing-out speed ups. This is very helpful to you 150-words-a-minute wizards.",
"Physical-Keyboard interaction enhancements. This has Wife-Seal-of-Approval stamp on it.",
"Automatically switch to previously used layout in an App. Probably good for multilingual users.",
"And, fixed a few bugs (probably also introduced a few...)",
"Localization update: PL, CA, MY, UK, DE, FR, SL.",
"YABTU"));
return log;
}
public static class VersionChangeLog {
public final String versionName;
public final String[] changes;
public final Uri changesWebUrl;
public VersionChangeLog(
int major, int minor, String qualifier, Uri changesWebUrl, String... changes) {
if (TextUtils.isEmpty(qualifier)) {
this.versionName = String.format(Locale.US, "%d.%d", major, minor);
} else {
this.versionName = String.format(Locale.US, "%d.%d-%s", major, minor, qualifier);
}
this.changes = changes;
this.changesWebUrl = changesWebUrl;
}
}
}
| [
"menny@evendanan.net"
] | menny@evendanan.net |
ccdd43234435806a22592a15cdf145d8ff7d8fe0 | 6abf093021b98834687189dd86f0fff73de9809a | /tools/concurrent/src/main/java/com/concurrent/Phaser.java | e177f031858219b364d93208ee583fd53811a9d8 | [] | no_license | Hotpotboy/zhanghang | 53d1d59e1271dfb17b37bcc82940c272da84583e | 1624b953fccd3fc89b4b0c32627590aa9123ac93 | refs/heads/master | 2020-05-22T02:53:59.130067 | 2017-03-14T05:50:45 | 2017-03-14T05:50:45 | 39,623,209 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 45,296 | java | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package com.concurrent;
import com.concurrent.atomic.AtomicReference;
import com.concurrent.locks.LockSupport;
/**
* A reusable synchronization barrier, similar in functionality to
* {@link com.concurrent.CyclicBarrier CyclicBarrier} and
* {@link com.concurrent.CountDownLatch CountDownLatch}
* but supporting more flexible usage.
*
* <p><b>Registration.</b> Unlike the case for other barriers, the
* number of parties <em>registered</em> to synchronize on a phaser
* may vary over time. Tasks may be registered at any time (using
* methods {@link #register}, {@link #bulkRegister}, or forms of
* constructors establishing initial numbers of parties), and
* optionally deregistered upon any arrival (using {@link
* #arriveAndDeregister}). As is the case with most basic
* synchronization constructs, registration and deregistration affect
* only internal counts; they do not establish any further internal
* bookkeeping, so tasks cannot query whether they are registered.
* (However, you can introduce such bookkeeping by subclassing this
* class.)
*
* <p><b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code
* Phaser} may be repeatedly awaited. Method {@link
* #arriveAndAwaitAdvance} has effect analogous to {@link
* com.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each
* generation of a phaser has an associated phase number. The phase
* number starts at zero, and advances when all parties arrive at the
* phaser, wrapping around to zero after reaching {@code
* Integer.MAX_VALUE}. The use of phase numbers enables independent
* control of actions upon arrival at a phaser and upon awaiting
* others, via two kinds of methods that may be invoked by any
* registered party:
*
* <ul>
*
* <li> <b>Arrival.</b> Methods {@link #arrive} and
* {@link #arriveAndDeregister} record arrival. These methods
* do not block, but return an associated <em>arrival phase
* number</em>; that is, the phase number of the phaser to which
* the arrival applied. When the final party for a given phase
* arrives, an optional action is performed and the phase
* advances. These actions are performed by the party
* triggering a phase advance, and are arranged by overriding
* method {@link #onAdvance(int, int)}, which also controls
* termination. Overriding this method is similar to, but more
* flexible than, providing a barrier action to a {@code
* CyclicBarrier}.
*
* <li> <b>Waiting.</b> Method {@link #awaitAdvance} requires an
* argument indicating an arrival phase number, and returns when
* the phaser advances to (or is already at) a different phase.
* Unlike similar constructions using {@code CyclicBarrier},
* method {@code awaitAdvance} continues to wait even if the
* waiting thread is interrupted. Interruptible and timeout
* versions are also available, but exceptions encountered while
* tasks wait interruptibly or with timeout do not change the
* state of the phaser. If necessary, you can perform any
* associated recovery within handlers of those exceptions,
* often after invoking {@code forceTermination}. Phasers may
* also be used by tasks executing in a {@link ForkJoinPool},
* which will ensure sufficient parallelism to execute tasks
* when others are blocked waiting for a phase to advance.
*
* </ul>
*
* <p><b>Termination.</b> A phaser may enter a <em>termination</em>
* state, that may be checked using method {@link #isTerminated}. Upon
* termination, all synchronization methods immediately return without
* waiting for advance, as indicated by a negative return value.
* Similarly, attempts to register upon termination have no effect.
* Termination is triggered when an invocation of {@code onAdvance}
* returns {@code true}. The default implementation returns {@code
* true} if a deregistration has caused the number of registered
* parties to become zero. As illustrated below, when phasers control
* actions with a fixed number of iterations, it is often convenient
* to override this method to cause termination when the current phase
* number reaches a threshold. Method {@link #forceTermination} is
* also available to abruptly release waiting threads and allow them
* to terminate.
*
* <p><b>Tiering.</b> Phasers may be <em>tiered</em> (i.e.,
* constructed in tree structures) to reduce contention. Phasers with
* large numbers of parties that would otherwise experience heavy
* synchronization contention costs may instead be set up so that
* groups of sub-phasers share a common parent. This may greatly
* increase throughput even though it incurs greater per-operation
* overhead.
*
* <p>In a tree of tiered phasers, registration and deregistration of
* child phasers with their parent are managed automatically.
* Whenever the number of registered parties of a child phaser becomes
* non-zero (as established in the {@link #Phaser(Phaser,int)}
* constructor, {@link #register}, or {@link #bulkRegister}), the
* child phaser is registered with its parent. Whenever the number of
* registered parties becomes zero as the result of an invocation of
* {@link #arriveAndDeregister}, the child phaser is deregistered
* from its parent.
*
* <p><b>Monitoring.</b> While synchronization methods may be invoked
* only by registered parties, the current state of a phaser may be
* monitored by any caller. At any given moment there are {@link
* #getRegisteredParties} parties in total, of which {@link
* #getArrivedParties} have arrived at the current phase ({@link
* #getPhase}). When the remaining ({@link #getUnarrivedParties})
* parties arrive, the phase advances. The values returned by these
* methods may reflect transient states and so are not in general
* useful for synchronization control. Method {@link #toString}
* returns snapshots of these state queries in a form convenient for
* informal monitoring.
*
* <p><b>Sample usages:</b>
*
* <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
* to control a one-shot action serving a variable number of parties.
* The typical idiom is for the method setting this up to first
* register, then start the actions, then deregister, as in:
*
* <pre> {@code
* void runTasks(List<Runnable> tasks) {
* final Phaser phaser = new Phaser(1); // "1" to register self
* // create and start threads
* for (final Runnable task : tasks) {
* phaser.register();
* new Thread() {
* public void run() {
* phaser.arriveAndAwaitAdvance(); // await all creation
* task.run();
* }
* }.start();
* }
*
* // allow threads to start and deregister self
* phaser.arriveAndDeregister();
* }}</pre>
*
* <p>One way to cause a set of threads to repeatedly perform actions
* for a given number of iterations is to override {@code onAdvance}:
*
* <pre> {@code
* void startTasks(List<Runnable> tasks, final int iterations) {
* final Phaser phaser = new Phaser() {
* protected boolean onAdvance(int phase, int registeredParties) {
* return phase >= iterations || registeredParties == 0;
* }
* };
* phaser.register();
* for (final Runnable task : tasks) {
* phaser.register();
* new Thread() {
* public void run() {
* do {
* task.run();
* phaser.arriveAndAwaitAdvance();
* } while (!phaser.isTerminated());
* }
* }.start();
* }
* phaser.arriveAndDeregister(); // deregister self, don't wait
* }}</pre>
*
* If the main task must later await termination, it
* may re-register and then execute a similar loop:
* <pre> {@code
* // ...
* phaser.register();
* while (!phaser.isTerminated())
* phaser.arriveAndAwaitAdvance();}</pre>
*
* <p>Related constructions may be used to await particular phase numbers
* in contexts where you are sure that the phase will never wrap around
* {@code Integer.MAX_VALUE}. For example:
*
* <pre> {@code
* void awaitPhase(Phaser phaser, int phase) {
* int p = phaser.register(); // assumes caller not already registered
* while (p < phase) {
* if (phaser.isTerminated())
* // ... deal with unexpected termination
* else
* p = phaser.arriveAndAwaitAdvance();
* }
* phaser.arriveAndDeregister();
* }}</pre>
*
*
* <p>To create a set of {@code n} tasks using a tree of phasers, you
* could use code of the following form, assuming a Task class with a
* constructor accepting a {@code Phaser} that it registers with upon
* construction. After invocation of {@code build(new Task[n], 0, n,
* new Phaser())}, these tasks could then be started, for example by
* submitting to a pool:
*
* <pre> {@code
* void build(Task[] tasks, int lo, int hi, Phaser ph) {
* if (hi - lo > TASKS_PER_PHASER) {
* for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
* int j = Math.min(i + TASKS_PER_PHASER, hi);
* build(tasks, i, j, new Phaser(ph));
* }
* } else {
* for (int i = lo; i < hi; ++i)
* tasks[i] = new Task(ph);
* // assumes new Task(ph) performs ph.register()
* }
* }}</pre>
*
* The best value of {@code TASKS_PER_PHASER} depends mainly on
* expected synchronization rates. A value as low as four may
* be appropriate for extremely small per-phase task bodies (thus
* high rates), or up to hundreds for extremely large ones.
*
* <p><b>Implementation notes</b>: This implementation restricts the
* maximum number of parties to 65535. Attempts to register additional
* parties result in {@code IllegalStateException}. However, you can and
* should create tiered phasers to accommodate arbitrarily large sets
* of participants.
*
* @since 1.7
* @author Doug Lea
*/
public class Phaser {
/*
* This class implements an extension of X10 "clocks". Thanks to
* Vijay Saraswat for the idea, and to Vivek Sarkar for
* enhancements to extend functionality.
*/
/**
* Primary state representation, holding four bit-fields:
*
* unarrived -- the number of parties yet to hit barrier (bits 0-15)
* parties -- the number of parties to wait (bits 16-31)
* phase -- the generation of the barrier (bits 32-62)
* terminated -- set if barrier is terminated (bit 63 / sign)
*
* Except that a phaser with no registered parties is
* distinguished by the otherwise illegal state of having zero
* parties and one unarrived parties (encoded as EMPTY below).
*
* To efficiently maintain atomicity, these values are packed into
* a single (atomic) long. Good performance relies on keeping
* state decoding and encoding simple, and keeping race windows
* short.
*
* All state updates are performed via CAS except initial
* registration of a sub-phaser (i.e., one with a non-null
* parent). In this (relatively rare) case, we use built-in
* synchronization to lock while first registering with its
* parent.
*
* The phase of a subphaser is allowed to lag that of its
* ancestors until it is actually accessed -- see method
* reconcileState.
*/
private volatile long state;
private static final int MAX_PARTIES = 0xffff;
private static final int MAX_PHASE = Integer.MAX_VALUE;
private static final int PARTIES_SHIFT = 16;
private static final int PHASE_SHIFT = 32;
private static final int UNARRIVED_MASK = 0xffff; // to mask ints
private static final long PARTIES_MASK = 0xffff0000L; // to mask longs
private static final long COUNTS_MASK = 0xffffffffL;
private static final long TERMINATION_BIT = 1L << 63;
// some special values
private static final int ONE_ARRIVAL = 1;
private static final int ONE_PARTY = 1 << PARTIES_SHIFT;
private static final int ONE_DEREGISTER = ONE_ARRIVAL|ONE_PARTY;
private static final int EMPTY = 1;
// The following unpacking methods are usually manually inlined
private static int unarrivedOf(long s) {
int counts = (int)s;
return (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
}
private static int partiesOf(long s) {
return (int)s >>> PARTIES_SHIFT;
}
private static int phaseOf(long s) {
return (int)(s >>> PHASE_SHIFT);
}
private static int arrivedOf(long s) {
int counts = (int)s;
return (counts == EMPTY) ? 0 :
(counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK);
}
/**
* The parent of this phaser, or null if none
*/
private final Phaser parent;
/**
* The root of phaser tree. Equals this if not in a tree.
*/
private final Phaser root;
/**
* Heads of Treiber stacks for waiting threads. To eliminate
* contention when releasing some threads while adding others, we
* use two of them, alternating across even and odd phases.
* Subphasers share queues with root to speed up releases.
*/
private final AtomicReference<QNode> evenQ;
private final AtomicReference<QNode> oddQ;
private AtomicReference<QNode> queueFor(int phase) {
return ((phase & 1) == 0) ? evenQ : oddQ;
}
/**
* Returns message string for bounds exceptions on arrival.
*/
private String badArrive(long s) {
return "Attempted arrival of unregistered party for " +
stateToString(s);
}
/**
* Returns message string for bounds exceptions on registration.
*/
private String badRegister(long s) {
return "Attempt to register more than " +
MAX_PARTIES + " parties for " + stateToString(s);
}
/**
* Main implementation for methods arrive and arriveAndDeregister.
* Manually tuned to speed up and minimize race windows for the
* common case of just decrementing unarrived field.
*
* @param adjust value to subtract from state;
* ONE_ARRIVAL for arrive,
* ONE_DEREGISTER for arriveAndDeregister
*/
private int doArrive(int adjust) {
final Phaser root = this.root;
for (;;) {
long s = (root == this) ? state : reconcileState();
int phase = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
int counts = (int)s;
int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
if (unarrived <= 0)
throw new IllegalStateException(badArrive(s));
if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adjust)) {
if (unarrived == 1) {
long n = s & PARTIES_MASK; // base of next state
int nextUnarrived = (int)n >>> PARTIES_SHIFT;
if (root == this) {
if (onAdvance(phase, nextUnarrived))
n |= TERMINATION_BIT;
else if (nextUnarrived == 0)
n |= EMPTY;
else
n |= nextUnarrived;
int nextPhase = (phase + 1) & MAX_PHASE;
n |= (long)nextPhase << PHASE_SHIFT;
UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
releaseWaiters(phase);
}
else if (nextUnarrived == 0) { // propagate deregistration
phase = parent.doArrive(ONE_DEREGISTER);
UNSAFE.compareAndSwapLong(this, stateOffset,
s, s | EMPTY);
}
else
phase = parent.doArrive(ONE_ARRIVAL);
}
return phase;
}
}
}
/**
* Implementation of register, bulkRegister
*
* @param registrations number to add to both parties and
* unarrived fields. Must be greater than zero.
*/
private int doRegister(int registrations) {
// adjustment to state
long adjust = ((long)registrations << PARTIES_SHIFT) | registrations;
final Phaser parent = this.parent;
int phase;
for (;;) {
long s = (parent == null) ? state : reconcileState();
int counts = (int)s;
int parties = counts >>> PARTIES_SHIFT;
int unarrived = counts & UNARRIVED_MASK;
if (registrations > MAX_PARTIES - parties)
throw new IllegalStateException(badRegister(s));
phase = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
break;
if (counts != EMPTY) { // not 1st registration
if (parent == null || reconcileState() == s) {
if (unarrived == 0) // wait out advance
root.internalAwaitAdvance(phase, null);
else if (UNSAFE.compareAndSwapLong(this, stateOffset,
s, s + adjust))
break;
}
}
else if (parent == null) { // 1st root registration
long next = ((long)phase << PHASE_SHIFT) | adjust;
if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
break;
}
else {
synchronized (this) { // 1st sub registration
if (state == s) { // recheck under lock
phase = parent.doRegister(1);
if (phase < 0)
break;
// finish registration whenever parent registration
// succeeded, even when racing with termination,
// since these are part of the same "transaction".
while (!UNSAFE.compareAndSwapLong
(this, stateOffset, s,
((long)phase << PHASE_SHIFT) | adjust)) {
s = state;
phase = (int)(root.state >>> PHASE_SHIFT);
// assert (int)s == EMPTY;
}
break;
}
}
}
}
return phase;
}
/**
* Resolves lagged phase propagation from root if necessary.
* Reconciliation normally occurs when root has advanced but
* subphasers have not yet done so, in which case they must finish
* their own advance by setting unarrived to parties (or if
* parties is zero, resetting to unregistered EMPTY state).
*
* @return reconciled state
*/
private long reconcileState() {
final Phaser root = this.root;
long s = state;
if (root != this) {
int phase, p;
// CAS to root phase with current parties, tripping unarrived
while ((phase = (int)(root.state >>> PHASE_SHIFT)) !=
(int)(s >>> PHASE_SHIFT) &&
!UNSAFE.compareAndSwapLong
(this, stateOffset, s,
s = (((long)phase << PHASE_SHIFT) |
((phase < 0) ? (s & COUNTS_MASK) :
(((p = (int)s >>> PARTIES_SHIFT) == 0) ? EMPTY :
((s & PARTIES_MASK) | p))))))
s = state;
}
return s;
}
/**
* Creates a new phaser with no initially registered parties, no
* parent, and initial phase number 0. Any thread using this
* phaser will need to first register for it.
*/
public Phaser() {
this(null, 0);
}
/**
* Creates a new phaser with the given number of registered
* unarrived parties, no parent, and initial phase number 0.
*
* @param parties the number of parties required to advance to the
* next phase
* @throws IllegalArgumentException if parties less than zero
* or greater than the maximum number of parties supported
*/
public Phaser(int parties) {
this(null, parties);
}
/**
* Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
*
* @param parent the parent phaser
*/
public Phaser(Phaser parent) {
this(parent, 0);
}
/**
* Creates a new phaser with the given parent and number of
* registered unarrived parties. When the given parent is non-null
* and the given number of parties is greater than zero, this
* child phaser is registered with its parent.
*
* @param parent the parent phaser
* @param parties the number of parties required to advance to the
* next phase
* @throws IllegalArgumentException if parties less than zero
* or greater than the maximum number of parties supported
*/
public Phaser(Phaser parent, int parties) {
if (parties >>> PARTIES_SHIFT != 0)
throw new IllegalArgumentException("Illegal number of parties");
int phase = 0;
this.parent = parent;
if (parent != null) {
final Phaser root = parent.root;
this.root = root;
this.evenQ = root.evenQ;
this.oddQ = root.oddQ;
if (parties != 0)
phase = parent.doRegister(1);
}
else {
this.root = this;
this.evenQ = new AtomicReference<QNode>();
this.oddQ = new AtomicReference<QNode>();
}
this.state = (parties == 0) ? (long)EMPTY :
((long)phase << PHASE_SHIFT) |
((long)parties << PARTIES_SHIFT) |
((long)parties);
}
/**
* Adds a new unarrived party to this phaser. If an ongoing
* invocation of {@link #onAdvance} is in progress, this method
* may await its completion before returning. If this phaser has
* a parent, and this phaser previously had no registered parties,
* this child phaser is also registered with its parent. If
* this phaser is terminated, the attempt to register has
* no effect, and a negative value is returned.
*
* @return the arrival phase number to which this registration
* applied. If this value is negative, then this phaser has
* terminated, in which case registration has no effect.
* @throws IllegalStateException if attempting to register more
* than the maximum supported number of parties
*/
public int register() {
return doRegister(1);
}
/**
* Adds the given number of new unarrived parties to this phaser.
* If an ongoing invocation of {@link #onAdvance} is in progress,
* this method may await its completion before returning. If this
* phaser has a parent, and the given number of parties is greater
* than zero, and this phaser previously had no registered
* parties, this child phaser is also registered with its parent.
* If this phaser is terminated, the attempt to register has no
* effect, and a negative value is returned.
*
* @param parties the number of additional parties required to
* advance to the next phase
* @return the arrival phase number to which this registration
* applied. If this value is negative, then this phaser has
* terminated, in which case registration has no effect.
* @throws IllegalStateException if attempting to register more
* than the maximum supported number of parties
* @throws IllegalArgumentException if {@code parties < 0}
*/
public int bulkRegister(int parties) {
if (parties < 0)
throw new IllegalArgumentException();
if (parties == 0)
return getPhase();
return doRegister(parties);
}
/**
* Arrives at this phaser, without waiting for others to arrive.
*
* <p>It is a usage error for an unregistered party to invoke this
* method. However, this error may result in an {@code
* IllegalStateException} only upon some subsequent operation on
* this phaser, if ever.
*
* @return the arrival phase number, or a negative value if terminated
* @throws IllegalStateException if not terminated and the number
* of unarrived parties would become negative
*/
public int arrive() {
return doArrive(ONE_ARRIVAL);
}
/**
* Arrives at this phaser and deregisters from it without waiting
* for others to arrive. Deregistration reduces the number of
* parties required to advance in future phases. If this phaser
* has a parent, and deregistration causes this phaser to have
* zero parties, this phaser is also deregistered from its parent.
*
* <p>It is a usage error for an unregistered party to invoke this
* method. However, this error may result in an {@code
* IllegalStateException} only upon some subsequent operation on
* this phaser, if ever.
*
* @return the arrival phase number, or a negative value if terminated
* @throws IllegalStateException if not terminated and the number
* of registered or unarrived parties would become negative
*/
public int arriveAndDeregister() {
return doArrive(ONE_DEREGISTER);
}
/**
* Arrives at this phaser and awaits others. Equivalent in effect
* to {@code awaitAdvance(arrive())}. If you need to await with
* interruption or timeout, you can arrange this with an analogous
* construction using one of the other forms of the {@code
* awaitAdvance} method. If instead you need to deregister upon
* arrival, use {@code awaitAdvance(arriveAndDeregister())}.
*
* <p>It is a usage error for an unregistered party to invoke this
* method. However, this error may result in an {@code
* IllegalStateException} only upon some subsequent operation on
* this phaser, if ever.
*
* @return the arrival phase number, or the (negative)
* {@linkplain #getPhase() current phase} if terminated
* @throws IllegalStateException if not terminated and the number
* of unarrived parties would become negative
*/
public int arriveAndAwaitAdvance() {
// Specialization of doArrive+awaitAdvance eliminating some reads/paths
final Phaser root = this.root;
for (;;) {
long s = (root == this) ? state : reconcileState();
int phase = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
int counts = (int)s;
int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
if (unarrived <= 0)
throw new IllegalStateException(badArrive(s));
if (UNSAFE.compareAndSwapLong(this, stateOffset, s,
s -= ONE_ARRIVAL)) {
if (unarrived > 1)
return root.internalAwaitAdvance(phase, null);
if (root != this)
return parent.arriveAndAwaitAdvance();
long n = s & PARTIES_MASK; // base of next state
int nextUnarrived = (int)n >>> PARTIES_SHIFT;
if (onAdvance(phase, nextUnarrived))
n |= TERMINATION_BIT;
else if (nextUnarrived == 0)
n |= EMPTY;
else
n |= nextUnarrived;
int nextPhase = (phase + 1) & MAX_PHASE;
n |= (long)nextPhase << PHASE_SHIFT;
if (!UNSAFE.compareAndSwapLong(this, stateOffset, s, n))
return (int)(state >>> PHASE_SHIFT); // terminated
releaseWaiters(phase);
return nextPhase;
}
}
}
/**
* Awaits the phase of this phaser to advance from the given phase
* value, returning immediately if the current phase is not equal
* to the given phase value or this phaser is terminated.
*
* @param phase an arrival phase number, or negative value if
* terminated; this argument is normally the value returned by a
* previous call to {@code arrive} or {@code arriveAndDeregister}.
* @return the next arrival phase number, or the argument if it is
* negative, or the (negative) {@linkplain #getPhase() current phase}
* if terminated
*/
public int awaitAdvance(int phase) {
final Phaser root = this.root;
long s = (root == this) ? state : reconcileState();
int p = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
if (p == phase)
return root.internalAwaitAdvance(phase, null);
return p;
}
/**
* Awaits the phase of this phaser to advance from the given phase
* value, throwing {@code InterruptedException} if interrupted
* while waiting, or returning immediately if the current phase is
* not equal to the given phase value or this phaser is
* terminated.
*
* @param phase an arrival phase number, or negative value if
* terminated; this argument is normally the value returned by a
* previous call to {@code arrive} or {@code arriveAndDeregister}.
* @return the next arrival phase number, or the argument if it is
* negative, or the (negative) {@linkplain #getPhase() current phase}
* if terminated
* @throws InterruptedException if thread interrupted while waiting
*/
public int awaitAdvanceInterruptibly(int phase)
throws InterruptedException {
final Phaser root = this.root;
long s = (root == this) ? state : reconcileState();
int p = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
if (p == phase) {
QNode node = new QNode(this, phase, true, false, 0L);
p = root.internalAwaitAdvance(phase, node);
if (node.wasInterrupted)
throw new InterruptedException();
}
return p;
}
/**
* Awaits the phase of this phaser to advance from the given phase
* value or the given timeout to elapse, throwing {@code
* InterruptedException} if interrupted while waiting, or
* returning immediately if the current phase is not equal to the
* given phase value or this phaser is terminated.
*
* @param phase an arrival phase number, or negative value if
* terminated; this argument is normally the value returned by a
* previous call to {@code arrive} or {@code arriveAndDeregister}.
* @param timeout how long to wait before giving up, in units of
* {@code unit}
* @param unit a {@code TimeUnit} determining how to interpret the
* {@code timeout} parameter
* @return the next arrival phase number, or the argument if it is
* negative, or the (negative) {@linkplain #getPhase() current phase}
* if terminated
* @throws InterruptedException if thread interrupted while waiting
* @throws TimeoutException if timed out while waiting
*/
public int awaitAdvanceInterruptibly(int phase,
long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException {
long nanos = unit.toNanos(timeout);
final Phaser root = this.root;
long s = (root == this) ? state : reconcileState();
int p = (int)(s >>> PHASE_SHIFT);
if (phase < 0)
return phase;
if (p == phase) {
QNode node = new QNode(this, phase, true, true, nanos);
p = root.internalAwaitAdvance(phase, node);
if (node.wasInterrupted)
throw new InterruptedException();
else if (p == phase)
throw new TimeoutException();
}
return p;
}
/**
* Forces this phaser to enter termination state. Counts of
* registered parties are unaffected. If this phaser is a member
* of a tiered set of phasers, then all of the phasers in the set
* are terminated. If this phaser is already terminated, this
* method has no effect. This method may be useful for
* coordinating recovery after one or more tasks encounter
* unexpected exceptions.
*/
public void forceTermination() {
// Only need to change root state
final Phaser root = this.root;
long s;
while ((s = root.state) >= 0) {
if (UNSAFE.compareAndSwapLong(root, stateOffset,
s, s | TERMINATION_BIT)) {
// signal all threads
releaseWaiters(0); // Waiters on evenQ
releaseWaiters(1); // Waiters on oddQ
return;
}
}
}
/**
* Returns the current phase number. The maximum phase number is
* {@code Integer.MAX_VALUE}, after which it restarts at
* zero. Upon termination, the phase number is negative,
* in which case the prevailing phase prior to termination
* may be obtained via {@code getPhase() + Integer.MIN_VALUE}.
*
* @return the phase number, or a negative value if terminated
*/
public final int getPhase() {
return (int)(root.state >>> PHASE_SHIFT);
}
/**
* Returns the number of parties registered at this phaser.
*
* @return the number of parties
*/
public int getRegisteredParties() {
return partiesOf(state);
}
/**
* Returns the number of registered parties that have arrived at
* the current phase of this phaser. If this phaser has terminated,
* the returned value is meaningless and arbitrary.
*
* @return the number of arrived parties
*/
public int getArrivedParties() {
return arrivedOf(reconcileState());
}
/**
* Returns the number of registered parties that have not yet
* arrived at the current phase of this phaser. If this phaser has
* terminated, the returned value is meaningless and arbitrary.
*
* @return the number of unarrived parties
*/
public int getUnarrivedParties() {
return unarrivedOf(reconcileState());
}
/**
* Returns the parent of this phaser, or {@code null} if none.
*
* @return the parent of this phaser, or {@code null} if none
*/
public Phaser getParent() {
return parent;
}
/**
* Returns the root ancestor of this phaser, which is the same as
* this phaser if it has no parent.
*
* @return the root ancestor of this phaser
*/
public Phaser getRoot() {
return root;
}
/**
* Returns {@code true} if this phaser has been terminated.
*
* @return {@code true} if this phaser has been terminated
*/
public boolean isTerminated() {
return root.state < 0L;
}
/**
* Overridable method to perform an action upon impending phase
* advance, and to control termination. This method is invoked
* upon arrival of the party advancing this phaser (when all other
* waiting parties are dormant). If this method returns {@code
* true}, this phaser will be set to a final termination state
* upon advance, and subsequent calls to {@link #isTerminated}
* will return true. Any (unchecked) Exception or Error thrown by
* an invocation of this method is propagated to the party
* attempting to advance this phaser, in which case no advance
* occurs.
*
* <p>The arguments to this method provide the state of the phaser
* prevailing for the current transition. The effects of invoking
* arrival, registration, and waiting methods on this phaser from
* within {@code onAdvance} are unspecified and should not be
* relied on.
*
* <p>If this phaser is a member of a tiered set of phasers, then
* {@code onAdvance} is invoked only for its root phaser on each
* advance.
*
* <p>To support the most common use cases, the default
* implementation of this method returns {@code true} when the
* number of registered parties has become zero as the result of a
* party invoking {@code arriveAndDeregister}. You can disable
* this behavior, thus enabling continuation upon future
* registrations, by overriding this method to always return
* {@code false}:
*
* <pre> {@code
* Phaser phaser = new Phaser() {
* protected boolean onAdvance(int phase, int parties) { return false; }
* }}</pre>
*
* @param phase the current phase number on entry to this method,
* before this phaser is advanced
* @param registeredParties the current number of registered parties
* @return {@code true} if this phaser should terminate
*/
protected boolean onAdvance(int phase, int registeredParties) {
return registeredParties == 0;
}
/**
* Returns a string identifying this phaser, as well as its
* state. The state, in brackets, includes the String {@code
* "phase = "} followed by the phase number, {@code "parties = "}
* followed by the number of registered parties, and {@code
* "arrived = "} followed by the number of arrived parties.
*
* @return a string identifying this phaser, as well as its state
*/
public String toString() {
return stateToString(reconcileState());
}
/**
* Implementation of toString and string-based error messages
*/
private String stateToString(long s) {
return super.toString() +
"[phase = " + phaseOf(s) +
" parties = " + partiesOf(s) +
" arrived = " + arrivedOf(s) + "]";
}
// Waiting mechanics
/**
* Removes and signals threads from queue for phase.
*/
private void releaseWaiters(int phase) {
QNode q; // first element of queue
Thread t; // its thread
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
while ((q = head.get()) != null &&
q.phase != (int)(root.state >>> PHASE_SHIFT)) {
if (head.compareAndSet(q, q.next) &&
(t = q.thread) != null) {
q.thread = null;
LockSupport.unpark(t);
}
}
}
/**
* Variant of releaseWaiters that additionally tries to remove any
* nodes no longer waiting for advance due to timeout or
* interrupt. Currently, nodes are removed only if they are at
* head of queue, which suffices to reduce memory footprint in
* most usages.
*
* @return current phase on exit
*/
private int abortWait(int phase) {
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
for (;;) {
Thread t;
QNode q = head.get();
int p = (int)(root.state >>> PHASE_SHIFT);
if (q == null || ((t = q.thread) != null && q.phase == p))
return p;
if (head.compareAndSet(q, q.next) && t != null) {
q.thread = null;
LockSupport.unpark(t);
}
}
}
/** The number of CPUs, for spin control */
private static final int NCPU = Runtime.getRuntime().availableProcessors();
/**
* The number of times to spin before blocking while waiting for
* advance, per arrival while waiting. On multiprocessors, fully
* blocking and waking up a large number of threads all at once is
* usually a very slow process, so we use rechargeable spins to
* avoid it when threads regularly arrive: When a thread in
* internalAwaitAdvance notices another arrival before blocking,
* and there appear to be enough CPUs available, it spins
* SPINS_PER_ARRIVAL more times before blocking. The value trades
* off good-citizenship vs big unnecessary slowdowns.
*/
static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
/**
* Possibly blocks and waits for phase to advance unless aborted.
* Call only on root phaser.
*
* @param phase current phase
* @param node if non-null, the wait node to track interrupt and timeout;
* if null, denotes noninterruptible wait
* @return current phase
*/
private int internalAwaitAdvance(int phase, QNode node) {
// assert root == this;
releaseWaiters(phase-1); // ensure old queue clean
boolean queued = false; // true when node is enqueued
int lastUnarrived = 0; // to increase spins upon change
int spins = SPINS_PER_ARRIVAL;
long s;
int p;
while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
if (node == null) { // spinning in noninterruptible mode
int unarrived = (int)s & UNARRIVED_MASK;
if (unarrived != lastUnarrived &&
(lastUnarrived = unarrived) < NCPU)
spins += SPINS_PER_ARRIVAL;
boolean interrupted = Thread.interrupted();
if (interrupted || --spins < 0) { // need node to record intr
node = new QNode(this, phase, false, false, 0L);
node.wasInterrupted = interrupted;
}
}
else if (node.isReleasable()) // done or aborted
break;
else if (!queued) { // push onto queue
AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
QNode q = node.next = head.get();
if ((q == null || q.phase == phase) &&
(int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
queued = head.compareAndSet(q, node);
}
else {
try {
ForkJoinPool.managedBlock(node);
} catch (InterruptedException ie) {
node.wasInterrupted = true;
}
}
}
if (node != null) {
if (node.thread != null)
node.thread = null; // avoid need for unpark()
if (node.wasInterrupted && !node.interruptible)
Thread.currentThread().interrupt();
if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
return abortWait(phase); // possibly clean up on abort
}
releaseWaiters(phase);
return p;
}
/**
* Wait nodes for Treiber stack representing wait queue
*/
static final class QNode implements ForkJoinPool.ManagedBlocker {
final Phaser phaser;
final int phase;
final boolean interruptible;
final boolean timed;
boolean wasInterrupted;
long nanos;
final long deadline;
volatile Thread thread; // nulled to cancel wait
QNode next;
QNode(Phaser phaser, int phase, boolean interruptible,
boolean timed, long nanos) {
this.phaser = phaser;
this.phase = phase;
this.interruptible = interruptible;
this.nanos = nanos;
this.timed = timed;
this.deadline = timed ? System.nanoTime() + nanos : 0L;
thread = Thread.currentThread();
}
public boolean isReleasable() {
if (thread == null)
return true;
if (phaser.getPhase() != phase) {
thread = null;
return true;
}
if (Thread.interrupted())
wasInterrupted = true;
if (wasInterrupted && interruptible) {
thread = null;
return true;
}
if (timed) {
if (nanos > 0L) {
nanos = deadline - System.nanoTime();
}
if (nanos <= 0L) {
thread = null;
return true;
}
}
return false;
}
public boolean block() {
if (isReleasable())
return true;
else if (!timed)
LockSupport.park(this);
else if (nanos > 0L)
LockSupport.parkNanos(this, nanos);
return isReleasable();
}
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long stateOffset;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> k = Phaser.class;
stateOffset = UNSAFE.objectFieldOffset
(k.getDeclaredField("state"));
} catch (Exception e) {
throw new Error(e);
}
}
}
| [
"407376249@qq.com"
] | 407376249@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.