blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
5b79d6eac2d29f0526282a38f3c4aefa78c13f5b
30,812,095,430,607
c094407979d4d9de4ffc15bcc524bfb6aee6107a
/ASB2/common/GU/models/ModeLaser2.java
573c06056a26a7c207b32b02cf894ad4a6169c5b
[]
no_license
jordanwhite1/GearUtilities
https://github.com/jordanwhite1/GearUtilities
6d012c8d89ae84f3de1518c61391acf324e25ad4
f677cf0f1d88a3cae293c3918d8963d06741fe37
refs/heads/master
2021-01-16T09:01:10.178000
2013-08-19T03:58:03
2013-08-19T03:58:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GU.models; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; public class ModeLaser2 extends ModelBase { ModelRenderer Bottom; ModelRenderer Top; ModelRenderer Right; ModelRenderer Left; ModelRenderer Back; ModelRenderer LeftHandle; ModelRenderer RightHandle; ModelRenderer CenterLens; ModelRenderer TopHandle; ModelRenderer BottomHandle; ModelRenderer LensFocus; public ModeLaser2() { textureWidth = 128; textureHeight = 64; Bottom = new ModelRenderer(this, 0, 0); Bottom.addBox(-8F, 0F, -8F, 16, 1, 16); Bottom.setRotationPoint(0F, 23F, 0F); Bottom.setTextureSize(128, 64); Bottom.mirror = true; setRotation(Bottom, 0F, 0F, 0F); Top = new ModelRenderer(this, 0, 0); Top.addBox(-8F, 0F, -8F, 16, 1, 16); Top.setRotationPoint(0F, 8F, 0F); Top.setTextureSize(128, 64); Top.mirror = true; setRotation(Top, 0F, 0F, 0F); Right = new ModelRenderer(this, 0, 18); Right.addBox(0F, -7F, -8F, 1, 14, 16); Right.setRotationPoint(-8F, 16F, 0F); Right.setTextureSize(128, 64); Right.mirror = true; setRotation(Right, 0F, 0F, 0F); Left = new ModelRenderer(this, 0, 18); Left.addBox(0F, -7F, -8F, 1, 14, 16); Left.setRotationPoint(7F, 16F, 0F); Left.setTextureSize(128, 64); Left.mirror = true; setRotation(Left, 0F, 0F, 0F); Back = new ModelRenderer(this, 0, 49); Back.addBox(-7F, -7F, 0F, 14, 14, 1); Back.setRotationPoint(0F, 16F, 7F); Back.setTextureSize(128, 64); Back.mirror = true; setRotation(Back, 0F, 0F, 0F); LeftHandle = new ModelRenderer(this, 65, 0); LeftHandle.addBox(-2F, -1F, -2F, 4, 2, 2); LeftHandle.setRotationPoint(5F, 16F, -6F); LeftHandle.setTextureSize(128, 64); LeftHandle.mirror = true; setRotation(LeftHandle, 0F, 0F, 0F); RightHandle = new ModelRenderer(this, 65, 0); RightHandle.addBox(-2F, -1F, -2F, 4, 2, 2); RightHandle.setRotationPoint(-5F, 16F, -6F); RightHandle.setTextureSize(128, 64); RightHandle.mirror = true; setRotation(RightHandle, 0F, 0F, 0F); CenterLens = new ModelRenderer(this, 35, 18); CenterLens.addBox(-2F, -2F, 0F, 4, 4, 11); CenterLens.setRotationPoint(0F, 16F, -4F); CenterLens.setTextureSize(128, 64); CenterLens.mirror = true; setRotation(CenterLens, 0F, 0F, 0F); TopHandle = new ModelRenderer(this, 65, 5); TopHandle.addBox(-1F, -2F, -1F, 2, 4, 2); TopHandle.setRotationPoint(0F, 11F, -7F); TopHandle.setTextureSize(128, 64); TopHandle.mirror = true; setRotation(TopHandle, 0F, 0F, 0F); BottomHandle = new ModelRenderer(this, 65, 5); BottomHandle.addBox(-1F, -2F, -1F, 2, 4, 2); BottomHandle.setRotationPoint(0F, 21F, -7F); BottomHandle.setTextureSize(128, 64); BottomHandle.mirror = true; setRotation(BottomHandle, 0F, 0F, 0F); LensFocus = new ModelRenderer(this, 35, 34); LensFocus.addBox(-3F, -3F, 0F, 6, 6, 1); LensFocus.setRotationPoint(0F, 16F, -8F); LensFocus.setTextureSize(128, 64); LensFocus.mirror = true; setRotation(LensFocus, 0F, 0F, 0F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); Bottom.render(f5); Top.render(f5); Right.render(f5); Left.render(f5); Back.render(f5); LeftHandle.render(f5); RightHandle.render(f5); CenterLens.render(f5); TopHandle.render(f5); BottomHandle.render(f5); LensFocus.render(f5); } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } @Override public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } public void renderLaser() { Bottom.render(0.0625F); Top.render(0.0625F); Right.render(0.0625F); Left.render(0.0625F); Back.render(0.0625F); LeftHandle.render(0.0625F); RightHandle.render(0.0625F); CenterLens.render(0.0625F); TopHandle.render(0.0625F); BottomHandle.render(0.0625F); } public void renderFocus() { LensFocus.render(0.0625F); } }
UTF-8
Java
4,862
java
ModeLaser2.java
Java
[]
null
[]
package GU.models; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; public class ModeLaser2 extends ModelBase { ModelRenderer Bottom; ModelRenderer Top; ModelRenderer Right; ModelRenderer Left; ModelRenderer Back; ModelRenderer LeftHandle; ModelRenderer RightHandle; ModelRenderer CenterLens; ModelRenderer TopHandle; ModelRenderer BottomHandle; ModelRenderer LensFocus; public ModeLaser2() { textureWidth = 128; textureHeight = 64; Bottom = new ModelRenderer(this, 0, 0); Bottom.addBox(-8F, 0F, -8F, 16, 1, 16); Bottom.setRotationPoint(0F, 23F, 0F); Bottom.setTextureSize(128, 64); Bottom.mirror = true; setRotation(Bottom, 0F, 0F, 0F); Top = new ModelRenderer(this, 0, 0); Top.addBox(-8F, 0F, -8F, 16, 1, 16); Top.setRotationPoint(0F, 8F, 0F); Top.setTextureSize(128, 64); Top.mirror = true; setRotation(Top, 0F, 0F, 0F); Right = new ModelRenderer(this, 0, 18); Right.addBox(0F, -7F, -8F, 1, 14, 16); Right.setRotationPoint(-8F, 16F, 0F); Right.setTextureSize(128, 64); Right.mirror = true; setRotation(Right, 0F, 0F, 0F); Left = new ModelRenderer(this, 0, 18); Left.addBox(0F, -7F, -8F, 1, 14, 16); Left.setRotationPoint(7F, 16F, 0F); Left.setTextureSize(128, 64); Left.mirror = true; setRotation(Left, 0F, 0F, 0F); Back = new ModelRenderer(this, 0, 49); Back.addBox(-7F, -7F, 0F, 14, 14, 1); Back.setRotationPoint(0F, 16F, 7F); Back.setTextureSize(128, 64); Back.mirror = true; setRotation(Back, 0F, 0F, 0F); LeftHandle = new ModelRenderer(this, 65, 0); LeftHandle.addBox(-2F, -1F, -2F, 4, 2, 2); LeftHandle.setRotationPoint(5F, 16F, -6F); LeftHandle.setTextureSize(128, 64); LeftHandle.mirror = true; setRotation(LeftHandle, 0F, 0F, 0F); RightHandle = new ModelRenderer(this, 65, 0); RightHandle.addBox(-2F, -1F, -2F, 4, 2, 2); RightHandle.setRotationPoint(-5F, 16F, -6F); RightHandle.setTextureSize(128, 64); RightHandle.mirror = true; setRotation(RightHandle, 0F, 0F, 0F); CenterLens = new ModelRenderer(this, 35, 18); CenterLens.addBox(-2F, -2F, 0F, 4, 4, 11); CenterLens.setRotationPoint(0F, 16F, -4F); CenterLens.setTextureSize(128, 64); CenterLens.mirror = true; setRotation(CenterLens, 0F, 0F, 0F); TopHandle = new ModelRenderer(this, 65, 5); TopHandle.addBox(-1F, -2F, -1F, 2, 4, 2); TopHandle.setRotationPoint(0F, 11F, -7F); TopHandle.setTextureSize(128, 64); TopHandle.mirror = true; setRotation(TopHandle, 0F, 0F, 0F); BottomHandle = new ModelRenderer(this, 65, 5); BottomHandle.addBox(-1F, -2F, -1F, 2, 4, 2); BottomHandle.setRotationPoint(0F, 21F, -7F); BottomHandle.setTextureSize(128, 64); BottomHandle.mirror = true; setRotation(BottomHandle, 0F, 0F, 0F); LensFocus = new ModelRenderer(this, 35, 34); LensFocus.addBox(-3F, -3F, 0F, 6, 6, 1); LensFocus.setRotationPoint(0F, 16F, -8F); LensFocus.setTextureSize(128, 64); LensFocus.mirror = true; setRotation(LensFocus, 0F, 0F, 0F); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); setRotationAngles(f, f1, f2, f3, f4, f5, entity); Bottom.render(f5); Top.render(f5); Right.render(f5); Left.render(f5); Back.render(f5); LeftHandle.render(f5); RightHandle.render(f5); CenterLens.render(f5); TopHandle.render(f5); BottomHandle.render(f5); LensFocus.render(f5); } private void setRotation(ModelRenderer model, float x, float y, float z) { model.rotateAngleX = x; model.rotateAngleY = y; model.rotateAngleZ = z; } @Override public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); } public void renderLaser() { Bottom.render(0.0625F); Top.render(0.0625F); Right.render(0.0625F); Left.render(0.0625F); Back.render(0.0625F); LeftHandle.render(0.0625F); RightHandle.render(0.0625F); CenterLens.render(0.0625F); TopHandle.render(0.0625F); BottomHandle.render(0.0625F); } public void renderFocus() { LensFocus.render(0.0625F); } }
4,862
0.601604
0.53188
143
33
18.617609
109
false
false
0
0
0
0
0
0
2.006993
false
false
12
9a66cd0e500a0d1e040d922edfba0f6e02cc15b4
2,757,369,057,622
ef0685bf469349cda45f938d48a528c54bdcbb23
/app/src/main/java/com/ryw/zsxs/utils/StringUtil.java
94fc78f0954bfa515b5b0001d782312167ca3622
[]
no_license
JoseeRen/ZSXS
https://github.com/JoseeRen/ZSXS
22ace113c435c1087f28579044272bad984f9a3b
d6b11e5c80a79c0cfb14c89cb37594e45f88cbe6
refs/heads/master
2021-01-25T08:07:16.741000
2017-07-08T10:39:42
2017-07-08T10:39:42
93,717,252
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Create on 2017-6-28 下午10:31 * FileName: StringUtil.java * Author: Ren Yaowei * Blog: http://www.renyaowei.top * Email renyaowei@foxmail.com */ package com.ryw.zsxs.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Mr_Shadow on 2017/5/14. * 字符串相关的类 */ public class StringUtil { private static final int HOUR = 1000 * 60 * 60; private static final int MIN = 1000 * 60; private static final int SEC = 1000; private static String time; /** * 格式化时长 的方法 */ public static String formatDuration(int duration) { int hour = duration / HOUR; int min = duration % HOUR / MIN; int sec = duration % MIN / SEC; if (hour == 0) { time = String.format("%02d:%02d", min, sec); } else { time = String.format("%02d:%02d:%02d", hour, min, sec); } return time; } /** * 获取格式化后的系统时间 * hh:MM:ss * * @return */ public static String getSystemTime() { Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss"); String time = sf.format(date); return time; } /** * 格式化音频名称 */ public static String formatAudioName(String name) { //name.mp3 //substring 包含头不包含尾 name = name.substring(0, name.lastIndexOf(".")); return name; } }
UTF-8
Java
1,508
java
StringUtil.java
Java
[ { "context": "28 下午10:31\n * FileName: StringUtil.java\n * Author: Ren Yaowei\n * Blog: http://www.renyaowei.top\n * Email renyao", "end": 84, "score": 0.9998922348022461, "start": 74, "tag": "NAME", "value": "Ren Yaowei" }, { "context": " Yaowei\n * Blog: http://www.renyaowei.top\n * Email renyaowei@foxmail.com\n */\n\npackage com.ryw.zsxs.utils;\n\nimport java.tex", "end": 149, "score": 0.9999293088912964, "start": 128, "tag": "EMAIL", "value": "renyaowei@foxmail.com" }, { "context": "eFormat;\nimport java.util.Date;\n\n/**\n * Created by Mr_Shadow on 2017/5/14.\n * 字符串相关的类\n */\n\npublic class String", "end": 270, "score": 0.9985976815223694, "start": 261, "tag": "USERNAME", "value": "Mr_Shadow" } ]
null
[]
/* * Create on 2017-6-28 下午10:31 * FileName: StringUtil.java * Author: <NAME> * Blog: http://www.renyaowei.top * Email <EMAIL> */ package com.ryw.zsxs.utils; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Mr_Shadow on 2017/5/14. * 字符串相关的类 */ public class StringUtil { private static final int HOUR = 1000 * 60 * 60; private static final int MIN = 1000 * 60; private static final int SEC = 1000; private static String time; /** * 格式化时长 的方法 */ public static String formatDuration(int duration) { int hour = duration / HOUR; int min = duration % HOUR / MIN; int sec = duration % MIN / SEC; if (hour == 0) { time = String.format("%02d:%02d", min, sec); } else { time = String.format("%02d:%02d:%02d", hour, min, sec); } return time; } /** * 获取格式化后的系统时间 * hh:MM:ss * * @return */ public static String getSystemTime() { Date date = new Date(); SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss"); String time = sf.format(date); return time; } /** * 格式化音频名称 */ public static String formatAudioName(String name) { //name.mp3 //substring 包含头不包含尾 name = name.substring(0, name.lastIndexOf(".")); return name; } }
1,490
0.560393
0.525983
75
17.986666
18.513773
67
false
false
0
0
0
0
0
0
0.333333
false
false
12
59be8df98db548f65e15b37d086799a29a2a3a44
21,895,743,320,199
1a4e94bf9f187c89322feab26921179d1bda4d57
/src/main/java/com/jhlali/fr/repository/package-info.java
e0bdad4ca99a33c79d5ef89e315ffc134c359ced
[]
no_license
jamalhlali/footour
https://github.com/jamalhlali/footour
fb60e063407fa8c7d724efab19cca1385b78a27f
608edc95130f0a0a29102a2926dde7aebfb83755
refs/heads/master
2020-07-17T19:33:41.076000
2019-09-03T13:59:14
2019-09-03T13:59:14
206,083,183
0
0
null
false
2020-04-05T01:38:23
2019-09-03T13:23:30
2019-09-03T13:59:19
2020-04-05T01:38:22
953
0
0
2
Java
false
false
/** * Spring Data JPA repositories. */ package com.jhlali.fr.repository;
UTF-8
Java
75
java
package-info.java
Java
[]
null
[]
/** * Spring Data JPA repositories. */ package com.jhlali.fr.repository;
75
0.706667
0.706667
4
17.75
14.754236
33
false
false
0
0
0
0
0
0
0.25
false
false
12
544cf657b6f51d4b998604bbac226f1f969d2dbf
29,334,626,675,990
803dff0cea34fc6f7d028bca9a1e599dd10b7fdd
/src/main/java/org/its/dl/count/CountDLImpl.java
db407f16f4039cc04fb6347ac295fae9923a4c26
[]
no_license
fiacca98/SpringBootWeb
https://github.com/fiacca98/SpringBootWeb
7fe8721ab2b014e0266a0efb378273dd2367d979
2ba4a18bdbad11ed169a749bf416a2b67aec920a
refs/heads/master
2020-04-30T10:26:53.141000
2019-03-20T16:50:56
2019-03-20T16:50:56
176,777,598
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.its.dl.count; import javax.inject.Named; @Named("countDL") public class CountDLImpl implements CountDL { private int enabled = 0; @Override public void incrementEnabled() { enabled++; } @Override public void decrementEnabled() { enabled--; } public int getEnabled() { return enabled; } public void setEnabled(int enabled) { this.enabled = enabled; } }
UTF-8
Java
447
java
CountDLImpl.java
Java
[]
null
[]
package org.its.dl.count; import javax.inject.Named; @Named("countDL") public class CountDLImpl implements CountDL { private int enabled = 0; @Override public void incrementEnabled() { enabled++; } @Override public void decrementEnabled() { enabled--; } public int getEnabled() { return enabled; } public void setEnabled(int enabled) { this.enabled = enabled; } }
447
0.610738
0.608501
27
15.555555
14.345818
45
false
false
0
0
0
0
0
0
0.259259
false
false
12
afad1ecde30194eb83f79a8d33e04870790c0c1f
32,366,873,597,302
89f59d74a1ef859112e6b18b5561508ce1f3e261
/src/Aula_06/testaListaEncadeada.java
f731ab596f444fe998313efc3bba2b37632c5522
[ "MIT" ]
permissive
gabrielribeiroo/AulasEstruturaDados
https://github.com/gabrielribeiroo/AulasEstruturaDados
f642e262071e412089ce6cfedf931c5c6a55891f
8e28a7c872df565220674b2c353181c1af36d02a
refs/heads/master
2020-07-08T13:31:57.469000
2019-11-07T01:16:29
2019-11-07T01:16:29
203,689,706
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Aula_06; /** * * @author gabriel.rvital */ public class testaListaEncadeada { public static void main(String[] args) { /** * No p = new No(10,null); No q = new No(20,p); No l = new No(30,q); * System.out.println(l); * */ ListaEncadeada lst = new ListaEncadeada(); lst.insereInicio(30); lst.insereInicio(20); lst.insereInicio(10); lst.insereFinal(40); lst.insereFinal(50); lst.insereOrdenado(35); lst.insereOrdenado(5); lst.insereOrdenado(85); System.out.println(lst); System.out.println(lst.buscaLinear(20)); System.out.println(lst.buscaLinear(13)); System.out.println(lst.buscaLinear2(40)); System.out.println(lst.buscaLinear2(42)); System.out.println(lst.buscaLinearRecurcivaR(40)); System.out.println(lst.buscaLinearRecurcivaR(42)); System.out.println(lst.buscaLinear2RecursivaR(40)); System.out.println(lst.buscaLinear2RecursivaR(42)); lst.insereFinalR(33); lst.insereFinalR(44); System.out.println(lst); lst.insereOrdenadoR(3); lst.insereOrdenadoR(39); lst.insereOrdenadoR(13); System.out.println(lst); lst.removerInicio(); System.out.println(lst); lst.removerFinal(); System.out.println(lst); lst.removerOrdenado(35); System.out.println(lst); lst.removerOrdenado(13); System.out.println(lst); lst.removerOrdenado(33); System.out.println(lst); lst.removerFinalRecursivo(); System.out.println(lst); lst.inverterLista(); System.out.println(lst); } }
UTF-8
Java
1,980
java
testaListaEncadeada.java
Java
[ { "context": "tor.\r\n */\r\npackage Aula_06;\r\n\r\n/**\r\n *\r\n * @author gabriel.rvital\r\n */\r\npublic class testaListaEncadeada {\r\n\r\n p", "end": 244, "score": 0.9761855006217957, "start": 230, "tag": "NAME", "value": "gabriel.rvital" } ]
null
[]
/* * 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 Aula_06; /** * * @author gabriel.rvital */ public class testaListaEncadeada { public static void main(String[] args) { /** * No p = new No(10,null); No q = new No(20,p); No l = new No(30,q); * System.out.println(l); * */ ListaEncadeada lst = new ListaEncadeada(); lst.insereInicio(30); lst.insereInicio(20); lst.insereInicio(10); lst.insereFinal(40); lst.insereFinal(50); lst.insereOrdenado(35); lst.insereOrdenado(5); lst.insereOrdenado(85); System.out.println(lst); System.out.println(lst.buscaLinear(20)); System.out.println(lst.buscaLinear(13)); System.out.println(lst.buscaLinear2(40)); System.out.println(lst.buscaLinear2(42)); System.out.println(lst.buscaLinearRecurcivaR(40)); System.out.println(lst.buscaLinearRecurcivaR(42)); System.out.println(lst.buscaLinear2RecursivaR(40)); System.out.println(lst.buscaLinear2RecursivaR(42)); lst.insereFinalR(33); lst.insereFinalR(44); System.out.println(lst); lst.insereOrdenadoR(3); lst.insereOrdenadoR(39); lst.insereOrdenadoR(13); System.out.println(lst); lst.removerInicio(); System.out.println(lst); lst.removerFinal(); System.out.println(lst); lst.removerOrdenado(35); System.out.println(lst); lst.removerOrdenado(13); System.out.println(lst); lst.removerOrdenado(33); System.out.println(lst); lst.removerFinalRecursivo(); System.out.println(lst); lst.inverterLista(); System.out.println(lst); } }
1,980
0.590404
0.561111
63
29.428572
18.594004
79
false
false
0
0
0
0
0
0
0.793651
false
false
12
d5bcba98faa8b55dd0e0d42976ae7b6f5a7b6889
10,591,389,360,445
46a34337a3084e8937967518942022599f3fa205
/src/test/java/testng/example/listner/SuiteListeners.java
db7894abb98937e5065449d2a7de87bb61f5eb84
[]
no_license
ashishsingh123/testnglearning
https://github.com/ashishsingh123/testnglearning
d5c63c282185d9fe37f99e3ea2e252938a2dd1c6
97ce7a96518955fbe66cc6e43cde6cc00554c9f4
refs/heads/master
2023-06-01T08:26:11.925000
2020-06-29T09:21:47
2020-06-29T09:21:47
272,475,949
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testng.example.listner; import org.testng.ISuite; import org.testng.ISuiteListener; public class SuiteListeners implements ISuiteListener { public void onStart(ISuite suite) { System.out.println("Suite executed onStart" + suite.getName()); } public void onFinish(ISuite suite) { System.out.println("Suite executed onFinish" + suite.getName()); } }
UTF-8
Java
392
java
SuiteListeners.java
Java
[]
null
[]
package testng.example.listner; import org.testng.ISuite; import org.testng.ISuiteListener; public class SuiteListeners implements ISuiteListener { public void onStart(ISuite suite) { System.out.println("Suite executed onStart" + suite.getName()); } public void onFinish(ISuite suite) { System.out.println("Suite executed onFinish" + suite.getName()); } }
392
0.714286
0.714286
13
29.153847
25.322067
73
false
false
0
0
0
0
0
0
0.384615
false
false
12
5f85310ed17ee05a511c0fba08d6b54d12b609b0
953,482,789,942
ff5f00be10ef21710493902d0ad334c556ac1221
/pkuhit.iih.mr-impl/src/main/java/pkuhit/iih/mr/md/dao/custom/CusMdMetaElementValueDaoImpl.java
49f0b7c41108b123ac431e8c04768a16280f3a6c
[]
no_license
sun-wangbaiyu/emr-code
https://github.com/sun-wangbaiyu/emr-code
2ed323a682f42db1ce3c3c61c7680de2f80d6290
034f2a6a969b55ff97c8b8cdaff1e0c0615a0dc7
refs/heads/master
2020-05-16T09:14:30.758000
2017-11-19T03:31:40
2017-11-19T03:31:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pkuhit.iih.mr.md.dao.custom; /** */ @org.springframework.stereotype.Repository() @javax.annotation.Generated(value = { "Doma", "1.35.0" }, date = "2017-01-01T01:49:39.019+0800") public class CusMdMetaElementValueDaoImpl extends org.seasar.doma.internal.jdbc.dao.AbstractDao implements pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDao { static { org.seasar.doma.internal.Artifact.validateVersion("1.35.0"); } /** * @param config the config */ @org.springframework.beans.factory.annotation.Autowired() public CusMdMetaElementValueDaoImpl(org.seasar.doma.jdbc.Config config) { super(config); } @Override public java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue> selectByDataElementCd(java.lang.String dataElementCd) { entering("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "selectByDataElementCd", dataElementCd); try { org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery __query = new org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery(); __query.setConfig(config); __query.setSqlFilePath("META-INF/pkuhit/iih/mr/md/dao/custom/CusMdMetaElementValueDao/selectByDataElementCd.sql"); __query.addParameter("dataElementCd", java.lang.String.class, dataElementCd); __query.setCallerClassName("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl"); __query.setCallerMethodName("selectByDataElementCd"); __query.setResultEnsured(false); __query.setResultMappingEnsured(false); __query.setQueryTimeout(-1); __query.setMaxRows(-1); __query.setFetchSize(-1); __query.prepare(); org.seasar.doma.internal.jdbc.command.SelectCommand<java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue>> __command = new org.seasar.doma.internal.jdbc.command.SelectCommand<java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue>>(__query, new org.seasar.doma.internal.jdbc.command.EntityResultListHandler<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue>(pkuhit.iih.mr.md.dao.auto.entity._MdMetaElementValue.getSingletonInternal())); java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue> __result = __command.execute(); __query.complete(); exiting("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "selectByDataElementCd", __result); return __result; } catch (java.lang.RuntimeException __e) { throwing("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "selectByDataElementCd", __e); throw __e; } } @Override public java.lang.String getNewSn() { entering("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getNewSn"); try { org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery __query = new org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery(); __query.setConfig(config); __query.setSqlFilePath("META-INF/pkuhit/iih/mr/md/dao/custom/CusMdMetaElementValueDao/getNewSn.sql"); __query.setCallerClassName("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl"); __query.setCallerMethodName("getNewSn"); __query.setResultEnsured(false); __query.setResultMappingEnsured(false); __query.setQueryTimeout(-1); __query.setMaxRows(-1); __query.setFetchSize(-1); __query.prepare(); org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String> __command = new org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String>(__query, new org.seasar.doma.internal.jdbc.command.BasicSingleResultHandler<java.lang.String>(new org.seasar.doma.wrapper.StringWrapper(), false)); java.lang.String __result = __command.execute(); __query.complete(); exiting("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getNewSn", __result); return __result; } catch (java.lang.RuntimeException __e) { throwing("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getNewSn", __e); throw __e; } } @Override public java.lang.String getMaxDimenValueCode(java.lang.String dataElementCd) { entering("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getMaxDimenValueCode", dataElementCd); try { org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery __query = new org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery(); __query.setConfig(config); __query.setSqlFilePath("META-INF/pkuhit/iih/mr/md/dao/custom/CusMdMetaElementValueDao/getMaxDimenValueCode.sql"); __query.addParameter("dataElementCd", java.lang.String.class, dataElementCd); __query.setCallerClassName("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl"); __query.setCallerMethodName("getMaxDimenValueCode"); __query.setResultEnsured(false); __query.setResultMappingEnsured(false); __query.setQueryTimeout(-1); __query.setMaxRows(-1); __query.setFetchSize(-1); __query.prepare(); org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String> __command = new org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String>(__query, new org.seasar.doma.internal.jdbc.command.BasicSingleResultHandler<java.lang.String>(new org.seasar.doma.wrapper.StringWrapper(), false)); java.lang.String __result = __command.execute(); __query.complete(); exiting("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getMaxDimenValueCode", __result); return __result; } catch (java.lang.RuntimeException __e) { throwing("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getMaxDimenValueCode", __e); throw __e; } } }
UTF-8
Java
6,176
java
CusMdMetaElementValueDaoImpl.java
Java
[]
null
[]
package pkuhit.iih.mr.md.dao.custom; /** */ @org.springframework.stereotype.Repository() @javax.annotation.Generated(value = { "Doma", "1.35.0" }, date = "2017-01-01T01:49:39.019+0800") public class CusMdMetaElementValueDaoImpl extends org.seasar.doma.internal.jdbc.dao.AbstractDao implements pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDao { static { org.seasar.doma.internal.Artifact.validateVersion("1.35.0"); } /** * @param config the config */ @org.springframework.beans.factory.annotation.Autowired() public CusMdMetaElementValueDaoImpl(org.seasar.doma.jdbc.Config config) { super(config); } @Override public java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue> selectByDataElementCd(java.lang.String dataElementCd) { entering("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "selectByDataElementCd", dataElementCd); try { org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery __query = new org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery(); __query.setConfig(config); __query.setSqlFilePath("META-INF/pkuhit/iih/mr/md/dao/custom/CusMdMetaElementValueDao/selectByDataElementCd.sql"); __query.addParameter("dataElementCd", java.lang.String.class, dataElementCd); __query.setCallerClassName("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl"); __query.setCallerMethodName("selectByDataElementCd"); __query.setResultEnsured(false); __query.setResultMappingEnsured(false); __query.setQueryTimeout(-1); __query.setMaxRows(-1); __query.setFetchSize(-1); __query.prepare(); org.seasar.doma.internal.jdbc.command.SelectCommand<java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue>> __command = new org.seasar.doma.internal.jdbc.command.SelectCommand<java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue>>(__query, new org.seasar.doma.internal.jdbc.command.EntityResultListHandler<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue>(pkuhit.iih.mr.md.dao.auto.entity._MdMetaElementValue.getSingletonInternal())); java.util.List<pkuhit.iih.mr.md.dao.auto.entity.MdMetaElementValue> __result = __command.execute(); __query.complete(); exiting("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "selectByDataElementCd", __result); return __result; } catch (java.lang.RuntimeException __e) { throwing("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "selectByDataElementCd", __e); throw __e; } } @Override public java.lang.String getNewSn() { entering("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getNewSn"); try { org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery __query = new org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery(); __query.setConfig(config); __query.setSqlFilePath("META-INF/pkuhit/iih/mr/md/dao/custom/CusMdMetaElementValueDao/getNewSn.sql"); __query.setCallerClassName("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl"); __query.setCallerMethodName("getNewSn"); __query.setResultEnsured(false); __query.setResultMappingEnsured(false); __query.setQueryTimeout(-1); __query.setMaxRows(-1); __query.setFetchSize(-1); __query.prepare(); org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String> __command = new org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String>(__query, new org.seasar.doma.internal.jdbc.command.BasicSingleResultHandler<java.lang.String>(new org.seasar.doma.wrapper.StringWrapper(), false)); java.lang.String __result = __command.execute(); __query.complete(); exiting("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getNewSn", __result); return __result; } catch (java.lang.RuntimeException __e) { throwing("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getNewSn", __e); throw __e; } } @Override public java.lang.String getMaxDimenValueCode(java.lang.String dataElementCd) { entering("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getMaxDimenValueCode", dataElementCd); try { org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery __query = new org.seasar.doma.internal.jdbc.query.SqlFileSelectQuery(); __query.setConfig(config); __query.setSqlFilePath("META-INF/pkuhit/iih/mr/md/dao/custom/CusMdMetaElementValueDao/getMaxDimenValueCode.sql"); __query.addParameter("dataElementCd", java.lang.String.class, dataElementCd); __query.setCallerClassName("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl"); __query.setCallerMethodName("getMaxDimenValueCode"); __query.setResultEnsured(false); __query.setResultMappingEnsured(false); __query.setQueryTimeout(-1); __query.setMaxRows(-1); __query.setFetchSize(-1); __query.prepare(); org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String> __command = new org.seasar.doma.internal.jdbc.command.SelectCommand<java.lang.String>(__query, new org.seasar.doma.internal.jdbc.command.BasicSingleResultHandler<java.lang.String>(new org.seasar.doma.wrapper.StringWrapper(), false)); java.lang.String __result = __command.execute(); __query.complete(); exiting("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getMaxDimenValueCode", __result); return __result; } catch (java.lang.RuntimeException __e) { throwing("pkuhit.iih.mr.md.dao.custom.CusMdMetaElementValueDaoImpl", "getMaxDimenValueCode", __e); throw __e; } } }
6,176
0.665641
0.659488
100
59.759998
69.300087
476
false
false
0
0
0
0
78
0.035622
0.9
false
false
12
125abe665476f3684b7cf20a6920ba710b6c63fa
953,482,788,550
1acd752e7577a83bd55f25764a328d00c0ef1b89
/src/modelo/division/Division.java
db9f7d1c1b1bfe6b4d0831f00e89ca822607761f
[]
no_license
eliasgomezv/sistema_gestion_docente
https://github.com/eliasgomezv/sistema_gestion_docente
097c04d91c63a9fba0c30bfd31636a41013b150d
ad9936d1c15c240b9256a4d9884a2617c3c17339
refs/heads/master
2020-03-11T17:36:22.007000
2018-04-18T01:39:01
2018-04-18T01:39:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package modelo.division; import java.time.LocalDate; import modelo.docente.IDocente; public class Division implements IDivision { private int codigo; private String descripcion; private IDocente jefe; private String disposicion; private LocalDate dispDesde; private LocalDate dispHasta; @Override public IDivision clone() { return (IDivision) new Division( this.codigo, this.descripcion, this.jefe, this.disposicion, this.dispDesde, this.dispHasta ); } public Division(int codigo, String descripcion, IDocente jefe, String disposicion, LocalDate dispDesde, LocalDate dispHasta) { this.codigo = codigo; this.descripcion = descripcion; this.jefe = jefe; this.disposicion = disposicion; this.dispDesde = dispDesde; this.dispHasta = dispHasta; } @Override public int getCodigo() { return this.codigo; } @Override public void setCodigo(int codigo) { this.codigo = codigo; } @Override public String getDescripcion() { return this.descripcion; } @Override public void setDescripcion(String descripcion) { this.descripcion = descripcion; } @Override public IDocente getJefe() { return this.jefe; } @Override public void setJefe(IDocente jefe) { this.jefe = jefe; } @Override public String getDisposicion() { return this.disposicion; } @Override public void setDisposicion(String disposicion) { this.disposicion = disposicion; } @Override public LocalDate getDispDesde() { return this.dispDesde; } @Override public void setDispDesde(LocalDate dispDesde) { this.dispDesde = dispDesde; } @Override public LocalDate getDispHasta() { return this.dispHasta; } @Override public void setDispHasta(LocalDate dispHasta) { this.dispHasta = dispHasta; } }
UTF-8
Java
2,051
java
Division.java
Java
[]
null
[]
package modelo.division; import java.time.LocalDate; import modelo.docente.IDocente; public class Division implements IDivision { private int codigo; private String descripcion; private IDocente jefe; private String disposicion; private LocalDate dispDesde; private LocalDate dispHasta; @Override public IDivision clone() { return (IDivision) new Division( this.codigo, this.descripcion, this.jefe, this.disposicion, this.dispDesde, this.dispHasta ); } public Division(int codigo, String descripcion, IDocente jefe, String disposicion, LocalDate dispDesde, LocalDate dispHasta) { this.codigo = codigo; this.descripcion = descripcion; this.jefe = jefe; this.disposicion = disposicion; this.dispDesde = dispDesde; this.dispHasta = dispHasta; } @Override public int getCodigo() { return this.codigo; } @Override public void setCodigo(int codigo) { this.codigo = codigo; } @Override public String getDescripcion() { return this.descripcion; } @Override public void setDescripcion(String descripcion) { this.descripcion = descripcion; } @Override public IDocente getJefe() { return this.jefe; } @Override public void setJefe(IDocente jefe) { this.jefe = jefe; } @Override public String getDisposicion() { return this.disposicion; } @Override public void setDisposicion(String disposicion) { this.disposicion = disposicion; } @Override public LocalDate getDispDesde() { return this.dispDesde; } @Override public void setDispDesde(LocalDate dispDesde) { this.dispDesde = dispDesde; } @Override public LocalDate getDispHasta() { return this.dispHasta; } @Override public void setDispHasta(LocalDate dispHasta) { this.dispHasta = dispHasta; } }
2,051
0.630424
0.630424
100
19.52
16.683813
68
false
false
0
0
0
0
0
0
0.49
false
false
12
3930bef682142e3768777da0b9d6fa20a6c6b36d
12,335,146,075,955
3db7f518c9a0ce46c076c4f131ec7566f6a57319
/src/test/java/Scenario_Component/Scenario_Search.java
8ee26ceee886a046931c15f228ee4f1c3146b1a7
[]
no_license
divyasiri49/Selenium_Frame_May
https://github.com/divyasiri49/Selenium_Frame_May
35030aeebe668374f583312cf54859a39e3a0c0b
2c1ed79938fb973b38b15d1e5a2ad29a5fe953c6
refs/heads/master
2020-03-16T03:04:03.197000
2018-05-07T15:23:10
2018-05-07T15:23:10
132,479,675
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Scenario_Component; import java.io.IOException; import java.util.Map; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import Generic_Component.Base_Class; import PageObject_Component.Pf_HomePage; public class Scenario_Search extends Base_Class { @Test(dataProvider="dp_ValidSearch", dataProviderClass=DataProvider_Component.DataProvider_loaddata.class,groups={"regression"}) public void testValidSearchItem(Map<String, String> search) throws IOException { SoftAssert sAssert = new SoftAssert(); String tc_id = search.get("TC_ID"); String order_set = search.get("Order_Set"); String search_item = search.get("Search_Item"); String expRes = search.get("Exp_Result").replace(".0",""); log.info("Executing the testcase "+tc_id+" order set is "+order_set); Pf_HomePage pfHomePage = new Pf_HomePage(driver); pfHomePage.ClickSearch(search_item); String actRes = pfHomePage.getValidSearchMsg(); if(actRes.equals(expRes)) { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); } else { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); CaptureScreenshot(tc_id, order_set); sAssert.fail("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); } sAssert.assertAll(); } @Test(dataProvider="dp_InvalidSearch", dataProviderClass=DataProvider_Component.DataProvider_loaddata.class,groups={"smoke"}) public void testInvalidSearchItem(Map<String, String> search) throws IOException { SoftAssert sAssert = new SoftAssert(); String tc_id = search.get("TC_ID"); String order_set = search.get("Order_Set"); String search_item = search.get("Search_Item"); String expRes = search.get("Exp_Result"); log.info("Executing the testcase "+tc_id+" order set is "+order_set); Pf_HomePage pfHomePage = new Pf_HomePage(driver); pfHomePage.ClickSearch(search_item); String actRes = pfHomePage.getInvalidSearchMsg(); if(actRes.equals(expRes)) { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); } else { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); CaptureScreenshot(tc_id, order_set); sAssert.fail("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); } sAssert.assertAll(); } }
UTF-8
Java
2,734
java
Scenario_Search.java
Java
[]
null
[]
package Scenario_Component; import java.io.IOException; import java.util.Map; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import Generic_Component.Base_Class; import PageObject_Component.Pf_HomePage; public class Scenario_Search extends Base_Class { @Test(dataProvider="dp_ValidSearch", dataProviderClass=DataProvider_Component.DataProvider_loaddata.class,groups={"regression"}) public void testValidSearchItem(Map<String, String> search) throws IOException { SoftAssert sAssert = new SoftAssert(); String tc_id = search.get("TC_ID"); String order_set = search.get("Order_Set"); String search_item = search.get("Search_Item"); String expRes = search.get("Exp_Result").replace(".0",""); log.info("Executing the testcase "+tc_id+" order set is "+order_set); Pf_HomePage pfHomePage = new Pf_HomePage(driver); pfHomePage.ClickSearch(search_item); String actRes = pfHomePage.getValidSearchMsg(); if(actRes.equals(expRes)) { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); } else { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); CaptureScreenshot(tc_id, order_set); sAssert.fail("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); } sAssert.assertAll(); } @Test(dataProvider="dp_InvalidSearch", dataProviderClass=DataProvider_Component.DataProvider_loaddata.class,groups={"smoke"}) public void testInvalidSearchItem(Map<String, String> search) throws IOException { SoftAssert sAssert = new SoftAssert(); String tc_id = search.get("TC_ID"); String order_set = search.get("Order_Set"); String search_item = search.get("Search_Item"); String expRes = search.get("Exp_Result"); log.info("Executing the testcase "+tc_id+" order set is "+order_set); Pf_HomePage pfHomePage = new Pf_HomePage(driver); pfHomePage.ClickSearch(search_item); String actRes = pfHomePage.getInvalidSearchMsg(); if(actRes.equals(expRes)) { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); } else { //System.out.println("Passed as Actual result is "+actRes+" "+"Expected Result "+expRes); log.info("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); CaptureScreenshot(tc_id, order_set); sAssert.fail("Failed as Actual result is "+actRes+" "+"Expected Result "+expRes); } sAssert.assertAll(); } }
2,734
0.708852
0.708486
79
33.607594
33.539101
129
false
false
0
0
0
0
0
0
2.278481
false
false
12
4e9804c7143f05d47bf8eeb80cb2b353423b7551
19,112,604,511,438
578c8a449ece9a8d372aaab6068cd2242013cb55
/hotelbooking/src/main/java/project/selfefd/restcontroller/PanController.java
3b227c9372ddf2d8df5dd86d8049a6280d2c175c
[]
no_license
andrewsselvaraj/hotelbooking
https://github.com/andrewsselvaraj/hotelbooking
d70a2c90e77ef3c65ab17d9e26c25b341dfcebcb
c841bc6b79bae05c5f23ac3391888825d500b27e
refs/heads/master
2022-12-05T12:06:17.270000
2020-08-16T17:52:30
2020-08-16T17:52:30
282,397,837
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package project.selfefd.restcontroller; public class PanController { }
UTF-8
Java
73
java
PanController.java
Java
[]
null
[]
package project.selfefd.restcontroller; public class PanController { }
73
0.808219
0.808219
5
13.6
16.62047
39
false
false
0
0
0
0
0
0
0.2
false
false
12
691a8973e0e132ed292cd680a559dca4b317e9a7
19,696,720,022,961
a25894c9cfc153c6c149538150833bb244619ebb
/app/src/main/java/requestApiManager/PerformDevice.java
eca8ad752b93173ef6e8a74c0b9a04227357a17b
[]
no_license
kebouh/Android-SitchozrApp-AndroidStudio
https://github.com/kebouh/Android-SitchozrApp-AndroidStudio
2ab8b4c12b6f6fcff1853c49925507c8ef56933a
7a58a145d876cc749cbccff427a157c124653df1
refs/heads/master
2021-01-10T08:53:20.850000
2016-01-14T10:44:15
2016-01-14T10:44:15
45,260,675
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package requestApiManager; import interfaces.IRequestProcess; import sdk.SDKDevice; public class PerformDevice { public class PerformDeviceCreate implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.create()}; return result; } } public class PerformDeviceDelete implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.delete()}; return result; } } public class PerformDeviceRead implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.read()}; return result; } } public class PerformDeviceUpdate implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.update()}; return result; } } }
UTF-8
Java
1,195
java
PerformDevice.java
Java
[]
null
[]
package requestApiManager; import interfaces.IRequestProcess; import sdk.SDKDevice; public class PerformDevice { public class PerformDeviceCreate implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.create()}; return result; } } public class PerformDeviceDelete implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.delete()}; return result; } } public class PerformDeviceRead implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.read()}; return result; } } public class PerformDeviceUpdate implements IRequestProcess { @Override public Object[] performRequest(Object[] obj) { Object[] result = null; SDKDevice device = (SDKDevice)obj[1]; result = new Object[]{obj[0], device.update()}; return result; } } }
1,195
0.697071
0.690377
46
24.97826
20.749531
63
false
false
0
0
0
0
0
0
2.304348
false
false
12
f293eaea398f10643c5e9844d6547ed0f8ca6dfc
13,726,715,487,339
d7a926a60197d9433179f2a5894eebcb6deac2de
/src/serviceImpl/AuthorityServiceImpl.java
660a9788f46067679fe149d3dc317d71c412f330
[]
no_license
caocaobucaocao/SpringWeChat
https://github.com/caocaobucaocao/SpringWeChat
ae03bf8d5c05d43ca903e47eb5356dcd7238aa2a
802849d930554c9c410ded4052eb1783013ada25
refs/heads/master
2020-01-22T14:08:58.626000
2017-06-27T10:21:44
2017-06-27T10:21:44
83,286,065
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package serviceImpl; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import dbdao.AuthorityDao; import model.Authority; import service.AuthorityService; @Service @Scope("prototype") public class AuthorityServiceImpl implements AuthorityService { private AuthorityDao authorityDao; @Override public Authority getUserAuthorities(String username) { // TODO Auto-generated method stub return authorityDao.getUserAuthorities(username); } }
UTF-8
Java
500
java
AuthorityServiceImpl.java
Java
[]
null
[]
package serviceImpl; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import dbdao.AuthorityDao; import model.Authority; import service.AuthorityService; @Service @Scope("prototype") public class AuthorityServiceImpl implements AuthorityService { private AuthorityDao authorityDao; @Override public Authority getUserAuthorities(String username) { // TODO Auto-generated method stub return authorityDao.getUserAuthorities(username); } }
500
0.824
0.824
21
22.809525
20.895702
63
false
false
0
0
0
0
0
0
0.761905
false
false
12
2793374b7c0d56880ac309c4561c42573e51a5da
29,059,748,730,263
38a43de7e64ab157a4b45a1394d4fcfeed1fd8dc
/lib/java-stable_old/m/service/FileSystemAuthenticationSandbox.java
48f4f01327ccb6c3730fd60cfcbbb3b767c3d98c
[ "MIT" ]
permissive
massimilianonardi/m
https://github.com/massimilianonardi/m
c9fdb21e32f083fae868366ac6d22ab0f3ecedfd
93f6216ecc8e20de44561e95c6f760d0098a2c5c
refs/heads/master
2022-08-08T20:11:45.570000
2022-07-11T22:16:38
2022-07-11T22:16:38
215,794,121
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package m.service; import java.text.*; import java.util.*; import m.object.*; import m.conf.*; import m.auth.*; import m.file.*; import m.stream.*; public class FileSystemAuthenticationSandbox extends ConfigurableWrapper<___FileSystem> implements AuthorizedService, Authorizator.Listener { static protected final String CMD_SEPARATOR = " "; static protected final String CMD_READ = "read"; static protected final String CMD_WRITE = "write"; static protected final String CMD_MOVE = "move"; static protected final String CMD_SAVE = "save"; static protected final String CMD_SHARE = "share"; static protected final String DIR_SEPARATOR = "/"; static protected final String DIR_INDEX = "$index"; static protected final String DIR_HASH = "$hash"; static protected final String DIR_ABSOLUTE = "file"; static protected final String DIR_PROFILE = "$profile"; static protected final String DIR_USER = "$user"; static protected final String DIR_SESSION = "$session"; static protected final String ALIAS_ABSOLUTE = "@"; static protected final String ALIAS_PROFILE = "&"; static protected final String ALIAS_USER = "#"; static protected final String ALIAS_SESSION = "%"; static protected int MAX_RANDOM_SUFFIX = 1000000; static protected Random rnd = new Random(); public class FileAlias { protected String dir; protected String relPath; protected String path; public FileAlias(AuthorizationSession session, String alias) throws Exception { int index; index = alias.indexOf(DIR_SEPARATOR); if(index < 1) { throw new Exception(); } dir = alias.substring(0, index); relPath = alias.substring(index); if(java.nio.file.Paths.get(relPath).normalize().toString().startsWith("..")) { throw new Exception(); } String path; switch(dir) { case ALIAS_ABSOLUTE: path = DIR_ABSOLUTE; break; // case ALIAS_PROFILE: // List<String> authentications = session.authentications(); // path = DIR_PROFILE + DIR_SEPARATOR + authentications.get(authentications.size() - 1); // break; // case ALIAS_USER: // List<String> authentications = session.profiler().authentications().get("id"); // path = DIR_USER + DIR_SEPARATOR + authentications.get(authentications.size() - 1); // break; case ALIAS_SESSION: path = DIR_SESSION + DIR_SEPARATOR + session.id(); break; default: throw new Exception(); } if(relPath != null && !"".equals(relPath)) { path += DIR_SEPARATOR + relPath; } } public String dir() throws Exception { return dir; } public String relPath() throws Exception { return relPath; } public String path() throws Exception { return path; } } // public FileSystemAuthenticationSandbox() throws Exception public void configure(Obj params) throws Exception { // m.Global.objects.iface(Authorizator.class).addListener(this); } public void execute(AuthorizationSession session, String command, ObjInput in, ObjOutput out) throws Exception { String cmd; String dir; String relPath; String path; int index; index = command.indexOf(CMD_SEPARATOR); if(index < 1) { throw new Exception(); } cmd = command.substring(0, index); FileAlias alias = new FileAlias(session, command.substring(index)); dir = alias.dir(); relPath = alias.relPath(); path = alias.path(); // index = relPath.indexOf(DIR_SEPARATOR); // if(index < 1) // { // throw new Exception(); // } // dir = relPath.substring(0, index); // relPath = relPath.substring(index); // // if(java.nio.file.Paths.get(relPath).normalize().toString().startsWith("..")) // { // throw new Exception(); // } // switch(dir) // { // case ALIAS_ABSOLUTE: // path = DIR_ABSOLUTE; // break; // // case ALIAS_USER: // List<String> authentications = session.authentications(); // path = DIR_USER + DIR_SEPARATOR + authentications.get(authentications.size() - 1); // break; // // case ALIAS_SESSION: // path = DIR_SESSION + DIR_SEPARATOR + session.id(); // break; // // default: // throw new Exception(); // } // if(relPath != null && !"".equals(relPath)) // { // path += DIR_SEPARATOR + relPath; // } m.Global.log.debug(cmd, dir, relPath); String outPath; switch(cmd) { case CMD_READ: if(object.isFile(path)) { out.set(object.stream(path)); } else { out.set(object.list(path)); } break; case CMD_WRITE: if(relPath == null || "".equals(relPath)) { if(ALIAS_ABSOLUTE.equals(dir)) { path = object.file(); } else { // relPath = DIR_INDEX + DIR_SEPARATOR + System.currentTimeMillis() + "_" + command.hashCode(); relPath = DIR_INDEX + DIR_SEPARATOR + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()) + "_" + ("" + (rnd.nextInt(MAX_RANDOM_SUFFIX) + MAX_RANDOM_SUFFIX)).substring(1); path += DIR_SEPARATOR + relPath; object.file(path); } } else { object.file(path); } outPath = dir + DIR_SEPARATOR + relPath; object.stream(path).streamFromInput(in.stream()); out.set(outPath); break; case CMD_MOVE: String dest = DIR_SESSION + DIR_SEPARATOR + session.id() + DIR_SEPARATOR + in.string(); m.Global.log.debug(command, path, dest); object.move(path, dest); break; case CMD_SAVE: // anon session file to anon user file if(!ALIAS_SESSION.equals(dir) || relPath == null || "".equals(relPath)) { throw new Exception(); } FileAlias param = new FileAlias(session, in.string()); outPath = DIR_SESSION + DIR_SEPARATOR + session.id() + DIR_SEPARATOR + in.string(); m.Global.log.debug(command, path, outPath); object.move(path, param.path()); out.set(param.relPath()); break; case CMD_SHARE: // anon user file to anon abs file if(!ALIAS_SESSION.equals(dir) || relPath == null || "".equals(relPath)) { throw new Exception(); } // FileAlias param = new FileAlias(session, in.string()); // outPath = DIR_SESSION + DIR_SEPARATOR + session.id() + DIR_SEPARATOR + in.string(); // // m.Global.log.debug(command, path, outPath); // // object.move(path, param.path()); // out.set(param.relPath()); break; default: throw new Exception(); } } public void sessionCreated(AuthorizationSession session) throws Exception { object.nodes(DIR_SESSION + DIR_SEPARATOR + session.id()); } public void sessionDestroyed(AuthorizationSession session) throws Exception { object.delete(DIR_SESSION + DIR_SEPARATOR + session.id(), true); } public void sessionRenamed(AuthorizationSession session) throws Exception { } }
UTF-8
Java
7,566
java
FileSystemAuthenticationSandbox.java
Java
[]
null
[]
package m.service; import java.text.*; import java.util.*; import m.object.*; import m.conf.*; import m.auth.*; import m.file.*; import m.stream.*; public class FileSystemAuthenticationSandbox extends ConfigurableWrapper<___FileSystem> implements AuthorizedService, Authorizator.Listener { static protected final String CMD_SEPARATOR = " "; static protected final String CMD_READ = "read"; static protected final String CMD_WRITE = "write"; static protected final String CMD_MOVE = "move"; static protected final String CMD_SAVE = "save"; static protected final String CMD_SHARE = "share"; static protected final String DIR_SEPARATOR = "/"; static protected final String DIR_INDEX = "$index"; static protected final String DIR_HASH = "$hash"; static protected final String DIR_ABSOLUTE = "file"; static protected final String DIR_PROFILE = "$profile"; static protected final String DIR_USER = "$user"; static protected final String DIR_SESSION = "$session"; static protected final String ALIAS_ABSOLUTE = "@"; static protected final String ALIAS_PROFILE = "&"; static protected final String ALIAS_USER = "#"; static protected final String ALIAS_SESSION = "%"; static protected int MAX_RANDOM_SUFFIX = 1000000; static protected Random rnd = new Random(); public class FileAlias { protected String dir; protected String relPath; protected String path; public FileAlias(AuthorizationSession session, String alias) throws Exception { int index; index = alias.indexOf(DIR_SEPARATOR); if(index < 1) { throw new Exception(); } dir = alias.substring(0, index); relPath = alias.substring(index); if(java.nio.file.Paths.get(relPath).normalize().toString().startsWith("..")) { throw new Exception(); } String path; switch(dir) { case ALIAS_ABSOLUTE: path = DIR_ABSOLUTE; break; // case ALIAS_PROFILE: // List<String> authentications = session.authentications(); // path = DIR_PROFILE + DIR_SEPARATOR + authentications.get(authentications.size() - 1); // break; // case ALIAS_USER: // List<String> authentications = session.profiler().authentications().get("id"); // path = DIR_USER + DIR_SEPARATOR + authentications.get(authentications.size() - 1); // break; case ALIAS_SESSION: path = DIR_SESSION + DIR_SEPARATOR + session.id(); break; default: throw new Exception(); } if(relPath != null && !"".equals(relPath)) { path += DIR_SEPARATOR + relPath; } } public String dir() throws Exception { return dir; } public String relPath() throws Exception { return relPath; } public String path() throws Exception { return path; } } // public FileSystemAuthenticationSandbox() throws Exception public void configure(Obj params) throws Exception { // m.Global.objects.iface(Authorizator.class).addListener(this); } public void execute(AuthorizationSession session, String command, ObjInput in, ObjOutput out) throws Exception { String cmd; String dir; String relPath; String path; int index; index = command.indexOf(CMD_SEPARATOR); if(index < 1) { throw new Exception(); } cmd = command.substring(0, index); FileAlias alias = new FileAlias(session, command.substring(index)); dir = alias.dir(); relPath = alias.relPath(); path = alias.path(); // index = relPath.indexOf(DIR_SEPARATOR); // if(index < 1) // { // throw new Exception(); // } // dir = relPath.substring(0, index); // relPath = relPath.substring(index); // // if(java.nio.file.Paths.get(relPath).normalize().toString().startsWith("..")) // { // throw new Exception(); // } // switch(dir) // { // case ALIAS_ABSOLUTE: // path = DIR_ABSOLUTE; // break; // // case ALIAS_USER: // List<String> authentications = session.authentications(); // path = DIR_USER + DIR_SEPARATOR + authentications.get(authentications.size() - 1); // break; // // case ALIAS_SESSION: // path = DIR_SESSION + DIR_SEPARATOR + session.id(); // break; // // default: // throw new Exception(); // } // if(relPath != null && !"".equals(relPath)) // { // path += DIR_SEPARATOR + relPath; // } m.Global.log.debug(cmd, dir, relPath); String outPath; switch(cmd) { case CMD_READ: if(object.isFile(path)) { out.set(object.stream(path)); } else { out.set(object.list(path)); } break; case CMD_WRITE: if(relPath == null || "".equals(relPath)) { if(ALIAS_ABSOLUTE.equals(dir)) { path = object.file(); } else { // relPath = DIR_INDEX + DIR_SEPARATOR + System.currentTimeMillis() + "_" + command.hashCode(); relPath = DIR_INDEX + DIR_SEPARATOR + new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()) + "_" + ("" + (rnd.nextInt(MAX_RANDOM_SUFFIX) + MAX_RANDOM_SUFFIX)).substring(1); path += DIR_SEPARATOR + relPath; object.file(path); } } else { object.file(path); } outPath = dir + DIR_SEPARATOR + relPath; object.stream(path).streamFromInput(in.stream()); out.set(outPath); break; case CMD_MOVE: String dest = DIR_SESSION + DIR_SEPARATOR + session.id() + DIR_SEPARATOR + in.string(); m.Global.log.debug(command, path, dest); object.move(path, dest); break; case CMD_SAVE: // anon session file to anon user file if(!ALIAS_SESSION.equals(dir) || relPath == null || "".equals(relPath)) { throw new Exception(); } FileAlias param = new FileAlias(session, in.string()); outPath = DIR_SESSION + DIR_SEPARATOR + session.id() + DIR_SEPARATOR + in.string(); m.Global.log.debug(command, path, outPath); object.move(path, param.path()); out.set(param.relPath()); break; case CMD_SHARE: // anon user file to anon abs file if(!ALIAS_SESSION.equals(dir) || relPath == null || "".equals(relPath)) { throw new Exception(); } // FileAlias param = new FileAlias(session, in.string()); // outPath = DIR_SESSION + DIR_SEPARATOR + session.id() + DIR_SEPARATOR + in.string(); // // m.Global.log.debug(command, path, outPath); // // object.move(path, param.path()); // out.set(param.relPath()); break; default: throw new Exception(); } } public void sessionCreated(AuthorizationSession session) throws Exception { object.nodes(DIR_SESSION + DIR_SEPARATOR + session.id()); } public void sessionDestroyed(AuthorizationSession session) throws Exception { object.delete(DIR_SESSION + DIR_SEPARATOR + session.id(), true); } public void sessionRenamed(AuthorizationSession session) throws Exception { } }
7,566
0.575601
0.573354
270
27.022223
27.091604
194
false
false
0
0
0
0
0
0
0.548148
false
false
12
0bd693c1d523182f51be25c3b52f09b722656afb
10,110,353,024,498
b583e62623f7dd7601cddf190f0ec7793d4421a6
/learn/CoreJava/src/com/oracle/oops/part1/StaticEx3.java
694ddcba9d6d15ebbc63f8dd73dc6aefced3e42f
[]
no_license
Akshayk0367/java_core
https://github.com/Akshayk0367/java_core
a1e72f142d5e23934499592b41b9f204e3414c3c
16878344583cef215c4c897a37bacf4a2a442c9b
refs/heads/main
2023-07-04T14:29:04.837000
2021-08-12T03:51:10
2021-08-12T03:51:10
395,186,814
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oracle.oops.part1; public class StaticEx3 { public static void main(String[] args) { // TODO Auto-generated method stub Test t = new Test(); t = null; // now Test object is eligible for gc..garbage collection System.out.println(t.x); } } class Test{ static int x = 10; }
UTF-8
Java
314
java
StaticEx3.java
Java
[]
null
[]
package com.oracle.oops.part1; public class StaticEx3 { public static void main(String[] args) { // TODO Auto-generated method stub Test t = new Test(); t = null; // now Test object is eligible for gc..garbage collection System.out.println(t.x); } } class Test{ static int x = 10; }
314
0.646497
0.633758
16
17.625
19.189434
69
false
false
0
0
0
0
0
0
1
false
false
12
a8a8883ef7573576ab3b17d6d123d8f22f720cac
17,162,689,327,494
27e3179ed3ba4e5d8585d9b942ba0f687666d3a9
/src/main/java/com/light/graduation/redis/SaveUserToRedis.java
a945349d17f9942689eb8cad24887c6aff0cb623
[]
no_license
GuangPanSir/iaback
https://github.com/GuangPanSir/iaback
6e3da32dff8f404d1fae7235351a13220d1e3d87
060a8264b45aaa0c9263734b9e57d29bb82f8c41
refs/heads/master
2022-12-22T17:49:53.749000
2021-01-05T03:02:06
2021-01-05T03:02:06
241,284,507
0
0
null
false
2022-12-16T05:11:53
2020-02-18T05:58:10
2021-01-05T03:02:41
2022-12-16T05:11:52
108,545
0
0
10
Java
false
false
package com.light.graduation.redis; import com.light.graduation.dto.CheckLoginDTO; import org.jetbrains.annotations.NotNull; import org.springframework.data.redis.core.RedisTemplate; import java.util.Map; /** * @Author: Light * @Date 2020/3/7 17:15 */ public class SaveUserToRedis { /** * 将redis中没有的用户登录信息保存至redis */ public static void saveUserToRedis ( @NotNull RedisTemplate< String, Object > redisTemplate , @NotNull Map< Object, Object > redisMap , @NotNull CheckLoginDTO checkLoginUser ) { redisMap.put ( "userName" , checkLoginUser.getUserName ( ) ); redisMap.put ( "userPassword" , checkLoginUser.getUserPassword ( ) ); redisMap.put ( "identity" , checkLoginUser.getIdentity ( ) ); redisMap.put ( "isFirstLogin" , "1" ); //save to redis redisTemplate.opsForHash ( ).putAll ( "user:" + checkLoginUser.identity + ":" + checkLoginUser.getUserName ( ) , redisMap ); } }
UTF-8
Java
929
java
SaveUserToRedis.java
Java
[ { "context": "sTemplate;\n\nimport java.util.Map;\n\n/**\n * @Author: Light\n * @Date 2020/3/7 17:15\n */\npublic class SaveUser", "end": 229, "score": 0.575520396232605, "start": 224, "tag": "USERNAME", "value": "Light" } ]
null
[]
package com.light.graduation.redis; import com.light.graduation.dto.CheckLoginDTO; import org.jetbrains.annotations.NotNull; import org.springframework.data.redis.core.RedisTemplate; import java.util.Map; /** * @Author: Light * @Date 2020/3/7 17:15 */ public class SaveUserToRedis { /** * 将redis中没有的用户登录信息保存至redis */ public static void saveUserToRedis ( @NotNull RedisTemplate< String, Object > redisTemplate , @NotNull Map< Object, Object > redisMap , @NotNull CheckLoginDTO checkLoginUser ) { redisMap.put ( "userName" , checkLoginUser.getUserName ( ) ); redisMap.put ( "userPassword" , checkLoginUser.getUserPassword ( ) ); redisMap.put ( "identity" , checkLoginUser.getIdentity ( ) ); redisMap.put ( "isFirstLogin" , "1" ); //save to redis redisTemplate.opsForHash ( ).putAll ( "user:" + checkLoginUser.identity + ":" + checkLoginUser.getUserName ( ) , redisMap ); } }
929
0.722531
0.710322
26
33.653847
41.25618
178
false
false
0
0
0
0
0
0
1.461538
false
false
12
871ea8ea6f71c834ab1eb798bece8482dd64dd1f
11,957,188,964,092
548ad85975f2c2e52a461740bed6373bd7bbf9fa
/src/main/java/first/food/controller/FoodCategoryController.java
a2a7bf9d3ef76777c114aacce5354046e3884e2d
[]
no_license
sc-kim/FriendsConnection
https://github.com/sc-kim/FriendsConnection
c586c355f638a880019217c62a687653a1fdc7a7
c083f5141517c301a3fc16a367e19f39e2c08f2d
refs/heads/master
2020-12-24T07:17:47.042000
2018-07-13T05:51:52
2018-07-13T05:51:52
56,508,077
0
1
null
false
2018-07-13T05:51:53
2016-04-18T13:00:36
2016-04-18T13:09:56
2018-07-13T05:51:53
36,945
0
1
0
Java
false
null
package first.food.controller; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import first.common.common.CommandMap; import first.food.dto.FoodCategoryDTO; import first.food.service.FoodCategoryService; @Controller public class FoodCategoryController { protected Log log = LogFactory.getLog(this.getClass()); @Resource(name="foodCategoryService") private FoodCategoryService fService; @RequestMapping(value="/food.do") public ModelAndView foodCategory(CommandMap commandMap) throws Exception{ ModelAndView mv = new ModelAndView("/food/food"); System.out.println(mv); return mv; } @RequestMapping(value="/foodCategory/selectFoodRankList.do", method = RequestMethod.POST) public ModelAndView selectFoodRankList(CommandMap commandMap) throws Exception{ ModelAndView mv = new ModelAndView("jsonView"); List<Map<String,Object>> list = fService.selectFoodRankList(commandMap.getMap()); mv.addObject("list", list); System.out.println(mv); return mv; } @RequestMapping(value="/foodCategory/updateFoodData.do", method=RequestMethod.POST) public void updateFoodRankList(CommandMap commandMap, FoodCategoryDTO fDTO, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{ log.debug(this.getClass()); String[] test = request.getParameterValues("params"); for(String str : test){ System.out.println( str ); } /* fDTO.setDocId(request.getParameter("docId")); fDTO.setLikesCount(Integer.parseInt((request.getParameter("likesCount")))); try{ fService.updateFoodRankList(fDTO); }catch(Exception e ){ e.printStackTrace(); } */ } }
UTF-8
Java
2,222
java
FoodCategoryController.java
Java
[]
null
[]
package first.food.controller; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import first.common.common.CommandMap; import first.food.dto.FoodCategoryDTO; import first.food.service.FoodCategoryService; @Controller public class FoodCategoryController { protected Log log = LogFactory.getLog(this.getClass()); @Resource(name="foodCategoryService") private FoodCategoryService fService; @RequestMapping(value="/food.do") public ModelAndView foodCategory(CommandMap commandMap) throws Exception{ ModelAndView mv = new ModelAndView("/food/food"); System.out.println(mv); return mv; } @RequestMapping(value="/foodCategory/selectFoodRankList.do", method = RequestMethod.POST) public ModelAndView selectFoodRankList(CommandMap commandMap) throws Exception{ ModelAndView mv = new ModelAndView("jsonView"); List<Map<String,Object>> list = fService.selectFoodRankList(commandMap.getMap()); mv.addObject("list", list); System.out.println(mv); return mv; } @RequestMapping(value="/foodCategory/updateFoodData.do", method=RequestMethod.POST) public void updateFoodRankList(CommandMap commandMap, FoodCategoryDTO fDTO, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{ log.debug(this.getClass()); String[] test = request.getParameterValues("params"); for(String str : test){ System.out.println( str ); } /* fDTO.setDocId(request.getParameter("docId")); fDTO.setLikesCount(Integer.parseInt((request.getParameter("likesCount")))); try{ fService.updateFoodRankList(fDTO); }catch(Exception e ){ e.printStackTrace(); } */ } }
2,222
0.743474
0.743474
78
27.487179
26.985155
99
false
false
0
0
0
0
0
0
1.320513
false
false
12
830dc0984462efeaad195f6b3ea7ea04921b4d5d
19,129,784,348,355
88ec26317575df39254e5e357657362a6bdfd01d
/src/test/java/ControllerTests/ShopControllerTests.java
4fa8f413163c19e4ecbb27aa0f9f611ac7e624aa
[]
no_license
kamil7108/MyShop
https://github.com/kamil7108/MyShop
404a35a4a32d1319d2188454b684dca786e4bd14
66ccceb7190388414041d7c498bb27a10d0cb558
refs/heads/master
2023-01-25T04:13:18.063000
2020-11-28T20:57:09
2020-11-28T20:57:09
313,133,471
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ControllerTests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class ShopControllerTests { @BeforeEach void init(){ } @Test public void test_takeArgs_with_wrong_number_of_params(){ } }
UTF-8
Java
260
java
ShopControllerTests.java
Java
[]
null
[]
package ControllerTests; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class ShopControllerTests { @BeforeEach void init(){ } @Test public void test_takeArgs_with_wrong_number_of_params(){ } }
260
0.696154
0.696154
17
14.294118
17.535727
60
false
false
0
0
0
0
0
0
0.176471
false
false
12
59b2b37615f8d05addea02831d67011b829807d9
4,947,802,340,653
fa93da963a120fb3126d226bca80b1abee5aee8e
/treebase-core/src/main/java/org/cipres/treebase/domain/matrix/CharWeight.java
1e11ae2036f64f98a9eb539244b350e822785a96
[ "BSD-3-Clause" ]
permissive
TreeBASE/treebase
https://github.com/TreeBASE/treebase
b67402f27c443aa2edf473ac38b8e5824958bb4a
d098e885d394d6bddb9338c82c727d527747b73e
refs/heads/master
2022-09-03T22:56:57.401000
2022-08-24T07:12:31
2022-08-24T07:12:31
45,452,022
7
2
BSD-3-Clause
false
2022-06-27T07:05:31
2015-11-03T08:24:31
2022-05-19T20:35:31
2022-06-27T07:05:30
220,560
7
2
88
Java
false
false
package org.cipres.treebase.domain.matrix; import java.util.ArrayList; import java.util.Collection; import javax.persistence.AttributeOverride; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.cipres.treebase.domain.AbstractPersistedObject; /** * CharWeight.java * * Created on Mar 27, 2006 * * @author Jin Ruan * */ @Entity @Table(name = "CHARWEIGHT") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.CHAR) @AttributeOverride(name = "id", column = @Column(name = "CHARWEIGHT_ID")) @DiscriminatorValue("-") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "matrixCache") public abstract class CharWeight extends AbstractPersistedObject { private Collection<ColumnRange> mWeightColumns = new ArrayList<ColumnRange>(); /** * Constructor. */ public CharWeight() { super(); } /** * Return the weight columns. * * @return */ @OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}) @JoinTable(name = "CharWeight_ColRange", joinColumns = {@JoinColumn(name = "CHARWEIGHT_ID")}, inverseJoinColumns = @JoinColumn(name = "COLUMNRANGE_ID")) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "matrixCache") public Collection<ColumnRange> getWeightColumns() { return mWeightColumns; } /** * Set the weight columns. */ public void setWeightColumns(Collection<ColumnRange> pWeightColumns) { mWeightColumns = pWeightColumns; } /** * Print the weight to the string buffer. * * Return the string buffer for call chaining. * * @return */ public abstract StringBuilder appendWeight(StringBuilder pBuilder); /** * Get the weight and the associated columns. * * @return */ @Transient public String getWeightAndColumnAsString() { StringBuilder sb = new StringBuilder(); appendWeight(sb).append(": "); for (ColumnRange colRange : getWeightColumns()) { colRange.appendRange(sb).append(" "); } return sb.toString(); } }
UTF-8
Java
2,694
java
CharWeight.java
Java
[ { "context": "\r\n * \r\n * Created on Mar 27, 2006\r\n * \r\n * @author Jin Ruan\r\n * \r\n */\r\n@Entity\r\n@Table(name = \"CHARWEIGHT\")\r\n", "end": 910, "score": 0.9998060464859009, "start": 902, "tag": "NAME", "value": "Jin Ruan" } ]
null
[]
package org.cipres.treebase.domain.matrix; import java.util.ArrayList; import java.util.Collection; import javax.persistence.AttributeOverride; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.cipres.treebase.domain.AbstractPersistedObject; /** * CharWeight.java * * Created on Mar 27, 2006 * * @author <NAME> * */ @Entity @Table(name = "CHARWEIGHT") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.CHAR) @AttributeOverride(name = "id", column = @Column(name = "CHARWEIGHT_ID")) @DiscriminatorValue("-") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "matrixCache") public abstract class CharWeight extends AbstractPersistedObject { private Collection<ColumnRange> mWeightColumns = new ArrayList<ColumnRange>(); /** * Constructor. */ public CharWeight() { super(); } /** * Return the weight columns. * * @return */ @OneToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE}) @JoinTable(name = "CharWeight_ColRange", joinColumns = {@JoinColumn(name = "CHARWEIGHT_ID")}, inverseJoinColumns = @JoinColumn(name = "COLUMNRANGE_ID")) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "matrixCache") public Collection<ColumnRange> getWeightColumns() { return mWeightColumns; } /** * Set the weight columns. */ public void setWeightColumns(Collection<ColumnRange> pWeightColumns) { mWeightColumns = pWeightColumns; } /** * Print the weight to the string buffer. * * Return the string buffer for call chaining. * * @return */ public abstract StringBuilder appendWeight(StringBuilder pBuilder); /** * Get the weight and the associated columns. * * @return */ @Transient public String getWeightAndColumnAsString() { StringBuilder sb = new StringBuilder(); appendWeight(sb).append(": "); for (ColumnRange colRange : getWeightColumns()) { colRange.appendRange(sb).append(" "); } return sb.toString(); } }
2,692
0.730141
0.727914
95
26.357895
27.355713
153
false
false
0
0
0
0
0
0
0.989474
false
false
12
989585282d3bbcede03d593e21a8e4eff4c03d80
18,528,488,931,997
b4655eca4da9cc9872e25166261d1ab09224b19b
/storebuild/opt/zimbra/jetty_base/work/zimbra/jsp/org/apache/jsp/tag/webmobile/moHandleError_tag.java
886f43b5a311a4a9d5a98c8232282bf8866f886b
[]
no_license
jholder85638/zimbra-builds-src-devel
https://github.com/jholder85638/zimbra-builds-src-devel
23917c2c28dd4222dee74664475ecc83df541c9f
84993f6905399285cb8f9c3e20bb16d53de29ecb
refs/heads/master
2021-08-29T20:13:27.425000
2017-12-12T06:56:02
2017-12-12T06:56:02
113,503,181
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Generated by the Jasper component of Apache Tomcat * Version: JspC/ApacheTomcat8 * Generated at: 2017-12-07 23:24:24 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.tag.webmobile; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class moHandleError_tag extends javax.servlet.jsp.tagext.SimpleTagSupport implements org.apache.jasper.runtime.JspSourceDependent { private static org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0; static { _jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fn:escapeXml", org.apache.taglibs.standard.functions.Functions.class, "escapeXml", new Class[] {java.lang.String.class}); } private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1); _jspx_dependants.put("/WEB-INF/tags/mobile/moStatus.tag", Long.valueOf(1512680905000L)); } private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private javax.servlet.jsp.JspContext jspContext; private java.io.Writer _jspx_sout; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fif_0026_005ftest; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fchoose; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fotherwise; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public void setJspContext(javax.servlet.jsp.JspContext ctx) { super.setJspContext(ctx); java.util.ArrayList _jspx_nested = null; java.util.ArrayList _jspx_at_begin = null; java.util.ArrayList _jspx_at_end = null; this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null); } public javax.servlet.jsp.JspContext getJspContext() { return this.jspContext; } public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } private void _jspInit(javax.servlet.ServletConfig config) { _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fchoose = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fotherwise = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _el_expressionfactory = _jspxFactory.getJspApplicationContext(config.getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(config); } public void _jspDestroy() { _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar.release(); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.release(); _005fjspx_005ftagPool_005fc_005fchoose.release(); _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.release(); _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.release(); _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.release(); _005fjspx_005ftagPool_005fc_005fotherwise.release(); _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.release(); } public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException { javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext; javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest(); javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse(); javax.servlet.http.HttpSession session = _jspx_page_context.getSession(); javax.servlet.ServletContext application = _jspx_page_context.getServletContext(); javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig(); javax.servlet.jsp.JspWriter out = jspContext.getOut(); _jspInit(config); jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext); try { if (_jspx_meth_c_005fcatch_005f0(_jspx_page_context)) return; // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f0.setParent(new javax.servlet.jsp.tagext.TagAdapter((javax.servlet.jsp.tagext.SimpleTag) this )); // /WEB-INF/tags/mobile/moHandleError.tag(27,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${!empty actionException}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fif_005f0 = _jspx_th_c_005fif_005f0.doStartTag(); if (_jspx_eval_c_005fif_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { // zm:getException com.zimbra.cs.taglib.tag.GetExceptionTag _jspx_th_zm_005fgetException_005f0 = (new com.zimbra.cs.taglib.tag.GetExceptionTag()); _jsp_instancemanager.newInstance(_jspx_th_zm_005fgetException_005f0); _jspx_th_zm_005fgetException_005f0.setJspContext(_jspx_page_context); _jspx_th_zm_005fgetException_005f0.setParent(_jspx_th_c_005fif_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(28,4) name = var type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_zm_005fgetException_005f0.setVar("error"); // /WEB-INF/tags/mobile/moHandleError.tag(28,4) name = exception type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_zm_005fgetException_005f0.setException((java.lang.Exception) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${actionException}", java.lang.Exception.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); _jspx_th_zm_005fgetException_005f0.doTag(); com.zimbra.cs.taglib.bean.ZExceptionBean error = null; error = (com.zimbra.cs.taglib.bean.ZExceptionBean) _jspx_page_context.findAttribute("error"); _jsp_instancemanager.destroyInstance(_jspx_th_zm_005fgetException_005f0); if (_jspx_meth_c_005fchoose_005f0(_jspx_th_c_005fif_005f0, _jspx_page_context)) return; int evalDoAfterBody = _jspx_th_c_005fif_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); } catch( java.lang.Throwable t ) { if( t instanceof javax.servlet.jsp.SkipPageException ) throw (javax.servlet.jsp.SkipPageException) t; if( t instanceof java.io.IOException ) throw (java.io.IOException) t; if( t instanceof java.lang.IllegalStateException ) throw (java.lang.IllegalStateException) t; if( t instanceof javax.servlet.jsp.JspException ) throw (javax.servlet.jsp.JspException) t; throw new javax.servlet.jsp.JspException(t); } finally { jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext()); ((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile(); _jspDestroy(); } } private boolean _jspx_meth_c_005fcatch_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:catch org.apache.taglibs.standard.tag.common.core.CatchTag _jspx_th_c_005fcatch_005f0 = (org.apache.taglibs.standard.tag.common.core.CatchTag) _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar.get(org.apache.taglibs.standard.tag.common.core.CatchTag.class); _jspx_th_c_005fcatch_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fcatch_005f0.setParent(new javax.servlet.jsp.tagext.TagAdapter((javax.servlet.jsp.tagext.SimpleTag) this )); // /WEB-INF/tags/mobile/moHandleError.tag(24,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fcatch_005f0.setVar("actionException"); int[] _jspx_push_body_count_c_005fcatch_005f0 = new int[] { 0 }; try { int _jspx_eval_c_005fcatch_005f0 = _jspx_th_c_005fcatch_005f0.doStartTag(); if (_jspx_eval_c_005fcatch_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { ((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke(); _jspx_sout = null; if (getJspBody() != null) getJspBody().invoke(_jspx_sout); jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,getJspContext()); int evalDoAfterBody = _jspx_th_c_005fcatch_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fcatch_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { throw new javax.servlet.jsp.SkipPageException(); } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fcatch_005f0[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fcatch_005f0.doCatch(_jspx_exception); } finally { _jspx_th_c_005fcatch_005f0.doFinally(); _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar.reuse(_jspx_th_c_005fcatch_005f0); } return false; } private boolean _jspx_meth_c_005fchoose_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fif_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:choose org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_005fchoose_005f0 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _005fjspx_005ftagPool_005fc_005fchoose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class); _jspx_th_c_005fchoose_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fchoose_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fif_005f0); int _jspx_eval_c_005fchoose_005f0 = _jspx_th_c_005fchoose_005f0.doStartTag(); if (_jspx_eval_c_005fchoose_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fwhen_005f0(_jspx_th_c_005fchoose_005f0, _jspx_page_context)) return true; if (_jspx_meth_c_005fwhen_005f1(_jspx_th_c_005fchoose_005f0, _jspx_page_context)) return true; if (_jspx_meth_c_005fotherwise_005f1(_jspx_th_c_005fchoose_005f0, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fchoose_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fchoose_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f0); return false; } private boolean _jspx_meth_c_005fwhen_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:when org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_005fwhen_005f0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class); _jspx_th_c_005fwhen_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fwhen_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(30,8) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fwhen_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${error.code eq 'ztaglib.SERVER_REDIRECT'}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fwhen_005f0 = _jspx_th_c_005fwhen_005f0.doStartTag(); if (_jspx_eval_c_005fwhen_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fredirect_005f0(_jspx_th_c_005fwhen_005f0, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fwhen_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fwhen_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f0); return false; } private boolean _jspx_meth_c_005fredirect_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fwhen_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:redirect org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_005fredirect_005f0 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class); _jspx_th_c_005fredirect_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fredirect_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fwhen_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(31,12) name = url type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fredirect_005f0.setUrl((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${not empty requestScope.SERVIER_REDIRECT_URL ? requestScope.SERVIER_REDIRECT_URL : '/'}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_c_005fredirect_005f0 = _jspx_th_c_005fredirect_005f0.doStartTag(); if (_jspx_th_c_005fredirect_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f0); return false; } private boolean _jspx_meth_c_005fwhen_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:when org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_005fwhen_005f1 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class); _jspx_th_c_005fwhen_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fwhen_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(33,8) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fwhen_005f1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${error.code eq 'service.AUTH_EXPIRED' or error.code eq 'service.AUTH_REQUIRED'}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fwhen_005f1 = _jspx_th_c_005fwhen_005f1.doStartTag(); if (_jspx_eval_c_005fwhen_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fchoose_005f1(_jspx_th_c_005fwhen_005f1, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fwhen_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fwhen_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f1); return false; } private boolean _jspx_meth_c_005fchoose_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fwhen_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:choose org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_005fchoose_005f1 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _005fjspx_005ftagPool_005fc_005fchoose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class); _jspx_th_c_005fchoose_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fchoose_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fwhen_005f1); int _jspx_eval_c_005fchoose_005f1 = _jspx_th_c_005fchoose_005f1.doStartTag(); if (_jspx_eval_c_005fchoose_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fwhen_005f2(_jspx_th_c_005fchoose_005f1, _jspx_page_context)) return true; if (_jspx_meth_c_005fotherwise_005f0(_jspx_th_c_005fchoose_005f1, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fchoose_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fchoose_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f1); return false; } private boolean _jspx_meth_c_005fwhen_005f2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:when org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_005fwhen_005f2 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class); _jspx_th_c_005fwhen_005f2.setPageContext(_jspx_page_context); _jspx_th_c_005fwhen_005f2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f1); // /WEB-INF/tags/mobile/moHandleError.tag(35,16) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fwhen_005f2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${not empty (paramValues.ajax[0]||param.ajax)}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fwhen_005f2 = _jspx_th_c_005fwhen_005f2.doStartTag(); if (_jspx_eval_c_005fwhen_005f2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("<script type=\"text/javascript\">\n var logouturl = \""); if (_jspx_meth_c_005furl_005f0(_jspx_th_c_005fwhen_005f2, _jspx_page_context)) return true; out.write("\";\n window.location.href = logouturl;\n </script>\n "); int evalDoAfterBody = _jspx_th_c_005fwhen_005f2.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fwhen_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f2); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f2); return false; } private boolean _jspx_meth_c_005furl_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fwhen_005f2, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:url org.apache.taglibs.standard.tag.rt.core.UrlTag _jspx_th_c_005furl_005f0 = (org.apache.taglibs.standard.tag.rt.core.UrlTag) _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.UrlTag.class); _jspx_th_c_005furl_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005furl_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fwhen_005f2); // /WEB-INF/tags/mobile/moHandleError.tag(37,41) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005furl_005f0.setValue((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("/?loginOp=relogin&client=mobile&loginErrorCode=${error.code}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_c_005furl_005f0 = _jspx_th_c_005furl_005f0.doStartTag(); if (_jspx_th_c_005furl_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005furl_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005furl_005f0); return false; } private boolean _jspx_meth_c_005fotherwise_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:otherwise org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_005fotherwise_005f0 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _005fjspx_005ftagPool_005fc_005fotherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class); _jspx_th_c_005fotherwise_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fotherwise_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f1); int _jspx_eval_c_005fotherwise_005f0 = _jspx_th_c_005fotherwise_005f0.doStartTag(); if (_jspx_eval_c_005fotherwise_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fredirect_005f1(_jspx_th_c_005fotherwise_005f0, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fotherwise_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fotherwise_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f0); return false; } private boolean _jspx_meth_c_005fredirect_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fotherwise_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:redirect org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_005fredirect_005f1 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class); _jspx_th_c_005fredirect_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fredirect_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fotherwise_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(42,20) name = url type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fredirect_005f1.setUrl((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("/?loginOp=relogin&client=mobile&loginErrorCode=${error.code}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_c_005fredirect_005f1 = _jspx_th_c_005fredirect_005f1.doStartTag(); if (_jspx_th_c_005fredirect_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f1); return false; } private boolean _jspx_meth_c_005fotherwise_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:otherwise org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_005fotherwise_005f1 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _005fjspx_005ftagPool_005fc_005fotherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class); _jspx_th_c_005fotherwise_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fotherwise_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f0); int _jspx_eval_c_005fotherwise_005f1 = _jspx_th_c_005fotherwise_005f1.doStartTag(); if (_jspx_eval_c_005fotherwise_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_mo_005fstatus_005f0(_jspx_th_c_005fotherwise_005f1, _jspx_page_context)) return true; out.write("<!-- "); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${fn:escapeXml(error.id)}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), _jspx_fnmap_0)); out.write(" -->\n "); int evalDoAfterBody = _jspx_th_c_005fotherwise_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fotherwise_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f1); return false; } private boolean _jspx_meth_mo_005fstatus_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fotherwise_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // mo:status org.apache.jsp.tag.webmobile.moStatus_tag _jspx_th_mo_005fstatus_005f0 = (new org.apache.jsp.tag.webmobile.moStatus_tag()); _jsp_instancemanager.newInstance(_jspx_th_mo_005fstatus_005f0); _jspx_th_mo_005fstatus_005f0.setJspContext(_jspx_page_context); _jspx_th_mo_005fstatus_005f0.setParent(_jspx_th_c_005fotherwise_005f1); // /WEB-INF/tags/mobile/moHandleError.tag(47,12) name = style type = java.lang.String reqTime = true required = false fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null _jspx_th_mo_005fstatus_005f0.setStyle("Critical"); _jspx_th_mo_005fstatus_005f0.setJspBody(new Helper( 0, _jspx_page_context, _jspx_th_mo_005fstatus_005f0, null)); _jspx_th_mo_005fstatus_005f0.doTag(); _jsp_instancemanager.destroyInstance(_jspx_th_mo_005fstatus_005f0); return false; } private boolean _jspx_meth_fmt_005fmessage_005f0(javax.servlet.jsp.tagext.JspTag _jspx_parent, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message com.zimbra.cs.taglib.tag.i18n.MessageTag _jspx_th_fmt_005fmessage_005f0 = (com.zimbra.cs.taglib.tag.i18n.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(com.zimbra.cs.taglib.tag.i18n.MessageTag.class); _jspx_th_fmt_005fmessage_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f0.setParent(new javax.servlet.jsp.tagext.TagAdapter((javax.servlet.jsp.tagext.SimpleTag) _jspx_parent)); // /WEB-INF/tags/mobile/moHandleError.tag(48,16) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f0.setKey((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${error.code}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_fmt_005fmessage_005f0 = _jspx_th_fmt_005fmessage_005f0.doStartTag(); if (_jspx_th_fmt_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); return false; } private class Helper extends org.apache.jasper.runtime.JspFragmentHelper { private javax.servlet.jsp.tagext.JspTag _jspx_parent; private int[] _jspx_push_body_count; public Helper( int discriminator, javax.servlet.jsp.JspContext jspContext, javax.servlet.jsp.tagext.JspTag _jspx_parent, int[] _jspx_push_body_count ) { super( discriminator, jspContext, _jspx_parent ); this._jspx_parent = _jspx_parent; this._jspx_push_body_count = _jspx_push_body_count; } public boolean invoke0( javax.servlet.jsp.JspWriter out ) throws java.lang.Throwable { if (_jspx_meth_fmt_005fmessage_005f0(_jspx_parent, _jspx_page_context)) return true; return false; } public void invoke( java.io.Writer writer ) throws javax.servlet.jsp.JspException { javax.servlet.jsp.JspWriter out = null; if( writer != null ) { out = this.jspContext.pushBody(writer); } else { out = this.jspContext.getOut(); } try { Object _jspx_saved_JspContext = this.jspContext.getELContext().getContext(javax.servlet.jsp.JspContext.class); this.jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,this.jspContext); switch( this.discriminator ) { case 0: invoke0( out ); break; } jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,_jspx_saved_JspContext); } catch( java.lang.Throwable e ) { if (e instanceof javax.servlet.jsp.SkipPageException) throw (javax.servlet.jsp.SkipPageException) e; throw new javax.servlet.jsp.JspException( e ); } finally { if( writer != null ) { this.jspContext.popBody(); } } } } }
UTF-8
Java
35,396
java
moHandleError_tag.java
Java
[]
null
[]
/* * Generated by the Jasper component of Apache Tomcat * Version: JspC/ApacheTomcat8 * Generated at: 2017-12-07 23:24:24 UTC * Note: The last modified time of this file was set to * the last modified time of the source file after * generation to assist with modification tracking. */ package org.apache.jsp.tag.webmobile; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class moHandleError_tag extends javax.servlet.jsp.tagext.SimpleTagSupport implements org.apache.jasper.runtime.JspSourceDependent { private static org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0; static { _jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fn:escapeXml", org.apache.taglibs.standard.functions.Functions.class, "escapeXml", new Class[] {java.lang.String.class}); } private static final javax.servlet.jsp.JspFactory _jspxFactory = javax.servlet.jsp.JspFactory.getDefaultFactory(); private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants; static { _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(1); _jspx_dependants.put("/WEB-INF/tags/mobile/moStatus.tag", Long.valueOf(1512680905000L)); } private static final java.util.Set<java.lang.String> _jspx_imports_packages; private static final java.util.Set<java.lang.String> _jspx_imports_classes; static { _jspx_imports_packages = new java.util.HashSet<>(); _jspx_imports_packages.add("javax.servlet"); _jspx_imports_packages.add("javax.servlet.http"); _jspx_imports_packages.add("javax.servlet.jsp"); _jspx_imports_classes = null; } private javax.servlet.jsp.JspContext jspContext; private java.io.Writer _jspx_sout; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fif_0026_005ftest; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fchoose; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fotherwise; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.tomcat.InstanceManager _jsp_instancemanager; public void setJspContext(javax.servlet.jsp.JspContext ctx) { super.setJspContext(ctx); java.util.ArrayList _jspx_nested = null; java.util.ArrayList _jspx_at_begin = null; java.util.ArrayList _jspx_at_end = null; this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null); } public javax.servlet.jsp.JspContext getJspContext() { return this.jspContext; } public java.util.Map<java.lang.String,java.lang.Long> getDependants() { return _jspx_dependants; } public java.util.Set<java.lang.String> getPackageImports() { return _jspx_imports_packages; } public java.util.Set<java.lang.String> getClassImports() { return _jspx_imports_classes; } private void _jspInit(javax.servlet.ServletConfig config) { _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fchoose = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005fc_005fotherwise = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(config); _el_expressionfactory = _jspxFactory.getJspApplicationContext(config.getServletContext()).getExpressionFactory(); _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(config); } public void _jspDestroy() { _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar.release(); _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.release(); _005fjspx_005ftagPool_005fc_005fchoose.release(); _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.release(); _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.release(); _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.release(); _005fjspx_005ftagPool_005fc_005fotherwise.release(); _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.release(); } public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException { javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext; javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest(); javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse(); javax.servlet.http.HttpSession session = _jspx_page_context.getSession(); javax.servlet.ServletContext application = _jspx_page_context.getServletContext(); javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig(); javax.servlet.jsp.JspWriter out = jspContext.getOut(); _jspInit(config); jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext); try { if (_jspx_meth_c_005fcatch_005f0(_jspx_page_context)) return; // c:if org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class); _jspx_th_c_005fif_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fif_005f0.setParent(new javax.servlet.jsp.tagext.TagAdapter((javax.servlet.jsp.tagext.SimpleTag) this )); // /WEB-INF/tags/mobile/moHandleError.tag(27,0) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fif_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${!empty actionException}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fif_005f0 = _jspx_th_c_005fif_005f0.doStartTag(); if (_jspx_eval_c_005fif_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { // zm:getException com.zimbra.cs.taglib.tag.GetExceptionTag _jspx_th_zm_005fgetException_005f0 = (new com.zimbra.cs.taglib.tag.GetExceptionTag()); _jsp_instancemanager.newInstance(_jspx_th_zm_005fgetException_005f0); _jspx_th_zm_005fgetException_005f0.setJspContext(_jspx_page_context); _jspx_th_zm_005fgetException_005f0.setParent(_jspx_th_c_005fif_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(28,4) name = var type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_zm_005fgetException_005f0.setVar("error"); // /WEB-INF/tags/mobile/moHandleError.tag(28,4) name = exception type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_zm_005fgetException_005f0.setException((java.lang.Exception) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${actionException}", java.lang.Exception.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); _jspx_th_zm_005fgetException_005f0.doTag(); com.zimbra.cs.taglib.bean.ZExceptionBean error = null; error = (com.zimbra.cs.taglib.bean.ZExceptionBean) _jspx_page_context.findAttribute("error"); _jsp_instancemanager.destroyInstance(_jspx_th_zm_005fgetException_005f0); if (_jspx_meth_c_005fchoose_005f0(_jspx_th_c_005fif_005f0, _jspx_page_context)) return; int evalDoAfterBody = _jspx_th_c_005fif_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fif_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0); } catch( java.lang.Throwable t ) { if( t instanceof javax.servlet.jsp.SkipPageException ) throw (javax.servlet.jsp.SkipPageException) t; if( t instanceof java.io.IOException ) throw (java.io.IOException) t; if( t instanceof java.lang.IllegalStateException ) throw (java.lang.IllegalStateException) t; if( t instanceof javax.servlet.jsp.JspException ) throw (javax.servlet.jsp.JspException) t; throw new javax.servlet.jsp.JspException(t); } finally { jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext()); ((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile(); _jspDestroy(); } } private boolean _jspx_meth_c_005fcatch_005f0(javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:catch org.apache.taglibs.standard.tag.common.core.CatchTag _jspx_th_c_005fcatch_005f0 = (org.apache.taglibs.standard.tag.common.core.CatchTag) _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar.get(org.apache.taglibs.standard.tag.common.core.CatchTag.class); _jspx_th_c_005fcatch_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fcatch_005f0.setParent(new javax.servlet.jsp.tagext.TagAdapter((javax.servlet.jsp.tagext.SimpleTag) this )); // /WEB-INF/tags/mobile/moHandleError.tag(24,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fcatch_005f0.setVar("actionException"); int[] _jspx_push_body_count_c_005fcatch_005f0 = new int[] { 0 }; try { int _jspx_eval_c_005fcatch_005f0 = _jspx_th_c_005fcatch_005f0.doStartTag(); if (_jspx_eval_c_005fcatch_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { ((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke(); _jspx_sout = null; if (getJspBody() != null) getJspBody().invoke(_jspx_sout); jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,getJspContext()); int evalDoAfterBody = _jspx_th_c_005fcatch_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fcatch_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { throw new javax.servlet.jsp.SkipPageException(); } } catch (java.lang.Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fcatch_005f0[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fcatch_005f0.doCatch(_jspx_exception); } finally { _jspx_th_c_005fcatch_005f0.doFinally(); _005fjspx_005ftagPool_005fc_005fcatch_0026_005fvar.reuse(_jspx_th_c_005fcatch_005f0); } return false; } private boolean _jspx_meth_c_005fchoose_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fif_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:choose org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_005fchoose_005f0 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _005fjspx_005ftagPool_005fc_005fchoose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class); _jspx_th_c_005fchoose_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fchoose_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fif_005f0); int _jspx_eval_c_005fchoose_005f0 = _jspx_th_c_005fchoose_005f0.doStartTag(); if (_jspx_eval_c_005fchoose_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fwhen_005f0(_jspx_th_c_005fchoose_005f0, _jspx_page_context)) return true; if (_jspx_meth_c_005fwhen_005f1(_jspx_th_c_005fchoose_005f0, _jspx_page_context)) return true; if (_jspx_meth_c_005fotherwise_005f1(_jspx_th_c_005fchoose_005f0, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fchoose_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fchoose_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f0); return false; } private boolean _jspx_meth_c_005fwhen_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:when org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_005fwhen_005f0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class); _jspx_th_c_005fwhen_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fwhen_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(30,8) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fwhen_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${error.code eq 'ztaglib.SERVER_REDIRECT'}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fwhen_005f0 = _jspx_th_c_005fwhen_005f0.doStartTag(); if (_jspx_eval_c_005fwhen_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fredirect_005f0(_jspx_th_c_005fwhen_005f0, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fwhen_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fwhen_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f0); return false; } private boolean _jspx_meth_c_005fredirect_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fwhen_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:redirect org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_005fredirect_005f0 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class); _jspx_th_c_005fredirect_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fredirect_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fwhen_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(31,12) name = url type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fredirect_005f0.setUrl((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${not empty requestScope.SERVIER_REDIRECT_URL ? requestScope.SERVIER_REDIRECT_URL : '/'}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_c_005fredirect_005f0 = _jspx_th_c_005fredirect_005f0.doStartTag(); if (_jspx_th_c_005fredirect_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f0); return false; } private boolean _jspx_meth_c_005fwhen_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:when org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_005fwhen_005f1 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class); _jspx_th_c_005fwhen_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fwhen_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(33,8) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fwhen_005f1.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${error.code eq 'service.AUTH_EXPIRED' or error.code eq 'service.AUTH_REQUIRED'}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fwhen_005f1 = _jspx_th_c_005fwhen_005f1.doStartTag(); if (_jspx_eval_c_005fwhen_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fchoose_005f1(_jspx_th_c_005fwhen_005f1, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fwhen_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fwhen_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f1); return false; } private boolean _jspx_meth_c_005fchoose_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fwhen_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:choose org.apache.taglibs.standard.tag.common.core.ChooseTag _jspx_th_c_005fchoose_005f1 = (org.apache.taglibs.standard.tag.common.core.ChooseTag) _005fjspx_005ftagPool_005fc_005fchoose.get(org.apache.taglibs.standard.tag.common.core.ChooseTag.class); _jspx_th_c_005fchoose_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fchoose_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fwhen_005f1); int _jspx_eval_c_005fchoose_005f1 = _jspx_th_c_005fchoose_005f1.doStartTag(); if (_jspx_eval_c_005fchoose_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fwhen_005f2(_jspx_th_c_005fchoose_005f1, _jspx_page_context)) return true; if (_jspx_meth_c_005fotherwise_005f0(_jspx_th_c_005fchoose_005f1, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fchoose_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fchoose_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fchoose.reuse(_jspx_th_c_005fchoose_005f1); return false; } private boolean _jspx_meth_c_005fwhen_005f2(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:when org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_005fwhen_005f2 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class); _jspx_th_c_005fwhen_005f2.setPageContext(_jspx_page_context); _jspx_th_c_005fwhen_005f2.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f1); // /WEB-INF/tags/mobile/moHandleError.tag(35,16) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fwhen_005f2.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${not empty (paramValues.ajax[0]||param.ajax)}", boolean.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)).booleanValue()); int _jspx_eval_c_005fwhen_005f2 = _jspx_th_c_005fwhen_005f2.doStartTag(); if (_jspx_eval_c_005fwhen_005f2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("<script type=\"text/javascript\">\n var logouturl = \""); if (_jspx_meth_c_005furl_005f0(_jspx_th_c_005fwhen_005f2, _jspx_page_context)) return true; out.write("\";\n window.location.href = logouturl;\n </script>\n "); int evalDoAfterBody = _jspx_th_c_005fwhen_005f2.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fwhen_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f2); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fwhen_0026_005ftest.reuse(_jspx_th_c_005fwhen_005f2); return false; } private boolean _jspx_meth_c_005furl_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fwhen_005f2, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:url org.apache.taglibs.standard.tag.rt.core.UrlTag _jspx_th_c_005furl_005f0 = (org.apache.taglibs.standard.tag.rt.core.UrlTag) _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.UrlTag.class); _jspx_th_c_005furl_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005furl_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fwhen_005f2); // /WEB-INF/tags/mobile/moHandleError.tag(37,41) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005furl_005f0.setValue((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("/?loginOp=relogin&client=mobile&loginErrorCode=${error.code}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_c_005furl_005f0 = _jspx_th_c_005furl_005f0.doStartTag(); if (_jspx_th_c_005furl_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005furl_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005furl_0026_005fvalue_005fnobody.reuse(_jspx_th_c_005furl_005f0); return false; } private boolean _jspx_meth_c_005fotherwise_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:otherwise org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_005fotherwise_005f0 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _005fjspx_005ftagPool_005fc_005fotherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class); _jspx_th_c_005fotherwise_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fotherwise_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f1); int _jspx_eval_c_005fotherwise_005f0 = _jspx_th_c_005fotherwise_005f0.doStartTag(); if (_jspx_eval_c_005fotherwise_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_c_005fredirect_005f1(_jspx_th_c_005fotherwise_005f0, _jspx_page_context)) return true; int evalDoAfterBody = _jspx_th_c_005fotherwise_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fotherwise_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f0); return false; } private boolean _jspx_meth_c_005fredirect_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fotherwise_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:redirect org.apache.taglibs.standard.tag.rt.core.RedirectTag _jspx_th_c_005fredirect_005f1 = (org.apache.taglibs.standard.tag.rt.core.RedirectTag) _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.RedirectTag.class); _jspx_th_c_005fredirect_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fredirect_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fotherwise_005f0); // /WEB-INF/tags/mobile/moHandleError.tag(42,20) name = url type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_c_005fredirect_005f1.setUrl((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("/?loginOp=relogin&client=mobile&loginErrorCode=${error.code}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_c_005fredirect_005f1 = _jspx_th_c_005fredirect_005f1.doStartTag(); if (_jspx_th_c_005fredirect_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fredirect_0026_005furl_005fnobody.reuse(_jspx_th_c_005fredirect_005f1); return false; } private boolean _jspx_meth_c_005fotherwise_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fchoose_005f0, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // c:otherwise org.apache.taglibs.standard.tag.common.core.OtherwiseTag _jspx_th_c_005fotherwise_005f1 = (org.apache.taglibs.standard.tag.common.core.OtherwiseTag) _005fjspx_005ftagPool_005fc_005fotherwise.get(org.apache.taglibs.standard.tag.common.core.OtherwiseTag.class); _jspx_th_c_005fotherwise_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fotherwise_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fchoose_005f0); int _jspx_eval_c_005fotherwise_005f1 = _jspx_th_c_005fotherwise_005f1.doStartTag(); if (_jspx_eval_c_005fotherwise_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { if (_jspx_meth_mo_005fstatus_005f0(_jspx_th_c_005fotherwise_005f1, _jspx_page_context)) return true; out.write("<!-- "); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${fn:escapeXml(error.id)}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), _jspx_fnmap_0)); out.write(" -->\n "); int evalDoAfterBody = _jspx_th_c_005fotherwise_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fotherwise_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f1); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005fc_005fotherwise.reuse(_jspx_th_c_005fotherwise_005f1); return false; } private boolean _jspx_meth_mo_005fstatus_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fotherwise_005f1, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // mo:status org.apache.jsp.tag.webmobile.moStatus_tag _jspx_th_mo_005fstatus_005f0 = (new org.apache.jsp.tag.webmobile.moStatus_tag()); _jsp_instancemanager.newInstance(_jspx_th_mo_005fstatus_005f0); _jspx_th_mo_005fstatus_005f0.setJspContext(_jspx_page_context); _jspx_th_mo_005fstatus_005f0.setParent(_jspx_th_c_005fotherwise_005f1); // /WEB-INF/tags/mobile/moHandleError.tag(47,12) name = style type = java.lang.String reqTime = true required = false fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null _jspx_th_mo_005fstatus_005f0.setStyle("Critical"); _jspx_th_mo_005fstatus_005f0.setJspBody(new Helper( 0, _jspx_page_context, _jspx_th_mo_005fstatus_005f0, null)); _jspx_th_mo_005fstatus_005f0.doTag(); _jsp_instancemanager.destroyInstance(_jspx_th_mo_005fstatus_005f0); return false; } private boolean _jspx_meth_fmt_005fmessage_005f0(javax.servlet.jsp.tagext.JspTag _jspx_parent, javax.servlet.jsp.PageContext _jspx_page_context) throws java.lang.Throwable { javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); // fmt:message com.zimbra.cs.taglib.tag.i18n.MessageTag _jspx_th_fmt_005fmessage_005f0 = (com.zimbra.cs.taglib.tag.i18n.MessageTag) _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.get(com.zimbra.cs.taglib.tag.i18n.MessageTag.class); _jspx_th_fmt_005fmessage_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fmessage_005f0.setParent(new javax.servlet.jsp.tagext.TagAdapter((javax.servlet.jsp.tagext.SimpleTag) _jspx_parent)); // /WEB-INF/tags/mobile/moHandleError.tag(48,16) name = key type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_fmt_005fmessage_005f0.setKey((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${error.code}", java.lang.String.class, (javax.servlet.jsp.PageContext)this.getJspContext(), null)); int _jspx_eval_fmt_005fmessage_005f0 = _jspx_th_fmt_005fmessage_005f0.doStartTag(); if (_jspx_th_fmt_005fmessage_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); throw new javax.servlet.jsp.SkipPageException(); } _005fjspx_005ftagPool_005ffmt_005fmessage_0026_005fkey_005fnobody.reuse(_jspx_th_fmt_005fmessage_005f0); return false; } private class Helper extends org.apache.jasper.runtime.JspFragmentHelper { private javax.servlet.jsp.tagext.JspTag _jspx_parent; private int[] _jspx_push_body_count; public Helper( int discriminator, javax.servlet.jsp.JspContext jspContext, javax.servlet.jsp.tagext.JspTag _jspx_parent, int[] _jspx_push_body_count ) { super( discriminator, jspContext, _jspx_parent ); this._jspx_parent = _jspx_parent; this._jspx_push_body_count = _jspx_push_body_count; } public boolean invoke0( javax.servlet.jsp.JspWriter out ) throws java.lang.Throwable { if (_jspx_meth_fmt_005fmessage_005f0(_jspx_parent, _jspx_page_context)) return true; return false; } public void invoke( java.io.Writer writer ) throws javax.servlet.jsp.JspException { javax.servlet.jsp.JspWriter out = null; if( writer != null ) { out = this.jspContext.pushBody(writer); } else { out = this.jspContext.getOut(); } try { Object _jspx_saved_JspContext = this.jspContext.getELContext().getContext(javax.servlet.jsp.JspContext.class); this.jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,this.jspContext); switch( this.discriminator ) { case 0: invoke0( out ); break; } jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,_jspx_saved_JspContext); } catch( java.lang.Throwable e ) { if (e instanceof javax.servlet.jsp.SkipPageException) throw (javax.servlet.jsp.SkipPageException) e; throw new javax.servlet.jsp.JspException( e ); } finally { if( writer != null ) { this.jspContext.popBody(); } } } } }
35,396
0.725534
0.649819
540
64.548149
63.384361
354
false
false
0
0
0
0
0
0
0.705556
false
false
12
3860a9f9bf929dbd84011e33f980c0178cf43155
15,479,062,204,125
402c6c4be7c27d01655f13ce072a1782ea8ce67a
/src/main/java/bookworm/db/backends/Backend.java
39e16158b87770f63780a617e06773b8fb349a9e
[ "MIT" ]
permissive
kf4x/BookWormApp
https://github.com/kf4x/BookWormApp
cda20283f0929f5f3f00ec3cd99ed34188af90c7
bab05073217a7d1f3c39d98bbe34c65e4392ed70
refs/heads/master
2021-05-31T09:27:42.883000
2016-04-19T08:26:15
2016-04-19T08:26:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bookworm.db.backends; import java.sql.ResultSet; import java.util.Hashtable; import java.util.Set; public interface Backend { /** * Connect to database. * * @return boolean true if successful connection */ boolean connect(); /** * Create a table * * @param table name of table to create * @param properties table of column name (key) and column type value * * With some cleverness, column constraints can be applied. * * TODO explicitly support constraints */ void createTable (String table, Hashtable<String, Object> properties); /** * Insert data into the database * * @param table name of the table to insert into * @param cols name of the columns corresponding to values * @param values actual values to be saved */ void insert (String table, Set<String> cols, Set<Object> values); /** * Query data * * @param table name of the table to be queried from * @param where where statement. * @return set of rows. */ ResultSet select (String table, String where); /** * Close the connection to the database. */ void close(); }
UTF-8
Java
1,142
java
Backend.java
Java
[]
null
[]
package bookworm.db.backends; import java.sql.ResultSet; import java.util.Hashtable; import java.util.Set; public interface Backend { /** * Connect to database. * * @return boolean true if successful connection */ boolean connect(); /** * Create a table * * @param table name of table to create * @param properties table of column name (key) and column type value * * With some cleverness, column constraints can be applied. * * TODO explicitly support constraints */ void createTable (String table, Hashtable<String, Object> properties); /** * Insert data into the database * * @param table name of the table to insert into * @param cols name of the columns corresponding to values * @param values actual values to be saved */ void insert (String table, Set<String> cols, Set<Object> values); /** * Query data * * @param table name of the table to be queried from * @param where where statement. * @return set of rows. */ ResultSet select (String table, String where); /** * Close the connection to the database. */ void close(); }
1,142
0.666375
0.666375
52
20.961538
21.826202
72
false
false
0
0
0
0
0
0
0.288462
false
false
12
f055f25e8ad3b1368427df6935342ed400f55745
28,441,273,455,272
779880de749133dea72c055b70a94a0ec7e65ba5
/Assignment2Maven/assignment/src/test/java/softwareeng/EquationSolverTest.java
c3ee4be5b1530f585d4b9f79552f57d331d9c221
[]
no_license
MarcoMontero8/software-engineering
https://github.com/MarcoMontero8/software-engineering
fd5fc2998f960b879fc2e39cb02728ff5a1a5219
4e2151dc83f93a2e21945294e50c12b502bb3dc3
refs/heads/master
2021-05-23T16:17:04.392000
2020-04-05T14:17:27
2020-04-05T14:17:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package softwareeng; import static org.mockito.Mockito.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.mockito.Mockito; import softwareeng.EquationSolver; public class EquationSolverTest { private EquationSolver solver = new EquationSolver(); @Test public void caluclateOk() { double[] res = this.solver.calculate(1, 2, 1); double resultPos = res[0]; double resultNeg = res[1]; assertTrue(resultPos == -1.0); assertTrue(resultNeg == -1.0); } @Test(expected = ArithmeticException.class) public void caluclateWhenAEquals0RaiseException() { this.solver.calculate(0, 2, 1); } @Test public void caluclateWithMockWhenAuxReturn0() { EquationSolver mockSolver = Mockito.spy(solver); Mockito.doReturn(0.0).when(mockSolver).aux(anyDouble(), anyDouble(), anyDouble()); double a = 1.0; double b = 2.0; double c = 1.0; double expectedResultPos = -1.0; double expectedResultNeg = -1.0; double[] res = mockSolver.calculate(a, b, c); double resultPos = res[0]; double resultNeg = res[1]; assertTrue(resultPos == expectedResultPos); assertTrue(resultNeg == expectedResultNeg); } @Test public void auxOk() { double res = this.solver.aux(1, 2, 1); assertTrue(0.0 == res); } @Test public void auxWhenSqrtIsNegativeRaiseException() { try { this.solver.aux(2, 1, 1); } catch (ArithmeticException exception) { assertEquals(exception.getClass(), ArithmeticException.class); } } }
UTF-8
Java
1,707
java
EquationSolverTest.java
Java
[]
null
[]
package softwareeng; import static org.mockito.Mockito.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.mockito.Mockito; import softwareeng.EquationSolver; public class EquationSolverTest { private EquationSolver solver = new EquationSolver(); @Test public void caluclateOk() { double[] res = this.solver.calculate(1, 2, 1); double resultPos = res[0]; double resultNeg = res[1]; assertTrue(resultPos == -1.0); assertTrue(resultNeg == -1.0); } @Test(expected = ArithmeticException.class) public void caluclateWhenAEquals0RaiseException() { this.solver.calculate(0, 2, 1); } @Test public void caluclateWithMockWhenAuxReturn0() { EquationSolver mockSolver = Mockito.spy(solver); Mockito.doReturn(0.0).when(mockSolver).aux(anyDouble(), anyDouble(), anyDouble()); double a = 1.0; double b = 2.0; double c = 1.0; double expectedResultPos = -1.0; double expectedResultNeg = -1.0; double[] res = mockSolver.calculate(a, b, c); double resultPos = res[0]; double resultNeg = res[1]; assertTrue(resultPos == expectedResultPos); assertTrue(resultNeg == expectedResultNeg); } @Test public void auxOk() { double res = this.solver.aux(1, 2, 1); assertTrue(0.0 == res); } @Test public void auxWhenSqrtIsNegativeRaiseException() { try { this.solver.aux(2, 1, 1); } catch (ArithmeticException exception) { assertEquals(exception.getClass(), ArithmeticException.class); } } }
1,707
0.633861
0.612771
72
22.708334
20.16008
87
false
false
0
0
0
0
0
0
1.055556
false
false
12
c4c7a7ed3bfcbf225063ccd7c1d334d128ff1f92
2,087,354,120,846
aef75e4ecbc09054978a990e3146058d98c010d9
/src/main/java/cn/edu/jxnu/rj/lrf/entity/Province.java
0da2e4afe9517427451fe1f92f2f6443f05c009d
[]
no_license
liurongfei/SpringBoot-campus
https://github.com/liurongfei/SpringBoot-campus
c2daefc19d9909935800cc4c59cda93e9c28bad0
94501c860acd0ec1b53cccdd7a319250e3dc0de9
refs/heads/main
2023-05-14T03:24:51.890000
2021-06-02T00:47:28
2021-06-02T00:47:28
352,245,581
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.edu.jxnu.rj.lrf.entity; /** * * * @author Michael Chow * @date 2021/04/18 */ public class Province { /** * * pid */ private Integer pid; /** * * province */ private String province; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province == null ? null : province.trim(); } }
UTF-8
Java
563
java
Province.java
Java
[ { "context": " cn.edu.jxnu.rj.lrf.entity;\n\n/**\n * \n *\n * @author Michael Chow\n * @date 2021/04/18\n */\npublic class Province {\n ", "end": 70, "score": 0.9996864199638367, "start": 58, "tag": "NAME", "value": "Michael Chow" } ]
null
[]
package cn.edu.jxnu.rj.lrf.entity; /** * * * @author <NAME> * @date 2021/04/18 */ public class Province { /** * * pid */ private Integer pid; /** * * province */ private String province; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province == null ? null : province.trim(); } }
557
0.53286
0.51865
37
14.243243
15.082485
66
false
false
0
0
0
0
0
0
0.189189
false
false
12
85c52596546c7f53536086725ec02b7b07ec949f
9,861,244,963,679
df10f3ee17a18767c98e4a8bf7cf3bf9f5dbca43
/springbootapp/src/main/java/com/ils/security/dao/AppUserDAO.java
5b6d321bc743fbd3e546b710bf145a0cf94a836a
[]
no_license
sachingitcode/springBootRepo
https://github.com/sachingitcode/springBootRepo
6c5bffd4be7a189875d8ee0f78c0e966960f28c7
0bf49ff854fadd59be28c436986f190ddcfa3e31
refs/heads/master
2023-03-04T07:12:13.485000
2021-02-09T07:25:13
2021-02-09T07:25:13
328,616,830
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ils.security.dao; import com.ils.security.mapper.AppUserMapper; import com.ils.security.model.AppUser; import javax.sql.DataSource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author maverick */ @Repository @Transactional public class AppUserDAO extends JdbcDaoSupport { Logger logger = Logger.getLogger(AppUserDAO.class); @Autowired public AppUserDAO(DataSource dataSource) { this.setDataSource(dataSource); } public AppUser findUserAccount(String userName) { String sql = AppUserMapper.BASE_SQL + " where u.username = ? "; Object[] params = new Object[]{userName}; AppUserMapper mapper = new AppUserMapper(); try { logger.info("["+ sql+"]"); AppUser userInfo = this.getJdbcTemplate().queryForObject(sql, params, mapper); logger.info(" userInfo : " + userInfo); return userInfo; } catch (EmptyResultDataAccessException e) { logger.info(" EmptyResultDataAccessException " + e); return null; } } }
UTF-8
Java
1,559
java
AppUserDAO.java
Java
[ { "context": "ction.annotation.Transactional;\n\n/**\n *\n * @author maverick\n */\n@Repository\n@Transactional\npublic class AppUs", "end": 691, "score": 0.9995244145393372, "start": 683, "tag": "USERNAME", "value": "maverick" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ils.security.dao; import com.ils.security.mapper.AppUserMapper; import com.ils.security.model.AppUser; import javax.sql.DataSource; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author maverick */ @Repository @Transactional public class AppUserDAO extends JdbcDaoSupport { Logger logger = Logger.getLogger(AppUserDAO.class); @Autowired public AppUserDAO(DataSource dataSource) { this.setDataSource(dataSource); } public AppUser findUserAccount(String userName) { String sql = AppUserMapper.BASE_SQL + " where u.username = ? "; Object[] params = new Object[]{userName}; AppUserMapper mapper = new AppUserMapper(); try { logger.info("["+ sql+"]"); AppUser userInfo = this.getJdbcTemplate().queryForObject(sql, params, mapper); logger.info(" userInfo : " + userInfo); return userInfo; } catch (EmptyResultDataAccessException e) { logger.info(" EmptyResultDataAccessException " + e); return null; } } }
1,559
0.703656
0.703015
47
32.170212
25.260614
90
false
false
0
0
0
0
0
0
0.553191
false
false
12
8009fecac4a38219b90bef4c9f3f83fd6f397ddb
16,346,645,550,771
efb8355066a8956d29059363a1fc397fbb36a7f9
/src/com/seaking/mapper/PermissionInterface.java
bb1ed46ff026497797774dbb52c9210de6475218
[]
no_license
seakinghuster/AMHanler
https://github.com/seakinghuster/AMHanler
30a5c0caeb177dc37d88df4e2d38a5ec3e5ebc88
83f962226c6611c4f605f638c85572f03c430fc4
refs/heads/master
2016-09-05T10:30:48.490000
2015-08-17T10:33:57
2015-08-17T10:33:57
40,703,367
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* SAAF: A static analyzer for APK files. * Copyright (C) 2013 syssec.rub.de * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.seaking.mapper; import org.w3c.dom.Entity; import com.seaking.component.PermissionType; import com.seaking.datamodel.PerEntity; /** * A permission that belongs to the set of known permissions. * * The idea of having two interfaces PermissionInterface and * PermissionRequestInterface stems from the fact that sometimes a permission as * it is requested in the manifest is not known to SAAF. * * At a given time SAAF has a set known Permissions. These are modeled using the * PermissionInterface. Over the course of a SAAF deployment the set of known * permissions may change for a number of reasons: * * <ul> * <li>Some permissions where forgotten in the inital config</li> * <li>The android platform changes. Google adds new permissions</li> * <li>New frameworks using custom permissions appear</li> * <li>...</li> * </ul> * * @author Tilman Bender <tilman.bender@rub.de> * */ public interface PermissionInterface extends PerEntity, Comparable<PermissionInterface> { public abstract String getName(); public abstract void setName(String permission); public abstract void setDescription(String description); public abstract String getDescription(); public abstract void setType(PermissionType type); public abstract PermissionType getType(); }
UTF-8
Java
2,031
java
PermissionInterface.java
Java
[ { "context": "ppear</li>\n * <li>...</li>\n * </ul>\n * \n * @author Tilman Bender <tilman.bender@rub.de>\n * \n */\npublic interface P", "end": 1619, "score": 0.9998846054077148, "start": 1606, "tag": "NAME", "value": "Tilman Bender" }, { "context": "i>...</li>\n * </ul>\n * \n * @author Tilman Bender <tilman.bender@rub.de>\n * \n */\npublic interface PermissionInterface ext", "end": 1641, "score": 0.9999351501464844, "start": 1621, "tag": "EMAIL", "value": "tilman.bender@rub.de" } ]
null
[]
/* SAAF: A static analyzer for APK files. * Copyright (C) 2013 syssec.rub.de * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.seaking.mapper; import org.w3c.dom.Entity; import com.seaking.component.PermissionType; import com.seaking.datamodel.PerEntity; /** * A permission that belongs to the set of known permissions. * * The idea of having two interfaces PermissionInterface and * PermissionRequestInterface stems from the fact that sometimes a permission as * it is requested in the manifest is not known to SAAF. * * At a given time SAAF has a set known Permissions. These are modeled using the * PermissionInterface. Over the course of a SAAF deployment the set of known * permissions may change for a number of reasons: * * <ul> * <li>Some permissions where forgotten in the inital config</li> * <li>The android platform changes. Google adds new permissions</li> * <li>New frameworks using custom permissions appear</li> * <li>...</li> * </ul> * * @author <NAME> <<EMAIL>> * */ public interface PermissionInterface extends PerEntity, Comparable<PermissionInterface> { public abstract String getName(); public abstract void setName(String permission); public abstract void setDescription(String description); public abstract String getDescription(); public abstract void setType(PermissionType type); public abstract PermissionType getType(); }
2,011
0.752339
0.749385
60
32.849998
28.197414
80
false
false
0
0
0
0
0
0
0.4
false
false
12
a07d3663f370f1025e9539ebe17825f9fb0cac1d
4,380,866,677,396
a4570a599a89fe316987d3f0bbbcd70e209fb615
/client/src/main/java/engine/client/player/ClientPlayerImpl.java
e906bffdb01fc763881e8e626475536f28bb1738
[ "Apache-2.0" ]
permissive
SkyFoundation/PanguEngine
https://github.com/SkyFoundation/PanguEngine
eeac45c0232fc1de916175372baafe33f3dbe97e
d0417fdca16458b4a257eb305e971bd1483fbba4
refs/heads/master
2021-04-19T06:32:51.972000
2020-03-16T13:08:10
2020-03-16T13:08:10
249,587,742
0
0
Apache-2.0
true
2020-03-24T01:53:40
2020-03-24T01:53:39
2020-03-24T01:53:33
2020-03-22T09:48:44
10,943
0
0
0
null
false
false
package engine.client.player; import engine.Platform; import engine.client.input.controller.EntityController; import engine.entity.Entity; import engine.graphics.GraphicsManager; import engine.graphics.display.callback.CursorCallback; import engine.player.PlayerImpl; import engine.player.Profile; import engine.server.network.NetworkHandler; import javax.annotation.Nonnull; public class ClientPlayerImpl extends PlayerImpl implements ClientPlayer { private EntityController entityController; private CursorCallback cursorCallback; public ClientPlayerImpl(Profile profile, Entity controlledEntity) { super(profile, controlledEntity); } public ClientPlayerImpl(Profile profile, NetworkHandler handler, Entity controlledEntity) { super(profile, handler, controlledEntity); } @Override public EntityController getEntityController() { return entityController; } @Override public void setEntityController(EntityController controller) { entityController = controller; controller.setPlayer(this, getControlledEntity()); GraphicsManager graphicsManager = Platform.getEngineClient().getGraphicsManager(); graphicsManager.getWindow().removeCursorCallback(cursorCallback); cursorCallback = (window, xpos, ypos) -> { if (!graphicsManager.getGUIManager().isShowing()) { entityController.onCursorMove(xpos, ypos); } }; graphicsManager.getWindow().addCursorCallback(cursorCallback); } @Nonnull @Override public Entity controlEntity(@Nonnull Entity entity) { return super.controlEntity(entity); } }
UTF-8
Java
1,688
java
ClientPlayerImpl.java
Java
[]
null
[]
package engine.client.player; import engine.Platform; import engine.client.input.controller.EntityController; import engine.entity.Entity; import engine.graphics.GraphicsManager; import engine.graphics.display.callback.CursorCallback; import engine.player.PlayerImpl; import engine.player.Profile; import engine.server.network.NetworkHandler; import javax.annotation.Nonnull; public class ClientPlayerImpl extends PlayerImpl implements ClientPlayer { private EntityController entityController; private CursorCallback cursorCallback; public ClientPlayerImpl(Profile profile, Entity controlledEntity) { super(profile, controlledEntity); } public ClientPlayerImpl(Profile profile, NetworkHandler handler, Entity controlledEntity) { super(profile, handler, controlledEntity); } @Override public EntityController getEntityController() { return entityController; } @Override public void setEntityController(EntityController controller) { entityController = controller; controller.setPlayer(this, getControlledEntity()); GraphicsManager graphicsManager = Platform.getEngineClient().getGraphicsManager(); graphicsManager.getWindow().removeCursorCallback(cursorCallback); cursorCallback = (window, xpos, ypos) -> { if (!graphicsManager.getGUIManager().isShowing()) { entityController.onCursorMove(xpos, ypos); } }; graphicsManager.getWindow().addCursorCallback(cursorCallback); } @Nonnull @Override public Entity controlEntity(@Nonnull Entity entity) { return super.controlEntity(entity); } }
1,688
0.734597
0.734597
54
30.25926
27.149916
95
false
false
0
0
0
0
0
0
0.611111
false
false
12
612fa2284b288f9ac8695d7bbb7b70fa05fda33e
4,380,866,676,203
6d8d1a0e83ae9f140344e695eb5d1ce6918296ad
/app/src/main/java/com/vt/vthacks/GcmIntentService.java
bbd1962420f6de70ec8a679dc6b31de4a7536bd9
[]
no_license
ObeliskIsHuge/VTHacksII
https://github.com/ObeliskIsHuge/VTHacksII
7cfd726185bd38fb7ebd269771b9f9523b4b1277
c3df2c11f5cc6919b89b5499a0b2fccd6f48321c
refs/heads/master
2015-08-19T22:05:53.812000
2015-01-29T06:20:02
2015-01-29T06:20:02
29,827,557
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vt.vthacks; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; import android.os.ResultReceiver; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; public class GcmIntentService extends IntentService { private static final String TAG = "GcmIntentService"; private static final int ANNOUNCEMENT_NOTIFICATION_ID = 1; private ResultReceiver pushNotificationListener; public GcmIntentService() { super("PushNotificationIntentService"); } @Override public IBinder onBind(Intent intent) { if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { pushNotificationListener = extras.getParcelable("pushNotificationListener"); } } return super.onBind(intent); } @Override public boolean onUnbind(Intent intent) { pushNotificationListener = null; return super.onUnbind(intent); } @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (extras != null && !extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM * will be extended in the future with new message types, just ignore * any message types you're not interested in, or that you don't * recognize. */ if (pushNotificationListener != null) { if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { pushNotificationListener.send(Constants.PUSH_NOTIFICATION_RECEIVED, extras); } } else { // TODO: Do something useful for errors or deleted categories if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { Intent activityIntent = new Intent(this, MainActivity.class); sendNotification(this, "Send error: " + extras.toString(), activityIntent); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { Intent activityIntent = new Intent(this, MainActivity.class); sendNotification(this, "Deleted messages on server: " + extras.toString(), activityIntent); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { sendMessageNotification(this, extras); } } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } public static void sendMessageNotification(Context context, Bundle bundle) { Intent activityIntent = new Intent(context, MainActivity.class); Log.d(TAG, bundle.toString()); String title = bundle.getString("title"); String message = bundle.getString("message"); sendNotification(context, String.format("%s: %s", title, message), activityIntent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private static void sendNotification(Context context, String msg, Intent intent) { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.launcher) .setContentTitle("VTHacks") .setContentText(msg) .setContentIntent(contentIntent); Notification notification = mBuilder.build(); notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL; notification.defaults = notification.defaults | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS; mNotificationManager.notify(ANNOUNCEMENT_NOTIFICATION_ID, notification); } }
UTF-8
Java
4,170
java
GcmIntentService.java
Java
[]
null
[]
package com.vt.vthacks; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; import android.os.ResultReceiver; import android.support.v4.app.NotificationCompat; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; public class GcmIntentService extends IntentService { private static final String TAG = "GcmIntentService"; private static final int ANNOUNCEMENT_NOTIFICATION_ID = 1; private ResultReceiver pushNotificationListener; public GcmIntentService() { super("PushNotificationIntentService"); } @Override public IBinder onBind(Intent intent) { if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { pushNotificationListener = extras.getParcelable("pushNotificationListener"); } } return super.onBind(intent); } @Override public boolean onUnbind(Intent intent) { pushNotificationListener = null; return super.onUnbind(intent); } @Override protected void onHandleIntent(Intent intent) { if (intent == null) { return; } Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (extras != null && !extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM * will be extended in the future with new message types, just ignore * any message types you're not interested in, or that you don't * recognize. */ if (pushNotificationListener != null) { if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { pushNotificationListener.send(Constants.PUSH_NOTIFICATION_RECEIVED, extras); } } else { // TODO: Do something useful for errors or deleted categories if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { Intent activityIntent = new Intent(this, MainActivity.class); sendNotification(this, "Send error: " + extras.toString(), activityIntent); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { Intent activityIntent = new Intent(this, MainActivity.class); sendNotification(this, "Deleted messages on server: " + extras.toString(), activityIntent); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { sendMessageNotification(this, extras); } } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } public static void sendMessageNotification(Context context, Bundle bundle) { Intent activityIntent = new Intent(context, MainActivity.class); Log.d(TAG, bundle.toString()); String title = bundle.getString("title"); String message = bundle.getString("message"); sendNotification(context, String.format("%s: %s", title, message), activityIntent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private static void sendNotification(Context context, String msg, Intent intent) { NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.launcher) .setContentTitle("VTHacks") .setContentText(msg) .setContentIntent(contentIntent); Notification notification = mBuilder.build(); notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL; notification.defaults = notification.defaults | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS; mNotificationManager.notify(ANNOUNCEMENT_NOTIFICATION_ID, notification); } }
4,170
0.757554
0.756595
116
34.948277
29.36302
109
false
false
0
0
0
0
0
0
2.327586
false
false
12
5540218e5b476dbf810ef9b1c90aa0ce22e91c2a
1,829,656,092,268
bcf3bbc95b63ac5f5aee8c01c8672e6f7ce50d57
/src/filterBeans/CalculateSolderJoint.java
0b55af13698299d5ebec3859a083d99d0ec4e3a6
[]
no_license
ManuelaLjubicic/UE03_beanbox
https://github.com/ManuelaLjubicic/UE03_beanbox
b579564239c773326cb1b050dd9fac25be88be4d
24abbcb030d6f8c1e08dbb8edcd04fb7d043ee7f
refs/heads/master
2021-01-15T08:26:32.856000
2015-12-06T16:44:44
2015-12-06T16:44:44
46,935,594
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package filterBeans; import Catalano.Imaging.FastBitmap; import helper.*; import java.awt.*; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; /** * Created by Karin on 04.12.2015. */ public class CalculateSolderJoint extends AbstractFilterBean implements IFilterEventListener { //berechnet die Position der Lötstellen und gibt diese Koordinaten, sowie Abweichungen von Sollwerten in einer Textdatei aus //dazu werden die Hilfs-Klassen CalcCentroids und CalculateSolderJointOutput verwendet //CalcCentroid berechnet gefundenen Lötstellen (= weiße "Bälle" im Bild); CalculateSolderJointOutput berechnet evtl. //Abweichungen und gibt die Koordinaten der Lötstellen mit den Abweichungen in einer Textdatei aus. private String fileName; private String path = "C:\\"; private String name = "TextFile"; private int startPoint = 6; private int setValueY = 25; private int incrementX = 65; private int toleranceX = 5; private int toleranceY = 5; private Point[] solderJoints; private CalcCentroids cc= new CalcCentroids(); private CalculateSolderJointOutput csjo; public CalculateSolderJoint(){ super("CalculateSolderJoint"); } @Override void process() { BufferedImage bi = ImageResize.scale(fb.toBufferedImage(), _HEIGHT); image = bi; solderJoints = cc.processFilter(fb); fileName = path + "\\" + name +".txt"; csjo = new CalculateSolderJointOutput(fileName, startPoint, setValueY, incrementX, toleranceX,toleranceY); csjo.processFilter(solderJoints); fireEvent(fb); } @Override public void handleFilterEvent(FilterEvent event) { fb = event.getFb(); fbCopy = new FastBitmap(fb); process(); } public String getPath() {return path;} public void setPath(String path) { // PropertyChangeEvent p = new PropertyChangeEvent(this, "path", this.path, path); this.path = path; // propertyChange(p); } public String getName() {return name;} public void setName (String name) { // PropertyChangeEvent p = new PropertyChangeEvent(this, "name", this.name, name); this.name = name; // propertyChange(p); } public int getStartPoint() {return startPoint;} public void setStartPoint(int startPoint) { PropertyChangeEvent p = new PropertyChangeEvent(this, "startPoint", this.startPoint, startPoint); this.startPoint = startPoint; propertyChange(p); } public int getSetValueY() { return setValueY; } public void setSetValueY(int setValueY) { PropertyChangeEvent p = new PropertyChangeEvent(this, "setValueY", this.setValueY, setValueY); this.setValueY = setValueY; propertyChange(p); } public int getIncrementX() { return incrementX; } public void setIncrementX(int incrementX) { PropertyChangeEvent p = new PropertyChangeEvent(this, "incrementX", this.incrementX, incrementX); this.incrementX = incrementX; propertyChange(p); } public int getToleranceX() { return toleranceX; } public void setToleranceX(int toleranceX) { PropertyChangeEvent p = new PropertyChangeEvent(this, "toleranceX", this.toleranceX, toleranceX); this.toleranceX = toleranceX; propertyChange(p); } public int getToleranceY() {return toleranceY; } public void setToleranceY(int toleranceY) { PropertyChangeEvent p = new PropertyChangeEvent(this, "toleranceY", this.toleranceY, toleranceY); this.toleranceY = toleranceY; propertyChange(p); } }
ISO-8859-1
Java
3,709
java
CalculateSolderJoint.java
Java
[ { "context": "java.beans.PropertyChangeEvent;\n\n/**\n * Created by Karin on 04.12.2015.\n */\npublic class CalculateSolderJo", "end": 195, "score": 0.8364896178245544, "start": 190, "tag": "USERNAME", "value": "Karin" } ]
null
[]
package filterBeans; import Catalano.Imaging.FastBitmap; import helper.*; import java.awt.*; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; /** * Created by Karin on 04.12.2015. */ public class CalculateSolderJoint extends AbstractFilterBean implements IFilterEventListener { //berechnet die Position der Lötstellen und gibt diese Koordinaten, sowie Abweichungen von Sollwerten in einer Textdatei aus //dazu werden die Hilfs-Klassen CalcCentroids und CalculateSolderJointOutput verwendet //CalcCentroid berechnet gefundenen Lötstellen (= weiße "Bälle" im Bild); CalculateSolderJointOutput berechnet evtl. //Abweichungen und gibt die Koordinaten der Lötstellen mit den Abweichungen in einer Textdatei aus. private String fileName; private String path = "C:\\"; private String name = "TextFile"; private int startPoint = 6; private int setValueY = 25; private int incrementX = 65; private int toleranceX = 5; private int toleranceY = 5; private Point[] solderJoints; private CalcCentroids cc= new CalcCentroids(); private CalculateSolderJointOutput csjo; public CalculateSolderJoint(){ super("CalculateSolderJoint"); } @Override void process() { BufferedImage bi = ImageResize.scale(fb.toBufferedImage(), _HEIGHT); image = bi; solderJoints = cc.processFilter(fb); fileName = path + "\\" + name +".txt"; csjo = new CalculateSolderJointOutput(fileName, startPoint, setValueY, incrementX, toleranceX,toleranceY); csjo.processFilter(solderJoints); fireEvent(fb); } @Override public void handleFilterEvent(FilterEvent event) { fb = event.getFb(); fbCopy = new FastBitmap(fb); process(); } public String getPath() {return path;} public void setPath(String path) { // PropertyChangeEvent p = new PropertyChangeEvent(this, "path", this.path, path); this.path = path; // propertyChange(p); } public String getName() {return name;} public void setName (String name) { // PropertyChangeEvent p = new PropertyChangeEvent(this, "name", this.name, name); this.name = name; // propertyChange(p); } public int getStartPoint() {return startPoint;} public void setStartPoint(int startPoint) { PropertyChangeEvent p = new PropertyChangeEvent(this, "startPoint", this.startPoint, startPoint); this.startPoint = startPoint; propertyChange(p); } public int getSetValueY() { return setValueY; } public void setSetValueY(int setValueY) { PropertyChangeEvent p = new PropertyChangeEvent(this, "setValueY", this.setValueY, setValueY); this.setValueY = setValueY; propertyChange(p); } public int getIncrementX() { return incrementX; } public void setIncrementX(int incrementX) { PropertyChangeEvent p = new PropertyChangeEvent(this, "incrementX", this.incrementX, incrementX); this.incrementX = incrementX; propertyChange(p); } public int getToleranceX() { return toleranceX; } public void setToleranceX(int toleranceX) { PropertyChangeEvent p = new PropertyChangeEvent(this, "toleranceX", this.toleranceX, toleranceX); this.toleranceX = toleranceX; propertyChange(p); } public int getToleranceY() {return toleranceY; } public void setToleranceY(int toleranceY) { PropertyChangeEvent p = new PropertyChangeEvent(this, "toleranceY", this.toleranceY, toleranceY); this.toleranceY = toleranceY; propertyChange(p); } }
3,709
0.681426
0.677376
111
32.36937
31.084578
128
false
false
0
0
0
0
0
0
0.765766
false
false
12
780edbb5612f613b9e16cf0b20dd1a2b543c6fca
28,681,791,654,611
ed8d4aeffbdbdb745aea15722e55b3c2bf485c37
/src/SmarterDashboard/extensions/FileSniffer.java
455ef7d925ed5002e81c3a48a498199c599938d2
[]
no_license
firebears-frc/SmarterDashboard
https://github.com/firebears-frc/SmarterDashboard
1dced4f85528a444b15527690c4ebfed4c36125c
223c81588415388d2dc3683f7acc67d1f75cefa7
refs/heads/master
2021-01-10T11:31:08.491000
2016-03-07T18:05:22
2016-03-07T18:05:22
53,282,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package SmarterDashboard.extensions; import java.io.*; import java.lang.String; import java.lang.System; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashSet; import java.util.jar.JarFile; import java.util.jar.JarEntry; import java.util.Enumeration; import java.net.*; import javax.swing.*; import SmarterDashboard.gui.*; import SmarterDashboard.gui.elements.*; import SmarterDashboard.types.*; /** * This class searches for library and extension jars and adds them * to the system class loader. It then searches within extension jars for * {@link StaticWidget StaticWidget}s or {@link Widget Widget}s, and registers * them in the dashboard. * * @author Joe Grinstead */ public class FileSniffer { private static final File[] LIBRARY_DIRS = { new File("."), }; private static final String LIB_LOAD_MSGE = "Searching for library jars in: "; public static void findExtensions(ProgressMonitor monitor, int min, int max) { monitor.setNote("Loading Libraries"); URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class<?> sysclass = URLClassLoader.class; Method method = null; try { method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); } catch (Exception e) { e.printStackTrace(); monitor.setProgress(max); return; } for (File libDir : LIBRARY_DIRS) { if (!libDir.exists()) { monitor.setProgress(min + (max - min) / 5); continue; } System.out.println(LIB_LOAD_MSGE + libDir); monitor.setNote(LIB_LOAD_MSGE + libDir); File[] files = libDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); if (files == null) { monitor.setProgress(min + (max - min) / 5); continue; } for (File file : files) { System.out.println("Adding Jar: " + file); try { method.invoke(sysloader, new Object[] { file.toURI().toURL() } ); } catch (Exception ex) { ex.printStackTrace(); } } monitor.setProgress(min + (max - min) / 5); } monitor.setProgress(max); } }
UTF-8
Java
2,179
java
FileSniffer.java
Java
[ { "context": " registers\n * them in the dashboard.\n *\n * @author Joe Grinstead\n */\npublic class FileSniffer {\n\tprivate static fi", "end": 705, "score": 0.9998728036880493, "start": 692, "tag": "NAME", "value": "Joe Grinstead" } ]
null
[]
package SmarterDashboard.extensions; import java.io.*; import java.lang.String; import java.lang.System; import java.lang.reflect.*; import java.util.ArrayList; import java.util.HashSet; import java.util.jar.JarFile; import java.util.jar.JarEntry; import java.util.Enumeration; import java.net.*; import javax.swing.*; import SmarterDashboard.gui.*; import SmarterDashboard.gui.elements.*; import SmarterDashboard.types.*; /** * This class searches for library and extension jars and adds them * to the system class loader. It then searches within extension jars for * {@link StaticWidget StaticWidget}s or {@link Widget Widget}s, and registers * them in the dashboard. * * @author <NAME> */ public class FileSniffer { private static final File[] LIBRARY_DIRS = { new File("."), }; private static final String LIB_LOAD_MSGE = "Searching for library jars in: "; public static void findExtensions(ProgressMonitor monitor, int min, int max) { monitor.setNote("Loading Libraries"); URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class<?> sysclass = URLClassLoader.class; Method method = null; try { method = sysclass.getDeclaredMethod("addURL", new Class[]{URL.class}); method.setAccessible(true); } catch (Exception e) { e.printStackTrace(); monitor.setProgress(max); return; } for (File libDir : LIBRARY_DIRS) { if (!libDir.exists()) { monitor.setProgress(min + (max - min) / 5); continue; } System.out.println(LIB_LOAD_MSGE + libDir); monitor.setNote(LIB_LOAD_MSGE + libDir); File[] files = libDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".jar"); } }); if (files == null) { monitor.setProgress(min + (max - min) / 5); continue; } for (File file : files) { System.out.println("Adding Jar: " + file); try { method.invoke(sysloader, new Object[] { file.toURI().toURL() } ); } catch (Exception ex) { ex.printStackTrace(); } } monitor.setProgress(min + (max - min) / 5); } monitor.setProgress(max); } }
2,172
0.675539
0.674162
91
22.945055
20.488733
81
false
false
0
0
0
0
0
0
2.263736
false
false
12
eb607838a3dbd95b83ad22888063742fd3260a27
29,051,158,836,982
322e4ea2bee0d0fd8ca4b57b39aba8db9b6fd6c8
/src/main/java/net/lightoze/jooq/postgresql/json/JacksonJsonbConverter.java
793088c0a21b663943a1594cf7a12f3d93d54820
[ "Apache-2.0" ]
permissive
lightoze/jOOQ-extras-postgresql
https://github.com/lightoze/jOOQ-extras-postgresql
f0361ff9eb72a0d1319084548fc067b4045178b8
88afe3b287d096839b10b5fbf2bc10e5962c3a73
refs/heads/master
2023-06-28T02:38:51.034000
2022-02-16T06:32:32
2022-02-16T06:32:32
77,342,171
3
1
Apache-2.0
false
2023-06-14T22:28:36
2016-12-25T20:41:30
2021-12-09T21:10:59
2023-06-14T22:28:36
131
3
0
5
Java
false
false
package net.lightoze.jooq.postgresql.json; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import org.jooq.JSONB; import java.io.IOException; public class JacksonJsonbConverter<T> extends AbstractJacksonConverter<JSONB, T, T> { public JacksonJsonbConverter() { } public JacksonJsonbConverter(JavaType userType, JavaType elementType) { super(userType, elementType); } @Override public T from(JSONB json) { if (json == null || json.data().equals("null")) { return getNull(); } else { try { return getObjectReader().readValue(json.data()); } catch (IOException e) { throw new RuntimeException(e); } } } @Override public JSONB to(T value) { if (value == null || isNull(value)) { return null; } else { try { return JSONB.valueOf(getObjectWriter().writeValueAsString(value)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } @Override public Class<JSONB> fromType() { return JSONB.class; } }
UTF-8
Java
1,256
java
JacksonJsonbConverter.java
Java
[]
null
[]
package net.lightoze.jooq.postgresql.json; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import org.jooq.JSONB; import java.io.IOException; public class JacksonJsonbConverter<T> extends AbstractJacksonConverter<JSONB, T, T> { public JacksonJsonbConverter() { } public JacksonJsonbConverter(JavaType userType, JavaType elementType) { super(userType, elementType); } @Override public T from(JSONB json) { if (json == null || json.data().equals("null")) { return getNull(); } else { try { return getObjectReader().readValue(json.data()); } catch (IOException e) { throw new RuntimeException(e); } } } @Override public JSONB to(T value) { if (value == null || isNull(value)) { return null; } else { try { return JSONB.valueOf(getObjectWriter().writeValueAsString(value)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } } @Override public Class<JSONB> fromType() { return JSONB.class; } }
1,256
0.584395
0.584395
49
24.632652
23.015251
85
false
false
0
0
0
0
0
0
0.428571
false
false
12
f00395acfe158ea47c2d1cc5957d92bb1888c6b4
15,590,731,300,979
63e36d35f51bea83017ec712179302a62608333e
/OnePlusCamera/com/amap/api/location/core/b.java
fbeaa51d25e78ee132f0f34be81cd7def7c0e289
[]
no_license
hiepgaf/oneplus_blobs_decompiled
https://github.com/hiepgaf/oneplus_blobs_decompiled
672aa002fa670bdcba8fdf34113bc4b8e85f8294
e1ab1f2dd111f905ff1eee18b6a072606c01c518
refs/heads/master
2021-06-26T11:24:21.954000
2017-08-26T12:45:56
2017-08-26T12:45:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amap.api.location.core; public class b { private static final char[] a = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static byte[] b = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; public static String a(byte[] paramArrayOfByte) { for (;;) { StringBuffer localStringBuffer; int j; int i; try { localStringBuffer = new StringBuffer(); j = paramArrayOfByte.length; i = 0; } catch (Throwable paramArrayOfByte) { int m; paramArrayOfByte.printStackTrace(); return ""; } return localStringBuffer.toString(); int n = i + 1; int k = paramArrayOfByte[i] & 0xFF; if (n != j) { m = n + 1; n = paramArrayOfByte[n] & 0xFF; if (m != j) { i = m + 1; m = paramArrayOfByte[m] & 0xFF; localStringBuffer.append(a[(k >>> 2)]); localStringBuffer.append(a[((k & 0x3) << 4 | (n & 0xF0) >>> 4)]); localStringBuffer.append(a[((n & 0xF) << 2 | (m & 0xC0) >>> 6)]); localStringBuffer.append(a[(m & 0x3F)]); break label273; } } else { localStringBuffer.append(a[(k >>> 2)]); localStringBuffer.append(a[((k & 0x3) << 4)]); localStringBuffer.append("=="); continue; } localStringBuffer.append(a[(k >>> 2)]); localStringBuffer.append(a[((k & 0x3) << 4 | (n & 0xF0) >>> 4)]); localStringBuffer.append(a[((n & 0xF) << 2)]); localStringBuffer.append("="); continue; label273: if (i < j) {} } } } /* Location: /Users/joshua/Desktop/system_framework/classes-dex2jar.jar!/com/amap/api/location/core/b.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
2,581
java
b.java
Java
[]
null
[]
package com.amap.api.location.core; public class b { private static final char[] a = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static byte[] b = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; public static String a(byte[] paramArrayOfByte) { for (;;) { StringBuffer localStringBuffer; int j; int i; try { localStringBuffer = new StringBuffer(); j = paramArrayOfByte.length; i = 0; } catch (Throwable paramArrayOfByte) { int m; paramArrayOfByte.printStackTrace(); return ""; } return localStringBuffer.toString(); int n = i + 1; int k = paramArrayOfByte[i] & 0xFF; if (n != j) { m = n + 1; n = paramArrayOfByte[n] & 0xFF; if (m != j) { i = m + 1; m = paramArrayOfByte[m] & 0xFF; localStringBuffer.append(a[(k >>> 2)]); localStringBuffer.append(a[((k & 0x3) << 4 | (n & 0xF0) >>> 4)]); localStringBuffer.append(a[((n & 0xF) << 2 | (m & 0xC0) >>> 6)]); localStringBuffer.append(a[(m & 0x3F)]); break label273; } } else { localStringBuffer.append(a[(k >>> 2)]); localStringBuffer.append(a[((k & 0x3) << 4)]); localStringBuffer.append("=="); continue; } localStringBuffer.append(a[(k >>> 2)]); localStringBuffer.append(a[((k & 0x3) << 4 | (n & 0xF0) >>> 4)]); localStringBuffer.append(a[((n & 0xF) << 2)]); localStringBuffer.append("="); continue; label273: if (i < j) {} } } } /* Location: /Users/joshua/Desktop/system_framework/classes-dex2jar.jar!/com/amap/api/location/core/b.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
2,581
0.442464
0.349477
67
37.537312
76.467598
533
false
false
0
0
0
0
0
0
3.402985
false
false
12
fa9a188f0618e59b818b3d6dbc316f48f0bddef1
32,564,442,052,526
e470d6c37a0e33524d9144b15a055084c7eb3b69
/javaProDemo/src/com/homework/Interface/BlackInkBox.java
a956ae419be5653f46ebb81ef5ab78506594e6f8
[]
no_license
rsl140/javalearn
https://github.com/rsl140/javalearn
bc81ccad188a6fa7c199abb7d1a4836e45535dd1
e246b4689707d04bdf2868d7ae05e612a2bcc98f
refs/heads/master
2021-01-20T15:19:22.745000
2017-06-08T14:50:14
2017-06-08T14:50:14
90,753,477
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.homework.Interface; /** * @author rsl * @功能 上机三 * @时间 2017.6.1 * */ public class BlackInkBox implements InkBox { @Override public String getColor() { return "黑白的"; } }
UTF-8
Java
225
java
BlackInkBox.java
Java
[ { "context": "package com.homework.Interface;\r\n/**\r\n * @author rsl\r\n * @功能 上机三\r\n * @时间 2017.6.1\r\n * */\r\npublic class", "end": 52, "score": 0.999630868434906, "start": 49, "tag": "USERNAME", "value": "rsl" } ]
null
[]
package com.homework.Interface; /** * @author rsl * @功能 上机三 * @时间 2017.6.1 * */ public class BlackInkBox implements InkBox { @Override public String getColor() { return "黑白的"; } }
225
0.604878
0.57561
14
12.642858
12.742545
44
false
false
0
0
0
0
0
0
0.5
false
false
12
c250efca3279b5fdce9a56d7ed7d339351af6687
25,640,954,777,500
f4c970c98c8771542913835ff7827f52a7429148
/src/main/java/com/reservation/landon/data/repository/GuestRepository.java
9d955848c8f21bc4e8ff9dd7d6dc463bbbdb86eb
[]
no_license
SivagKumar/reservation
https://github.com/SivagKumar/reservation
1a761414d769c61a0f802ccfc6eb27ab25a0b491
c3ee7fddd4b33b2872c26bd98fcb46d00453b9c5
refs/heads/master
2020-05-04T19:46:02.452000
2019-04-05T03:55:49
2019-04-05T03:55:49
179,407,104
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.reservation.landon.data.repository; import com.reservation.landon.data.entity.Guest; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface GuestRepository extends PagingAndSortingRepository <Guest, Long>{ Optional<Guest> findById(long guestId); }
UTF-8
Java
390
java
GuestRepository.java
Java
[]
null
[]
package com.reservation.landon.data.repository; import com.reservation.landon.data.entity.Guest; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface GuestRepository extends PagingAndSortingRepository <Guest, Long>{ Optional<Guest> findById(long guestId); }
390
0.835897
0.835897
13
29
28.082296
82
false
false
0
0
0
0
0
0
0.538462
false
false
12
88a7aa55cc1ee7f8970229c044673721c80c1dc5
26,869,315,429,949
24009506777c7715de70ff164577d51ddd32b653
/me/qiooip/notorious/commands/ReportCommand.java
e2a24481ac0051009e9e98ca4e9ce3182f52d97b
[]
no_license
John0118/Notorious
https://github.com/John0118/Notorious
2b091f2fc32b3cc714ae63cc2520fc4885efc23c
3ad9fa572968e8be52b018b43be89827e33393f0
refs/heads/master
2021-02-16T05:19:11.616000
2017-05-17T20:31:16
2017-05-17T20:31:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* */ package me.qiooip.notorious.commands; /* */ /* */ import me.qiooip.notorious.Notorious; /* */ import me.qiooip.notorious.handlers.ReportHandler; /* */ import me.qiooip.notorious.utils.Language; /* */ import me.qiooip.notorious.utils.StringUtils; /* */ import me.qiooip.notorious.vanish.VanishHandler; /* */ import org.bukkit.command.Command; /* */ import org.bukkit.command.CommandExecutor; /* */ import org.bukkit.command.CommandSender; /* */ import org.bukkit.entity.Player; /* */ /* */ public class ReportCommand implements CommandExecutor /* */ { /* */ public boolean onCommand(CommandSender paramCommandSender, Command paramCommand, String paramString, String[] paramArrayOfString) /* */ { /* 17 */ if (paramCommand.getName().equalsIgnoreCase("report")) { /* 18 */ if ((paramCommandSender instanceof Player)) { /* 19 */ Player localPlayer1 = (Player)paramCommandSender; /* 20 */ if (paramArrayOfString.length == 0) { /* 21 */ sendUsage(localPlayer1); /* 22 */ } else if (paramArrayOfString.length == 1) { /* 23 */ Player localPlayer2 = org.bukkit.Bukkit.getPlayer(paramArrayOfString[0]); /* 24 */ if ((localPlayer2 != null) && (!Notorious.getInstance().getVanishHandler().isVanished(localPlayer2))) { /* 25 */ if (localPlayer2 != localPlayer1) { /* 26 */ if (Notorious.getInstance().getReportHandler().isActive(localPlayer1)) { /* 27 */ localPlayer1.sendMessage(Language.PREFIX.toString() + Language.REPORT_DELAY_MESSAGE.toString().replace("<seconds>", /* 28 */ StringUtils.formatMilisecondsToSeconds(Long.valueOf(Notorious.getInstance().getReportHandler().getMillisecondsLeft(localPlayer1))))); /* */ } else { /* 30 */ Notorious.getInstance().getReportHandler().addReporter(localPlayer1, localPlayer2); /* 31 */ localPlayer1.openInventory(Notorious.getInstance().getReportHandler().getInventory()); /* */ } /* */ } else { /* 34 */ localPlayer1.sendMessage(Language.PREFIX.toString() + Language.REPORT_CAN_NOT_REPORT_YOURSELF.toString()); /* */ } /* */ } else { /* 37 */ localPlayer1.sendMessage(Language.PREFIX.toString() + Language.COMMANDS_PLAYER_NOT_ONLINE.toString().replace("<player>", paramArrayOfString[0])); /* */ } /* */ } else { /* 40 */ sendUsage(localPlayer1); /* */ } /* */ } else { /* 43 */ paramCommandSender.sendMessage(Language.COMMANDS_FOR_PLAYER_USE_ONLY.toString()); /* */ } /* */ } /* 46 */ return true; /* */ } /* */ /* */ public void sendUsage(Player paramPlayer) { /* 50 */ paramPlayer.sendMessage(Language.PREFIX.toString() + Language.REPORT_COMMAND_FORMAT.toString()); /* */ } /* */ } /* Location: C:\Users\leagu\Desktop\Notorious-Mango.jar!\me\qiooip\notorious\commands\ReportCommand.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
3,195
java
ReportCommand.java
Java
[]
null
[]
/* */ package me.qiooip.notorious.commands; /* */ /* */ import me.qiooip.notorious.Notorious; /* */ import me.qiooip.notorious.handlers.ReportHandler; /* */ import me.qiooip.notorious.utils.Language; /* */ import me.qiooip.notorious.utils.StringUtils; /* */ import me.qiooip.notorious.vanish.VanishHandler; /* */ import org.bukkit.command.Command; /* */ import org.bukkit.command.CommandExecutor; /* */ import org.bukkit.command.CommandSender; /* */ import org.bukkit.entity.Player; /* */ /* */ public class ReportCommand implements CommandExecutor /* */ { /* */ public boolean onCommand(CommandSender paramCommandSender, Command paramCommand, String paramString, String[] paramArrayOfString) /* */ { /* 17 */ if (paramCommand.getName().equalsIgnoreCase("report")) { /* 18 */ if ((paramCommandSender instanceof Player)) { /* 19 */ Player localPlayer1 = (Player)paramCommandSender; /* 20 */ if (paramArrayOfString.length == 0) { /* 21 */ sendUsage(localPlayer1); /* 22 */ } else if (paramArrayOfString.length == 1) { /* 23 */ Player localPlayer2 = org.bukkit.Bukkit.getPlayer(paramArrayOfString[0]); /* 24 */ if ((localPlayer2 != null) && (!Notorious.getInstance().getVanishHandler().isVanished(localPlayer2))) { /* 25 */ if (localPlayer2 != localPlayer1) { /* 26 */ if (Notorious.getInstance().getReportHandler().isActive(localPlayer1)) { /* 27 */ localPlayer1.sendMessage(Language.PREFIX.toString() + Language.REPORT_DELAY_MESSAGE.toString().replace("<seconds>", /* 28 */ StringUtils.formatMilisecondsToSeconds(Long.valueOf(Notorious.getInstance().getReportHandler().getMillisecondsLeft(localPlayer1))))); /* */ } else { /* 30 */ Notorious.getInstance().getReportHandler().addReporter(localPlayer1, localPlayer2); /* 31 */ localPlayer1.openInventory(Notorious.getInstance().getReportHandler().getInventory()); /* */ } /* */ } else { /* 34 */ localPlayer1.sendMessage(Language.PREFIX.toString() + Language.REPORT_CAN_NOT_REPORT_YOURSELF.toString()); /* */ } /* */ } else { /* 37 */ localPlayer1.sendMessage(Language.PREFIX.toString() + Language.COMMANDS_PLAYER_NOT_ONLINE.toString().replace("<player>", paramArrayOfString[0])); /* */ } /* */ } else { /* 40 */ sendUsage(localPlayer1); /* */ } /* */ } else { /* 43 */ paramCommandSender.sendMessage(Language.COMMANDS_FOR_PLAYER_USE_ONLY.toString()); /* */ } /* */ } /* 46 */ return true; /* */ } /* */ /* */ public void sendUsage(Player paramPlayer) { /* 50 */ paramPlayer.sendMessage(Language.PREFIX.toString() + Language.REPORT_COMMAND_FORMAT.toString()); /* */ } /* */ } /* Location: C:\Users\leagu\Desktop\Notorious-Mango.jar!\me\qiooip\notorious\commands\ReportCommand.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
3,195
0.591862
0.570892
58
53.120689
42.533184
166
false
false
0
0
0
0
0
0
0.482759
false
false
12
d6bc600499bc8a9e52cfd1cc541da04b6fae3f82
21,165,598,862,182
d437e930f54cc8a0ec32982e375c8c6f7ca96f60
/heron/packing/tests/java/com/twitter/heron/packing/roundrobin/ResourceCompliantRRPackingTest.java
bf875bc372c429e5b8cfa65bd88c48b6ce968da0
[ "Apache-2.0" ]
permissive
momoxixi/heron
https://github.com/momoxixi/heron
7c937dbedcad4d088af86c0b112c78f85878cc99
3b225144f77fa597637379745e4d73618aef6442
refs/heads/master
2021-01-24T09:18:56.528000
2016-09-27T17:00:58
2016-09-27T17:00:58
69,447,775
1
0
null
true
2016-09-28T09:26:51
2016-09-28T09:26:51
2016-09-28T06:20:03
2016-09-28T01:41:10
147,426
0
0
0
null
null
null
// Copyright 2016 Twitter. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.twitter.heron.packing.roundrobin; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; import com.twitter.heron.api.generated.TopologyAPI; import com.twitter.heron.packing.AssertPacking; import com.twitter.heron.spi.common.ClusterDefaults; import com.twitter.heron.spi.common.Config; import com.twitter.heron.spi.common.Constants; import com.twitter.heron.spi.common.Context; import com.twitter.heron.spi.common.Keys; import com.twitter.heron.spi.packing.PackingPlan; import com.twitter.heron.spi.packing.Resource; import com.twitter.heron.spi.utils.TopologyTests; import com.twitter.heron.spi.utils.TopologyUtils; public class ResourceCompliantRRPackingTest { private static final String BOLT_NAME = "bolt"; private static final String SPOUT_NAME = "spout"; private static final int DEFAULT_CONTAINER_PADDING = 10; private long instanceRamDefault; private double instanceCpuDefault; private long instanceDiskDefault; private int countComponent(String component, Set<PackingPlan.InstancePlan> instances) { int count = 0; for (PackingPlan.InstancePlan instancePlan : instances) { if (component.equals(instancePlan.getComponentName())) { count++; } } return count; } private TopologyAPI.Topology getTopology( int spoutParallelism, int boltParallelism, com.twitter.heron.api.Config topologyConfig) { return TopologyTests.createTopology("testTopology", topologyConfig, SPOUT_NAME, BOLT_NAME, spoutParallelism, boltParallelism); } private PackingPlan getResourceCompliantRRPackingPlan(TopologyAPI.Topology topology) { Config config = Config.newBuilder() .put(Keys.topologyId(), topology.getId()) .put(Keys.topologyName(), topology.getName()) .putAll(ClusterDefaults.getDefaults()) .build(); this.instanceRamDefault = Context.instanceRam(config); this.instanceCpuDefault = Context.instanceCpu(config); this.instanceDiskDefault = Context.instanceDisk(config); ResourceCompliantRRPacking packing = new ResourceCompliantRRPacking(); packing.initialize(config, topology); return packing.pack(); } @Test(expected = RuntimeException.class) public void testCheckFailure() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set insufficient ram for container long containerRam = -1L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); TopologyAPI.Topology topology = getTopology(spoutParallelism, boltParallelism, topologyConfig); getResourceCompliantRRPackingPlan(topology); } /** * Test the scenario where the max container size is the default */ @Test public void testDefaultResources() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // No explicit resources required TopologyAPI.Topology topologyNoExplicitResourcesConfig = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanNoExplicitResourcesConfig = getResourceCompliantRRPackingPlan(topologyNoExplicitResourcesConfig); Assert.assertEquals(packingPlanNoExplicitResourcesConfig.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlanNoExplicitResourcesConfig.getInstanceCount()); } /** * Test the scenario where the max container size is the default and padding is configured */ @Test public void testDefaultContainerSizeWithPadding() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; int padding = 50; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); topologyConfig.setContainerPaddingPercentage(padding); TopologyAPI.Topology topology = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlan = getResourceCompliantRRPackingPlan(topology); Assert.assertEquals(packingPlan.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlan.getInstanceCount()); } /** * Test the scenario where container level resource config are set */ @Test public void testContainerRequestedResourcesSingleContainer() throws Exception { int numContainers = 1; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 10L * Constants.GB; long containerDisk = 20L * Constants.GB; float containerCpu = 30; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setContainerDiskRequested(containerDisk); topologyConfig.setContainerCpuRequested(containerCpu); TopologyAPI.Topology topologyExplicitResourcesConfig = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitResourcesConfig = getResourceCompliantRRPackingPlan(topologyExplicitResourcesConfig); Assert.assertEquals(packingPlanExplicitResourcesConfig.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlanExplicitResourcesConfig.getInstanceCount()); for (PackingPlan.ContainerPlan containerPlan : packingPlanExplicitResourcesConfig.getContainers()) { Assert.assertEquals(Math.round(totalInstances * instanceCpuDefault + (DEFAULT_CONTAINER_PADDING / 100.0) * totalInstances * instanceCpuDefault), (long) containerPlan.getRequiredResource().getCpu()); Assert.assertEquals(totalInstances * instanceRamDefault + (long) ((DEFAULT_CONTAINER_PADDING / 100.0) * totalInstances * instanceRamDefault), containerPlan.getRequiredResource().getRam()); Assert.assertEquals(totalInstances * instanceDiskDefault + (long) ((DEFAULT_CONTAINER_PADDING / 100.0) * totalInstances * instanceDiskDefault), containerPlan.getRequiredResource().getDisk()); // All instances' resource requirement should be equal // So the size of set should be 1 Set<Resource> resources = new HashSet<>(); for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) { resources.add(instancePlan.getResource()); } Assert.assertEquals(1, resources.size()); Assert.assertEquals(instanceRamDefault, resources.iterator().next().getRam()); } } /** * Test the scenario where container level resource config are set */ @Test public void testContainerRequestedResourcesTwoContainers() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 10L * Constants.GB; long containerDisk = 20L * Constants.GB; float containerCpu = 30; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setContainerDiskRequested(containerDisk); topologyConfig.setContainerCpuRequested(containerCpu); TopologyAPI.Topology topologyExplicitResourcesConfig = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitResourcesConfig = getResourceCompliantRRPackingPlan(topologyExplicitResourcesConfig); Assert.assertEquals(packingPlanExplicitResourcesConfig.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlanExplicitResourcesConfig.getInstanceCount()); // Ram for bolt/spout should be the value in component ram map for (PackingPlan.ContainerPlan containerPlan : packingPlanExplicitResourcesConfig.getContainers()) { for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) { Assert.assertEquals(instanceRamDefault, instancePlan.getResource().getRam()); } } } /** * Test the scenario ram map config is partially set */ @Test public void testCompleteRamMapRequested() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container // the value should be ignored, since we set the complete component ram map long containerRam = Long.MAX_VALUE; // Explicit set component ram map long boltRam = 1L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setComponentRam(BOLT_NAME, boltRam); TopologyAPI.Topology topologyExplicitRamMap = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitRamMap = getResourceCompliantRRPackingPlan(topologyExplicitRamMap); Assert.assertEquals(totalInstances, packingPlanExplicitRamMap.getInstanceCount()); AssertPacking.assertContainers(packingPlanExplicitRamMap.getContainers(), BOLT_NAME, SPOUT_NAME, boltRam, instanceRamDefault, containerRam); } /** * Test the scenario ram map config is fully set */ @Test public void testPartialRamMap() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 10L * Constants.GB; // Explicit set component ram map long boltRam = 1L * Constants.GB; long spoutRam = 2L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setComponentRam(BOLT_NAME, boltRam); topologyConfig.setComponentRam(SPOUT_NAME, spoutRam); TopologyAPI.Topology topologyExplicitRamMap = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitRamMap = getResourceCompliantRRPackingPlan(topologyExplicitRamMap); Assert.assertEquals(totalInstances, packingPlanExplicitRamMap.getInstanceCount()); AssertPacking.assertContainers(packingPlanExplicitRamMap.getContainers(), BOLT_NAME, SPOUT_NAME, boltRam, spoutRam, containerRam); } /** * Test the scenario where the user defined number of containers is not sufficient. */ @Test public void testInsufficientContainersWithOneAdjustment() throws Exception { int numContainers = 1; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 2L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); TopologyAPI.Topology topology = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlan = getResourceCompliantRRPackingPlan(topology); Assert.assertEquals(packingPlan.getContainers().size(), 4); Assert.assertEquals(totalInstances, packingPlan.getInstanceCount()); } /** * Test the scenario where the user defined number of containers is not sufficient. */ @Test public void testInsufficientContainersWithMultipleAdjustments() throws Exception { int numContainers = 1; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 2L * Constants.GB; // Explicit set component ram map long boltRam = 1L * Constants.GB; long spoutRam = 2L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setComponentRam(BOLT_NAME, boltRam); topologyConfig.setComponentRam(SPOUT_NAME, spoutRam); TopologyAPI.Topology topologyExplicitRamMap = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlan = getResourceCompliantRRPackingPlan(topologyExplicitRamMap); Assert.assertEquals(packingPlan.getContainers().size(), 7); Assert.assertEquals(totalInstances, packingPlan.getInstanceCount()); } /** * test even packing of instances */ @Test public void testEvenPacking() throws Exception { int numContainers = 2; int componentParallelism = 4; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); TopologyAPI.Topology topology = getTopology(componentParallelism, componentParallelism, topologyConfig); int numInstance = TopologyUtils.getTotalInstance(topology); // Two components Assert.assertEquals(2 * componentParallelism, numInstance); PackingPlan output = getResourceCompliantRRPackingPlan(topology); Assert.assertEquals(numContainers, output.getContainers().size()); Assert.assertEquals((Integer) numInstance, output.getInstanceCount()); for (PackingPlan.ContainerPlan container : output.getContainers()) { Assert.assertEquals(numInstance / numContainers, container.getInstances().size()); Assert.assertEquals( 2, countComponent("spout", container.getInstances())); Assert.assertEquals( 2, countComponent("bolt", container.getInstances())); } } }
UTF-8
Java
15,982
java
ResourceCompliantRRPackingTest.java
Java
[]
null
[]
// Copyright 2016 Twitter. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.twitter.heron.packing.roundrobin; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; import com.twitter.heron.api.generated.TopologyAPI; import com.twitter.heron.packing.AssertPacking; import com.twitter.heron.spi.common.ClusterDefaults; import com.twitter.heron.spi.common.Config; import com.twitter.heron.spi.common.Constants; import com.twitter.heron.spi.common.Context; import com.twitter.heron.spi.common.Keys; import com.twitter.heron.spi.packing.PackingPlan; import com.twitter.heron.spi.packing.Resource; import com.twitter.heron.spi.utils.TopologyTests; import com.twitter.heron.spi.utils.TopologyUtils; public class ResourceCompliantRRPackingTest { private static final String BOLT_NAME = "bolt"; private static final String SPOUT_NAME = "spout"; private static final int DEFAULT_CONTAINER_PADDING = 10; private long instanceRamDefault; private double instanceCpuDefault; private long instanceDiskDefault; private int countComponent(String component, Set<PackingPlan.InstancePlan> instances) { int count = 0; for (PackingPlan.InstancePlan instancePlan : instances) { if (component.equals(instancePlan.getComponentName())) { count++; } } return count; } private TopologyAPI.Topology getTopology( int spoutParallelism, int boltParallelism, com.twitter.heron.api.Config topologyConfig) { return TopologyTests.createTopology("testTopology", topologyConfig, SPOUT_NAME, BOLT_NAME, spoutParallelism, boltParallelism); } private PackingPlan getResourceCompliantRRPackingPlan(TopologyAPI.Topology topology) { Config config = Config.newBuilder() .put(Keys.topologyId(), topology.getId()) .put(Keys.topologyName(), topology.getName()) .putAll(ClusterDefaults.getDefaults()) .build(); this.instanceRamDefault = Context.instanceRam(config); this.instanceCpuDefault = Context.instanceCpu(config); this.instanceDiskDefault = Context.instanceDisk(config); ResourceCompliantRRPacking packing = new ResourceCompliantRRPacking(); packing.initialize(config, topology); return packing.pack(); } @Test(expected = RuntimeException.class) public void testCheckFailure() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set insufficient ram for container long containerRam = -1L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); TopologyAPI.Topology topology = getTopology(spoutParallelism, boltParallelism, topologyConfig); getResourceCompliantRRPackingPlan(topology); } /** * Test the scenario where the max container size is the default */ @Test public void testDefaultResources() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // No explicit resources required TopologyAPI.Topology topologyNoExplicitResourcesConfig = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanNoExplicitResourcesConfig = getResourceCompliantRRPackingPlan(topologyNoExplicitResourcesConfig); Assert.assertEquals(packingPlanNoExplicitResourcesConfig.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlanNoExplicitResourcesConfig.getInstanceCount()); } /** * Test the scenario where the max container size is the default and padding is configured */ @Test public void testDefaultContainerSizeWithPadding() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; int padding = 50; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); topologyConfig.setContainerPaddingPercentage(padding); TopologyAPI.Topology topology = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlan = getResourceCompliantRRPackingPlan(topology); Assert.assertEquals(packingPlan.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlan.getInstanceCount()); } /** * Test the scenario where container level resource config are set */ @Test public void testContainerRequestedResourcesSingleContainer() throws Exception { int numContainers = 1; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 10L * Constants.GB; long containerDisk = 20L * Constants.GB; float containerCpu = 30; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setContainerDiskRequested(containerDisk); topologyConfig.setContainerCpuRequested(containerCpu); TopologyAPI.Topology topologyExplicitResourcesConfig = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitResourcesConfig = getResourceCompliantRRPackingPlan(topologyExplicitResourcesConfig); Assert.assertEquals(packingPlanExplicitResourcesConfig.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlanExplicitResourcesConfig.getInstanceCount()); for (PackingPlan.ContainerPlan containerPlan : packingPlanExplicitResourcesConfig.getContainers()) { Assert.assertEquals(Math.round(totalInstances * instanceCpuDefault + (DEFAULT_CONTAINER_PADDING / 100.0) * totalInstances * instanceCpuDefault), (long) containerPlan.getRequiredResource().getCpu()); Assert.assertEquals(totalInstances * instanceRamDefault + (long) ((DEFAULT_CONTAINER_PADDING / 100.0) * totalInstances * instanceRamDefault), containerPlan.getRequiredResource().getRam()); Assert.assertEquals(totalInstances * instanceDiskDefault + (long) ((DEFAULT_CONTAINER_PADDING / 100.0) * totalInstances * instanceDiskDefault), containerPlan.getRequiredResource().getDisk()); // All instances' resource requirement should be equal // So the size of set should be 1 Set<Resource> resources = new HashSet<>(); for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) { resources.add(instancePlan.getResource()); } Assert.assertEquals(1, resources.size()); Assert.assertEquals(instanceRamDefault, resources.iterator().next().getRam()); } } /** * Test the scenario where container level resource config are set */ @Test public void testContainerRequestedResourcesTwoContainers() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 10L * Constants.GB; long containerDisk = 20L * Constants.GB; float containerCpu = 30; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setContainerDiskRequested(containerDisk); topologyConfig.setContainerCpuRequested(containerCpu); TopologyAPI.Topology topologyExplicitResourcesConfig = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitResourcesConfig = getResourceCompliantRRPackingPlan(topologyExplicitResourcesConfig); Assert.assertEquals(packingPlanExplicitResourcesConfig.getContainers().size(), numContainers); Assert.assertEquals(totalInstances, packingPlanExplicitResourcesConfig.getInstanceCount()); // Ram for bolt/spout should be the value in component ram map for (PackingPlan.ContainerPlan containerPlan : packingPlanExplicitResourcesConfig.getContainers()) { for (PackingPlan.InstancePlan instancePlan : containerPlan.getInstances()) { Assert.assertEquals(instanceRamDefault, instancePlan.getResource().getRam()); } } } /** * Test the scenario ram map config is partially set */ @Test public void testCompleteRamMapRequested() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container // the value should be ignored, since we set the complete component ram map long containerRam = Long.MAX_VALUE; // Explicit set component ram map long boltRam = 1L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setComponentRam(BOLT_NAME, boltRam); TopologyAPI.Topology topologyExplicitRamMap = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitRamMap = getResourceCompliantRRPackingPlan(topologyExplicitRamMap); Assert.assertEquals(totalInstances, packingPlanExplicitRamMap.getInstanceCount()); AssertPacking.assertContainers(packingPlanExplicitRamMap.getContainers(), BOLT_NAME, SPOUT_NAME, boltRam, instanceRamDefault, containerRam); } /** * Test the scenario ram map config is fully set */ @Test public void testPartialRamMap() throws Exception { int numContainers = 2; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 10L * Constants.GB; // Explicit set component ram map long boltRam = 1L * Constants.GB; long spoutRam = 2L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setComponentRam(BOLT_NAME, boltRam); topologyConfig.setComponentRam(SPOUT_NAME, spoutRam); TopologyAPI.Topology topologyExplicitRamMap = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlanExplicitRamMap = getResourceCompliantRRPackingPlan(topologyExplicitRamMap); Assert.assertEquals(totalInstances, packingPlanExplicitRamMap.getInstanceCount()); AssertPacking.assertContainers(packingPlanExplicitRamMap.getContainers(), BOLT_NAME, SPOUT_NAME, boltRam, spoutRam, containerRam); } /** * Test the scenario where the user defined number of containers is not sufficient. */ @Test public void testInsufficientContainersWithOneAdjustment() throws Exception { int numContainers = 1; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 2L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); TopologyAPI.Topology topology = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlan = getResourceCompliantRRPackingPlan(topology); Assert.assertEquals(packingPlan.getContainers().size(), 4); Assert.assertEquals(totalInstances, packingPlan.getInstanceCount()); } /** * Test the scenario where the user defined number of containers is not sufficient. */ @Test public void testInsufficientContainersWithMultipleAdjustments() throws Exception { int numContainers = 1; int spoutParallelism = 4; int boltParallelism = 3; Integer totalInstances = spoutParallelism + boltParallelism; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); // Explicit set resources for container long containerRam = 2L * Constants.GB; // Explicit set component ram map long boltRam = 1L * Constants.GB; long spoutRam = 2L * Constants.GB; topologyConfig.setContainerRamRequested(containerRam); topologyConfig.setComponentRam(BOLT_NAME, boltRam); topologyConfig.setComponentRam(SPOUT_NAME, spoutRam); TopologyAPI.Topology topologyExplicitRamMap = getTopology(spoutParallelism, boltParallelism, topologyConfig); PackingPlan packingPlan = getResourceCompliantRRPackingPlan(topologyExplicitRamMap); Assert.assertEquals(packingPlan.getContainers().size(), 7); Assert.assertEquals(totalInstances, packingPlan.getInstanceCount()); } /** * test even packing of instances */ @Test public void testEvenPacking() throws Exception { int numContainers = 2; int componentParallelism = 4; // Set up the topology and its config com.twitter.heron.api.Config topologyConfig = new com.twitter.heron.api.Config(); topologyConfig.put(com.twitter.heron.api.Config.TOPOLOGY_STMGRS, numContainers); TopologyAPI.Topology topology = getTopology(componentParallelism, componentParallelism, topologyConfig); int numInstance = TopologyUtils.getTotalInstance(topology); // Two components Assert.assertEquals(2 * componentParallelism, numInstance); PackingPlan output = getResourceCompliantRRPackingPlan(topology); Assert.assertEquals(numContainers, output.getContainers().size()); Assert.assertEquals((Integer) numInstance, output.getInstanceCount()); for (PackingPlan.ContainerPlan container : output.getContainers()) { Assert.assertEquals(numInstance / numContainers, container.getInstances().size()); Assert.assertEquals( 2, countComponent("spout", container.getInstances())); Assert.assertEquals( 2, countComponent("bolt", container.getInstances())); } } }
15,982
0.750907
0.745714
398
39.155781
30.190449
100
false
false
0
0
0
0
0
0
0.665829
false
false
12
498310bda552ddbfd49d0e087679a270db04be3a
21,165,598,859,614
32f38cd53372ba374c6dab6cc27af78f0a1b0190
/app/src/main/java/defpackage/bjz.java
99d4e29053d99a71ac3f25d4b28e4b2c73bf0a30
[ "BSD-3-Clause" ]
permissive
shuixi2013/AmapCode
https://github.com/shuixi2013/AmapCode
9ea7aefb42e0413f348f238f0721c93245f4eac6
1a3a8d4dddfcc5439df8df570000cca12b15186a
refs/heads/master
2023-06-06T23:08:57.391000
2019-08-29T04:36:02
2019-08-29T04:36:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package defpackage; import android.graphics.Bitmap.Config; import android.net.Uri; import com.alipay.mobile.common.transport.monitor.RPCDataParser; import com.autonavi.common.imageloader.ImageLoader.Priority; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /* renamed from: bjz reason: default package */ /* compiled from: Request */ public final class bjz { private static final long u = TimeUnit.SECONDS.toNanos(5); int a; long b; int c; public final Uri d; public final int e; public final String f; public final List<bjo> g; public final int h; public final int i; public final boolean j; public final boolean k; public final boolean l; public final float m; public final float n; public final float o; public final boolean p; public final boolean q; public final Config r; public final Priority s; public final Map<String, String> t; bjz(Uri uri, int i2, String str, List<bjo> list, int i3, int i4, boolean z, boolean z2, boolean z3, float f2, float f3, float f4, boolean z4, boolean z5, Config config, Priority priority, Map<String, String> map) { this.d = uri; this.e = i2; this.f = str; if (list == null) { this.g = null; } else { this.g = Collections.unmodifiableList(list); } this.h = i3; this.i = i4; this.j = z; this.k = z2; this.l = z3; this.m = f2; this.n = f3; this.o = f4; this.p = z4; this.q = z5; this.r = config; this.s = priority; this.t = map; } public final String toString() { StringBuilder sb = new StringBuilder("Request{"); if (this.e > 0) { sb.append(this.e); } else { sb.append(this.d); } if (this.g != null && !this.g.isEmpty()) { for (bjo a2 : this.g) { sb.append(' '); sb.append(a2.a()); } } if (this.f != null) { sb.append(" stableKey("); sb.append(this.f); sb.append(')'); } if (this.h > 0) { sb.append(" resize("); sb.append(this.h); sb.append(','); sb.append(this.i); sb.append(')'); } if (this.j) { sb.append(" centerCrop"); } if (this.k) { sb.append(" centerInside"); } if (this.m != 0.0f) { sb.append(" rotation("); sb.append(this.m); if (this.p) { sb.append(" @ "); sb.append(this.n); sb.append(','); sb.append(this.o); } sb.append(')'); } if (this.q) { sb.append(" purgeable"); } if (this.r != null) { sb.append(' '); sb.append(this.r); } sb.append('}'); return sb.toString(); } public final String a() { long nanoTime = System.nanoTime() - this.b; if (nanoTime > u) { StringBuilder sb = new StringBuilder(); sb.append(b()); sb.append('+'); sb.append(TimeUnit.NANOSECONDS.toSeconds(nanoTime)); sb.append('s'); return sb.toString(); } StringBuilder sb2 = new StringBuilder(); sb2.append(b()); sb2.append('+'); sb2.append(TimeUnit.NANOSECONDS.toMillis(nanoTime)); sb2.append(RPCDataParser.TIME_MS); return sb2.toString(); } public final String b() { StringBuilder sb = new StringBuilder("[R"); sb.append(this.a); sb.append(']'); return sb.toString(); } public final boolean c() { return (this.h == 0 && this.i == 0) ? false : true; } /* access modifiers changed from: 0000 */ public final boolean d() { return c() || this.m != 0.0f; } /* access modifiers changed from: 0000 */ public final boolean e() { return this.g != null; } }
UTF-8
Java
4,203
java
bjz.java
Java
[]
null
[]
package defpackage; import android.graphics.Bitmap.Config; import android.net.Uri; import com.alipay.mobile.common.transport.monitor.RPCDataParser; import com.autonavi.common.imageloader.ImageLoader.Priority; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /* renamed from: bjz reason: default package */ /* compiled from: Request */ public final class bjz { private static final long u = TimeUnit.SECONDS.toNanos(5); int a; long b; int c; public final Uri d; public final int e; public final String f; public final List<bjo> g; public final int h; public final int i; public final boolean j; public final boolean k; public final boolean l; public final float m; public final float n; public final float o; public final boolean p; public final boolean q; public final Config r; public final Priority s; public final Map<String, String> t; bjz(Uri uri, int i2, String str, List<bjo> list, int i3, int i4, boolean z, boolean z2, boolean z3, float f2, float f3, float f4, boolean z4, boolean z5, Config config, Priority priority, Map<String, String> map) { this.d = uri; this.e = i2; this.f = str; if (list == null) { this.g = null; } else { this.g = Collections.unmodifiableList(list); } this.h = i3; this.i = i4; this.j = z; this.k = z2; this.l = z3; this.m = f2; this.n = f3; this.o = f4; this.p = z4; this.q = z5; this.r = config; this.s = priority; this.t = map; } public final String toString() { StringBuilder sb = new StringBuilder("Request{"); if (this.e > 0) { sb.append(this.e); } else { sb.append(this.d); } if (this.g != null && !this.g.isEmpty()) { for (bjo a2 : this.g) { sb.append(' '); sb.append(a2.a()); } } if (this.f != null) { sb.append(" stableKey("); sb.append(this.f); sb.append(')'); } if (this.h > 0) { sb.append(" resize("); sb.append(this.h); sb.append(','); sb.append(this.i); sb.append(')'); } if (this.j) { sb.append(" centerCrop"); } if (this.k) { sb.append(" centerInside"); } if (this.m != 0.0f) { sb.append(" rotation("); sb.append(this.m); if (this.p) { sb.append(" @ "); sb.append(this.n); sb.append(','); sb.append(this.o); } sb.append(')'); } if (this.q) { sb.append(" purgeable"); } if (this.r != null) { sb.append(' '); sb.append(this.r); } sb.append('}'); return sb.toString(); } public final String a() { long nanoTime = System.nanoTime() - this.b; if (nanoTime > u) { StringBuilder sb = new StringBuilder(); sb.append(b()); sb.append('+'); sb.append(TimeUnit.NANOSECONDS.toSeconds(nanoTime)); sb.append('s'); return sb.toString(); } StringBuilder sb2 = new StringBuilder(); sb2.append(b()); sb2.append('+'); sb2.append(TimeUnit.NANOSECONDS.toMillis(nanoTime)); sb2.append(RPCDataParser.TIME_MS); return sb2.toString(); } public final String b() { StringBuilder sb = new StringBuilder("[R"); sb.append(this.a); sb.append(']'); return sb.toString(); } public final boolean c() { return (this.h == 0 && this.i == 0) ? false : true; } /* access modifiers changed from: 0000 */ public final boolean d() { return c() || this.m != 0.0f; } /* access modifiers changed from: 0000 */ public final boolean e() { return this.g != null; } }
4,203
0.504877
0.494171
152
26.651316
21.093544
218
false
false
0
0
0
0
0
0
0.769737
false
false
12
1c43b22dfe33ef3d7e9a25d5b6f2ab61a51f97b5
7,490,422,997,563
609fc11530f60747668133b6c587e7af93a805ba
/src/crashcourse/k/library/debug/InputStreamTest.java
ac0b30422e9a8247c8195442c5130abac3d7f30e
[]
no_license
danmw3/CrashCourse
https://github.com/danmw3/CrashCourse
e5dc23670b53433693c91afa0df3f1b8b201af16
f585eaeae2cf9658f03ddf703f80b9373fc7d6d2
refs/heads/master
2018-12-28T13:39:07.991000
2013-11-30T19:50:06
2013-11-30T19:50:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package crashcourse.k.library.debug; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import crashcourse.k.library.util.LUtils; public class InputStreamTest { public static void main(String[] args) throws IOException { String path = // "C:/Users/Kenzie Togami/Dropbox/CrashCourse/test.zip/test/layer.zip/layer/zips.zip/zips/theresult.txt" .replace('/', '\\'); InputStream is = LUtils.getInputStream(path); System.err.println("Got " + is + " for " + path); if (is == null) { System.err.println("No InputStream, no data?"); return; } System.err.println("The result text file contains this message:"); BufferedInputStream bis = new BufferedInputStream(is); byte[] data = new byte[bis.available()]; bis.read(data); System.err.println(new String(data)); is.close(); } }
UTF-8
Java
848
java
InputStreamTest.java
Java
[ { "context": "rows IOException {\n\t\tString path = //\n\t\t\"C:/Users/Kenzie Togami/Dropbox/CrashCourse/test.zip/test/layer.zip/layer", "end": 311, "score": 0.9998462796211243, "start": 298, "tag": "NAME", "value": "Kenzie Togami" } ]
null
[]
package crashcourse.k.library.debug; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import crashcourse.k.library.util.LUtils; public class InputStreamTest { public static void main(String[] args) throws IOException { String path = // "C:/Users/<NAME>/Dropbox/CrashCourse/test.zip/test/layer.zip/layer/zips.zip/zips/theresult.txt" .replace('/', '\\'); InputStream is = LUtils.getInputStream(path); System.err.println("Got " + is + " for " + path); if (is == null) { System.err.println("No InputStream, no data?"); return; } System.err.println("The result text file contains this message:"); BufferedInputStream bis = new BufferedInputStream(is); byte[] data = new byte[bis.available()]; bis.read(data); System.err.println(new String(data)); is.close(); } }
841
0.709906
0.709906
28
29.285715
24.748531
104
false
false
0
0
0
0
0
0
1.928571
false
false
12
cedfcc12a0953f68705b0787725f7a66ad69c6a5
8,650,064,165,851
0f649a6caad7d87170840b0c8aee3a2a78774bc1
/src/main/java/pro/tremblay/javatools/NoOfCpu.java
49a1be8720f3ed710179ecddef403a6b3dcf43e0
[]
no_license
henri-tremblay/java-tools
https://github.com/henri-tremblay/java-tools
fd402b93d85584b68c19b2172052befaba27118e
88d82645f8ffc09c1caddb7aa5c06e490845f75b
refs/heads/master
2021-01-17T05:20:37.200000
2015-08-24T19:55:42
2015-08-24T19:55:42
31,679,039
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pro.tremblay.javatools; /** * Print the number of CPUs seen on a server */ public class NoOfCpu { public static void main( String[] args ) { System.out.println(Runtime.getRuntime().availableProcessors()); } }
UTF-8
Java
236
java
NoOfCpu.java
Java
[]
null
[]
package pro.tremblay.javatools; /** * Print the number of CPUs seen on a server */ public class NoOfCpu { public static void main( String[] args ) { System.out.println(Runtime.getRuntime().availableProcessors()); } }
236
0.677966
0.677966
11
20.454546
23.153101
71
false
false
0
0
0
0
0
0
0.181818
false
false
12
d3693863d43c7481a316e04ce97de51369b67e80
8,581,344,694,530
17756f81bd3219e89e014cf72fdd5270e1d559c2
/src/main/java/com/github/kong/ignite/spring/boot/features/rpc/annotation/IgniteRpcReference.java
299c6ad3abedd8f9e362a66047f18a578567053b
[ "Apache-2.0" ]
permissive
namnv98/ignite-spring-project
https://github.com/namnv98/ignite-spring-project
1d7e6e9b45d5a38f8bdb50c419087d743bff4419
1e079540ff228636cfff81c57c56160699b2c83c
refs/heads/master
2023-04-13T10:33:44.464000
2020-04-22T08:09:23
2020-04-22T08:09:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.kong.ignite.spring.boot.features.rpc.annotation; import java.lang.annotation.*; /** * 网格服务注入注解 */ @Target({ ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface IgniteRpcReference { String version() default "1.0"; //默认使用负载均衡 boolean isLoadbalance() default true; //默认不设超时 long timeout() default 0; }
UTF-8
Java
430
java
IgniteRpcReference.java
Java
[ { "context": "package com.github.kong.ignite.spring.boot.features.rpc.annotation;\n\nimpo", "end": 23, "score": 0.5557318925857544, "start": 19, "tag": "USERNAME", "value": "kong" } ]
null
[]
package com.github.kong.ignite.spring.boot.features.rpc.annotation; import java.lang.annotation.*; /** * 网格服务注入注解 */ @Target({ ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface IgniteRpcReference { String version() default "1.0"; //默认使用负载均衡 boolean isLoadbalance() default true; //默认不设超时 long timeout() default 0; }
430
0.699482
0.69171
21
17.380953
18.062
67
false
false
0
0
0
0
0
0
0.238095
false
false
12
ce101db81ba28865c3bcb7fc2a661a2837367757
1,657,857,412,712
f472272ec08492735492a77f6b591f101b944561
/geoPingProject/geoPing/src/main/java/eu/ttbox/geoping/ui/about/IntentAbout.java
e22d173232b3a4bfe4c692e48d80556c0d1f3200
[]
no_license
Liuchengxuan/android
https://github.com/Liuchengxuan/android
48fee5bc721028dc69d208593df681c10e3aebc2
c905367f54db8e9a1108467f8cb479440e318475
refs/heads/master
2020-12-03T05:25:46.249000
2013-07-25T16:12:25
2013-07-25T16:12:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package eu.ttbox.geoping.ui.about; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.webkit.WebView; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import eu.ttbox.geoping.R; public class IntentAbout { private static final String TAG = "IntentAbout"; public static final String ACTION_VIEW_HTML = Intent.ACTION_VIEW; public static final String ACTION_VIEW_ABOUT = "eu.ttbox.geoping.ui.about.ACTION_VIEW_ABOUT"; public static final String ACTION_VIEW_RELEASE_NOTES = "eu.ttbox.geoping.ui.about.ACTION_VIEW_RELEASE_NOTES"; public static final String ACTION_VIEW_LICENCE = "eu.ttbox.geoping.ui.about.ACTION_VIEW_LICENCE"; protected static void loadIntentContent(Intent intent, Activity activity, WebView webView ) { if (ACTION_VIEW_HTML.equals(intent.getAction())) { webView.loadUrl(intent.getData().getPath()); } else if (ACTION_VIEW_RELEASE_NOTES.equals(intent.getAction())) { webView.loadData(readTextFromResource(activity, R.raw.release_notes), "text/html", "utf-8"); activity.setTitle(R.string.prefs_relasenotes); } else if (ACTION_VIEW_ABOUT.equals(intent.getAction())) { webView.loadData(readTextFromResource(activity, R.raw.credits), "text/html", "utf-8"); activity.setTitle(R.string.prefs_about); } else if (ACTION_VIEW_LICENCE.equals(intent.getAction())) { webView.loadData(readTextFromResource(activity, R.raw.licence), "text/html", "utf-8"); activity.setTitle(R.string.prefs_license_activity_title); } } protected static String readTextFromResource(Context context , int resourceID) { InputStream raw = context.getResources().openRawResource(resourceID); ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { try { byte[] buffer = new byte[1024]; int len; while ((len = raw.read(buffer)) > -1) { stream.write(buffer, 0, len); } stream.flush(); } finally { raw.close(); stream.close(); } } catch (IOException e) { Log.e(TAG, "Error read TextFromResource [" + resourceID + "] in Raw : " + e.getMessage(), e); } return stream.toString(); } }
UTF-8
Java
2,499
java
IntentAbout.java
Java
[]
null
[]
package eu.ttbox.geoping.ui.about; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import android.webkit.WebView; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import eu.ttbox.geoping.R; public class IntentAbout { private static final String TAG = "IntentAbout"; public static final String ACTION_VIEW_HTML = Intent.ACTION_VIEW; public static final String ACTION_VIEW_ABOUT = "eu.ttbox.geoping.ui.about.ACTION_VIEW_ABOUT"; public static final String ACTION_VIEW_RELEASE_NOTES = "eu.ttbox.geoping.ui.about.ACTION_VIEW_RELEASE_NOTES"; public static final String ACTION_VIEW_LICENCE = "eu.ttbox.geoping.ui.about.ACTION_VIEW_LICENCE"; protected static void loadIntentContent(Intent intent, Activity activity, WebView webView ) { if (ACTION_VIEW_HTML.equals(intent.getAction())) { webView.loadUrl(intent.getData().getPath()); } else if (ACTION_VIEW_RELEASE_NOTES.equals(intent.getAction())) { webView.loadData(readTextFromResource(activity, R.raw.release_notes), "text/html", "utf-8"); activity.setTitle(R.string.prefs_relasenotes); } else if (ACTION_VIEW_ABOUT.equals(intent.getAction())) { webView.loadData(readTextFromResource(activity, R.raw.credits), "text/html", "utf-8"); activity.setTitle(R.string.prefs_about); } else if (ACTION_VIEW_LICENCE.equals(intent.getAction())) { webView.loadData(readTextFromResource(activity, R.raw.licence), "text/html", "utf-8"); activity.setTitle(R.string.prefs_license_activity_title); } } protected static String readTextFromResource(Context context , int resourceID) { InputStream raw = context.getResources().openRawResource(resourceID); ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { try { byte[] buffer = new byte[1024]; int len; while ((len = raw.read(buffer)) > -1) { stream.write(buffer, 0, len); } stream.flush(); } finally { raw.close(); stream.close(); } } catch (IOException e) { Log.e(TAG, "Error read TextFromResource [" + resourceID + "] in Raw : " + e.getMessage(), e); } return stream.toString(); } }
2,499
0.639056
0.635454
61
39.967213
32.987312
113
false
false
0
0
0
0
0
0
0.786885
false
false
12
1d2c70e145fda7bbb246022ad6800b8021a7c0e3
3,925,600,111,050
eceb5f0aa408caacf96eb9838733531a5284547c
/yhsmsServer/src/test/java/com/yhsms/test/MenumTest.java
6abbfb62f2194416e93184cda054ab25d2e2e48f
[]
no_license
STULCM/yhsmsServer
https://github.com/STULCM/yhsmsServer
2aa65c26693b1a4b9b8786fdc2b99239f8b60fcb
01b581deaeaca8a60a97b66b106fb14a0a94da8a
refs/heads/master
2020-05-14T23:46:54.906000
2019-04-23T06:18:06
2019-04-23T06:18:06
182,002,000
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yhsms.test; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import com.yhsms.Dao.menuDao; import com.yhsms.DaoImpl.menuDaoImpl; import com.yhsms.domain.Menum; import com.yhsms.domain.Menutype; public class MenumTest { //添加菜品 @Test public void addmenu() { menuDao dao=new menuDaoImpl(); System.out.println(dao.addmenu(new Menum(101, "青椒炒肉", 15,""),1)); } //客户查询所有菜 @Test public void userseletemenu() { menuDao dao=new menuDaoImpl(); Map<Integer, String> map = dao.userseletemenu(1); Set<Integer> keySet = map.keySet(); for (Integer i : keySet) { System.out.println(i+"\t"+map.get(i)); } } //经理查询所有的菜 @Test public void empseletemenu() { menuDao dao=new menuDaoImpl(); Map<Integer, String> map = dao.empseletemenu(); Set<Integer> keySet = map.keySet(); for (Integer i : keySet) { System.out.println(i+"\t"+map.get(i)); } } //删除菜 @Test public void deletemenu() { menuDao dao=new menuDaoImpl(); System.out.println(dao.deletemenu(103)); } //修改菜的价钱 @Test public void updatemenu() { menuDao dao=new menuDaoImpl(); System.out.println(dao.updatemenu(101, 20)); } //设置特价菜 @Test public void setspecial() { menuDao dao=new menuDaoImpl(); System.out.println(dao.setspecial(101)); } //显示特价菜 @Test public void selectspecial() { menuDao dao=new menuDaoImpl(); Map<Integer, String> map = dao.selectspecial(); Set<Integer> keySet = map.keySet(); for (Integer i : keySet) { System.out.println(i+"\t"+map.get(i)); } } }
UTF-8
Java
1,672
java
MenumTest.java
Java
[]
null
[]
package com.yhsms.test; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Test; import com.yhsms.Dao.menuDao; import com.yhsms.DaoImpl.menuDaoImpl; import com.yhsms.domain.Menum; import com.yhsms.domain.Menutype; public class MenumTest { //添加菜品 @Test public void addmenu() { menuDao dao=new menuDaoImpl(); System.out.println(dao.addmenu(new Menum(101, "青椒炒肉", 15,""),1)); } //客户查询所有菜 @Test public void userseletemenu() { menuDao dao=new menuDaoImpl(); Map<Integer, String> map = dao.userseletemenu(1); Set<Integer> keySet = map.keySet(); for (Integer i : keySet) { System.out.println(i+"\t"+map.get(i)); } } //经理查询所有的菜 @Test public void empseletemenu() { menuDao dao=new menuDaoImpl(); Map<Integer, String> map = dao.empseletemenu(); Set<Integer> keySet = map.keySet(); for (Integer i : keySet) { System.out.println(i+"\t"+map.get(i)); } } //删除菜 @Test public void deletemenu() { menuDao dao=new menuDaoImpl(); System.out.println(dao.deletemenu(103)); } //修改菜的价钱 @Test public void updatemenu() { menuDao dao=new menuDaoImpl(); System.out.println(dao.updatemenu(101, 20)); } //设置特价菜 @Test public void setspecial() { menuDao dao=new menuDaoImpl(); System.out.println(dao.setspecial(101)); } //显示特价菜 @Test public void selectspecial() { menuDao dao=new menuDaoImpl(); Map<Integer, String> map = dao.selectspecial(); Set<Integer> keySet = map.keySet(); for (Integer i : keySet) { System.out.println(i+"\t"+map.get(i)); } } }
1,672
0.660579
0.649244
80
18.549999
16.700974
67
false
false
0
0
0
0
0
0
1.65
false
false
12
a0d9ea5e15866dbedb037a22217b6e30cad2ee1c
23,356,032,201,506
039cb6c1ffb74d22318ff1dc1075172f5ce81d8e
/src/org/inventivetalent/murder/game/CountdownType.java
10000d4bf3a3be2655173829a78b96fd5bc9f24e
[ "MIT" ]
permissive
Tominous/Murder
https://github.com/Tominous/Murder
469901de44207fdb1ad31b0c6aa02ea4eb968205
3326609caa75f46f11370b612e7d47536f550f58
refs/heads/master
2020-05-15T21:55:08.187000
2019-04-21T09:12:57
2019-04-21T09:12:57
182,512,031
1
0
MIT
true
2019-04-21T09:03:04
2019-04-21T09:03:04
2019-04-21T09:03:01
2017-11-20T17:32:56
155
0
0
0
null
false
false
package org.inventivetalent.murder.game; public enum CountdownType { LOBBY, START; }
UTF-8
Java
88
java
CountdownType.java
Java
[]
null
[]
package org.inventivetalent.murder.game; public enum CountdownType { LOBBY, START; }
88
0.772727
0.772727
6
13.666667
14.76106
40
false
false
0
0
0
0
0
0
0.833333
false
false
12
e0bc5d0e7d5c34d5a5ac8f96bf2f123bad1d54bb
326,417,562,045
449893d30c547d8cc8e7f936ed827353daea72b7
/src/main/Actors/End.java
d4c1113715575e710a3810314b43a25c5333b538
[]
no_license
qkloh25/COMP2042_CW_lohqiankai
https://github.com/qkloh25/COMP2042_CW_lohqiankai
55ecc326870faa30316fec9614bead94f9e316b4
7784f96187285aac27cbe2bc5b7dd5c79d863856
refs/heads/master
2023-02-01T03:11:28.943000
2020-12-18T20:44:14
2020-12-18T20:44:14
309,449,637
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.Actors; import javafx.scene.image.Image; /** * The destinations. */ public class End extends Actor{ public static final String FILE_SRC_PICS = "file:src/res/pics/"; boolean activated = false; @Override public void act(long now) { // TODO Auto-generated method st } public End(int x, int y) { setX(x); setY(y); setImage(new Image(FILE_SRC_PICS + "End.png", 60, 60, true, true)); } /** * Destination arrived. */ public void setEnd() { setImage(new Image(FILE_SRC_PICS + "FrogEnd.png", 60, 60, true, true)); activated = true; } /** * Reset the destination state for next round. */ public void reset() { setImage(new Image(FILE_SRC_PICS + "End.png", 60, 60, true, true)); activated = false; } /** * * @return true if the destination is reached. */ public boolean isActivated() { return activated; } }
UTF-8
Java
872
java
End.java
Java
[]
null
[]
package main.Actors; import javafx.scene.image.Image; /** * The destinations. */ public class End extends Actor{ public static final String FILE_SRC_PICS = "file:src/res/pics/"; boolean activated = false; @Override public void act(long now) { // TODO Auto-generated method st } public End(int x, int y) { setX(x); setY(y); setImage(new Image(FILE_SRC_PICS + "End.png", 60, 60, true, true)); } /** * Destination arrived. */ public void setEnd() { setImage(new Image(FILE_SRC_PICS + "FrogEnd.png", 60, 60, true, true)); activated = true; } /** * Reset the destination state for next round. */ public void reset() { setImage(new Image(FILE_SRC_PICS + "End.png", 60, 60, true, true)); activated = false; } /** * * @return true if the destination is reached. */ public boolean isActivated() { return activated; } }
872
0.641055
0.627294
48
17.166666
20.23336
73
false
false
0
0
0
0
0
0
1.4375
false
false
12
09655bc1a33775d133a600fcb1de8214f5a44849
27,917,287,446,719
e2279c27430869443c282cd37d4fe1e2149e2aee
/src/main/java/com/lab2/zad2/model/RockPaperScissorsModel.java
b8e28f59b52e1917540608dbe1ffb7077c6e56f8
[]
no_license
piotrekjaromin/firstJavaEE
https://github.com/piotrekjaromin/firstJavaEE
2d008fbe2969440b1229b035bdda1099bab4b0b7
293e60335691e198925adcbd9f51da1821a7faa3
refs/heads/master
2021-01-10T05:34:34.643000
2016-03-31T12:14:27
2016-03-31T12:14:27
54,779,805
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lab2.zad2.model; import java.util.ArrayList; import java.util.List; /** * Created by piotrek on 10.03.16. */ public class RockPaperScissorsModel { private List<String> value = new ArrayList<>(); public RockPaperScissorsModel(){ value.add("rock"); value.add("paper"); value.add("scissors"); } public List<String> getValue() { return value; } public String generate(){ int random = (int)(Math.random() *3); return value.get(random); } public void setValue(List<String> value) { this.value = value; } }
UTF-8
Java
612
java
RockPaperScissorsModel.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by piotrek on 10.03.16.\n */\npublic class RockPaperScissorsMo", "end": 107, "score": 0.9996750950813293, "start": 100, "tag": "USERNAME", "value": "piotrek" } ]
null
[]
package com.lab2.zad2.model; import java.util.ArrayList; import java.util.List; /** * Created by piotrek on 10.03.16. */ public class RockPaperScissorsModel { private List<String> value = new ArrayList<>(); public RockPaperScissorsModel(){ value.add("rock"); value.add("paper"); value.add("scissors"); } public List<String> getValue() { return value; } public String generate(){ int random = (int)(Math.random() *3); return value.get(random); } public void setValue(List<String> value) { this.value = value; } }
612
0.602941
0.588235
30
19.4
16.420719
51
false
false
0
0
0
0
0
0
0.366667
false
false
12
c7fd09f1aba9b323bacc2b2842a41bd53a5447b1
23,184,233,505,784
ddda5ad6a17eda2ac67389f3c1047bcc15b78244
/app/src/main/java/com/apphunt/app/AppHuntApplication.java
c1fe2e0ce8da9733fc8884ae006bec59082ad494
[]
no_license
n0m0r3pa1n/apphunt_android
https://github.com/n0m0r3pa1n/apphunt_android
b2bfad063ebabcae9bc17f8705c8bb34618441f9
a0ffe3fd85bd38f277f5933eb0e66b968e628aa0
refs/heads/master
2022-12-14T05:31:57.832000
2021-12-29T12:54:33
2021-12-29T12:54:33
53,215,418
5
2
null
false
2022-12-05T22:24:20
2016-03-05T18:04:46
2022-08-03T17:22:15
2022-12-05T22:24:18
165,650
3
1
1
Java
false
false
package com.apphunt.app; import android.text.TextUtils; import com.apphunt.app.api.apphunt.VolleyInstance; import com.apphunt.app.auth.AnonymousLoginProvider; import com.apphunt.app.auth.LoginProviderFactory; import com.apphunt.app.constants.Constants; import com.apphunt.app.utils.FlurryWrapper; import com.apphunt.app.utils.GsonInstance; import com.apphunt.app.utils.SharedPreferencesHelper; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import com.facebook.FacebookSdk; import com.twitter.sdk.android.Twitter; import com.twitter.sdk.android.core.TwitterAuthConfig; import io.branch.referral.BranchApp; import io.fabric.sdk.android.Fabric; /** * Created by Naughty Spirit <hi@naughtyspirit.co> * on 3/6/15. */ public class AppHuntApplication extends BranchApp { @Override public void onCreate() { super.onCreate(); SharedPreferencesHelper.init(this); initNetworking(); initLogin(); initAnalytics(); } private void initLogin() { if(LoginProviderFactory.get(this) == null) { LoginProviderFactory.setLoginProvider(new AnonymousLoginProvider(this)); } } private void initAnalytics() { String userId = SharedPreferencesHelper.getStringPreference(Constants.KEY_USER_ID); if (!TextUtils.isEmpty(userId)) { FlurryWrapper.setUserId(userId); } TwitterAuthConfig authConfig = new TwitterAuthConfig(Constants.TWITTER_CONSUMER_KEY, Constants.TWITTER_CONSUMER_SECRET); CrashlyticsCore core = new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build(); Fabric.with(this, new Twitter(authConfig), new Crashlytics.Builder().core(core).build()); FacebookSdk.sdkInitialize(getApplicationContext(), Constants.FACEBOOK_SIGN_IN); FlurryWrapper.init(this); } private void initNetworking() { VolleyInstance.getInstance(this); GsonInstance.init(); } }
UTF-8
Java
2,037
java
AppHuntApplication.java
Java
[ { "context": "t io.fabric.sdk.android.Fabric;\n\n/**\n * Created by Naughty Spirit <hi@naughtyspirit.co>\n * on 3/6/15.\n */\npublic cl", "end": 729, "score": 0.9734708070755005, "start": 715, "tag": "USERNAME", "value": "Naughty Spirit" }, { "context": "ndroid.Fabric;\n\n/**\n * Created by Naughty Spirit <hi@naughtyspirit.co>\n * on 3/6/15.\n */\npublic class AppHuntApplicatio", "end": 750, "score": 0.999923050403595, "start": 731, "tag": "EMAIL", "value": "hi@naughtyspirit.co" } ]
null
[]
package com.apphunt.app; import android.text.TextUtils; import com.apphunt.app.api.apphunt.VolleyInstance; import com.apphunt.app.auth.AnonymousLoginProvider; import com.apphunt.app.auth.LoginProviderFactory; import com.apphunt.app.constants.Constants; import com.apphunt.app.utils.FlurryWrapper; import com.apphunt.app.utils.GsonInstance; import com.apphunt.app.utils.SharedPreferencesHelper; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import com.facebook.FacebookSdk; import com.twitter.sdk.android.Twitter; import com.twitter.sdk.android.core.TwitterAuthConfig; import io.branch.referral.BranchApp; import io.fabric.sdk.android.Fabric; /** * Created by Naughty Spirit <<EMAIL>> * on 3/6/15. */ public class AppHuntApplication extends BranchApp { @Override public void onCreate() { super.onCreate(); SharedPreferencesHelper.init(this); initNetworking(); initLogin(); initAnalytics(); } private void initLogin() { if(LoginProviderFactory.get(this) == null) { LoginProviderFactory.setLoginProvider(new AnonymousLoginProvider(this)); } } private void initAnalytics() { String userId = SharedPreferencesHelper.getStringPreference(Constants.KEY_USER_ID); if (!TextUtils.isEmpty(userId)) { FlurryWrapper.setUserId(userId); } TwitterAuthConfig authConfig = new TwitterAuthConfig(Constants.TWITTER_CONSUMER_KEY, Constants.TWITTER_CONSUMER_SECRET); CrashlyticsCore core = new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build(); Fabric.with(this, new Twitter(authConfig), new Crashlytics.Builder().core(core).build()); FacebookSdk.sdkInitialize(getApplicationContext(), Constants.FACEBOOK_SIGN_IN); FlurryWrapper.init(this); } private void initNetworking() { VolleyInstance.getInstance(this); GsonInstance.init(); } }
2,025
0.713304
0.71134
63
31.333334
26.170382
97
false
false
0
0
0
0
0
0
0.555556
false
false
12
8db31ab96b24fd70013d6e114cfe43c3fb5ef4d2
1,065,151,913,768
16491c1a59c55d80f09699e5568c2ba1769d2ff1
/src/main/java/FxUtils/SequentialAnimator.java
8f87ebf6690a2ecfc372f812918677dbb43d51b4
[]
no_license
domino2/javaUtilities
https://github.com/domino2/javaUtilities
d96f8ddabc06c0909e0201fb1e2df0518645d931
e6467dd26ebb12daa5dfc5a24dfa342707c9cf76
refs/heads/master
2021-05-08T15:46:19.659000
2018-02-03T20:15:50
2018-02-03T20:15:50
120,125,874
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package FxUtils; import EventLibrary.EventData; import java.util.ArrayList; public class SequentialAnimator<T extends Animation> extends EventLibrary.BasicEventOfferer { public double getRenderedTiles() { return this.currentAnimation + 1; } private enum InnerState { Running, WaitingForTiles, WantOneStep, WantToRun, WantToStop } public enum Events { NodeRendered } private final ArrayList<Animation> animationList; private int currentAnimation; private InnerState currentState; public SequentialAnimator(){ this.animationList = new ArrayList<>(); this.currentAnimation = -1; this.currentState = InnerState.WantToStop; } public void go(){ this.currentState = InnerState.WantToRun; runAnimations(); } public void oneStep(){ this.currentState = InnerState.WantOneStep; runAnimations(); } public void stop(){ this.currentState = InnerState.WantToStop; } public T addAnimation(Animation tileAnimation){ this.animationList.add(tileAnimation); if(this.currentState == InnerState.WaitingForTiles){ runAnimations(); } return (T)tileAnimation; } // ------------------------------ // ROUTINES // ------------------------------ private void runAnimations(){ if ( this.currentState == InnerState.Running ) { return; } animationStep(); } private void animationStep(){ if( this.currentState == InnerState.WantToStop ){ return; } if( this.currentState == InnerState.WantToRun ){ this.currentState = InnerState.Running; } if( this.currentState == InnerState.WantOneStep ){ this.currentState = InnerState.WantToStop; } if( this.animationList.isEmpty() || this.currentAnimation + 1 == this.animationList.size()){ this.currentState = InnerState.WaitingForTiles; return; } if( this.currentState == InnerState.WaitingForTiles ){ this.currentState = InnerState.Running; } animationList.get(++currentAnimation).run().then( (defer) -> { fireEvent(Events.NodeRendered, new EventData(defer.getPreserved(), this)); animationStep(); } ); } }
UTF-8
Java
2,562
java
SequentialAnimator.java
Java
[]
null
[]
package FxUtils; import EventLibrary.EventData; import java.util.ArrayList; public class SequentialAnimator<T extends Animation> extends EventLibrary.BasicEventOfferer { public double getRenderedTiles() { return this.currentAnimation + 1; } private enum InnerState { Running, WaitingForTiles, WantOneStep, WantToRun, WantToStop } public enum Events { NodeRendered } private final ArrayList<Animation> animationList; private int currentAnimation; private InnerState currentState; public SequentialAnimator(){ this.animationList = new ArrayList<>(); this.currentAnimation = -1; this.currentState = InnerState.WantToStop; } public void go(){ this.currentState = InnerState.WantToRun; runAnimations(); } public void oneStep(){ this.currentState = InnerState.WantOneStep; runAnimations(); } public void stop(){ this.currentState = InnerState.WantToStop; } public T addAnimation(Animation tileAnimation){ this.animationList.add(tileAnimation); if(this.currentState == InnerState.WaitingForTiles){ runAnimations(); } return (T)tileAnimation; } // ------------------------------ // ROUTINES // ------------------------------ private void runAnimations(){ if ( this.currentState == InnerState.Running ) { return; } animationStep(); } private void animationStep(){ if( this.currentState == InnerState.WantToStop ){ return; } if( this.currentState == InnerState.WantToRun ){ this.currentState = InnerState.Running; } if( this.currentState == InnerState.WantOneStep ){ this.currentState = InnerState.WantToStop; } if( this.animationList.isEmpty() || this.currentAnimation + 1 == this.animationList.size()){ this.currentState = InnerState.WaitingForTiles; return; } if( this.currentState == InnerState.WaitingForTiles ){ this.currentState = InnerState.Running; } animationList.get(++currentAnimation).run().then( (defer) -> { fireEvent(Events.NodeRendered, new EventData(defer.getPreserved(), this)); animationStep(); } ); } }
2,562
0.563622
0.562451
94
26.25532
22.884974
93
false
false
0
0
0
0
0
0
0.393617
false
false
12
08d811d68a34bdfd9cfd0ff74c810a8d08dd2c13
13,073,880,460,609
b4f8d2549f545cb02ec39507eb474abf6fb65657
/AdvAssess - Questions/src/main/java/com/questionserver/QuestionService/QuestionController.java
b06d6ec960363646fe9841eb9398fc9d207644ed
[]
no_license
jonathan784/HCL_Inter_Projects
https://github.com/jonathan784/HCL_Inter_Projects
7dc7c33375e47c29efef3e6e3743b37ad58a0aa4
5c5e14712b093b28340aba807902dd8d874276d7
refs/heads/main
2023-05-08T23:15:39.802000
2021-05-28T20:57:26
2021-05-28T20:57:26
338,443,153
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.questionserver.QuestionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @CrossOrigin(origins = "*") @RequestMapping("/api") public class QuestionController { @Autowired QuestionRepository questionRepository; @GetMapping("/getAllQuestions") public List<Question> getAllQuestions() { return questionRepository.findAll(); } @PostMapping("/insertQuestion") public String insertQuestion(@RequestBody Question question) { //creating a persistent question Question persistentQuestion = new Question(); //map passed object to this persistent object persistentQuestion = question; questionRepository.save(persistentQuestion); return "Question added."; } @DeleteMapping("/deleteAllQuestions") public String deleteAllQuestions(){ questionRepository.deleteAll(); return "All questions deleted"; } //Returns all of a particular user's assessments by querying the database against their userEmail that is assigned to their assessment @PostMapping(value = "/returnAllByAssessmentType", produces={"application/json"}) public List<Question> getAllByAssessmentType(@RequestBody Question theAssessmentObject) { //creating a persistent question Question persistentAssessmentObject = new Question(); //map passed object to this persistent object persistentAssessmentObject = theAssessmentObject; String assessmentType = persistentAssessmentObject.getAssessmentType(); return questionRepository.findAllByAssessmentType(assessmentType); } }
UTF-8
Java
1,741
java
QuestionController.java
Java
[]
null
[]
package com.questionserver.QuestionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @CrossOrigin(origins = "*") @RequestMapping("/api") public class QuestionController { @Autowired QuestionRepository questionRepository; @GetMapping("/getAllQuestions") public List<Question> getAllQuestions() { return questionRepository.findAll(); } @PostMapping("/insertQuestion") public String insertQuestion(@RequestBody Question question) { //creating a persistent question Question persistentQuestion = new Question(); //map passed object to this persistent object persistentQuestion = question; questionRepository.save(persistentQuestion); return "Question added."; } @DeleteMapping("/deleteAllQuestions") public String deleteAllQuestions(){ questionRepository.deleteAll(); return "All questions deleted"; } //Returns all of a particular user's assessments by querying the database against their userEmail that is assigned to their assessment @PostMapping(value = "/returnAllByAssessmentType", produces={"application/json"}) public List<Question> getAllByAssessmentType(@RequestBody Question theAssessmentObject) { //creating a persistent question Question persistentAssessmentObject = new Question(); //map passed object to this persistent object persistentAssessmentObject = theAssessmentObject; String assessmentType = persistentAssessmentObject.getAssessmentType(); return questionRepository.findAllByAssessmentType(assessmentType); } }
1,741
0.731763
0.731763
55
30.654545
29.745722
138
false
false
0
0
0
0
0
0
0.309091
false
false
12
50c96a2eb06d135d604d6c50bf25a861b3cd2727
13,073,880,461,913
1223ebac55e5dc6171620ce8c5215abe29fdd8e8
/modules/misc/src/misc/MiscSimulator.java
3b1342291855566cf0dc60d277e78d6c3d34459a
[ "BSD-3-Clause" ]
permissive
Dreamer-WangYiQiang/rcrs-server
https://github.com/Dreamer-WangYiQiang/rcrs-server
58d0ede69ebc49564811e362002b21765c6167a3
fcd97de77d8a4214cb3e12951bfbbd61960a73a5
refs/heads/master
2023-07-15T18:02:14.781000
2021-07-24T16:48:53
2021-07-24T16:48:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package misc; import java.util.ArrayList; import java.util.Deque; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import javax.swing.JComponent; import rescuecore2.GUIComponent; import rescuecore2.messages.Command; import rescuecore2.messages.control.KSCommands; import rescuecore2.messages.control.KSUpdate; import rescuecore2.misc.geometry.GeometryTools2D; import rescuecore2.misc.geometry.Point2D; import rescuecore2.standard.components.StandardSimulator; import rescuecore2.standard.entities.*; import rescuecore2.standard.messages.AKRescue; import rescuecore2.standard.messages.AKUnload; import rescuecore2.standard.messages.AKLoad; import rescuecore2.worldmodel.Entity; import rescuecore2.worldmodel.EntityID; import rescuecore2.worldmodel.EntityListener; import rescuecore2.worldmodel.Property; import rescuecore2.worldmodel.ChangeSet; import rescuecore2.log.Logger; /** * Implementation of the legacy misc simulator. * * @author Maitreyi Nanjanath * @author Cameron Skinner * * Implementation of Refuge Bed Capacity * @author Farshid Faraji */ public class MiscSimulator extends StandardSimulator implements GUIComponent { private Map<EntityID, HumanAttributes> humans; private Set<EntityID> newlyBrokenBuildings; private Map<EntityID, Integer> oldBrokenBuildingsBuriedness = new HashMap<>(); private MiscParameters parameters; private MiscSimulatorGUI gui; private int GAS_STATION_EXPLOSION_RANG; private int GAS_STATION_Buriedness_Bound; private int GAS_STATION_Buriedness_MIN; private int GAS_STATION_Damage_Bound; private int GAS_STATION_Damage_MIN; private Set<EntityID> notExplosedGasStations; private Map<EntityID, Deque<EntityID>> waitingList; private Map<EntityID, Deque<EntityID>> beds; @Override public JComponent getGUIComponent() { if ( gui == null ) { gui = new MiscSimulatorGUI(); } return gui; } @Override public String getGUIComponentName() { return "Misc simulator"; } @Override protected void postConnect() { super.postConnect(); notExplosedGasStations = new HashSet<>(); waitingList = new HashMap<EntityID, Deque<EntityID>>(); beds = new HashMap<EntityID, Deque<EntityID>>(); parameters = new MiscParameters( config ); GAS_STATION_EXPLOSION_RANG = config .getIntValue( "ignition.gas_station.explosion.range", 0 ); GAS_STATION_Buriedness_Bound = config .getIntValue( "misc.gas_station.Buriedness.bound", 30 ); GAS_STATION_Buriedness_MIN = config .getIntValue( "misc.gas_station.Buriedness.min", 0 ); GAS_STATION_Damage_Bound = config .getIntValue( "misc.gas_station.Damage.bound", 50 ); GAS_STATION_Damage_MIN = config.getIntValue( "misc.gas_station.Damage.min", 15 ); humans = new HashMap<EntityID, HumanAttributes>(); newlyBrokenBuildings = new HashSet<EntityID>(); Logger.info( "MiscSimulator connected. World has " + model.getAllEntities().size() + " entities." ); BuildingChangeListener buildingListener = new BuildingChangeListener(); // HumanChangeListener humanListener = new HumanChangeListener(); for ( Entity et : model.getAllEntities() ) { if ( et instanceof GasStation ) { notExplosedGasStations.add( et.getID() ); } if ( et instanceof Refuge ) { Deque<EntityID> wlist = new LinkedList<EntityID>(); waitingList.put( et.getID(), wlist ); Deque<EntityID> blist = new LinkedList<EntityID>(); beds.put( et.getID(), blist ); } if ( et instanceof Building ) { et.addEntityListener( buildingListener ); } else if ( et instanceof Human ) { // et.addEntityListener(humanListener); Human human = (Human) et; HumanAttributes ha = new HumanAttributes( human, config ); humans.put( ha.getID(), ha ); } } } @Override protected void processCommands( KSCommands c, ChangeSet changes ) { long start = System.currentTimeMillis(); int time = c.getTime(); Logger.info( "Timestep " + time ); for ( Command com : c.getCommands() ) { if ( checkValidity( com ) ) { if ( com instanceof AKRescue ) { Human human = (Human) ( model .getEntity( ( (AKRescue) com ).getTarget() ) ); handleRescue( human, changes ); } /* * For the implementation of Refuge Bed Capacity **/ if ( com instanceof AKUnload ) { handleUnload( com, changes ); } if ( com instanceof AKLoad ) { handleLoad( (AKLoad)com, changes ); } } else { Logger.debug( "Ignoring " + com ); } } updateRefuges(); processBrokenBuildings( changes ); //processBurningBuildings( changes ); //processExplodedGasStations( changes ); updateDamage( changes ); updateChangeSet( changes ); // Clean up newlyBrokenBuildings.clear(); writeDebugOutput( c.getTime() ); if ( gui != null ) { gui.refresh( humans.values() ); } long end = System.currentTimeMillis(); Logger.info( "Timestep " + time + " took " + ( end - start ) + " ms" ); } private void processExplodedGasStations( ChangeSet changes ) { Logger.info( "processExplodedGasStations for " + notExplosedGasStations ); for ( Iterator<EntityID> iterator = notExplosedGasStations .iterator(); iterator.hasNext(); ) { GasStation gasStation = (GasStation) model.getEntity( iterator.next() ); if ( gasStation.isFierynessDefined() && gasStation.getFieryness() == 1 ) { for ( HumanAttributes hA : humans.values() ) { Human human = hA.getHuman(); if ( !human.isXDefined() || !human.isYDefined() ) continue; if ( GeometryTools2D.getDistance( new Point2D( human.getX(), human.getY() ), new Point2D( gasStation.getX(), gasStation.getY() ) ) < GAS_STATION_EXPLOSION_RANG ) { Logger.info( human + " getting damage from explosion..." + human ); int oldBuriedness = human.isBuriednessDefined() ? human.getBuriedness() : 0; human.setBuriedness( oldBuriedness + hA.getRandom().nextInt( GAS_STATION_Buriedness_Bound ) + GAS_STATION_Buriedness_MIN ); changes.addChange( human, human.getBuriednessProperty() ); // Check for injury from being exploded int damage = hA.getRandom().nextInt( GAS_STATION_Damage_Bound ) + GAS_STATION_Damage_MIN; if ( damage != 0 ) { hA.addCollapseDamage( damage ); } } } iterator.remove(); } } } private void processBrokenBuildings( ChangeSet changes ) { for ( HumanAttributes hA : humans.values() ) { Human human = hA.getHuman(); EntityID positionID = human.getPosition(); if ( !newlyBrokenBuildings.contains( positionID ) ) { continue; } // Human is in a newly collapsed building // Check for buriedness Logger.trace( "Checking if human should be buried in broken building" ); Building b = (Building) human.getPosition( model ); if ( parameters.shouldBuryAgent( b, hA ) ) { int buriedness = parameters.getBuriedness( b ) - oldBrokenBuildingsBuriedness.get( b.getID() ); if ( buriedness != 0 ) { int oldBuriedness = human.isBuriednessDefined() ? human.getBuriedness() : 0; human.setBuriedness( oldBuriedness + buriedness ); changes.addChange( human, human.getBuriednessProperty() ); // Check for injury from being buried int damage = parameters.getBuryDamage( b, hA ); if ( damage != 0 ) { hA.addBuriednessDamage( damage ); } } } // Now check for injury from the collapse int damage = parameters.getCollapseDamage( b, hA ); if ( damage != 0 ) { hA.addCollapseDamage( damage ); } } } private void processBurningBuildings( ChangeSet changes ) { for ( HumanAttributes hA : humans.values() ) { Human human = hA.getHuman(); Entity position = human.getPosition( model ); if ( position instanceof Building && ( (Building) position ).isOnFire() ) { // Human is in a burning building int damage = parameters.getFireDamage( (Building) position, hA ); if ( damage != 0 ) { hA.addFireDamage( damage ); } } } } private void writeDebugOutput( int time ) { StringBuilder builder = new StringBuilder(); Formatter format = new Formatter( builder ); format.format( "Agents damaged or buried at timestep %1d%n", time ); format.format( " ID | HP | Damage | Bury | Collapse | Fire | Buriedness%n" ); for ( HumanAttributes ha : humans.values() ) { Human h = ha.getHuman(); int hp = h.isHPDefined() ? h.getHP() : 0; int damage = ha.getTotalDamage(); int buriedness = h.isBuriednessDefined() ? h.getBuriedness() : 0; boolean isAlive = hp > 0; boolean hasDamage = damage > 0; boolean isBuried = buriedness > 0; if ( ( hasDamage || isBuried ) && isAlive ) { format.format( "%1$9d | %2$6d | %3$6d | %4$8.3f | %5$8.3f | %6$8.3f | %7$6d%n", ha.getID().getValue(), hp, damage, ha.getBuriednessDamage(), ha.getCollapseDamage(), ha.getFireDamage(), buriedness ); } } format.close(); Logger.debug( builder.toString() ); } private void updateDamage( ChangeSet changes ) { for ( HumanAttributes ha : humans.values() ) { Human h = ha.getHuman(); int oldDamage = ha.getTotalDamage(); if ( h.isPositionDefined() && !( h.getPosition( model ) instanceof Refuge ) ) { updateDamage( ha ); int hp = h.isHPDefined() ? h.getHP() : 0; int damage = ha.getTotalDamage(); h.setDamage( damage ); changes.addChange( ha.getHuman(), ha.getHuman().getDamageProperty() ); // Update HP boolean isAlive = hp > 0; boolean hasDamage = damage > 0; if ( isAlive && hasDamage ) { int newHP = Math.max( 0, hp - damage ); h.setHP( newHP ); changes.addChange( ha.getHuman(), ha.getHuman().getHPProperty() ); } } /* * For the implementation of Refuge Bed Capacity Damage increases and HP * decreases while victim is in waiting list in Refuge While victim is on * the bed, Damage is reducing but HP is fix human will not die while on * the bed but it takes time to get damage to 0 */ else if ( h.isPositionDefined() && ( h.getPosition( model ) instanceof Refuge ) && h.isHPDefined() && h.getHP() > 0 ) { if (h instanceof FireBrigade || h instanceof AmbulanceTeam || h instanceof PoliceForce) { ha.clearDamage(); h.setDamage(0); changes.addChange(ha.getHuman(), ha.getHuman().getDamageProperty()); continue; } if ( waitingList.get( h.getPosition() ).size() > 0 && waitingList.get( h.getPosition() ).contains( h.getID() ) ) { updateDamage( ha ); int hp = h.isHPDefined() ? h.getHP() : 0; int damage = ha.getTotalDamage(); h.setDamage( damage ); changes.addChange( ha.getHuman(), ha.getHuman().getDamageProperty() ); // Update HP boolean isAlive = hp > 0; boolean hasDamage = damage > 0; if ( isAlive && hasDamage ) { int newHP = Math.max( 0, hp - damage ); h.setHP( newHP ); changes.addChange( ha.getHuman(), ha.getHuman().getHPProperty() ); } } else if ( beds.get( h.getPosition() ).size() > 0 && beds.get( h.getPosition() ).contains( h.getID() ) ) { updateDamageInRefuge( ha ); h.setDamage( ha.getTotalDamage() ); changes.addChange( ha.getHuman(), ha.getHuman().getDamageProperty() ); if ( oldDamage > 0 && h.getDamage() <= 0 ) { if (beds.get( h.getPosition() ).remove(h.getID())) { ((Refuge) h.getPosition(model)).decreaseOccupiedBeds(); } if ( waitingList.get( h.getPosition() ).size() > 0 ) { beds.get( h.getPosition() ).add( waitingList.get( h.getPosition() ).remove() ); ((Refuge) h.getPosition(model)).increaseOccupiedBeds(); } } } } } } private void updateDamage( HumanAttributes ha ) { Human h = ha.getHuman(); if ( h.getHP() <= 0 ) { return; // Agent is already dead. } ha.progressDamage(); } /* * For the implementation of Refuge Bed Capacity **/ private void updateDamageInRefuge( HumanAttributes ha ) { Human h = ha.getHuman(); if ( h.getHP() <= 0 ) { return; // Agent is already dead. } ha.progressDamageInRefuge(); } private boolean checkValidity( Command command ) { Entity e = model.getEntity( command.getAgentID() ); if ( e == null ) { Logger.warn( "Received a " + command.getURN() + " command from an unknown agent: " + command.getAgentID() ); return false; } if ( command instanceof AKRescue ) { return checkRescue( (AKRescue) command, e ); } if ( command instanceof AKUnload ) return checkUnload( (AKUnload) command, e ); if ( command instanceof AKLoad ) return checkLoad( (AKLoad) command, e ); return false; } private boolean checkRescue( AKRescue rescue, Entity agent ) { EntityID targetID = rescue.getTarget(); Entity target = model.getEntity( targetID ); // || agent instanceof AmbulanceTeam if ( !( agent instanceof FireBrigade ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " who is of type " + agent.getURN() ); return false; } if ( target == null ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-existent target " + targetID ); return false; } if ( !( target instanceof Human ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-human target: " + targetID + " is of type " + target.getURN() ); return false; } Human h = (Human) target; if ( !h.isBuriednessDefined() || h.getBuriedness() == 0 ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-buried target " + targetID ); return false; } // || agent instanceof AmbulanceTeam if ( agent instanceof FireBrigade ) { Human ag = (Human) agent; if ( ag.isHPDefined() && ag.getHP() <= 0 ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + ": agent is dead" ); return false; } if ( ag.isBuriednessDefined() && ag.getBuriedness() > 0 ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + ": agent is buried" ); return false; } if ( !h.isPositionDefined() || !ag.isPositionDefined() || !h.getPosition().equals( ag.getPosition() ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-adjacent target " + targetID ); return false; } if ( h.getID().equals( ag.getID() ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + ": tried to rescue self" ); return false; } } return true; } private boolean checkUnload( AKUnload unload, Entity agent ) { if ( !( agent instanceof AmbulanceTeam ) ) { Logger.warn( "Rejecting unload command from agent " + agent.getID() + " who is of type " + agent.getURN() ); return false; } AmbulanceTeam at = (AmbulanceTeam) agent; if ( at.isHPDefined() && at.getHP() <= 0 ) { Logger.warn( "Rejecting Unload command from agent " + agent.getID() + ": agent is dead" ); return false; } return true; } private boolean checkLoad( AKLoad unload, Entity agent ) { if ( !( agent instanceof AmbulanceTeam ) ) { Logger.warn( "Rejecting load command from agent " + agent.getID() + " who is of type " + agent.getURN() ); return false; } AmbulanceTeam at = (AmbulanceTeam) agent; if ( at.isHPDefined() && at.getHP() <= 0 ) { Logger.warn( "Rejecting Unload command from agent " + agent.getID() + ": agent is dead" ); return false; } return true; } private void handleRescue( Human target, ChangeSet changes ) { target.setBuriedness( Math.max( 0, target.getBuriedness() - 1 ) ); changes.addChange( target, target.getBuriednessProperty() ); } /* * For the implementation of Refuge Bed Capacity **/ private void handleUnload( Command command, ChangeSet changes ) { EntityID agentID = command.getAgentID(); Entity agent = model.getEntity( agentID ); Civilian target = null; for ( Entity e : model.getEntitiesOfType( StandardEntityURN.CIVILIAN ) ) { Civilian civ = (Civilian) e; if ( civ.isPositionDefined() && agentID.equals( civ.getPosition() ) ) { target = civ; break; } } if ( target != null ) { Entity AgentPosition = ( (Human) agent ).getPosition( model ); if ( AgentPosition != null && AgentPosition instanceof Refuge ) { addVictimToWaitingList( AgentPosition, target ); } } } private void handleLoad( AKLoad load, ChangeSet changes ) { EntityID agentID = load.getAgentID(); Entity agent = model.getEntity(agentID); EntityID targetID = load.getTarget(); Entity target = model.getEntity(targetID); //--------------- if (agent == null) { Logger.warn("Rejecting load command from agent " + agentID + ": agent does not exist"); return; } if (!(agent instanceof AmbulanceTeam)) { Logger.warn("Rejecting load command from agent " + agentID + ": agent type is " + agent.getURN()); return; } if (target == null) { Logger.warn("Rejecting load command from agent " + agentID + ": target does not exist " + targetID); return; } AmbulanceTeam at = (AmbulanceTeam) agent; Civilian h = (Civilian) target; if (at.isHPDefined() && at.getHP() <= 0) { Logger.warn("Rejecting load command from agent " + agentID + ": agent is dead"); return; } if (!h.isPositionDefined() || !at.isPositionDefined() || !h.getPosition().equals(at.getPosition())) { Logger.warn("Rejecting load command from agent " + agentID + ": target is non-adjacent " + targetID); return; } if (h.getID().equals(at.getID())) { Logger.warn("Rejecting load command from agent " + agentID + ": tried to load self"); return; } // Is there something already loaded? for (Entity e : model.getEntitiesOfType(StandardEntityURN.CIVILIAN)) { Civilian c = (Civilian) e; if (c.isPositionDefined() && agentID.equals(c.getPosition())) { Logger.warn("Rejecting load command from agent " + agentID + ": agent already has civilian " + c.getID() + " loaded"); return; } } //-------------------- Entity AgentPosition = ((Human) agent).getPosition(model); if (AgentPosition != null && AgentPosition instanceof Refuge) { if (waitingList.get(h.getPosition()).size() > 0 && waitingList.get(h.getPosition()).contains(h.getID())) { waitingList.get(h.getPosition()).remove(h.getID()); } if (beds.get(h.getPosition()).size() > 0 && beds.get(h.getPosition()).contains(h.getID())) { beds.get(h.getPosition()).remove(h.getID()); ((Refuge) h.getPosition(model)).decreaseOccupiedBeds(); if (waitingList.get(h.getPosition()).size() > 0) { beds.get(h.getPosition()).add(waitingList.get(h.getPosition()).remove()); ((Refuge) h.getPosition(model)).increaseOccupiedBeds(); } } } } private class BuildingChangeListener implements EntityListener { @Override public void propertyChanged( Entity e, Property p, Object oldValue, Object newValue ) { if ( !( e instanceof Building ) ) { return; // we want to only look at buildings } if ( p.getURN().equals( StandardPropertyURN.BROKENNESS.toString() ) ) checkBrokenness( e, oldValue, newValue ); } private void checkBrokenness( Entity e, Object oldValue, Object newValue ) { double old = oldValue == null ? 0 : (Integer) oldValue; double next = newValue == null ? 0 : (Integer) newValue; if ( next > old ) { newlyBrokenBuildings.add( e.getID() ); } } } @Override protected void handleUpdate( KSUpdate u ) { for ( StandardEntity entity : model ) { if ( entity instanceof Building ) { oldBrokenBuildingsBuriedness.put( entity.getID(), parameters.getBuriedness( (Building) entity ) ); } } super.handleUpdate( u ); } private void addVictimToWaitingList( Entity refuge, Civilian victim ) { if ( victim.getDamage() > 0 ) waitingList.get( refuge.getID() ).add( victim.getID() ); } /* * For the implementation of Refuge Bed Capacity **/ private void updateRefuges() { for ( Map.Entry<EntityID, Deque<EntityID>> e : waitingList.entrySet() ) { ArrayList<EntityID> tempList = new ArrayList<EntityID>(); for ( EntityID civ : (Deque<EntityID>) e.getValue() ) { if ( model.getEntity( civ ) instanceof Human ) { if ( ( (Human) model.getEntity( civ ) ).getDamage() <= 0 ) { tempList.add( civ ); } if ( ( (Human) model.getEntity( civ ) ).getHP() <= 0 ) { tempList.add( civ ); } } } if ( tempList.size() > 0 ) { ( (Deque<EntityID>) e.getValue() ).removeAll( tempList ); } } for ( Map.Entry<EntityID, Deque<EntityID>> e : beds.entrySet() ) { ArrayList<EntityID> tempList = new ArrayList<EntityID>(); for ( EntityID civ : (Deque<EntityID>) e.getValue() ) { if ( model.getEntity( civ ) instanceof Human ) { if ( ( (Human) model.getEntity( civ ) ).getDamage() <= 0 ) { tempList.add( civ ); } if ( ( (Human) model.getEntity( civ ) ).getHP() <= 0 ) { tempList.add( civ ); } } } if ( tempList.size() > 0 ) { //( (Deque<EntityID>) e.getValue() ).removeAll( tempList ); for (EntityID id : tempList) { if (( (Deque<EntityID>) e.getValue() ).remove( id )) { ((Refuge) model.getEntity(e.getKey())).decreaseOccupiedBeds(); Logger.warn("decreaseOccupiedBeds in update Refuge"); } } } } for ( StandardEntity e : model .getEntitiesOfType( StandardEntityURN.REFUGE ) ) { if ( e instanceof Refuge ) { //Logger.warn("Refuge = " + e.getID() + " bed cap = " + ( (Refuge) e ).getOccupiedBeds() + " beds size = " + beds.get(e.getID()).size() + " wait size = " + waitingList.get(e.getID()).size()); while ( ( (Refuge) e ).getOccupiedBeds() < ( (Refuge) e ) .getBedCapacity() ) { if ( waitingList.get( e.getID() ).size() > 0 ) { beds.get( e.getID() ).add( waitingList.get( e.getID() ).remove() ); ( (Refuge) e ).increaseOccupiedBeds(); } else break; } } } } /* * For the implementation of Refuge Bed Capacity **/ private void updateChangeSet( ChangeSet changes ) { for ( StandardEntity e : model .getEntitiesOfType( StandardEntityURN.REFUGE ) ) if ( e instanceof Refuge ) { int size = waitingList.get( e.getID() ).size(); ( (Refuge) e ).setWaitingListSize( size ); changes.addChange( (Refuge) e, ( (Refuge) e ).getOccupiedBedsProperty() ); changes.addChange( (Refuge) e, ( (Refuge) e ).getWaitingListSizeProperty() ); } } private void removeWaitingList( EntityID ref ) { if ( waitingList.get( ref ).size() > 0 ) { waitingList.get( ref ).remove(); Logger.warn( "removing from waiting list..." ); } } }
UTF-8
Java
24,948
java
MiscSimulator.java
Java
[ { "context": "tation of the legacy misc simulator.\n *\n * @author Maitreyi Nanjanath\n * @author Cameron Skinner\n *\n * Implemen", "end": 1092, "score": 0.9998829960823059, "start": 1074, "tag": "NAME", "value": "Maitreyi Nanjanath" }, { "context": "lator.\n *\n * @author Maitreyi Nanjanath\n * @author Cameron Skinner\n *\n * Implementation of Refuge Bed Capaci", "end": 1119, "score": 0.9998788833618164, "start": 1104, "tag": "NAME", "value": "Cameron Skinner" }, { "context": " Implementation of Refuge Bed Capacity\n * @author Farshid Faraji\n */\npublic class MiscSimulator extends StandardSi", "end": 1197, "score": 0.9998792409896851, "start": 1183, "tag": "NAME", "value": "Farshid Faraji" } ]
null
[]
package misc; import java.util.ArrayList; import java.util.Deque; import java.util.Formatter; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import javax.swing.JComponent; import rescuecore2.GUIComponent; import rescuecore2.messages.Command; import rescuecore2.messages.control.KSCommands; import rescuecore2.messages.control.KSUpdate; import rescuecore2.misc.geometry.GeometryTools2D; import rescuecore2.misc.geometry.Point2D; import rescuecore2.standard.components.StandardSimulator; import rescuecore2.standard.entities.*; import rescuecore2.standard.messages.AKRescue; import rescuecore2.standard.messages.AKUnload; import rescuecore2.standard.messages.AKLoad; import rescuecore2.worldmodel.Entity; import rescuecore2.worldmodel.EntityID; import rescuecore2.worldmodel.EntityListener; import rescuecore2.worldmodel.Property; import rescuecore2.worldmodel.ChangeSet; import rescuecore2.log.Logger; /** * Implementation of the legacy misc simulator. * * @author <NAME> * @author <NAME> * * Implementation of Refuge Bed Capacity * @author <NAME> */ public class MiscSimulator extends StandardSimulator implements GUIComponent { private Map<EntityID, HumanAttributes> humans; private Set<EntityID> newlyBrokenBuildings; private Map<EntityID, Integer> oldBrokenBuildingsBuriedness = new HashMap<>(); private MiscParameters parameters; private MiscSimulatorGUI gui; private int GAS_STATION_EXPLOSION_RANG; private int GAS_STATION_Buriedness_Bound; private int GAS_STATION_Buriedness_MIN; private int GAS_STATION_Damage_Bound; private int GAS_STATION_Damage_MIN; private Set<EntityID> notExplosedGasStations; private Map<EntityID, Deque<EntityID>> waitingList; private Map<EntityID, Deque<EntityID>> beds; @Override public JComponent getGUIComponent() { if ( gui == null ) { gui = new MiscSimulatorGUI(); } return gui; } @Override public String getGUIComponentName() { return "Misc simulator"; } @Override protected void postConnect() { super.postConnect(); notExplosedGasStations = new HashSet<>(); waitingList = new HashMap<EntityID, Deque<EntityID>>(); beds = new HashMap<EntityID, Deque<EntityID>>(); parameters = new MiscParameters( config ); GAS_STATION_EXPLOSION_RANG = config .getIntValue( "ignition.gas_station.explosion.range", 0 ); GAS_STATION_Buriedness_Bound = config .getIntValue( "misc.gas_station.Buriedness.bound", 30 ); GAS_STATION_Buriedness_MIN = config .getIntValue( "misc.gas_station.Buriedness.min", 0 ); GAS_STATION_Damage_Bound = config .getIntValue( "misc.gas_station.Damage.bound", 50 ); GAS_STATION_Damage_MIN = config.getIntValue( "misc.gas_station.Damage.min", 15 ); humans = new HashMap<EntityID, HumanAttributes>(); newlyBrokenBuildings = new HashSet<EntityID>(); Logger.info( "MiscSimulator connected. World has " + model.getAllEntities().size() + " entities." ); BuildingChangeListener buildingListener = new BuildingChangeListener(); // HumanChangeListener humanListener = new HumanChangeListener(); for ( Entity et : model.getAllEntities() ) { if ( et instanceof GasStation ) { notExplosedGasStations.add( et.getID() ); } if ( et instanceof Refuge ) { Deque<EntityID> wlist = new LinkedList<EntityID>(); waitingList.put( et.getID(), wlist ); Deque<EntityID> blist = new LinkedList<EntityID>(); beds.put( et.getID(), blist ); } if ( et instanceof Building ) { et.addEntityListener( buildingListener ); } else if ( et instanceof Human ) { // et.addEntityListener(humanListener); Human human = (Human) et; HumanAttributes ha = new HumanAttributes( human, config ); humans.put( ha.getID(), ha ); } } } @Override protected void processCommands( KSCommands c, ChangeSet changes ) { long start = System.currentTimeMillis(); int time = c.getTime(); Logger.info( "Timestep " + time ); for ( Command com : c.getCommands() ) { if ( checkValidity( com ) ) { if ( com instanceof AKRescue ) { Human human = (Human) ( model .getEntity( ( (AKRescue) com ).getTarget() ) ); handleRescue( human, changes ); } /* * For the implementation of Refuge Bed Capacity **/ if ( com instanceof AKUnload ) { handleUnload( com, changes ); } if ( com instanceof AKLoad ) { handleLoad( (AKLoad)com, changes ); } } else { Logger.debug( "Ignoring " + com ); } } updateRefuges(); processBrokenBuildings( changes ); //processBurningBuildings( changes ); //processExplodedGasStations( changes ); updateDamage( changes ); updateChangeSet( changes ); // Clean up newlyBrokenBuildings.clear(); writeDebugOutput( c.getTime() ); if ( gui != null ) { gui.refresh( humans.values() ); } long end = System.currentTimeMillis(); Logger.info( "Timestep " + time + " took " + ( end - start ) + " ms" ); } private void processExplodedGasStations( ChangeSet changes ) { Logger.info( "processExplodedGasStations for " + notExplosedGasStations ); for ( Iterator<EntityID> iterator = notExplosedGasStations .iterator(); iterator.hasNext(); ) { GasStation gasStation = (GasStation) model.getEntity( iterator.next() ); if ( gasStation.isFierynessDefined() && gasStation.getFieryness() == 1 ) { for ( HumanAttributes hA : humans.values() ) { Human human = hA.getHuman(); if ( !human.isXDefined() || !human.isYDefined() ) continue; if ( GeometryTools2D.getDistance( new Point2D( human.getX(), human.getY() ), new Point2D( gasStation.getX(), gasStation.getY() ) ) < GAS_STATION_EXPLOSION_RANG ) { Logger.info( human + " getting damage from explosion..." + human ); int oldBuriedness = human.isBuriednessDefined() ? human.getBuriedness() : 0; human.setBuriedness( oldBuriedness + hA.getRandom().nextInt( GAS_STATION_Buriedness_Bound ) + GAS_STATION_Buriedness_MIN ); changes.addChange( human, human.getBuriednessProperty() ); // Check for injury from being exploded int damage = hA.getRandom().nextInt( GAS_STATION_Damage_Bound ) + GAS_STATION_Damage_MIN; if ( damage != 0 ) { hA.addCollapseDamage( damage ); } } } iterator.remove(); } } } private void processBrokenBuildings( ChangeSet changes ) { for ( HumanAttributes hA : humans.values() ) { Human human = hA.getHuman(); EntityID positionID = human.getPosition(); if ( !newlyBrokenBuildings.contains( positionID ) ) { continue; } // Human is in a newly collapsed building // Check for buriedness Logger.trace( "Checking if human should be buried in broken building" ); Building b = (Building) human.getPosition( model ); if ( parameters.shouldBuryAgent( b, hA ) ) { int buriedness = parameters.getBuriedness( b ) - oldBrokenBuildingsBuriedness.get( b.getID() ); if ( buriedness != 0 ) { int oldBuriedness = human.isBuriednessDefined() ? human.getBuriedness() : 0; human.setBuriedness( oldBuriedness + buriedness ); changes.addChange( human, human.getBuriednessProperty() ); // Check for injury from being buried int damage = parameters.getBuryDamage( b, hA ); if ( damage != 0 ) { hA.addBuriednessDamage( damage ); } } } // Now check for injury from the collapse int damage = parameters.getCollapseDamage( b, hA ); if ( damage != 0 ) { hA.addCollapseDamage( damage ); } } } private void processBurningBuildings( ChangeSet changes ) { for ( HumanAttributes hA : humans.values() ) { Human human = hA.getHuman(); Entity position = human.getPosition( model ); if ( position instanceof Building && ( (Building) position ).isOnFire() ) { // Human is in a burning building int damage = parameters.getFireDamage( (Building) position, hA ); if ( damage != 0 ) { hA.addFireDamage( damage ); } } } } private void writeDebugOutput( int time ) { StringBuilder builder = new StringBuilder(); Formatter format = new Formatter( builder ); format.format( "Agents damaged or buried at timestep %1d%n", time ); format.format( " ID | HP | Damage | Bury | Collapse | Fire | Buriedness%n" ); for ( HumanAttributes ha : humans.values() ) { Human h = ha.getHuman(); int hp = h.isHPDefined() ? h.getHP() : 0; int damage = ha.getTotalDamage(); int buriedness = h.isBuriednessDefined() ? h.getBuriedness() : 0; boolean isAlive = hp > 0; boolean hasDamage = damage > 0; boolean isBuried = buriedness > 0; if ( ( hasDamage || isBuried ) && isAlive ) { format.format( "%1$9d | %2$6d | %3$6d | %4$8.3f | %5$8.3f | %6$8.3f | %7$6d%n", ha.getID().getValue(), hp, damage, ha.getBuriednessDamage(), ha.getCollapseDamage(), ha.getFireDamage(), buriedness ); } } format.close(); Logger.debug( builder.toString() ); } private void updateDamage( ChangeSet changes ) { for ( HumanAttributes ha : humans.values() ) { Human h = ha.getHuman(); int oldDamage = ha.getTotalDamage(); if ( h.isPositionDefined() && !( h.getPosition( model ) instanceof Refuge ) ) { updateDamage( ha ); int hp = h.isHPDefined() ? h.getHP() : 0; int damage = ha.getTotalDamage(); h.setDamage( damage ); changes.addChange( ha.getHuman(), ha.getHuman().getDamageProperty() ); // Update HP boolean isAlive = hp > 0; boolean hasDamage = damage > 0; if ( isAlive && hasDamage ) { int newHP = Math.max( 0, hp - damage ); h.setHP( newHP ); changes.addChange( ha.getHuman(), ha.getHuman().getHPProperty() ); } } /* * For the implementation of Refuge Bed Capacity Damage increases and HP * decreases while victim is in waiting list in Refuge While victim is on * the bed, Damage is reducing but HP is fix human will not die while on * the bed but it takes time to get damage to 0 */ else if ( h.isPositionDefined() && ( h.getPosition( model ) instanceof Refuge ) && h.isHPDefined() && h.getHP() > 0 ) { if (h instanceof FireBrigade || h instanceof AmbulanceTeam || h instanceof PoliceForce) { ha.clearDamage(); h.setDamage(0); changes.addChange(ha.getHuman(), ha.getHuman().getDamageProperty()); continue; } if ( waitingList.get( h.getPosition() ).size() > 0 && waitingList.get( h.getPosition() ).contains( h.getID() ) ) { updateDamage( ha ); int hp = h.isHPDefined() ? h.getHP() : 0; int damage = ha.getTotalDamage(); h.setDamage( damage ); changes.addChange( ha.getHuman(), ha.getHuman().getDamageProperty() ); // Update HP boolean isAlive = hp > 0; boolean hasDamage = damage > 0; if ( isAlive && hasDamage ) { int newHP = Math.max( 0, hp - damage ); h.setHP( newHP ); changes.addChange( ha.getHuman(), ha.getHuman().getHPProperty() ); } } else if ( beds.get( h.getPosition() ).size() > 0 && beds.get( h.getPosition() ).contains( h.getID() ) ) { updateDamageInRefuge( ha ); h.setDamage( ha.getTotalDamage() ); changes.addChange( ha.getHuman(), ha.getHuman().getDamageProperty() ); if ( oldDamage > 0 && h.getDamage() <= 0 ) { if (beds.get( h.getPosition() ).remove(h.getID())) { ((Refuge) h.getPosition(model)).decreaseOccupiedBeds(); } if ( waitingList.get( h.getPosition() ).size() > 0 ) { beds.get( h.getPosition() ).add( waitingList.get( h.getPosition() ).remove() ); ((Refuge) h.getPosition(model)).increaseOccupiedBeds(); } } } } } } private void updateDamage( HumanAttributes ha ) { Human h = ha.getHuman(); if ( h.getHP() <= 0 ) { return; // Agent is already dead. } ha.progressDamage(); } /* * For the implementation of Refuge Bed Capacity **/ private void updateDamageInRefuge( HumanAttributes ha ) { Human h = ha.getHuman(); if ( h.getHP() <= 0 ) { return; // Agent is already dead. } ha.progressDamageInRefuge(); } private boolean checkValidity( Command command ) { Entity e = model.getEntity( command.getAgentID() ); if ( e == null ) { Logger.warn( "Received a " + command.getURN() + " command from an unknown agent: " + command.getAgentID() ); return false; } if ( command instanceof AKRescue ) { return checkRescue( (AKRescue) command, e ); } if ( command instanceof AKUnload ) return checkUnload( (AKUnload) command, e ); if ( command instanceof AKLoad ) return checkLoad( (AKLoad) command, e ); return false; } private boolean checkRescue( AKRescue rescue, Entity agent ) { EntityID targetID = rescue.getTarget(); Entity target = model.getEntity( targetID ); // || agent instanceof AmbulanceTeam if ( !( agent instanceof FireBrigade ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " who is of type " + agent.getURN() ); return false; } if ( target == null ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-existent target " + targetID ); return false; } if ( !( target instanceof Human ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-human target: " + targetID + " is of type " + target.getURN() ); return false; } Human h = (Human) target; if ( !h.isBuriednessDefined() || h.getBuriedness() == 0 ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-buried target " + targetID ); return false; } // || agent instanceof AmbulanceTeam if ( agent instanceof FireBrigade ) { Human ag = (Human) agent; if ( ag.isHPDefined() && ag.getHP() <= 0 ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + ": agent is dead" ); return false; } if ( ag.isBuriednessDefined() && ag.getBuriedness() > 0 ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + ": agent is buried" ); return false; } if ( !h.isPositionDefined() || !ag.isPositionDefined() || !h.getPosition().equals( ag.getPosition() ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + " for a non-adjacent target " + targetID ); return false; } if ( h.getID().equals( ag.getID() ) ) { Logger.warn( "Rejecting rescue command from agent " + agent.getID() + ": tried to rescue self" ); return false; } } return true; } private boolean checkUnload( AKUnload unload, Entity agent ) { if ( !( agent instanceof AmbulanceTeam ) ) { Logger.warn( "Rejecting unload command from agent " + agent.getID() + " who is of type " + agent.getURN() ); return false; } AmbulanceTeam at = (AmbulanceTeam) agent; if ( at.isHPDefined() && at.getHP() <= 0 ) { Logger.warn( "Rejecting Unload command from agent " + agent.getID() + ": agent is dead" ); return false; } return true; } private boolean checkLoad( AKLoad unload, Entity agent ) { if ( !( agent instanceof AmbulanceTeam ) ) { Logger.warn( "Rejecting load command from agent " + agent.getID() + " who is of type " + agent.getURN() ); return false; } AmbulanceTeam at = (AmbulanceTeam) agent; if ( at.isHPDefined() && at.getHP() <= 0 ) { Logger.warn( "Rejecting Unload command from agent " + agent.getID() + ": agent is dead" ); return false; } return true; } private void handleRescue( Human target, ChangeSet changes ) { target.setBuriedness( Math.max( 0, target.getBuriedness() - 1 ) ); changes.addChange( target, target.getBuriednessProperty() ); } /* * For the implementation of Refuge Bed Capacity **/ private void handleUnload( Command command, ChangeSet changes ) { EntityID agentID = command.getAgentID(); Entity agent = model.getEntity( agentID ); Civilian target = null; for ( Entity e : model.getEntitiesOfType( StandardEntityURN.CIVILIAN ) ) { Civilian civ = (Civilian) e; if ( civ.isPositionDefined() && agentID.equals( civ.getPosition() ) ) { target = civ; break; } } if ( target != null ) { Entity AgentPosition = ( (Human) agent ).getPosition( model ); if ( AgentPosition != null && AgentPosition instanceof Refuge ) { addVictimToWaitingList( AgentPosition, target ); } } } private void handleLoad( AKLoad load, ChangeSet changes ) { EntityID agentID = load.getAgentID(); Entity agent = model.getEntity(agentID); EntityID targetID = load.getTarget(); Entity target = model.getEntity(targetID); //--------------- if (agent == null) { Logger.warn("Rejecting load command from agent " + agentID + ": agent does not exist"); return; } if (!(agent instanceof AmbulanceTeam)) { Logger.warn("Rejecting load command from agent " + agentID + ": agent type is " + agent.getURN()); return; } if (target == null) { Logger.warn("Rejecting load command from agent " + agentID + ": target does not exist " + targetID); return; } AmbulanceTeam at = (AmbulanceTeam) agent; Civilian h = (Civilian) target; if (at.isHPDefined() && at.getHP() <= 0) { Logger.warn("Rejecting load command from agent " + agentID + ": agent is dead"); return; } if (!h.isPositionDefined() || !at.isPositionDefined() || !h.getPosition().equals(at.getPosition())) { Logger.warn("Rejecting load command from agent " + agentID + ": target is non-adjacent " + targetID); return; } if (h.getID().equals(at.getID())) { Logger.warn("Rejecting load command from agent " + agentID + ": tried to load self"); return; } // Is there something already loaded? for (Entity e : model.getEntitiesOfType(StandardEntityURN.CIVILIAN)) { Civilian c = (Civilian) e; if (c.isPositionDefined() && agentID.equals(c.getPosition())) { Logger.warn("Rejecting load command from agent " + agentID + ": agent already has civilian " + c.getID() + " loaded"); return; } } //-------------------- Entity AgentPosition = ((Human) agent).getPosition(model); if (AgentPosition != null && AgentPosition instanceof Refuge) { if (waitingList.get(h.getPosition()).size() > 0 && waitingList.get(h.getPosition()).contains(h.getID())) { waitingList.get(h.getPosition()).remove(h.getID()); } if (beds.get(h.getPosition()).size() > 0 && beds.get(h.getPosition()).contains(h.getID())) { beds.get(h.getPosition()).remove(h.getID()); ((Refuge) h.getPosition(model)).decreaseOccupiedBeds(); if (waitingList.get(h.getPosition()).size() > 0) { beds.get(h.getPosition()).add(waitingList.get(h.getPosition()).remove()); ((Refuge) h.getPosition(model)).increaseOccupiedBeds(); } } } } private class BuildingChangeListener implements EntityListener { @Override public void propertyChanged( Entity e, Property p, Object oldValue, Object newValue ) { if ( !( e instanceof Building ) ) { return; // we want to only look at buildings } if ( p.getURN().equals( StandardPropertyURN.BROKENNESS.toString() ) ) checkBrokenness( e, oldValue, newValue ); } private void checkBrokenness( Entity e, Object oldValue, Object newValue ) { double old = oldValue == null ? 0 : (Integer) oldValue; double next = newValue == null ? 0 : (Integer) newValue; if ( next > old ) { newlyBrokenBuildings.add( e.getID() ); } } } @Override protected void handleUpdate( KSUpdate u ) { for ( StandardEntity entity : model ) { if ( entity instanceof Building ) { oldBrokenBuildingsBuriedness.put( entity.getID(), parameters.getBuriedness( (Building) entity ) ); } } super.handleUpdate( u ); } private void addVictimToWaitingList( Entity refuge, Civilian victim ) { if ( victim.getDamage() > 0 ) waitingList.get( refuge.getID() ).add( victim.getID() ); } /* * For the implementation of Refuge Bed Capacity **/ private void updateRefuges() { for ( Map.Entry<EntityID, Deque<EntityID>> e : waitingList.entrySet() ) { ArrayList<EntityID> tempList = new ArrayList<EntityID>(); for ( EntityID civ : (Deque<EntityID>) e.getValue() ) { if ( model.getEntity( civ ) instanceof Human ) { if ( ( (Human) model.getEntity( civ ) ).getDamage() <= 0 ) { tempList.add( civ ); } if ( ( (Human) model.getEntity( civ ) ).getHP() <= 0 ) { tempList.add( civ ); } } } if ( tempList.size() > 0 ) { ( (Deque<EntityID>) e.getValue() ).removeAll( tempList ); } } for ( Map.Entry<EntityID, Deque<EntityID>> e : beds.entrySet() ) { ArrayList<EntityID> tempList = new ArrayList<EntityID>(); for ( EntityID civ : (Deque<EntityID>) e.getValue() ) { if ( model.getEntity( civ ) instanceof Human ) { if ( ( (Human) model.getEntity( civ ) ).getDamage() <= 0 ) { tempList.add( civ ); } if ( ( (Human) model.getEntity( civ ) ).getHP() <= 0 ) { tempList.add( civ ); } } } if ( tempList.size() > 0 ) { //( (Deque<EntityID>) e.getValue() ).removeAll( tempList ); for (EntityID id : tempList) { if (( (Deque<EntityID>) e.getValue() ).remove( id )) { ((Refuge) model.getEntity(e.getKey())).decreaseOccupiedBeds(); Logger.warn("decreaseOccupiedBeds in update Refuge"); } } } } for ( StandardEntity e : model .getEntitiesOfType( StandardEntityURN.REFUGE ) ) { if ( e instanceof Refuge ) { //Logger.warn("Refuge = " + e.getID() + " bed cap = " + ( (Refuge) e ).getOccupiedBeds() + " beds size = " + beds.get(e.getID()).size() + " wait size = " + waitingList.get(e.getID()).size()); while ( ( (Refuge) e ).getOccupiedBeds() < ( (Refuge) e ) .getBedCapacity() ) { if ( waitingList.get( e.getID() ).size() > 0 ) { beds.get( e.getID() ).add( waitingList.get( e.getID() ).remove() ); ( (Refuge) e ).increaseOccupiedBeds(); } else break; } } } } /* * For the implementation of Refuge Bed Capacity **/ private void updateChangeSet( ChangeSet changes ) { for ( StandardEntity e : model .getEntitiesOfType( StandardEntityURN.REFUGE ) ) if ( e instanceof Refuge ) { int size = waitingList.get( e.getID() ).size(); ( (Refuge) e ).setWaitingListSize( size ); changes.addChange( (Refuge) e, ( (Refuge) e ).getOccupiedBedsProperty() ); changes.addChange( (Refuge) e, ( (Refuge) e ).getWaitingListSizeProperty() ); } } private void removeWaitingList( EntityID ref ) { if ( waitingList.get( ref ).size() > 0 ) { waitingList.get( ref ).remove(); Logger.warn( "removing from waiting list..." ); } } }
24,919
0.59155
0.587502
733
33.036835
26.861475
199
false
false
0
0
0
0
0
0
0.518417
false
false
12
3c92912ebfb371c88728aab5b9933147b5e3c731
27,659,589,405,251
a4095fde44844ba7eb6088016dee70b67fd8fb17
/plugmin-web-spring/src/main/java/org/plugmin/core/config/context/PlugminContextConfiguration.java
85fc5b9cb474eb42da7226e07f538a4255951658
[]
no_license
varunkumarsp/plugmin-aggregator
https://github.com/varunkumarsp/plugmin-aggregator
e05f35eac35a93ac2e3443005d233469e4abc738
b8112a027be2a3f6f1d2bd82764aebebce28f86f
refs/heads/master
2016-08-03T13:59:21.691000
2015-01-09T13:34:33
2015-01-09T13:34:33
28,268,110
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.plugmin.core.config.context; import java.util.List; import javax.persistence.EntityManagerFactory; import javax.servlet.ServletContext; import org.hibernate.SessionFactory; import org.plugmin.core.config.PlugminConfiguration; import org.plugmin.core.config.StandardPlugminConfiguration; import org.plugmin.core.config.context.json.ViewAwareJsonMessageConverter; import org.plugmin.core.view.PlugminSpringTilesInitializer; import org.plugmin.core.view.SeparateContainerTilesView; import org.plugmin.core.web.ApplicationController; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor; import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.context.request.WebRequestInterceptor; import org.springframework.web.context.support.ServletContextResourceLoader; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver; import org.springframework.web.servlet.view.UrlBasedViewResolver; import org.springframework.web.servlet.view.tiles2.SpringBeanPreparerFactory; import org.springframework.web.servlet.view.tiles2.TilesConfigurer; @Configuration @ComponentScan("org.plugmin.core.controller") @Import({ PlugminDaoConfiguration.class, PlugminServiceConfiguration.class, PlugminRemoteConfiguration.class, PlugminRepositoryRestConfiguration.class, PlugminViewConfiguration.class }) @EnableWebMvc public class PlugminContextConfiguration extends WebMvcConfigurerAdapter implements BeanFactoryAware { @Autowired(required = false) private EntityManagerFactory entityManagerFactory; @Autowired(required = false) private SessionFactory sessionFactory; private BeanFactory parentBeanFactory; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addWebRequestInterceptor(openSessionOrEntityMgrInViewInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/styles/**").addResourceLocations("classpath:/META-INF/resources/styles/"); registry.addResourceHandler("/scripts/**").addResourceLocations("classpath:/META-INF/resources/scripts/"); registry.addResourceHandler("/kendo-ui/**").addResourceLocations("classpath:/META-INF/resources/kendo-ui/"); registry.addResourceHandler("/images/**").addResourceLocations("classpath:/META-INF/resources/images/").setCachePeriod(31556926); } @Bean @Autowired public PlugminConfiguration plugminConfiguration(ServletContext servletContext) { return new StandardPlugminConfiguration(servletContext); } @Bean @Autowired public ServletContextResourceLoader servletContextResourceLoader(ServletContext servletContext) { return new ServletContextResourceLoader(servletContext); } @Bean public WebRequestInterceptor openSessionOrEntityMgrInViewInterceptor() { WebRequestInterceptor webRequestInterceptor = null; if(entityManagerFactory != null) { OpenEntityManagerInViewInterceptor openEntityManagerInViewInterceptor = new OpenEntityManagerInViewInterceptor(); openEntityManagerInViewInterceptor.setEntityManagerFactory(entityManagerFactory); webRequestInterceptor = openEntityManagerInViewInterceptor; } else { OpenSessionInViewInterceptor openSessionInViewInterceptor = new OpenSessionInViewInterceptor(); openSessionInViewInterceptor.setSessionFactory(sessionFactory); webRequestInterceptor = openSessionInViewInterceptor; } return webRequestInterceptor; } @Bean public CommonsMultipartResolver multipartResolver() { return new CommonsMultipartResolver(); } @Override public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { ExceptionHandlerExceptionResolver exceptionHandlerResolver = new ExceptionHandlerExceptionResolver(); exceptionHandlerResolver.afterPropertiesSet(); exceptionResolvers.add(exceptionHandlerResolver); } @Override public Validator getValidator() { return validator(); } @Bean public LocalValidatorFactoryBean validator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource()); validator.afterPropertiesSet(); return validator; } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setDefaultEncoding("UTF-8"); messageSource.setCacheSeconds(0); messageSource.setFallbackToSystemLocale(false); return messageSource; } @Bean public ApplicationController applicationController() { return new ApplicationController(); } @Bean public ViewResolver viewResolver() { final UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(SeparateContainerTilesView.class); return viewResolver; } @Bean public TilesConfigurer tilesConfigurer() { final String[] definitions = {"classpath*:META-INF/tiles/**/*.xml"}; final TilesConfigurer configurer = new TilesConfigurer(); configurer.setTilesInitializer(plugminSpringTilesInitializer(definitions)); configurer.setDefinitions(definitions); configurer.setPreparerFactoryClass(SpringBeanPreparerFactory.class); configurer.setCheckRefresh(true); return configurer; } private PlugminSpringTilesInitializer plugminSpringTilesInitializer(String[] definitions) { final PlugminSpringTilesInitializer plugminSpringTilesInitializer = new PlugminSpringTilesInitializer(); plugminSpringTilesInitializer.setCheckRefresh(true); plugminSpringTilesInitializer.setDefinitions(definitions); plugminSpringTilesInitializer.setPreparerFactoryClass(SpringBeanPreparerFactory.class); return plugminSpringTilesInitializer; } @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { converters.add(viewAwareJsonMessageConverter()); } @Bean public HttpMessageConverter<?> viewAwareJsonMessageConverter() { HttpMessageConverter<?> converter = new ViewAwareJsonMessageConverter(); return converter; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { DefaultListableBeanFactory bf = (DefaultListableBeanFactory) beanFactory; parentBeanFactory = bf.getParentBeanFactory(); } }
UTF-8
Java
8,356
java
PlugminContextConfiguration.java
Java
[]
null
[]
package org.plugmin.core.config.context; import java.util.List; import javax.persistence.EntityManagerFactory; import javax.servlet.ServletContext; import org.hibernate.SessionFactory; import org.plugmin.core.config.PlugminConfiguration; import org.plugmin.core.config.StandardPlugminConfiguration; import org.plugmin.core.config.context.json.ViewAwareJsonMessageConverter; import org.plugmin.core.view.PlugminSpringTilesInitializer; import org.plugmin.core.view.SeparateContainerTilesView; import org.plugmin.core.web.ApplicationController; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.orm.hibernate4.support.OpenSessionInViewInterceptor; import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.context.request.WebRequestInterceptor; import org.springframework.web.context.support.ServletContextResourceLoader; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver; import org.springframework.web.servlet.view.UrlBasedViewResolver; import org.springframework.web.servlet.view.tiles2.SpringBeanPreparerFactory; import org.springframework.web.servlet.view.tiles2.TilesConfigurer; @Configuration @ComponentScan("org.plugmin.core.controller") @Import({ PlugminDaoConfiguration.class, PlugminServiceConfiguration.class, PlugminRemoteConfiguration.class, PlugminRepositoryRestConfiguration.class, PlugminViewConfiguration.class }) @EnableWebMvc public class PlugminContextConfiguration extends WebMvcConfigurerAdapter implements BeanFactoryAware { @Autowired(required = false) private EntityManagerFactory entityManagerFactory; @Autowired(required = false) private SessionFactory sessionFactory; private BeanFactory parentBeanFactory; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addWebRequestInterceptor(openSessionOrEntityMgrInViewInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/styles/**").addResourceLocations("classpath:/META-INF/resources/styles/"); registry.addResourceHandler("/scripts/**").addResourceLocations("classpath:/META-INF/resources/scripts/"); registry.addResourceHandler("/kendo-ui/**").addResourceLocations("classpath:/META-INF/resources/kendo-ui/"); registry.addResourceHandler("/images/**").addResourceLocations("classpath:/META-INF/resources/images/").setCachePeriod(31556926); } @Bean @Autowired public PlugminConfiguration plugminConfiguration(ServletContext servletContext) { return new StandardPlugminConfiguration(servletContext); } @Bean @Autowired public ServletContextResourceLoader servletContextResourceLoader(ServletContext servletContext) { return new ServletContextResourceLoader(servletContext); } @Bean public WebRequestInterceptor openSessionOrEntityMgrInViewInterceptor() { WebRequestInterceptor webRequestInterceptor = null; if(entityManagerFactory != null) { OpenEntityManagerInViewInterceptor openEntityManagerInViewInterceptor = new OpenEntityManagerInViewInterceptor(); openEntityManagerInViewInterceptor.setEntityManagerFactory(entityManagerFactory); webRequestInterceptor = openEntityManagerInViewInterceptor; } else { OpenSessionInViewInterceptor openSessionInViewInterceptor = new OpenSessionInViewInterceptor(); openSessionInViewInterceptor.setSessionFactory(sessionFactory); webRequestInterceptor = openSessionInViewInterceptor; } return webRequestInterceptor; } @Bean public CommonsMultipartResolver multipartResolver() { return new CommonsMultipartResolver(); } @Override public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { ExceptionHandlerExceptionResolver exceptionHandlerResolver = new ExceptionHandlerExceptionResolver(); exceptionHandlerResolver.afterPropertiesSet(); exceptionResolvers.add(exceptionHandlerResolver); } @Override public Validator getValidator() { return validator(); } @Bean public LocalValidatorFactoryBean validator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource()); validator.afterPropertiesSet(); return validator; } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setDefaultEncoding("UTF-8"); messageSource.setCacheSeconds(0); messageSource.setFallbackToSystemLocale(false); return messageSource; } @Bean public ApplicationController applicationController() { return new ApplicationController(); } @Bean public ViewResolver viewResolver() { final UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(SeparateContainerTilesView.class); return viewResolver; } @Bean public TilesConfigurer tilesConfigurer() { final String[] definitions = {"classpath*:META-INF/tiles/**/*.xml"}; final TilesConfigurer configurer = new TilesConfigurer(); configurer.setTilesInitializer(plugminSpringTilesInitializer(definitions)); configurer.setDefinitions(definitions); configurer.setPreparerFactoryClass(SpringBeanPreparerFactory.class); configurer.setCheckRefresh(true); return configurer; } private PlugminSpringTilesInitializer plugminSpringTilesInitializer(String[] definitions) { final PlugminSpringTilesInitializer plugminSpringTilesInitializer = new PlugminSpringTilesInitializer(); plugminSpringTilesInitializer.setCheckRefresh(true); plugminSpringTilesInitializer.setDefinitions(definitions); plugminSpringTilesInitializer.setPreparerFactoryClass(SpringBeanPreparerFactory.class); return plugminSpringTilesInitializer; } @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { converters.add(viewAwareJsonMessageConverter()); } @Bean public HttpMessageConverter<?> viewAwareJsonMessageConverter() { HttpMessageConverter<?> converter = new ViewAwareJsonMessageConverter(); return converter; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { DefaultListableBeanFactory bf = (DefaultListableBeanFactory) beanFactory; parentBeanFactory = bf.getParentBeanFactory(); } }
8,356
0.798947
0.797391
194
42.07732
35.557693
180
false
false
0
0
0
0
0
0
0.706186
false
false
12
bf876d09633ae7539399db8e49d149282f77be1a
30,554,397,396,233
8acfe488b36e7662d598a63c55979078c3d73f85
/src/test/java/org/folio/rest/api/testdata/ItemEffectiveLocationTestDataProvider.java
b88e033c83b4b3497c9dbf6f4b3eda3304dc8c5e
[ "Apache-2.0" ]
permissive
openlibraryenvironment/deprecated-mod-inventory-storage
https://github.com/openlibraryenvironment/deprecated-mod-inventory-storage
d5f714897d0e90f46d175491662ff4bdcff34f94
4cb76c93edf5ca6cf0f0a0900c45aa7975aec431
refs/heads/master
2022-12-27T05:11:57.565000
2020-10-07T09:51:44
2020-10-07T09:51:44
238,787,965
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.folio.rest.api.testdata; import static org.folio.rest.api.TestBaseWithInventoryUtil.ANNEX_LIBRARY_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.FOURTH_FLOOR_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.MAIN_LIBRARY_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.ONLINE_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.SECOND_FLOOR_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.THIRD_FLOOR_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.annexLibraryLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.fourthFloorLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.mainLibraryLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.onlineLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.secondFloorLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.thirdFloorLocationId; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * Parameter provider for ItemEffectiveLocationTest.class. */ public class ItemEffectiveLocationTestDataProvider { private static Map<UUID, String> locationIdToNameMap = buildLocationIdToNameMap(); @SuppressWarnings("unused") public static List<PermTemp[]> canCalculateEffectiveLocationOnHoldingUpdateParams() { List<PermTemp[]> params = new ArrayList<>(); PermTemp[] itemLocationsList = { new PermTemp(null, null), new PermTemp(null, mainLibraryLocationId), new PermTemp(mainLibraryLocationId, null), new PermTemp(mainLibraryLocationId, annexLibraryLocationId), }; PermTemp[] holdingsStartLocationsList = { new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), }; PermTemp[] holdingsEndLocationsList = { new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), new PermTemp(thirdFloorLocationId, null), new PermTemp(thirdFloorLocationId, fourthFloorLocationId), }; for (PermTemp itemLocations : itemLocationsList) { for (PermTemp holdingStartLocations : holdingsStartLocationsList) { for (PermTemp holdingEndLocations : holdingsEndLocationsList) { params.add(new PermTemp[]{itemLocations, holdingStartLocations, holdingEndLocations}); } } } return params; } @SuppressWarnings("unused") public static List<PermTemp[]> canCalculateEffectiveLocationOnItemUpdateParams() { List<PermTemp[]> parameters = new ArrayList<>(); PermTemp[] holdingsLocationsList = { new PermTemp(mainLibraryLocationId, null), new PermTemp(mainLibraryLocationId, annexLibraryLocationId), }; PermTemp[] itemStartLocationsList = { new PermTemp(null, null), new PermTemp(null, onlineLocationId), new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), }; PermTemp[] itemEndLocationsList = { new PermTemp(null, null), new PermTemp(null, onlineLocationId), new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), new PermTemp(null, thirdFloorLocationId), new PermTemp(thirdFloorLocationId, null), new PermTemp(thirdFloorLocationId, fourthFloorLocationId), }; for (PermTemp holdingLocations : holdingsLocationsList) { for (PermTemp itemStartLocations : itemStartLocationsList) { for (PermTemp itemEndLocations : itemEndLocationsList) { parameters.add(new PermTemp[]{holdingLocations, itemStartLocations, itemEndLocations}); } } } return parameters; } private static Map<UUID, String> buildLocationIdToNameMap() { HashMap<UUID, String> idToNameMap = new HashMap<>(); idToNameMap.put(mainLibraryLocationId, MAIN_LIBRARY_LOCATION); idToNameMap.put(annexLibraryLocationId, ANNEX_LIBRARY_LOCATION); idToNameMap.put(onlineLocationId, ONLINE_LOCATION); idToNameMap.put(secondFloorLocationId, SECOND_FLOOR_LOCATION); idToNameMap.put(thirdFloorLocationId, THIRD_FLOOR_LOCATION); idToNameMap.put(fourthFloorLocationId, FOURTH_FLOOR_LOCATION); return idToNameMap; } /** * Store a permanent location UUID and a temporary location UUID. */ public static class PermTemp { /** * permanent location UUID */ public UUID perm; /** * temporary location UUID */ public UUID temp; /** * @param perm permanent location UUID * @param temp temporary location UUID */ PermTemp(UUID perm, UUID temp) { this.perm = perm; this.temp = temp; } @Override public String toString() { return locationIdToNameMap.get(perm) + ", " + locationIdToNameMap.get(temp); } } }
UTF-8
Java
4,951
java
ItemEffectiveLocationTestDataProvider.java
Java
[]
null
[]
package org.folio.rest.api.testdata; import static org.folio.rest.api.TestBaseWithInventoryUtil.ANNEX_LIBRARY_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.FOURTH_FLOOR_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.MAIN_LIBRARY_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.ONLINE_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.SECOND_FLOOR_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.THIRD_FLOOR_LOCATION; import static org.folio.rest.api.TestBaseWithInventoryUtil.annexLibraryLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.fourthFloorLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.mainLibraryLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.onlineLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.secondFloorLocationId; import static org.folio.rest.api.TestBaseWithInventoryUtil.thirdFloorLocationId; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * Parameter provider for ItemEffectiveLocationTest.class. */ public class ItemEffectiveLocationTestDataProvider { private static Map<UUID, String> locationIdToNameMap = buildLocationIdToNameMap(); @SuppressWarnings("unused") public static List<PermTemp[]> canCalculateEffectiveLocationOnHoldingUpdateParams() { List<PermTemp[]> params = new ArrayList<>(); PermTemp[] itemLocationsList = { new PermTemp(null, null), new PermTemp(null, mainLibraryLocationId), new PermTemp(mainLibraryLocationId, null), new PermTemp(mainLibraryLocationId, annexLibraryLocationId), }; PermTemp[] holdingsStartLocationsList = { new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), }; PermTemp[] holdingsEndLocationsList = { new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), new PermTemp(thirdFloorLocationId, null), new PermTemp(thirdFloorLocationId, fourthFloorLocationId), }; for (PermTemp itemLocations : itemLocationsList) { for (PermTemp holdingStartLocations : holdingsStartLocationsList) { for (PermTemp holdingEndLocations : holdingsEndLocationsList) { params.add(new PermTemp[]{itemLocations, holdingStartLocations, holdingEndLocations}); } } } return params; } @SuppressWarnings("unused") public static List<PermTemp[]> canCalculateEffectiveLocationOnItemUpdateParams() { List<PermTemp[]> parameters = new ArrayList<>(); PermTemp[] holdingsLocationsList = { new PermTemp(mainLibraryLocationId, null), new PermTemp(mainLibraryLocationId, annexLibraryLocationId), }; PermTemp[] itemStartLocationsList = { new PermTemp(null, null), new PermTemp(null, onlineLocationId), new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), }; PermTemp[] itemEndLocationsList = { new PermTemp(null, null), new PermTemp(null, onlineLocationId), new PermTemp(onlineLocationId, null), new PermTemp(onlineLocationId, secondFloorLocationId), new PermTemp(null, thirdFloorLocationId), new PermTemp(thirdFloorLocationId, null), new PermTemp(thirdFloorLocationId, fourthFloorLocationId), }; for (PermTemp holdingLocations : holdingsLocationsList) { for (PermTemp itemStartLocations : itemStartLocationsList) { for (PermTemp itemEndLocations : itemEndLocationsList) { parameters.add(new PermTemp[]{holdingLocations, itemStartLocations, itemEndLocations}); } } } return parameters; } private static Map<UUID, String> buildLocationIdToNameMap() { HashMap<UUID, String> idToNameMap = new HashMap<>(); idToNameMap.put(mainLibraryLocationId, MAIN_LIBRARY_LOCATION); idToNameMap.put(annexLibraryLocationId, ANNEX_LIBRARY_LOCATION); idToNameMap.put(onlineLocationId, ONLINE_LOCATION); idToNameMap.put(secondFloorLocationId, SECOND_FLOOR_LOCATION); idToNameMap.put(thirdFloorLocationId, THIRD_FLOOR_LOCATION); idToNameMap.put(fourthFloorLocationId, FOURTH_FLOOR_LOCATION); return idToNameMap; } /** * Store a permanent location UUID and a temporary location UUID. */ public static class PermTemp { /** * permanent location UUID */ public UUID perm; /** * temporary location UUID */ public UUID temp; /** * @param perm permanent location UUID * @param temp temporary location UUID */ PermTemp(UUID perm, UUID temp) { this.perm = perm; this.temp = temp; } @Override public String toString() { return locationIdToNameMap.get(perm) + ", " + locationIdToNameMap.get(temp); } } }
4,951
0.74187
0.74187
134
35.947762
28.823788
97
true
false
0
0
0
0
0
0
0.783582
false
false
12
584bdd698d3d1ca8664a023d60e13ef792153702
28,200,755,286,668
4159e7712e09de1c6eb69cb94043992952ce3cbe
/src/test/java/pl/com/lang/unit/web/service/AuthorServiceImplTest.java
bd7411a0ae6c4068f72fb53b4f9d0801d1ab25fa
[]
no_license
IssamAssahal/Publisher-LangLTC
https://github.com/IssamAssahal/Publisher-LangLTC
be820761fd9bc894ba412a1a6b6bedd1dc8a12a0
bfbeca707fe11925a9d4d001fdef13b825e1d584
refs/heads/master
2020-04-03T08:09:24.461000
2018-10-29T00:16:17
2018-10-29T00:16:17
155,124,314
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.com.lang.unit.web.service; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.test.context.junit4.SpringRunner; import pl.com.lang.support.exception.DuplicateException; import pl.com.lang.support.exception.NotFoundException; import pl.com.lang.web.entity.Author; import pl.com.lang.web.entity.Book; import pl.com.lang.web.entity.BookAuthor; import pl.com.lang.web.repository.AuthorRepository; import pl.com.lang.web.repository.BookAuthorRepository; import pl.com.lang.web.repository.BookRepository; import pl.com.lang.web.service.AuthorService; import pl.com.lang.web.service.impl.AuthorServiceImpl; /** * <b>Author Service Unit Test</b><br> * @author Issam As-sahal ISA */ @RunWith(SpringRunner.class) public class AuthorServiceImplTest { private @Mock BookRepository bookRepository; private @Mock AuthorRepository authorRepository; private @Mock BookAuthorRepository bookAuthorRepository; private @InjectMocks AuthorService authorService = new AuthorServiceImpl(); private Long authorId = 1L; private Long bookId = 1L; private String authorName = "Adam"; private String bookName = "English Level B2"; @Test public void testGetAuthorById() { Author author = new Author(); author.setId(authorId); author.setAuthorName(authorName); Mockito.when(authorRepository.findOne(authorId)).thenReturn(author); Author retrievedAuthor = authorService.getAuthor(authorId); Assert.assertEquals(author, retrievedAuthor); } @Test(expected = NotFoundException.class) public void testGetNonExistAuthorById() { Mockito.when(authorRepository.findOne(authorId)).thenReturn(null); authorService.getAuthor(authorId); } @Test public void testCreateAuthorByAuthorName() { Author author = new Author(); author.setAuthorName(authorName); Mockito.when(authorRepository.findByAuthorName(authorName)).thenReturn(null); Mockito.when(authorRepository.save(author)).thenReturn(author); Author savedAuthor = authorService.createAuthor(authorName); Assert.assertEquals(author, savedAuthor); } @Test(expected = DuplicateException.class) public void testCreateDuplicateAuthorByAuthorName() { Author author = new Author(); author.setAuthorName(authorName); Mockito.when(authorRepository.findByAuthorName(authorName)).thenReturn(author); Mockito.when(authorRepository.save(author)).thenReturn(author); authorService.createAuthor(authorName); } @Test public void testDeleteAuthorById() { Author author = new Author(); author.setId(authorId); author.setAuthorName(authorName); Mockito.when(authorRepository.findOne(authorId)).thenReturn(author); authorService.deleteAuthor(authorId); Mockito.verify(bookAuthorRepository, Mockito.times(1)).deleteByAuthor(author); Mockito.verify(authorRepository, Mockito.times(1)).delete(author); } @Test(expected = NotFoundException.class) public void testDeleteNonExistAuthorById() { Mockito.when(authorRepository.findOne(authorId)).thenReturn(null); authorService.deleteAuthor(authorId); } @Test public void testAssignBook() { Author author = new Author(); author.setId(authorId); author.setAuthorName(authorName); Book book = new Book(); book.setId(bookId); book.setBookName(bookName); BookAuthor bookAuthor = new BookAuthor(); bookAuthor.setBook(book); bookAuthor.setAuthor(author); Mockito.when(authorRepository.findOne(authorId)).thenReturn(author); Mockito.when(bookRepository.findOne(bookId)).thenReturn(book); Mockito.when(bookAuthorRepository.findByBookAndAuthor(book, author)).thenReturn(null); Mockito.when(bookAuthorRepository.save(bookAuthor)).thenReturn(bookAuthor); Author assignedAuthor = authorService.assignBook(authorId, bookId); Assert.assertEquals(author, assignedAuthor); } @Test(expected = NotFoundException.class) public void testAssignBookWithNonExistAuthor() { Mockito.when(authorRepository.findOne(authorId)).thenReturn(null); authorService.assignBook(authorId, bookId); } @Test(expected = NotFoundException.class) public void testAssignBookWithNonExistBook() { Mockito.when(bookRepository.findOne(bookId)).thenReturn(null); authorService.assignBook(authorId, bookId); } }
UTF-8
Java
4,477
java
AuthorServiceImplTest.java
Java
[ { "context": " * <b>Author Service Unit Test</b><br>\r\n * @author Issam As-sahal ISA\r\n */\r\n@RunWith(SpringRunner.class)\r\npublic class ", "end": 849, "score": 0.9601395726203918, "start": 831, "tag": "NAME", "value": "Issam As-sahal ISA" }, { "context": " Long bookId = 1L;\r\n\tprivate String authorName = \"Adam\";\r\n\tprivate String bookName = \"English Level B2\";", "end": 1266, "score": 0.9997420907020569, "start": 1262, "tag": "NAME", "value": "Adam" } ]
null
[]
package pl.com.lang.unit.web.service; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.test.context.junit4.SpringRunner; import pl.com.lang.support.exception.DuplicateException; import pl.com.lang.support.exception.NotFoundException; import pl.com.lang.web.entity.Author; import pl.com.lang.web.entity.Book; import pl.com.lang.web.entity.BookAuthor; import pl.com.lang.web.repository.AuthorRepository; import pl.com.lang.web.repository.BookAuthorRepository; import pl.com.lang.web.repository.BookRepository; import pl.com.lang.web.service.AuthorService; import pl.com.lang.web.service.impl.AuthorServiceImpl; /** * <b>Author Service Unit Test</b><br> * @author <NAME> */ @RunWith(SpringRunner.class) public class AuthorServiceImplTest { private @Mock BookRepository bookRepository; private @Mock AuthorRepository authorRepository; private @Mock BookAuthorRepository bookAuthorRepository; private @InjectMocks AuthorService authorService = new AuthorServiceImpl(); private Long authorId = 1L; private Long bookId = 1L; private String authorName = "Adam"; private String bookName = "English Level B2"; @Test public void testGetAuthorById() { Author author = new Author(); author.setId(authorId); author.setAuthorName(authorName); Mockito.when(authorRepository.findOne(authorId)).thenReturn(author); Author retrievedAuthor = authorService.getAuthor(authorId); Assert.assertEquals(author, retrievedAuthor); } @Test(expected = NotFoundException.class) public void testGetNonExistAuthorById() { Mockito.when(authorRepository.findOne(authorId)).thenReturn(null); authorService.getAuthor(authorId); } @Test public void testCreateAuthorByAuthorName() { Author author = new Author(); author.setAuthorName(authorName); Mockito.when(authorRepository.findByAuthorName(authorName)).thenReturn(null); Mockito.when(authorRepository.save(author)).thenReturn(author); Author savedAuthor = authorService.createAuthor(authorName); Assert.assertEquals(author, savedAuthor); } @Test(expected = DuplicateException.class) public void testCreateDuplicateAuthorByAuthorName() { Author author = new Author(); author.setAuthorName(authorName); Mockito.when(authorRepository.findByAuthorName(authorName)).thenReturn(author); Mockito.when(authorRepository.save(author)).thenReturn(author); authorService.createAuthor(authorName); } @Test public void testDeleteAuthorById() { Author author = new Author(); author.setId(authorId); author.setAuthorName(authorName); Mockito.when(authorRepository.findOne(authorId)).thenReturn(author); authorService.deleteAuthor(authorId); Mockito.verify(bookAuthorRepository, Mockito.times(1)).deleteByAuthor(author); Mockito.verify(authorRepository, Mockito.times(1)).delete(author); } @Test(expected = NotFoundException.class) public void testDeleteNonExistAuthorById() { Mockito.when(authorRepository.findOne(authorId)).thenReturn(null); authorService.deleteAuthor(authorId); } @Test public void testAssignBook() { Author author = new Author(); author.setId(authorId); author.setAuthorName(authorName); Book book = new Book(); book.setId(bookId); book.setBookName(bookName); BookAuthor bookAuthor = new BookAuthor(); bookAuthor.setBook(book); bookAuthor.setAuthor(author); Mockito.when(authorRepository.findOne(authorId)).thenReturn(author); Mockito.when(bookRepository.findOne(bookId)).thenReturn(book); Mockito.when(bookAuthorRepository.findByBookAndAuthor(book, author)).thenReturn(null); Mockito.when(bookAuthorRepository.save(bookAuthor)).thenReturn(bookAuthor); Author assignedAuthor = authorService.assignBook(authorId, bookId); Assert.assertEquals(author, assignedAuthor); } @Test(expected = NotFoundException.class) public void testAssignBookWithNonExistAuthor() { Mockito.when(authorRepository.findOne(authorId)).thenReturn(null); authorService.assignBook(authorId, bookId); } @Test(expected = NotFoundException.class) public void testAssignBookWithNonExistBook() { Mockito.when(bookRepository.findOne(bookId)).thenReturn(null); authorService.assignBook(authorId, bookId); } }
4,465
0.758767
0.757427
151
27.649006
24.470066
88
false
false
0
0
0
0
0
0
1.417219
false
false
13
f6889f56b635e0255fbe694d00ae26bb5ac56341
18,820,546,743,301
0e44cf827ea3555d8f785ab76d31251bdb3c4a37
/APracticeByYourSelf/src/oop/polimorphism/overloading/TestOverloading.java
3fe8a5453ff0d04766b951930e8267162caa99aa
[]
no_license
ReziaFarhana/farhananew
https://github.com/ReziaFarhana/farhananew
d91e165a0a02321b6562d05aef81a933c9804df5
b79f618c30ca215e25a682b50a8b076fee1f356b
refs/heads/main
2023-03-19T16:57:10.065000
2021-03-05T04:04:18
2021-03-05T04:04:18
332,104,932
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oop.polimorphism.overloading; public class TestOverloading { public static void main(String[] args) { MethodOverloading.doSum(10, 20, 30, 40); MethodOverloading.stId("Farhana", "Bronx", 30294, 5000); } }
UTF-8
Java
238
java
TestOverloading.java
Java
[ { "context": "(10, 20, 30, 40);\n MethodOverloading.stId(\"Farhana\", \"Bronx\", 30294, 5000);\n }\n}", "end": 205, "score": 0.9996364116668701, "start": 198, "tag": "NAME", "value": "Farhana" }, { "context": ", 40);\n MethodOverloading.stId(\"Farhana\", \"Bronx\", 30294, 5000);\n }\n}", "end": 214, "score": 0.9995410442352295, "start": 209, "tag": "NAME", "value": "Bronx" } ]
null
[]
package oop.polimorphism.overloading; public class TestOverloading { public static void main(String[] args) { MethodOverloading.doSum(10, 20, 30, 40); MethodOverloading.stId("Farhana", "Bronx", 30294, 5000); } }
238
0.676471
0.605042
10
22.9
23.209696
64
false
false
0
0
0
0
0
0
0.9
false
false
13
e7042591557aabc9a44e6b7e9b4789314c936c31
18,820,546,743,031
85f5bf1ca9fef7772fa7d6e99765e4bbf788bb4b
/java/src/main/java/fr/automated/trading/systems/pricingmodel/pricingstrategies/neuralnetworks/layer/Layer.java
6078b8881a3ff0cf3b1c4119dc8c94d9a628885a
[]
no_license
5l1v3r1/Data-Mining-Automaton
https://github.com/5l1v3r1/Data-Mining-Automaton
b50d4ecb0df7a84206fd42f6926649e0778aa13e
1bc4fd8b6218047094efa721f8934800c588ce8b
refs/heads/master
2021-04-11T03:22:56.756000
2013-06-25T21:31:03
2013-06-25T21:31:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.automated.trading.systems.pricingmodel.pricingstrategies.neuralnetworks.layer; import fr.automated.trading.systems.exception.RemoveNeuronOutOfBounds; import fr.automated.trading.systems.pricingmodel.pricingstrategies.neuralnetworks.neuron.INeuron; import fr.automated.trading.systems.utils.utils.AtsLogger; import java.util.ArrayList; /** * Container for neurons. Layer implements ILayer. * @author Philippe REMY */ public class Layer implements ILayer { private final ArrayList<INeuron> neurons = new ArrayList<>(); public void addNeuron(INeuron neuron) { neurons.add(neuron); } public void removeNeuron(int count) throws RemoveNeuronOutOfBounds { if(neurons.size() >= count) { for(int i=0; i<count; i++) { neurons.remove(i); } } else throw new RemoveNeuronOutOfBounds(); } public INeuron getNeuron(int id) { return neurons.get(id); } public void freeLayer() { neurons.removeAll(neurons); } public void createNewLayer() { AtsLogger.log("layer created"); } public int getCount() { return neurons.size(); } public Layer() { createNewLayer(); } }
UTF-8
Java
1,146
java
Layer.java
Java
[ { "context": "r for neurons. Layer implements ILayer.\n * @author Philippe REMY\n */\npublic class Layer implements ILayer {\n\n\tpriv", "end": 428, "score": 0.9998129606246948, "start": 415, "tag": "NAME", "value": "Philippe REMY" } ]
null
[]
package fr.automated.trading.systems.pricingmodel.pricingstrategies.neuralnetworks.layer; import fr.automated.trading.systems.exception.RemoveNeuronOutOfBounds; import fr.automated.trading.systems.pricingmodel.pricingstrategies.neuralnetworks.neuron.INeuron; import fr.automated.trading.systems.utils.utils.AtsLogger; import java.util.ArrayList; /** * Container for neurons. Layer implements ILayer. * @author <NAME> */ public class Layer implements ILayer { private final ArrayList<INeuron> neurons = new ArrayList<>(); public void addNeuron(INeuron neuron) { neurons.add(neuron); } public void removeNeuron(int count) throws RemoveNeuronOutOfBounds { if(neurons.size() >= count) { for(int i=0; i<count; i++) { neurons.remove(i); } } else throw new RemoveNeuronOutOfBounds(); } public INeuron getNeuron(int id) { return neurons.get(id); } public void freeLayer() { neurons.removeAll(neurons); } public void createNewLayer() { AtsLogger.log("layer created"); } public int getCount() { return neurons.size(); } public Layer() { createNewLayer(); } }
1,139
0.71815
0.717277
53
20.622641
24.178757
97
false
false
0
0
0
0
0
0
1.09434
false
false
13
f5b81062873b3da9aaae0a888275eee9c8685420
2,027,224,631,135
d2e367e78de401a42dbfee65ad04f127f45fd7b2
/src/com/ivantod/trancer/light/Light.java
858ff0a42dbecfe8f17dd10adece211a5b04ee76
[]
no_license
ivantod/TrancerJ
https://github.com/ivantod/TrancerJ
e8eab3a833346961cfb311c6f5eff8703a8fe0a3
e756fd5440700aa9c3bda6ca34e5277aec770e66
refs/heads/master
2021-01-01T06:54:53.308000
2013-01-05T18:13:18
2013-01-05T18:13:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ivantod.trancer.light; import com.ivantod.trancer.geometry.Ray; import com.ivantod.trancer.geometry.Vector; import com.ivantod.trancer.scene.ShadingInfo; import com.ivantod.trancer.util.color.Color; public abstract class Light { private boolean castsShadow = true; public abstract Vector direction(ShadingInfo shadingInfo); public abstract Color luminance(ShadingInfo shadingInfo); public boolean inShadow(Ray ray, ShadingInfo shadingInfo) { return false; } public boolean castsShadow() { return castsShadow; } public void setCastsShadow(boolean castsShadow) { this.castsShadow = castsShadow; } }
UTF-8
Java
639
java
Light.java
Java
[]
null
[]
package com.ivantod.trancer.light; import com.ivantod.trancer.geometry.Ray; import com.ivantod.trancer.geometry.Vector; import com.ivantod.trancer.scene.ShadingInfo; import com.ivantod.trancer.util.color.Color; public abstract class Light { private boolean castsShadow = true; public abstract Vector direction(ShadingInfo shadingInfo); public abstract Color luminance(ShadingInfo shadingInfo); public boolean inShadow(Ray ray, ShadingInfo shadingInfo) { return false; } public boolean castsShadow() { return castsShadow; } public void setCastsShadow(boolean castsShadow) { this.castsShadow = castsShadow; } }
639
0.780908
0.780908
29
21.034483
21.616537
60
false
false
0
0
0
0
0
0
1.103448
false
false
13
657e3813000da76b6df5898f1d206e9da8216107
3,607,772,533,863
0153d87e4c8129c2eae84808892703069e275001
/src/eps-parent/eps-main/src/main/java/com/vanform/eps/device/vo/EpsDeviceParamsTransfer.java
f453c1797bcc38265512608455b0bb3afd50c0a0
[]
no_license
xuenianming/spcs
https://github.com/xuenianming/spcs
e1a8e0a4a6fbc180503dbd4167b6c79758ab7199
9c4c9c18f11004e126a821c86d01120f365b9891
refs/heads/master
2020-03-29T13:09:51.847000
2018-11-28T07:38:49
2018-11-28T07:38:49
149,943,544
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vanform.eps.device.vo; import com.vanform.eps.device.domain.EpsDeviceParams; /** * <b>概述</b>:EpsDeviceParamsTransfer类<br> * TODO * <p> * <b>功能</b>:<br> * TODO * * @author jiaoj */ public class EpsDeviceParamsTransfer { private EpsDeviceParamsTransfer(){} /** * @toPO:vo转为po * @param vo vo对象 * @return EpsDeviceParams EpsDeviceParams对象 * @date 2018-11-17 00:54:19 * @author jiaoj */ public static EpsDeviceParams toPO(EpsDeviceParamsVO vo) { EpsDeviceParams epsDeviceParams = new EpsDeviceParams(); if(vo != null){ epsDeviceParams.setGuid(vo.getGuid()); epsDeviceParams.setDescription(vo.getDescription()); epsDeviceParams.setSort(vo.getSort()); epsDeviceParams.setUpdateuser(vo.getUpdateuser()); epsDeviceParams.setUpdatetime(vo.getUpdatetime()); epsDeviceParams.setDeviceGUID(vo.getDeviceGUID()); } return epsDeviceParams; } /** * @toVO:po转为vo * @param po po对象 * @return EpsDeviceParamsVO EpsDeviceParamsVO对象 * @date 2018-11-17 00:54:19 * @author jiaoj */ public static EpsDeviceParamsVO toVO(EpsDeviceParams po) { EpsDeviceParamsVO vo = new EpsDeviceParamsVO(); vo.setGuid(po.getGuid()); vo.setDescription(po.getDescription()); vo.setSort(po.getSort()); vo.setUpdateuser(po.getUpdateuser()); vo.setUpdatetime(po.getUpdatetime()); vo.setDeviceGUID(po.getDeviceGUID()); return vo; } }
UTF-8
Java
1,427
java
EpsDeviceParamsTransfer.java
Java
[ { "context": "ODO\n * <p>\n * <b>功能</b>:<br>\n * TODO\n *\n * @author jiaoj\n */\npublic class EpsDeviceParamsTransfer {\n\t\n\tpri", "end": 197, "score": 0.9995282292366028, "start": 192, "tag": "USERNAME", "value": "jiaoj" }, { "context": "Params对象\n\t * @date 2018-11-17 00:54:19\n\t * @author jiaoj\n\t */\n\tpublic static EpsDeviceParams toPO(EpsDevic", "end": 415, "score": 0.9995881915092468, "start": 410, "tag": "USERNAME", "value": "jiaoj" }, { "context": "ramsVO对象\n\t * @date 2018-11-17 00:54:19\n\t * @author jiaoj\n\t */\n\tpublic static EpsDeviceParamsVO toVO(EpsDev", "end": 1037, "score": 0.9995689988136292, "start": 1032, "tag": "USERNAME", "value": "jiaoj" } ]
null
[]
package com.vanform.eps.device.vo; import com.vanform.eps.device.domain.EpsDeviceParams; /** * <b>概述</b>:EpsDeviceParamsTransfer类<br> * TODO * <p> * <b>功能</b>:<br> * TODO * * @author jiaoj */ public class EpsDeviceParamsTransfer { private EpsDeviceParamsTransfer(){} /** * @toPO:vo转为po * @param vo vo对象 * @return EpsDeviceParams EpsDeviceParams对象 * @date 2018-11-17 00:54:19 * @author jiaoj */ public static EpsDeviceParams toPO(EpsDeviceParamsVO vo) { EpsDeviceParams epsDeviceParams = new EpsDeviceParams(); if(vo != null){ epsDeviceParams.setGuid(vo.getGuid()); epsDeviceParams.setDescription(vo.getDescription()); epsDeviceParams.setSort(vo.getSort()); epsDeviceParams.setUpdateuser(vo.getUpdateuser()); epsDeviceParams.setUpdatetime(vo.getUpdatetime()); epsDeviceParams.setDeviceGUID(vo.getDeviceGUID()); } return epsDeviceParams; } /** * @toVO:po转为vo * @param po po对象 * @return EpsDeviceParamsVO EpsDeviceParamsVO对象 * @date 2018-11-17 00:54:19 * @author jiaoj */ public static EpsDeviceParamsVO toVO(EpsDeviceParams po) { EpsDeviceParamsVO vo = new EpsDeviceParamsVO(); vo.setGuid(po.getGuid()); vo.setDescription(po.getDescription()); vo.setSort(po.getSort()); vo.setUpdateuser(po.getUpdateuser()); vo.setUpdatetime(po.getUpdatetime()); vo.setDeviceGUID(po.getDeviceGUID()); return vo; } }
1,427
0.714183
0.694025
54
24.722221
19.429279
59
false
false
0
0
0
0
0
0
1.444444
false
false
13
7f8afe8146857a1ff5837147be182860ce59fc56
10,763,188,112,167
0750bad7d4a963d66d822fad0d022aae5ced7176
/Spring-06-java-config/src/main/java/com/hong/pojo/User.java
e5b7f56389a8e8d306b4555b02147210c172e748
[]
no_license
lovivi101/Spring-test
https://github.com/lovivi101/Spring-test
bd159668833a53207795615dc44be11d0b7b503a
f7f108919d8ed876782092769468c5dbe7b72d85
refs/heads/master
2023-04-10T14:17:32.512000
2021-04-21T02:51:59
2021-04-21T02:51:59
360,010,956
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hong.pojo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @description: * @author: hjx * @time: 2021年04月07日 21:06 */ @Component("user") public class User { private String name; private int age; private Dog dog; private Cat cat ; @Autowired @Qualifier(value = "dog") public void setDog(Dog dog) { this.dog = dog; } @Autowired @Qualifier(value = "cat") public void setCat(Cat cat) { this.cat = cat; } @Value("乐乐") public void setName(String name) { this.name = name; } @Value("20") public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", dog=" + dog + ", cat=" + cat + '}'; } }
UTF-8
Java
1,106
java
User.java
Java
[ { "context": "otype.Component;\n\n/**\n * @description:\n * @author: hjx\n * @time: 2021年04月07日 21:06\n */\n\n@Component(\"user", "end": 295, "score": 0.9997111558914185, "start": 292, "tag": "USERNAME", "value": "hjx" } ]
null
[]
package com.hong.pojo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @description: * @author: hjx * @time: 2021年04月07日 21:06 */ @Component("user") public class User { private String name; private int age; private Dog dog; private Cat cat ; @Autowired @Qualifier(value = "dog") public void setDog(Dog dog) { this.dog = dog; } @Autowired @Qualifier(value = "cat") public void setCat(Cat cat) { this.cat = cat; } @Value("乐乐") public void setName(String name) { this.name = name; } @Value("20") public void setAge(int age) { this.age = age; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", dog=" + dog + ", cat=" + cat + '}'; } }
1,106
0.556569
0.543796
60
17.266666
16.347137
62
false
false
0
0
0
0
0
0
0.283333
false
false
13
a1c9724f948724234f6571f78e4ea2ea3cabfa25
12,936,441,538,387
4057ddd3fe4f35b8ee70e4f22d86c9355fb0ec2b
/DogLibrary/src/main/java/parkinsonbenjamin/doglibrary/processor/FavouritesProcessor.java
22759f00a87b4b2c1c05a13e494576f67bd62599
[]
no_license
benparkinson/doglibrary
https://github.com/benparkinson/doglibrary
fb9ae9e8cc262fb5ac0fefc388ceb05d3bd92a2c
65c836766611eb704d67e71f9ef2e0bb2719a725
refs/heads/master
2021-05-11T20:10:28.378000
2019-04-05T15:51:29
2019-04-05T15:51:29
117,433,025
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package parkinsonbenjamin.doglibrary.processor; import parkinsonbenjamin.doglibrary.dal.DoggoDal; public class FavouritesProcessor implements Processor { @Override public void initialise(DoggoDal dal) { } }
UTF-8
Java
222
java
FavouritesProcessor.java
Java
[ { "context": "package parkinsonbenjamin.doglibrary.processor;\n\nimport parkinsonbenjamin.d", "end": 25, "score": 0.9775550961494446, "start": 8, "tag": "USERNAME", "value": "parkinsonbenjamin" }, { "context": "ge parkinsonbenjamin.doglibrary.processor;\n\nimport parkinsonbenjamin.doglibrary.dal.DoggoDal;\n\npublic class Favourites", "end": 73, "score": 0.997209906578064, "start": 56, "tag": "USERNAME", "value": "parkinsonbenjamin" } ]
null
[]
package parkinsonbenjamin.doglibrary.processor; import parkinsonbenjamin.doglibrary.dal.DoggoDal; public class FavouritesProcessor implements Processor { @Override public void initialise(DoggoDal dal) { } }
222
0.788288
0.788288
10
21.200001
22.582294
55
false
false
0
0
0
0
0
0
0.2
false
false
13
0f9b2aff6ae3cadffb8290decad227a61dea19bc
12,936,441,535,623
6c0e95514b7bd993c9017527b64dfc28d170fa01
/src/cakehat/views/config/AssignmentPanel.java
db3d85fcd20f4766a471a5e457e6fa1a5c8803f7
[]
no_license
jveldridge/cakehat
https://github.com/jveldridge/cakehat
d241dedee97f3ae8bb9d9eae21b4e6d37e9f9e0c
16cebddf2391aa0dae8a53411a781e400150da19
refs/heads/master
2021-01-01T19:42:12.911000
2013-09-20T20:09:53
2013-09-20T20:09:53
32,119,640
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cakehat.views.config; import cakehat.Allocator; import cakehat.database.DbAction; import cakehat.database.DbActionProperty; import cakehat.database.DbAssignment; import cakehat.database.DbGradableEvent; import cakehat.database.DbPart; import cakehat.assignment.ActionDescription; import cakehat.assignment.DeadlineInfo; import cakehat.assignment.Task; import cakehat.assignment.TaskProperty; import cakehat.assignment.TaskRepository; import cakehat.logging.ErrorReporter; import cakehat.views.config.ValidationResult.ValidationState; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.sql.SQLException; 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.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.joda.time.DateTime; import org.joda.time.Period; import support.resources.icons.IconLoader; import support.resources.icons.IconLoader.IconImage; import support.resources.icons.IconLoader.IconSize; import support.ui.DateTimeControl; import support.ui.DescriptionProvider; import support.ui.DocumentAdapter; import support.ui.DnDList; import support.ui.DnDListener; import support.ui.FixedWidthJPanel; import support.ui.FormattedLabel; import support.ui.GenericJComboBox; import support.ui.ModalDialog; import support.ui.ModalJFrameHostHelper.CloseAction; import support.ui.PaddingPanel; import support.ui.PartialDescriptionProvider; import support.ui.PeriodControl; import support.ui.PreferredHeightJPanel; import support.ui.SelectionListener; import support.ui.SelectionListener.SelectionAction; /** * * @author jak2 */ class AssignmentPanel extends JPanel { static final String WORKER_TAG = "ASSIGNMENT"; private final ConfigManagerView _configManager; private final UniqueElementSingleThreadWorker _worker; private final DnDList<DbAssignment> _assignmentList; private final JPanel _selectedAssignmentPanel; private final Map<DbAssignment, JPanel> _assignmentPanels = new WeakHashMap<DbAssignment, JPanel>(); /** * A map of {@link DbAssignment} objects to the currently user supplied name. This is not necessarily the name * stored in the DbAssignment object. It will be different if the user is currently modifying the input field for * the assignment. */ private final ConcurrentMap<DbAssignment, String> _asgnDisplayName = new ConcurrentHashMap<DbAssignment, String>(); public AssignmentPanel(ConfigManagerView configManager, UniqueElementSingleThreadWorker worker) { _configManager = configManager; _worker = worker; this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); _assignmentList = new DnDList<DbAssignment>(); this.setupAssignmentList(); this.add(Box.createHorizontalStrut(5)); _selectedAssignmentPanel = new JPanel(); this.add(_selectedAssignmentPanel); this.initialize(); } private void setupAssignmentList() { _assignmentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); _assignmentList.addDnDSource(_assignmentList); _assignmentList.setDescriptionProvider(new PartialDescriptionProvider<DbAssignment>() { @Override public String getDisplayText(DbAssignment asgn) { String name = _asgnDisplayName.get(asgn); if(name == null) { name = asgn.getName(); } //A blank string will result in the cell being given an abnormally short height - so use a space instead if(name.isEmpty()) { name = " "; } return name; } }); _assignmentList.addDnDListener(new DnDListener<DbAssignment>() { @Override public void valuesAdded(Map<Integer, DbAssignment> added) { } @Override public void valuesRemoved(List<DbAssignment> removed) { } @Override public void valuesReordered(Map<Integer, DbAssignment> values) { final Set<DbAssignment> reorderedAssignments = getReorderedAssignments(); if(!reorderedAssignments.isEmpty()) { _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(reorderedAssignments); } @Override public String dbFailureMessage() { return "Unable to reorder assignments"; } }); } } }); JPanel listPanel = new JPanel(new BorderLayout(0, 0)); listPanel.setMinimumSize(new Dimension(180, Short.MIN_VALUE)); listPanel.setPreferredSize(new Dimension(180, Short.MAX_VALUE)); listPanel.setMaximumSize(new Dimension(180, Short.MAX_VALUE)); this.add(listPanel); final JScrollPane listPane = new JScrollPane(_assignmentList); listPanel.add(listPane, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new BorderLayout(0, 0)); buttonPanel.add(Box.createVerticalStrut(5), BorderLayout.NORTH); listPanel.add(buttonPanel, BorderLayout.SOUTH); JButton addButton = new JButton("Add"); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new assignment int maxOrder = -1; HashSet<String> assignmentNames = new HashSet<String>(); List<DbAssignment> assignments = _assignmentList.getListData(); for(DbAssignment asgn : assignments) { maxOrder = Math.max(maxOrder, asgn.getOrder()); assignmentNames.add(asgn.getName()); } int asgnOrder = maxOrder + 1; String defaultName = "Assignment " + asgnOrder; if(assignmentNames.contains(defaultName)) { //Attempt to generate a unique name - but don't loop forever //Non-unique names are allowed, but a warning will be shown for(int defaultNameEnding = asgnOrder + 1; defaultNameEnding < 1000; defaultNameEnding++) { defaultName = "Assignment " + defaultNameEnding; if(assignmentNames.contains(defaultName)) { break; } } } //Create the assignment final DbAssignment asgn = new DbAssignment(defaultName, asgnOrder); //Add the assignment visually and to the database _assignmentList.getModel().addElement(asgn); _assignmentList.setSelectedValue(asgn); int listSize = _assignmentList.getModel().getSize(); listPane.getViewport().scrollRectToVisible(_assignmentList.getCellBounds(listSize - 1, listSize)); //Add the assignment on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(ImmutableSet.of(asgn)); } @Override public String dbFailureMessage() { return "Unable to add assignment: " + asgn.getName(); } }); } }); buttonPanel.add(addButton, BorderLayout.WEST); buttonPanel.add(Box.createHorizontalBox(), BorderLayout.CENTER); final JButton deleteButton = new JButton("Delete"); deleteButton.setEnabled(false); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final DbAssignment asgn = _assignmentList.getSelectedValue(); boolean proceed = ModalDialog.showConfirmation(_configManager, "Delete Assignment", "Deleting assignment " + asgn.getName() + " will delete all associated grades, " + "extensions, exemptions, and groups.", "Delete", "Cancel"); if(proceed) { //Remove the assignment from the visible list _assignmentList.getModel().removeElement(asgn); //Get a list of assignments that now have a new order as a result final Set<DbAssignment> reorderedAssignments = getReorderedAssignments(); //Delete the assignment on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeAssignments(ImmutableSet.of(asgn)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putAssignments(reorderedAssignments); } @Override public String dbFailureMessage() { return "Unable to delete assignment: " + asgn.getName(); } }); } } }); buttonPanel.add(deleteButton, BorderLayout.EAST); _assignmentList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent lse) { DbAssignment selectedAsgn = _assignmentList.getSelectedValue(); deleteButton.setEnabled(selectedAsgn != null); assignmentSelectionChanged(selectedAsgn); } }); } private void assignmentSelectionChanged(final DbAssignment selectedAsgn) { _selectedAssignmentPanel.removeAll(); _selectedAssignmentPanel.setLayout(new BorderLayout(0, 0)); if(selectedAsgn == null) { _selectedAssignmentPanel.add(FormattedLabel.asSubheader("No Assignment Selected").centerHorizontally(), BorderLayout.CENTER); } else { JPanel panel = _assignmentPanels.get(selectedAsgn); if(panel == null) { panel = new SelectedAssignmentPanel(selectedAsgn); _assignmentPanels.put(selectedAsgn, panel); } _selectedAssignmentPanel.add(panel, BorderLayout.CENTER); } //Force visual update to reflect these changes _selectedAssignmentPanel.repaint(); _selectedAssignmentPanel.revalidate(); } /** * Returns a list of the assignments in the DnDList whose visual order does not match the order stored in the * assignment object. * * @return */ private Set<DbAssignment> getReorderedAssignments() { Set<DbAssignment> reorderedAssignments = new HashSet<DbAssignment>(); List<DbAssignment> assignments = _assignmentList.getListData(); for(int i = 0; i < assignments.size(); i++) { DbAssignment asgn = assignments.get(i); if(asgn.getOrder() != i) { asgn.setOrder(i); reorderedAssignments.add(asgn); } } return reorderedAssignments; } private abstract class ReinitializeRunnable implements Runnable { public void run() { try { dbCall(); } catch(SQLException e) { reinitialize(e, dbFailureMessage()); } } public abstract void dbCall() throws SQLException; public abstract String dbFailureMessage(); } void reinitialize(final Throwable t, final String msg) { //Cancel everything and re-initialize _worker.cancel(WORKER_TAG); initialize(); ErrorReporter.report(msg, t); } private void initialize() { _worker.submit(null, new Runnable() { @Override public void run() { try { List<DbAssignment> assignments = new ArrayList<DbAssignment>(Allocator.getDatabase().getAssignments()); Collections.sort(assignments); final List<DbAssignment> sortedAssignments = ImmutableList.copyOf(assignments); EventQueue.invokeLater(new Runnable() { @Override public void run() { _assignmentPanels.clear(); _selectedAssignmentPanel.removeAll(); _assignmentList.setListData(sortedAssignments, true); if(_assignmentList.getSelectedValue() == null) { _assignmentList.selectFirst(); } //Force visual update to reflect these changes AssignmentPanel.this.repaint(); AssignmentPanel.this.revalidate(); } }); } catch(final SQLException e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { _assignmentPanels.clear(); _selectedAssignmentPanel.removeAll(); _assignmentList.clearListData(); //Force visual update to reflect these changes AssignmentPanel.this.repaint(); AssignmentPanel.this.revalidate(); ErrorReporter.report(e); } }); } } }); } private class SelectedAssignmentPanel extends JPanel { private final DbAssignment _asgn; private final ValidatingTextField _asgnNameField; private final JCheckBox _hasGroupsCheckBox; private final Map<DbGradableEvent, GradableEventPanel> _gradableEventPanels = new HashMap<DbGradableEvent, GradableEventPanel>(); private final JPanel _gradableEventsPanel; private final JButton _addGradableEventButton; SelectedAssignmentPanel(DbAssignment selectedAsgn) { _asgn = selectedAsgn; this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); //Assignment name _asgnNameField = new ValidatingTextField() { @Override protected String getDbValue() { return _asgn.getName(); } @Override protected ValidationResult validate(String value) { ValidationResult result = ValidationResult.NO_ISSUE; if(value.isEmpty()) { result = ValidationResult.TEXT_EMPTY; } else { //TODO: Make this more efficient boolean uniqueName = true; for(DbAssignment asgn : _assignmentList.getListData()) { if(asgn != _asgn && asgn.getName().equals(value)) { uniqueName = false; break; } } if(!uniqueName) { result = new ValidationResult(ValidationResult.ValidationState.WARNING, value + " is not " + "a unique assignment name"); } } return result; } @Override protected void applyChange(final String newValue) { _asgn.setName(newValue); _worker.submit(WORKER_TAG, new AssignmentRunnable()); } }; _asgnNameField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void modificationOccurred(DocumentEvent de) { _asgnDisplayName.put(_asgn, _asgnNameField.getText()); _assignmentList.refreshList(); } }); _asgnNameField.setMaximumSize(new Dimension(Short.MAX_VALUE, 25)); _asgnNameField.setAlignmentX(LEFT_ALIGNMENT); this.add(_asgnNameField); //Has groups _hasGroupsCheckBox = new JCheckBox("Group Assignment", _asgn.hasGroups()); _hasGroupsCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { boolean selected = _hasGroupsCheckBox.isSelected(); boolean proceed = ModalDialog.showConfirmation(_configManager, "Change Groups", "Changing whether this assignment has groups will delete all grades, extensions, and " + "exemptions for this assignment.", "Change", "Cancel"); if(proceed) { _asgn.setHasGroups(selected); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(ImmutableSet.of(_asgn)); Allocator.getDatabase().removeGroups(Allocator.getDatabase().getGroups(_asgn.getId())); } @Override public String dbFailureMessage() { return "Unable to change whether assignment " + _asgn.getName() + " has groups"; } }); } else { _hasGroupsCheckBox.setSelected(!selected); } } }); _hasGroupsCheckBox.setAlignmentX(LEFT_ALIGNMENT); this.add(_hasGroupsCheckBox); this.add(Box.createVerticalStrut(10)); JLabel gradableEventsLabel = FormattedLabel.asSubheader("Gradable Events"); gradableEventsLabel.setToolTipText("A gradable event represents a gradable product of work done by a " + "group of one or more students. This could be, but is not limited to, paper handins, digital " + "handins, labs, design checks, and exams."); this.add(gradableEventsLabel); _addGradableEventButton = new JButton("Add Gradable Event"); _addGradableEventButton.setAlignmentX(LEFT_ALIGNMENT); _addGradableEventButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new gradable event int maxOrder = -1; HashSet<String> geNames = new HashSet<String>(); for(DbGradableEvent ge : _asgn.getGradableEvents()) { maxOrder = Math.max(maxOrder, ge.getOrder()); geNames.add(ge.getName()); } int geOrder = maxOrder + 1; String defaultName = "Gradable Event " + geOrder; if(geNames.contains(defaultName)) { //Attempt to generate a unique name - but don't loop forever //Non-unique names are allowed, but a warning will be shown for(int defaultNameEnding = geOrder + 1; defaultNameEnding < 1000; defaultNameEnding++) { defaultName = "Gradable Event " + defaultNameEnding; if(!geNames.contains(defaultName)) { break; } } } final DbGradableEvent gradableEvent = DbGradableEvent.build(_asgn, defaultName, geOrder); GradableEventPanel panel = new GradableEventPanel(SelectedAssignmentPanel.this, gradableEvent); _gradableEventPanels.put(gradableEvent, panel); updateDisplayedGradableEventPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to insert or update " + gradableEvent.getName() + " into the database"; } }); } }); _gradableEventsPanel = new FixedWidthJPanel(); _gradableEventsPanel.setLayout(new BoxLayout(_gradableEventsPanel, BoxLayout.Y_AXIS)); JScrollPane scrollPane = new JScrollPane(_gradableEventsPanel); scrollPane.setBorder(null); this.add(scrollPane); scrollPane.setAlignmentX(LEFT_ALIGNMENT); List<DbGradableEvent> gradableEvents = new ArrayList<DbGradableEvent>(_asgn.getGradableEvents()); Collections.sort(gradableEvents); for(DbGradableEvent gradableEvent : gradableEvents) { GradableEventPanel panel = new GradableEventPanel(this, gradableEvent); _gradableEventPanels.put(gradableEvent, panel); } this.updateDisplayedGradableEventPanels(); } void updateDisplayedGradableEventPanels() { _gradableEventsPanel.removeAll(); List<DbGradableEvent> gradableEvents = new ArrayList<DbGradableEvent>(_asgn.getGradableEvents()); Collections.sort(gradableEvents); for(DbGradableEvent event : gradableEvents) { GradableEventPanel panel = _gradableEventPanels.get(event); _gradableEventsPanel.add(panel); _gradableEventsPanel.add(Box.createVerticalStrut(5)); panel.reorderOccurred(); } JPanel addPanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); addPanel.add(_addGradableEventButton, BorderLayout.CENTER); _gradableEventsPanel.add(addPanel); //Force visual update to reflect these changes _gradableEventsPanel.repaint(); _gradableEventsPanel.revalidate(); } private class AssignmentRunnable extends ReinitializeRunnable { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(ImmutableSet.of(_asgn)); } @Override public String dbFailureMessage() { return "Unable to insert or update assignment " + _asgn.getName(); } } } private class GradableEventPanel extends PreferredHeightJPanel { private final DbGradableEvent _gradableEvent; private final JButton _upButton, _downButton, _addPartButton; private final ValidatingTextField _nameField, _directoryField; private final SelectedAssignmentPanel _asgnPanel; private final Map<DbPart, PartPanel> _partPanels = new HashMap<DbPart, PartPanel>(); private final JPanel _partsPanel; GradableEventPanel(SelectedAssignmentPanel asgnPanel, DbGradableEvent gradableEvent) { _asgnPanel = asgnPanel; _gradableEvent = gradableEvent; this.setBackground(new Color(225, 225, 225)); this.setBorder(BorderFactory.createEtchedBorder()); this.setLayout(new BorderLayout(0, 0)); JPanel contentPanel = new JPanel(); contentPanel.setBackground(this.getBackground()); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); this.add(new PaddingPanel(contentPanel, 5, this.getBackground()), BorderLayout.CENTER); JPanel headlinePanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); headlinePanel.setAlignmentX(LEFT_ALIGNMENT); headlinePanel.setBackground(this.getBackground()); contentPanel.add(headlinePanel); JPanel controlPanel = new JPanel(); controlPanel.setBackground(this.getBackground()); headlinePanel.add(controlPanel, BorderLayout.EAST); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); controlPanel.add(Box.createHorizontalStrut(3)); _upButton = new JButton("↑"); _upButton.setToolTipText("Move up"); _upButton.setMargin(new Insets(1, 1, 1, 1)); _upButton.setEnabled(false); _upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setOrder(_gradableEvent.getOrder() - 1); ImmutableSet.Builder<DbGradableEvent> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_gradableEvent); for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(event != _gradableEvent && event.getOrder() == _gradableEvent.getOrder()) { event.setOrder(event.getOrder() + 1); reorderedBuilder.add(event); } } final ImmutableSet<DbGradableEvent> reorderedEvents = reorderedBuilder.build(); _asgnPanel.updateDisplayedGradableEventPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(reorderedEvents); } @Override public String dbFailureMessage() { return "Unable to reorder gradable event: " + _gradableEvent.getName(); } }); } }); controlPanel.add(_upButton); controlPanel.add(Box.createHorizontalStrut(3)); _downButton = new JButton("↓"); _downButton.setToolTipText("Move down"); _downButton.setMargin(new Insets(1, 1, 1, 1)); _downButton.setEnabled(false); _downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setOrder(_gradableEvent.getOrder() + 1); ImmutableSet.Builder<DbGradableEvent> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_gradableEvent); for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(event != _gradableEvent && event.getOrder() == _gradableEvent.getOrder()) { event.setOrder(event.getOrder() - 1); reorderedBuilder.add(event); } } final ImmutableSet<DbGradableEvent> reorderedEvents = reorderedBuilder.build(); _asgnPanel.updateDisplayedGradableEventPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(reorderedEvents); } @Override public String dbFailureMessage() { return "Unable to reorder gradable event: " + _gradableEvent.getName(); } }); } }); controlPanel.add(_downButton); this.reorderOccurred(); controlPanel.add(Box.createHorizontalStrut(3)); JButton deleteButton = new JButton("✗"); deleteButton.setToolTipText("Delete"); deleteButton.setMargin(new Insets(1, 1, 1, 1)); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { boolean proceed = ModalDialog.showConfirmation(_configManager, "Delete Gradable Event", "Deleting this Gradable Event will delete all grades, extensions and exemptions for this " + "Gradable Event.", "Delete", "Cancel"); if(proceed) { _asgnPanel._asgn.removeGradableEvent(_gradableEvent); ImmutableSet.Builder<DbGradableEvent> reorderedBuilder = ImmutableSet.builder(); for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(event.getOrder() > _gradableEvent.getOrder()) { event.setOrder(event.getOrder() - 1); reorderedBuilder.add(event); } } final ImmutableSet<DbGradableEvent> reorderedEvents = reorderedBuilder.build(); //Force visual update to reflect these changes _asgnPanel.updateDisplayedGradableEventPanels(); //Delete the gradable event and reordered others on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeGradableEvents(ImmutableSet.of(_gradableEvent)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putGradableEvents(reorderedEvents); } @Override public String dbFailureMessage() { return "Unable to delete gradable event: " + _gradableEvent.getName(); } }); } } }); controlPanel.add(deleteButton); _nameField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getName(); } @Override protected ValidationResult validate(String value) { return ValidationResult.validateNotEmpty(value); } @Override protected void applyChange(String newValue) { _gradableEvent.setName(newValue); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(_gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to insert or update " + _gradableEvent.getName(); } }); } }; headlinePanel.add(_nameField, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(10)); contentPanel.add(FormattedLabel.asSubheader("Deadlines")); JPanel deadlinePanel = new DeadlinePanel(this.getBackground()); deadlinePanel.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(deadlinePanel); contentPanel.add(Box.createVerticalStrut(10)); JLabel directoryLabel = FormattedLabel.asSubheader("Digital Handin Directory"); directoryLabel.setToolTipText("This directory will be searched recursively for digital handins"); contentPanel.add(directoryLabel); _directoryField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getDirectory() == null ? "" : _gradableEvent.getDirectory().getAbsolutePath(); } @Override protected ValidationResult validate(String value) { ValidationResult result = ValidationResult.NO_ISSUE; if(!value.isEmpty()) { File file = new File(value); if(!file.exists()) { result = new ValidationResult(ValidationState.WARNING, "Specified directory does not exist"); } else { if(file.isFile()) { result = new ValidationResult(ValidationState.WARNING, "Specified directory is a file"); } else if(!file.canExecute()) { result = new ValidationResult(ValidationState.WARNING, "Cannot read contents of specified directory"); } } } return result; } @Override protected void applyChange(String newValue) { String currValue = _gradableEvent.getDirectory() == null ? "" : _gradableEvent.getDirectory().getAbsolutePath(); if(!newValue.equals(currValue)) { if(newValue.isEmpty()) { _gradableEvent.setDirectory(null); } else { _gradableEvent.setDirectory(new File(newValue)); } _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(_gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to insert or update " + _gradableEvent.getName(); } }); } } }; _directoryField.setAlignmentX(LEFT_ALIGNMENT); _directoryField.setMaximumSize(new Dimension(Short.MAX_VALUE, 25)); contentPanel.add(_directoryField); contentPanel.add(Box.createVerticalStrut(10)); JLabel partsLabel = FormattedLabel.asSubheader("Parts"); partsLabel.setToolTipText("A Part is an arbitrary portion of a Gradable Event that can be assigned to a TA"); contentPanel.add(partsLabel); _addPartButton = new JButton("Add Part"); _addPartButton.setAlignmentX(LEFT_ALIGNMENT); _addPartButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new part int maxOrder = -1; HashSet<String> partNames = new HashSet<String>(); for(DbPart part : _gradableEvent.getParts()) { maxOrder = Math.max(maxOrder, part.getOrder()); partNames.add(part.getName()); } int partOrder = maxOrder + 1; String defaultName = "Part " + partOrder; if(partNames.contains(defaultName)) { //Attempt to generate a unique name - but don't loop forever; Non-unique names are allowed for(int defaultNameEnding = partOrder + 1; defaultNameEnding < 1000; defaultNameEnding++) { defaultName = "Part " + defaultNameEnding; if(!partNames.contains(defaultName)) { break; } } } final DbPart part = DbPart.build(_gradableEvent, defaultName, partOrder); PartPanel panel = new PartPanel(GradableEventPanel.this, part); _partPanels.put(part, panel); updateDisplayedPartPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(ImmutableSet.of(part)); } @Override public String dbFailureMessage() { return "Unable to update or insert part " + part.getName(); } }); } }); _partsPanel = new JPanel(); _partsPanel.setBackground(this.getBackground()); _partsPanel.setLayout(new BoxLayout(_partsPanel, BoxLayout.Y_AXIS)); _partsPanel.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(_partsPanel); List<DbPart> parts = new ArrayList<DbPart>(_gradableEvent.getParts()); Collections.sort(parts); for(DbPart part : parts) { PartPanel panel = new PartPanel(this, part); _partPanels.put(part, panel); } this.updateDisplayedPartPanels(); } void reorderOccurred() { _upButton.setEnabled(_gradableEvent.getOrder() != 0); boolean isLastGradableEvent = true; for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(_gradableEvent.getOrder() < event.getOrder()) { isLastGradableEvent = false; break; } } _downButton.setEnabled(!isLastGradableEvent); } void updateDisplayedPartPanels() { _partsPanel.removeAll(); List<DbPart> parts = new ArrayList<DbPart>(_gradableEvent.getParts()); Collections.sort(parts); for(DbPart part : parts) { PartPanel panel = _partPanels.get(part); _partsPanel.add(panel); _partsPanel.add(Box.createVerticalStrut(5)); panel.reorderOccurred(); } JPanel addPanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); addPanel.add(_addPartButton, BorderLayout.CENTER); _partsPanel.add(addPanel); //Force visual update to reflect these changes _partsPanel.repaint(); _partsPanel.revalidate(); } private class DeadlinePanel extends PreferredHeightJPanel { private final DateTimeControl _earlyDateControl, _onTimeDateControl, _lateDateControl; private final ValidatingTextField _earlyPointsField, _latePointsField; private final PeriodControl _latePeriodControl; private DeadlinePanel(Color backgroundColor) { this.setBackground(backgroundColor); //Dates _earlyDateControl = new DateTimeControl(_gradableEvent.getEarlyDate()); _earlyDateControl.setBackground(backgroundColor); _earlyDateControl.addDateTimeChangeListener(new DateTimeControl.DateTimeChangeListener() { @Override public void dateTimeChanged(DateTime prevDateTime, DateTime newDateTime) { _gradableEvent.setEarlyDate(newDateTime); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); _onTimeDateControl = new DateTimeControl(_gradableEvent.getOnTimeDate()); _onTimeDateControl.setBackground(backgroundColor); _onTimeDateControl.addDateTimeChangeListener(new DateTimeControl.DateTimeChangeListener() { @Override public void dateTimeChanged(DateTime prevDateTime, DateTime newDateTime) { _gradableEvent.setOnTimeDate(newDateTime); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); _lateDateControl = new DateTimeControl(_gradableEvent.getLateDate()); _lateDateControl.setBackground(backgroundColor); _lateDateControl.addDateTimeChangeListener(new DateTimeControl.DateTimeChangeListener() { @Override public void dateTimeChanged(DateTime prevDateTime, DateTime newDateTime) { _gradableEvent.setLateDate(newDateTime); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); //Points _earlyPointsField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getEarlyPoints() == null ? "" : (_gradableEvent.getEarlyPoints() + ""); } @Override protected void applyChange(String newValue) { _gradableEvent.setEarlyPoints(newValue.isEmpty() ? null : Double.parseDouble(newValue)); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } @Override protected ValidationResult validate(String value) { ValidationResult result; if(this.isEnabled()) { try { double numericValue = Double.parseDouble(value); if(numericValue == 0.0D) { result = new ValidationResult(ValidationState.WARNING, "No bonus given"); } else if(numericValue < 0D) { result = new ValidationResult(ValidationState.WARNING, "Bonus is negative. " + "Student work will lose points for being early."); } else { result = ValidationResult.NO_ISSUE; } } catch(NumberFormatException e) { result = new ValidationResult(ValidationState.ERROR, "Numerical value not provided"); } } else { result = ValidationResult.NO_VALIDATION; } return result; } }; _earlyPointsField.setColumns(5); _latePointsField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getLatePoints() == null ? "" : (_gradableEvent.getLatePoints() + ""); } @Override protected void applyChange(String newValue) { _gradableEvent.setLatePoints(newValue.isEmpty() ? null : Double.parseDouble(newValue)); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } @Override protected ValidationResult validate(String value) { ValidationResult result; if(this.isEnabled()) { try { double numericValue = Double.parseDouble(value); if(numericValue == 0.0D) { result = new ValidationResult(ValidationState.WARNING, "No penalty given"); } else if(numericValue > 0D) { result = new ValidationResult(ValidationState.WARNING, "Penalty is positive. " + "Student work will gain points for being late."); } else { result = ValidationResult.NO_ISSUE; } } catch(NumberFormatException e) { result = new ValidationResult(ValidationState.ERROR, "Numerical value not provided"); } } else { result = ValidationResult.NO_VALIDATION; } return result; } }; _latePointsField.setColumns(5); //Period _latePeriodControl = new PeriodControl(_gradableEvent.getLatePeriod()); _latePeriodControl.setBackground(backgroundColor); _latePeriodControl.addPeriodChangeListener(new PeriodControl.PeriodChangeListener() { @Override public void periodChanged(Period prevPeriod, Period newPeriod) { _gradableEvent.setLatePeriod(newPeriod); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); this.displayDeadlineInfo(); } private class RemoveDeadlinesActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setDeadlineType(DeadlineInfo.Type.NONE); _gradableEvent.setEarlyDate(null); _gradableEvent.setOnTimeDate(null); _gradableEvent.setLateDate(null); _gradableEvent.setEarlyPoints(null); _gradableEvent.setLatePoints(null); _gradableEvent.setLatePeriod(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); displayDeadlineInfo(); } } private void displayDeadlineInfo() { this.removeAll(); _earlyDateControl.setDateTime(_gradableEvent.getEarlyDate(), true); _onTimeDateControl.setDateTime(_gradableEvent.getOnTimeDate(), true); _lateDateControl.setDateTime(_gradableEvent.getLateDate(), true); _latePeriodControl.setPeriod(_gradableEvent.getLatePeriod(), true); DeadlineInfo.Type deadlineType = _gradableEvent.getDeadlineType(); if(deadlineType == DeadlineInfo.Type.FIXED) { this.setLayout(new BorderLayout(0, 0)); //Controls for the fixed deadlines JPanel controlsPanel = new JPanel(); controlsPanel.setBackground(this.getBackground()); this.add(controlsPanel, BorderLayout.CENTER); controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.Y_AXIS)); //Early boolean hasEarly = _earlyDateControl.getDateTime() != null; final JCheckBox earlyCheckBox = new JCheckBox("Early", hasEarly); earlyCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(earlyCheckBox.isSelected()) { DateTime earlyDate = _onTimeDateControl.getDateTime().minusDays(2); _gradableEvent.setEarlyDate(earlyDate); _gradableEvent.setEarlyPoints(0D); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _earlyDateControl.setDateTime(earlyDate, true); _earlyPointsField.setEnabled(true); _earlyPointsField.setText("0"); } else { _gradableEvent.setEarlyDate(null); _gradableEvent.setEarlyPoints(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _earlyDateControl.setDateTime(null, true); _earlyPointsField.setEnabled(false); _earlyPointsField.setText(""); } } }); earlyCheckBox.setBackground(this.getBackground()); earlyCheckBox.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(earlyCheckBox); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _earlyDateControl)); controlsPanel.add(Box.createVerticalStrut(3)); _earlyPointsField.setEnabled(hasEarly); _earlyPointsField.setTextToDbValue(); controlsPanel.add(createDeadlineComponentPanel("Bonus Points: ", _earlyPointsField)); controlsPanel.add(Box.createVerticalStrut(5)); //On Time controlsPanel.add(FormattedLabel.asContent("On Time")); _onTimeDateControl.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _onTimeDateControl)); controlsPanel.add(Box.createVerticalStrut(5)); //Late boolean hasLate = _lateDateControl.getDateTime() != null; final JCheckBox lateCheckBox = new JCheckBox("Late", hasLate); lateCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(lateCheckBox.isSelected()) { DateTime lateDate = _onTimeDateControl.getDateTime().plusDays(2); _gradableEvent.setLateDate(lateDate); _gradableEvent.setLatePoints(0D); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(lateDate, true); _latePointsField.setEnabled(true); _latePointsField.setText("0"); } else { _gradableEvent.setLateDate(null); _gradableEvent.setLatePoints(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(null, true); _latePointsField.setEnabled(false); _latePointsField.setText(""); } } }); lateCheckBox.setBackground(this.getBackground()); lateCheckBox.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(lateCheckBox); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _lateDateControl)); controlsPanel.add(Box.createVerticalStrut(3)); _latePointsField.setEnabled(hasLate); _latePointsField.setTextToDbValue(); controlsPanel.add(createDeadlineComponentPanel("Penalty Points: ", _latePointsField)); //Remove deadlines JPanel removePanel = new JPanel(); removePanel.setBackground(this.getBackground()); this.add(removePanel, BorderLayout.SOUTH); JButton removeButton = new JButton("Remove Deadlines"); removeButton.setAlignmentX(CENTER_ALIGNMENT); removeButton.addActionListener(new RemoveDeadlinesActionListener()); removePanel.add(removeButton); } else if(deadlineType == DeadlineInfo.Type.VARIABLE) { this.setLayout(new BorderLayout(0, 0)); //Controls for the variable deadlines JPanel controlsPanel = new JPanel(); controlsPanel.setBackground(this.getBackground()); this.add(controlsPanel, BorderLayout.CENTER); controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.Y_AXIS)); //On Time controlsPanel.add(FormattedLabel.asContent("On Time")); _onTimeDateControl.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _onTimeDateControl)); controlsPanel.add(Box.createVerticalStrut(5)); //Deduction controlsPanel.add(FormattedLabel.asContent("Deduction")); _latePeriodControl.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(createDeadlineComponentPanel("Period: ", _latePeriodControl)); controlsPanel.add(Box.createVerticalStrut(3)); _latePointsField.setAlignmentX(LEFT_ALIGNMENT); _latePointsField.setEnabled(true); _latePointsField.setTextToDbValue(); controlsPanel.add(createDeadlineComponentPanel("Penalty Points per Period: ", _latePointsField)); //Late boolean hasLate = _lateDateControl.getDateTime() != null; final JCheckBox lateCheckBox = new JCheckBox("Late", hasLate); lateCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(lateCheckBox.isSelected()) { Period period = _latePeriodControl.getPeriod(); DateTime lateDate = _onTimeDateControl.getDateTime().plus(period).plus(period); _gradableEvent.setLateDate(lateDate); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(lateDate, true); } else { _gradableEvent.setLateDate(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(null, true); } } }); lateCheckBox.setBackground(this.getBackground()); lateCheckBox.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(lateCheckBox); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _lateDateControl)); controlsPanel.add(Box.createVerticalStrut(3)); //Remove deadlines JPanel removePanel = new JPanel(); removePanel.setBackground(this.getBackground()); this.add(removePanel, BorderLayout.SOUTH); JButton removeButton = new JButton("Remove Deadlines"); removeButton.setAlignmentX(CENTER_ALIGNMENT); removeButton.addActionListener(new RemoveDeadlinesActionListener()); removePanel.add(removeButton); } else { this.setLayout(new GridLayout(1, 2, 3, 0)); JButton fixedButton = new JButton("Add Fixed Deadlines"); fixedButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setDeadlineType(DeadlineInfo.Type.FIXED); _gradableEvent.setOnTimeDate(new DateTime()); _worker.submit(WORKER_TAG, new DeadlineRunnable()); displayDeadlineInfo(); } }); this.add(fixedButton); JButton variableButton = new JButton("Add Variable Deadlines"); variableButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setDeadlineType(DeadlineInfo.Type.VARIABLE); _gradableEvent.setOnTimeDate(new DateTime()); _gradableEvent.setLatePeriod(new Period(0, 0, 0, 1, 0, 0, 0, 0)); _gradableEvent.setLatePoints(0D); _worker.submit(WORKER_TAG, new DeadlineRunnable()); displayDeadlineInfo(); } }); this.add(variableButton); } //Force visual update to reflect these changes this.repaint(); this.revalidate(); } private JPanel createDeadlineComponentPanel(String labelText, Component component) { JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); panel.setBackground(this.getBackground()); panel.setAlignmentX(LEFT_ALIGNMENT); panel.add(Box.createHorizontalStrut(21)); panel.add(FormattedLabel.asContent(labelText)); panel.add(component); return panel; } private class DeadlineRunnable extends ReinitializeRunnable { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(_gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to save deadline information for gradable event " + _gradableEvent.getName(); } } } } private class PartPanel extends PreferredHeightJPanel { private final GradableEventPanel _gePanel; private final DbPart _part; private final JButton _upButton, _downButton; private final ValidatingTextField _nameField, _quickNameField; private final JButton _gradingSheetButton; private final Map<DbAction, ActionPanel> _actionPanels = new HashMap<DbAction, ActionPanel>(); private final JPanel _actionsPanel; private final JButton _addActionButton; private PartPanel(GradableEventPanel gePanel, DbPart part) { _gePanel = gePanel; _part = part; this.setBackground(new Color(212, 212, 212)); this.setBorder(BorderFactory.createEtchedBorder()); this.setLayout(new BorderLayout(0, 0)); JPanel contentPanel = new JPanel(); contentPanel.setBackground(this.getBackground()); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); this.add(new PaddingPanel(contentPanel, 5, this.getBackground()), BorderLayout.CENTER); JPanel headlinePanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); headlinePanel.setAlignmentX(LEFT_ALIGNMENT); headlinePanel.setBackground(this.getBackground()); contentPanel.add(headlinePanel); JPanel controlPanel = new JPanel(); controlPanel.setBackground(this.getBackground()); headlinePanel.add(controlPanel, BorderLayout.EAST); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); controlPanel.add(Box.createHorizontalStrut(3)); _upButton = new JButton("↑"); _upButton.setToolTipText("Move up"); _upButton.setMargin(new Insets(1, 1, 1, 1)); _upButton.setEnabled(false); _upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _part.setOrder(_part.getOrder() - 1); ImmutableSet.Builder<DbPart> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_part); for(DbPart part : _gePanel._gradableEvent.getParts()) { if(part != _part && part.getOrder() == _part.getOrder()) { part.setOrder(part.getOrder() + 1); reorderedBuilder.add(part); } } final ImmutableSet<DbPart> reorderedParts = reorderedBuilder.build(); _gePanel.updateDisplayedPartPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(reorderedParts); } @Override public String dbFailureMessage() { return "Unable to reorder part: " + _part.getName(); } }); } }); controlPanel.add(_upButton); controlPanel.add(Box.createHorizontalStrut(3)); _downButton = new JButton("↓"); _downButton.setToolTipText("Move down"); _downButton.setMargin(new Insets(1, 1, 1, 1)); _downButton.setEnabled(false); _downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _part.setOrder(_part.getOrder() + 1); ImmutableSet.Builder<DbPart> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_part); for(DbPart part : _gePanel._gradableEvent.getParts()) { if(_part != part && part.getOrder() == _part.getOrder()) { part.setOrder(part.getOrder() - 1); reorderedBuilder.add(part); } } final ImmutableSet<DbPart> reorderedParts = reorderedBuilder.build(); _gePanel.updateDisplayedPartPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(reorderedParts); } @Override public String dbFailureMessage() { return "Unable to reorder part: " + _part.getName(); } }); } }); controlPanel.add(_downButton); this.reorderOccurred(); controlPanel.add(Box.createHorizontalStrut(3)); JButton deleteButton = new JButton("✗"); deleteButton.setToolTipText("Delete"); deleteButton.setMargin(new Insets(1, 1, 1, 1)); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { boolean proceed = ModalDialog.showConfirmation(_configManager, "Delete Part", "Deleting this Part will delete all grades and distributions for this Part", "Delete", "Cancel"); if(proceed) { _gePanel._gradableEvent.removePart(_part); ImmutableSet.Builder<DbPart> reorderedBuilder = ImmutableSet.builder(); for(DbPart part : _gePanel._gradableEvent.getParts()) { if(part.getOrder() > _part.getOrder()) { part.setOrder(part.getOrder() - 1); reorderedBuilder.add(part); } } final ImmutableSet<DbPart> reorderedParts = reorderedBuilder.build(); _gePanel.updateDisplayedPartPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeParts(ImmutableSet.of(_part)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putParts(reorderedParts); } @Override public String dbFailureMessage() { return "Unable to delete part: " + _part.getName(); } }); } } }); controlPanel.add(deleteButton); _nameField = new ValidatingTextField() { @Override protected String getDbValue() { return _part.getName(); } @Override protected ValidationResult validate(String value) { return ValidationResult.validateNotEmpty(value); } @Override protected void applyChange(String newValue) { _part.setName(newValue); _worker.submit(WORKER_TAG, new PartRunnable()); } }; headlinePanel.add(_nameField, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(10)); JPanel combinedPanel = new JPanel(new GridLayout(1, 2, 3, 0)); combinedPanel.setAlignmentX(LEFT_ALIGNMENT); combinedPanel.setBackground(contentPanel.getBackground()); contentPanel.add(combinedPanel); JPanel gradingSheetPanel = new JPanel(new BorderLayout(0, 0)); gradingSheetPanel.setBackground(combinedPanel.getBackground()); combinedPanel.add(gradingSheetPanel); JLabel gradingSheetLabel = FormattedLabel.asSubheader("Grading Sheet"); gradingSheetLabel.setToolTipText("A grading sheet is filled out by TAs while grading a student"); gradingSheetPanel.add(gradingSheetLabel, BorderLayout.NORTH); _gradingSheetButton = new JButton("Edit Grading Sheet"); _gradingSheetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { _worker.blockOnQueuedTasks(); GradingSheetCreatorPanel gradingSheetCreator = new GradingSheetCreatorPanel(AssignmentPanel.this, _worker, _part); CloseAction closeAction = _configManager.hostModal(gradingSheetCreator); gradingSheetCreator.setCloseAction(closeAction); } catch(InterruptedException e) { ErrorReporter.report("Unable to show grading sheet creator due to failure to block on " + "queued tasks", e); } } }); gradingSheetPanel.add(_gradingSheetButton); JPanel quickNamePanel = new JPanel(new BorderLayout(0, 0)); quickNamePanel.setBackground(combinedPanel.getBackground()); combinedPanel.add(quickNamePanel); JLabel quickNameLabel = FormattedLabel.asSubheader("Quick Name"); quickNameLabel.setToolTipText("A unique name for the part that can be referenced from a shell script"); quickNamePanel.add(quickNameLabel, BorderLayout.NORTH); _quickNameField = new ValidatingTextField() { @Override protected String getDbValue() { return _part.getQuickName() == null ? "" : _part.getQuickName(); } @Override protected ValidationResult validate(String value) { ValidationResult result; //Allows a through z (upper and lower case), 0 through 9, and underscore Matcher matcher = Pattern.compile("[0-9a-zA-Z_]*").matcher(value); if(matcher.find() && (matcher.end() - matcher.start() == value.length())) { //TODO: Improve efficiency HashSet<String> quickNames = new HashSet<String>(); List<DbAssignment> asgns = _assignmentList.getListData(); for(DbAssignment asgn : asgns) { for(DbGradableEvent ge : asgn.getGradableEvents()) { for(DbPart part : ge.getParts()) { if(part != _part && part.getQuickName() != null) { quickNames.add(part.getQuickName()); } } } } if(quickNames.contains(value)) { result = new ValidationResult(ValidationState.ERROR, "This quick name is not unique"); } else { result = ValidationResult.NO_ISSUE; } } else { result = new ValidationResult(ValidationState.ERROR, "Only letters, numbers, and underscores " + "are allowed"); } return result; } @Override protected void applyChange(String newValue) { _part.setQuickName(newValue.isEmpty() ? null : newValue); _worker.submit(WORKER_TAG, new PartRunnable()); } }; quickNamePanel.add(_quickNameField, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(5)); JLabel actionsLabel = FormattedLabel.asSubheader("Actions"); actionsLabel.setToolTipText("An Action is a task performed for a part, which can include acting on a " + "digital handin"); contentPanel.add(actionsLabel); _addActionButton = new JButton("Add Action"); _addActionButton.setAlignmentX(LEFT_ALIGNMENT); _addActionButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new action int maxOrder = -1; HashSet<String> actionNames = new HashSet<String>(); for(DbAction action : _part.getActions()) { maxOrder = Math.max(maxOrder, action.getOrder()); actionNames.add(action.getName()); } int actionOrder = maxOrder + 1; String actionName; IconImage actionIcon; List<ActionDescription> availableSuggestedDescriptions = new ArrayList<ActionDescription>(); for(ActionDescription description : ActionDescription.getDefaultDescriptions()) { if(!actionNames.contains(description.getName())) { availableSuggestedDescriptions.add(description); } } if(availableSuggestedDescriptions.isEmpty()) { actionName = ActionDescription.CUSTOM.getName(); actionIcon = ActionDescription.CUSTOM.getIcon(); } else { ActionDescription description = availableSuggestedDescriptions.get(0); actionName = description.getName(); actionIcon = description.getIcon(); } final DbAction action = DbAction.build(_part, actionName, actionIcon, actionOrder); ActionPanel panel = new ActionPanel(PartPanel.this, action); _actionPanels.put(action, panel); updateDisplayedActionPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putActions(ImmutableSet.of(action)); } @Override public String dbFailureMessage() { return "Unable to update or insert action " + action.getName(); } }); } }); _actionsPanel = new JPanel(); _actionsPanel.setBackground(this.getBackground()); _actionsPanel.setLayout(new BoxLayout(_actionsPanel, BoxLayout.Y_AXIS)); _actionsPanel.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(_actionsPanel); List<DbAction> actions = new ArrayList<DbAction>(_part.getActions()); Collections.sort(actions); for(DbAction action : actions) { ActionPanel panel = new ActionPanel(this, action); _actionPanels.put(action, panel); } this.updateDisplayedActionPanels(); } void updateDisplayedActionPanels() { _actionsPanel.removeAll(); List<DbAction> actions = new ArrayList<DbAction>(_part.getActions()); Collections.sort(actions); for(DbAction action : actions) { ActionPanel panel = _actionPanels.get(action); _actionsPanel.add(panel); _actionsPanel.add(Box.createVerticalStrut(5)); panel.reorderOccurred(); } JPanel addPanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); addPanel.add(_addActionButton, BorderLayout.CENTER); _actionsPanel.add(addPanel); //Force visual update to reflect these changes _actionsPanel.repaint(); _actionsPanel.revalidate(); } void reorderOccurred() { _upButton.setEnabled(_part.getOrder() != 0); boolean isLastPart = true; for(DbPart part : _gePanel._gradableEvent.getParts()) { if(_part.getOrder() < part.getOrder()) { isLastPart = false; break; } } _downButton.setEnabled(!isLastPart); } private class PartRunnable extends ReinitializeRunnable { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(ImmutableSet.of(_part)); } @Override public String dbFailureMessage() { return "Unable to insert or update part " + _part.getName(); } } } private class ActionPanel extends JPanel { private final PartPanel _partPanel; private final DbAction _action; private final JButton _upButton, _downButton; private final JComboBox _iconComboBox; private final JComboBox _nameComboBox; private final GenericJComboBox<Task> _taskComboBox; private final JPanel _propertiesPanel; ActionPanel(PartPanel partPanel, DbAction action) { _partPanel = partPanel; _action = action; this.setBackground(new Color(200, 200, 200)); this.setBorder(BorderFactory.createEtchedBorder()); this.setLayout(new BorderLayout(0, 0)); JPanel contentPanel = new JPanel(); contentPanel.setBackground(this.getBackground()); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); this.add(new PaddingPanel(contentPanel, 5, this.getBackground()), BorderLayout.CENTER); JPanel headlinePanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); headlinePanel.setAlignmentX(LEFT_ALIGNMENT); headlinePanel.setBackground(this.getBackground()); contentPanel.add(headlinePanel); JPanel controlPanel = new JPanel(); controlPanel.setBackground(this.getBackground()); headlinePanel.add(controlPanel, BorderLayout.EAST); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); controlPanel.add(Box.createHorizontalStrut(3)); _upButton = new JButton("↑"); _upButton.setToolTipText("Move up"); _upButton.setMargin(new Insets(1, 1, 1, 1)); _upButton.setEnabled(false); _upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _action.setOrder(_action.getOrder() - 1); ImmutableSet.Builder<DbAction> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_action); for(DbAction action : _partPanel._part.getActions()) { if(action != _action && action.getOrder() == _action.getOrder()) { action.setOrder(action.getOrder() + 1); reorderedBuilder.add(action); } } final ImmutableSet<DbAction> reorderedActions = reorderedBuilder.build(); _partPanel.updateDisplayedActionPanels(); //Reorder actions on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putActions(reorderedActions); } @Override public String dbFailureMessage() { return "Unable to reorder action: " + _action.getName(); } }); } }); controlPanel.add(_upButton); controlPanel.add(Box.createHorizontalStrut(3)); _downButton = new JButton("↓"); _downButton.setToolTipText("Move down"); _downButton.setMargin(new Insets(1, 1, 1, 1)); _downButton.setEnabled(false); _downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _action.setOrder(_action.getOrder() + 1); ImmutableSet.Builder<DbAction> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_action); for(DbAction action : _partPanel._part.getActions()) { if(_action != action && action.getOrder() == _action.getOrder()) { action.setOrder(action.getOrder() - 1); reorderedBuilder.add(action); } } final ImmutableSet<DbAction> reorderedActions = reorderedBuilder.build(); _partPanel.updateDisplayedActionPanels(); //Reorder actions on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putActions(reorderedActions); } @Override public String dbFailureMessage() { return "Unable to reorder action: " + _action.getName(); } }); } }); controlPanel.add(_downButton); this.reorderOccurred(); controlPanel.add(Box.createHorizontalStrut(3)); JButton deleteButton = new JButton("✗"); deleteButton.setToolTipText("Delete"); deleteButton.setMargin(new Insets(1, 1, 1, 1)); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _partPanel._part.removeAction(_action); ImmutableSet.Builder<DbAction> reorderedBuilder = ImmutableSet.builder(); for(DbAction action : _partPanel._part.getActions()) { if(action.getOrder() > _action.getOrder()) { action.setOrder(action.getOrder() - 1); reorderedBuilder.add(action); } } final ImmutableSet<DbAction> reorderedActions = reorderedBuilder.build(); _partPanel.updateDisplayedActionPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeActions(ImmutableSet.of(_action)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putActions(reorderedActions); } @Override public String dbFailureMessage() { return "Unable to delete action: " + _action.getName(); } }); } }); controlPanel.add(deleteButton); JPanel nameAndIconPanel = new JPanel(new BorderLayout(0, 0)); nameAndIconPanel.setBackground(headlinePanel.getBackground()); headlinePanel.add(nameAndIconPanel, BorderLayout.CENTER); _iconComboBox = new JComboBox(IconImage.values()); _iconComboBox.setSelectedItem(_action.getIcon()); _iconComboBox.setPreferredSize(new Dimension(40, 25)); _iconComboBox.setRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Icon icon = null; if(value instanceof IconImage) { icon = IconLoader.loadIcon(IconSize.s16x16, (IconImage) value); } JLabel label = new JLabel("", icon, SwingConstants.LEFT); if(isSelected) { label.setBackground(list.getSelectionBackground()); label.setForeground(list.getSelectionForeground()); } else { label.setBackground(list.getBackground()); label.setForeground(list.getForeground()); } return label; } }); _iconComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final IconImage icon; //This should always be true, but check just in case if(_iconComboBox.getSelectedItem() instanceof IconImage) { icon = (IconImage) _iconComboBox.getSelectedItem(); } else { icon = null; } _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { _action.setIcon(icon); Allocator.getDatabase().putActions(ImmutableSet.of(_action)); } @Override public String dbFailureMessage() { return "Unable to modify action name: " + _action.getName(); } }); } }); nameAndIconPanel.add(_iconComboBox, BorderLayout.WEST); _nameComboBox = new JComboBox(ActionDescription.getDefaultDescriptions().toArray()); _nameComboBox.setEditable(true); _nameComboBox.setSelectedItem(_action.getName()); _nameComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final String name = _nameComboBox.getSelectedItem().toString(); if(_nameComboBox.getSelectedItem() instanceof ActionDescription) { ActionDescription description = (ActionDescription) _nameComboBox.getSelectedItem(); _iconComboBox.setSelectedItem(description.getIcon()); } _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { _action.setName(name); Allocator.getDatabase().putActions(ImmutableSet.of(_action)); } @Override public String dbFailureMessage() { return "Unable to modify action name from " + _action.getName() + " to " + name; } }); } }); nameAndIconPanel.add(_nameComboBox, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(10)); contentPanel.add(FormattedLabel.asHeader("Task")); final FormattedLabel digitalHandinRequiredLabel = FormattedLabel.asContent("This task requires a digital " + "handin to operate"); digitalHandinRequiredLabel.setVisible(false); final FormattedLabel taskDescriptionLabel = FormattedLabel.asContent("").usePlainFont(); JPanel propertyIndentPanel = new JPanel(); propertyIndentPanel.setBackground(contentPanel.getBackground()); _propertiesPanel = new JPanel(); _propertiesPanel.setBackground(propertyIndentPanel.getBackground()); _propertiesPanel.setLayout(new BoxLayout(_propertiesPanel, BoxLayout.Y_AXIS)); _taskComboBox = new GenericJComboBox<Task>(TaskRepository.getTasks().values(), new DescriptionProvider<Task>() { @Override public String getDisplayText(Task task) { String displayText = ""; if(task != null) { displayText = task.getFullName(); } return displayText; } @Override public String getToolTipText(Task task) { String toolTip = ""; if(task != null) { toolTip = task.getDescription(); } return toolTip; } }); Task task = TaskRepository.getTasks().get(_action.getTask()); _taskComboBox.setGenericSelectedItem(task); //If there is a task stored in the database, load up the properties if(task != null) { digitalHandinRequiredLabel.setVisible(task.requiresDigitalHandin()); taskDescriptionLabel.setText(task.getDescription()); //Required Set<DbActionProperty> requiredProperties = new HashSet<DbActionProperty>(); for(TaskProperty property : task.getRequiredProperties()) { for(DbActionProperty propertyValue : _action.getActionProperties()) { if(property.getName().equals(propertyValue.getKey())) { requiredProperties.add(propertyValue); } } } if(!task.getRequiredProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Required Properties", task.getRequiredProperties(), requiredProperties); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } //Optional Set<DbActionProperty> optionalProperties = new HashSet<DbActionProperty>(); for(TaskProperty property : task.getOptionalProperties()) { for(DbActionProperty propertyValue : _action.getActionProperties()) { if(property.getName().equals(propertyValue.getKey())) { optionalProperties.add(propertyValue); } } } if(!task.getOptionalProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Optional Properties", task.getOptionalProperties(), optionalProperties); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } } _taskComboBox.addSelectionListener(new SelectionListener<Task>() { @Override public void selectionPerformed(Task currTask, Task newTask, SelectionAction action) { _propertiesPanel.removeAll(); final String taskName; if(newTask == null) { taskName = null; digitalHandinRequiredLabel.setVisible(false); taskDescriptionLabel.setText("No task selected"); } else { taskName = newTask.getFullName(); digitalHandinRequiredLabel.setVisible(newTask.requiresDigitalHandin()); taskDescriptionLabel.setText(newTask.getDescription()); if(!newTask.getRequiredProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Required Properties", newTask.getRequiredProperties(), ImmutableSet.<DbActionProperty>of()); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } if(!newTask.getOptionalProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Optional Properties", newTask.getOptionalProperties(), ImmutableSet.<DbActionProperty>of()); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } } _propertiesPanel.repaint(); _propertiesPanel.revalidate(); //Remove the no longer valid properties, as they belong to a different task final Set<DbActionProperty> properties = ImmutableSet.copyOf(_action.getActionProperties()); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { _action.setTask(taskName); Allocator.getDatabase().putActions(ImmutableSet.of(_action)); Allocator.getDatabase().removeActionProperties(properties); } @Override public String dbFailureMessage() { return "Unable to set action's task to: " + taskName; } }); } }); _taskComboBox.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(_taskComboBox); contentPanel.add(digitalHandinRequiredLabel); contentPanel.add(taskDescriptionLabel); propertyIndentPanel.setAlignmentX(LEFT_ALIGNMENT); propertyIndentPanel.setLayout(new BoxLayout(propertyIndentPanel, BoxLayout.X_AXIS)); propertyIndentPanel.add(Box.createHorizontalStrut(10)); propertyIndentPanel.add(_propertiesPanel); contentPanel.add(propertyIndentPanel); } private class PropertiesPanel extends JPanel { PropertiesPanel(String title, Set<TaskProperty> properties, Set<DbActionProperty> propertiesValues) { this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.add(FormattedLabel.asSubheader(title)); for(final TaskProperty property : properties) { this.add(Box.createVerticalStrut(3)); this.add(FormattedLabel.asContent(property.getName())); this.add(FormattedLabel.asContent(property.getDescription().replaceAll("\n", "<br/>")) .usePlainFont()); //Find the existing value in the database, if it does not exist - make one DbActionProperty propertyValue = null; for(DbActionProperty value : propertiesValues) { if(property.getName().equals(value.getKey())) { propertyValue = value; } } if(propertyValue == null) { propertyValue = DbActionProperty.build(_action, property.getName()); } final DbActionProperty dbPropertyValue = propertyValue; ValidatingTextField propertyField = new ValidatingTextField() { @Override protected String getDbValue() { return dbPropertyValue.getValue() == null ? "" : dbPropertyValue.getValue(); } @Override protected ValidationResult validate(String value) { ValidationResult result = ValidationResult.NO_VALIDATION; if(property.isRequired() && (value == null || value.isEmpty())) { result = new ValidationResult(ValidationState.ERROR, "This property is required"); } return result; } @Override protected void applyChange(final String newValue) { dbPropertyValue.setValue(newValue); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { if(newValue == null || newValue.isEmpty()) { Allocator.getDatabase().removeActionProperties( ImmutableSet.of(dbPropertyValue)); } else { Allocator.getDatabase().putActionProperties(ImmutableSet.of(dbPropertyValue)); } } @Override public String dbFailureMessage() { return "Unable to update property: " + property.getName(); } }); } }; propertyField.setAlignmentX(LEFT_ALIGNMENT); this.add(propertyField); } } } void reorderOccurred() { _upButton.setEnabled(_action.getOrder() != 0); boolean isLastAction = true; for(DbAction action : _partPanel._part.getActions()) { if(_action.getOrder() < action.getOrder()) { isLastAction = false; break; } } _downButton.setEnabled(!isLastAction); } } }
UTF-8
Java
112,338
java
AssignmentPanel.java
Java
[ { "context": "ectionListener.SelectionAction;\n\n/**\n *\n * @author jak2\n */\nclass AssignmentPanel extends JPanel\n{\n st", "end": 2725, "score": 0.9994943737983704, "start": 2721, "tag": "USERNAME", "value": "jak2" } ]
null
[]
package cakehat.views.config; import cakehat.Allocator; import cakehat.database.DbAction; import cakehat.database.DbActionProperty; import cakehat.database.DbAssignment; import cakehat.database.DbGradableEvent; import cakehat.database.DbPart; import cakehat.assignment.ActionDescription; import cakehat.assignment.DeadlineInfo; import cakehat.assignment.Task; import cakehat.assignment.TaskProperty; import cakehat.assignment.TaskRepository; import cakehat.logging.ErrorReporter; import cakehat.views.config.ValidationResult.ValidationState; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.sql.SQLException; 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.Set; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.joda.time.DateTime; import org.joda.time.Period; import support.resources.icons.IconLoader; import support.resources.icons.IconLoader.IconImage; import support.resources.icons.IconLoader.IconSize; import support.ui.DateTimeControl; import support.ui.DescriptionProvider; import support.ui.DocumentAdapter; import support.ui.DnDList; import support.ui.DnDListener; import support.ui.FixedWidthJPanel; import support.ui.FormattedLabel; import support.ui.GenericJComboBox; import support.ui.ModalDialog; import support.ui.ModalJFrameHostHelper.CloseAction; import support.ui.PaddingPanel; import support.ui.PartialDescriptionProvider; import support.ui.PeriodControl; import support.ui.PreferredHeightJPanel; import support.ui.SelectionListener; import support.ui.SelectionListener.SelectionAction; /** * * @author jak2 */ class AssignmentPanel extends JPanel { static final String WORKER_TAG = "ASSIGNMENT"; private final ConfigManagerView _configManager; private final UniqueElementSingleThreadWorker _worker; private final DnDList<DbAssignment> _assignmentList; private final JPanel _selectedAssignmentPanel; private final Map<DbAssignment, JPanel> _assignmentPanels = new WeakHashMap<DbAssignment, JPanel>(); /** * A map of {@link DbAssignment} objects to the currently user supplied name. This is not necessarily the name * stored in the DbAssignment object. It will be different if the user is currently modifying the input field for * the assignment. */ private final ConcurrentMap<DbAssignment, String> _asgnDisplayName = new ConcurrentHashMap<DbAssignment, String>(); public AssignmentPanel(ConfigManagerView configManager, UniqueElementSingleThreadWorker worker) { _configManager = configManager; _worker = worker; this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); _assignmentList = new DnDList<DbAssignment>(); this.setupAssignmentList(); this.add(Box.createHorizontalStrut(5)); _selectedAssignmentPanel = new JPanel(); this.add(_selectedAssignmentPanel); this.initialize(); } private void setupAssignmentList() { _assignmentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); _assignmentList.addDnDSource(_assignmentList); _assignmentList.setDescriptionProvider(new PartialDescriptionProvider<DbAssignment>() { @Override public String getDisplayText(DbAssignment asgn) { String name = _asgnDisplayName.get(asgn); if(name == null) { name = asgn.getName(); } //A blank string will result in the cell being given an abnormally short height - so use a space instead if(name.isEmpty()) { name = " "; } return name; } }); _assignmentList.addDnDListener(new DnDListener<DbAssignment>() { @Override public void valuesAdded(Map<Integer, DbAssignment> added) { } @Override public void valuesRemoved(List<DbAssignment> removed) { } @Override public void valuesReordered(Map<Integer, DbAssignment> values) { final Set<DbAssignment> reorderedAssignments = getReorderedAssignments(); if(!reorderedAssignments.isEmpty()) { _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(reorderedAssignments); } @Override public String dbFailureMessage() { return "Unable to reorder assignments"; } }); } } }); JPanel listPanel = new JPanel(new BorderLayout(0, 0)); listPanel.setMinimumSize(new Dimension(180, Short.MIN_VALUE)); listPanel.setPreferredSize(new Dimension(180, Short.MAX_VALUE)); listPanel.setMaximumSize(new Dimension(180, Short.MAX_VALUE)); this.add(listPanel); final JScrollPane listPane = new JScrollPane(_assignmentList); listPanel.add(listPane, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(new BorderLayout(0, 0)); buttonPanel.add(Box.createVerticalStrut(5), BorderLayout.NORTH); listPanel.add(buttonPanel, BorderLayout.SOUTH); JButton addButton = new JButton("Add"); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new assignment int maxOrder = -1; HashSet<String> assignmentNames = new HashSet<String>(); List<DbAssignment> assignments = _assignmentList.getListData(); for(DbAssignment asgn : assignments) { maxOrder = Math.max(maxOrder, asgn.getOrder()); assignmentNames.add(asgn.getName()); } int asgnOrder = maxOrder + 1; String defaultName = "Assignment " + asgnOrder; if(assignmentNames.contains(defaultName)) { //Attempt to generate a unique name - but don't loop forever //Non-unique names are allowed, but a warning will be shown for(int defaultNameEnding = asgnOrder + 1; defaultNameEnding < 1000; defaultNameEnding++) { defaultName = "Assignment " + defaultNameEnding; if(assignmentNames.contains(defaultName)) { break; } } } //Create the assignment final DbAssignment asgn = new DbAssignment(defaultName, asgnOrder); //Add the assignment visually and to the database _assignmentList.getModel().addElement(asgn); _assignmentList.setSelectedValue(asgn); int listSize = _assignmentList.getModel().getSize(); listPane.getViewport().scrollRectToVisible(_assignmentList.getCellBounds(listSize - 1, listSize)); //Add the assignment on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(ImmutableSet.of(asgn)); } @Override public String dbFailureMessage() { return "Unable to add assignment: " + asgn.getName(); } }); } }); buttonPanel.add(addButton, BorderLayout.WEST); buttonPanel.add(Box.createHorizontalBox(), BorderLayout.CENTER); final JButton deleteButton = new JButton("Delete"); deleteButton.setEnabled(false); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final DbAssignment asgn = _assignmentList.getSelectedValue(); boolean proceed = ModalDialog.showConfirmation(_configManager, "Delete Assignment", "Deleting assignment " + asgn.getName() + " will delete all associated grades, " + "extensions, exemptions, and groups.", "Delete", "Cancel"); if(proceed) { //Remove the assignment from the visible list _assignmentList.getModel().removeElement(asgn); //Get a list of assignments that now have a new order as a result final Set<DbAssignment> reorderedAssignments = getReorderedAssignments(); //Delete the assignment on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeAssignments(ImmutableSet.of(asgn)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putAssignments(reorderedAssignments); } @Override public String dbFailureMessage() { return "Unable to delete assignment: " + asgn.getName(); } }); } } }); buttonPanel.add(deleteButton, BorderLayout.EAST); _assignmentList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent lse) { DbAssignment selectedAsgn = _assignmentList.getSelectedValue(); deleteButton.setEnabled(selectedAsgn != null); assignmentSelectionChanged(selectedAsgn); } }); } private void assignmentSelectionChanged(final DbAssignment selectedAsgn) { _selectedAssignmentPanel.removeAll(); _selectedAssignmentPanel.setLayout(new BorderLayout(0, 0)); if(selectedAsgn == null) { _selectedAssignmentPanel.add(FormattedLabel.asSubheader("No Assignment Selected").centerHorizontally(), BorderLayout.CENTER); } else { JPanel panel = _assignmentPanels.get(selectedAsgn); if(panel == null) { panel = new SelectedAssignmentPanel(selectedAsgn); _assignmentPanels.put(selectedAsgn, panel); } _selectedAssignmentPanel.add(panel, BorderLayout.CENTER); } //Force visual update to reflect these changes _selectedAssignmentPanel.repaint(); _selectedAssignmentPanel.revalidate(); } /** * Returns a list of the assignments in the DnDList whose visual order does not match the order stored in the * assignment object. * * @return */ private Set<DbAssignment> getReorderedAssignments() { Set<DbAssignment> reorderedAssignments = new HashSet<DbAssignment>(); List<DbAssignment> assignments = _assignmentList.getListData(); for(int i = 0; i < assignments.size(); i++) { DbAssignment asgn = assignments.get(i); if(asgn.getOrder() != i) { asgn.setOrder(i); reorderedAssignments.add(asgn); } } return reorderedAssignments; } private abstract class ReinitializeRunnable implements Runnable { public void run() { try { dbCall(); } catch(SQLException e) { reinitialize(e, dbFailureMessage()); } } public abstract void dbCall() throws SQLException; public abstract String dbFailureMessage(); } void reinitialize(final Throwable t, final String msg) { //Cancel everything and re-initialize _worker.cancel(WORKER_TAG); initialize(); ErrorReporter.report(msg, t); } private void initialize() { _worker.submit(null, new Runnable() { @Override public void run() { try { List<DbAssignment> assignments = new ArrayList<DbAssignment>(Allocator.getDatabase().getAssignments()); Collections.sort(assignments); final List<DbAssignment> sortedAssignments = ImmutableList.copyOf(assignments); EventQueue.invokeLater(new Runnable() { @Override public void run() { _assignmentPanels.clear(); _selectedAssignmentPanel.removeAll(); _assignmentList.setListData(sortedAssignments, true); if(_assignmentList.getSelectedValue() == null) { _assignmentList.selectFirst(); } //Force visual update to reflect these changes AssignmentPanel.this.repaint(); AssignmentPanel.this.revalidate(); } }); } catch(final SQLException e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { _assignmentPanels.clear(); _selectedAssignmentPanel.removeAll(); _assignmentList.clearListData(); //Force visual update to reflect these changes AssignmentPanel.this.repaint(); AssignmentPanel.this.revalidate(); ErrorReporter.report(e); } }); } } }); } private class SelectedAssignmentPanel extends JPanel { private final DbAssignment _asgn; private final ValidatingTextField _asgnNameField; private final JCheckBox _hasGroupsCheckBox; private final Map<DbGradableEvent, GradableEventPanel> _gradableEventPanels = new HashMap<DbGradableEvent, GradableEventPanel>(); private final JPanel _gradableEventsPanel; private final JButton _addGradableEventButton; SelectedAssignmentPanel(DbAssignment selectedAsgn) { _asgn = selectedAsgn; this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); //Assignment name _asgnNameField = new ValidatingTextField() { @Override protected String getDbValue() { return _asgn.getName(); } @Override protected ValidationResult validate(String value) { ValidationResult result = ValidationResult.NO_ISSUE; if(value.isEmpty()) { result = ValidationResult.TEXT_EMPTY; } else { //TODO: Make this more efficient boolean uniqueName = true; for(DbAssignment asgn : _assignmentList.getListData()) { if(asgn != _asgn && asgn.getName().equals(value)) { uniqueName = false; break; } } if(!uniqueName) { result = new ValidationResult(ValidationResult.ValidationState.WARNING, value + " is not " + "a unique assignment name"); } } return result; } @Override protected void applyChange(final String newValue) { _asgn.setName(newValue); _worker.submit(WORKER_TAG, new AssignmentRunnable()); } }; _asgnNameField.getDocument().addDocumentListener(new DocumentAdapter() { @Override public void modificationOccurred(DocumentEvent de) { _asgnDisplayName.put(_asgn, _asgnNameField.getText()); _assignmentList.refreshList(); } }); _asgnNameField.setMaximumSize(new Dimension(Short.MAX_VALUE, 25)); _asgnNameField.setAlignmentX(LEFT_ALIGNMENT); this.add(_asgnNameField); //Has groups _hasGroupsCheckBox = new JCheckBox("Group Assignment", _asgn.hasGroups()); _hasGroupsCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { boolean selected = _hasGroupsCheckBox.isSelected(); boolean proceed = ModalDialog.showConfirmation(_configManager, "Change Groups", "Changing whether this assignment has groups will delete all grades, extensions, and " + "exemptions for this assignment.", "Change", "Cancel"); if(proceed) { _asgn.setHasGroups(selected); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(ImmutableSet.of(_asgn)); Allocator.getDatabase().removeGroups(Allocator.getDatabase().getGroups(_asgn.getId())); } @Override public String dbFailureMessage() { return "Unable to change whether assignment " + _asgn.getName() + " has groups"; } }); } else { _hasGroupsCheckBox.setSelected(!selected); } } }); _hasGroupsCheckBox.setAlignmentX(LEFT_ALIGNMENT); this.add(_hasGroupsCheckBox); this.add(Box.createVerticalStrut(10)); JLabel gradableEventsLabel = FormattedLabel.asSubheader("Gradable Events"); gradableEventsLabel.setToolTipText("A gradable event represents a gradable product of work done by a " + "group of one or more students. This could be, but is not limited to, paper handins, digital " + "handins, labs, design checks, and exams."); this.add(gradableEventsLabel); _addGradableEventButton = new JButton("Add Gradable Event"); _addGradableEventButton.setAlignmentX(LEFT_ALIGNMENT); _addGradableEventButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new gradable event int maxOrder = -1; HashSet<String> geNames = new HashSet<String>(); for(DbGradableEvent ge : _asgn.getGradableEvents()) { maxOrder = Math.max(maxOrder, ge.getOrder()); geNames.add(ge.getName()); } int geOrder = maxOrder + 1; String defaultName = "Gradable Event " + geOrder; if(geNames.contains(defaultName)) { //Attempt to generate a unique name - but don't loop forever //Non-unique names are allowed, but a warning will be shown for(int defaultNameEnding = geOrder + 1; defaultNameEnding < 1000; defaultNameEnding++) { defaultName = "Gradable Event " + defaultNameEnding; if(!geNames.contains(defaultName)) { break; } } } final DbGradableEvent gradableEvent = DbGradableEvent.build(_asgn, defaultName, geOrder); GradableEventPanel panel = new GradableEventPanel(SelectedAssignmentPanel.this, gradableEvent); _gradableEventPanels.put(gradableEvent, panel); updateDisplayedGradableEventPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to insert or update " + gradableEvent.getName() + " into the database"; } }); } }); _gradableEventsPanel = new FixedWidthJPanel(); _gradableEventsPanel.setLayout(new BoxLayout(_gradableEventsPanel, BoxLayout.Y_AXIS)); JScrollPane scrollPane = new JScrollPane(_gradableEventsPanel); scrollPane.setBorder(null); this.add(scrollPane); scrollPane.setAlignmentX(LEFT_ALIGNMENT); List<DbGradableEvent> gradableEvents = new ArrayList<DbGradableEvent>(_asgn.getGradableEvents()); Collections.sort(gradableEvents); for(DbGradableEvent gradableEvent : gradableEvents) { GradableEventPanel panel = new GradableEventPanel(this, gradableEvent); _gradableEventPanels.put(gradableEvent, panel); } this.updateDisplayedGradableEventPanels(); } void updateDisplayedGradableEventPanels() { _gradableEventsPanel.removeAll(); List<DbGradableEvent> gradableEvents = new ArrayList<DbGradableEvent>(_asgn.getGradableEvents()); Collections.sort(gradableEvents); for(DbGradableEvent event : gradableEvents) { GradableEventPanel panel = _gradableEventPanels.get(event); _gradableEventsPanel.add(panel); _gradableEventsPanel.add(Box.createVerticalStrut(5)); panel.reorderOccurred(); } JPanel addPanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); addPanel.add(_addGradableEventButton, BorderLayout.CENTER); _gradableEventsPanel.add(addPanel); //Force visual update to reflect these changes _gradableEventsPanel.repaint(); _gradableEventsPanel.revalidate(); } private class AssignmentRunnable extends ReinitializeRunnable { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putAssignments(ImmutableSet.of(_asgn)); } @Override public String dbFailureMessage() { return "Unable to insert or update assignment " + _asgn.getName(); } } } private class GradableEventPanel extends PreferredHeightJPanel { private final DbGradableEvent _gradableEvent; private final JButton _upButton, _downButton, _addPartButton; private final ValidatingTextField _nameField, _directoryField; private final SelectedAssignmentPanel _asgnPanel; private final Map<DbPart, PartPanel> _partPanels = new HashMap<DbPart, PartPanel>(); private final JPanel _partsPanel; GradableEventPanel(SelectedAssignmentPanel asgnPanel, DbGradableEvent gradableEvent) { _asgnPanel = asgnPanel; _gradableEvent = gradableEvent; this.setBackground(new Color(225, 225, 225)); this.setBorder(BorderFactory.createEtchedBorder()); this.setLayout(new BorderLayout(0, 0)); JPanel contentPanel = new JPanel(); contentPanel.setBackground(this.getBackground()); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); this.add(new PaddingPanel(contentPanel, 5, this.getBackground()), BorderLayout.CENTER); JPanel headlinePanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); headlinePanel.setAlignmentX(LEFT_ALIGNMENT); headlinePanel.setBackground(this.getBackground()); contentPanel.add(headlinePanel); JPanel controlPanel = new JPanel(); controlPanel.setBackground(this.getBackground()); headlinePanel.add(controlPanel, BorderLayout.EAST); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); controlPanel.add(Box.createHorizontalStrut(3)); _upButton = new JButton("↑"); _upButton.setToolTipText("Move up"); _upButton.setMargin(new Insets(1, 1, 1, 1)); _upButton.setEnabled(false); _upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setOrder(_gradableEvent.getOrder() - 1); ImmutableSet.Builder<DbGradableEvent> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_gradableEvent); for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(event != _gradableEvent && event.getOrder() == _gradableEvent.getOrder()) { event.setOrder(event.getOrder() + 1); reorderedBuilder.add(event); } } final ImmutableSet<DbGradableEvent> reorderedEvents = reorderedBuilder.build(); _asgnPanel.updateDisplayedGradableEventPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(reorderedEvents); } @Override public String dbFailureMessage() { return "Unable to reorder gradable event: " + _gradableEvent.getName(); } }); } }); controlPanel.add(_upButton); controlPanel.add(Box.createHorizontalStrut(3)); _downButton = new JButton("↓"); _downButton.setToolTipText("Move down"); _downButton.setMargin(new Insets(1, 1, 1, 1)); _downButton.setEnabled(false); _downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setOrder(_gradableEvent.getOrder() + 1); ImmutableSet.Builder<DbGradableEvent> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_gradableEvent); for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(event != _gradableEvent && event.getOrder() == _gradableEvent.getOrder()) { event.setOrder(event.getOrder() - 1); reorderedBuilder.add(event); } } final ImmutableSet<DbGradableEvent> reorderedEvents = reorderedBuilder.build(); _asgnPanel.updateDisplayedGradableEventPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(reorderedEvents); } @Override public String dbFailureMessage() { return "Unable to reorder gradable event: " + _gradableEvent.getName(); } }); } }); controlPanel.add(_downButton); this.reorderOccurred(); controlPanel.add(Box.createHorizontalStrut(3)); JButton deleteButton = new JButton("✗"); deleteButton.setToolTipText("Delete"); deleteButton.setMargin(new Insets(1, 1, 1, 1)); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { boolean proceed = ModalDialog.showConfirmation(_configManager, "Delete Gradable Event", "Deleting this Gradable Event will delete all grades, extensions and exemptions for this " + "Gradable Event.", "Delete", "Cancel"); if(proceed) { _asgnPanel._asgn.removeGradableEvent(_gradableEvent); ImmutableSet.Builder<DbGradableEvent> reorderedBuilder = ImmutableSet.builder(); for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(event.getOrder() > _gradableEvent.getOrder()) { event.setOrder(event.getOrder() - 1); reorderedBuilder.add(event); } } final ImmutableSet<DbGradableEvent> reorderedEvents = reorderedBuilder.build(); //Force visual update to reflect these changes _asgnPanel.updateDisplayedGradableEventPanels(); //Delete the gradable event and reordered others on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeGradableEvents(ImmutableSet.of(_gradableEvent)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putGradableEvents(reorderedEvents); } @Override public String dbFailureMessage() { return "Unable to delete gradable event: " + _gradableEvent.getName(); } }); } } }); controlPanel.add(deleteButton); _nameField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getName(); } @Override protected ValidationResult validate(String value) { return ValidationResult.validateNotEmpty(value); } @Override protected void applyChange(String newValue) { _gradableEvent.setName(newValue); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(_gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to insert or update " + _gradableEvent.getName(); } }); } }; headlinePanel.add(_nameField, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(10)); contentPanel.add(FormattedLabel.asSubheader("Deadlines")); JPanel deadlinePanel = new DeadlinePanel(this.getBackground()); deadlinePanel.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(deadlinePanel); contentPanel.add(Box.createVerticalStrut(10)); JLabel directoryLabel = FormattedLabel.asSubheader("Digital Handin Directory"); directoryLabel.setToolTipText("This directory will be searched recursively for digital handins"); contentPanel.add(directoryLabel); _directoryField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getDirectory() == null ? "" : _gradableEvent.getDirectory().getAbsolutePath(); } @Override protected ValidationResult validate(String value) { ValidationResult result = ValidationResult.NO_ISSUE; if(!value.isEmpty()) { File file = new File(value); if(!file.exists()) { result = new ValidationResult(ValidationState.WARNING, "Specified directory does not exist"); } else { if(file.isFile()) { result = new ValidationResult(ValidationState.WARNING, "Specified directory is a file"); } else if(!file.canExecute()) { result = new ValidationResult(ValidationState.WARNING, "Cannot read contents of specified directory"); } } } return result; } @Override protected void applyChange(String newValue) { String currValue = _gradableEvent.getDirectory() == null ? "" : _gradableEvent.getDirectory().getAbsolutePath(); if(!newValue.equals(currValue)) { if(newValue.isEmpty()) { _gradableEvent.setDirectory(null); } else { _gradableEvent.setDirectory(new File(newValue)); } _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(_gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to insert or update " + _gradableEvent.getName(); } }); } } }; _directoryField.setAlignmentX(LEFT_ALIGNMENT); _directoryField.setMaximumSize(new Dimension(Short.MAX_VALUE, 25)); contentPanel.add(_directoryField); contentPanel.add(Box.createVerticalStrut(10)); JLabel partsLabel = FormattedLabel.asSubheader("Parts"); partsLabel.setToolTipText("A Part is an arbitrary portion of a Gradable Event that can be assigned to a TA"); contentPanel.add(partsLabel); _addPartButton = new JButton("Add Part"); _addPartButton.setAlignmentX(LEFT_ALIGNMENT); _addPartButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new part int maxOrder = -1; HashSet<String> partNames = new HashSet<String>(); for(DbPart part : _gradableEvent.getParts()) { maxOrder = Math.max(maxOrder, part.getOrder()); partNames.add(part.getName()); } int partOrder = maxOrder + 1; String defaultName = "Part " + partOrder; if(partNames.contains(defaultName)) { //Attempt to generate a unique name - but don't loop forever; Non-unique names are allowed for(int defaultNameEnding = partOrder + 1; defaultNameEnding < 1000; defaultNameEnding++) { defaultName = "Part " + defaultNameEnding; if(!partNames.contains(defaultName)) { break; } } } final DbPart part = DbPart.build(_gradableEvent, defaultName, partOrder); PartPanel panel = new PartPanel(GradableEventPanel.this, part); _partPanels.put(part, panel); updateDisplayedPartPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(ImmutableSet.of(part)); } @Override public String dbFailureMessage() { return "Unable to update or insert part " + part.getName(); } }); } }); _partsPanel = new JPanel(); _partsPanel.setBackground(this.getBackground()); _partsPanel.setLayout(new BoxLayout(_partsPanel, BoxLayout.Y_AXIS)); _partsPanel.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(_partsPanel); List<DbPart> parts = new ArrayList<DbPart>(_gradableEvent.getParts()); Collections.sort(parts); for(DbPart part : parts) { PartPanel panel = new PartPanel(this, part); _partPanels.put(part, panel); } this.updateDisplayedPartPanels(); } void reorderOccurred() { _upButton.setEnabled(_gradableEvent.getOrder() != 0); boolean isLastGradableEvent = true; for(DbGradableEvent event : _asgnPanel._asgn.getGradableEvents()) { if(_gradableEvent.getOrder() < event.getOrder()) { isLastGradableEvent = false; break; } } _downButton.setEnabled(!isLastGradableEvent); } void updateDisplayedPartPanels() { _partsPanel.removeAll(); List<DbPart> parts = new ArrayList<DbPart>(_gradableEvent.getParts()); Collections.sort(parts); for(DbPart part : parts) { PartPanel panel = _partPanels.get(part); _partsPanel.add(panel); _partsPanel.add(Box.createVerticalStrut(5)); panel.reorderOccurred(); } JPanel addPanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); addPanel.add(_addPartButton, BorderLayout.CENTER); _partsPanel.add(addPanel); //Force visual update to reflect these changes _partsPanel.repaint(); _partsPanel.revalidate(); } private class DeadlinePanel extends PreferredHeightJPanel { private final DateTimeControl _earlyDateControl, _onTimeDateControl, _lateDateControl; private final ValidatingTextField _earlyPointsField, _latePointsField; private final PeriodControl _latePeriodControl; private DeadlinePanel(Color backgroundColor) { this.setBackground(backgroundColor); //Dates _earlyDateControl = new DateTimeControl(_gradableEvent.getEarlyDate()); _earlyDateControl.setBackground(backgroundColor); _earlyDateControl.addDateTimeChangeListener(new DateTimeControl.DateTimeChangeListener() { @Override public void dateTimeChanged(DateTime prevDateTime, DateTime newDateTime) { _gradableEvent.setEarlyDate(newDateTime); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); _onTimeDateControl = new DateTimeControl(_gradableEvent.getOnTimeDate()); _onTimeDateControl.setBackground(backgroundColor); _onTimeDateControl.addDateTimeChangeListener(new DateTimeControl.DateTimeChangeListener() { @Override public void dateTimeChanged(DateTime prevDateTime, DateTime newDateTime) { _gradableEvent.setOnTimeDate(newDateTime); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); _lateDateControl = new DateTimeControl(_gradableEvent.getLateDate()); _lateDateControl.setBackground(backgroundColor); _lateDateControl.addDateTimeChangeListener(new DateTimeControl.DateTimeChangeListener() { @Override public void dateTimeChanged(DateTime prevDateTime, DateTime newDateTime) { _gradableEvent.setLateDate(newDateTime); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); //Points _earlyPointsField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getEarlyPoints() == null ? "" : (_gradableEvent.getEarlyPoints() + ""); } @Override protected void applyChange(String newValue) { _gradableEvent.setEarlyPoints(newValue.isEmpty() ? null : Double.parseDouble(newValue)); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } @Override protected ValidationResult validate(String value) { ValidationResult result; if(this.isEnabled()) { try { double numericValue = Double.parseDouble(value); if(numericValue == 0.0D) { result = new ValidationResult(ValidationState.WARNING, "No bonus given"); } else if(numericValue < 0D) { result = new ValidationResult(ValidationState.WARNING, "Bonus is negative. " + "Student work will lose points for being early."); } else { result = ValidationResult.NO_ISSUE; } } catch(NumberFormatException e) { result = new ValidationResult(ValidationState.ERROR, "Numerical value not provided"); } } else { result = ValidationResult.NO_VALIDATION; } return result; } }; _earlyPointsField.setColumns(5); _latePointsField = new ValidatingTextField() { @Override protected String getDbValue() { return _gradableEvent.getLatePoints() == null ? "" : (_gradableEvent.getLatePoints() + ""); } @Override protected void applyChange(String newValue) { _gradableEvent.setLatePoints(newValue.isEmpty() ? null : Double.parseDouble(newValue)); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } @Override protected ValidationResult validate(String value) { ValidationResult result; if(this.isEnabled()) { try { double numericValue = Double.parseDouble(value); if(numericValue == 0.0D) { result = new ValidationResult(ValidationState.WARNING, "No penalty given"); } else if(numericValue > 0D) { result = new ValidationResult(ValidationState.WARNING, "Penalty is positive. " + "Student work will gain points for being late."); } else { result = ValidationResult.NO_ISSUE; } } catch(NumberFormatException e) { result = new ValidationResult(ValidationState.ERROR, "Numerical value not provided"); } } else { result = ValidationResult.NO_VALIDATION; } return result; } }; _latePointsField.setColumns(5); //Period _latePeriodControl = new PeriodControl(_gradableEvent.getLatePeriod()); _latePeriodControl.setBackground(backgroundColor); _latePeriodControl.addPeriodChangeListener(new PeriodControl.PeriodChangeListener() { @Override public void periodChanged(Period prevPeriod, Period newPeriod) { _gradableEvent.setLatePeriod(newPeriod); _worker.submit(WORKER_TAG, new DeadlineRunnable()); } }); this.displayDeadlineInfo(); } private class RemoveDeadlinesActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setDeadlineType(DeadlineInfo.Type.NONE); _gradableEvent.setEarlyDate(null); _gradableEvent.setOnTimeDate(null); _gradableEvent.setLateDate(null); _gradableEvent.setEarlyPoints(null); _gradableEvent.setLatePoints(null); _gradableEvent.setLatePeriod(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); displayDeadlineInfo(); } } private void displayDeadlineInfo() { this.removeAll(); _earlyDateControl.setDateTime(_gradableEvent.getEarlyDate(), true); _onTimeDateControl.setDateTime(_gradableEvent.getOnTimeDate(), true); _lateDateControl.setDateTime(_gradableEvent.getLateDate(), true); _latePeriodControl.setPeriod(_gradableEvent.getLatePeriod(), true); DeadlineInfo.Type deadlineType = _gradableEvent.getDeadlineType(); if(deadlineType == DeadlineInfo.Type.FIXED) { this.setLayout(new BorderLayout(0, 0)); //Controls for the fixed deadlines JPanel controlsPanel = new JPanel(); controlsPanel.setBackground(this.getBackground()); this.add(controlsPanel, BorderLayout.CENTER); controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.Y_AXIS)); //Early boolean hasEarly = _earlyDateControl.getDateTime() != null; final JCheckBox earlyCheckBox = new JCheckBox("Early", hasEarly); earlyCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(earlyCheckBox.isSelected()) { DateTime earlyDate = _onTimeDateControl.getDateTime().minusDays(2); _gradableEvent.setEarlyDate(earlyDate); _gradableEvent.setEarlyPoints(0D); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _earlyDateControl.setDateTime(earlyDate, true); _earlyPointsField.setEnabled(true); _earlyPointsField.setText("0"); } else { _gradableEvent.setEarlyDate(null); _gradableEvent.setEarlyPoints(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _earlyDateControl.setDateTime(null, true); _earlyPointsField.setEnabled(false); _earlyPointsField.setText(""); } } }); earlyCheckBox.setBackground(this.getBackground()); earlyCheckBox.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(earlyCheckBox); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _earlyDateControl)); controlsPanel.add(Box.createVerticalStrut(3)); _earlyPointsField.setEnabled(hasEarly); _earlyPointsField.setTextToDbValue(); controlsPanel.add(createDeadlineComponentPanel("Bonus Points: ", _earlyPointsField)); controlsPanel.add(Box.createVerticalStrut(5)); //On Time controlsPanel.add(FormattedLabel.asContent("On Time")); _onTimeDateControl.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _onTimeDateControl)); controlsPanel.add(Box.createVerticalStrut(5)); //Late boolean hasLate = _lateDateControl.getDateTime() != null; final JCheckBox lateCheckBox = new JCheckBox("Late", hasLate); lateCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(lateCheckBox.isSelected()) { DateTime lateDate = _onTimeDateControl.getDateTime().plusDays(2); _gradableEvent.setLateDate(lateDate); _gradableEvent.setLatePoints(0D); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(lateDate, true); _latePointsField.setEnabled(true); _latePointsField.setText("0"); } else { _gradableEvent.setLateDate(null); _gradableEvent.setLatePoints(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(null, true); _latePointsField.setEnabled(false); _latePointsField.setText(""); } } }); lateCheckBox.setBackground(this.getBackground()); lateCheckBox.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(lateCheckBox); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _lateDateControl)); controlsPanel.add(Box.createVerticalStrut(3)); _latePointsField.setEnabled(hasLate); _latePointsField.setTextToDbValue(); controlsPanel.add(createDeadlineComponentPanel("Penalty Points: ", _latePointsField)); //Remove deadlines JPanel removePanel = new JPanel(); removePanel.setBackground(this.getBackground()); this.add(removePanel, BorderLayout.SOUTH); JButton removeButton = new JButton("Remove Deadlines"); removeButton.setAlignmentX(CENTER_ALIGNMENT); removeButton.addActionListener(new RemoveDeadlinesActionListener()); removePanel.add(removeButton); } else if(deadlineType == DeadlineInfo.Type.VARIABLE) { this.setLayout(new BorderLayout(0, 0)); //Controls for the variable deadlines JPanel controlsPanel = new JPanel(); controlsPanel.setBackground(this.getBackground()); this.add(controlsPanel, BorderLayout.CENTER); controlsPanel.setLayout(new BoxLayout(controlsPanel, BoxLayout.Y_AXIS)); //On Time controlsPanel.add(FormattedLabel.asContent("On Time")); _onTimeDateControl.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _onTimeDateControl)); controlsPanel.add(Box.createVerticalStrut(5)); //Deduction controlsPanel.add(FormattedLabel.asContent("Deduction")); _latePeriodControl.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(createDeadlineComponentPanel("Period: ", _latePeriodControl)); controlsPanel.add(Box.createVerticalStrut(3)); _latePointsField.setAlignmentX(LEFT_ALIGNMENT); _latePointsField.setEnabled(true); _latePointsField.setTextToDbValue(); controlsPanel.add(createDeadlineComponentPanel("Penalty Points per Period: ", _latePointsField)); //Late boolean hasLate = _lateDateControl.getDateTime() != null; final JCheckBox lateCheckBox = new JCheckBox("Late", hasLate); lateCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(lateCheckBox.isSelected()) { Period period = _latePeriodControl.getPeriod(); DateTime lateDate = _onTimeDateControl.getDateTime().plus(period).plus(period); _gradableEvent.setLateDate(lateDate); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(lateDate, true); } else { _gradableEvent.setLateDate(null); _worker.submit(WORKER_TAG, new DeadlineRunnable()); _lateDateControl.setDateTime(null, true); } } }); lateCheckBox.setBackground(this.getBackground()); lateCheckBox.setAlignmentX(LEFT_ALIGNMENT); controlsPanel.add(lateCheckBox); controlsPanel.add(createDeadlineComponentPanel("Deadline: ", _lateDateControl)); controlsPanel.add(Box.createVerticalStrut(3)); //Remove deadlines JPanel removePanel = new JPanel(); removePanel.setBackground(this.getBackground()); this.add(removePanel, BorderLayout.SOUTH); JButton removeButton = new JButton("Remove Deadlines"); removeButton.setAlignmentX(CENTER_ALIGNMENT); removeButton.addActionListener(new RemoveDeadlinesActionListener()); removePanel.add(removeButton); } else { this.setLayout(new GridLayout(1, 2, 3, 0)); JButton fixedButton = new JButton("Add Fixed Deadlines"); fixedButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setDeadlineType(DeadlineInfo.Type.FIXED); _gradableEvent.setOnTimeDate(new DateTime()); _worker.submit(WORKER_TAG, new DeadlineRunnable()); displayDeadlineInfo(); } }); this.add(fixedButton); JButton variableButton = new JButton("Add Variable Deadlines"); variableButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _gradableEvent.setDeadlineType(DeadlineInfo.Type.VARIABLE); _gradableEvent.setOnTimeDate(new DateTime()); _gradableEvent.setLatePeriod(new Period(0, 0, 0, 1, 0, 0, 0, 0)); _gradableEvent.setLatePoints(0D); _worker.submit(WORKER_TAG, new DeadlineRunnable()); displayDeadlineInfo(); } }); this.add(variableButton); } //Force visual update to reflect these changes this.repaint(); this.revalidate(); } private JPanel createDeadlineComponentPanel(String labelText, Component component) { JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); panel.setBackground(this.getBackground()); panel.setAlignmentX(LEFT_ALIGNMENT); panel.add(Box.createHorizontalStrut(21)); panel.add(FormattedLabel.asContent(labelText)); panel.add(component); return panel; } private class DeadlineRunnable extends ReinitializeRunnable { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putGradableEvents(ImmutableSet.of(_gradableEvent)); } @Override public String dbFailureMessage() { return "Unable to save deadline information for gradable event " + _gradableEvent.getName(); } } } } private class PartPanel extends PreferredHeightJPanel { private final GradableEventPanel _gePanel; private final DbPart _part; private final JButton _upButton, _downButton; private final ValidatingTextField _nameField, _quickNameField; private final JButton _gradingSheetButton; private final Map<DbAction, ActionPanel> _actionPanels = new HashMap<DbAction, ActionPanel>(); private final JPanel _actionsPanel; private final JButton _addActionButton; private PartPanel(GradableEventPanel gePanel, DbPart part) { _gePanel = gePanel; _part = part; this.setBackground(new Color(212, 212, 212)); this.setBorder(BorderFactory.createEtchedBorder()); this.setLayout(new BorderLayout(0, 0)); JPanel contentPanel = new JPanel(); contentPanel.setBackground(this.getBackground()); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); this.add(new PaddingPanel(contentPanel, 5, this.getBackground()), BorderLayout.CENTER); JPanel headlinePanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); headlinePanel.setAlignmentX(LEFT_ALIGNMENT); headlinePanel.setBackground(this.getBackground()); contentPanel.add(headlinePanel); JPanel controlPanel = new JPanel(); controlPanel.setBackground(this.getBackground()); headlinePanel.add(controlPanel, BorderLayout.EAST); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); controlPanel.add(Box.createHorizontalStrut(3)); _upButton = new JButton("↑"); _upButton.setToolTipText("Move up"); _upButton.setMargin(new Insets(1, 1, 1, 1)); _upButton.setEnabled(false); _upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _part.setOrder(_part.getOrder() - 1); ImmutableSet.Builder<DbPart> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_part); for(DbPart part : _gePanel._gradableEvent.getParts()) { if(part != _part && part.getOrder() == _part.getOrder()) { part.setOrder(part.getOrder() + 1); reorderedBuilder.add(part); } } final ImmutableSet<DbPart> reorderedParts = reorderedBuilder.build(); _gePanel.updateDisplayedPartPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(reorderedParts); } @Override public String dbFailureMessage() { return "Unable to reorder part: " + _part.getName(); } }); } }); controlPanel.add(_upButton); controlPanel.add(Box.createHorizontalStrut(3)); _downButton = new JButton("↓"); _downButton.setToolTipText("Move down"); _downButton.setMargin(new Insets(1, 1, 1, 1)); _downButton.setEnabled(false); _downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _part.setOrder(_part.getOrder() + 1); ImmutableSet.Builder<DbPart> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_part); for(DbPart part : _gePanel._gradableEvent.getParts()) { if(_part != part && part.getOrder() == _part.getOrder()) { part.setOrder(part.getOrder() - 1); reorderedBuilder.add(part); } } final ImmutableSet<DbPart> reorderedParts = reorderedBuilder.build(); _gePanel.updateDisplayedPartPanels(); //Reorder gradable events on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(reorderedParts); } @Override public String dbFailureMessage() { return "Unable to reorder part: " + _part.getName(); } }); } }); controlPanel.add(_downButton); this.reorderOccurred(); controlPanel.add(Box.createHorizontalStrut(3)); JButton deleteButton = new JButton("✗"); deleteButton.setToolTipText("Delete"); deleteButton.setMargin(new Insets(1, 1, 1, 1)); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { boolean proceed = ModalDialog.showConfirmation(_configManager, "Delete Part", "Deleting this Part will delete all grades and distributions for this Part", "Delete", "Cancel"); if(proceed) { _gePanel._gradableEvent.removePart(_part); ImmutableSet.Builder<DbPart> reorderedBuilder = ImmutableSet.builder(); for(DbPart part : _gePanel._gradableEvent.getParts()) { if(part.getOrder() > _part.getOrder()) { part.setOrder(part.getOrder() - 1); reorderedBuilder.add(part); } } final ImmutableSet<DbPart> reorderedParts = reorderedBuilder.build(); _gePanel.updateDisplayedPartPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeParts(ImmutableSet.of(_part)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putParts(reorderedParts); } @Override public String dbFailureMessage() { return "Unable to delete part: " + _part.getName(); } }); } } }); controlPanel.add(deleteButton); _nameField = new ValidatingTextField() { @Override protected String getDbValue() { return _part.getName(); } @Override protected ValidationResult validate(String value) { return ValidationResult.validateNotEmpty(value); } @Override protected void applyChange(String newValue) { _part.setName(newValue); _worker.submit(WORKER_TAG, new PartRunnable()); } }; headlinePanel.add(_nameField, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(10)); JPanel combinedPanel = new JPanel(new GridLayout(1, 2, 3, 0)); combinedPanel.setAlignmentX(LEFT_ALIGNMENT); combinedPanel.setBackground(contentPanel.getBackground()); contentPanel.add(combinedPanel); JPanel gradingSheetPanel = new JPanel(new BorderLayout(0, 0)); gradingSheetPanel.setBackground(combinedPanel.getBackground()); combinedPanel.add(gradingSheetPanel); JLabel gradingSheetLabel = FormattedLabel.asSubheader("Grading Sheet"); gradingSheetLabel.setToolTipText("A grading sheet is filled out by TAs while grading a student"); gradingSheetPanel.add(gradingSheetLabel, BorderLayout.NORTH); _gradingSheetButton = new JButton("Edit Grading Sheet"); _gradingSheetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { _worker.blockOnQueuedTasks(); GradingSheetCreatorPanel gradingSheetCreator = new GradingSheetCreatorPanel(AssignmentPanel.this, _worker, _part); CloseAction closeAction = _configManager.hostModal(gradingSheetCreator); gradingSheetCreator.setCloseAction(closeAction); } catch(InterruptedException e) { ErrorReporter.report("Unable to show grading sheet creator due to failure to block on " + "queued tasks", e); } } }); gradingSheetPanel.add(_gradingSheetButton); JPanel quickNamePanel = new JPanel(new BorderLayout(0, 0)); quickNamePanel.setBackground(combinedPanel.getBackground()); combinedPanel.add(quickNamePanel); JLabel quickNameLabel = FormattedLabel.asSubheader("Quick Name"); quickNameLabel.setToolTipText("A unique name for the part that can be referenced from a shell script"); quickNamePanel.add(quickNameLabel, BorderLayout.NORTH); _quickNameField = new ValidatingTextField() { @Override protected String getDbValue() { return _part.getQuickName() == null ? "" : _part.getQuickName(); } @Override protected ValidationResult validate(String value) { ValidationResult result; //Allows a through z (upper and lower case), 0 through 9, and underscore Matcher matcher = Pattern.compile("[0-9a-zA-Z_]*").matcher(value); if(matcher.find() && (matcher.end() - matcher.start() == value.length())) { //TODO: Improve efficiency HashSet<String> quickNames = new HashSet<String>(); List<DbAssignment> asgns = _assignmentList.getListData(); for(DbAssignment asgn : asgns) { for(DbGradableEvent ge : asgn.getGradableEvents()) { for(DbPart part : ge.getParts()) { if(part != _part && part.getQuickName() != null) { quickNames.add(part.getQuickName()); } } } } if(quickNames.contains(value)) { result = new ValidationResult(ValidationState.ERROR, "This quick name is not unique"); } else { result = ValidationResult.NO_ISSUE; } } else { result = new ValidationResult(ValidationState.ERROR, "Only letters, numbers, and underscores " + "are allowed"); } return result; } @Override protected void applyChange(String newValue) { _part.setQuickName(newValue.isEmpty() ? null : newValue); _worker.submit(WORKER_TAG, new PartRunnable()); } }; quickNamePanel.add(_quickNameField, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(5)); JLabel actionsLabel = FormattedLabel.asSubheader("Actions"); actionsLabel.setToolTipText("An Action is a task performed for a part, which can include acting on a " + "digital handin"); contentPanel.add(actionsLabel); _addActionButton = new JButton("Add Action"); _addActionButton.setAlignmentX(LEFT_ALIGNMENT); _addActionButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { //Determine the order and the default name for the new action int maxOrder = -1; HashSet<String> actionNames = new HashSet<String>(); for(DbAction action : _part.getActions()) { maxOrder = Math.max(maxOrder, action.getOrder()); actionNames.add(action.getName()); } int actionOrder = maxOrder + 1; String actionName; IconImage actionIcon; List<ActionDescription> availableSuggestedDescriptions = new ArrayList<ActionDescription>(); for(ActionDescription description : ActionDescription.getDefaultDescriptions()) { if(!actionNames.contains(description.getName())) { availableSuggestedDescriptions.add(description); } } if(availableSuggestedDescriptions.isEmpty()) { actionName = ActionDescription.CUSTOM.getName(); actionIcon = ActionDescription.CUSTOM.getIcon(); } else { ActionDescription description = availableSuggestedDescriptions.get(0); actionName = description.getName(); actionIcon = description.getIcon(); } final DbAction action = DbAction.build(_part, actionName, actionIcon, actionOrder); ActionPanel panel = new ActionPanel(PartPanel.this, action); _actionPanels.put(action, panel); updateDisplayedActionPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putActions(ImmutableSet.of(action)); } @Override public String dbFailureMessage() { return "Unable to update or insert action " + action.getName(); } }); } }); _actionsPanel = new JPanel(); _actionsPanel.setBackground(this.getBackground()); _actionsPanel.setLayout(new BoxLayout(_actionsPanel, BoxLayout.Y_AXIS)); _actionsPanel.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(_actionsPanel); List<DbAction> actions = new ArrayList<DbAction>(_part.getActions()); Collections.sort(actions); for(DbAction action : actions) { ActionPanel panel = new ActionPanel(this, action); _actionPanels.put(action, panel); } this.updateDisplayedActionPanels(); } void updateDisplayedActionPanels() { _actionsPanel.removeAll(); List<DbAction> actions = new ArrayList<DbAction>(_part.getActions()); Collections.sort(actions); for(DbAction action : actions) { ActionPanel panel = _actionPanels.get(action); _actionsPanel.add(panel); _actionsPanel.add(Box.createVerticalStrut(5)); panel.reorderOccurred(); } JPanel addPanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); addPanel.add(_addActionButton, BorderLayout.CENTER); _actionsPanel.add(addPanel); //Force visual update to reflect these changes _actionsPanel.repaint(); _actionsPanel.revalidate(); } void reorderOccurred() { _upButton.setEnabled(_part.getOrder() != 0); boolean isLastPart = true; for(DbPart part : _gePanel._gradableEvent.getParts()) { if(_part.getOrder() < part.getOrder()) { isLastPart = false; break; } } _downButton.setEnabled(!isLastPart); } private class PartRunnable extends ReinitializeRunnable { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putParts(ImmutableSet.of(_part)); } @Override public String dbFailureMessage() { return "Unable to insert or update part " + _part.getName(); } } } private class ActionPanel extends JPanel { private final PartPanel _partPanel; private final DbAction _action; private final JButton _upButton, _downButton; private final JComboBox _iconComboBox; private final JComboBox _nameComboBox; private final GenericJComboBox<Task> _taskComboBox; private final JPanel _propertiesPanel; ActionPanel(PartPanel partPanel, DbAction action) { _partPanel = partPanel; _action = action; this.setBackground(new Color(200, 200, 200)); this.setBorder(BorderFactory.createEtchedBorder()); this.setLayout(new BorderLayout(0, 0)); JPanel contentPanel = new JPanel(); contentPanel.setBackground(this.getBackground()); contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS)); this.add(new PaddingPanel(contentPanel, 5, this.getBackground()), BorderLayout.CENTER); JPanel headlinePanel = new PreferredHeightJPanel(new BorderLayout(0, 0)); headlinePanel.setAlignmentX(LEFT_ALIGNMENT); headlinePanel.setBackground(this.getBackground()); contentPanel.add(headlinePanel); JPanel controlPanel = new JPanel(); controlPanel.setBackground(this.getBackground()); headlinePanel.add(controlPanel, BorderLayout.EAST); controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.X_AXIS)); controlPanel.add(Box.createHorizontalStrut(3)); _upButton = new JButton("↑"); _upButton.setToolTipText("Move up"); _upButton.setMargin(new Insets(1, 1, 1, 1)); _upButton.setEnabled(false); _upButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _action.setOrder(_action.getOrder() - 1); ImmutableSet.Builder<DbAction> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_action); for(DbAction action : _partPanel._part.getActions()) { if(action != _action && action.getOrder() == _action.getOrder()) { action.setOrder(action.getOrder() + 1); reorderedBuilder.add(action); } } final ImmutableSet<DbAction> reorderedActions = reorderedBuilder.build(); _partPanel.updateDisplayedActionPanels(); //Reorder actions on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putActions(reorderedActions); } @Override public String dbFailureMessage() { return "Unable to reorder action: " + _action.getName(); } }); } }); controlPanel.add(_upButton); controlPanel.add(Box.createHorizontalStrut(3)); _downButton = new JButton("↓"); _downButton.setToolTipText("Move down"); _downButton.setMargin(new Insets(1, 1, 1, 1)); _downButton.setEnabled(false); _downButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _action.setOrder(_action.getOrder() + 1); ImmutableSet.Builder<DbAction> reorderedBuilder = ImmutableSet.builder(); reorderedBuilder.add(_action); for(DbAction action : _partPanel._part.getActions()) { if(_action != action && action.getOrder() == _action.getOrder()) { action.setOrder(action.getOrder() - 1); reorderedBuilder.add(action); } } final ImmutableSet<DbAction> reorderedActions = reorderedBuilder.build(); _partPanel.updateDisplayedActionPanels(); //Reorder actions on the worker thread _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().putActions(reorderedActions); } @Override public String dbFailureMessage() { return "Unable to reorder action: " + _action.getName(); } }); } }); controlPanel.add(_downButton); this.reorderOccurred(); controlPanel.add(Box.createHorizontalStrut(3)); JButton deleteButton = new JButton("✗"); deleteButton.setToolTipText("Delete"); deleteButton.setMargin(new Insets(1, 1, 1, 1)); deleteButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { _partPanel._part.removeAction(_action); ImmutableSet.Builder<DbAction> reorderedBuilder = ImmutableSet.builder(); for(DbAction action : _partPanel._part.getActions()) { if(action.getOrder() > _action.getOrder()) { action.setOrder(action.getOrder() - 1); reorderedBuilder.add(action); } } final ImmutableSet<DbAction> reorderedActions = reorderedBuilder.build(); _partPanel.updateDisplayedActionPanels(); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { Allocator.getDatabase().removeActions(ImmutableSet.of(_action)); //This absolutely needs to occur after the delete call so in case that fails this //code will not execute Allocator.getDatabase().putActions(reorderedActions); } @Override public String dbFailureMessage() { return "Unable to delete action: " + _action.getName(); } }); } }); controlPanel.add(deleteButton); JPanel nameAndIconPanel = new JPanel(new BorderLayout(0, 0)); nameAndIconPanel.setBackground(headlinePanel.getBackground()); headlinePanel.add(nameAndIconPanel, BorderLayout.CENTER); _iconComboBox = new JComboBox(IconImage.values()); _iconComboBox.setSelectedItem(_action.getIcon()); _iconComboBox.setPreferredSize(new Dimension(40, 25)); _iconComboBox.setRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Icon icon = null; if(value instanceof IconImage) { icon = IconLoader.loadIcon(IconSize.s16x16, (IconImage) value); } JLabel label = new JLabel("", icon, SwingConstants.LEFT); if(isSelected) { label.setBackground(list.getSelectionBackground()); label.setForeground(list.getSelectionForeground()); } else { label.setBackground(list.getBackground()); label.setForeground(list.getForeground()); } return label; } }); _iconComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final IconImage icon; //This should always be true, but check just in case if(_iconComboBox.getSelectedItem() instanceof IconImage) { icon = (IconImage) _iconComboBox.getSelectedItem(); } else { icon = null; } _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { _action.setIcon(icon); Allocator.getDatabase().putActions(ImmutableSet.of(_action)); } @Override public String dbFailureMessage() { return "Unable to modify action name: " + _action.getName(); } }); } }); nameAndIconPanel.add(_iconComboBox, BorderLayout.WEST); _nameComboBox = new JComboBox(ActionDescription.getDefaultDescriptions().toArray()); _nameComboBox.setEditable(true); _nameComboBox.setSelectedItem(_action.getName()); _nameComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { final String name = _nameComboBox.getSelectedItem().toString(); if(_nameComboBox.getSelectedItem() instanceof ActionDescription) { ActionDescription description = (ActionDescription) _nameComboBox.getSelectedItem(); _iconComboBox.setSelectedItem(description.getIcon()); } _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { _action.setName(name); Allocator.getDatabase().putActions(ImmutableSet.of(_action)); } @Override public String dbFailureMessage() { return "Unable to modify action name from " + _action.getName() + " to " + name; } }); } }); nameAndIconPanel.add(_nameComboBox, BorderLayout.CENTER); contentPanel.add(Box.createVerticalStrut(10)); contentPanel.add(FormattedLabel.asHeader("Task")); final FormattedLabel digitalHandinRequiredLabel = FormattedLabel.asContent("This task requires a digital " + "handin to operate"); digitalHandinRequiredLabel.setVisible(false); final FormattedLabel taskDescriptionLabel = FormattedLabel.asContent("").usePlainFont(); JPanel propertyIndentPanel = new JPanel(); propertyIndentPanel.setBackground(contentPanel.getBackground()); _propertiesPanel = new JPanel(); _propertiesPanel.setBackground(propertyIndentPanel.getBackground()); _propertiesPanel.setLayout(new BoxLayout(_propertiesPanel, BoxLayout.Y_AXIS)); _taskComboBox = new GenericJComboBox<Task>(TaskRepository.getTasks().values(), new DescriptionProvider<Task>() { @Override public String getDisplayText(Task task) { String displayText = ""; if(task != null) { displayText = task.getFullName(); } return displayText; } @Override public String getToolTipText(Task task) { String toolTip = ""; if(task != null) { toolTip = task.getDescription(); } return toolTip; } }); Task task = TaskRepository.getTasks().get(_action.getTask()); _taskComboBox.setGenericSelectedItem(task); //If there is a task stored in the database, load up the properties if(task != null) { digitalHandinRequiredLabel.setVisible(task.requiresDigitalHandin()); taskDescriptionLabel.setText(task.getDescription()); //Required Set<DbActionProperty> requiredProperties = new HashSet<DbActionProperty>(); for(TaskProperty property : task.getRequiredProperties()) { for(DbActionProperty propertyValue : _action.getActionProperties()) { if(property.getName().equals(propertyValue.getKey())) { requiredProperties.add(propertyValue); } } } if(!task.getRequiredProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Required Properties", task.getRequiredProperties(), requiredProperties); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } //Optional Set<DbActionProperty> optionalProperties = new HashSet<DbActionProperty>(); for(TaskProperty property : task.getOptionalProperties()) { for(DbActionProperty propertyValue : _action.getActionProperties()) { if(property.getName().equals(propertyValue.getKey())) { optionalProperties.add(propertyValue); } } } if(!task.getOptionalProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Optional Properties", task.getOptionalProperties(), optionalProperties); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } } _taskComboBox.addSelectionListener(new SelectionListener<Task>() { @Override public void selectionPerformed(Task currTask, Task newTask, SelectionAction action) { _propertiesPanel.removeAll(); final String taskName; if(newTask == null) { taskName = null; digitalHandinRequiredLabel.setVisible(false); taskDescriptionLabel.setText("No task selected"); } else { taskName = newTask.getFullName(); digitalHandinRequiredLabel.setVisible(newTask.requiresDigitalHandin()); taskDescriptionLabel.setText(newTask.getDescription()); if(!newTask.getRequiredProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Required Properties", newTask.getRequiredProperties(), ImmutableSet.<DbActionProperty>of()); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } if(!newTask.getOptionalProperties().isEmpty()) { _propertiesPanel.add(Box.createVerticalStrut(5)); PropertiesPanel panel = new PropertiesPanel("Optional Properties", newTask.getOptionalProperties(), ImmutableSet.<DbActionProperty>of()); panel.setBackground(_propertiesPanel.getBackground()); _propertiesPanel.add(panel); } } _propertiesPanel.repaint(); _propertiesPanel.revalidate(); //Remove the no longer valid properties, as they belong to a different task final Set<DbActionProperty> properties = ImmutableSet.copyOf(_action.getActionProperties()); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { _action.setTask(taskName); Allocator.getDatabase().putActions(ImmutableSet.of(_action)); Allocator.getDatabase().removeActionProperties(properties); } @Override public String dbFailureMessage() { return "Unable to set action's task to: " + taskName; } }); } }); _taskComboBox.setAlignmentX(LEFT_ALIGNMENT); contentPanel.add(_taskComboBox); contentPanel.add(digitalHandinRequiredLabel); contentPanel.add(taskDescriptionLabel); propertyIndentPanel.setAlignmentX(LEFT_ALIGNMENT); propertyIndentPanel.setLayout(new BoxLayout(propertyIndentPanel, BoxLayout.X_AXIS)); propertyIndentPanel.add(Box.createHorizontalStrut(10)); propertyIndentPanel.add(_propertiesPanel); contentPanel.add(propertyIndentPanel); } private class PropertiesPanel extends JPanel { PropertiesPanel(String title, Set<TaskProperty> properties, Set<DbActionProperty> propertiesValues) { this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); this.add(FormattedLabel.asSubheader(title)); for(final TaskProperty property : properties) { this.add(Box.createVerticalStrut(3)); this.add(FormattedLabel.asContent(property.getName())); this.add(FormattedLabel.asContent(property.getDescription().replaceAll("\n", "<br/>")) .usePlainFont()); //Find the existing value in the database, if it does not exist - make one DbActionProperty propertyValue = null; for(DbActionProperty value : propertiesValues) { if(property.getName().equals(value.getKey())) { propertyValue = value; } } if(propertyValue == null) { propertyValue = DbActionProperty.build(_action, property.getName()); } final DbActionProperty dbPropertyValue = propertyValue; ValidatingTextField propertyField = new ValidatingTextField() { @Override protected String getDbValue() { return dbPropertyValue.getValue() == null ? "" : dbPropertyValue.getValue(); } @Override protected ValidationResult validate(String value) { ValidationResult result = ValidationResult.NO_VALIDATION; if(property.isRequired() && (value == null || value.isEmpty())) { result = new ValidationResult(ValidationState.ERROR, "This property is required"); } return result; } @Override protected void applyChange(final String newValue) { dbPropertyValue.setValue(newValue); _worker.submit(WORKER_TAG, new ReinitializeRunnable() { @Override public void dbCall() throws SQLException { if(newValue == null || newValue.isEmpty()) { Allocator.getDatabase().removeActionProperties( ImmutableSet.of(dbPropertyValue)); } else { Allocator.getDatabase().putActionProperties(ImmutableSet.of(dbPropertyValue)); } } @Override public String dbFailureMessage() { return "Unable to update property: " + property.getName(); } }); } }; propertyField.setAlignmentX(LEFT_ALIGNMENT); this.add(propertyField); } } } void reorderOccurred() { _upButton.setEnabled(_action.getOrder() != 0); boolean isLastAction = true; for(DbAction action : _partPanel._part.getActions()) { if(_action.getOrder() < action.getOrder()) { isLastAction = false; break; } } _downButton.setEnabled(!isLastAction); } } }
112,338
0.477163
0.474973
2,567
42.755745
28.018553
132
false
false
0
0
0
0
0
0
0.527464
false
false
13
57732c9ced38aa10d47a221b30bd56c355620114
1,795,296,345,676
3c49b77ce51366acd9087aae2ca2f40918a102db
/src/com/elian/cms/admin/action/OrderAction.java
762a8f7ac9d01cf83a4236bd993db8b8f3b053f9
[]
no_license
cckmit/ElianCms
https://github.com/cckmit/ElianCms
7fa4b995c847354337e4878f1f7a95ba72080650
d9c8df3c95ed706297ff2d6b4036c5b46ea6006b
refs/heads/master
2023-03-17T15:02:42.130000
2017-08-24T07:17:26
2017-08-24T07:17:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.elian.cms.admin.action; import java.util.List; import javax.annotation.Resource; import net.sf.json.JSONObject; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.elian.cms.admin.model.Order; import com.elian.cms.admin.service.OrderService; import com.elian.cms.syst.action.BaseAction; import com.elian.cms.syst.model.Pagination; import com.elian.cms.syst.model.SelectItem; import com.elian.cms.syst.util.ApplicationUtils; import com.elian.cms.syst.util.ElianUtils; import com.elian.cms.syst.util.HibernateEagerLoadingUtil; import com.elian.cms.syst.util.SearchParamUtils; /** * 订单功能 * * @author Joe * */ @Component @Scope("prototype") public class OrderAction extends BaseAction { /** * 序列化 */ private static final long serialVersionUID = 3744498219689067010L; private Integer compId; private Pagination<Order> pagination = new Pagination<Order>( SearchParamUtils.getOrderConditionMap()); private OrderService orderService; public String list() { orderService.findByAll( ApplicationUtils.getCompany() != null ? ApplicationUtils .getCompany().getId() : compId, pagination); return LIST; } public void ajaxList() { list(); HibernateEagerLoadingUtil.eagerLoadFiled(pagination.getList()); JSONObject obj = new JSONObject(); obj.put("pagi", pagination.getList()); ApplicationUtils.sendJsonpObj(obj); } public void delete() { List<Integer> idList = ApplicationUtils.getAjaxIds(); if (idList != null) { Order order = null; for (Integer id : idList) { order = orderService.get(id); if (order == null) continue; orderService.delete(order); } } } public String trees() { if (ApplicationUtils.isCompany()) { return list(); } return "tree"; } public List<SelectItem> getOrderStatusList() { return ElianUtils.getOrderStatusList(); } public List<SelectItem> getPaymentStatusList() { return ElianUtils.getPaymentStatusList(); } public Integer getCompId() { return compId; } public void setCompId(Integer compId) { this.compId = compId; } public Pagination<Order> getPagination() { return pagination; } @Resource public void setOrderService(OrderService orderService) { this.orderService = orderService; } }
UTF-8
Java
2,317
java
OrderAction.java
Java
[ { "context": "util.SearchParamUtils;\n\n/**\n * 订单功能\n * \n * @author Joe\n * \n */\n@Component\n@Scope(\"prototype\")\npublic cla", "end": 683, "score": 0.9994199275970459, "start": 680, "tag": "NAME", "value": "Joe" } ]
null
[]
package com.elian.cms.admin.action; import java.util.List; import javax.annotation.Resource; import net.sf.json.JSONObject; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.elian.cms.admin.model.Order; import com.elian.cms.admin.service.OrderService; import com.elian.cms.syst.action.BaseAction; import com.elian.cms.syst.model.Pagination; import com.elian.cms.syst.model.SelectItem; import com.elian.cms.syst.util.ApplicationUtils; import com.elian.cms.syst.util.ElianUtils; import com.elian.cms.syst.util.HibernateEagerLoadingUtil; import com.elian.cms.syst.util.SearchParamUtils; /** * 订单功能 * * @author Joe * */ @Component @Scope("prototype") public class OrderAction extends BaseAction { /** * 序列化 */ private static final long serialVersionUID = 3744498219689067010L; private Integer compId; private Pagination<Order> pagination = new Pagination<Order>( SearchParamUtils.getOrderConditionMap()); private OrderService orderService; public String list() { orderService.findByAll( ApplicationUtils.getCompany() != null ? ApplicationUtils .getCompany().getId() : compId, pagination); return LIST; } public void ajaxList() { list(); HibernateEagerLoadingUtil.eagerLoadFiled(pagination.getList()); JSONObject obj = new JSONObject(); obj.put("pagi", pagination.getList()); ApplicationUtils.sendJsonpObj(obj); } public void delete() { List<Integer> idList = ApplicationUtils.getAjaxIds(); if (idList != null) { Order order = null; for (Integer id : idList) { order = orderService.get(id); if (order == null) continue; orderService.delete(order); } } } public String trees() { if (ApplicationUtils.isCompany()) { return list(); } return "tree"; } public List<SelectItem> getOrderStatusList() { return ElianUtils.getOrderStatusList(); } public List<SelectItem> getPaymentStatusList() { return ElianUtils.getPaymentStatusList(); } public Integer getCompId() { return compId; } public void setCompId(Integer compId) { this.compId = compId; } public Pagination<Order> getPagination() { return pagination; } @Resource public void setOrderService(OrderService orderService) { this.orderService = orderService; } }
2,317
0.735562
0.727312
101
21.801981
19.973755
67
false
false
0
0
0
0
0
0
1.485149
false
false
13
6da1a5051bf6dee85d182ab671ae112c1a04733f
30,923,764,592,972
2824cfa53f04b08e7c5fb94b34a90ef9c49849dc
/src/main/java/org/usc/demo/clazz/Parent2.java
6ac22b91c770dd29538e24ec3debb961fde5b1e8
[ "Apache-2.0" ]
permissive
usc/demo
https://github.com/usc/demo
abfb88a044f5f6e8367a1cd9cfe446d656a7e370
9319e2f453c6d078a02976645d220753f62d0967
refs/heads/master
2020-05-22T01:48:31.670000
2018-04-07T09:26:43
2018-04-07T09:26:43
33,235,922
0
2
null
false
2016-03-15T12:10:52
2015-04-01T08:33:07
2015-05-04T02:59:39
2016-03-15T12:10:52
442
0
2
0
Java
null
null
package org.usc.demo.clazz; import com.google.common.base.Objects; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.Arrays; /** * * @author Shunli */ public class Parent2 { private static LoadingCache<CacheKey, String> cache = CacheBuilder.newBuilder().build(new CacheLoader<CacheKey, String>() { @Override public String load(CacheKey inner) throws Exception { System.out.println("Parent2->" + Arrays.toString(inner.getClazz().getDeclaredMethods())); return "1"; } }); public void doAction() throws Exception { cache.get(new CacheKey(getClass(), "test")); } private class CacheKey { private Class<?> clazz; private String actionName; public CacheKey(Class<?> clazz, String actionName) { this.clazz = clazz; this.actionName = actionName; } public Class<?> getClazz() { return clazz; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } CacheKey other = (CacheKey) obj; return Objects.equal(this.clazz, other.clazz) && Objects.equal(this.actionName, other.actionName); } @Override public int hashCode() { return Objects.hashCode(clazz, actionName); } } }
UTF-8
Java
1,654
java
Parent2.java
Java
[ { "context": "\n\r\nimport java.util.Arrays;\r\n\r\n/**\r\n *\r\n * @author Shunli\r\n */\r\npublic class Parent2 {\r\n private static ", "end": 264, "score": 0.8103544116020203, "start": 258, "tag": "USERNAME", "value": "Shunli" } ]
null
[]
package org.usc.demo.clazz; import com.google.common.base.Objects; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.Arrays; /** * * @author Shunli */ public class Parent2 { private static LoadingCache<CacheKey, String> cache = CacheBuilder.newBuilder().build(new CacheLoader<CacheKey, String>() { @Override public String load(CacheKey inner) throws Exception { System.out.println("Parent2->" + Arrays.toString(inner.getClazz().getDeclaredMethods())); return "1"; } }); public void doAction() throws Exception { cache.get(new CacheKey(getClass(), "test")); } private class CacheKey { private Class<?> clazz; private String actionName; public CacheKey(Class<?> clazz, String actionName) { this.clazz = clazz; this.actionName = actionName; } public Class<?> getClazz() { return clazz; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } CacheKey other = (CacheKey) obj; return Objects.equal(this.clazz, other.clazz) && Objects.equal(this.actionName, other.actionName); } @Override public int hashCode() { return Objects.hashCode(clazz, actionName); } } }
1,654
0.563482
0.561669
60
25.566668
27.193361
127
false
false
0
0
0
0
0
0
0.483333
false
false
13
922edf95dadcf913b05ba009661967655d0b76bf
5,720,896,451,378
4f343efc9339d56dd1aebf63c8586e007b9e5815
/src/main/java/org/algorithms/leetcode/easy/MinStack.java
47701772d1d57e43fdedc10bd7928047808d4e50
[]
no_license
SierikovMark/algorithms
https://github.com/SierikovMark/algorithms
d157f70e1df160c528951f18d699a135a55b21e0
c1583817a0a8edc34ccb5d3b18c02f317511f2c1
refs/heads/master
2023-08-04T22:59:36.517000
2023-07-23T21:18:55
2023-07-23T21:18:55
199,925,867
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.algorithms.leetcode.easy; public class MinStack { private int[] stack; private int tail; public MinStack() { stack = new int[8]; } // ~ time complexity = O(1), O(n) extra space public void push(int val) { if (tail + 1 >= stack.length) { int[] temp = stack; stack = new int[stack.length * 2]; System.arraycopy(temp, 0, stack, 0, temp.length); } stack[tail++] = val; } // time complexity = O(1), no extra space public void pop() { if (tail - 1 < 0) { throw new IllegalStateException(); } tail--; } // time complexity = O(1), no extra space public int top() { return stack[tail - 1]; } // time complexity = O(n), constant space public int getMin() { int min = Integer.MAX_VALUE; for (int i = 0; i < tail; i++) { if (stack[i] < min) { min = stack[i]; } } return min; } public static void main(String[] args) { MinStack minStack = new MinStack(); minStack.push(1); minStack.push(0); minStack.push(3); System.out.println(minStack.getMin()); minStack.pop(); minStack.pop(); System.out.println(minStack.getMin()); } }
UTF-8
Java
1,350
java
MinStack.java
Java
[]
null
[]
package org.algorithms.leetcode.easy; public class MinStack { private int[] stack; private int tail; public MinStack() { stack = new int[8]; } // ~ time complexity = O(1), O(n) extra space public void push(int val) { if (tail + 1 >= stack.length) { int[] temp = stack; stack = new int[stack.length * 2]; System.arraycopy(temp, 0, stack, 0, temp.length); } stack[tail++] = val; } // time complexity = O(1), no extra space public void pop() { if (tail - 1 < 0) { throw new IllegalStateException(); } tail--; } // time complexity = O(1), no extra space public int top() { return stack[tail - 1]; } // time complexity = O(n), constant space public int getMin() { int min = Integer.MAX_VALUE; for (int i = 0; i < tail; i++) { if (stack[i] < min) { min = stack[i]; } } return min; } public static void main(String[] args) { MinStack minStack = new MinStack(); minStack.push(1); minStack.push(0); minStack.push(3); System.out.println(minStack.getMin()); minStack.pop(); minStack.pop(); System.out.println(minStack.getMin()); } }
1,350
0.502963
0.491852
56
23.107143
16.529928
61
false
false
0
0
0
0
0
0
0.571429
false
false
13
3924c16ccf71bfa5bba797989d660354e351e2ea
5,720,896,449,751
5f21a8fb42579f594192b639f0745fe4eff741a0
/core/src/hering/gdx/tanks/components/Position.java
159a72bf3abccbf9b874b9b65682b00cca130862
[]
no_license
pjhering/hering-tanks
https://github.com/pjhering/hering-tanks
39fab70d2a9d9fd9567347e64156497b9eda7b02
393d7b6419a5bf44acde44bed6a5cf4b3262fe7e
refs/heads/master
2016-09-17T00:44:42.103000
2016-07-18T12:51:38
2016-07-18T12:51:38
63,568,034
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hering.gdx.tanks.components; import hering.gdx.core.Component; public class Position implements Component { public final float X, Y; public Position(float x, float y) { this.X = x; this.Y = y; } public Position move(float dx, float dy) { return new Position(X + dx, Y + dy); } }
UTF-8
Java
366
java
Position.java
Java
[]
null
[]
package hering.gdx.tanks.components; import hering.gdx.core.Component; public class Position implements Component { public final float X, Y; public Position(float x, float y) { this.X = x; this.Y = y; } public Position move(float dx, float dy) { return new Position(X + dx, Y + dy); } }
366
0.568306
0.568306
19
18.263159
16.685455
46
false
false
0
0
0
0
0
0
0.526316
false
false
13
cd361c415086cdefe0d5bd897872192c9f2bbe0d
1,030,792,198,554
c3afa6b7ba1f507d4323765a98451619d2e000a2
/lib-common/src/main/java/id/co/sigma/common/data/serializer/json/ObjectSerializerManager.java
d5b9761acd481b087d41993ee1077ab7b6b79db9
[ "Apache-2.0" ]
permissive
palawindu/bc-core
https://github.com/palawindu/bc-core
608371c410bc00e53381d6939c828b2c63a309e3
49f8f9e7d0b61a35014a5ae42d5a2043f9afa77d
refs/heads/master
2020-12-24T13:35:25.080000
2014-08-19T07:49:50
2014-08-19T07:49:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package id.co.sigma.common.data.serializer.json; import id.co.sigma.common.data.ObjectSerializer; import id.co.sigma.common.data.serializer.BigDecimalSerializer; import id.co.sigma.common.data.serializer.BigIntegerSerializer; import id.co.sigma.common.data.serializer.BooleanSerializer; import id.co.sigma.common.data.serializer.DateSerializer; import id.co.sigma.common.data.serializer.IntegerSerializer; import id.co.sigma.common.data.serializer.LongSerializer; import id.co.sigma.common.data.serializer.StringSerializer; import id.co.sigma.common.data.serializer.VoidSerializer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * spoller object serializer * @author Gede Sutarsa */ public final class ObjectSerializerManager { private static ObjectSerializerManager instance ; /** * tipe data simple yang tidak di json kan */ public final static Class <?>[] SIMPLE_OBJECTS ={ Long.class , long.class , Integer.class , int.class , Float.class , float.class , Short.class , short.class , String.class , Boolean.class , boolean.class , Date.class , java.sql.Date.class , BigDecimal.class , BigInteger.class , Void.class }; /** * object as simple array. ini untuk kemudahan konversi */ public final static ArrayList<String> SIMPLE_OBJECT_ARRAY =new ArrayList<String>(); public static final ArrayList<String> SIMPLE_ARRAY_OFOBJECT_TYPES = new ArrayList<String>(); public static final String [] SIMPLE_TYPE_FQCNS = new String[SIMPLE_OBJECTS.length] ; static { for ( Class<?> scn : SIMPLE_OBJECTS){ SIMPLE_OBJECT_ARRAY.add(scn.getName()); SIMPLE_ARRAY_OFOBJECT_TYPES.add("[L" + scn.getName() +";"); } for (int i=0;i<SIMPLE_TYPE_FQCNS.length;i++){ SIMPLE_TYPE_FQCNS[i]=SIMPLE_OBJECTS[i].getName(); } } /** * mengecek object tipe simple atau tidak */ public static boolean isSimpleObject ( String fqcn ){ return SIMPLE_OBJECT_ARRAY.contains(fqcn); } /** * ini untuk mengecek array of simple object atau bukan **/ public boolean isArrayofSimpleObject ( String classFqcn ){ return SIMPLE_ARRAY_OFOBJECT_TYPES.contains(classFqcn); } private Map<String , ObjectSerializer<?>> indexedSerializer ; private ObjectSerializerManager () { indexedSerializer = new HashMap<String, ObjectSerializer<?>>(); registerSerializer(new BigDecimalSerializer()); registerSerializer(new BigIntegerSerializer()); registerSerializer(new BooleanSerializer()); registerSerializer(new DateSerializer()); registerSerializer(new IntegerSerializer()); registerSerializer(new LongSerializer()); registerSerializer(new VoidSerializer()); registerSerializer(new StringSerializer()); } /** * register serializer ke dalam manager */ public void registerSerializer (ObjectSerializer<?> serializer ){ if ( serializer==null || serializer.acceptedClassFQCNS()== null || serializer.acceptedClassFQCNS().length ==0) return ; for ( String scn : serializer.acceptedClassFQCNS()){ indexedSerializer.put(scn, serializer); } } public ObjectSerializer<?> getSerializer (String fqcn ){ return this.indexedSerializer.get(fqcn); } /** * checker apakah ada deserializer untuk object dengan fqcn yang di minta */ public boolean isHaveSerializer (String fqcn ) { return this.indexedSerializer.containsKey(fqcn); } public static ObjectSerializerManager getInstance() { if ( instance == null){ instance = new ObjectSerializerManager(); } return instance; } public static void main (String [] args){ System.out.println(Object[].class.getName()); } }
UTF-8
Java
4,512
java
ObjectSerializerManager.java
Java
[ { "context": ".Map;\n\n/**\n * spoller object serializer\n * @author Gede Sutarsa\n */\npublic final class ObjectSerializerManager {\n", "end": 898, "score": 0.9998896718025208, "start": 886, "tag": "NAME", "value": "Gede Sutarsa" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package id.co.sigma.common.data.serializer.json; import id.co.sigma.common.data.ObjectSerializer; import id.co.sigma.common.data.serializer.BigDecimalSerializer; import id.co.sigma.common.data.serializer.BigIntegerSerializer; import id.co.sigma.common.data.serializer.BooleanSerializer; import id.co.sigma.common.data.serializer.DateSerializer; import id.co.sigma.common.data.serializer.IntegerSerializer; import id.co.sigma.common.data.serializer.LongSerializer; import id.co.sigma.common.data.serializer.StringSerializer; import id.co.sigma.common.data.serializer.VoidSerializer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * spoller object serializer * @author <NAME> */ public final class ObjectSerializerManager { private static ObjectSerializerManager instance ; /** * tipe data simple yang tidak di json kan */ public final static Class <?>[] SIMPLE_OBJECTS ={ Long.class , long.class , Integer.class , int.class , Float.class , float.class , Short.class , short.class , String.class , Boolean.class , boolean.class , Date.class , java.sql.Date.class , BigDecimal.class , BigInteger.class , Void.class }; /** * object as simple array. ini untuk kemudahan konversi */ public final static ArrayList<String> SIMPLE_OBJECT_ARRAY =new ArrayList<String>(); public static final ArrayList<String> SIMPLE_ARRAY_OFOBJECT_TYPES = new ArrayList<String>(); public static final String [] SIMPLE_TYPE_FQCNS = new String[SIMPLE_OBJECTS.length] ; static { for ( Class<?> scn : SIMPLE_OBJECTS){ SIMPLE_OBJECT_ARRAY.add(scn.getName()); SIMPLE_ARRAY_OFOBJECT_TYPES.add("[L" + scn.getName() +";"); } for (int i=0;i<SIMPLE_TYPE_FQCNS.length;i++){ SIMPLE_TYPE_FQCNS[i]=SIMPLE_OBJECTS[i].getName(); } } /** * mengecek object tipe simple atau tidak */ public static boolean isSimpleObject ( String fqcn ){ return SIMPLE_OBJECT_ARRAY.contains(fqcn); } /** * ini untuk mengecek array of simple object atau bukan **/ public boolean isArrayofSimpleObject ( String classFqcn ){ return SIMPLE_ARRAY_OFOBJECT_TYPES.contains(classFqcn); } private Map<String , ObjectSerializer<?>> indexedSerializer ; private ObjectSerializerManager () { indexedSerializer = new HashMap<String, ObjectSerializer<?>>(); registerSerializer(new BigDecimalSerializer()); registerSerializer(new BigIntegerSerializer()); registerSerializer(new BooleanSerializer()); registerSerializer(new DateSerializer()); registerSerializer(new IntegerSerializer()); registerSerializer(new LongSerializer()); registerSerializer(new VoidSerializer()); registerSerializer(new StringSerializer()); } /** * register serializer ke dalam manager */ public void registerSerializer (ObjectSerializer<?> serializer ){ if ( serializer==null || serializer.acceptedClassFQCNS()== null || serializer.acceptedClassFQCNS().length ==0) return ; for ( String scn : serializer.acceptedClassFQCNS()){ indexedSerializer.put(scn, serializer); } } public ObjectSerializer<?> getSerializer (String fqcn ){ return this.indexedSerializer.get(fqcn); } /** * checker apakah ada deserializer untuk object dengan fqcn yang di minta */ public boolean isHaveSerializer (String fqcn ) { return this.indexedSerializer.containsKey(fqcn); } public static ObjectSerializerManager getInstance() { if ( instance == null){ instance = new ObjectSerializerManager(); } return instance; } public static void main (String [] args){ System.out.println(Object[].class.getName()); } }
4,506
0.618794
0.618351
175
24.782858
24.92844
118
false
false
0
0
0
0
0
0
0.417143
false
false
13
9383043f53b8b90defd0b897958093d6f73f2141
2,516,850,838,508
a728fb0df57e107be863513cd1b55f2c5c847255
/common/src/main/java/com/backinbusiness/cs_t/common/ResponseData.java
7e2ba405e0129a47533dd3b5748e419830cf7d62
[]
no_license
Kirill-Lap/CloudStorageTest
https://github.com/Kirill-Lap/CloudStorageTest
02fd5d49c176c499794ede1860d8cae82b9e5bae
74a348c0a18f5ca4e2fb138b8b4b858308800bb3
refs/heads/master
2020-05-17T15:21:08.422000
2019-05-13T13:03:56
2019-05-13T13:03:56
183,788,367
0
0
null
false
2019-05-13T13:03:57
2019-04-27T15:13:24
2019-04-29T01:17:21
2019-05-13T13:03:57
12
0
0
0
Java
false
false
package com.backinbusiness.cs_t.common; public class ResponseData { private int intVal; public int getIntVal() { return intVal; } public void setIntVal(int intVal) { this.intVal = intVal; } @Override public String toString() { return "ResponseData{" + "intVal=" + intVal + '}'; } }
UTF-8
Java
374
java
ResponseData.java
Java
[]
null
[]
package com.backinbusiness.cs_t.common; public class ResponseData { private int intVal; public int getIntVal() { return intVal; } public void setIntVal(int intVal) { this.intVal = intVal; } @Override public String toString() { return "ResponseData{" + "intVal=" + intVal + '}'; } }
374
0.545455
0.545455
20
17.700001
14.156624
39
false
false
0
0
0
0
0
0
0.25
false
false
13
d1c3d3aac74d8e434a7b860c484d7d4e3d2aec0b
10,342,281,296,452
89787e3f116369ec8a9ee75885b18afc8483d0d0
/src/main/java/com/exa/pesa/core/views/checkpoint/LogbookView.java
8ca2cf10afbedd344611a0f7379d43e6c7a4edd8
[]
no_license
andresandoval/exa-pesa
https://github.com/andresandoval/exa-pesa
ed7e1735eedcf7af88d81042f1cdc0a2bf108d43
f7630bb8f2cf2849f882d2cf0c7cac254ea295e5
refs/heads/master
2023-01-29T07:35:01.522000
2017-12-28T03:52:54
2017-12-28T03:52:54
111,467,457
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.exa.pesa.core.views.checkpoint; import com.exa.pesa.core.model.checkpoint.Logbook; import com.exa.pesa.core.util.TimeUtils; import com.exa.pesa.core.views.business.ParameterView; import com.exa.pesa.core.views.parties.PersonView; import java.time.LocalDateTime; import java.util.Date; import java.util.Objects; /** * Created by Andres on 22/10/2017. */ public class LogbookView { private Integer id; private String inputDate; private String outputDate; private String name; private ParameterView vehicleType; private String vehiclePlate; private ParameterView vehicleColor; private PersonView contactPerson; private ParameterView area; private ParameterView materialType; private String observation; private ParameterView inputReason; private ParameterView outputReason; public LogbookView() { super(); } public LogbookView(Integer id, String inputDate, String outputDate, String name, ParameterView vehicleType, String vehiclePlate, ParameterView vehicleColor, PersonView contactPerson, ParameterView area, ParameterView materialType, String observation, ParameterView inputReason, ParameterView outputReason) { this.id = id; this.inputDate = inputDate; this.outputDate = outputDate; this.name = name; this.vehicleType = vehicleType; this.vehiclePlate = vehiclePlate; this.vehicleColor = vehicleColor; this.contactPerson = contactPerson; this.area = area; this.materialType = materialType; this.observation = observation; this.inputReason = inputReason; this.outputReason = outputReason; } public LogbookView(Logbook logBook) { this.id = logBook.getId(); this.inputDate = TimeUtils.localDateTimeToIsoString(logBook.getInputDate()); this.outputDate = TimeUtils.localDateTimeToIsoString(logBook.getOutputDate()); this.name = logBook.getName(); this.vehicleType = Objects.nonNull(logBook.getVehicleType()) ? new ParameterView(logBook.getVehicleType()) : null; this.vehiclePlate = logBook.getVehiclePlate(); this.vehicleColor = Objects.nonNull(logBook.getVehicleColor()) ? new ParameterView(logBook.getVehicleColor()) : null; this.contactPerson = Objects.nonNull(logBook.getContactPerson()) ? new PersonView(logBook.getContactPerson()) : null; this.area = Objects.nonNull(logBook.getArea()) ? new ParameterView(logBook.getArea()) : null; this.materialType = Objects.nonNull(logBook.getMaterialType()) ? new ParameterView(logBook.getMaterialType()) : null; this.observation = logBook.getObservation(); this.inputReason = Objects.nonNull(logBook.getInputReason()) ? new ParameterView(logBook.getInputReason()) : null; this.outputReason = Objects.nonNull(logBook.getOutputReason()) ? new ParameterView(logBook.getOutputReason()) : null; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getInputDate() { return inputDate; } public void setInputDate(String inputDate) { this.inputDate = inputDate; } public String getOutputDate() { return outputDate; } public void setOutputDate(String outputDate) { this.outputDate = outputDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ParameterView getVehicleType() { return vehicleType; } public void setVehicleType(ParameterView vehicleType) { this.vehicleType = vehicleType; } public String getVehiclePlate() { return vehiclePlate; } public void setVehiclePlate(String vehiclePlate) { this.vehiclePlate = vehiclePlate; } public ParameterView getVehicleColor() { return vehicleColor; } public void setVehicleColor(ParameterView vehicleColor) { this.vehicleColor = vehicleColor; } public PersonView getContactPerson() { return contactPerson; } public void setContactPerson(PersonView contactPerson) { this.contactPerson = contactPerson; } public ParameterView getArea() { return area; } public void setArea(ParameterView area) { this.area = area; } public ParameterView getMaterialType() { return materialType; } public void setMaterialType(ParameterView materialType) { this.materialType = materialType; } public String getObservation() { return observation; } public void setObservation(String observation) { this.observation = observation; } public ParameterView getInputReason() { return inputReason; } public void setInputReason(ParameterView inputReason) { this.inputReason = inputReason; } public ParameterView getOutputReason() { return outputReason; } public void setOutputReason(ParameterView outputReason) { this.outputReason = outputReason; } }
UTF-8
Java
5,308
java
LogbookView.java
Java
[ { "context": "Date;\nimport java.util.Objects;\n\n/**\n * Created by Andres on 22/10/2017.\n */\npublic class LogbookView {\n ", "end": 350, "score": 0.9931756258010864, "start": 344, "tag": "NAME", "value": "Andres" } ]
null
[]
package com.exa.pesa.core.views.checkpoint; import com.exa.pesa.core.model.checkpoint.Logbook; import com.exa.pesa.core.util.TimeUtils; import com.exa.pesa.core.views.business.ParameterView; import com.exa.pesa.core.views.parties.PersonView; import java.time.LocalDateTime; import java.util.Date; import java.util.Objects; /** * Created by Andres on 22/10/2017. */ public class LogbookView { private Integer id; private String inputDate; private String outputDate; private String name; private ParameterView vehicleType; private String vehiclePlate; private ParameterView vehicleColor; private PersonView contactPerson; private ParameterView area; private ParameterView materialType; private String observation; private ParameterView inputReason; private ParameterView outputReason; public LogbookView() { super(); } public LogbookView(Integer id, String inputDate, String outputDate, String name, ParameterView vehicleType, String vehiclePlate, ParameterView vehicleColor, PersonView contactPerson, ParameterView area, ParameterView materialType, String observation, ParameterView inputReason, ParameterView outputReason) { this.id = id; this.inputDate = inputDate; this.outputDate = outputDate; this.name = name; this.vehicleType = vehicleType; this.vehiclePlate = vehiclePlate; this.vehicleColor = vehicleColor; this.contactPerson = contactPerson; this.area = area; this.materialType = materialType; this.observation = observation; this.inputReason = inputReason; this.outputReason = outputReason; } public LogbookView(Logbook logBook) { this.id = logBook.getId(); this.inputDate = TimeUtils.localDateTimeToIsoString(logBook.getInputDate()); this.outputDate = TimeUtils.localDateTimeToIsoString(logBook.getOutputDate()); this.name = logBook.getName(); this.vehicleType = Objects.nonNull(logBook.getVehicleType()) ? new ParameterView(logBook.getVehicleType()) : null; this.vehiclePlate = logBook.getVehiclePlate(); this.vehicleColor = Objects.nonNull(logBook.getVehicleColor()) ? new ParameterView(logBook.getVehicleColor()) : null; this.contactPerson = Objects.nonNull(logBook.getContactPerson()) ? new PersonView(logBook.getContactPerson()) : null; this.area = Objects.nonNull(logBook.getArea()) ? new ParameterView(logBook.getArea()) : null; this.materialType = Objects.nonNull(logBook.getMaterialType()) ? new ParameterView(logBook.getMaterialType()) : null; this.observation = logBook.getObservation(); this.inputReason = Objects.nonNull(logBook.getInputReason()) ? new ParameterView(logBook.getInputReason()) : null; this.outputReason = Objects.nonNull(logBook.getOutputReason()) ? new ParameterView(logBook.getOutputReason()) : null; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getInputDate() { return inputDate; } public void setInputDate(String inputDate) { this.inputDate = inputDate; } public String getOutputDate() { return outputDate; } public void setOutputDate(String outputDate) { this.outputDate = outputDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ParameterView getVehicleType() { return vehicleType; } public void setVehicleType(ParameterView vehicleType) { this.vehicleType = vehicleType; } public String getVehiclePlate() { return vehiclePlate; } public void setVehiclePlate(String vehiclePlate) { this.vehiclePlate = vehiclePlate; } public ParameterView getVehicleColor() { return vehicleColor; } public void setVehicleColor(ParameterView vehicleColor) { this.vehicleColor = vehicleColor; } public PersonView getContactPerson() { return contactPerson; } public void setContactPerson(PersonView contactPerson) { this.contactPerson = contactPerson; } public ParameterView getArea() { return area; } public void setArea(ParameterView area) { this.area = area; } public ParameterView getMaterialType() { return materialType; } public void setMaterialType(ParameterView materialType) { this.materialType = materialType; } public String getObservation() { return observation; } public void setObservation(String observation) { this.observation = observation; } public ParameterView getInputReason() { return inputReason; } public void setInputReason(ParameterView inputReason) { this.inputReason = inputReason; } public ParameterView getOutputReason() { return outputReason; } public void setOutputReason(ParameterView outputReason) { this.outputReason = outputReason; } }
5,308
0.66786
0.666353
178
28.820225
28.140324
118
false
false
0
0
0
0
0
0
0.483146
false
false
13
6f88e948ccd0a15b6fb66be2a09eebf44d7cdbfe
19,439,021,999,789
7ff92936f085041dc46573a29722f7729aa86acb
/src/main/java/com/codefans/xml/XmlTest.java
37d811d0d9005672facf332826fad5986faa5bb9
[]
no_license
codefans/test-utf8
https://github.com/codefans/test-utf8
e6442ba04cf06c0c4350868ddeeda51e73e7ed30
96a6722e0e989805621b266703b1762beaa85aea
refs/heads/master
2017-04-27T15:25:04.514000
2017-04-22T01:29:32
2017-04-22T01:29:32
21,294,654
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.codefans.xml; public class XmlTest { /** * @param args */ public static void main(String[] args) { } }
UTF-8
Java
126
java
XmlTest.java
Java
[]
null
[]
package com.codefans.xml; public class XmlTest { /** * @param args */ public static void main(String[] args) { } }
126
0.619048
0.619048
12
9.5
12.809502
41
false
false
0
0
0
0
0
0
0.5
false
false
13
9437c7820fb38041c6156b36067c24c0dcdfeddf
2,963,527,436,967
ef7b307db032c9866bf47a5294c4470751cbdea8
/core-bc/composites/svc/src/main/java/se/vgregion/vardplatspusslet/service/PatientService.java
c6e52a2a5813d01761d144d9a754b6781834bef0
[]
no_license
Vastra-Gotalandsregionen/vardplatspusslet
https://github.com/Vastra-Gotalandsregionen/vardplatspusslet
c440ba1f86bd2604d1ddb5d85d2e80794ae9405b
f7b3597435559092a9f84e66bf6de371fc02cd59
refs/heads/master
2023-03-16T12:49:25.460000
2023-03-08T13:05:52
2023-03-08T13:05:52
150,435,351
0
1
null
false
2023-03-02T08:50:16
2018-09-26T13:58:13
2022-02-07T20:27:22
2023-03-02T08:50:16
4,743
0
0
34
Java
false
false
package se.vgregion.vardplatspusslet.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; import java.util.HashMap; import java.util.List; @Service @Transactional public class PatientService { private static final Logger LOGGER = LoggerFactory.getLogger(PatientService.class); @Autowired private DataSource dataSource; public void removeOrphanPatientsWithCareBurdenChoices() { NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // Query for patients who aren't in any bed nor any unit List<Long> orphanPatients = jdbcTemplate.queryForList("select p.id from patient p where p.id not in " + "(select distinct patient_id from bed where patient_id is not null) and p.id not in " + "(select patients_id from unit_patient)", Long.class); if (orphanPatients.size() > 0) { // Remove patientCareBurdenChoiceJoins MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("ids", orphanPatients); int update1 = namedParameterJdbcTemplate.update( "delete from patient_careburdenchoice pc where pc.patient_id in (:ids)", parameters ); // Remove patientExaminations namedParameterJdbcTemplate.update( "delete from patient_patientexamination ppe where ppe.patient_id in (:ids)", parameters ); namedParameterJdbcTemplate.update( "delete from patientexamination pe where pe.id not in " + "(select distinct patientexaminations_id from patient_patientexamination)", new HashMap<>() ); // Remove patientEvents namedParameterJdbcTemplate.update( "delete from patient_patientevent ppe where ppe.patient_id in (:ids)", parameters ); namedParameterJdbcTemplate.update( "delete from patientevent pe where pe.id not in " + "(select distinct patientevents_id from patient_patientevent)", new HashMap<>() ); // Remove patients int update = namedParameterJdbcTemplate.update("delete from patient where id in (:ids)", parameters); LOGGER.info("Deleted " + update + " orphan patient entries and " + update1 + " patient_careburdenchoices"); } // Select all careburdenchoices which have no connection to patient. List<Long> orphanCareBurdenChoices = jdbcTemplate.queryForList("select id from careburdenchoice cbc" + " where cbc.id not in " + "(select distinct careburdenchoices_id from patient_careburdenchoice)", Long.class); if (orphanCareBurdenChoices.size() > 0) { MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("ids", orphanCareBurdenChoices); int update = namedParameterJdbcTemplate.update("delete from careburdenchoice where id in (:ids)", parameters); LOGGER.info("Deleted " + update + " orphan careburdenchoice entries."); } } }
UTF-8
Java
3,809
java
PatientService.java
Java
[]
null
[]
package se.vgregion.vardplatspusslet.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.sql.DataSource; import java.util.HashMap; import java.util.List; @Service @Transactional public class PatientService { private static final Logger LOGGER = LoggerFactory.getLogger(PatientService.class); @Autowired private DataSource dataSource; public void removeOrphanPatientsWithCareBurdenChoices() { NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // Query for patients who aren't in any bed nor any unit List<Long> orphanPatients = jdbcTemplate.queryForList("select p.id from patient p where p.id not in " + "(select distinct patient_id from bed where patient_id is not null) and p.id not in " + "(select patients_id from unit_patient)", Long.class); if (orphanPatients.size() > 0) { // Remove patientCareBurdenChoiceJoins MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("ids", orphanPatients); int update1 = namedParameterJdbcTemplate.update( "delete from patient_careburdenchoice pc where pc.patient_id in (:ids)", parameters ); // Remove patientExaminations namedParameterJdbcTemplate.update( "delete from patient_patientexamination ppe where ppe.patient_id in (:ids)", parameters ); namedParameterJdbcTemplate.update( "delete from patientexamination pe where pe.id not in " + "(select distinct patientexaminations_id from patient_patientexamination)", new HashMap<>() ); // Remove patientEvents namedParameterJdbcTemplate.update( "delete from patient_patientevent ppe where ppe.patient_id in (:ids)", parameters ); namedParameterJdbcTemplate.update( "delete from patientevent pe where pe.id not in " + "(select distinct patientevents_id from patient_patientevent)", new HashMap<>() ); // Remove patients int update = namedParameterJdbcTemplate.update("delete from patient where id in (:ids)", parameters); LOGGER.info("Deleted " + update + " orphan patient entries and " + update1 + " patient_careburdenchoices"); } // Select all careburdenchoices which have no connection to patient. List<Long> orphanCareBurdenChoices = jdbcTemplate.queryForList("select id from careburdenchoice cbc" + " where cbc.id not in " + "(select distinct careburdenchoices_id from patient_careburdenchoice)", Long.class); if (orphanCareBurdenChoices.size() > 0) { MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("ids", orphanCareBurdenChoices); int update = namedParameterJdbcTemplate.update("delete from careburdenchoice where id in (:ids)", parameters); LOGGER.info("Deleted " + update + " orphan careburdenchoice entries."); } } }
3,809
0.65424
0.652665
89
41.797752
35.74321
122
false
false
0
0
0
0
0
0
0.47191
false
false
13
1b0bafd90a80f9a36740c324e68d67e52df409c4
6,854,767,857,424
7a45adbda050f4c4420b8d7aa361f7ac4bd3a94c
/logcollection/src/main/java/com/xhw/logcollection/job/entity/ConfigurationBean.java
57a97578928a4bdbd277c2f03461fb93397dbde8
[]
no_license
hufabo/learngit
https://github.com/hufabo/learngit
3d929b987e8ddf361c94b9b12d40ad7c68893b1e
f6dd6cb68a701a68cd2d6ea80e65e31d0e26eb2c
refs/heads/master
2020-03-23T15:17:37.421000
2018-07-21T03:13:14
2018-07-21T03:13:14
141,736,064
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xhw.logcollection.job.entity; /** * 后端任务配置参数 * * @author yangconghong * @version 0.0.1 * @date 2018-02-09 * @note * @update 修改日期 修改人 修改内容 * ----------------------------------------------- */ public class ConfigurationBean { //日志解析文件传输守护线程任务 private int intervalTimeFilePutDeamon = 30*1000; private String patternFilePutDeamon; //错误数据重传守护线程任务 private int intervalTimeFileRePutDeamon = 30*1000; private String patternFileRePutDeamon; //日志解析文件反馈处理守护线程任务 private int intervalTimeFileResultStatusDeamon = 30*1000; private String patternFileResultStatusDeamon; //HTTP传输守护线程任务 private int intervalTimeHttpInteractionDeamon = 30*1000; private String patternHttpInteractionDeamon; //增量数据采集守护线程执行任务 private int intervalTimeIncrExecuteDeamon = 30*1000; private String patternIncrExecuteDeamon; //增量数据采集守护线程拆分任务 private int intervalTimeIncrSplitDeamon = 30*1000; private String patternIncrSplitDeamon; //增量数据Oracle归档文件或在线文件的采集守护线程任务 private int intervalTimeIncrGetSourceFileDeamon = 30*1000; private String patternIncrGetSourceFileDeamon; //心跳状态上报守护线程任务 private int intervalTimeReportHeartbeatDeamon = 30*1000; private String patternReportHeartbeatDeamon; //存量数据采集守护线程执行任务 private int intervalTimeStockExecuteDeamon = 30*1000; private String patternStockExecuteDeamon; //存量数据采集守护线程拆分任务 private int intervalTimeStockSplitDeamon = 30*1000; private String patternStockSplitDeamon; //采集策略更新守护线程任务 private int intervalTimeUpdateStrategyDeamon = 30*1000; private String patternUpdateStrategyDeamon; //系统运行状态统计任务周期 private int intervalTimeRunlogDeamon = 24 * 60 * 60 * 1000 ; private String patternRunlogDeamon; //每日采集情况统计任务(时间点) private int timePointMonitorStatDeamon = 2; private String patternMonitorStatDeamon; private String patternIncrIntegratedDeamon; public int getIntervalTimeFilePutDeamon() { return intervalTimeFilePutDeamon; } public void setIntervalTimeFilePutDeamon(int intervalTimeFilePutDeamon) { this.intervalTimeFilePutDeamon = intervalTimeFilePutDeamon; } public int getIntervalTimeFileRePutDeamon() { return intervalTimeFileRePutDeamon; } public void setIntervalTimeFileRePutDeamon(int intervalTimeFileRePutDeamon) { this.intervalTimeFileRePutDeamon = intervalTimeFileRePutDeamon; } public int getIntervalTimeFileResultStatusDeamon() { return intervalTimeFileResultStatusDeamon; } public void setIntervalTimeFileResultStatusDeamon(int intervalTimeFileResultStatusDeamon) { this.intervalTimeFileResultStatusDeamon = intervalTimeFileResultStatusDeamon; } public int getIntervalTimeHttpInteractionDeamon() { return intervalTimeHttpInteractionDeamon; } public void setIntervalTimeHttpInteractionDeamon(int intervalTimeHttpInteractionDeamon) { this.intervalTimeHttpInteractionDeamon = intervalTimeHttpInteractionDeamon; } public int getIntervalTimeIncrExecuteDeamon() { return intervalTimeIncrExecuteDeamon; } public void setIntervalTimeIncrExecuteDeamon(int intervalTimeIncrExecuteDeamon) { this.intervalTimeIncrExecuteDeamon = intervalTimeIncrExecuteDeamon; } public int getIntervalTimeIncrSplitDeamon() { return intervalTimeIncrSplitDeamon; } public void setIntervalTimeIncrSplitDeamon(int intervalTimeIncrSplitDeamon) { this.intervalTimeIncrSplitDeamon = intervalTimeIncrSplitDeamon; } public int getIntervalTimeReportHeartbeatDeamon() { return intervalTimeReportHeartbeatDeamon; } public void setIntervalTimeReportHeartbeatDeamon(int intervalTimeReportHeartbeatDeamon) { this.intervalTimeReportHeartbeatDeamon = intervalTimeReportHeartbeatDeamon; } public int getIntervalTimeStockExecuteDeamon() { return intervalTimeStockExecuteDeamon; } public void setIntervalTimeStockExecuteDeamon(int intervalTimeStockExecuteDeamon) { this.intervalTimeStockExecuteDeamon = intervalTimeStockExecuteDeamon; } public int getIntervalTimeStockSplitDeamon() { return intervalTimeStockSplitDeamon; } public void setIntervalTimeStockSplitDeamon(int intervalTimeStockSplitDeamon) { this.intervalTimeStockSplitDeamon = intervalTimeStockSplitDeamon; } public int getIntervalTimeUpdateStrategyDeamon() { return intervalTimeUpdateStrategyDeamon; } public void setIntervalTimeUpdateStrategyDeamon(int intervalTimeUpdateStrategyDeamon) { this.intervalTimeUpdateStrategyDeamon = intervalTimeUpdateStrategyDeamon; } public int getIntervalTimeIncrGetSourceFileDeamon() { return intervalTimeIncrGetSourceFileDeamon; } public void setIntervalTimeIncrGetSourceFileDeamon(int value) { this.intervalTimeIncrGetSourceFileDeamon = value; } public int getIntervalTimeRunlogDeamon() { return intervalTimeRunlogDeamon; } public void setIntervalTimeRunlogDeamon(int intervalTimeRunlogDeamon) { this.intervalTimeRunlogDeamon = intervalTimeRunlogDeamon; } public int getTimePointMonitorStatDeamon() { return timePointMonitorStatDeamon; } public void setTimePointMonitorStatDeamon(int timePointMonitorStatDeamon) { this.timePointMonitorStatDeamon = timePointMonitorStatDeamon; } public String getPatternFilePutDeamon() { return patternFilePutDeamon; } public void setPatternFilePutDeamon(String patternFilePutDeamon) { this.patternFilePutDeamon = patternFilePutDeamon; } public String getPatternFileRePutDeamon() { return patternFileRePutDeamon; } public void setPatternFileRePutDeamon(String patternFileRePutDeamon) { this.patternFileRePutDeamon = patternFileRePutDeamon; } public String getPatternFileResultStatusDeamon() { return patternFileResultStatusDeamon; } public void setPatternFileResultStatusDeamon(String patternFileResultStatusDeamon) { this.patternFileResultStatusDeamon = patternFileResultStatusDeamon; } public String getPatternHttpInteractionDeamon() { return patternHttpInteractionDeamon; } public void setPatternHttpInteractionDeamon(String patternHttpInteractionDeamon) { this.patternHttpInteractionDeamon = patternHttpInteractionDeamon; } public String getPatternIncrExecuteDeamon() { return patternIncrExecuteDeamon; } public void setPatternIncrExecuteDeamon(String patternIncrExecuteDeamon) { this.patternIncrExecuteDeamon = patternIncrExecuteDeamon; } public String getPatternIncrSplitDeamon() { return patternIncrSplitDeamon; } public void setPatternIncrSplitDeamon(String patternIncrSplitDeamon) { this.patternIncrSplitDeamon = patternIncrSplitDeamon; } public String getPatternIncrGetSourceFileDeamon() { return patternIncrGetSourceFileDeamon; } public void setPatternIncrGetSourceFileDeamon(String patternIncrGetSourceFileDeamon) { this.patternIncrGetSourceFileDeamon = patternIncrGetSourceFileDeamon; } public String getPatternReportHeartbeatDeamon() { return patternReportHeartbeatDeamon; } public void setPatternReportHeartbeatDeamon(String patternReportHeartbeatDeamon) { this.patternReportHeartbeatDeamon = patternReportHeartbeatDeamon; } public String getPatternStockExecuteDeamon() { return patternStockExecuteDeamon; } public void setPatternStockExecuteDeamon(String patternStockExecuteDeamon) { this.patternStockExecuteDeamon = patternStockExecuteDeamon; } public String getPatternStockSplitDeamon() { return patternStockSplitDeamon; } public void setPatternStockSplitDeamon(String patternStockSplitDeamon) { this.patternStockSplitDeamon = patternStockSplitDeamon; } public String getPatternUpdateStrategyDeamon() { return patternUpdateStrategyDeamon; } public void setPatternUpdateStrategyDeamon(String patternUpdateStrategyDeamon) { this.patternUpdateStrategyDeamon = patternUpdateStrategyDeamon; } public String getPatternRunlogDeamon() { return patternRunlogDeamon; } public void setPatternRunlogDeamon(String patternRunlogDeamon) { this.patternRunlogDeamon = patternRunlogDeamon; } public String getPatternMonitorStatDeamon() { return patternMonitorStatDeamon; } public void setPatternMonitorStatDeamon(String patternMonitorStatDeamon) { this.patternMonitorStatDeamon = patternMonitorStatDeamon; } public String getPatternIncrIntegratedDeamon() { return patternIncrIntegratedDeamon; } public void setPatternIncrIntegratedDeamon(String patternIncrIntegratedDeamon) { this.patternIncrIntegratedDeamon = patternIncrIntegratedDeamon; } }
UTF-8
Java
9,463
java
ConfigurationBean.java
Java
[ { "context": "lection.job.entity;\n\n/**\n * 后端任务配置参数\n *\n * @author yangconghong\n * @version 0.0.1\n * @date 2018-02-09\n * @note\n *", "end": 85, "score": 0.9987571239471436, "start": 73, "tag": "USERNAME", "value": "yangconghong" } ]
null
[]
package com.xhw.logcollection.job.entity; /** * 后端任务配置参数 * * @author yangconghong * @version 0.0.1 * @date 2018-02-09 * @note * @update 修改日期 修改人 修改内容 * ----------------------------------------------- */ public class ConfigurationBean { //日志解析文件传输守护线程任务 private int intervalTimeFilePutDeamon = 30*1000; private String patternFilePutDeamon; //错误数据重传守护线程任务 private int intervalTimeFileRePutDeamon = 30*1000; private String patternFileRePutDeamon; //日志解析文件反馈处理守护线程任务 private int intervalTimeFileResultStatusDeamon = 30*1000; private String patternFileResultStatusDeamon; //HTTP传输守护线程任务 private int intervalTimeHttpInteractionDeamon = 30*1000; private String patternHttpInteractionDeamon; //增量数据采集守护线程执行任务 private int intervalTimeIncrExecuteDeamon = 30*1000; private String patternIncrExecuteDeamon; //增量数据采集守护线程拆分任务 private int intervalTimeIncrSplitDeamon = 30*1000; private String patternIncrSplitDeamon; //增量数据Oracle归档文件或在线文件的采集守护线程任务 private int intervalTimeIncrGetSourceFileDeamon = 30*1000; private String patternIncrGetSourceFileDeamon; //心跳状态上报守护线程任务 private int intervalTimeReportHeartbeatDeamon = 30*1000; private String patternReportHeartbeatDeamon; //存量数据采集守护线程执行任务 private int intervalTimeStockExecuteDeamon = 30*1000; private String patternStockExecuteDeamon; //存量数据采集守护线程拆分任务 private int intervalTimeStockSplitDeamon = 30*1000; private String patternStockSplitDeamon; //采集策略更新守护线程任务 private int intervalTimeUpdateStrategyDeamon = 30*1000; private String patternUpdateStrategyDeamon; //系统运行状态统计任务周期 private int intervalTimeRunlogDeamon = 24 * 60 * 60 * 1000 ; private String patternRunlogDeamon; //每日采集情况统计任务(时间点) private int timePointMonitorStatDeamon = 2; private String patternMonitorStatDeamon; private String patternIncrIntegratedDeamon; public int getIntervalTimeFilePutDeamon() { return intervalTimeFilePutDeamon; } public void setIntervalTimeFilePutDeamon(int intervalTimeFilePutDeamon) { this.intervalTimeFilePutDeamon = intervalTimeFilePutDeamon; } public int getIntervalTimeFileRePutDeamon() { return intervalTimeFileRePutDeamon; } public void setIntervalTimeFileRePutDeamon(int intervalTimeFileRePutDeamon) { this.intervalTimeFileRePutDeamon = intervalTimeFileRePutDeamon; } public int getIntervalTimeFileResultStatusDeamon() { return intervalTimeFileResultStatusDeamon; } public void setIntervalTimeFileResultStatusDeamon(int intervalTimeFileResultStatusDeamon) { this.intervalTimeFileResultStatusDeamon = intervalTimeFileResultStatusDeamon; } public int getIntervalTimeHttpInteractionDeamon() { return intervalTimeHttpInteractionDeamon; } public void setIntervalTimeHttpInteractionDeamon(int intervalTimeHttpInteractionDeamon) { this.intervalTimeHttpInteractionDeamon = intervalTimeHttpInteractionDeamon; } public int getIntervalTimeIncrExecuteDeamon() { return intervalTimeIncrExecuteDeamon; } public void setIntervalTimeIncrExecuteDeamon(int intervalTimeIncrExecuteDeamon) { this.intervalTimeIncrExecuteDeamon = intervalTimeIncrExecuteDeamon; } public int getIntervalTimeIncrSplitDeamon() { return intervalTimeIncrSplitDeamon; } public void setIntervalTimeIncrSplitDeamon(int intervalTimeIncrSplitDeamon) { this.intervalTimeIncrSplitDeamon = intervalTimeIncrSplitDeamon; } public int getIntervalTimeReportHeartbeatDeamon() { return intervalTimeReportHeartbeatDeamon; } public void setIntervalTimeReportHeartbeatDeamon(int intervalTimeReportHeartbeatDeamon) { this.intervalTimeReportHeartbeatDeamon = intervalTimeReportHeartbeatDeamon; } public int getIntervalTimeStockExecuteDeamon() { return intervalTimeStockExecuteDeamon; } public void setIntervalTimeStockExecuteDeamon(int intervalTimeStockExecuteDeamon) { this.intervalTimeStockExecuteDeamon = intervalTimeStockExecuteDeamon; } public int getIntervalTimeStockSplitDeamon() { return intervalTimeStockSplitDeamon; } public void setIntervalTimeStockSplitDeamon(int intervalTimeStockSplitDeamon) { this.intervalTimeStockSplitDeamon = intervalTimeStockSplitDeamon; } public int getIntervalTimeUpdateStrategyDeamon() { return intervalTimeUpdateStrategyDeamon; } public void setIntervalTimeUpdateStrategyDeamon(int intervalTimeUpdateStrategyDeamon) { this.intervalTimeUpdateStrategyDeamon = intervalTimeUpdateStrategyDeamon; } public int getIntervalTimeIncrGetSourceFileDeamon() { return intervalTimeIncrGetSourceFileDeamon; } public void setIntervalTimeIncrGetSourceFileDeamon(int value) { this.intervalTimeIncrGetSourceFileDeamon = value; } public int getIntervalTimeRunlogDeamon() { return intervalTimeRunlogDeamon; } public void setIntervalTimeRunlogDeamon(int intervalTimeRunlogDeamon) { this.intervalTimeRunlogDeamon = intervalTimeRunlogDeamon; } public int getTimePointMonitorStatDeamon() { return timePointMonitorStatDeamon; } public void setTimePointMonitorStatDeamon(int timePointMonitorStatDeamon) { this.timePointMonitorStatDeamon = timePointMonitorStatDeamon; } public String getPatternFilePutDeamon() { return patternFilePutDeamon; } public void setPatternFilePutDeamon(String patternFilePutDeamon) { this.patternFilePutDeamon = patternFilePutDeamon; } public String getPatternFileRePutDeamon() { return patternFileRePutDeamon; } public void setPatternFileRePutDeamon(String patternFileRePutDeamon) { this.patternFileRePutDeamon = patternFileRePutDeamon; } public String getPatternFileResultStatusDeamon() { return patternFileResultStatusDeamon; } public void setPatternFileResultStatusDeamon(String patternFileResultStatusDeamon) { this.patternFileResultStatusDeamon = patternFileResultStatusDeamon; } public String getPatternHttpInteractionDeamon() { return patternHttpInteractionDeamon; } public void setPatternHttpInteractionDeamon(String patternHttpInteractionDeamon) { this.patternHttpInteractionDeamon = patternHttpInteractionDeamon; } public String getPatternIncrExecuteDeamon() { return patternIncrExecuteDeamon; } public void setPatternIncrExecuteDeamon(String patternIncrExecuteDeamon) { this.patternIncrExecuteDeamon = patternIncrExecuteDeamon; } public String getPatternIncrSplitDeamon() { return patternIncrSplitDeamon; } public void setPatternIncrSplitDeamon(String patternIncrSplitDeamon) { this.patternIncrSplitDeamon = patternIncrSplitDeamon; } public String getPatternIncrGetSourceFileDeamon() { return patternIncrGetSourceFileDeamon; } public void setPatternIncrGetSourceFileDeamon(String patternIncrGetSourceFileDeamon) { this.patternIncrGetSourceFileDeamon = patternIncrGetSourceFileDeamon; } public String getPatternReportHeartbeatDeamon() { return patternReportHeartbeatDeamon; } public void setPatternReportHeartbeatDeamon(String patternReportHeartbeatDeamon) { this.patternReportHeartbeatDeamon = patternReportHeartbeatDeamon; } public String getPatternStockExecuteDeamon() { return patternStockExecuteDeamon; } public void setPatternStockExecuteDeamon(String patternStockExecuteDeamon) { this.patternStockExecuteDeamon = patternStockExecuteDeamon; } public String getPatternStockSplitDeamon() { return patternStockSplitDeamon; } public void setPatternStockSplitDeamon(String patternStockSplitDeamon) { this.patternStockSplitDeamon = patternStockSplitDeamon; } public String getPatternUpdateStrategyDeamon() { return patternUpdateStrategyDeamon; } public void setPatternUpdateStrategyDeamon(String patternUpdateStrategyDeamon) { this.patternUpdateStrategyDeamon = patternUpdateStrategyDeamon; } public String getPatternRunlogDeamon() { return patternRunlogDeamon; } public void setPatternRunlogDeamon(String patternRunlogDeamon) { this.patternRunlogDeamon = patternRunlogDeamon; } public String getPatternMonitorStatDeamon() { return patternMonitorStatDeamon; } public void setPatternMonitorStatDeamon(String patternMonitorStatDeamon) { this.patternMonitorStatDeamon = patternMonitorStatDeamon; } public String getPatternIncrIntegratedDeamon() { return patternIncrIntegratedDeamon; } public void setPatternIncrIntegratedDeamon(String patternIncrIntegratedDeamon) { this.patternIncrIntegratedDeamon = patternIncrIntegratedDeamon; } }
9,463
0.758244
0.748539
272
32.33456
29.664085
95
false
false
0
0
0
0
0
0
0.397059
false
false
13
683c6f7329c5ce250b0c2e32e68ba4a6d1b1596d
4,509,715,709,873
e56523d69ed15a32068c6a20e836bfc7a210696c
/src/colgen/Instance.java
0513de45fa0cd638d4fd2656439e185246254816
[ "MIT" ]
permissive
pcbouman-eur/JavaCplexExample
https://github.com/pcbouman-eur/JavaCplexExample
25d4f385a109ae2b79f8b67a938acdd6de8bc06f
40c83f6cd2de6b83e34c1e75faaaaacc5ed86636
refs/heads/master
2023-02-22T10:35:24.803000
2023-02-15T09:35:37
2023-02-15T09:35:37
116,706,341
26
7
null
null
null
null
null
null
null
null
null
null
null
null
null
package colgen; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import java.util.Set; /** * This class models an instance of the cutting-stock problem. * The cutting stock problem consists of a number of orders * of certain sizes. The question is how we can most efficiently * cut the orders out of larger stock such that we need the least * amount of large stock. * * For example, we have to produce metal bars. The orders indicate * how many bars of a certain length we must produce. The capacity * indicates how long a bar is that we can cut up into smallers bars * required for the order. The goal is to cut up as few large bars * as possible. * @author Paul Bouman * */ public class Instance { private int capacity; private Map<Integer,Integer> orders; /** * Creates a cutting stock instance based on the provided orders and a capacity * @param orders the orders that need to be produced * @param capacity the length or capacity of the base stock we must cut up */ public Instance(Map<Integer,Integer> orders, int capacity) { this.orders = new LinkedHashMap<>(orders); this.capacity = capacity; } /** * Provides a list of sizes that occur in the orders in this instance. * The size of the order is the amount of stock required to produce a * single item of a particular size. * @return a list with the sizes of the order. */ public Set<Integer> getSizes() { return Collections.unmodifiableSet(orders.keySet()); } /** * Provides how many copies of items of the provides size need to be * produces * @param size the size of the item to be produced * @return how many copies of the item must be produced */ public int getAmount(int size) { return orders.getOrDefault(size, 0); } /** * Provides the capacity of a unit of base stock that will be cut up * in order to produce the items in the orders. * @return the capacity of a unit of base stock */ public int getCapacity() { return capacity; } /** * Method that can be used to generate a random cutting-stock instance * @param seed a random seed * @param orders the number unique sizes that occur in the orders * @param maxStep the maximum step size of the sizes in the orders * @param maxAmount the maximum amount that can be ordered of a single size * @return a random instance based on the provided information */ public static Instance randomInstance(long seed, int orders, int maxStep, int maxAmount) { Random ran = new Random(seed); Map<Integer,Integer> map = new LinkedHashMap<>(); int curLength = 0; for (int t=0; t < orders; t++) { curLength += 1 + ran.nextInt(maxStep); int amount = 1 + ran.nextInt(maxAmount); map.put(curLength, amount); } curLength += 1 + ran.nextInt(maxStep); return new Instance(map, curLength); } @Override public String toString() { return "Instance [capacity=" + capacity + ", orders=" + orders + "]"; } }
UTF-8
Java
2,992
java
Instance.java
Java
[ { "context": "ut up as few large bars\n * as possible.\n * @author Paul Bouman\n *\n */\npublic class Instance\n{\n\tprivate int capac", "end": 744, "score": 0.9997575283050537, "start": 733, "tag": "NAME", "value": "Paul Bouman" } ]
null
[]
package colgen; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import java.util.Set; /** * This class models an instance of the cutting-stock problem. * The cutting stock problem consists of a number of orders * of certain sizes. The question is how we can most efficiently * cut the orders out of larger stock such that we need the least * amount of large stock. * * For example, we have to produce metal bars. The orders indicate * how many bars of a certain length we must produce. The capacity * indicates how long a bar is that we can cut up into smallers bars * required for the order. The goal is to cut up as few large bars * as possible. * @author <NAME> * */ public class Instance { private int capacity; private Map<Integer,Integer> orders; /** * Creates a cutting stock instance based on the provided orders and a capacity * @param orders the orders that need to be produced * @param capacity the length or capacity of the base stock we must cut up */ public Instance(Map<Integer,Integer> orders, int capacity) { this.orders = new LinkedHashMap<>(orders); this.capacity = capacity; } /** * Provides a list of sizes that occur in the orders in this instance. * The size of the order is the amount of stock required to produce a * single item of a particular size. * @return a list with the sizes of the order. */ public Set<Integer> getSizes() { return Collections.unmodifiableSet(orders.keySet()); } /** * Provides how many copies of items of the provides size need to be * produces * @param size the size of the item to be produced * @return how many copies of the item must be produced */ public int getAmount(int size) { return orders.getOrDefault(size, 0); } /** * Provides the capacity of a unit of base stock that will be cut up * in order to produce the items in the orders. * @return the capacity of a unit of base stock */ public int getCapacity() { return capacity; } /** * Method that can be used to generate a random cutting-stock instance * @param seed a random seed * @param orders the number unique sizes that occur in the orders * @param maxStep the maximum step size of the sizes in the orders * @param maxAmount the maximum amount that can be ordered of a single size * @return a random instance based on the provided information */ public static Instance randomInstance(long seed, int orders, int maxStep, int maxAmount) { Random ran = new Random(seed); Map<Integer,Integer> map = new LinkedHashMap<>(); int curLength = 0; for (int t=0; t < orders; t++) { curLength += 1 + ran.nextInt(maxStep); int amount = 1 + ran.nextInt(maxAmount); map.put(curLength, amount); } curLength += 1 + ran.nextInt(maxStep); return new Instance(map, curLength); } @Override public String toString() { return "Instance [capacity=" + capacity + ", orders=" + orders + "]"; } }
2,987
0.710227
0.708222
98
29.530613
26.298212
89
false
false
0
0
0
0
0
0
1.306122
false
false
13
088b6684c7c987de7ebf7dfcf081c41905e88774
38,852,274,168,066
42a9e83d8d9e4e940b49cc9763febdc972d06989
/userservice/app/com/cementify/userservice/settings/Global.java
3e07aba81c3a4cdbfeecd6c9d6b3fed95a2fb3ed
[ "Apache-2.0" ]
permissive
rnjailamba/foundationStone
https://github.com/rnjailamba/foundationStone
c79a1eb26ed8bff0c1bd7cacee5e58deebc342c3
4aa9b34c3cfb1688c67a51df38900615e8ceaf8b
refs/heads/master
2021-05-01T11:55:11.009000
2016-04-13T06:55:29
2016-04-13T06:55:29
52,734,667
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cementify.userservice.settings; /** * Created by roshan on 19/01/16. */ import play.Application; import play.GlobalSettings; import play.Logger; import play.mvc.Action; import play.mvc.Http; import java.lang.reflect.Method; public class Global extends GlobalSettings { public void onStart(Application app) { Logger.info("Application has started"); } public void onStop(Application app) { Logger.info("Application shutdown..."); } public Action onRequest(Http.Request request, Method actionMethod) { Logger.info("before each request..." + request.toString()); return super.onRequest(request, actionMethod); } }
UTF-8
Java
689
java
Global.java
Java
[ { "context": "cementify.userservice.settings;\n\n/**\n * Created by roshan on 19/01/16.\n */\n\nimport play.Application;\nimport", "end": 69, "score": 0.9992780089378357, "start": 63, "tag": "USERNAME", "value": "roshan" } ]
null
[]
package com.cementify.userservice.settings; /** * Created by roshan on 19/01/16. */ import play.Application; import play.GlobalSettings; import play.Logger; import play.mvc.Action; import play.mvc.Http; import java.lang.reflect.Method; public class Global extends GlobalSettings { public void onStart(Application app) { Logger.info("Application has started"); } public void onStop(Application app) { Logger.info("Application shutdown..."); } public Action onRequest(Http.Request request, Method actionMethod) { Logger.info("before each request..." + request.toString()); return super.onRequest(request, actionMethod); } }
689
0.699565
0.690856
30
21.933332
22.096657
72
false
false
0
0
0
0
0
0
0.433333
false
false
13
ddc786d77f2962b1820ce4ac525130e7e07bff98
11,854,109,803,520
45a1c1d880e5f4d3fb733b99ef8c22be3ab491ae
/my_coderside/tensquare_parent/tensquare_recruit/src/main/java/com/tensquare/recruit/pojo/entity/Enterprise.java
4fa78fcba08374b74a425acd22380cac7a2f0960
[]
no_license
zhu-xiu/codersite
https://github.com/zhu-xiu/codersite
16673ed94f6a8889f08385e7e633b83657ee5117
06759eedfa0666890b6792973829fe25e4511bcd
refs/heads/master
2020-08-10T01:17:08.233000
2019-10-28T14:34:10
2019-10-28T14:34:10
214,219,048
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tensquare.recruit.pojo.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * 数据表实体类 * @author root */ @Entity @Table(name = "tb_enterprise") @Data public class Enterprise { /** * ID */ @Id private String id; /** * 企业名称 */ private String name; /** * 企业简介 */ private String summary; /** * 企业地址 */ private String address; /** * 标签列表,用逗号分割 */ private String labels; /** * 企业坐标位置,经度纬度 */ private String coordinate; /** * 是否热门,0:非热门  1:热门 */ private String isHot; /** * LOGO */ private String logo; /** * 职位数 */ private String jobCount; /** * URL */ private String url; }
UTF-8
Java
969
java
Enterprise.java
Java
[ { "context": "javax.persistence.Table;\n\n/**\n * 数据表实体类\n * @author root\n */\n@Entity\n@Table(name = \"tb_enterprise\")\n@Data\n", "end": 188, "score": 0.9989333152770996, "start": 184, "tag": "USERNAME", "value": "root" } ]
null
[]
package com.tensquare.recruit.pojo.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * 数据表实体类 * @author root */ @Entity @Table(name = "tb_enterprise") @Data public class Enterprise { /** * ID */ @Id private String id; /** * 企业名称 */ private String name; /** * 企业简介 */ private String summary; /** * 企业地址 */ private String address; /** * 标签列表,用逗号分割 */ private String labels; /** * 企业坐标位置,经度纬度 */ private String coordinate; /** * 是否热门,0:非热门  1:热门 */ private String isHot; /** * LOGO */ private String logo; /** * 职位数 */ private String jobCount; /** * URL */ private String url; }
969
0.516999
0.514654
68
11.544118
10.377342
42
false
false
0
0
0
0
0
0
0.220588
false
false
13
c342feebee109faade0865ce75ccf6841819c324
38,525,856,656,135
368d983ab780e67fcead1562bf7cd14b3d0f350e
/dmit2015-jsp-servlet-demo/src/main/java/ca/nait/dmit/servlet/CircleServlet.java
a147fa5a381130287e0ba124130e62b9bfd1ea0c
[]
no_license
DMIT-2015/dmit2015-oa02-1201-demos
https://github.com/DMIT-2015/dmit2015-oa02-1201-demos
8ad1e369be7b502af8988fb90e2133525832b5ae
020b52f3d488e7623c7fe269fdb5bfda9e8af41e
refs/heads/master
2023-02-02T05:03:25.264000
2020-12-17T18:55:09
2020-12-17T18:55:09
297,771,007
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package ca.nait.dmit.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Set; 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 javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import ca.nait.dmit.domain.Circle; /** * Servlet implementation class CircleServlet */ @WebServlet("/servlet/CircleServlet") public class CircleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CircleServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Retrieve the radius value from the request String radiusString = request.getParameter("radius"); // Convert the radius from a String to a double double radius = Double.parseDouble(radiusString); // Construct with Circle with the radius Circle circle1 = new Circle(radius); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Circle>> constraintViolations = validator.validate(circle1, javax.validation.groups.Default.class); // Output the area and perimeter of the circle directly to the HTTP response PrintWriter out = response.getWriter(); if (constraintViolations.size() > 0) { out.println("<p>Please fix the following error: " + constraintViolations.iterator().next().getMessage() + "</p>"); } else { out.println("<p>The area is <strong>" + circle1.area() + "</strong> for a radius of " + radius + "</p>"); out.println("<p>The perimeter is <strong>" + circle1.circumference() + "</strong> for a radius of " + radius + "</p>"); } out.close(); } /** * @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); } }
UTF-8
Java
2,469
java
CircleServlet.java
Java
[]
null
[]
package ca.nait.dmit.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Set; 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 javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import ca.nait.dmit.domain.Circle; /** * Servlet implementation class CircleServlet */ @WebServlet("/servlet/CircleServlet") public class CircleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CircleServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Retrieve the radius value from the request String radiusString = request.getParameter("radius"); // Convert the radius from a String to a double double radius = Double.parseDouble(radiusString); // Construct with Circle with the radius Circle circle1 = new Circle(radius); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Circle>> constraintViolations = validator.validate(circle1, javax.validation.groups.Default.class); // Output the area and perimeter of the circle directly to the HTTP response PrintWriter out = response.getWriter(); if (constraintViolations.size() > 0) { out.println("<p>Please fix the following error: " + constraintViolations.iterator().next().getMessage() + "</p>"); } else { out.println("<p>The area is <strong>" + circle1.area() + "</strong> for a radius of " + radius + "</p>"); out.println("<p>The perimeter is <strong>" + circle1.circumference() + "</strong> for a radius of " + radius + "</p>"); } out.close(); } /** * @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); } }
2,469
0.743621
0.741191
69
34.782608
33.886372
125
false
false
0
0
0
0
0
0
1.463768
false
false
13
dcb0d0d2a7b41c8184f4f409542550f3879a81a5
34,385,508,220,036
c34c51917c59eb5c5e0cfa847510664d8dd94a68
/src/test/java/com/epam/cdp/olha/testng/MultCalcNgTest.java
37dd505aad41530c79e6153fca4f71ce9d32688e
[]
no_license
OlhaKurbatova/Homework4
https://github.com/OlhaKurbatova/Homework4
0b1deac2fbe0871570d97ba24e6e396f5809aa3b
dbb6cb3de7a41358fc4e2efabf5d9c1b26114f62
refs/heads/master
2020-03-22T06:29:35.547000
2018-07-03T21:24:23
2018-07-03T21:24:23
139,638,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.epam.cdp.olha.testng; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class MultCalcNgTest extends BaseNgTest { @Test(dataProvider = "valuesForMultLong", groups = "long") public void multTwoLong(long a, long b, double expected) { long result = calculator.mult(a, b); Assert.assertEquals((double) result, expected, "Invalid result of mult long operation! "); } @Test(dataProvider = "valuesForMultDouble", groups = "double") public void multTwoDouble(double a, double b, double expected) { double result = calculator.mult(a, b); Assert.assertEquals(result, expected, "Invalid result of mult double operation! "); } //create dataprovider @DataProvider(name = "valuesForMultDouble") public Object[][] multValuesDouble() { return new Object[][]{ {1, 2, 2}, {0.5d, 0.5d, 0.25d}, {Long.MAX_VALUE, 2, ((double) Long.MAX_VALUE * 2)} }; } //create dataprovider @DataProvider(name = "valuesForMultLong") public Object[][] multValuesLong() { return new Object[][]{ {1, 2, 2}, {2, -2, -4}, {Long.MAX_VALUE, 2, ((double) Long.MAX_VALUE * 2)} }; } }
UTF-8
Java
1,334
java
MultCalcNgTest.java
Java
[]
null
[]
package com.epam.cdp.olha.testng; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class MultCalcNgTest extends BaseNgTest { @Test(dataProvider = "valuesForMultLong", groups = "long") public void multTwoLong(long a, long b, double expected) { long result = calculator.mult(a, b); Assert.assertEquals((double) result, expected, "Invalid result of mult long operation! "); } @Test(dataProvider = "valuesForMultDouble", groups = "double") public void multTwoDouble(double a, double b, double expected) { double result = calculator.mult(a, b); Assert.assertEquals(result, expected, "Invalid result of mult double operation! "); } //create dataprovider @DataProvider(name = "valuesForMultDouble") public Object[][] multValuesDouble() { return new Object[][]{ {1, 2, 2}, {0.5d, 0.5d, 0.25d}, {Long.MAX_VALUE, 2, ((double) Long.MAX_VALUE * 2)} }; } //create dataprovider @DataProvider(name = "valuesForMultLong") public Object[][] multValuesLong() { return new Object[][]{ {1, 2, 2}, {2, -2, -4}, {Long.MAX_VALUE, 2, ((double) Long.MAX_VALUE * 2)} }; } }
1,334
0.603448
0.588456
40
32.349998
25.946629
98
false
false
0
0
0
0
0
0
0.95
false
false
13
adbfc512a914d7f2451f4e2441253a0e3f501117
36,464,272,372,871
b29f10d1f78326b9fd1d9f1053c51ffff55ae029
/src/main/java/com/lys/controller/UserController.java
5b3aef84dd6e6c73d166d6dedeb85a6a4690c554
[]
no_license
linyusheng/resume
https://github.com/linyusheng/resume
5e09362cf3984803c5be1d36147f9c5db4a78ce7
33344c2614acf839ce3ccaf5ec2412ffc995dee2
refs/heads/master
2021-01-12T07:46:21.448000
2016-12-26T09:38:38
2016-12-26T09:38:41
77,011,261
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lys.controller; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.lys.face.IAbiinfoService; import com.lys.face.IBaseinfoService; import com.lys.face.IHoninfoService; import com.lys.face.IUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.lys.entity.Userinfo; import com.lys.model.Ajax; import com.lys.util.Global; import com.lys.util.MD5; import com.lys.util.EmailUtil; import com.lys.util.Tool; import com.lys.util.VerifyCode; /** * 用户访问控制类(类资源访问:/user/*) * @author between */ @Controller @RequestMapping("/user") public class UserController extends BaseController{ private static Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired private IUserService userService; @Autowired private IBaseinfoService baseinfoService; @Autowired private IHoninfoService honinfoService; @Autowired private IAbiinfoService abiinfoService; /** * 修改头像 * @param session * @param request * @return * @throws IOException * @throws IllegalStateException */ @ResponseBody @RequestMapping("/face") public void editHead(Userinfo userifo,MultipartHttpServletRequest request,HttpSession session) throws IllegalStateException, IOException { MultipartFile multipartFile = request.getFile("file"); String realPath = request.getSession().getServletContext().getRealPath("/assets/image/head/"); File file = new File(realPath); if (!file.exists()) { file.mkdirs(); } //获取文件的后缀 String suffix = multipartFile.getOriginalFilename().substring( multipartFile.getOriginalFilename().lastIndexOf(".")); // 使用UUID生成文件名称 String fileName = UUID.randomUUID().toString() + suffix; //完整路径 realPath += File.separator + fileName; file = new File(realPath); multipartFile.transferTo(file); //删除原来的头像 Userinfo user = (Userinfo)session.getAttribute("user"); String head = user.getHead(); if (!head.equals(Global.DEFAULT_HEAD)) { Tool.deleteFile(System.getProperty("web.root") + head.replace("/", "\\")); } head = "assets/image/head/"+fileName; baseinfoService.editHead(user.getUid(), head); userService.editHead(user.getUid(), head); user.setHead(head); session.setAttribute("user", user); } /** * 获取用户基本信息 * * @return */ @ResponseBody @RequestMapping("/get") public Userinfo get(){ return userService.getUser("a@qq.com"); } /** * 生成验证码 * @param request * @param response */ @RequestMapping("/verifyCode") public void verifyCode(HttpServletRequest request, HttpServletResponse response) { try { VerifyCode.getVerifyCode(request, response); } catch (IOException e) { e.printStackTrace(); } } /** * 登陆 * @param email * @param rememberPass * @param data * @param session * @return */ @ResponseBody @RequestMapping("/login") public Ajax login(String email,String rememberPass,@RequestBody String data,HttpSession session) { Ajax ajax = new Ajax(); JSONObject object = JSON.parseObject(data); String pw = (String)object.get("pw"); Userinfo user = userService.getUser("普通用户", email, pw); if (user == null) { ajax.setState("Bad"); ajax.setException("用户名或密码错误"); }else { ajax.setState("Success"); //ajax.setReturnUrl("active.jsp"); user.setLoginTime(Tool.getCurrentTime()); userService.update(user); session.setAttribute("user", user); //将当前session添加到在线用户session中 Global.ONLINEUSER.add(session); } return ajax; } /** * 注册 * @param email * @param code * @return */ @ResponseBody @RequestMapping("/register") public Ajax register(String email,String code,HttpSession session) { Ajax ajax = new Ajax(); String verifyCode = (String)session.getAttribute("verifyCode"); if (!code.toLowerCase().equals(verifyCode.toLowerCase())) { ajax.setState("Bad"); ajax.setException("验证码不正确"); }else { Userinfo user = userService.getUser(email); if (user != null) { ajax.setState("Bad"); ajax.setException("用户名已存在"); }else { userService.init(email,"",""); EmailUtil.sendRegisterEmail(email, MD5.string2MD5(email)); ajax.setState("Success"); ajax.setReturnUrl("https://mail.qq.com"); } } return ajax; } /** * 激活账号 * @param email * @param code * @return */ @RequestMapping("/activate") public String activate(String email,String validateCode,Model model) { Userinfo user = userService.getUser(email); //验证用户是否存在 if (user != null) { //验证用户激活状态 if (!user.getStatus()) { Date currentTime = new Date(); //验证链接是否过期 if (currentTime.before(user.getLastActivateTime())) { //验证激活码是否正确 if (validateCode.equals(user.getValidateCode())) { user.setStatus(true); userService.update(user); model.addAttribute("email", email); model.addAttribute("info", "账号激活成功!即将跳转..."); }else { model.addAttribute("info", "激活码不正确!"); } }else { model.addAttribute("info", "激活码已过期!"); } }else { model.addAttribute("info", "邮箱已激活,请登录!"); } }else{ model.addAttribute("info", "该邮箱未注册(邮箱地址不存在)!"); } return "active"; } /** * 跳转到设置密码页 * @param email * @param model * @return */ @RequestMapping("/toPwdPage") public String toPwdPage(String email,Model model) { model.addAttribute("email", email); return "setPwd"; } /** * 设置密码 * @param email * @param password */ @ResponseBody @RequestMapping("/setPwd") public Ajax setPwd(@RequestBody String data,HttpSession session) { Ajax ajax = new Ajax(); JSONObject object = JSON.parseObject(data); String email = (String)object.get("email"); String password = (String)object.get("password"); password = MD5.string2MD5(password); boolean result = userService.setPwd(email, password); if (result) { Userinfo user = userService.getUser("普通用户", email, password); user.setLoginTime(Tool.getCurrentTime()); user.setNickname(email.substring(0, email.indexOf("@"))); userService.save(user); //初始化简历基本信息 baseinfoService.init(user); honinfoService.init(user); abiinfoService.init(user); session.setAttribute("user", user); ajax.setState("success"); ajax.setReturnUrl("./"); }else { ajax.setState("fail"); } return ajax; } /** * 找回密码 * @param email * @param code * @return */ @ResponseBody @RequestMapping("/findPass") public Ajax findPass(String email,String code) { Ajax ajax = new Ajax(); return ajax; } /** * 注销 * @param session * @return */ @ResponseBody @RequestMapping("/logout") public String logout(HttpSession session) { session.invalidate(); return "success"; } /** * 修改密码 * @param data * @return */ @ResponseBody @RequestMapping("/modifyPwd") public Ajax modifyPwd(@RequestBody String data) { Ajax ajax = new Ajax(); JSONObject object = JSON.parseObject(data); Integer uid = (Integer)object.get("uid"); String oldPass = (String)object.get("oldPass"); String pass = (String)object.get("pass"); if (uid == null || oldPass == null || pass == null) { ajax.setState("Bad"); ajax.setException("数据不能为空"); }else { Userinfo user = userService.get(uid); if (!user.getPwd().equals(oldPass)) { ajax.setState("Bad"); ajax.setException("旧密码不正确"); }else { userService.setPwd(uid, pass); ajax.setState("Success"); } } return ajax; } /** * 积分经验 * @return */ @RequestMapping("/point") public String point() { return Global.PERSONAL_POINT; } }
UTF-8
Java
8,632
java
UserController.java
Java
[ { "context": "ifyCode;\n\n/**\n * 用户访问控制类(类资源访问:/user/*)\n * @author between\n */\n@Controller\n@RequestMapping(\"/user\")\npublic c", "end": 1246, "score": 0.9938453435897827, "start": 1239, "tag": "USERNAME", "value": "between" }, { "context": "lic Userinfo get(){\n\t\treturn userService.getUser(\"a@qq.com\");\n\t}\n\t/**\n\t * 生成验证码\n\t * @param request\n\t * @para", "end": 3101, "score": 0.9997665286064148, "start": 3093, "tag": "EMAIL", "value": "a@qq.com" }, { "context": "get(\"pw\");\n\t\tUserinfo user = userService.getUser(\"普通用户\", email, pw);\n\t\tif (user == null) {\n\t\t\tajax.setSt", "end": 3800, "score": 0.9986281394958496, "start": 3796, "tag": "USERNAME", "value": "普通用户" }, { "context": "ord = (String)object.get(\"password\");\n\t\tpassword = MD5.string2MD5(password);\n\t\tboolean result = userService.setPwd(", "end": 6389, "score": 0.9986804723739624, "start": 6375, "tag": "PASSWORD", "value": "MD5.string2MD5" } ]
null
[]
package com.lys.controller; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.lys.face.IAbiinfoService; import com.lys.face.IBaseinfoService; import com.lys.face.IHoninfoService; import com.lys.face.IUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.lys.entity.Userinfo; import com.lys.model.Ajax; import com.lys.util.Global; import com.lys.util.MD5; import com.lys.util.EmailUtil; import com.lys.util.Tool; import com.lys.util.VerifyCode; /** * 用户访问控制类(类资源访问:/user/*) * @author between */ @Controller @RequestMapping("/user") public class UserController extends BaseController{ private static Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired private IUserService userService; @Autowired private IBaseinfoService baseinfoService; @Autowired private IHoninfoService honinfoService; @Autowired private IAbiinfoService abiinfoService; /** * 修改头像 * @param session * @param request * @return * @throws IOException * @throws IllegalStateException */ @ResponseBody @RequestMapping("/face") public void editHead(Userinfo userifo,MultipartHttpServletRequest request,HttpSession session) throws IllegalStateException, IOException { MultipartFile multipartFile = request.getFile("file"); String realPath = request.getSession().getServletContext().getRealPath("/assets/image/head/"); File file = new File(realPath); if (!file.exists()) { file.mkdirs(); } //获取文件的后缀 String suffix = multipartFile.getOriginalFilename().substring( multipartFile.getOriginalFilename().lastIndexOf(".")); // 使用UUID生成文件名称 String fileName = UUID.randomUUID().toString() + suffix; //完整路径 realPath += File.separator + fileName; file = new File(realPath); multipartFile.transferTo(file); //删除原来的头像 Userinfo user = (Userinfo)session.getAttribute("user"); String head = user.getHead(); if (!head.equals(Global.DEFAULT_HEAD)) { Tool.deleteFile(System.getProperty("web.root") + head.replace("/", "\\")); } head = "assets/image/head/"+fileName; baseinfoService.editHead(user.getUid(), head); userService.editHead(user.getUid(), head); user.setHead(head); session.setAttribute("user", user); } /** * 获取用户基本信息 * * @return */ @ResponseBody @RequestMapping("/get") public Userinfo get(){ return userService.getUser("<EMAIL>"); } /** * 生成验证码 * @param request * @param response */ @RequestMapping("/verifyCode") public void verifyCode(HttpServletRequest request, HttpServletResponse response) { try { VerifyCode.getVerifyCode(request, response); } catch (IOException e) { e.printStackTrace(); } } /** * 登陆 * @param email * @param rememberPass * @param data * @param session * @return */ @ResponseBody @RequestMapping("/login") public Ajax login(String email,String rememberPass,@RequestBody String data,HttpSession session) { Ajax ajax = new Ajax(); JSONObject object = JSON.parseObject(data); String pw = (String)object.get("pw"); Userinfo user = userService.getUser("普通用户", email, pw); if (user == null) { ajax.setState("Bad"); ajax.setException("用户名或密码错误"); }else { ajax.setState("Success"); //ajax.setReturnUrl("active.jsp"); user.setLoginTime(Tool.getCurrentTime()); userService.update(user); session.setAttribute("user", user); //将当前session添加到在线用户session中 Global.ONLINEUSER.add(session); } return ajax; } /** * 注册 * @param email * @param code * @return */ @ResponseBody @RequestMapping("/register") public Ajax register(String email,String code,HttpSession session) { Ajax ajax = new Ajax(); String verifyCode = (String)session.getAttribute("verifyCode"); if (!code.toLowerCase().equals(verifyCode.toLowerCase())) { ajax.setState("Bad"); ajax.setException("验证码不正确"); }else { Userinfo user = userService.getUser(email); if (user != null) { ajax.setState("Bad"); ajax.setException("用户名已存在"); }else { userService.init(email,"",""); EmailUtil.sendRegisterEmail(email, MD5.string2MD5(email)); ajax.setState("Success"); ajax.setReturnUrl("https://mail.qq.com"); } } return ajax; } /** * 激活账号 * @param email * @param code * @return */ @RequestMapping("/activate") public String activate(String email,String validateCode,Model model) { Userinfo user = userService.getUser(email); //验证用户是否存在 if (user != null) { //验证用户激活状态 if (!user.getStatus()) { Date currentTime = new Date(); //验证链接是否过期 if (currentTime.before(user.getLastActivateTime())) { //验证激活码是否正确 if (validateCode.equals(user.getValidateCode())) { user.setStatus(true); userService.update(user); model.addAttribute("email", email); model.addAttribute("info", "账号激活成功!即将跳转..."); }else { model.addAttribute("info", "激活码不正确!"); } }else { model.addAttribute("info", "激活码已过期!"); } }else { model.addAttribute("info", "邮箱已激活,请登录!"); } }else{ model.addAttribute("info", "该邮箱未注册(邮箱地址不存在)!"); } return "active"; } /** * 跳转到设置密码页 * @param email * @param model * @return */ @RequestMapping("/toPwdPage") public String toPwdPage(String email,Model model) { model.addAttribute("email", email); return "setPwd"; } /** * 设置密码 * @param email * @param password */ @ResponseBody @RequestMapping("/setPwd") public Ajax setPwd(@RequestBody String data,HttpSession session) { Ajax ajax = new Ajax(); JSONObject object = JSON.parseObject(data); String email = (String)object.get("email"); String password = (String)object.get("password"); password = <PASSWORD>(password); boolean result = userService.setPwd(email, password); if (result) { Userinfo user = userService.getUser("普通用户", email, password); user.setLoginTime(Tool.getCurrentTime()); user.setNickname(email.substring(0, email.indexOf("@"))); userService.save(user); //初始化简历基本信息 baseinfoService.init(user); honinfoService.init(user); abiinfoService.init(user); session.setAttribute("user", user); ajax.setState("success"); ajax.setReturnUrl("./"); }else { ajax.setState("fail"); } return ajax; } /** * 找回密码 * @param email * @param code * @return */ @ResponseBody @RequestMapping("/findPass") public Ajax findPass(String email,String code) { Ajax ajax = new Ajax(); return ajax; } /** * 注销 * @param session * @return */ @ResponseBody @RequestMapping("/logout") public String logout(HttpSession session) { session.invalidate(); return "success"; } /** * 修改密码 * @param data * @return */ @ResponseBody @RequestMapping("/modifyPwd") public Ajax modifyPwd(@RequestBody String data) { Ajax ajax = new Ajax(); JSONObject object = JSON.parseObject(data); Integer uid = (Integer)object.get("uid"); String oldPass = (String)object.get("oldPass"); String pass = (String)object.get("pass"); if (uid == null || oldPass == null || pass == null) { ajax.setState("Bad"); ajax.setException("数据不能为空"); }else { Userinfo user = userService.get(uid); if (!user.getPwd().equals(oldPass)) { ajax.setState("Bad"); ajax.setException("旧密码不正确"); }else { userService.setPwd(uid, pass); ajax.setState("Success"); } } return ajax; } /** * 积分经验 * @return */ @RequestMapping("/point") public String point() { return Global.PERSONAL_POINT; } }
8,627
0.691205
0.68998
315
24.917459
20.280247
139
false
false
0
0
0
0
0
0
2.174603
false
false
13
20eccbb325a11b429b7bb8bc6a4804348771cbb7
5,789,615,963,951
2bf15298c4686014a01c36539f043faa6aec40ca
/src/main/java/exception/ZabbixException.java
7e8514d17ffed0fc080d1716d0ad4ac23897ca98
[]
no_license
lucasrest/zabbix
https://github.com/lucasrest/zabbix
ab5b68cda0a3ee47e7d62b52f4c83fa85f15f87a
5c0cb7dab26d9ab34bc81ba00ff301d1721f511b
refs/heads/master
2020-05-19T09:25:48.525000
2019-05-07T00:14:27
2019-05-07T00:14:27
184,945,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exception; public class ZabbixException extends RuntimeException { public ZabbixException() { } public ZabbixException(String message) { super(message); } }
UTF-8
Java
192
java
ZabbixException.java
Java
[]
null
[]
package exception; public class ZabbixException extends RuntimeException { public ZabbixException() { } public ZabbixException(String message) { super(message); } }
192
0.6875
0.6875
11
16.454546
18.553919
55
false
false
0
0
0
0
0
0
0.181818
false
false
13
668312c1ca6f4b56cf6d094a3ad12f6cab7fd0fa
36,232,344,138,634
43cc8cde06c1ce5af841efefc969b82268ee0c47
/app/src/main/java/com/example/nachiket/lx16/Collection_Loader.java
e00fce8db7d95c68343fda37efa0c7290f41ecff
[]
no_license
nachiket008/LX16
https://github.com/nachiket008/LX16
e164de2df47bd34bfa8287b5080bfe06b2160266
7393dbba9cb2f7111ee76b16e1c6f274f93dcd9d
refs/heads/master
2021-01-10T07:00:47.576000
2016-03-22T06:11:24
2016-03-22T06:11:24
54,449,830
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.nachiket.lx16; /** * Created by Ankit on 14-01-2016. */ public class Collection_Loader { public static String[] date; public static int[] total_amt; public static int[] s_no; public static int cnt; public Collection_Loader() { cnt=(int) MainActivity.pUtility.getCollectionCount(); date=new String[cnt]; total_amt=new int[cnt]; s_no=new int[cnt]; } }
UTF-8
Java
438
java
Collection_Loader.java
Java
[ { "context": "kage com.example.nachiket.lx16;\n\n/**\n * Created by Ankit on 14-01-2016.\n */\npublic class Collection_Loader", "end": 59, "score": 0.9653260111808777, "start": 54, "tag": "NAME", "value": "Ankit" } ]
null
[]
package com.example.nachiket.lx16; /** * Created by Ankit on 14-01-2016. */ public class Collection_Loader { public static String[] date; public static int[] total_amt; public static int[] s_no; public static int cnt; public Collection_Loader() { cnt=(int) MainActivity.pUtility.getCollectionCount(); date=new String[cnt]; total_amt=new int[cnt]; s_no=new int[cnt]; } }
438
0.621005
0.598173
21
19.761906
16.902817
61
false
false
0
0
0
0
0
0
0.428571
false
false
13
9bdf4c529eddaf34450f2f373fc701961a1c6b3c
38,886,633,906,794
3176d7bf6dd61e3a95c9cb33c52476b4a3c3a1b3
/Data Generator/src/main/java/core/Combination.java
51d5397fc45934b2f4c279d7b256dbdd483cbe53
[]
no_license
armankocharyan/Honours-Project
https://github.com/armankocharyan/Honours-Project
366fbfa7f8e74e8fcf0e64d3f6a8bcee20c6d5aa
c9d5751af63619d735512abdd98e54ab328c5f79
refs/heads/master
2022-11-05T22:23:07.145000
2019-04-23T20:11:35
2019-04-23T20:11:35
162,048,788
2
1
null
false
2022-10-24T04:14:44
2018-12-16T22:58:55
2022-02-01T01:06:10
2019-04-23T20:11:35
24,204
1
1
1
Python
false
false
package core; import java.util.ArrayList; public class Combination { //COMBINATION CLASS //this class has methods and attributes that recursively find all the subsets combinations in a array list //get combinations is the only public method that gets called private static ArrayList<String> storage = new ArrayList<String>(); private static void combinationUtil(String [] arr, String [] data, int start, int end, int index, int r){ String tempString = ""; if (index == r) { for (int j=0; j<r; j++) { //System.out.print(data[j] +" "); tempString += data[j] + " "; } storage.add(tempString); tempString = ""; //System.out.println(""); return; } for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } private static void Combination(String [] arr, int n, int r) { String [] data = new String [r]; combinationUtil(arr, data, 0, n-1, 0, r); } //returns the a list of all the subsets size r public static ArrayList<String> getCombination(ArrayList<String> list, int r) { storage.removeAll(storage); String [] tempArr = new String[list.size()]; for(int i = 0; i < tempArr.length; i++) { tempArr[i] = list.get(i); } Combination(tempArr, list.size(), r); ArrayList<String> rList = new ArrayList<String>(); rList.addAll(storage); storage.removeAll(storage); return rList; } }
UTF-8
Java
1,498
java
Combination.java
Java
[]
null
[]
package core; import java.util.ArrayList; public class Combination { //COMBINATION CLASS //this class has methods and attributes that recursively find all the subsets combinations in a array list //get combinations is the only public method that gets called private static ArrayList<String> storage = new ArrayList<String>(); private static void combinationUtil(String [] arr, String [] data, int start, int end, int index, int r){ String tempString = ""; if (index == r) { for (int j=0; j<r; j++) { //System.out.print(data[j] +" "); tempString += data[j] + " "; } storage.add(tempString); tempString = ""; //System.out.println(""); return; } for (int i=start; i<=end && end-i+1 >= r-index; i++) { data[index] = arr[i]; combinationUtil(arr, data, i+1, end, index+1, r); } } private static void Combination(String [] arr, int n, int r) { String [] data = new String [r]; combinationUtil(arr, data, 0, n-1, 0, r); } //returns the a list of all the subsets size r public static ArrayList<String> getCombination(ArrayList<String> list, int r) { storage.removeAll(storage); String [] tempArr = new String[list.size()]; for(int i = 0; i < tempArr.length; i++) { tempArr[i] = list.get(i); } Combination(tempArr, list.size(), r); ArrayList<String> rList = new ArrayList<String>(); rList.addAll(storage); storage.removeAll(storage); return rList; } }
1,498
0.624833
0.619493
67
21.35821
25.427509
107
false
false
0
0
0
0
0
0
2.477612
false
false
13
5724152ba2914dd660094bfdef788d7df2b3c033
35,974,646,109,270
8db87e25e1a9cff09f8354ef9e9cc41828b65ad6
/KinderFoodFinder/app/src/main/java/comp5703/sydney/edu/au/kinderfoodfinder/UserInfomation/UserDBHelper.java
442403eca9503ae3bc981a0525078dc82c9a7404
[]
no_license
WolfeLeee/comp5703project
https://github.com/WolfeLeee/comp5703project
dd30744409a68c6c36c4f4ec1e5c15da365ac421
871e0bcb9a4b07fa33b00c5d7cde9e7d3a3e3d07
refs/heads/master
2022-12-15T04:42:10.670000
2019-06-14T03:26:00
2019-06-14T03:26:00
174,070,719
5
1
null
false
2022-12-08T17:28:09
2019-03-06T04:21:50
2021-05-04T23:46:28
2022-12-08T17:28:09
85,772
3
0
12
Java
false
false
package comp5703.sydney.edu.au.kinderfoodfinder.UserInfomation; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class UserDBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "user_db"; public static final int DATABASE_VERSION=1; public static final String CREATE_TABLE="create table "+ UserContact.ContactEntry.TABLE_NAME+"(" +UserContact.ContactEntry.USER_ID+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+UserContact.ContactEntry.NAME+" TEXT," +UserContact.ContactEntry.STATUS+" INTEGER);"; public static final String DROP_TABLE="drop table if exists "+UserContact.ContactEntry.TABLE_NAME; public UserDBHelper(Context context){ super(context,DATABASE_NAME,null,DATABASE_VERSION); Log.d("User Database Operation","Database created..."); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); Log.d("User Database Operation","Table created..."); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL( DROP_TABLE ); onCreate( db ); } public void addContact(String name,int status,SQLiteDatabase database){ ContentValues contentValues= new ContentValues( ); // contentValues.put( ProductContract.ContactEntry.CONTACT_ID,id ); contentValues.put( UserContact.ContactEntry.NAME,name ); contentValues.put( UserContact.ContactEntry.STATUS,status ); database.insert( UserContact.ContactEntry.TABLE_NAME,null,contentValues ); Log.d("User Database Operation","One Raw inserted..."); } public Cursor getContats(SQLiteDatabase database,String name){ // String[] projiectons={UserContact.ContactEntry.USER_ID,UserContact.ContactEntry.NAME,UserContact.ContactEntry.STATUS}; // // String[] args = {String.valueOf(name)}; // Cursor cursor=database.query( UserContact.ContactEntry.TABLE_NAME , // projiectons,UserContact.ContactEntry.NAME+"?",args,null,null,null ); // return cursor; Cursor cursor = database.rawQuery("select * from user_info where name=?", new String[]{name});//得到游标 if(cursor.moveToFirst()){ String NUMBER = cursor.getString(cursor.getColumnIndex("NUMBER")); String PASSWORD = cursor.getString(cursor.getColumnIndex("PASSWORD")); String SOFTNAME=cursor.getString(cursor.getColumnIndex("SOFTNAME")); return cursor; } else return null; } }
UTF-8
Java
2,764
java
UserDBHelper.java
Java
[]
null
[]
package comp5703.sydney.edu.au.kinderfoodfinder.UserInfomation; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class UserDBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "user_db"; public static final int DATABASE_VERSION=1; public static final String CREATE_TABLE="create table "+ UserContact.ContactEntry.TABLE_NAME+"(" +UserContact.ContactEntry.USER_ID+" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+UserContact.ContactEntry.NAME+" TEXT," +UserContact.ContactEntry.STATUS+" INTEGER);"; public static final String DROP_TABLE="drop table if exists "+UserContact.ContactEntry.TABLE_NAME; public UserDBHelper(Context context){ super(context,DATABASE_NAME,null,DATABASE_VERSION); Log.d("User Database Operation","Database created..."); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); Log.d("User Database Operation","Table created..."); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL( DROP_TABLE ); onCreate( db ); } public void addContact(String name,int status,SQLiteDatabase database){ ContentValues contentValues= new ContentValues( ); // contentValues.put( ProductContract.ContactEntry.CONTACT_ID,id ); contentValues.put( UserContact.ContactEntry.NAME,name ); contentValues.put( UserContact.ContactEntry.STATUS,status ); database.insert( UserContact.ContactEntry.TABLE_NAME,null,contentValues ); Log.d("User Database Operation","One Raw inserted..."); } public Cursor getContats(SQLiteDatabase database,String name){ // String[] projiectons={UserContact.ContactEntry.USER_ID,UserContact.ContactEntry.NAME,UserContact.ContactEntry.STATUS}; // // String[] args = {String.valueOf(name)}; // Cursor cursor=database.query( UserContact.ContactEntry.TABLE_NAME , // projiectons,UserContact.ContactEntry.NAME+"?",args,null,null,null ); // return cursor; Cursor cursor = database.rawQuery("select * from user_info where name=?", new String[]{name});//得到游标 if(cursor.moveToFirst()){ String NUMBER = cursor.getString(cursor.getColumnIndex("NUMBER")); String PASSWORD = cursor.getString(cursor.getColumnIndex("PASSWORD")); String SOFTNAME=cursor.getString(cursor.getColumnIndex("SOFTNAME")); return cursor; } else return null; } }
2,764
0.696299
0.694485
70
38.371429
35.313362
131
false
false
0
0
0
0
0
0
0.871429
false
false
13
f9dd946e4a3e146d8c3124dd574bc97ef9456b58
38,130,719,671,417
1804907c19e2173b562e4b84aac484c179a2180b
/android_code/changhong/SNS/src/com/changhong/sns/interactshare/bean/TSnsThemePay.java
b64cd1203d6f57969754aa09bedd65a114119191
[]
no_license
lostsakya/Git_code
https://github.com/lostsakya/Git_code
44cd983eada1a68b03d6674bc15e6fb616a0a862
d1674be2527557051a955cde70fafb8544e20b46
refs/heads/master
2018-01-13T19:08:26.384000
2014-05-13T09:51:28
2014-05-13T09:51:28
19,765,916
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.changhong.sns.interactshare.bean; import java.math.BigDecimal; @SuppressWarnings("serial") public class TSnsThemePay implements java.io.Serializable { private BigDecimal id; private BigDecimal themeId; private BigDecimal price; private BigDecimal count; private String isActive; private String tel; private String telName; public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getTelName() { return telName; } public void setTelName(String telName) { this.telName = telName; } public BigDecimal getId() { return id; } public void setId(BigDecimal id) { this.id = id; } public BigDecimal getThemeId() { return themeId; } public void setThemeId(BigDecimal themeId) { this.themeId = themeId; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getCount() { return count; } public void setCount(BigDecimal count) { this.count = count; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } }
UTF-8
Java
1,488
java
TSnsThemePay.java
Java
[]
null
[]
package com.changhong.sns.interactshare.bean; import java.math.BigDecimal; @SuppressWarnings("serial") public class TSnsThemePay implements java.io.Serializable { private BigDecimal id; private BigDecimal themeId; private BigDecimal price; private BigDecimal count; private String isActive; private String tel; private String telName; public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getTelName() { return telName; } public void setTelName(String telName) { this.telName = telName; } public BigDecimal getId() { return id; } public void setId(BigDecimal id) { this.id = id; } public BigDecimal getThemeId() { return themeId; } public void setThemeId(BigDecimal themeId) { this.themeId = themeId; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getCount() { return count; } public void setCount(BigDecimal count) { this.count = count; } public String getIsActive() { return isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } }
1,488
0.56586
0.56586
91
15.362638
14.314763
57
false
false
0
0
0
0
0
0
0.252747
false
false
13
54ff183ffe6aa10c6bbeeb0558f45fac6fa08136
9,878,424,838,970
51798b04810e041d0e02debda8dd1f64afc6665f
/src/main/java/com/example/springboot/bean/Users.java
4890b709c71e9929da271823edb9b45093cf9d19
[]
no_license
daming626/ReserveSystem
https://github.com/daming626/ReserveSystem
369376fe24233574db1e448a3d4e6e30412d1233
592830afdbabe6c37a9c3cffafde6f71dd8d6dc4
refs/heads/master
2023-07-23T00:52:19.100000
2021-09-07T15:12:35
2021-09-07T15:12:35
387,312,241
0
6
null
false
2021-08-03T02:39:34
2021-07-19T02:07:11
2021-08-02T15:37:01
2021-08-03T02:39:34
1,000
0
6
0
Java
false
false
package com.example.springboot.bean; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.io.Serializable; /** * Users实体类 */ @Data @TableName("tb_user") public class Users implements Serializable { private static final long serialVersionUID = 1L; @TableId(type = IdType.INPUT) private String userid; private String username; private String password; private String realname; private String sex; private String tclass; private String grade; private String contacts; private Integer state; public static long getSerialVersionUID() { return serialVersionUID; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTclass() { return tclass; } public void setTclass(String tclass) { this.tclass = tclass; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getContacts() { return contacts; } public void setContacts(String contacts) { this.contacts = contacts; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } }
UTF-8
Java
1,957
java
Users.java
Java
[ { "context": "\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String userna", "end": 851, "score": 0.9156855940818787, "start": 843, "tag": "USERNAME", "value": "username" }, { "context": "sername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n ", "end": 939, "score": 0.9695433974266052, "start": 931, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.example.springboot.bean; import com.baomidou.mybatisplus.annotation.*; import lombok.Data; import java.io.Serializable; /** * Users实体类 */ @Data @TableName("tb_user") public class Users implements Serializable { private static final long serialVersionUID = 1L; @TableId(type = IdType.INPUT) private String userid; private String username; private String password; private String realname; private String sex; private String tclass; private String grade; private String contacts; private Integer state; public static long getSerialVersionUID() { return serialVersionUID; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealname() { return realname; } public void setRealname(String realname) { this.realname = realname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTclass() { return tclass; } public void setTclass(String tclass) { this.tclass = tclass; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getContacts() { return contacts; } public void setContacts(String contacts) { this.contacts = contacts; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } }
1,957
0.61917
0.618657
103
17.941748
15.76824
52
false
false
0
0
0
0
0
0
0.320388
false
false
13
94066ce5acdeae160b8b18deea03d9bf25d0fe96
9,878,424,840,133
8ffa800ada0e1e718556416b5f46c349384ad362
/src/test/java/com/github/binarySmile/declarationtest/core/BaseTest.java
e35048855bb147196b0c02121fb0f5e729ab8049
[]
no_license
binarySmile/DeclarationTest-Selenium
https://github.com/binarySmile/DeclarationTest-Selenium
8cd0b4265a6183d794a418c349dc2d03ef74a938
cf71292a9cb782216ee634f7ffdf7ff9ef1db4ea
refs/heads/master
2021-01-25T13:34:56.312000
2018-04-04T19:40:02
2018-04-04T19:40:02
123,584,947
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.binarySmile.declarationtest.core; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Properties; import java.util.concurrent.TimeUnit; public class BaseTest { protected static final String path = System.getProperty("user.dir") + "\\src\\test\\java\\com\\github\\binarySmile\\declarationtest\\core\\packageForFile"; protected static Properties data; protected WebDriver webDriver; @BeforeTest public void initialize() { data = new Properties(); try (FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "/src/test/resources/data.properties")) { data.load(new InputStreamReader(fis, Charset.forName("UTF-8"))); } catch (Exception ex) { throw new RuntimeException("Exception during the IO operation: " + ex.getLocalizedMessage()); } } @BeforeMethod public void setUp() throws MalformedURLException { System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe"); ChromeOptions options = new ChromeOptions(); HashMap <String, Object> chromeOptionsMap = new HashMap <>(); chromeOptionsMap.put("plugins.plugins_disabled", new String[]{ "Chrome PDF Viewer" }); chromeOptionsMap.put("plugins.always_open_pdf_externally", true); options.setExperimentalOption("prefs", chromeOptionsMap); chromeOptionsMap.put("download.prompt_for_download", "false"); chromeOptionsMap.put("download.default_directory", path); DesiredCapabilities cap = DesiredCapabilities.chrome(); options.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap); options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); options.setCapability(ChromeOptions.CAPABILITY, cap); webDriver = new ChromeDriver(options); webDriver.manage().window().maximize(); webDriver.navigate().to(getURL()); webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @AfterMethod public void tearDown() { if (webDriver != null) webDriver.quit(); } protected String getURL() { return data.getProperty("url"); } protected String getName1() { return data.getProperty("name_1"); } protected String getName2() { return data.getProperty("name_2"); } protected String getTypeFilter1() { return data.getProperty("type_filter_1"); } protected String getTypeFilter2() { return data.getProperty("type_filter_2"); } protected String getType() { return data.getProperty("type"); } protected String getYear() { return data.getProperty("year"); } protected String getSpecificName() { return data.getProperty("specific_name"); } protected String getValueInsteadOfEmptyCell() { return data.getProperty("value_instead_of_empty_cell"); } }
UTF-8
Java
3,524
java
BaseTest.java
Java
[ { "context": "package com.github.binarySmile.declarationtest.core;\n\nimport org.openqa.selenium", "end": 30, "score": 0.6093409061431885, "start": 25, "tag": "USERNAME", "value": "Smile" } ]
null
[]
package com.github.binarySmile.declarationtest.core; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Properties; import java.util.concurrent.TimeUnit; public class BaseTest { protected static final String path = System.getProperty("user.dir") + "\\src\\test\\java\\com\\github\\binarySmile\\declarationtest\\core\\packageForFile"; protected static Properties data; protected WebDriver webDriver; @BeforeTest public void initialize() { data = new Properties(); try (FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "/src/test/resources/data.properties")) { data.load(new InputStreamReader(fis, Charset.forName("UTF-8"))); } catch (Exception ex) { throw new RuntimeException("Exception during the IO operation: " + ex.getLocalizedMessage()); } } @BeforeMethod public void setUp() throws MalformedURLException { System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe"); ChromeOptions options = new ChromeOptions(); HashMap <String, Object> chromeOptionsMap = new HashMap <>(); chromeOptionsMap.put("plugins.plugins_disabled", new String[]{ "Chrome PDF Viewer" }); chromeOptionsMap.put("plugins.always_open_pdf_externally", true); options.setExperimentalOption("prefs", chromeOptionsMap); chromeOptionsMap.put("download.prompt_for_download", "false"); chromeOptionsMap.put("download.default_directory", path); DesiredCapabilities cap = DesiredCapabilities.chrome(); options.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap); options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); options.setCapability(ChromeOptions.CAPABILITY, cap); webDriver = new ChromeDriver(options); webDriver.manage().window().maximize(); webDriver.navigate().to(getURL()); webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @AfterMethod public void tearDown() { if (webDriver != null) webDriver.quit(); } protected String getURL() { return data.getProperty("url"); } protected String getName1() { return data.getProperty("name_1"); } protected String getName2() { return data.getProperty("name_2"); } protected String getTypeFilter1() { return data.getProperty("type_filter_1"); } protected String getTypeFilter2() { return data.getProperty("type_filter_2"); } protected String getType() { return data.getProperty("type"); } protected String getYear() { return data.getProperty("year"); } protected String getSpecificName() { return data.getProperty("specific_name"); } protected String getValueInsteadOfEmptyCell() { return data.getProperty("value_instead_of_empty_cell"); } }
3,524
0.681896
0.678774
102
33.539215
25.492279
99
false
false
0
0
0
0
0
0
0.588235
false
false
13
90af7f5caaad23cc25850d2c70991314be0e3453
2,164,663,585,654
90b1ef79387b92ee5faf5b33705e1db26bfb4f11
/IssueTrackingSystem/src/com/issuetracker/bean/SendEmail.java
88183de4178bbc1dc509bdc7c991549410d198dc
[]
no_license
maulik4107/Issue-Tracking-System
https://github.com/maulik4107/Issue-Tracking-System
01e3fd9c0192711726df3ddc847fc017ca8844ac
3aa1711e73a7b815bc935ce697a41829d3c21b4f
refs/heads/master
2023-07-15T22:29:25.958000
2021-05-28T07:28:47
2021-05-28T07:28:47
398,555,686
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.issuetracker.bean; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public void sendmail(String mail, String msg) { final String username = "issuetrackingsystem2623@gmail.com"; final String password = "Dkm@2623"; Properties prop = new Properties(); prop.put("mail.smtp.host", "smtp.gmail.com"); prop.put("mail.smtp.port", "465"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.smtp.socketFactory.port", "465"); prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session session = Session.getInstance(prop, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("issuetrackingsystem2623@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail)); message.setSubject("Issue Tracking System"); message.setContent(msg, "text/html"); // message.setText(msg); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } } }
UTF-8
Java
1,506
java
SendEmail.java
Java
[ { "context": "ng mail, String msg) {\n\t\tfinal String username = \"issuetrackingsystem2623@gmail.com\";\n\t\tfinal String password = \"Dkm@2623\";\n\n\t\tProper", "end": 445, "score": 0.9999189376831055, "start": 412, "tag": "EMAIL", "value": "issuetrackingsystem2623@gmail.com" }, { "context": "system2623@gmail.com\";\n\t\tfinal String password = \"Dkm@2623\";\n\n\t\tProperties prop = new Properties();\n\t\tprop.p", "end": 483, "score": 0.9992445111274719, "start": 475, "tag": "PASSWORD", "value": "Dkm@2623" }, { "context": "session);\n\t\t\tmessage.setFrom(new InternetAddress(\"issuetrackingsystem2623@gmail.com\"));\n\t\t\tmessage.setRecipients(Message.RecipientTyp", "end": 1172, "score": 0.9999197125434875, "start": 1139, "tag": "EMAIL", "value": "issuetrackingsystem2623@gmail.com" } ]
null
[]
package com.issuetracker.bean; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public void sendmail(String mail, String msg) { final String username = "<EMAIL>"; final String password = "<PASSWORD>"; Properties prop = new Properties(); prop.put("mail.smtp.host", "smtp.gmail.com"); prop.put("mail.smtp.port", "465"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.starttls.enable", "true"); prop.put("mail.smtp.socketFactory.port", "465"); prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Session session = Session.getInstance(prop, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("<EMAIL>")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail)); message.setSubject("Issue Tracking System"); message.setContent(msg, "text/html"); // message.setText(msg); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } } }
1,456
0.741036
0.729084
50
29.120001
24.140953
80
false
false
0
0
0
0
0
0
2.14
false
false
13
97faef6036f6abc06c43dee474ef693c5ee8a909
7,911,329,771,514
561496b0940bcc705774cc7fd1bbeb6963644ba3
/com.agit.crm.user.management/src/main/java/com/agit/crm/user/management/domain/role/RolePrivilege.java
7d25e68817ae0ef8aaf4a8f2ad6098a421fb2e62
[]
no_license
bellmit/POC-1
https://github.com/bellmit/POC-1
2e1cdeaaa383815a89065e4ba32d15b80e805436
3582bf815c2e14f407cb385a559476b6df688fef
refs/heads/master
2022-03-09T19:35:52.251000
2018-07-25T02:52:34
2018-07-25T02:52:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.agit.crm.user.management.domain.role; import com.agit.crm.shared.object.ValueObject; import com.agit.crm.shared.type.AccessType; import com.agit.crm.user.management.domain.privilege.Privilege; import java.util.Objects; /** * * * @author bayutridewanto */ public class RolePrivilege implements ValueObject<RolePrivilege>{ private Privilege privilege; private AccessType accessType; public RolePrivilege() { } public RolePrivilege(Privilege privilege, AccessType accessType) { this.privilege = privilege; this.accessType = accessType; } public Privilege getPrivilege() { return privilege; } public AccessType getAccessType() { return accessType; } @Override public int hashCode() { int hash = 7; hash = 23 * hash + Objects.hashCode(this.privilege); hash = 23 * hash + Objects.hashCode(this.accessType); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RolePrivilege other = (RolePrivilege) obj; if (!Objects.equals(this.privilege, other.privilege)) { return false; } if (this.accessType != other.accessType) { return false; } return true; } @Override public boolean sameValueAs(RolePrivilege other) { return this.equals(other); } }
UTF-8
Java
1,608
java
RolePrivilege.java
Java
[ { "context": "ort java.util.Objects;\r\n\r\n/**\r\n * \r\n *\r\n * @author bayutridewanto\r\n */\r\npublic class RolePrivilege implements Value", "end": 279, "score": 0.9990550875663757, "start": 265, "tag": "USERNAME", "value": "bayutridewanto" } ]
null
[]
package com.agit.crm.user.management.domain.role; import com.agit.crm.shared.object.ValueObject; import com.agit.crm.shared.type.AccessType; import com.agit.crm.user.management.domain.privilege.Privilege; import java.util.Objects; /** * * * @author bayutridewanto */ public class RolePrivilege implements ValueObject<RolePrivilege>{ private Privilege privilege; private AccessType accessType; public RolePrivilege() { } public RolePrivilege(Privilege privilege, AccessType accessType) { this.privilege = privilege; this.accessType = accessType; } public Privilege getPrivilege() { return privilege; } public AccessType getAccessType() { return accessType; } @Override public int hashCode() { int hash = 7; hash = 23 * hash + Objects.hashCode(this.privilege); hash = 23 * hash + Objects.hashCode(this.accessType); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final RolePrivilege other = (RolePrivilege) obj; if (!Objects.equals(this.privilege, other.privilege)) { return false; } if (this.accessType != other.accessType) { return false; } return true; } @Override public boolean sameValueAs(RolePrivilege other) { return this.equals(other); } }
1,608
0.592662
0.589552
65
22.738462
20.498613
70
false
false
0
0
0
0
0
0
0.369231
false
false
13
47fd0fcc1c333929a2bfee31f3b63581c21fb522
27,676,769,266,106
11fa7db93357c4697b0d750a58674d556350c091
/app/src/main/java/entity/FamilyMember.java
f5fa9da47c992c4ca1f59d8292a98df0ad1378f7
[]
no_license
Laughing-program-monkey/XCSJCT
https://github.com/Laughing-program-monkey/XCSJCT
3ad481af78fd2f530b9dcf9940d698892d11e078
c3767eb02e22d59c360ddb5bb1a7586593a1ac02
refs/heads/master
2022-02-23T13:16:23.941000
2019-06-17T13:17:54
2019-06-17T13:17:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package entity; public class FamilyMember { private String userName;//用户名 private String phoneNumber;//用户号码 private String pwd;//用户密码 private int status;//在职状态 private double salary;//薪资 private int loginstatus;//在线状态 private String NickName;//昵称 private byte[] headImage; private int count;//记录进入平台次数; private String Date; private byte[] MyCode; public byte[] getMyCode() { return MyCode; } public void setMyCode(byte[] myCode) { MyCode = myCode; } public String getDate() { return Date; } public void setDate(String date) { Date = date; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public byte[] getHeadImage() { return headImage; } public void setHeadImage(byte[] headImage) { this.headImage = headImage; } public String getNickName() { return NickName; } public void setNickName(String nickName) { NickName = nickName; } public int getLoginstatus() { return loginstatus; } public void setLoginstatus(int loginstatus) { this.loginstatus = loginstatus; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public FamilyMember() { super(); } }
GB18030
Java
1,814
java
FamilyMember.java
Java
[ { "context": "lass FamilyMember {\n private String userName;//用户名\n private String phoneNumber;//用户号码\n private", "end": 78, "score": 0.9992565512657166, "start": 75, "tag": "USERNAME", "value": "用户名" }, { "context": "tring phoneNumber;//用户号码\n private String pwd;//用户密码\n private int status;//在职状态\n private double ", "end": 146, "score": 0.9959196448326111, "start": 142, "tag": "PASSWORD", "value": "用户密码" }, { "context": "status;\n\t}\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\tpublic void setUserName(String userName) {\n\t", "end": 1154, "score": 0.9679422974586487, "start": 1146, "tag": "USERNAME", "value": "userName" }, { "context": "d setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\tpublic String getPhoneNumber() {\n\t\treturn ph", "end": 1229, "score": 0.9722924828529358, "start": 1221, "tag": "USERNAME", "value": "userName" } ]
null
[]
package entity; public class FamilyMember { private String userName;//用户名 private String phoneNumber;//用户号码 private String pwd;//<PASSWORD> private int status;//在职状态 private double salary;//薪资 private int loginstatus;//在线状态 private String NickName;//昵称 private byte[] headImage; private int count;//记录进入平台次数; private String Date; private byte[] MyCode; public byte[] getMyCode() { return MyCode; } public void setMyCode(byte[] myCode) { MyCode = myCode; } public String getDate() { return Date; } public void setDate(String date) { Date = date; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public byte[] getHeadImage() { return headImage; } public void setHeadImage(byte[] headImage) { this.headImage = headImage; } public String getNickName() { return NickName; } public void setNickName(String nickName) { NickName = nickName; } public int getLoginstatus() { return loginstatus; } public void setLoginstatus(int loginstatus) { this.loginstatus = loginstatus; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public FamilyMember() { super(); } }
1,812
0.688571
0.688571
86
19.348837
13.963214
49
false
false
0
0
0
0
0
0
1.5
false
false
13
c737c6046ea7a19a934accb5fad9e97baae89866
5,231,270,184,359
9fd01d46525478506b7208fb73891df922ae43b3
/src/main/java/com/atguigu/mgt/manager/service/impl/xktimpl/TUserRoleServiceImpl.java
a20e813565e8e08b891a904422c20ce1c6853b48
[]
no_license
longxiao817/mana-service
https://github.com/longxiao817/mana-service
5f952aec9a301885fcd5a6510898c26e541e11ec
acc27fcb5ab3da37aedb354efac272e555979e2b
refs/heads/master
2021-01-15T22:14:13.958000
2017-08-19T02:17:13
2017-08-19T02:17:13
99,759,392
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.mgt.manager.service.impl.xktimpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.mgt.manager.bean.TRole; import com.atguigu.mgt.manager.bean.TUserRole; import com.atguigu.mgt.manager.bean.TUserRoleExample; import com.atguigu.mgt.manager.bean.TUserRoleExample.Criteria; import com.atguigu.mgt.manager.bean.TUserRoleExample.Criterion; import com.atguigu.mgt.manager.dao.TUserRoleMapper; import com.atguigu.mgt.manager.service.xktservice.TUserRoleService; @Service public class TUserRoleServiceImpl implements TUserRoleService { @Autowired TUserRoleMapper tUserRoleMapper; @Override public void del(Integer uid) { // TODO Auto-generated method stub TUserRoleExample example=new TUserRoleExample(); Criteria createCriteria = example.createCriteria(); createCriteria.andUseridEqualTo(uid); tUserRoleMapper.deleteByExample(example); } @Override public void add(Integer uid,String rids) { // TODO Auto-generated method stub if(rids!=null&&rids!=""){ if(rids.contains(",")){ String[] str = rids.split(","); for (String ridStr : str) { int rid = Integer.parseInt(ridStr); tUserRoleMapper.insertSelective(new TUserRole(uid, rid)); } }else{ int rid = Integer.parseInt(rids); tUserRoleMapper.insertSelective(new TUserRole(uid, rid)); } } } }
UTF-8
Java
1,683
java
TUserRoleServiceImpl.java
Java
[]
null
[]
package com.atguigu.mgt.manager.service.impl.xktimpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.mgt.manager.bean.TRole; import com.atguigu.mgt.manager.bean.TUserRole; import com.atguigu.mgt.manager.bean.TUserRoleExample; import com.atguigu.mgt.manager.bean.TUserRoleExample.Criteria; import com.atguigu.mgt.manager.bean.TUserRoleExample.Criterion; import com.atguigu.mgt.manager.dao.TUserRoleMapper; import com.atguigu.mgt.manager.service.xktservice.TUserRoleService; @Service public class TUserRoleServiceImpl implements TUserRoleService { @Autowired TUserRoleMapper tUserRoleMapper; @Override public void del(Integer uid) { // TODO Auto-generated method stub TUserRoleExample example=new TUserRoleExample(); Criteria createCriteria = example.createCriteria(); createCriteria.andUseridEqualTo(uid); tUserRoleMapper.deleteByExample(example); } @Override public void add(Integer uid,String rids) { // TODO Auto-generated method stub if(rids!=null&&rids!=""){ if(rids.contains(",")){ String[] str = rids.split(","); for (String ridStr : str) { int rid = Integer.parseInt(ridStr); tUserRoleMapper.insertSelective(new TUserRole(uid, rid)); } }else{ int rid = Integer.parseInt(rids); tUserRoleMapper.insertSelective(new TUserRole(uid, rid)); } } } }
1,683
0.648247
0.648247
49
32.346939
23.730246
77
false
false
0
0
0
0
0
0
0.530612
false
false
13
9c1c684518e717efe18e21853e1c04184f39fd2b
31,765,578,138,351
25713830beecbedaab641b9970b1241292f31286
/src/main/java/com/ihbaby/service/CommentService.java
cfd92ab1c9ae9c96b0db0ea92606faa3b7da5eb8
[]
no_license
jasonbourn/ihbaby-bbs
https://github.com/jasonbourn/ihbaby-bbs
9695dcd177ebb1ff84478b225e5c49bfa19436bd
52b15faa482c7f1b1c69f36130d8ef02ea81e7b1
refs/heads/master
2021-01-22T19:22:08.204000
2017-05-08T09:21:40
2017-05-08T09:21:40
85,192,448
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ihbaby.service; import com.ihbaby.dao.CommentDao; import com.ihbaby.entity.Comment; import com.ihbaby.sys.ApiResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by qiang on 2017/03/14. */ @Service public class CommentService { @Autowired private CommentDao commentDao; public ApiResult saveComment(Comment comment){ commentDao.save(comment); return ApiResult.createSuccess(); } }
UTF-8
Java
508
java
CommentService.java
Java
[ { "context": "ngframework.stereotype.Service;\n\n/**\n * Created by qiang on 2017/03/14.\n */\n@Service\npublic class CommentS", "end": 264, "score": 0.9992904663085938, "start": 259, "tag": "USERNAME", "value": "qiang" } ]
null
[]
package com.ihbaby.service; import com.ihbaby.dao.CommentDao; import com.ihbaby.entity.Comment; import com.ihbaby.sys.ApiResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by qiang on 2017/03/14. */ @Service public class CommentService { @Autowired private CommentDao commentDao; public ApiResult saveComment(Comment comment){ commentDao.save(comment); return ApiResult.createSuccess(); } }
508
0.753937
0.738189
20
24.4
18.317751
62
false
false
0
0
0
0
0
0
0.45
false
false
13
6e9ac546cbb7572de912c36343558bae796b7f72
824,633,783,709
070b9e745c5aad76fb310f5c9111ed77a1036291
/Drona-Package/com/facebook/react/bridge/WritableNativeMap.java
453a9994809b60215a44ba573a8e71bd9b0e6cdc
[]
no_license
Drona-team/Drona
https://github.com/Drona-team/Drona
0f057e62e7f77babf112311734ee98c5824f166c
e33a9d92011ef7790c7547cc5a5380083f0dbcd7
refs/heads/master
2022-11-18T06:38:57.404000
2020-07-18T09:35:57
2020-07-18T09:35:57
280,390,561
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.react.bridge; import com.facebook.infer.annotation.Assertions; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.upgrade.HybridData; @DoNotStrip public class WritableNativeMap extends ReadableNativeMap implements WritableMap { static {} public WritableNativeMap() { super(initHybrid()); } private static native HybridData initHybrid(); private native void mergeNativeMap(ReadableNativeMap paramReadableNativeMap); private native void putNativeArray(String paramString, WritableNativeArray paramWritableNativeArray); private native void putNativeMap(String paramString, WritableNativeMap paramWritableNativeMap); public WritableMap copy() { WritableNativeMap localWritableNativeMap = new WritableNativeMap(); localWritableNativeMap.merge(this); return localWritableNativeMap; } public void merge(ReadableMap paramReadableMap) { Assertions.assertCondition(paramReadableMap instanceof ReadableNativeMap, "Illegal type provided"); mergeNativeMap((ReadableNativeMap)paramReadableMap); } public void putArray(String paramString, ReadableArray paramReadableArray) { boolean bool; if ((paramReadableArray != null) && (!(paramReadableArray instanceof WritableNativeArray))) { bool = false; } else { bool = true; } Assertions.assertCondition(bool, "Illegal type provided"); putNativeArray(paramString, (WritableNativeArray)paramReadableArray); } public native void putBoolean(String paramString, boolean paramBoolean); public native void putDouble(String paramString, double paramDouble); public native void putInt(String paramString, int paramInt); public void putMap(String paramString, ReadableMap paramReadableMap) { boolean bool; if ((paramReadableMap != null) && (!(paramReadableMap instanceof WritableNativeMap))) { bool = false; } else { bool = true; } Assertions.assertCondition(bool, "Illegal type provided"); putNativeMap(paramString, (WritableNativeMap)paramReadableMap); } public native void putNull(String paramString); public native void putString(String paramString1, String paramString2); }
UTF-8
Java
2,236
java
WritableNativeMap.java
Java
[]
null
[]
package com.facebook.react.bridge; import com.facebook.infer.annotation.Assertions; import com.facebook.proguard.annotations.DoNotStrip; import com.facebook.upgrade.HybridData; @DoNotStrip public class WritableNativeMap extends ReadableNativeMap implements WritableMap { static {} public WritableNativeMap() { super(initHybrid()); } private static native HybridData initHybrid(); private native void mergeNativeMap(ReadableNativeMap paramReadableNativeMap); private native void putNativeArray(String paramString, WritableNativeArray paramWritableNativeArray); private native void putNativeMap(String paramString, WritableNativeMap paramWritableNativeMap); public WritableMap copy() { WritableNativeMap localWritableNativeMap = new WritableNativeMap(); localWritableNativeMap.merge(this); return localWritableNativeMap; } public void merge(ReadableMap paramReadableMap) { Assertions.assertCondition(paramReadableMap instanceof ReadableNativeMap, "Illegal type provided"); mergeNativeMap((ReadableNativeMap)paramReadableMap); } public void putArray(String paramString, ReadableArray paramReadableArray) { boolean bool; if ((paramReadableArray != null) && (!(paramReadableArray instanceof WritableNativeArray))) { bool = false; } else { bool = true; } Assertions.assertCondition(bool, "Illegal type provided"); putNativeArray(paramString, (WritableNativeArray)paramReadableArray); } public native void putBoolean(String paramString, boolean paramBoolean); public native void putDouble(String paramString, double paramDouble); public native void putInt(String paramString, int paramInt); public void putMap(String paramString, ReadableMap paramReadableMap) { boolean bool; if ((paramReadableMap != null) && (!(paramReadableMap instanceof WritableNativeMap))) { bool = false; } else { bool = true; } Assertions.assertCondition(bool, "Illegal type provided"); putNativeMap(paramString, (WritableNativeMap)paramReadableMap); } public native void putNull(String paramString); public native void putString(String paramString1, String paramString2); }
2,236
0.755814
0.754919
73
29.630136
31.176699
103
false
false
0
0
0
0
0
0
0.575342
false
false
13
0b081e0bd6b822cebc8bcc342d0e6e26bda5f764
824,633,781,897
9349d76bb070a44091b8112365e1983367b6d716
/bitcoin-zeromq-client/bitcoin-zeromq-client-bitcoin-kmp/src/main/java/org/tbk/bitcoin/zeromq/kmp/KmpBlockPublisherFactory.java
351577f183c42d017d8c3d363a58b6a0b4bc0cf9
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
theborakompanioni/spring-boot-bitcoin-starter
https://github.com/theborakompanioni/spring-boot-bitcoin-starter
575c641f0794a7c97399d7c2c78b200ffb11801c
1aa6b1199b5de4902af0dc850883dbcafe7a6d18
refs/heads/master
2023-03-15T05:34:01.574000
2023-02-23T14:57:17
2023-02-23T14:57:17
303,107,075
8
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.tbk.bitcoin.zeromq.kmp; import fr.acinq.bitcoin.Block; import lombok.extern.slf4j.Slf4j; import org.tbk.bitcoin.zeromq.client.MessagePublisherFactory; import reactor.core.publisher.Flux; import static java.util.Objects.requireNonNull; @Slf4j public final class KmpBlockPublisherFactory implements MessagePublisherFactory<Block> { private final MessagePublisherFactory<byte[]> delegate; public KmpBlockPublisherFactory(MessagePublisherFactory<byte[]> publisherFactory) { this.delegate = requireNonNull(publisherFactory); } @Override public String getTopicName() { return delegate.getTopicName(); } @Override public Flux<Block> create() { return delegate.create() .map(Block::read); } }
UTF-8
Java
780
java
KmpBlockPublisherFactory.java
Java
[]
null
[]
package org.tbk.bitcoin.zeromq.kmp; import fr.acinq.bitcoin.Block; import lombok.extern.slf4j.Slf4j; import org.tbk.bitcoin.zeromq.client.MessagePublisherFactory; import reactor.core.publisher.Flux; import static java.util.Objects.requireNonNull; @Slf4j public final class KmpBlockPublisherFactory implements MessagePublisherFactory<Block> { private final MessagePublisherFactory<byte[]> delegate; public KmpBlockPublisherFactory(MessagePublisherFactory<byte[]> publisherFactory) { this.delegate = requireNonNull(publisherFactory); } @Override public String getTopicName() { return delegate.getTopicName(); } @Override public Flux<Block> create() { return delegate.create() .map(Block::read); } }
780
0.732051
0.728205
29
25.896551
25.72044
87
false
false
0
0
0
0
0
0
0.344828
false
false
13
dd9916e8646d745ee017c8e815e01ca80a05cb31
17,179,869,212,676
39b6f83641d1a80a48937c42beb6a73311aebc55
/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/ListMethodImplementor.java
1b8ec8077590f682ff9339499cffb9d766e16bc4
[ "Apache-2.0" ]
permissive
quarkusio/quarkus
https://github.com/quarkusio/quarkus
112ecda7236bc061920978ac49289da6259360f4
68af440f3081de7a26bbee655f74bb8b2c57c2d5
refs/heads/main
2023-09-04T06:39:33.043000
2023-09-04T05:44:43
2023-09-04T05:44:43
139,914,932
13,109
2,940
Apache-2.0
false
2023-09-14T21:31:23
2018-07-06T00:44:20
2023-09-14T21:29:58
2023-09-14T21:31:22
264,839
12,241
2,328
2,315
Java
false
false
package io.quarkus.rest.data.panache.deployment.methods; import static io.quarkus.arc.processor.DotNames.BOOLEAN; import static io.quarkus.arc.processor.DotNames.BYTE; import static io.quarkus.arc.processor.DotNames.CHARACTER; import static io.quarkus.arc.processor.DotNames.DOUBLE; import static io.quarkus.arc.processor.DotNames.FLOAT; import static io.quarkus.arc.processor.DotNames.INTEGER; import static io.quarkus.arc.processor.DotNames.LONG; import static io.quarkus.arc.processor.DotNames.SHORT; import static io.quarkus.arc.processor.DotNames.STRING; import static io.quarkus.gizmo.MethodDescriptor.ofConstructor; import static io.quarkus.gizmo.MethodDescriptor.ofMethod; import static io.quarkus.gizmo.Type.classType; import static io.quarkus.gizmo.Type.intType; import static io.quarkus.gizmo.Type.parameterizedType; import static io.quarkus.rest.data.panache.deployment.utils.PaginationImplementor.DEFAULT_PAGE_INDEX; import static io.quarkus.rest.data.panache.deployment.utils.PaginationImplementor.DEFAULT_PAGE_SIZE; import static io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator.param; import static io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator.responseType; import static io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator.uniType; import static io.quarkus.rest.data.panache.deployment.utils.TypeUtils.primitiveToClass; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import org.jboss.jandex.Type; import io.quarkus.deployment.Capabilities; import io.quarkus.gizmo.AnnotatedElement; import io.quarkus.gizmo.AssignableResultHandle; import io.quarkus.gizmo.BranchResult; import io.quarkus.gizmo.BytecodeCreator; import io.quarkus.gizmo.ClassCreator; import io.quarkus.gizmo.FieldDescriptor; import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.ResultHandle; import io.quarkus.gizmo.TryBlock; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; import io.quarkus.rest.data.panache.RestDataResource; import io.quarkus.rest.data.panache.deployment.Constants; import io.quarkus.rest.data.panache.deployment.ResourceMetadata; import io.quarkus.rest.data.panache.deployment.properties.ResourceProperties; import io.quarkus.rest.data.panache.deployment.utils.PaginationImplementor; import io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator; import io.quarkus.rest.data.panache.deployment.utils.SortImplementor; import io.quarkus.rest.data.panache.deployment.utils.UniImplementor; import io.smallrye.mutiny.Uni; public class ListMethodImplementor extends StandardMethodImplementor { private static final String METHOD_NAME = "list"; private static final String RESOURCE_METHOD_NAME = "list"; private static final String EXCEPTION_MESSAGE = "Failed to list the entities"; private static final String REL = "list"; private final PaginationImplementor paginationImplementor = new PaginationImplementor(); private final SortImplementor sortImplementor = new SortImplementor(); public ListMethodImplementor(Capabilities capabilities) { super(capabilities); } /** * Generate JAX-RS GET method. * * The RESTEasy Classic version exposes {@link RestDataResource#list(Page, Sort)} * and the generated pseudocode with enabled pagination is shown below. If pagination is disabled pageIndex and pageSize * query parameters are skipped and null {@link Page} instance is used. * * <pre> * {@code * &#64;GET * &#64;Path("") * &#64;Produces({"application/json"}) * &#64;LinkResource( * rel = "list", * entityClassName = "com.example.Entity" * ) * public Response list(&#64;QueryParam("page") &#64;DefaultValue("0") int pageIndex, * &#64;QueryParam("size") &#64;DefaultValue("20") int pageSize, * &#64;QueryParam("sort") List<String> sortQuery) { * Page page = Page.of(pageIndex, pageSize); * Sort sort = ...; // Build a sort instance from String entries of sortQuery * try { * List<Entity> entities = resource.getAll(page, sort); * // Get the page count, and build first, last, next, previous page instances * Response.ResponseBuilder responseBuilder = Response.status(200); * responseBuilder.entity(entities); * // Add headers with first, last, next and previous page URIs if they exist * return responseBuilder.build(); * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> * * The RESTEasy Reactive version exposes {@link io.quarkus.rest.data.panache.ReactiveRestDataResource#list(Page, Sort)} * and the generated code looks more or less like this: * * <pre> * {@code * &#64;GET * &#64;Path("") * &#64;Produces({"application/json"}) * &#64;LinkResource( * rel = "list", * entityClassName = "com.example.Entity" * ) * public Uni<Response> list(&#64;QueryParam("page") &#64;DefaultValue("0") int pageIndex, * &#64;QueryParam("size") &#64;DefaultValue("20") int pageSize, * &#64;QueryParam("sort") List<String> sortQuery) { * Page page = Page.of(pageIndex, pageSize); * Sort sort = ...; // Build a sort instance from String entries of sortQuery * try { * return resource.getAll(page, sort).map(entities -> { * // Get the page count, and build first, last, next, previous page instances * Response.ResponseBuilder responseBuilder = Response.status(200); * responseBuilder.entity(entities); * // Add headers with first, last, next and previous page URIs if they exist * return responseBuilder.build(); * }); * * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> */ @Override protected void implementInternal(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceField) { if (resourceProperties.isPaged()) { implementPaged(classCreator, resourceMetadata, resourceProperties, resourceField); } else { implementNotPaged(classCreator, resourceMetadata, resourceProperties, resourceField); } } @Override protected String getResourceMethodName() { return RESOURCE_METHOD_NAME; } protected String getMethodName() { return METHOD_NAME; } @Override protected void addProducesJsonAnnotation(AnnotatedElement element, ResourceProperties properties) { super.addProducesAnnotation(element, APPLICATION_JSON); } protected void returnValueWithLinks(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, ResultHandle value, ResultHandle links) { creator.returnValue(responseImplementor.ok(creator, value, links)); } protected void returnValue(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, ResultHandle value) { creator.returnValue(responseImplementor.ok(creator, value)); } private void implementPaged(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceField) { // Method parameters: sort strings, page index, page size, uri info Collection<SignatureMethodCreator.Parameter> compatibleFieldsForQuery = getFieldsToQuery(resourceMetadata); List<SignatureMethodCreator.Parameter> parameters = new ArrayList<>(); parameters.add(param("sort", List.class, parameterizedType(classType(List.class), classType(String.class)))); parameters.add(param("page", int.class, intType())); parameters.add(param("size", int.class, intType())); parameters.add(param("uriInfo", UriInfo.class)); parameters.add(param("namedQuery", String.class)); parameters.addAll(compatibleFieldsForQuery); MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(getMethodName(), classCreator, isNotReactivePanache() ? responseType() : uniType(resourceMetadata.getEntityType()), parameters.toArray(new SignatureMethodCreator.Parameter[0])); // Add method annotations addGetAnnotation(methodCreator); addPathAnnotation(methodCreator, resourceProperties.getPath(RESOURCE_METHOD_NAME)); addProducesJsonAnnotation(methodCreator, resourceProperties); addLinksAnnotation(methodCreator, resourceProperties, resourceMetadata.getEntityType(), REL); addMethodAnnotations(methodCreator, resourceProperties.getMethodAnnotations(RESOURCE_METHOD_NAME)); addOpenApiResponseAnnotation(methodCreator, Response.Status.OK, resourceMetadata.getEntityType(), true); addSecurityAnnotations(methodCreator, resourceProperties); addSortQueryParamValidatorAnnotation(methodCreator); addQueryParamAnnotation(methodCreator.getParameterAnnotations(0), "sort"); addQueryParamAnnotation(methodCreator.getParameterAnnotations(1), "page"); addDefaultValueAnnotation(methodCreator.getParameterAnnotations(1), Integer.toString(DEFAULT_PAGE_INDEX)); addQueryParamAnnotation(methodCreator.getParameterAnnotations(2), "size"); addDefaultValueAnnotation(methodCreator.getParameterAnnotations(2), Integer.toString(DEFAULT_PAGE_SIZE)); addContextAnnotation(methodCreator.getParameterAnnotations(3)); addQueryParamAnnotation(methodCreator.getParameterAnnotations(4), "namedQuery"); Map<String, ResultHandle> fieldValues = new HashMap<>(); int index = 5; for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { addQueryParamAnnotation(methodCreator.getParameterAnnotations(index), param.getName()); fieldValues.put(param.getName(), methodCreator.getMethodParam(index)); index++; } ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis()); ResultHandle sortQuery = methodCreator.getMethodParam(0); ResultHandle sort = sortImplementor.getSort(methodCreator, sortQuery); ResultHandle pageIndex = methodCreator.getMethodParam(1); ResultHandle pageSize = methodCreator.getMethodParam(2); ResultHandle page = paginationImplementor.getPage(methodCreator, pageIndex, pageSize); ResultHandle uriInfo = methodCreator.getMethodParam(3); ResultHandle namedQuery = methodCreator.getMethodParam(4); if (isNotReactivePanache()) { TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE); ResultHandle pageCount = tryBlock.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), Constants.PAGE_COUNT_METHOD_PREFIX + RESOURCE_METHOD_NAME, int.class, Page.class), resource, page); ResultHandle links = paginationImplementor.getLinks(tryBlock, uriInfo, page, pageCount); ResultHandle entities = list(tryBlock, resourceMetadata, resource, page, sort, namedQuery, fieldValues); // Return response returnValueWithLinks(tryBlock, resourceMetadata, resourceProperties, entities, links); tryBlock.close(); } else { ResultHandle uniPageCount = methodCreator.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), Constants.PAGE_COUNT_METHOD_PREFIX + RESOURCE_METHOD_NAME, Uni.class, Page.class), resource, page); methodCreator.returnValue(UniImplementor.flatMap(methodCreator, uniPageCount, EXCEPTION_MESSAGE, (body, pageCount) -> { ResultHandle pageCountAsInt = body.checkCast(pageCount, Integer.class); ResultHandle links = paginationImplementor.getLinks(body, uriInfo, page, pageCountAsInt); ResultHandle uniEntities = list(body, resourceMetadata, resource, page, sort, namedQuery, fieldValues); body.returnValue(UniImplementor.map(body, uniEntities, EXCEPTION_MESSAGE, (listBody, list) -> returnValueWithLinks(listBody, resourceMetadata, resourceProperties, list, links))); })); } methodCreator.close(); } private Collection<SignatureMethodCreator.Parameter> getFieldsToQuery(ResourceMetadata resourceMetadata) { return resourceMetadata.getFields().entrySet() .stream() .filter(e -> isFieldTypeCompatibleForQueryParam(e.getValue())) // we need to map primitive types to classes to make the fields nullable .map(e -> param(e.getKey(), primitiveToClass(e.getValue().name().toString()))) .collect(Collectors.toList()); } private void implementNotPaged(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceFieldDescriptor) { Collection<SignatureMethodCreator.Parameter> compatibleFieldsForQuery = getFieldsToQuery(resourceMetadata); List<SignatureMethodCreator.Parameter> parameters = new ArrayList<>(); parameters.add(param("sort", List.class, parameterizedType(classType(List.class), classType(String.class)))); parameters.add(param("namedQuery", String.class)); parameters.addAll(compatibleFieldsForQuery); MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(getMethodName(), classCreator, isNotReactivePanache() ? responseType() : uniType(resourceMetadata.getEntityType()), parameters.toArray(new SignatureMethodCreator.Parameter[0])); // Add method annotations addGetAnnotation(methodCreator); addPathAnnotation(methodCreator, resourceProperties.getPath(RESOURCE_METHOD_NAME)); addProducesJsonAnnotation(methodCreator, resourceProperties); addLinksAnnotation(methodCreator, resourceProperties, resourceMetadata.getEntityType(), REL); addMethodAnnotations(methodCreator, resourceProperties.getMethodAnnotations(RESOURCE_METHOD_NAME)); addOpenApiResponseAnnotation(methodCreator, Response.Status.OK, resourceMetadata.getEntityType(), true); addSecurityAnnotations(methodCreator, resourceProperties); addQueryParamAnnotation(methodCreator.getParameterAnnotations(0), "sort"); addQueryParamAnnotation(methodCreator.getParameterAnnotations(1), "namedQuery"); Map<String, ResultHandle> fieldValues = new HashMap<>(); int index = 2; for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { addQueryParamAnnotation(methodCreator.getParameterAnnotations(index), param.getName()); fieldValues.put(param.getName(), methodCreator.getMethodParam(index)); index++; } ResultHandle sortQuery = methodCreator.getMethodParam(0); ResultHandle namedQuery = methodCreator.getMethodParam(1); ResultHandle sort = sortImplementor.getSort(methodCreator, sortQuery); ResultHandle resource = methodCreator.readInstanceField(resourceFieldDescriptor, methodCreator.getThis()); if (isNotReactivePanache()) { TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE); ResultHandle entities = list(tryBlock, resourceMetadata, resource, null, sort, namedQuery, fieldValues); returnValue(tryBlock, resourceMetadata, resourceProperties, entities); tryBlock.close(); } else { ResultHandle uniEntities = list(methodCreator, resourceMetadata, resource, methodCreator.loadNull(), sort, namedQuery, fieldValues); methodCreator.returnValue(UniImplementor.map(methodCreator, uniEntities, EXCEPTION_MESSAGE, (body, entities) -> returnValue(body, resourceMetadata, resourceProperties, entities))); } methodCreator.close(); } public ResultHandle list(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResultHandle resource, ResultHandle page, ResultHandle sort, ResultHandle namedQuery, Map<String, ResultHandle> fieldValues) { ResultHandle dataParams = creator.newInstance(ofConstructor(HashMap.class)); ResultHandle queryList = creator.newInstance(ofConstructor(ArrayList.class)); for (Map.Entry<String, ResultHandle> field : fieldValues.entrySet()) { String fieldName = field.getKey(); ResultHandle fieldValueFromQuery = field.getValue(); BytecodeCreator fieldValueFromQueryIsSet = creator.ifNotNull(fieldValueFromQuery).trueBranch(); fieldValueFromQueryIsSet.invokeInterfaceMethod(ofMethod(List.class, "add", boolean.class, Object.class), queryList, fieldValueFromQueryIsSet.load(fieldName + "=:" + fieldName)); fieldValueFromQueryIsSet.invokeInterfaceMethod( ofMethod(Map.class, "put", Object.class, Object.class, Object.class), dataParams, fieldValueFromQueryIsSet.load(fieldName), fieldValueFromQuery); } /** * String query; * if (namedQuery != null) { * query = "#" + namedQuery; * } else { * query = String.join(" AND ", queryList); * } */ AssignableResultHandle query = creator.createVariable(String.class); BranchResult checkIfNamedQueryIsNull = creator.ifNull(namedQuery); BytecodeCreator whenNamedQueryIsNull = checkIfNamedQueryIsNull.trueBranch(); BytecodeCreator whenNamedQueryIsNotNull = checkIfNamedQueryIsNull.falseBranch(); whenNamedQueryIsNotNull.assign(query, whenNamedQueryIsNotNull.invokeVirtualMethod( ofMethod(String.class, "concat", String.class, String.class), whenNamedQueryIsNotNull.load("#"), namedQuery)); whenNamedQueryIsNull.assign(query, whenNamedQueryIsNull.invokeStaticMethod( ofMethod(String.class, "join", String.class, CharSequence.class, Iterable.class), creator.load(" AND "), queryList)); return creator.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), "list", isNotReactivePanache() ? List.class : Uni.class, Page.class, Sort.class, String.class, Map.class), resource, page == null ? creator.loadNull() : page, sort, query, dataParams); } private boolean isFieldTypeCompatibleForQueryParam(Type fieldType) { return fieldType.name().equals(STRING) || fieldType.name().equals(BOOLEAN) || fieldType.name().equals(CHARACTER) || fieldType.name().equals(DOUBLE) || fieldType.name().equals(SHORT) || fieldType.name().equals(FLOAT) || fieldType.name().equals(INTEGER) || fieldType.name().equals(LONG) || fieldType.name().equals(BYTE) || fieldType.kind() == Type.Kind.PRIMITIVE; } }
UTF-8
Java
20,003
java
ListMethodImplementor.java
Java
[]
null
[]
package io.quarkus.rest.data.panache.deployment.methods; import static io.quarkus.arc.processor.DotNames.BOOLEAN; import static io.quarkus.arc.processor.DotNames.BYTE; import static io.quarkus.arc.processor.DotNames.CHARACTER; import static io.quarkus.arc.processor.DotNames.DOUBLE; import static io.quarkus.arc.processor.DotNames.FLOAT; import static io.quarkus.arc.processor.DotNames.INTEGER; import static io.quarkus.arc.processor.DotNames.LONG; import static io.quarkus.arc.processor.DotNames.SHORT; import static io.quarkus.arc.processor.DotNames.STRING; import static io.quarkus.gizmo.MethodDescriptor.ofConstructor; import static io.quarkus.gizmo.MethodDescriptor.ofMethod; import static io.quarkus.gizmo.Type.classType; import static io.quarkus.gizmo.Type.intType; import static io.quarkus.gizmo.Type.parameterizedType; import static io.quarkus.rest.data.panache.deployment.utils.PaginationImplementor.DEFAULT_PAGE_INDEX; import static io.quarkus.rest.data.panache.deployment.utils.PaginationImplementor.DEFAULT_PAGE_SIZE; import static io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator.param; import static io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator.responseType; import static io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator.uniType; import static io.quarkus.rest.data.panache.deployment.utils.TypeUtils.primitiveToClass; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import org.jboss.jandex.Type; import io.quarkus.deployment.Capabilities; import io.quarkus.gizmo.AnnotatedElement; import io.quarkus.gizmo.AssignableResultHandle; import io.quarkus.gizmo.BranchResult; import io.quarkus.gizmo.BytecodeCreator; import io.quarkus.gizmo.ClassCreator; import io.quarkus.gizmo.FieldDescriptor; import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.ResultHandle; import io.quarkus.gizmo.TryBlock; import io.quarkus.panache.common.Page; import io.quarkus.panache.common.Sort; import io.quarkus.rest.data.panache.RestDataResource; import io.quarkus.rest.data.panache.deployment.Constants; import io.quarkus.rest.data.panache.deployment.ResourceMetadata; import io.quarkus.rest.data.panache.deployment.properties.ResourceProperties; import io.quarkus.rest.data.panache.deployment.utils.PaginationImplementor; import io.quarkus.rest.data.panache.deployment.utils.SignatureMethodCreator; import io.quarkus.rest.data.panache.deployment.utils.SortImplementor; import io.quarkus.rest.data.panache.deployment.utils.UniImplementor; import io.smallrye.mutiny.Uni; public class ListMethodImplementor extends StandardMethodImplementor { private static final String METHOD_NAME = "list"; private static final String RESOURCE_METHOD_NAME = "list"; private static final String EXCEPTION_MESSAGE = "Failed to list the entities"; private static final String REL = "list"; private final PaginationImplementor paginationImplementor = new PaginationImplementor(); private final SortImplementor sortImplementor = new SortImplementor(); public ListMethodImplementor(Capabilities capabilities) { super(capabilities); } /** * Generate JAX-RS GET method. * * The RESTEasy Classic version exposes {@link RestDataResource#list(Page, Sort)} * and the generated pseudocode with enabled pagination is shown below. If pagination is disabled pageIndex and pageSize * query parameters are skipped and null {@link Page} instance is used. * * <pre> * {@code * &#64;GET * &#64;Path("") * &#64;Produces({"application/json"}) * &#64;LinkResource( * rel = "list", * entityClassName = "com.example.Entity" * ) * public Response list(&#64;QueryParam("page") &#64;DefaultValue("0") int pageIndex, * &#64;QueryParam("size") &#64;DefaultValue("20") int pageSize, * &#64;QueryParam("sort") List<String> sortQuery) { * Page page = Page.of(pageIndex, pageSize); * Sort sort = ...; // Build a sort instance from String entries of sortQuery * try { * List<Entity> entities = resource.getAll(page, sort); * // Get the page count, and build first, last, next, previous page instances * Response.ResponseBuilder responseBuilder = Response.status(200); * responseBuilder.entity(entities); * // Add headers with first, last, next and previous page URIs if they exist * return responseBuilder.build(); * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> * * The RESTEasy Reactive version exposes {@link io.quarkus.rest.data.panache.ReactiveRestDataResource#list(Page, Sort)} * and the generated code looks more or less like this: * * <pre> * {@code * &#64;GET * &#64;Path("") * &#64;Produces({"application/json"}) * &#64;LinkResource( * rel = "list", * entityClassName = "com.example.Entity" * ) * public Uni<Response> list(&#64;QueryParam("page") &#64;DefaultValue("0") int pageIndex, * &#64;QueryParam("size") &#64;DefaultValue("20") int pageSize, * &#64;QueryParam("sort") List<String> sortQuery) { * Page page = Page.of(pageIndex, pageSize); * Sort sort = ...; // Build a sort instance from String entries of sortQuery * try { * return resource.getAll(page, sort).map(entities -> { * // Get the page count, and build first, last, next, previous page instances * Response.ResponseBuilder responseBuilder = Response.status(200); * responseBuilder.entity(entities); * // Add headers with first, last, next and previous page URIs if they exist * return responseBuilder.build(); * }); * * } catch (Throwable t) { * throw new RestDataPanacheException(t); * } * } * } * </pre> */ @Override protected void implementInternal(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceField) { if (resourceProperties.isPaged()) { implementPaged(classCreator, resourceMetadata, resourceProperties, resourceField); } else { implementNotPaged(classCreator, resourceMetadata, resourceProperties, resourceField); } } @Override protected String getResourceMethodName() { return RESOURCE_METHOD_NAME; } protected String getMethodName() { return METHOD_NAME; } @Override protected void addProducesJsonAnnotation(AnnotatedElement element, ResourceProperties properties) { super.addProducesAnnotation(element, APPLICATION_JSON); } protected void returnValueWithLinks(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, ResultHandle value, ResultHandle links) { creator.returnValue(responseImplementor.ok(creator, value, links)); } protected void returnValue(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, ResultHandle value) { creator.returnValue(responseImplementor.ok(creator, value)); } private void implementPaged(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceField) { // Method parameters: sort strings, page index, page size, uri info Collection<SignatureMethodCreator.Parameter> compatibleFieldsForQuery = getFieldsToQuery(resourceMetadata); List<SignatureMethodCreator.Parameter> parameters = new ArrayList<>(); parameters.add(param("sort", List.class, parameterizedType(classType(List.class), classType(String.class)))); parameters.add(param("page", int.class, intType())); parameters.add(param("size", int.class, intType())); parameters.add(param("uriInfo", UriInfo.class)); parameters.add(param("namedQuery", String.class)); parameters.addAll(compatibleFieldsForQuery); MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(getMethodName(), classCreator, isNotReactivePanache() ? responseType() : uniType(resourceMetadata.getEntityType()), parameters.toArray(new SignatureMethodCreator.Parameter[0])); // Add method annotations addGetAnnotation(methodCreator); addPathAnnotation(methodCreator, resourceProperties.getPath(RESOURCE_METHOD_NAME)); addProducesJsonAnnotation(methodCreator, resourceProperties); addLinksAnnotation(methodCreator, resourceProperties, resourceMetadata.getEntityType(), REL); addMethodAnnotations(methodCreator, resourceProperties.getMethodAnnotations(RESOURCE_METHOD_NAME)); addOpenApiResponseAnnotation(methodCreator, Response.Status.OK, resourceMetadata.getEntityType(), true); addSecurityAnnotations(methodCreator, resourceProperties); addSortQueryParamValidatorAnnotation(methodCreator); addQueryParamAnnotation(methodCreator.getParameterAnnotations(0), "sort"); addQueryParamAnnotation(methodCreator.getParameterAnnotations(1), "page"); addDefaultValueAnnotation(methodCreator.getParameterAnnotations(1), Integer.toString(DEFAULT_PAGE_INDEX)); addQueryParamAnnotation(methodCreator.getParameterAnnotations(2), "size"); addDefaultValueAnnotation(methodCreator.getParameterAnnotations(2), Integer.toString(DEFAULT_PAGE_SIZE)); addContextAnnotation(methodCreator.getParameterAnnotations(3)); addQueryParamAnnotation(methodCreator.getParameterAnnotations(4), "namedQuery"); Map<String, ResultHandle> fieldValues = new HashMap<>(); int index = 5; for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { addQueryParamAnnotation(methodCreator.getParameterAnnotations(index), param.getName()); fieldValues.put(param.getName(), methodCreator.getMethodParam(index)); index++; } ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis()); ResultHandle sortQuery = methodCreator.getMethodParam(0); ResultHandle sort = sortImplementor.getSort(methodCreator, sortQuery); ResultHandle pageIndex = methodCreator.getMethodParam(1); ResultHandle pageSize = methodCreator.getMethodParam(2); ResultHandle page = paginationImplementor.getPage(methodCreator, pageIndex, pageSize); ResultHandle uriInfo = methodCreator.getMethodParam(3); ResultHandle namedQuery = methodCreator.getMethodParam(4); if (isNotReactivePanache()) { TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE); ResultHandle pageCount = tryBlock.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), Constants.PAGE_COUNT_METHOD_PREFIX + RESOURCE_METHOD_NAME, int.class, Page.class), resource, page); ResultHandle links = paginationImplementor.getLinks(tryBlock, uriInfo, page, pageCount); ResultHandle entities = list(tryBlock, resourceMetadata, resource, page, sort, namedQuery, fieldValues); // Return response returnValueWithLinks(tryBlock, resourceMetadata, resourceProperties, entities, links); tryBlock.close(); } else { ResultHandle uniPageCount = methodCreator.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), Constants.PAGE_COUNT_METHOD_PREFIX + RESOURCE_METHOD_NAME, Uni.class, Page.class), resource, page); methodCreator.returnValue(UniImplementor.flatMap(methodCreator, uniPageCount, EXCEPTION_MESSAGE, (body, pageCount) -> { ResultHandle pageCountAsInt = body.checkCast(pageCount, Integer.class); ResultHandle links = paginationImplementor.getLinks(body, uriInfo, page, pageCountAsInt); ResultHandle uniEntities = list(body, resourceMetadata, resource, page, sort, namedQuery, fieldValues); body.returnValue(UniImplementor.map(body, uniEntities, EXCEPTION_MESSAGE, (listBody, list) -> returnValueWithLinks(listBody, resourceMetadata, resourceProperties, list, links))); })); } methodCreator.close(); } private Collection<SignatureMethodCreator.Parameter> getFieldsToQuery(ResourceMetadata resourceMetadata) { return resourceMetadata.getFields().entrySet() .stream() .filter(e -> isFieldTypeCompatibleForQueryParam(e.getValue())) // we need to map primitive types to classes to make the fields nullable .map(e -> param(e.getKey(), primitiveToClass(e.getValue().name().toString()))) .collect(Collectors.toList()); } private void implementNotPaged(ClassCreator classCreator, ResourceMetadata resourceMetadata, ResourceProperties resourceProperties, FieldDescriptor resourceFieldDescriptor) { Collection<SignatureMethodCreator.Parameter> compatibleFieldsForQuery = getFieldsToQuery(resourceMetadata); List<SignatureMethodCreator.Parameter> parameters = new ArrayList<>(); parameters.add(param("sort", List.class, parameterizedType(classType(List.class), classType(String.class)))); parameters.add(param("namedQuery", String.class)); parameters.addAll(compatibleFieldsForQuery); MethodCreator methodCreator = SignatureMethodCreator.getMethodCreator(getMethodName(), classCreator, isNotReactivePanache() ? responseType() : uniType(resourceMetadata.getEntityType()), parameters.toArray(new SignatureMethodCreator.Parameter[0])); // Add method annotations addGetAnnotation(methodCreator); addPathAnnotation(methodCreator, resourceProperties.getPath(RESOURCE_METHOD_NAME)); addProducesJsonAnnotation(methodCreator, resourceProperties); addLinksAnnotation(methodCreator, resourceProperties, resourceMetadata.getEntityType(), REL); addMethodAnnotations(methodCreator, resourceProperties.getMethodAnnotations(RESOURCE_METHOD_NAME)); addOpenApiResponseAnnotation(methodCreator, Response.Status.OK, resourceMetadata.getEntityType(), true); addSecurityAnnotations(methodCreator, resourceProperties); addQueryParamAnnotation(methodCreator.getParameterAnnotations(0), "sort"); addQueryParamAnnotation(methodCreator.getParameterAnnotations(1), "namedQuery"); Map<String, ResultHandle> fieldValues = new HashMap<>(); int index = 2; for (SignatureMethodCreator.Parameter param : compatibleFieldsForQuery) { addQueryParamAnnotation(methodCreator.getParameterAnnotations(index), param.getName()); fieldValues.put(param.getName(), methodCreator.getMethodParam(index)); index++; } ResultHandle sortQuery = methodCreator.getMethodParam(0); ResultHandle namedQuery = methodCreator.getMethodParam(1); ResultHandle sort = sortImplementor.getSort(methodCreator, sortQuery); ResultHandle resource = methodCreator.readInstanceField(resourceFieldDescriptor, methodCreator.getThis()); if (isNotReactivePanache()) { TryBlock tryBlock = implementTryBlock(methodCreator, EXCEPTION_MESSAGE); ResultHandle entities = list(tryBlock, resourceMetadata, resource, null, sort, namedQuery, fieldValues); returnValue(tryBlock, resourceMetadata, resourceProperties, entities); tryBlock.close(); } else { ResultHandle uniEntities = list(methodCreator, resourceMetadata, resource, methodCreator.loadNull(), sort, namedQuery, fieldValues); methodCreator.returnValue(UniImplementor.map(methodCreator, uniEntities, EXCEPTION_MESSAGE, (body, entities) -> returnValue(body, resourceMetadata, resourceProperties, entities))); } methodCreator.close(); } public ResultHandle list(BytecodeCreator creator, ResourceMetadata resourceMetadata, ResultHandle resource, ResultHandle page, ResultHandle sort, ResultHandle namedQuery, Map<String, ResultHandle> fieldValues) { ResultHandle dataParams = creator.newInstance(ofConstructor(HashMap.class)); ResultHandle queryList = creator.newInstance(ofConstructor(ArrayList.class)); for (Map.Entry<String, ResultHandle> field : fieldValues.entrySet()) { String fieldName = field.getKey(); ResultHandle fieldValueFromQuery = field.getValue(); BytecodeCreator fieldValueFromQueryIsSet = creator.ifNotNull(fieldValueFromQuery).trueBranch(); fieldValueFromQueryIsSet.invokeInterfaceMethod(ofMethod(List.class, "add", boolean.class, Object.class), queryList, fieldValueFromQueryIsSet.load(fieldName + "=:" + fieldName)); fieldValueFromQueryIsSet.invokeInterfaceMethod( ofMethod(Map.class, "put", Object.class, Object.class, Object.class), dataParams, fieldValueFromQueryIsSet.load(fieldName), fieldValueFromQuery); } /** * String query; * if (namedQuery != null) { * query = "#" + namedQuery; * } else { * query = String.join(" AND ", queryList); * } */ AssignableResultHandle query = creator.createVariable(String.class); BranchResult checkIfNamedQueryIsNull = creator.ifNull(namedQuery); BytecodeCreator whenNamedQueryIsNull = checkIfNamedQueryIsNull.trueBranch(); BytecodeCreator whenNamedQueryIsNotNull = checkIfNamedQueryIsNull.falseBranch(); whenNamedQueryIsNotNull.assign(query, whenNamedQueryIsNotNull.invokeVirtualMethod( ofMethod(String.class, "concat", String.class, String.class), whenNamedQueryIsNotNull.load("#"), namedQuery)); whenNamedQueryIsNull.assign(query, whenNamedQueryIsNull.invokeStaticMethod( ofMethod(String.class, "join", String.class, CharSequence.class, Iterable.class), creator.load(" AND "), queryList)); return creator.invokeVirtualMethod( ofMethod(resourceMetadata.getResourceClass(), "list", isNotReactivePanache() ? List.class : Uni.class, Page.class, Sort.class, String.class, Map.class), resource, page == null ? creator.loadNull() : page, sort, query, dataParams); } private boolean isFieldTypeCompatibleForQueryParam(Type fieldType) { return fieldType.name().equals(STRING) || fieldType.name().equals(BOOLEAN) || fieldType.name().equals(CHARACTER) || fieldType.name().equals(DOUBLE) || fieldType.name().equals(SHORT) || fieldType.name().equals(FLOAT) || fieldType.name().equals(INTEGER) || fieldType.name().equals(LONG) || fieldType.name().equals(BYTE) || fieldType.kind() == Type.Kind.PRIMITIVE; } }
20,003
0.691096
0.687697
370
53.06216
36.178894
127
false
false
0
0
0
0
0
0
1.197297
false
false
13
0726a6250620fa25393794254ef5531e4025637c
28,166,395,585,885
c4f9abe9ec9c967ae2333d0cc394184975532020
/change-log-generator-gui/src/main/java/com/tuannguyen/liquibase/gui/helper/DefaultCallbackListCell.java
37f40f14b06cab2b0453516b2df91e2ccbe0e1e2
[]
no_license
vdtn359/change-log-generator-gui
https://github.com/vdtn359/change-log-generator-gui
e77635abbc2162d30a6251c2492ddba559637a69
b450b9eb5ad644b6de77689247ea686e37231886
refs/heads/master
2020-03-31T07:12:18.730000
2019-04-15T01:23:36
2019-04-15T01:23:36
152,012,284
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tuannguyen.liquibase.gui.helper; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.util.Callback; public abstract class DefaultCallbackListCell<T> implements Callback<ListView<T>, ListCell<T>> { @Override public ListCell<T> call(ListView<T> listView) { return new ListCell<T>() { @Override protected void updateItem(T item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); } else { setText(getTitle(item)); } this.setVisible(item != null || !empty); } }; } public abstract String getTitle(T item); }
UTF-8
Java
654
java
DefaultCallbackListCell.java
Java
[]
null
[]
package com.tuannguyen.liquibase.gui.helper; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.util.Callback; public abstract class DefaultCallbackListCell<T> implements Callback<ListView<T>, ListCell<T>> { @Override public ListCell<T> call(ListView<T> listView) { return new ListCell<T>() { @Override protected void updateItem(T item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setGraphic(null); } else { setText(getTitle(item)); } this.setVisible(item != null || !empty); } }; } public abstract String getTitle(T item); }
654
0.689602
0.689602
29
21.551723
21.829411
94
false
false
0
0
0
0
0
0
2.413793
false
false
13
699465985a0db9a1c906e5d17b5f9107a8dbabd2
18,348,100,305,648
b93c7d2e3befd4ad85417addf63cc516ac555dc1
/Week8/User.java
640a7e735ed7051f24ea119ee94415fb12909709
[]
no_license
cagankeskin/CMPE261_Large_Scale_Programming
https://github.com/cagankeskin/CMPE261_Large_Scale_Programming
5cc3f9f486451b8f8d8649241cba7ce9f0c2910a
ab107ed3647bc315dc9aa68e9404d116887faa10
refs/heads/master
2020-05-16T11:48:23.880000
2018-02-24T20:30:39
2018-02-24T20:30:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class User extends Thread{ private Item item; public User(Item i){ this.item=i; } public void run(){ try{ for(int i=0;i<=5;i++){ System.out.println(item.buyCar()); sleep(1000); } }catch(Exception e){return;} } }
UTF-8
Java
277
java
User.java
Java
[]
null
[]
public class User extends Thread{ private Item item; public User(Item i){ this.item=i; } public void run(){ try{ for(int i=0;i<=5;i++){ System.out.println(item.buyCar()); sleep(1000); } }catch(Exception e){return;} } }
277
0.541516
0.519856
24
10.5
12.213381
40
false
false
0
0
0
0
0
0
2.208333
false
false
13
a9a9879da707219776214ff5d9878084b3971f6b
29,618,094,511,758
b6fb271116e13e2f8be7fcf86bca06bc0a8e4874
/src/org/young/dao/UserDao.java
c8305a7c8b74db589b2d9eb3c6551685431a607b
[]
no_license
xue-x-d/CollectionCode4Java
https://github.com/xue-x-d/CollectionCode4Java
59f1fdacb87c7356a5e5dc6e9f492aa1052ac0d0
cc258aec46316484dd131148d977233040427c49
refs/heads/master
2020-12-25T00:05:09.074000
2014-05-16T08:31:26
2014-05-16T08:31:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.young.dao; import org.young.entity.User; public interface UserDao { User load(String id); void save(User user); }
UTF-8
Java
144
java
UserDao.java
Java
[]
null
[]
package org.young.dao; import org.young.entity.User; public interface UserDao { User load(String id); void save(User user); }
144
0.666667
0.666667
11
11.090909
12.124015
29
false
false
0
0
0
0
0
0
0.545455
false
false
13
b6cf98299b97a4d7bc6ec91a6e61b8647fc564c0
33,586,644,254,943
65b33c5ad14ca9b0707ca2b7c0ffd0878132ac80
/src/main/java/com/weberfly/entities/Category.java
425172aeb646d6b46875be9aa66d0f3076a59305
[ "MIT" ]
permissive
kamalber/FlyProject-spring-boot
https://github.com/kamalber/FlyProject-spring-boot
303e443d929c5440fca43850d4a1efb41b043a22
73e02d2037389019887928207ccb8d5408738e00
refs/heads/master
2021-08-23T23:13:29.413000
2017-12-07T01:32:44
2017-12-07T01:32:44
87,922,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.weberfly.entities; /******************************************************************************* * 2017, All rights reserved. *******************************************************************************/ import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; // Start of user code (user defined imports) // End of user code /** * Description of Category. * * @author kamal */ @Entity @Table(name="Category") public class Category implements Serializable{ /** * Description of the property id. */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private Date dateCreation; public Date getDateCreation() { return dateCreation; } public void setDateCreation(Date dateCreation) { this.dateCreation = dateCreation; } @OneToMany(cascade = CascadeType.ALL, mappedBy = "category") private List<TwitterKeyWord> keyWords; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void setKeyWords(List<TwitterKeyWord> keyWords) { this.keyWords = keyWords; } }
UTF-8
Java
1,661
java
Category.java
Java
[ { "context": "\n/**\r\n * Description of Category.\r\n * \r\n * @author kamal\r\n */\r\n@Entity\r\n@Table(name=\"Category\")\r\npublic cl", "end": 799, "score": 0.997639536857605, "start": 794, "tag": "USERNAME", "value": "kamal" } ]
null
[]
package com.weberfly.entities; /******************************************************************************* * 2017, All rights reserved. *******************************************************************************/ import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; // Start of user code (user defined imports) // End of user code /** * Description of Category. * * @author kamal */ @Entity @Table(name="Category") public class Category implements Serializable{ /** * Description of the property id. */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private Date dateCreation; public Date getDateCreation() { return dateCreation; } public void setDateCreation(Date dateCreation) { this.dateCreation = dateCreation; } @OneToMany(cascade = CascadeType.ALL, mappedBy = "category") private List<TwitterKeyWord> keyWords; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public void setKeyWords(List<TwitterKeyWord> keyWords) { this.keyWords = keyWords; } }
1,661
0.63817
0.635762
78
19.294872
19.464701
81
false
false
0
0
0
0
0
0
0.846154
false
false
13
fcc9007d48b2b2c01983a3b48e631cf1ec593116
11,484,742,583,351
4f926c51518332ee8e87229e29f74b3248a4d560
/perfManageSys/perfManageSys/src/main/java/com/hnran/perfmanagesys/activity/CustomerActivity.java
e41347fb74c9c0c3837a8cc131b71aa0b44d25ba
[]
no_license
fubuki01/perfMS
https://github.com/fubuki01/perfMS
051d08d294a7fa8e1841dceda636579e75976134
3eac1e97ac81c457ba6a6804b2453b35239ce986
refs/heads/master
2020-03-21T02:20:30.601000
2018-06-20T07:54:56
2018-06-20T07:54:56
137,994,167
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hnran.perfmanagesys.activity; import java.util.ArrayList; import java.util.List; import com.hnran.perfmanagesys.R; import com.hnran.perfmanagesys.adapter.ViewPagerAdapter; import com.hnran.perfmanagesys.fragment.customer.CustomerInfoFragment; import com.hnran.perfmanagesys.fragment.customer.CustomerProductFragment2; import com.hnran.perfmanagesys.fragment.customer.CustomerRelationFragment; import android.R.color; import android.annotation.SuppressLint; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; public class CustomerActivity extends FragmentActivity{ private ViewPager viewPager; private ViewPagerAdapter vpAdapter; private List<Fragment> fragmentLists; private List<TextView> tvLists; private LinearLayout llBack; private HorizontalScrollView horizontalScrollView; private int currentPosition; private int oldPosition; private int width; private Resources mResources; private String mTitle; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); initVariables(); initViews(savedInstanceState); loadData(); } protected void initVariables() { // TODO Auto-generated method stub WindowManager wm = this.getWindowManager(); width = wm.getDefaultDisplay().getWidth(); mTitle = getIntent().getStringExtra("Extra_title"); mResources = getResources(); oldPosition = currentPosition = 0; fragmentLists = new ArrayList<Fragment>(); vpAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragmentLists); tvLists = new ArrayList<TextView>(); } protected void initViews(Bundle savedInstanceState) { // TODO Auto-generated method stub setContentView(R.layout.activity_customer); TextView tv = (TextView) findViewById(R.id.tv_common_back_title); tv.setText(mTitle); llBack = (LinearLayout)findViewById(R.id.ll_common_back); llBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); viewPager = (ViewPager) findViewById(R.id.customer_viewpager); viewPager.setAdapter(vpAdapter); viewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int arg0) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = arg0; changeTabState(); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } }); TextView tv0 = (TextView) findViewById(R.id.customer_tv_jiben); tv0.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = 0; changeTabState(); } }); TextView tv1 = (TextView) findViewById(R.id.customer_tv_guanlianren); tv1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = 1; changeTabState(); } }); TextView tv2 = (TextView) findViewById(R.id.customer_tv_chanpin); tv2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = 2; changeTabState(); } }); tvLists.add(tv0); tvLists.add(tv1); tvLists.add(tv2); } protected void loadData() { // TODO Auto-generated method stub fragmentLists.add(new CustomerInfoFragment()); fragmentLists.add(new CustomerRelationFragment()); fragmentLists.add(new CustomerProductFragment2()); vpAdapter.notifyDataSetChanged(); viewPager.setCurrentItem(currentPosition); changeTabState(); } @SuppressLint("NewApi") public void changeTabState(){ TextView old = tvLists.get(oldPosition); TextView current = tvLists.get(currentPosition); old.setBackgroundColor(color.transparent); old.setTextColor(mResources.getColor(R.color.font_black_1)); current.setBackgroundColor(mResources.getColor(R.color.bg_tab_selected)); current.setTextColor(mResources.getColor(R.color.font_tab_selected)); if(viewPager.getCurrentItem() != currentPosition){ viewPager.setCurrentItem(currentPosition); } } }
UTF-8
Java
5,090
java
CustomerActivity.java
Java
[]
null
[]
package com.hnran.perfmanagesys.activity; import java.util.ArrayList; import java.util.List; import com.hnran.perfmanagesys.R; import com.hnran.perfmanagesys.adapter.ViewPagerAdapter; import com.hnran.perfmanagesys.fragment.customer.CustomerInfoFragment; import com.hnran.perfmanagesys.fragment.customer.CustomerProductFragment2; import com.hnran.perfmanagesys.fragment.customer.CustomerRelationFragment; import android.R.color; import android.annotation.SuppressLint; import android.content.res.Resources; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.TextView; public class CustomerActivity extends FragmentActivity{ private ViewPager viewPager; private ViewPagerAdapter vpAdapter; private List<Fragment> fragmentLists; private List<TextView> tvLists; private LinearLayout llBack; private HorizontalScrollView horizontalScrollView; private int currentPosition; private int oldPosition; private int width; private Resources mResources; private String mTitle; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE); initVariables(); initViews(savedInstanceState); loadData(); } protected void initVariables() { // TODO Auto-generated method stub WindowManager wm = this.getWindowManager(); width = wm.getDefaultDisplay().getWidth(); mTitle = getIntent().getStringExtra("Extra_title"); mResources = getResources(); oldPosition = currentPosition = 0; fragmentLists = new ArrayList<Fragment>(); vpAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragmentLists); tvLists = new ArrayList<TextView>(); } protected void initViews(Bundle savedInstanceState) { // TODO Auto-generated method stub setContentView(R.layout.activity_customer); TextView tv = (TextView) findViewById(R.id.tv_common_back_title); tv.setText(mTitle); llBack = (LinearLayout)findViewById(R.id.ll_common_back); llBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); viewPager = (ViewPager) findViewById(R.id.customer_viewpager); viewPager.setAdapter(vpAdapter); viewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int arg0) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = arg0; changeTabState(); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } }); TextView tv0 = (TextView) findViewById(R.id.customer_tv_jiben); tv0.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = 0; changeTabState(); } }); TextView tv1 = (TextView) findViewById(R.id.customer_tv_guanlianren); tv1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = 1; changeTabState(); } }); TextView tv2 = (TextView) findViewById(R.id.customer_tv_chanpin); tv2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub oldPosition = currentPosition; currentPosition = 2; changeTabState(); } }); tvLists.add(tv0); tvLists.add(tv1); tvLists.add(tv2); } protected void loadData() { // TODO Auto-generated method stub fragmentLists.add(new CustomerInfoFragment()); fragmentLists.add(new CustomerRelationFragment()); fragmentLists.add(new CustomerProductFragment2()); vpAdapter.notifyDataSetChanged(); viewPager.setCurrentItem(currentPosition); changeTabState(); } @SuppressLint("NewApi") public void changeTabState(){ TextView old = tvLists.get(oldPosition); TextView current = tvLists.get(currentPosition); old.setBackgroundColor(color.transparent); old.setTextColor(mResources.getColor(R.color.font_black_1)); current.setBackgroundColor(mResources.getColor(R.color.bg_tab_selected)); current.setTextColor(mResources.getColor(R.color.font_tab_selected)); if(viewPager.getCurrentItem() != currentPosition){ viewPager.setCurrentItem(currentPosition); } } }
5,090
0.736542
0.731434
207
23.589373
21.685064
79
false
false
0
0
0
0
0
0
2.144928
false
false
13
470caf79c86038c1b93fecd45fa10731d35c6d7e
14,671,608,322,848
958b8e242a9e55e2f1b038f1c4bf40c1bf5d8e26
/MyMember/src/com/pro/queue/deque/MyDeque.java
43b7a72b36ac4d668d9a749b0ef5a08f46706d7e
[]
no_license
BegoniaQu/myproject
https://github.com/BegoniaQu/myproject
9018e7b77627e5364bce5d5c49007d24ca1a50fb
ad8ee008187e569d6a57b78db398809c8fe3645b
refs/heads/master
2021-01-13T00:57:21.899000
2016-01-07T05:31:05
2016-01-07T05:31:05
48,986,780
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pro.queue.deque; import java.util.ArrayDeque; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; /** * Deque与BlockingDeque --双端队列,用于工作密取模式,BlockingQueue用于生产者-消费者模式 * 双端队列:不像生产者-消费者设置中,所有消费者都共享一个工作队列。 * 双端队列在工作密取中,每个消费者都有各自的双端队列。如果一个消费者完成了自己双端队列中的全部工作, * 那么它可以从其他消费者双端队列末尾秘密地获取工作。在大多数时候,它们都只是访问自己的双端队列,从而极大的减少了竞争。 * * @author Administrator * */ public class MyDeque { /** * @param args */ public static void main(String[] args) { // Semaphore //信号量 // LinkedBlockingDeque<E> 并发 // ArrayDeque<E> //非并发 } }
UTF-8
Java
928
java
MyDeque.java
Java
[ { "context": "作。在大多数时候,它们都只是访问自己的双端队列,从而极大的减少了竞争。\n * \n * @author Administrator\n * \n */\npublic class MyDeque {\n\n\t/**\n\t * @param a", "end": 400, "score": 0.8397990465164185, "start": 387, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.pro.queue.deque; import java.util.ArrayDeque; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; /** * Deque与BlockingDeque --双端队列,用于工作密取模式,BlockingQueue用于生产者-消费者模式 * 双端队列:不像生产者-消费者设置中,所有消费者都共享一个工作队列。 * 双端队列在工作密取中,每个消费者都有各自的双端队列。如果一个消费者完成了自己双端队列中的全部工作, * 那么它可以从其他消费者双端队列末尾秘密地获取工作。在大多数时候,它们都只是访问自己的双端队列,从而极大的减少了竞争。 * * @author Administrator * */ public class MyDeque { /** * @param args */ public static void main(String[] args) { // Semaphore //信号量 // LinkedBlockingDeque<E> 并发 // ArrayDeque<E> //非并发 } }
928
0.743151
0.743151
27
20.629629
19.953924
63
false
false
0
0
0
0
0
0
0.555556
false
false
13
e9f2c158c1fda454fdb5f30647b051a190e289c7
4,750,233,863,558
be7cfc221e6a98f0ad56c7486ee275298847e6a5
/src/main/java/bi/baiqiu/service/impl/StoreSaleServiceImpl.java
71cfa3ef61ea39a7b9a76ab948c91c2384860a71
[]
no_license
XiLingNote/bi
https://github.com/XiLingNote/bi
3f9baa7c8121765848bc362fab64f40cc4e2e2fe
963b11b8cf99ae3cd9fdd4e546621b323ef5b2bc
refs/heads/master
2021-05-15T04:55:56.580000
2017-12-07T02:14:14
2017-12-07T02:14:14
94,998,080
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package bi.baiqiu.service.impl; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import bi.baiqiu.pojo.RedisPojo; import bi.baiqiu.pojo.SortShop; import bi.baiqiu.pojo.SortShopDrillDown; import bi.baiqiu.service.StoreSaleService; import bi.baiqiu.utils.DateUtils; import bi.baiqiu.utils.GsonUtils; import bi.baiqiu.utils.KeyUtils; import bi.baiqiu.utils.PinYin4jUtils; @SuppressWarnings("all") @Service("storeSaleService") public class StoreSaleServiceImpl implements StoreSaleService { @Autowired private JedisPool jedisPool; @Override public Map<String, Object> queryThisMonth(String amountType, String department) { Map<String, Object> map = new HashMap<String, Object>(); Jedis jedis = jedisPool.getResource(); Set<String> querySet = new HashSet<String>(); // 查询店铺集合 Set<String> storeShorts = new HashSet<String>(); // 所有部门 Set<String> departments = jedis.smembers(KeyUtils.departments); for (String depart : departments) { // 店铺集合 Set<String> stores = jedis.smembers(depart + KeyUtils.EN); storeShorts.addAll(stores); } if (StringUtils.isNotBlank(department)) { if (department.equals(KeyUtils.All)) { querySet = storeShorts; } else { querySet = jedis.smembers(department + KeyUtils.EN); } } else { return null; } Date date = new Date(); String yyyyMM = DateUtils.getyyyyMM(date); // String yyyyMM = "201705"; TreeSet<SortShop> treeSet = new TreeSet<SortShop>(); // 店铺简称 for (String shopName : querySet) { String dataString = jedis.hget(shopName + KeyUtils.MONTH, yyyyMM); String name = null; try { name = URLEncoder.encode(shopName, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); double value; if (amountType.equals("GMV")) { value = redisPojo.getGmv().doubleValue(); } else { value = redisPojo.getAlipay().doubleValue(); } double b = 0.0; if (b == value) { continue; } String pinyin = PinYin4jUtils.hanziToPinyin(shopName, ""); SortShop sortShop = new SortShop(); sortShop.setAmount(value); sortShop.setShopName(name); sortShop.setId(pinyin); treeSet.add(sortShop); } } map.put("set", treeSet); List<SortShopDrillDown> arrayList = new ArrayList<SortShopDrillDown>(); for (String shopName : querySet) { SortShopDrillDown drillDown = new SortShopDrillDown(); String name = null; String id = null; try { name = URLEncoder.encode(shopName, "utf-8"); id = PinYin4jUtils.hanziToPinyin(shopName, ""); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } drillDown.setId(id); drillDown.setShopName(name); List<RedisPojo> redisList = new ArrayList<RedisPojo>(); for (int i = 1; i <= 31; i++) { String yyyyMMdd = (i < 9) ? yyyyMM + "0" + i : yyyyMM + i; String dataString = jedis.hget(shopName + KeyUtils.DAY, yyyyMMdd); if (StringUtils.isNotBlank(dataString)) { RedisPojo fromJson = GsonUtils.gson.fromJson(dataString, RedisPojo.class); redisList.add(fromJson); } } drillDown.setList(redisList); arrayList.add(drillDown); } map.put("arrayList", arrayList); jedisPool.returnResource(jedis); return map; } @Override public Map<String, Object> queryByThisDay(String dateType, Date date, String type) { Map<String, Object> map = new HashMap<String, Object>(); TreeSet<SortShop> treeSet = new TreeSet<SortShop>(); if (date == null) { Date date2 = new Date(); int year = date2.getYear(); int month = date2.getMonth(); int day = date2.getDate(); date = new Date(year, month, day); } String yyyyMMdd = DateUtils.getyyyyMMdd(date); if (KeyUtils.YEAR.equals(dateType)) { yyyyMMdd = DateUtils.getyyyy(date); } else if (KeyUtils.MONTH.equals(dateType)) { yyyyMMdd = DateUtils.getyyyyMM(date); } // redis field // 获取redis客户端 Jedis jedis = jedisPool.getResource(); // 部门集合 Set<String> departments = jedis.smembers(KeyUtils.departments); Set<String> set = new HashSet<String>(); // 获取店铺名称集合 for (String department : departments) { Set<String> store = jedis.smembers(department + KeyUtils.EN); set.addAll(store); } for (String storeName : set) { String dataString = jedis.hget(storeName + dateType, yyyyMMdd); String name = null; try { name = URLEncoder.encode(storeName, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); double value; if (type.equals("GMV")) { value = redisPojo.getGmv().doubleValue(); } else { value = redisPojo.getAlipay().doubleValue(); } double b = 0.0; if (b == value) { continue; } SortShop sortShop = new SortShop(); sortShop.setAmount(value); sortShop.setShopName(name); sortShop.setId(name); treeSet.add(sortShop); } } map.put("set", treeSet); jedisPool.returnResource(jedis); return map; } /** * * 按天查询记录 * * */ @Override public Map<String, Object> getDayOfMonth(String store, Date begin, Date end) { Map<String, Object> map = new HashMap<String, Object>(); Set<RedisPojo> treeSet = new TreeSet<RedisPojo>(); Jedis jedis = jedisPool.getResource(); String name = jedis.get(store); int d = begin.getDate(); int m = begin.getMonth(); int y = begin.getYear(); String getyyyyMMdd = DateUtils.getyyyyMMdd(end); int endtime = Integer.parseInt(getyyyyMMdd); for (int i = d;; i++) { Date date = new Date(y, m, i); String thisdate = DateUtils.getyyyyMMdd(date); int thistime = Integer.parseInt(thisdate); if (endtime < thistime) { break; } /* * if (date.after(end)) { break; } */ String string = jedis.hget(name + KeyUtils.DAY, thisdate); RedisPojo redisPojo ; if (StringUtils.isNotBlank(string)) { redisPojo = GsonUtils.gson.fromJson(string, RedisPojo.class); redisPojo.setAlipayCompleteness(); redisPojo.setCompleteness(); }else{ redisPojo =new RedisPojo(); redisPojo.setDatetime(thisdate); } treeSet.add(redisPojo); } map.put("treeSet", treeSet); jedisPool.returnResource(jedis); return map; } @Override public Map<String, Object> getMonthofYear(String store, Date begin, Date end) { Jedis jedis = jedisPool.getResource(); Map<String, Object> map = new HashMap<String, Object>(); Set<RedisPojo> treeSet = new TreeSet<RedisPojo>(); int y = begin.getYear(); int m = begin.getMonth(); int d = begin.getDate(); String name = jedis.get(store); for (int i = m;; i++) { Date date = new Date(y, i, d); if (date.after(end)) { break; } String string = jedis.hget(name + KeyUtils.MONTH, DateUtils.getyyyyMM(date)); RedisPojo redisPojo ; if (StringUtils.isNotBlank(string)) { redisPojo = GsonUtils.gson.fromJson(string, RedisPojo.class); redisPojo.setAlipayCompleteness(); redisPojo.setCompleteness(); }else{ redisPojo =new RedisPojo(); redisPojo.setDatetime(DateUtils.getyyyyMM(date)); } treeSet.add(redisPojo); } map.put("treeSet", treeSet); jedisPool.returnResource(jedis); return map; } @Override public Map<String, Object> getYear(String store, int y1, int y2) { Map<String, Object> map = new HashMap<String, Object>(); Set<RedisPojo> treeSet = new TreeSet<RedisPojo>(); Jedis jedis = jedisPool.getResource(); String name = jedis.get(store); for (int i = y1; i <= y2; i++) { String string = jedis.hget(name + KeyUtils.YEAR, "" + i); RedisPojo redisPojo ; if (StringUtils.isNotBlank(string)) { redisPojo = GsonUtils.gson.fromJson(string, RedisPojo.class); redisPojo.setAlipayCompleteness(); redisPojo.setCompleteness(); }else{ redisPojo =new RedisPojo(); redisPojo.setDatetime(i+""); } treeSet.add(redisPojo); } map.put("treeSet", treeSet); jedisPool.returnResource(jedis); return map; } @Override public Set<String> queryStoreName() { Jedis jedis = jedisPool.getResource(); Set<String> departNameSet = jedis.smembers(KeyUtils.departments); Set<String> storeNameSet = new HashSet<String>(); for (String departName : departNameSet) { Set<String> shoes = jedis.smembers(departName); storeNameSet.addAll(shoes); } jedisPool.returnResource(jedis); return storeNameSet; } /** * @see bi.baiqiu.service.StoreSaleService#storeSalesDemonstrate(java.lang.String) * @Function: StoreSaleServiceImpl.java * @Description: 该函数的功能描述 3.5.1.1sales 模块 * * @param:参数描述 店铺名称简写对应表 shop : name * @return:返回结果描述 * Yesterday:店铺昨日销售额,MTD_GMV:店铺本月销售额,MTD_Alipay:店铺本月支付宝收账额,GMV_Complection * :店铺本月业绩完成率 的map * 最近31天的日期,GMV,(调用getRecentlyDateAndGmvlistAndGmvavg方法) * @throws:异常描述 * * @version: v1.0.0 * @author: FengCheng * @date: 2017年7月19日 下午1:58:33 * * Modification History: Date Author Version Description * ---------------------------------------------------------* * 2017年7月19日 FengCheng v1.0.0 修改原因 */ @Override public Map<String, Object> storeSalesDemonstrate(String storeName) { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> dateAndGmvlistAndGmvavgMap; double gmv = 0, alipay = 0, gmvTarget, alipayTarget, yesterday_gmv = 0, completeness = 0, alipayCompleteness = 0; Jedis jedis = jedisPool.getResource(); Date date = new Date();// 取当前时间 // int day = date.getDate(); String month = DateUtils.getyyyyMM(date);// 本月 /* * Calendar calendar = new GregorianCalendar(); calendar.setTime(date); * calendar.add(calendar.DATE,-1);//把日期往前增加一天.整数往后推,负数往前移动 * date=calendar.getTime(); //这个时间就是表示昨天 */ String Yesterday = DateUtils.getyyyyMMdd(DateUtils.getYesterday()); String dataString = jedis.hget(storeName + KeyUtils.MONTH, "201705"); if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); gmv = redisPojo.getGmv().doubleValue(); alipay = redisPojo.getAlipay().doubleValue(); gmvTarget = redisPojo.getAlipay().doubleValue(); alipayTarget = redisPojo.getAlipayTarget().doubleValue(); redisPojo.setCompleteness(); redisPojo.setAlipayCompleteness(); completeness = redisPojo.getCompleteness(); alipayCompleteness = redisPojo.getAlipayCompleteness(); } String Yesterday_dataString = jedis.hget(storeName + KeyUtils.DAY, Yesterday); if (StringUtils.isNotBlank(Yesterday_dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(Yesterday_dataString, RedisPojo.class); yesterday_gmv = redisPojo.getGmv().doubleValue(); } map.put("Yesterday_gmv", 123123); // map.put("Yesterday_gmv", yesterday_gmv); map.put("gmv", gmv); map.put("alipay", alipay); map.put("completeness", completeness); map.put("alipayCompleteness", alipayCompleteness); dateAndGmvlistAndGmvavgMap = getRecentlyDateAndGmvlist(storeName); map.putAll(dateAndGmvlistAndGmvavgMap); jedisPool.returnResource(jedis); return map; } /** * @Function: StoreSaleServiceImpl.java * @Description: 该函数的功能描述 获取最近31天的日期,GMV, * * @param:参数描述 店铺名称 * @return:返回结果描述 map * @throws:异常描述 * * @version: v1.0.0 * @author: FengCheng * @date: 2017年7月24日 上午10:33:46 * * Modification History: Date Author Version Description * ---------------------------------------------------------* * 2017年7月24日 FengCheng v1.0.01 修改原因 无需gmvAvg字段 */ @Override public Map<String, Object> getRecentlyDateAndGmvlist(String storeName) { String dataString; double gmvSum = 0; int recent = 31; double gmv; Map<String, Object> map = new HashMap<String, Object>(); Jedis jedis = jedisPool.getResource(); List<String> recentlyDate = DateUtils.getRecentlyDate(recent);// 获取近31天的日期\ List gmvList = new ArrayList(); for (String date : recentlyDate) { dataString = jedis.hget(storeName + KeyUtils.DAY, date); gmv = 0; if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); gmv = redisPojo.getGmv().doubleValue(); } gmvList.add(gmv); gmvSum += gmv; } map.put("recentlyDate", recentlyDate); map.put("gmvlist", gmvList); jedisPool.returnResource(jedis); return map; } }
UTF-8
Java
13,454
java
StoreSaleServiceImpl.java
Java
[ { "context": "@throws:异常描述\n\t *\n\t * @version: v1.0.0\n\t * @author: FengCheng\n\t * @date: 2017年7月19日 下午1:58:33\n\t *\n\t * Mo", "end": 9505, "score": 0.9998507499694824, "start": 9496, "tag": "NAME", "value": "FengCheng" }, { "context": "---------------------------*\n\t * 2017年7月19日 FengCheng v1.0.0 修改原因\n\t */\n\t@Override\n\tpublic Map<String, O", "end": 9708, "score": 0.9990738034248352, "start": 9699, "tag": "NAME", "value": "FengCheng" }, { "context": "@throws:异常描述\n\t *\n\t * @version: v1.0.0\n\t * @author: FengCheng\n\t * @date: 2017年7月24日 上午10:33:46\n\t *\n\t * M", "end": 11912, "score": 0.9998534917831421, "start": 11903, "tag": "NAME", "value": "FengCheng" }, { "context": "---------------------------*\n\t * 2017年7月24日 FengCheng v1.0.01 修改原因 无需gmvAvg字段\n\t */\n\t@Override\n\tpubli", "end": 12113, "score": 0.7956158518791199, "start": 12107, "tag": "NAME", "value": "FengCh" } ]
null
[]
package bi.baiqiu.service.impl; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import bi.baiqiu.pojo.RedisPojo; import bi.baiqiu.pojo.SortShop; import bi.baiqiu.pojo.SortShopDrillDown; import bi.baiqiu.service.StoreSaleService; import bi.baiqiu.utils.DateUtils; import bi.baiqiu.utils.GsonUtils; import bi.baiqiu.utils.KeyUtils; import bi.baiqiu.utils.PinYin4jUtils; @SuppressWarnings("all") @Service("storeSaleService") public class StoreSaleServiceImpl implements StoreSaleService { @Autowired private JedisPool jedisPool; @Override public Map<String, Object> queryThisMonth(String amountType, String department) { Map<String, Object> map = new HashMap<String, Object>(); Jedis jedis = jedisPool.getResource(); Set<String> querySet = new HashSet<String>(); // 查询店铺集合 Set<String> storeShorts = new HashSet<String>(); // 所有部门 Set<String> departments = jedis.smembers(KeyUtils.departments); for (String depart : departments) { // 店铺集合 Set<String> stores = jedis.smembers(depart + KeyUtils.EN); storeShorts.addAll(stores); } if (StringUtils.isNotBlank(department)) { if (department.equals(KeyUtils.All)) { querySet = storeShorts; } else { querySet = jedis.smembers(department + KeyUtils.EN); } } else { return null; } Date date = new Date(); String yyyyMM = DateUtils.getyyyyMM(date); // String yyyyMM = "201705"; TreeSet<SortShop> treeSet = new TreeSet<SortShop>(); // 店铺简称 for (String shopName : querySet) { String dataString = jedis.hget(shopName + KeyUtils.MONTH, yyyyMM); String name = null; try { name = URLEncoder.encode(shopName, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); double value; if (amountType.equals("GMV")) { value = redisPojo.getGmv().doubleValue(); } else { value = redisPojo.getAlipay().doubleValue(); } double b = 0.0; if (b == value) { continue; } String pinyin = PinYin4jUtils.hanziToPinyin(shopName, ""); SortShop sortShop = new SortShop(); sortShop.setAmount(value); sortShop.setShopName(name); sortShop.setId(pinyin); treeSet.add(sortShop); } } map.put("set", treeSet); List<SortShopDrillDown> arrayList = new ArrayList<SortShopDrillDown>(); for (String shopName : querySet) { SortShopDrillDown drillDown = new SortShopDrillDown(); String name = null; String id = null; try { name = URLEncoder.encode(shopName, "utf-8"); id = PinYin4jUtils.hanziToPinyin(shopName, ""); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } drillDown.setId(id); drillDown.setShopName(name); List<RedisPojo> redisList = new ArrayList<RedisPojo>(); for (int i = 1; i <= 31; i++) { String yyyyMMdd = (i < 9) ? yyyyMM + "0" + i : yyyyMM + i; String dataString = jedis.hget(shopName + KeyUtils.DAY, yyyyMMdd); if (StringUtils.isNotBlank(dataString)) { RedisPojo fromJson = GsonUtils.gson.fromJson(dataString, RedisPojo.class); redisList.add(fromJson); } } drillDown.setList(redisList); arrayList.add(drillDown); } map.put("arrayList", arrayList); jedisPool.returnResource(jedis); return map; } @Override public Map<String, Object> queryByThisDay(String dateType, Date date, String type) { Map<String, Object> map = new HashMap<String, Object>(); TreeSet<SortShop> treeSet = new TreeSet<SortShop>(); if (date == null) { Date date2 = new Date(); int year = date2.getYear(); int month = date2.getMonth(); int day = date2.getDate(); date = new Date(year, month, day); } String yyyyMMdd = DateUtils.getyyyyMMdd(date); if (KeyUtils.YEAR.equals(dateType)) { yyyyMMdd = DateUtils.getyyyy(date); } else if (KeyUtils.MONTH.equals(dateType)) { yyyyMMdd = DateUtils.getyyyyMM(date); } // redis field // 获取redis客户端 Jedis jedis = jedisPool.getResource(); // 部门集合 Set<String> departments = jedis.smembers(KeyUtils.departments); Set<String> set = new HashSet<String>(); // 获取店铺名称集合 for (String department : departments) { Set<String> store = jedis.smembers(department + KeyUtils.EN); set.addAll(store); } for (String storeName : set) { String dataString = jedis.hget(storeName + dateType, yyyyMMdd); String name = null; try { name = URLEncoder.encode(storeName, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); double value; if (type.equals("GMV")) { value = redisPojo.getGmv().doubleValue(); } else { value = redisPojo.getAlipay().doubleValue(); } double b = 0.0; if (b == value) { continue; } SortShop sortShop = new SortShop(); sortShop.setAmount(value); sortShop.setShopName(name); sortShop.setId(name); treeSet.add(sortShop); } } map.put("set", treeSet); jedisPool.returnResource(jedis); return map; } /** * * 按天查询记录 * * */ @Override public Map<String, Object> getDayOfMonth(String store, Date begin, Date end) { Map<String, Object> map = new HashMap<String, Object>(); Set<RedisPojo> treeSet = new TreeSet<RedisPojo>(); Jedis jedis = jedisPool.getResource(); String name = jedis.get(store); int d = begin.getDate(); int m = begin.getMonth(); int y = begin.getYear(); String getyyyyMMdd = DateUtils.getyyyyMMdd(end); int endtime = Integer.parseInt(getyyyyMMdd); for (int i = d;; i++) { Date date = new Date(y, m, i); String thisdate = DateUtils.getyyyyMMdd(date); int thistime = Integer.parseInt(thisdate); if (endtime < thistime) { break; } /* * if (date.after(end)) { break; } */ String string = jedis.hget(name + KeyUtils.DAY, thisdate); RedisPojo redisPojo ; if (StringUtils.isNotBlank(string)) { redisPojo = GsonUtils.gson.fromJson(string, RedisPojo.class); redisPojo.setAlipayCompleteness(); redisPojo.setCompleteness(); }else{ redisPojo =new RedisPojo(); redisPojo.setDatetime(thisdate); } treeSet.add(redisPojo); } map.put("treeSet", treeSet); jedisPool.returnResource(jedis); return map; } @Override public Map<String, Object> getMonthofYear(String store, Date begin, Date end) { Jedis jedis = jedisPool.getResource(); Map<String, Object> map = new HashMap<String, Object>(); Set<RedisPojo> treeSet = new TreeSet<RedisPojo>(); int y = begin.getYear(); int m = begin.getMonth(); int d = begin.getDate(); String name = jedis.get(store); for (int i = m;; i++) { Date date = new Date(y, i, d); if (date.after(end)) { break; } String string = jedis.hget(name + KeyUtils.MONTH, DateUtils.getyyyyMM(date)); RedisPojo redisPojo ; if (StringUtils.isNotBlank(string)) { redisPojo = GsonUtils.gson.fromJson(string, RedisPojo.class); redisPojo.setAlipayCompleteness(); redisPojo.setCompleteness(); }else{ redisPojo =new RedisPojo(); redisPojo.setDatetime(DateUtils.getyyyyMM(date)); } treeSet.add(redisPojo); } map.put("treeSet", treeSet); jedisPool.returnResource(jedis); return map; } @Override public Map<String, Object> getYear(String store, int y1, int y2) { Map<String, Object> map = new HashMap<String, Object>(); Set<RedisPojo> treeSet = new TreeSet<RedisPojo>(); Jedis jedis = jedisPool.getResource(); String name = jedis.get(store); for (int i = y1; i <= y2; i++) { String string = jedis.hget(name + KeyUtils.YEAR, "" + i); RedisPojo redisPojo ; if (StringUtils.isNotBlank(string)) { redisPojo = GsonUtils.gson.fromJson(string, RedisPojo.class); redisPojo.setAlipayCompleteness(); redisPojo.setCompleteness(); }else{ redisPojo =new RedisPojo(); redisPojo.setDatetime(i+""); } treeSet.add(redisPojo); } map.put("treeSet", treeSet); jedisPool.returnResource(jedis); return map; } @Override public Set<String> queryStoreName() { Jedis jedis = jedisPool.getResource(); Set<String> departNameSet = jedis.smembers(KeyUtils.departments); Set<String> storeNameSet = new HashSet<String>(); for (String departName : departNameSet) { Set<String> shoes = jedis.smembers(departName); storeNameSet.addAll(shoes); } jedisPool.returnResource(jedis); return storeNameSet; } /** * @see bi.baiqiu.service.StoreSaleService#storeSalesDemonstrate(java.lang.String) * @Function: StoreSaleServiceImpl.java * @Description: 该函数的功能描述 3.5.1.1sales 模块 * * @param:参数描述 店铺名称简写对应表 shop : name * @return:返回结果描述 * Yesterday:店铺昨日销售额,MTD_GMV:店铺本月销售额,MTD_Alipay:店铺本月支付宝收账额,GMV_Complection * :店铺本月业绩完成率 的map * 最近31天的日期,GMV,(调用getRecentlyDateAndGmvlistAndGmvavg方法) * @throws:异常描述 * * @version: v1.0.0 * @author: FengCheng * @date: 2017年7月19日 下午1:58:33 * * Modification History: Date Author Version Description * ---------------------------------------------------------* * 2017年7月19日 FengCheng v1.0.0 修改原因 */ @Override public Map<String, Object> storeSalesDemonstrate(String storeName) { Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> dateAndGmvlistAndGmvavgMap; double gmv = 0, alipay = 0, gmvTarget, alipayTarget, yesterday_gmv = 0, completeness = 0, alipayCompleteness = 0; Jedis jedis = jedisPool.getResource(); Date date = new Date();// 取当前时间 // int day = date.getDate(); String month = DateUtils.getyyyyMM(date);// 本月 /* * Calendar calendar = new GregorianCalendar(); calendar.setTime(date); * calendar.add(calendar.DATE,-1);//把日期往前增加一天.整数往后推,负数往前移动 * date=calendar.getTime(); //这个时间就是表示昨天 */ String Yesterday = DateUtils.getyyyyMMdd(DateUtils.getYesterday()); String dataString = jedis.hget(storeName + KeyUtils.MONTH, "201705"); if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); gmv = redisPojo.getGmv().doubleValue(); alipay = redisPojo.getAlipay().doubleValue(); gmvTarget = redisPojo.getAlipay().doubleValue(); alipayTarget = redisPojo.getAlipayTarget().doubleValue(); redisPojo.setCompleteness(); redisPojo.setAlipayCompleteness(); completeness = redisPojo.getCompleteness(); alipayCompleteness = redisPojo.getAlipayCompleteness(); } String Yesterday_dataString = jedis.hget(storeName + KeyUtils.DAY, Yesterday); if (StringUtils.isNotBlank(Yesterday_dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(Yesterday_dataString, RedisPojo.class); yesterday_gmv = redisPojo.getGmv().doubleValue(); } map.put("Yesterday_gmv", 123123); // map.put("Yesterday_gmv", yesterday_gmv); map.put("gmv", gmv); map.put("alipay", alipay); map.put("completeness", completeness); map.put("alipayCompleteness", alipayCompleteness); dateAndGmvlistAndGmvavgMap = getRecentlyDateAndGmvlist(storeName); map.putAll(dateAndGmvlistAndGmvavgMap); jedisPool.returnResource(jedis); return map; } /** * @Function: StoreSaleServiceImpl.java * @Description: 该函数的功能描述 获取最近31天的日期,GMV, * * @param:参数描述 店铺名称 * @return:返回结果描述 map * @throws:异常描述 * * @version: v1.0.0 * @author: FengCheng * @date: 2017年7月24日 上午10:33:46 * * Modification History: Date Author Version Description * ---------------------------------------------------------* * 2017年7月24日 FengCheng v1.0.01 修改原因 无需gmvAvg字段 */ @Override public Map<String, Object> getRecentlyDateAndGmvlist(String storeName) { String dataString; double gmvSum = 0; int recent = 31; double gmv; Map<String, Object> map = new HashMap<String, Object>(); Jedis jedis = jedisPool.getResource(); List<String> recentlyDate = DateUtils.getRecentlyDate(recent);// 获取近31天的日期\ List gmvList = new ArrayList(); for (String date : recentlyDate) { dataString = jedis.hget(storeName + KeyUtils.DAY, date); gmv = 0; if (StringUtils.isNotBlank(dataString)) { RedisPojo redisPojo = GsonUtils.gson.fromJson(dataString, RedisPojo.class); gmv = redisPojo.getGmv().doubleValue(); } gmvList.add(gmv); gmvSum += gmv; } map.put("recentlyDate", recentlyDate); map.put("gmvlist", gmvList); jedisPool.returnResource(jedis); return map; } }
13,454
0.679997
0.671213
439
28.562643
21.269505
115
false
false
0
0
0
0
0
0
2.892939
false
false
13
c7c1987abe6ff9b7dba0296149928c6a11447049
7,413,113,603,620
58776a250bf4af8a56f56da407d4523764871faa
/src/com/jomaange/model/EntityModel.java
57a558d3c508c1bbe4000fd47b5fd1c1691afb3d
[]
no_license
manjunath317/Jo_Maange_V1.0
https://github.com/manjunath317/Jo_Maange_V1.0
08cdda66224c66224b320c5ca9cff39a8d78368e
396d63d46fdf82e8f8f1e80f0f8e2fe0c927ced6
refs/heads/master
2021-01-01T19:55:44.885000
2015-03-19T08:51:28
2015-03-19T08:51:28
32,379,749
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jomaange.model; import java.io.Serializable; public class EntityModel implements Serializable{ private static final long serialVersionUID = 1L; private String entityId; private String vendor_id; private String isdelivery; private String landline; private String iscorporate; private String address_id; private String team_id; private String mobile; private String addressType; private String street; private String door; private String locality; private String pincode; private String landmark; private String title; private String latitude; private String longitude; private String geotagged; private String imagePath; public EntityModel(){ } public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } public String getVendor_id() { return vendor_id; } public void setVendor_id(String vendor_id) { this.vendor_id = vendor_id; } public String getIsdelivery() { return isdelivery; } public void setIsdelivery(String isdelivery) { this.isdelivery = isdelivery; } public String getLandline() { return landline; } public void setLandline(String landline) { this.landline = landline; } public String getIscorporate() { return iscorporate; } public void setIscorporate(String iscorporate) { this.iscorporate = iscorporate; } public String getAddress_id() { return address_id; } public void setAddress_id(String address_id) { this.address_id = address_id; } public String getTeam_id() { return team_id; } public void setTeam_id(String team_id) { this.team_id = team_id; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getDoor() { return door; } public void setDoor(String door) { this.door = door; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getPincode() { return pincode; } public void setPincode(String pincode) { this.pincode = pincode; } public String getLandmark() { return landmark; } public void setLandmark(String landmark) { this.landmark = landmark; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getGeotagged() { return geotagged; } public void setGeotagged(String geotagged) { this.geotagged = geotagged; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } }
UTF-8
Java
3,167
java
EntityModel.java
Java
[]
null
[]
package com.jomaange.model; import java.io.Serializable; public class EntityModel implements Serializable{ private static final long serialVersionUID = 1L; private String entityId; private String vendor_id; private String isdelivery; private String landline; private String iscorporate; private String address_id; private String team_id; private String mobile; private String addressType; private String street; private String door; private String locality; private String pincode; private String landmark; private String title; private String latitude; private String longitude; private String geotagged; private String imagePath; public EntityModel(){ } public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } public String getVendor_id() { return vendor_id; } public void setVendor_id(String vendor_id) { this.vendor_id = vendor_id; } public String getIsdelivery() { return isdelivery; } public void setIsdelivery(String isdelivery) { this.isdelivery = isdelivery; } public String getLandline() { return landline; } public void setLandline(String landline) { this.landline = landline; } public String getIscorporate() { return iscorporate; } public void setIscorporate(String iscorporate) { this.iscorporate = iscorporate; } public String getAddress_id() { return address_id; } public void setAddress_id(String address_id) { this.address_id = address_id; } public String getTeam_id() { return team_id; } public void setTeam_id(String team_id) { this.team_id = team_id; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getDoor() { return door; } public void setDoor(String door) { this.door = door; } public String getLocality() { return locality; } public void setLocality(String locality) { this.locality = locality; } public String getPincode() { return pincode; } public void setPincode(String pincode) { this.pincode = pincode; } public String getLandmark() { return landmark; } public void setLandmark(String landmark) { this.landmark = landmark; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getGeotagged() { return geotagged; } public void setGeotagged(String geotagged) { this.geotagged = geotagged; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } }
3,167
0.72024
0.719924
185
16.118919
15.44815
49
false
false
0
0
0
0
0
0
1.286487
false
false
13
d874fb5aa6a43923cb94a1e688e88becf3903058
7,413,113,603,921
4690267e7bd5bbf51e95fbf00b7c44407e83420a
/app/src/main/java/com/carelife/infogo/ui/BaseInfoFragment.java
c1dd631795f931288f6704cd400fc779c54a996d
[]
no_license
chenzhu33/InfoGo
https://github.com/chenzhu33/InfoGo
7cd20b8a9ae15aba5c42e13b0775791c9ea7a2d6
349cb58af7daed6a41754a056aad95f997a608bc
refs/heads/master
2021-01-12T17:59:50.268000
2016-10-22T10:09:43
2016-10-22T10:09:43
71,320,212
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.carelife.infogo.ui; import android.support.v4.app.Fragment; public class BaseInfoFragment extends Fragment { }
UTF-8
Java
128
java
BaseInfoFragment.java
Java
[]
null
[]
package com.carelife.infogo.ui; import android.support.v4.app.Fragment; public class BaseInfoFragment extends Fragment { }
128
0.789063
0.78125
9
13.222222
18.896076
48
false
false
0
0
0
0
0
0
0.222222
false
false
13
b03971ee4959ec574d8a16e4477d77eaa9909323
29,119,878,308,197
5b82ce79950e3714bdb8d1f3f7f1998af7975dc6
/apple-cache-ehcache/src/main/java/com/appleframework/cache/ehcache/enums/ExpiryType.java
afefd580ec00dd56c139be77f714edccb2e28946
[ "Apache-2.0" ]
permissive
wangscript007/apple-cache
https://github.com/wangscript007/apple-cache
38e1e3f8e29cb719ef02cc77fd405151e1b7c600
87f162eebfce9927750e3ef83397426f087f0066
refs/heads/master
2023-02-10T03:41:42.298000
2021-01-09T02:50:25
2021-01-09T02:50:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.appleframework.cache.ehcache.enums; public enum ExpiryType { TTI("time to idle"), TTL("time to leave"); ExpiryType(String desc) { this.desc = desc; } private String desc; public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
UTF-8
Java
310
java
ExpiryType.java
Java
[]
null
[]
package com.appleframework.cache.ehcache.enums; public enum ExpiryType { TTI("time to idle"), TTL("time to leave"); ExpiryType(String desc) { this.desc = desc; } private String desc; public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
310
0.66129
0.66129
21
13.761905
13.731801
47
true
false
0
0
0
0
0
0
1.047619
false
false
13
77c00666f8bd3db1a576d9a68bfa830c6e17b941
13,752,485,314,737
90832ef90b03d541a26888a92a3c00e7ee1aec98
/app/src/main/java/com/bits/cloudlib/controlador/ConexionBDRemotaMovilCloudLib.java
bfa476204aa64c736cdbd935ded40e56380e1c28
[]
no_license
albertoadan/CloudLib
https://github.com/albertoadan/CloudLib
fc383bc524f8ee2f85f0336dab86dcdb16b2d77c
3fda7c08a4343ee79d4281c4d3836e7161535651
refs/heads/master
2021-01-19T04:08:43.106000
2016-07-07T22:14:17
2016-07-07T22:14:17
62,841,368
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bits.cloudlib.controlador; /** * Created by Alberto Adán & Rafael Bravo & Víctor Castellanos on 02/04/2016. */ import com.bits.cloudlib.objetos.Biblioteca; import com.bits.cloudlib.objetos.Disponible; import com.bits.cloudlib.objetos.Ejemplar; import com.bits.cloudlib.objetos.FechaHoraConexionUsuario; import com.bits.cloudlib.objetos.Libro; import com.bits.cloudlib.objetos.Prestamo; import com.bits.cloudlib.objetos.Reserva; import com.bits.cloudlib.objetos.Rol; import com.bits.cloudlib.objetos.Sancion; import com.bits.cloudlib.objetos.SancionUsuario; import com.bits.cloudlib.objetos.Seccion; import com.bits.cloudlib.objetos.Usuario; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; /** * Clase que proporciona una conexión con la base de datos y métodos para * introducir, consultar y actualizar los datos en la base de datos * * @author Rafael Bravo Contreras */ public class ConexionBDRemotaMovilCloudLib { // Constantes: valores por defecto private static final String DEFAULT_USUARIO = "cloudlib"; private static final String DEFAULT_PASSWORD = "admin"; private static final String DEFAULT_NOMBRE_BD = "cloudlib"; private static final String DEFAULT_IP = "localhost"; private static final String DEFAULT_PORT = "3306"; // Variable: Conexión con la BD private Connection conexion; // Variables: Datos de conexión private final String usuario, password, nombreBD, ip, port, urlConexion; /** * Constructor sin parámetros * * @throws ConexionBDRemotaCloudLibException */ public ConexionBDRemotaMovilCloudLib() throws ConexionBDRemotaCloudLibException { usuario = DEFAULT_USUARIO; password = DEFAULT_PASSWORD; nombreBD = DEFAULT_NOMBRE_BD; ip = DEFAULT_IP; port = DEFAULT_PORT; urlConexion = getUrlConexion(); conexion = getConexionBDRemotaCloudLib(); } /** * Constructor con parámetros * * @param usuario Usuario de la base de datos del sistema * @param password Password del usuario de la base de datos del sistema * @param nombreBD Nombre de la base de datos del sistema * @param ip IP de conexión con la base de datos del sistema * @param port Puerto de conexión con la base de datos del sistema * * @throws ConexionBDRemotaCloudLibException */ public ConexionBDRemotaMovilCloudLib(String usuario, String password, String nombreBD, String ip, String port) throws ConexionBDRemotaCloudLibException { this.usuario = usuario; this.password = password; this.nombreBD = nombreBD; this.ip = ip; this.port = port; urlConexion = getUrlConexion(); conexion = getConexionBDRemotaCloudLib(); } /** * Método para obtener la conexión con la base de datos * * @author Rafael Bravo Contreras * * @return Objeto Connection * @throws ConexionBDRemotaCloudLibException */ public final Connection getConexionBDRemotaCloudLib() throws ConexionBDRemotaCloudLibException { try { Class.forName("com.mysql.jdbc.Driver"); conexion = (Connection) DriverManager.getConnection(urlConexion, usuario, password); } catch (SQLException | ClassNotFoundException ex) { throw new ConexionBDRemotaCloudLibException(ex.getMessage(), ex); } return conexion; } /** * Método que cierra la conexión con la base de datos * * @throws ConexionBDRemotaCloudLibException */ public void closeConexionBDRemotaCloudLib() throws ConexionBDRemotaCloudLibException { try { conexion.close(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que comprueba si la conexión con la base de datos está cerrada * * @author Rafael Bravo Contreras * * @return true si la conexión está activa o false si no lo está * @throws ConexionBDRemotaCloudLibException */ public boolean isConnectionClosed() { return conexion.isClosed(); } /** * Método que comprueba si el objeto Connection es null * * @author Rafael Bravo Contreras * * @return true si conexion es null, false en caso contrario */ public boolean isConnectionNull() { return conexion == null; } /** * Método que obtiene un listado de objetos Biblioteca * * @author Rafael Bravo Contreras * * @return listado de objetos Biblioteca * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Biblioteca> getAllBiblioteca() throws ConexionBDRemotaCloudLibException { ResultSet rs; Statement st; ArrayList<Biblioteca> listadoBiblioteca; try { //Preparamos la consulta String consulta = "SELECT * FROM biblioteca ORDER BY nombre ASC"; st = (Statement) conexion.createStatement(); //Y ejecutamos rs = st.executeQuery(consulta); //Obtenemos el unico resultado. if (rs.next()) { listadoBiblioteca = new ArrayList<>(); do { Biblioteca biblioteca = new Biblioteca(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)); listadoBiblioteca.add(biblioteca); } while (rs.next()); return listadoBiblioteca; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un libro a partir de un identificador de ejemplar * @author Rafael Bravo Contreras * * @param idEjemplar Identificador de ejemplar * @return objeto Libro * @throws ConexionBDRemotaCloudLibException */ public Libro getLibroPorIdEjemplar(int idEjemplar) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Libro libro; try { //Preparamos la consulta String consulta = "SELECT * FROM libro WHERE _id=(SELECT id_libro FROM ejemplar WHERE _id=?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idEjemplar); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { libro = new Libro(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getString(8)); return libro; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un libro * @author Víctor Castellanos * * @param titulo Titulo del libro * @return objeto Libro * @throws ConexionBDRemotaCloudLibException */ public Libro getLibroByTitulo(String titulo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Libro libro; try { //Preparamos la consulta String consulta = "SELECT * FROM libro WHERE titulo=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, titulo); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { libro = new Libro(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getString(8)); return libro; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene una sección genérica * @author Rafael Bravo Contreras * * @param idLibro Identificador del ejemplar * @return objeto Seccion * @throws ConexionBDRemotaCloudLibException */ public Seccion getSeccionPorIdLibro(int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Seccion seccion; try { //Preparamos la consulta String consulta = "SELECT * FROM seccion WHERE _id=(SELECT id_seccion FROM ejemplar WHERE id_libro=? LIMIT 1) "; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { seccion = new Seccion(rs.getInt(1), rs.getString(2)); return seccion; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene una sección genérica * @author Rafael Bravo Contreras * * @param idEjemplar Identificador del ejemplar * @return objeto Seccion * @throws ConexionBDRemotaCloudLibException */ public Seccion getSeccionPorIdEjemplar(int idEjemplar) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Seccion seccion; try { //Preparamos la consulta String consulta = "SELECT * FROM seccion WHERE _id=(SELECT id_seccion FROM ejemplar WHERE _id=?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idEjemplar); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { seccion = new Seccion(rs.getInt(1), rs.getString(2)); return seccion; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Metodo que obtiene un usuario * * @author Víctor Castellanos Pérez & Rafael Bravo Contreras * * @param email - Email del usuario * @return Objeto Usuario * @throws ConexionBDRemotaCloudLibException */ public Usuario getUsuario(String email) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Usuario usr; try { //Preparamos la consulta String consulta = "SELECT * FROM usuario WHERE email=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, email); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { usr = new Usuario(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getInt(12), rs.getInt(13), rs.getDate(14), rs.getDate(15), rs.getInt(16), rs.getInt(17)); return usr; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Metodo que obtiene un usuario * * @author Víctor Castellanos Pérez & Rafael Bravo Contreras * * @param id - Identificador del usuario * @return Objeto Usuario * @throws ConexionBDRemotaCloudLibException */ public Usuario getUsuario(int id) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Usuario usr; try { //Preparamos la consulta String consulta = "SELECT * FROM usuario WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, id); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { usr = new Usuario(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getInt(12), rs.getInt(13), rs.getDate(14), rs.getDate(15), rs.getInt(16), rs.getInt(17)); return usr; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce un usuario. Incluye la introducción de fecha y hora de * conexión. * * @author Rafael Bravo Contreras * * @param usuario objeto usr * @throws ConexionBDRemotaCloudLibException */ public void putUsuario(Usuario usuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO usuario (nombre, apellidos, dni, direccion, poblacion, " + "codigo_postal, telefono, email, observaciones, password, fecha_alta, rol, id_biblioteca) VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, md5(?), now(), ?, ?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, usuario.getNombre()); ps.setString(2, usuario.getApellidos()); ps.setString(3, usuario.getDni()); ps.setString(4, usuario.getDireccion()); ps.setString(5, usuario.getPoblacion()); ps.setString(6, usuario.getCodigoPostal()); ps.setString(7, usuario.getTelefono()); ps.setString(8, usuario.getEmail()); ps.setString(9, usuario.getObservaciones()); ps.setString(10, usuario.getPassword()); ps.setInt(11, usuario.getRol()); ps.setInt(12, usuario.getIdBiblioteca()); ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que actualiza todos los datos de un usuario * * @author Rafael Bravo Contreras * * @param usuario objeto Usuario * @throws ConexionBDRemotaCloudLibException */ public void updateUsuario(Usuario usuario) throws ConexionBDRemotaCloudLibException { switch (usuario.getId()) { case 1: throw new ConexionBDRemotaCloudLibException("Error: Éste usuario no es modificable"); } PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET nombre=?, apellidos=?, dni=?, direccion=?, poblacion=?, codigo_postal=?, telefono=?, " + "email=?, observaciones=?, contador_bloqueo=?, " + "rol=?, id_biblioteca=? WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, usuario.getNombre()); ps.setString(2, usuario.getApellidos()); ps.setString(3, usuario.getDni()); ps.setString(4, usuario.getDireccion()); ps.setString(5, usuario.getPoblacion()); ps.setString(6, usuario.getCodigoPostal()); ps.setString(7, usuario.getTelefono()); ps.setString(8, usuario.getEmail()); ps.setString(9, usuario.getObservaciones()); ps.setInt(10, usuario.getContadorBloqueo()); ps.setInt(11, usuario.getRol()); ps.setInt(12, usuario.getIdBiblioteca()); ps.setInt(13, usuario.getId()); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + usuario.getId() + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que actualiza el password de un usuario * * @author Rafael Bravo Contreras * * @param idUsuario Identificador del usuario * @param password Password * @throws ConexionBDRemotaCloudLibException */ public void updatePasswordUsuario(int idUsuario, String password) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET password=md5(?) WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, password); ps.setInt(2, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce el número de días de retraso de devoluciones de un * usuario * * @author Rafael Bravo Contreras * * @param idUsuario Identificador del usuario * @param numDias Número de días * @throws ConexionBDRemotaCloudLibException */ public void setDiasRetrasoDevolucionesUsuario(int idUsuario, int numDias) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET dias_retraso_devoluciones=? WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, numDias); ps.setInt(2, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id= " + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que incrementa el contador de bloqueo de un usuario * * @author Víctor Castellanos Pérez & Rafael Bravo Contreras * * @param idUsuario Identificador del usuario. * @throws ConexionBDRemotaCloudLibException */ public void incrementContadorBloqueoUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET contador_bloqueo=contador_bloqueo+1 WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que resetea a 0 el contador de bloqueo de un usuario * * @author Víctor Castellanos Pérez & Rafael Bravo Contreras * * @param idUsuario Identificador del usuario. * @throws ConexionBDRemotaCloudLibException */ public void resetContadorBloqueoUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET contador_bloqueo=0 WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que gestiona los cambios necesarios en la base de datos para dar * de baja a un usuario * * @author Rafael Bravo Contreras * * @param idUsuario Identificador del usuario * @throws ConexionBDRemotaCloudLibException */ public void setBajaUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET fecha_baja=now(), rol=3 WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene la fecha y hora más reciente de conexión de un usuario * * @author Rafael Bravo Contreras * * @param idUsuario identificador de usuario * @return objeto FechaHoraConexionUsuario * @throws ConexionBDRemotaCloudLibException */ public FechaHoraConexionUsuario getFechaHoraConexionUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; FechaHoraConexionUsuario fechaHoraConexionUsuario; try { //Preparamos la consulta String consulta = "SELECT _id, max(fecha_hora_conexion), id_usuario FROM fecha_hora_conexion_usuario " + "WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { fechaHoraConexionUsuario = new FechaHoraConexionUsuario(rs.getInt(1), rs.getDate(2), rs.getInt(3)); return fechaHoraConexionUsuario; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce la fecha y hora de conexión de un usuario * * @author Rafael Bravo Contreras * * @param usuario Objeto usuario * @throws ConexionBDRemotaCloudLibException */ public void putFechaHoraConexionUsuario(Usuario usuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO fecha_hora_conexion_usuario (fecha_hora_conexion, id_usuario) " + "VALUES (now(), (SELECT _id FROM usuario WHERE email=?))"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, usuario.getEmail()); ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce la fecha y hora de conexión de un usuario. * * @author Rafael Bravo Contreras * * @param idUsuario Identificador del usuario * @throws ConexionBDRemotaCloudLibException */ public void putFechaHoraConexionUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO fecha_hora_conexion_usuario (fecha_hora_conexion, id_usuario) " + "VALUES (now(), ?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un rol * * @author Rafael Bravo Contreras * * @param tipo el tipo de rol * @return objeto Rol * @throws ConexionBDRemotaCloudLibException */ public Rol getRol(int tipo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Rol rol; try { //Preparamos la consulta String consulta = "SELECT * FROM rol WHERE tipo=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, tipo); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { rol = new Rol(rs.getInt(1), rs.getInt(2), rs.getString(3)); return rol; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un rol * * @author Rafael Bravo Contreras * * @param descripcion la descripcion o nombre del rol * @return objeto Rol * @throws ConexionBDRemotaCloudLibException */ public Rol getRol(String descripcion) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Rol rol; try { //Preparamos la consulta String consulta = "SELECT * FROM rol WHERE descripcion=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, descripcion); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { rol = new Rol(rs.getInt(1), rs.getInt(2), rs.getString(3)); return rol; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de roles * * @author Rafael Bravo Contreras * * @return listado de objetos Rol * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Rol> getAllRol() throws ConexionBDRemotaCloudLibException { ResultSet rs; Statement st; ArrayList<Rol> listadoRol; try { //Preparamos la consulta String consulta = "SELECT * FROM rol ORDER BY descripcion ASC"; st = (Statement) conexion.createStatement(); //Y ejecutamos rs = st.executeQuery(consulta); //Obtenemos el unico resultado. if (rs.next()) { listadoRol = new ArrayList<>(); do { Rol rol = new Rol(rs.getInt(1), rs.getInt(2), rs.getString(3)); listadoRol.add(rol); } while (rs.next()); return listadoRol; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado préstamos de un usuario * * @author Rafael Bravo Contreras * * @param idUsuario Identificador del usuario * @return objeto Prestamo * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Prestamo> getPrestamosUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Prestamo> listadoPrestamos; try { //Preparamos la consulta String consulta = "SELECT * FROM prestamo WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoPrestamos = new ArrayList<>(); do { Prestamo prestamo = new Prestamo(rs.getInt(1), rs.getDate(2), rs.getDate(3), rs.getDate(4), rs.getString(5), rs.getInt(6), rs.getInt(7), rs.getInt(8)); listadoPrestamos.add(prestamo); } while (rs.next()); return listadoPrestamos; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } // return listadoPrestamos; } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de reservas de un usuario * * @author Rafael Bravo Contreras * * @param idUsuario Identificador del usuario al que pertenecen las reseras * @return listado de objetos Reserva * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Reserva> getReservasUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Reserva> listadoReservas; try { //Preparamos la consulta String consulta = "SELECT * FROM reserva WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); if (rs.next()) { listadoReservas = new ArrayList<>(); do { Reserva reserva = new Reserva(rs.getInt(1), rs.getDate(2), rs.getDate(3), rs.getString(4), rs.getInt(5), rs.getInt(6), rs.getInt(7)); listadoReservas.add(reserva); } while (rs.next()); return listadoReservas; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce una reserva * * @author Rafael Bravo Contreras * * @param reserva objeto Reserva * @throws ConexionBDRemotaCloudLibException */ public void putReserva(Reserva reserva) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO reserva (fecha_reserva, fecha_caducidad, observaciones, estado, " + "id_ejemplar, id_usuario) VALUES (now(), ?, ?, ?, ?, ?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, getFechaHoraFormatoBD(reserva.getFechaCaducidad())); ps.setString(2, reserva.getObservaciones()); ps.setInt(3, reserva.getEstado()); ps.setInt(4, reserva.getIdEjemplar()); ps.setInt(5, reserva.getIdUsuario()); ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que actualiza los datos de una reserva * * @author Rafael Bravo Contreras * * @param reserva objeto Reserva * @throws ConexionBDRemotaCloudLibException */ public void updateReserva(Reserva reserva) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE reserva SET fecha_reserva=?, fecha_caducidad=?, observaciones=?, " + "estado=?, id_ejemplar=?, id_usuario=? WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, getFechaHoraFormatoBD(reserva.getFechaReserva())); ps.setString(2, getFechaHoraFormatoBD(reserva.getFechaCaducidad())); ps.setString(3, reserva.getObservaciones()); ps.setInt(4, reserva.getEstado()); ps.setInt(5, reserva.getIdEjemplar()); ps.setInt(6, reserva.getIdUsuario()); ps.setInt(7, reserva.getId()); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + reserva.getId() + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de sanciones * * @author Rafael Bravo Contreras * * @return listado de objetos Sancion * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Sancion> getAllSancion() throws ConexionBDRemotaCloudLibException { ResultSet rs; Statement st; ArrayList<Sancion> listadoSancion; try { //Preparamos la consulta String consulta = "SELECT * FROM sancion ORDER BY descripcion ASC"; st = (Statement) conexion.createStatement(); //Y ejecutamos rs = st.executeQuery(consulta); //Obtenemos el unico resultado. if (rs.next()) { listadoSancion = new ArrayList<>(); do { Sancion sancion = new Sancion(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getInt(4), rs.getInt(5)); listadoSancion.add(sancion); } while (rs.next()); return listadoSancion; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene todas las sanciones de un usuario * * @author Rafael Bravo Contreras * * @param idUsuario identificador del usuario * @return listado de sanciones de un usuario * @throws ConexionBDRemotaCloudLibException */ public ArrayList<SancionUsuario> getSancionesUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<SancionUsuario> listadoSancionesUsuario; try { //Preparamos la consulta String consulta = "SELECT * FROM sancion_usuario WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoSancionesUsuario = new ArrayList<>(); do { SancionUsuario sancionUsuario = new SancionUsuario(rs.getInt(1), rs.getDate(2), rs.getDate(3), rs.getInt(4), rs.getInt(5)); listadoSancionesUsuario.add(sancionUsuario); } while (rs.next()); return listadoSancionesUsuario; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que construye la url de conexión con la base de datos a partir de * las variables de la clase * * @author Rafael Bravo Contreras * * @return URL de conexión con la base de datos */ private String getUrlConexion() { StringBuilder builder = new StringBuilder(); builder.append("jdbc:mysql://"); builder.append(this.ip); builder.append(":"); builder.append(this.port); builder.append("/"); builder.append(this.nombreBD); return builder.toString(); } /** * Método que obtiene una hora y fecha en formato 'agradable' para la base * de datos * * @author Rafael Bravo Contreras * * @param fecha fecha * @return texto con la fecha */ private String getFechaHoraFormatoBD(Date fecha) { String formato = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat formatData = new SimpleDateFormat(formato, Locale.ROOT); String fechaConFormato = formatData.format(fecha); return fechaConFormato; } /** * Método que obtiene un listado de ejemplares disponibles del título solicitado * @author Rafael Bravo Contreras * * @param titulo Título solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorTitulo(String titulo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where titulo LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, titulo); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles relacionados con el título solicitado * @author Rafael Bravo Contreras * * @param titulo Título solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesRelacionadosPorTitulo(String titulo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where titulo LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. String tituloParecido = "%" + titulo + "%"; ps.setString(1, tituloParecido); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles del autor solicitado * @author Rafael Bravo Contreras * * @param autor Autor solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorAutor(String autor) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where autor LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, autor); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles relacionados con el autor solicitado * @author Rafael Bravo Contreras * * @param autor Autor solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesRelacionadosPorAutor(String autor) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where autor LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. String autorParecido = "%" + autor + "%"; ps.setString(1, autorParecido); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles de la editorial solicitada * @author Rafael Bravo Contreras * * @param editorial Editorial solicitada * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorEditorial(String editorial) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where editorial LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, editorial); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles de la editorial solicitada * @author Rafael Bravo Contreras * * @param editorial Editorial solicitada * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesRelacionadosPorEditorial(String editorial) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where editorial LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. String editorialParecida = "%" + editorial + "%"; ps.setString(1, editorialParecida); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles del isbn solicitado * @author Rafael Bravo Contreras * * @param isbn Isbn solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorIsbn(String isbn) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro=(select _id from libro where isbn LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, isbn); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles * @author Rafael Bravo Contreras * * @param idBiblioteca Identificador de la biblioteca * @param idLibro Identificador del libro * @return Listado de objetos Ejemplar * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Ejemplar> getEjemplaresDisponibles(int idBiblioteca, int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Ejemplar> listadoEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select * from ejemplar where id_biblioteca=? and id_libro=? and estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idBiblioteca); ps.setInt(2, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoEjemplaresDisponibles = new ArrayList<>(); do { Ejemplar ejemplar = new Ejemplar(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)); listadoEjemplaresDisponibles.add(ejemplar); } while (rs.next()); return listadoEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un objeto Ejemplar * * @author Rafael Bravo Contreras * * @param idEjemplar identificador de ejemplar * @return objeto Ejemplar * @throws ConexionBDRemotaCloudLibException */ public Ejemplar getEjemplar(int idEjemplar) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Ejemplar ejemplar; try { //Preparamos la consulta String consulta = "SELECT * FROM ejemplar WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idEjemplar); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { ejemplar = new Ejemplar(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)); return ejemplar; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares * @author Rafael Bravo Contreras * * @param idLibro Identificador del libro al que pertenecen * @return listado de objetos Ejemplar * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Ejemplar> getEjemplares(int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Ejemplar> listadoEjemplar; try { //Preparamos la consulta String consulta = "SELECT * FROM ejemplar WHERE id_libro=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoEjemplar = new ArrayList<>(); do { Ejemplar ejemplar = new Ejemplar(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)); listadoEjemplar.add(ejemplar); } while (rs.next()); return listadoEjemplar; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un libro * * @author Rafael Bravo Contreras * * @param idLibro identificador del libro * @return objeto Libro * @throws ConexionBDRemotaCloudLibException */ public Libro getLibro(int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Libro libro; try { //Preparamos la consulta String consulta = "SELECT * FROM libro WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { libro = new Libro(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getString(8)); return libro; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } }
UTF-8
Java
60,540
java
ConexionBDRemotaMovilCloudLib.java
Java
[ { "context": " com.bits.cloudlib.controlador;\n\n/**\n * Created by Alberto Adán & Rafael Bravo & Víctor Castellanos on 02/04/2016", "end": 70, "score": 0.9998763799667358, "start": 58, "tag": "NAME", "value": "Alberto Adán" }, { "context": "lib.controlador;\n\n/**\n * Created by Alberto Adán & Rafael Bravo & Víctor Castellanos on 02/04/2016.\n */\nimport co", "end": 85, "score": 0.9998776316642761, "start": 73, "tag": "NAME", "value": "Rafael Bravo" }, { "context": ";\n\n/**\n * Created by Alberto Adán & Rafael Bravo & Víctor Castellanos on 02/04/2016.\n */\nimport com.bits.cloudlib.objet", "end": 106, "score": 0.999879002571106, "start": 88, "tag": "NAME", "value": "Víctor Castellanos" }, { "context": "alizar los datos en la base de datos\n *\n * @author Rafael Bravo Contreras\n */\npublic class ConexionBDRemotaMovilCloudLib {\n", "end": 1147, "score": 0.9998733401298523, "start": 1125, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": " private static final String DEFAULT_PASSWORD = \"admin\";\n private static final String DEFAULT_NOMBRE_", "end": 1356, "score": 0.9994857907295227, "start": 1351, "tag": "PASSWORD", "value": "admin" }, { "context": " usuario = DEFAULT_USUARIO;\n password = DEFAULT_PASSWORD;\n nombreBD = DEFAULT_NOMBRE_BD;\n ip", "end": 1983, "score": 0.9882078170776367, "start": 1967, "tag": "PASSWORD", "value": "DEFAULT_PASSWORD" }, { "context": " this.usuario = usuario;\n this.password = password;\n this.nombreBD = nombreBD;\n this.i", "end": 2857, "score": 0.9993712306022644, "start": 2849, "tag": "PASSWORD", "value": "password" }, { "context": "onexión con la base de datos\n *\n * @author Rafael Bravo Contreras\n *\n * @return Objeto Connection\n * @t", "end": 3150, "score": 0.9998544454574585, "start": 3128, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "a base de datos está cerrada\n *\n * @author Rafael Bravo Contreras\n *\n * @return true si la conexión está ac", "end": 4226, "score": 0.9998920559883118, "start": 4204, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "el objeto Connection es null\n *\n * @author Rafael Bravo Contreras\n *\n * @return true si conexion es null, f", "end": 4557, "score": 0.9998906254768372, "start": 4535, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "istado de objetos Biblioteca\n *\n * @author Rafael Bravo Contreras\n *\n * @return listado de objetos Bibliote", "end": 4829, "score": 0.9998897910118103, "start": 4807, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "tir de un identificador de ejemplar\n * @author Rafael Bravo Contreras\n *\n * @param idEjemplar Identificador de ", "end": 6209, "score": 0.9998880624771118, "start": 6187, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "\n * Método que obtiene un libro\n * @author Víctor Castellanos\n *\n * @param titulo Titulo del libro\n ", "end": 7520, "score": 0.9998956322669983, "start": 7502, "tag": "NAME", "value": "Víctor Castellanos" }, { "context": "do que obtiene una sección genérica\n * @author Rafael Bravo Contreras\n *\n * @param idLibro Identificador del ej", "end": 8788, "score": 0.9998788833618164, "start": 8766, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "do que obtiene una sección genérica\n * @author Rafael Bravo Contreras\n *\n * @param idEjemplar Identificador del", "end": 10014, "score": 0.9998784065246582, "start": 9992, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "etodo que obtiene un usuario\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param ema", "end": 11237, "score": 0.9998873472213745, "start": 11213, "tag": "NAME", "value": "Víctor Castellanos Pérez" }, { "context": "o\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param email - Email del usuario\n ", "end": 11262, "score": 0.999885618686676, "start": 11240, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "etodo que obtiene un usuario\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param id ", "end": 12722, "score": 0.9998847842216492, "start": 12698, "tag": "NAME", "value": "Víctor Castellanos Pérez" }, { "context": "o\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param id - Identificador del usuar", "end": 12747, "score": 0.9998763203620911, "start": 12725, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "a y hora de\n * conexión.\n *\n * @author Rafael Bravo Contreras\n *\n * @param usuario objeto usr\n * @t", "end": 14259, "score": 0.9998777508735657, "start": 14237, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "odos los datos de un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param usuario objeto Usuario\n ", "end": 15851, "score": 0.9998311996459961, "start": 15829, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "za el password de un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 17870, "score": 0.9998782873153687, "start": 17848, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "o Identificador del usuario\n * @param password Password\n * @throws ConexionBDRemotaCloudLibException\n", "end": 17959, "score": 0.5644017457962036, "start": 17951, "tag": "PASSWORD", "value": "Password" }, { "context": "uciones de un\n * usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 19040, "score": 0.9998798370361328, "start": 19018, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "dor de bloqueo de un usuario\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param idU", "end": 20206, "score": 0.9998865127563477, "start": 20182, "tag": "NAME", "value": "Víctor Castellanos Pérez" }, { "context": "o\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 20231, "score": 0.9998794794082642, "start": 20209, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "dor de bloqueo de un usuario\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param idU", "end": 21319, "score": 0.9998863339424133, "start": 21295, "tag": "NAME", "value": "Víctor Castellanos Pérez" }, { "context": "o\n *\n * @author Víctor Castellanos Pérez & Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 21344, "score": 0.9998864531517029, "start": 21322, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "\n * de baja a un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 22449, "score": 0.9998888373374939, "start": 22427, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "te de conexión de un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario identificador de u", "end": 23519, "score": 0.9998811483383179, "start": 23497, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "ra de conexión de un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param usuario Objeto usuario\n ", "end": 24976, "score": 0.9998832941055298, "start": 24954, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "a de conexión de un usuario.\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 25921, "score": 0.9998880624771118, "start": 25899, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": " * Método que obtiene un rol\n *\n * @author Rafael Bravo Contreras\n *\n * @param tipo el tipo de rol\n * @", "end": 26809, "score": 0.9998857378959656, "start": 26787, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": " * Método que obtiene un rol\n *\n * @author Rafael Bravo Contreras\n *\n * @param descripcion la descripcion o", "end": 27919, "score": 0.9998906254768372, "start": 27897, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": " obtiene un listado de roles\n *\n * @author Rafael Bravo Contreras\n *\n * @return listado de objetos Rol\n ", "end": 29093, "score": 0.9998866319656372, "start": 29071, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "tado préstamos de un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 30333, "score": 0.9998696446418762, "start": 30311, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "do de reservas de un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario Identificador del ", "end": 31914, "score": 0.9998756647109985, "start": 31892, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "do que introduce una reserva\n *\n * @author Rafael Bravo Contreras\n *\n * @param reserva objeto Reserva\n ", "end": 33402, "score": 0.9998802542686462, "start": 33380, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "iza los datos de una reserva\n *\n * @author Rafael Bravo Contreras\n *\n * @param reserva objeto Reserva\n ", "end": 34550, "score": 0.9998713731765747, "start": 34528, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "iene un listado de sanciones\n *\n * @author Rafael Bravo Contreras\n *\n * @return listado de objetos Sancion\n", "end": 36046, "score": 0.9998850226402283, "start": 36024, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": " las sanciones de un usuario\n *\n * @author Rafael Bravo Contreras\n *\n * @param idUsuario identificador del ", "end": 37393, "score": 0.9998893141746521, "start": 37371, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": " * las variables de la clase\n *\n * @author Rafael Bravo Contreras\n *\n * @return URL de conexión con la base", "end": 39027, "score": 0.9998930096626282, "start": 39005, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "para la base\n * de datos\n *\n * @author Rafael Bravo Contreras\n *\n * @param fecha fecha\n * @return t", "end": 39582, "score": 0.9998931288719177, "start": 39560, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "s disponibles del título solicitado\n * @author Rafael Bravo Contreras\n *\n * @param titulo Título solicitado\n ", "end": 40073, "score": 0.9998930096626282, "start": 40051, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "lacionados con el título solicitado\n * @author Rafael Bravo Contreras\n *\n * @param titulo Título solicitado\n ", "end": 42164, "score": 0.9998254776000977, "start": 42142, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "es disponibles del autor solicitado\n * @author Rafael Bravo Contreras\n *\n * @param autor Autor solicitado\n ", "end": 44314, "score": 0.9998430609703064, "start": 44292, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "elacionados con el autor solicitado\n * @author Rafael Bravo Contreras\n *\n * @param autor Autor solicitado\n ", "end": 46398, "score": 0.9991821050643921, "start": 46376, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "ponibles de la editorial solicitada\n * @author Rafael Bravo Contreras\n *\n * @param editorial Editorial solicita", "end": 48546, "score": 0.9996494054794312, "start": 48524, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "ponibles de la editorial solicitada\n * @author Rafael Bravo Contreras\n *\n * @param editorial Editorial solicita", "end": 50644, "score": 0.9998199343681335, "start": 50622, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "res disponibles del isbn solicitado\n * @author Rafael Bravo Contreras\n *\n * @param isbn Isbn solicitado\n * ", "end": 52817, "score": 0.9998771548271179, "start": 52795, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "n listado de ejemplares disponibles\n * @author Rafael Bravo Contreras\n *\n * @param idBiblioteca Identificador d", "end": 54853, "score": 0.9998860955238342, "start": 54831, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "e obtiene un objeto Ejemplar\n *\n * @author Rafael Bravo Contreras\n *\n * @param idEjemplar identificador de ", "end": 56528, "score": 0.999882698059082, "start": 56506, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": "ue obtiene un listado de ejemplares\n * @author Rafael Bravo Contreras\n *\n * @param idLibro Identificador del li", "end": 57771, "score": 0.9998490214347839, "start": 57749, "tag": "NAME", "value": "Rafael Bravo Contreras" }, { "context": " Método que obtiene un libro\n *\n * @author Rafael Bravo Contreras\n *\n * @param idLibro identificador del li", "end": 59247, "score": 0.9998658299446106, "start": 59225, "tag": "NAME", "value": "Rafael Bravo Contreras" } ]
null
[]
package com.bits.cloudlib.controlador; /** * Created by <NAME> & <NAME> & <NAME> on 02/04/2016. */ import com.bits.cloudlib.objetos.Biblioteca; import com.bits.cloudlib.objetos.Disponible; import com.bits.cloudlib.objetos.Ejemplar; import com.bits.cloudlib.objetos.FechaHoraConexionUsuario; import com.bits.cloudlib.objetos.Libro; import com.bits.cloudlib.objetos.Prestamo; import com.bits.cloudlib.objetos.Reserva; import com.bits.cloudlib.objetos.Rol; import com.bits.cloudlib.objetos.Sancion; import com.bits.cloudlib.objetos.SancionUsuario; import com.bits.cloudlib.objetos.Seccion; import com.bits.cloudlib.objetos.Usuario; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; /** * Clase que proporciona una conexión con la base de datos y métodos para * introducir, consultar y actualizar los datos en la base de datos * * @author <NAME> */ public class ConexionBDRemotaMovilCloudLib { // Constantes: valores por defecto private static final String DEFAULT_USUARIO = "cloudlib"; private static final String DEFAULT_PASSWORD = "<PASSWORD>"; private static final String DEFAULT_NOMBRE_BD = "cloudlib"; private static final String DEFAULT_IP = "localhost"; private static final String DEFAULT_PORT = "3306"; // Variable: Conexión con la BD private Connection conexion; // Variables: Datos de conexión private final String usuario, password, nombreBD, ip, port, urlConexion; /** * Constructor sin parámetros * * @throws ConexionBDRemotaCloudLibException */ public ConexionBDRemotaMovilCloudLib() throws ConexionBDRemotaCloudLibException { usuario = DEFAULT_USUARIO; password = <PASSWORD>; nombreBD = DEFAULT_NOMBRE_BD; ip = DEFAULT_IP; port = DEFAULT_PORT; urlConexion = getUrlConexion(); conexion = getConexionBDRemotaCloudLib(); } /** * Constructor con parámetros * * @param usuario Usuario de la base de datos del sistema * @param password Password del usuario de la base de datos del sistema * @param nombreBD Nombre de la base de datos del sistema * @param ip IP de conexión con la base de datos del sistema * @param port Puerto de conexión con la base de datos del sistema * * @throws ConexionBDRemotaCloudLibException */ public ConexionBDRemotaMovilCloudLib(String usuario, String password, String nombreBD, String ip, String port) throws ConexionBDRemotaCloudLibException { this.usuario = usuario; this.password = <PASSWORD>; this.nombreBD = nombreBD; this.ip = ip; this.port = port; urlConexion = getUrlConexion(); conexion = getConexionBDRemotaCloudLib(); } /** * Método para obtener la conexión con la base de datos * * @author <NAME> * * @return Objeto Connection * @throws ConexionBDRemotaCloudLibException */ public final Connection getConexionBDRemotaCloudLib() throws ConexionBDRemotaCloudLibException { try { Class.forName("com.mysql.jdbc.Driver"); conexion = (Connection) DriverManager.getConnection(urlConexion, usuario, password); } catch (SQLException | ClassNotFoundException ex) { throw new ConexionBDRemotaCloudLibException(ex.getMessage(), ex); } return conexion; } /** * Método que cierra la conexión con la base de datos * * @throws ConexionBDRemotaCloudLibException */ public void closeConexionBDRemotaCloudLib() throws ConexionBDRemotaCloudLibException { try { conexion.close(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que comprueba si la conexión con la base de datos está cerrada * * @author <NAME> * * @return true si la conexión está activa o false si no lo está * @throws ConexionBDRemotaCloudLibException */ public boolean isConnectionClosed() { return conexion.isClosed(); } /** * Método que comprueba si el objeto Connection es null * * @author <NAME> * * @return true si conexion es null, false en caso contrario */ public boolean isConnectionNull() { return conexion == null; } /** * Método que obtiene un listado de objetos Biblioteca * * @author <NAME> * * @return listado de objetos Biblioteca * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Biblioteca> getAllBiblioteca() throws ConexionBDRemotaCloudLibException { ResultSet rs; Statement st; ArrayList<Biblioteca> listadoBiblioteca; try { //Preparamos la consulta String consulta = "SELECT * FROM biblioteca ORDER BY nombre ASC"; st = (Statement) conexion.createStatement(); //Y ejecutamos rs = st.executeQuery(consulta); //Obtenemos el unico resultado. if (rs.next()) { listadoBiblioteca = new ArrayList<>(); do { Biblioteca biblioteca = new Biblioteca(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)); listadoBiblioteca.add(biblioteca); } while (rs.next()); return listadoBiblioteca; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un libro a partir de un identificador de ejemplar * @author <NAME> * * @param idEjemplar Identificador de ejemplar * @return objeto Libro * @throws ConexionBDRemotaCloudLibException */ public Libro getLibroPorIdEjemplar(int idEjemplar) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Libro libro; try { //Preparamos la consulta String consulta = "SELECT * FROM libro WHERE _id=(SELECT id_libro FROM ejemplar WHERE _id=?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idEjemplar); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { libro = new Libro(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getString(8)); return libro; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un libro * @author <NAME> * * @param titulo Titulo del libro * @return objeto Libro * @throws ConexionBDRemotaCloudLibException */ public Libro getLibroByTitulo(String titulo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Libro libro; try { //Preparamos la consulta String consulta = "SELECT * FROM libro WHERE titulo=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, titulo); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { libro = new Libro(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getString(8)); return libro; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene una sección genérica * @author <NAME> * * @param idLibro Identificador del ejemplar * @return objeto Seccion * @throws ConexionBDRemotaCloudLibException */ public Seccion getSeccionPorIdLibro(int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Seccion seccion; try { //Preparamos la consulta String consulta = "SELECT * FROM seccion WHERE _id=(SELECT id_seccion FROM ejemplar WHERE id_libro=? LIMIT 1) "; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { seccion = new Seccion(rs.getInt(1), rs.getString(2)); return seccion; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene una sección genérica * @author <NAME> * * @param idEjemplar Identificador del ejemplar * @return objeto Seccion * @throws ConexionBDRemotaCloudLibException */ public Seccion getSeccionPorIdEjemplar(int idEjemplar) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Seccion seccion; try { //Preparamos la consulta String consulta = "SELECT * FROM seccion WHERE _id=(SELECT id_seccion FROM ejemplar WHERE _id=?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idEjemplar); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { seccion = new Seccion(rs.getInt(1), rs.getString(2)); return seccion; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Metodo que obtiene un usuario * * @author <NAME> & <NAME> * * @param email - Email del usuario * @return Objeto Usuario * @throws ConexionBDRemotaCloudLibException */ public Usuario getUsuario(String email) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Usuario usr; try { //Preparamos la consulta String consulta = "SELECT * FROM usuario WHERE email=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, email); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { usr = new Usuario(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getInt(12), rs.getInt(13), rs.getDate(14), rs.getDate(15), rs.getInt(16), rs.getInt(17)); return usr; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Metodo que obtiene un usuario * * @author <NAME> & <NAME> * * @param id - Identificador del usuario * @return Objeto Usuario * @throws ConexionBDRemotaCloudLibException */ public Usuario getUsuario(int id) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Usuario usr; try { //Preparamos la consulta String consulta = "SELECT * FROM usuario WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, id); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { usr = new Usuario(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getString(9), rs.getString(10), rs.getString(11), rs.getInt(12), rs.getInt(13), rs.getDate(14), rs.getDate(15), rs.getInt(16), rs.getInt(17)); return usr; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce un usuario. Incluye la introducción de fecha y hora de * conexión. * * @author <NAME> * * @param usuario objeto usr * @throws ConexionBDRemotaCloudLibException */ public void putUsuario(Usuario usuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO usuario (nombre, apellidos, dni, direccion, poblacion, " + "codigo_postal, telefono, email, observaciones, password, fecha_alta, rol, id_biblioteca) VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?, ?, md5(?), now(), ?, ?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, usuario.getNombre()); ps.setString(2, usuario.getApellidos()); ps.setString(3, usuario.getDni()); ps.setString(4, usuario.getDireccion()); ps.setString(5, usuario.getPoblacion()); ps.setString(6, usuario.getCodigoPostal()); ps.setString(7, usuario.getTelefono()); ps.setString(8, usuario.getEmail()); ps.setString(9, usuario.getObservaciones()); ps.setString(10, usuario.getPassword()); ps.setInt(11, usuario.getRol()); ps.setInt(12, usuario.getIdBiblioteca()); ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que actualiza todos los datos de un usuario * * @author <NAME> * * @param usuario objeto Usuario * @throws ConexionBDRemotaCloudLibException */ public void updateUsuario(Usuario usuario) throws ConexionBDRemotaCloudLibException { switch (usuario.getId()) { case 1: throw new ConexionBDRemotaCloudLibException("Error: Éste usuario no es modificable"); } PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET nombre=?, apellidos=?, dni=?, direccion=?, poblacion=?, codigo_postal=?, telefono=?, " + "email=?, observaciones=?, contador_bloqueo=?, " + "rol=?, id_biblioteca=? WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, usuario.getNombre()); ps.setString(2, usuario.getApellidos()); ps.setString(3, usuario.getDni()); ps.setString(4, usuario.getDireccion()); ps.setString(5, usuario.getPoblacion()); ps.setString(6, usuario.getCodigoPostal()); ps.setString(7, usuario.getTelefono()); ps.setString(8, usuario.getEmail()); ps.setString(9, usuario.getObservaciones()); ps.setInt(10, usuario.getContadorBloqueo()); ps.setInt(11, usuario.getRol()); ps.setInt(12, usuario.getIdBiblioteca()); ps.setInt(13, usuario.getId()); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + usuario.getId() + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que actualiza el password de un usuario * * @author <NAME> * * @param idUsuario Identificador del usuario * @param password <PASSWORD> * @throws ConexionBDRemotaCloudLibException */ public void updatePasswordUsuario(int idUsuario, String password) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET password=md5(?) WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, password); ps.setInt(2, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce el número de días de retraso de devoluciones de un * usuario * * @author <NAME> * * @param idUsuario Identificador del usuario * @param numDias Número de días * @throws ConexionBDRemotaCloudLibException */ public void setDiasRetrasoDevolucionesUsuario(int idUsuario, int numDias) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET dias_retraso_devoluciones=? WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, numDias); ps.setInt(2, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id= " + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que incrementa el contador de bloqueo de un usuario * * @author <NAME> & <NAME> * * @param idUsuario Identificador del usuario. * @throws ConexionBDRemotaCloudLibException */ public void incrementContadorBloqueoUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET contador_bloqueo=contador_bloqueo+1 WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que resetea a 0 el contador de bloqueo de un usuario * * @author <NAME> & <NAME> * * @param idUsuario Identificador del usuario. * @throws ConexionBDRemotaCloudLibException */ public void resetContadorBloqueoUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET contador_bloqueo=0 WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que gestiona los cambios necesarios en la base de datos para dar * de baja a un usuario * * @author <NAME> * * @param idUsuario Identificador del usuario * @throws ConexionBDRemotaCloudLibException */ public void setBajaUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE usuario SET fecha_baja=now(), rol=3 WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + idUsuario + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene la fecha y hora más reciente de conexión de un usuario * * @author <NAME> * * @param idUsuario identificador de usuario * @return objeto FechaHoraConexionUsuario * @throws ConexionBDRemotaCloudLibException */ public FechaHoraConexionUsuario getFechaHoraConexionUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; FechaHoraConexionUsuario fechaHoraConexionUsuario; try { //Preparamos la consulta String consulta = "SELECT _id, max(fecha_hora_conexion), id_usuario FROM fecha_hora_conexion_usuario " + "WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { fechaHoraConexionUsuario = new FechaHoraConexionUsuario(rs.getInt(1), rs.getDate(2), rs.getInt(3)); return fechaHoraConexionUsuario; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce la fecha y hora de conexión de un usuario * * @author <NAME> * * @param usuario Objeto usuario * @throws ConexionBDRemotaCloudLibException */ public void putFechaHoraConexionUsuario(Usuario usuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO fecha_hora_conexion_usuario (fecha_hora_conexion, id_usuario) " + "VALUES (now(), (SELECT _id FROM usuario WHERE email=?))"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, usuario.getEmail()); ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce la fecha y hora de conexión de un usuario. * * @author <NAME> * * @param idUsuario Identificador del usuario * @throws ConexionBDRemotaCloudLibException */ public void putFechaHoraConexionUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO fecha_hora_conexion_usuario (fecha_hora_conexion, id_usuario) " + "VALUES (now(), ?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); int executeUpdate = ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un rol * * @author <NAME> * * @param tipo el tipo de rol * @return objeto Rol * @throws ConexionBDRemotaCloudLibException */ public Rol getRol(int tipo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Rol rol; try { //Preparamos la consulta String consulta = "SELECT * FROM rol WHERE tipo=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, tipo); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { rol = new Rol(rs.getInt(1), rs.getInt(2), rs.getString(3)); return rol; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un rol * * @author <NAME> * * @param descripcion la descripcion o nombre del rol * @return objeto Rol * @throws ConexionBDRemotaCloudLibException */ public Rol getRol(String descripcion) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Rol rol; try { //Preparamos la consulta String consulta = "SELECT * FROM rol WHERE descripcion=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, descripcion); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { rol = new Rol(rs.getInt(1), rs.getInt(2), rs.getString(3)); return rol; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de roles * * @author <NAME> * * @return listado de objetos Rol * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Rol> getAllRol() throws ConexionBDRemotaCloudLibException { ResultSet rs; Statement st; ArrayList<Rol> listadoRol; try { //Preparamos la consulta String consulta = "SELECT * FROM rol ORDER BY descripcion ASC"; st = (Statement) conexion.createStatement(); //Y ejecutamos rs = st.executeQuery(consulta); //Obtenemos el unico resultado. if (rs.next()) { listadoRol = new ArrayList<>(); do { Rol rol = new Rol(rs.getInt(1), rs.getInt(2), rs.getString(3)); listadoRol.add(rol); } while (rs.next()); return listadoRol; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado préstamos de un usuario * * @author <NAME> * * @param idUsuario Identificador del usuario * @return objeto Prestamo * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Prestamo> getPrestamosUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Prestamo> listadoPrestamos; try { //Preparamos la consulta String consulta = "SELECT * FROM prestamo WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoPrestamos = new ArrayList<>(); do { Prestamo prestamo = new Prestamo(rs.getInt(1), rs.getDate(2), rs.getDate(3), rs.getDate(4), rs.getString(5), rs.getInt(6), rs.getInt(7), rs.getInt(8)); listadoPrestamos.add(prestamo); } while (rs.next()); return listadoPrestamos; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } // return listadoPrestamos; } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de reservas de un usuario * * @author <NAME> * * @param idUsuario Identificador del usuario al que pertenecen las reseras * @return listado de objetos Reserva * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Reserva> getReservasUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Reserva> listadoReservas; try { //Preparamos la consulta String consulta = "SELECT * FROM reserva WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); if (rs.next()) { listadoReservas = new ArrayList<>(); do { Reserva reserva = new Reserva(rs.getInt(1), rs.getDate(2), rs.getDate(3), rs.getString(4), rs.getInt(5), rs.getInt(6), rs.getInt(7)); listadoReservas.add(reserva); } while (rs.next()); return listadoReservas; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que introduce una reserva * * @author <NAME> * * @param reserva objeto Reserva * @throws ConexionBDRemotaCloudLibException */ public void putReserva(Reserva reserva) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "INSERT INTO reserva (fecha_reserva, fecha_caducidad, observaciones, estado, " + "id_ejemplar, id_usuario) VALUES (now(), ?, ?, ?, ?, ?)"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, getFechaHoraFormatoBD(reserva.getFechaCaducidad())); ps.setString(2, reserva.getObservaciones()); ps.setInt(3, reserva.getEstado()); ps.setInt(4, reserva.getIdEjemplar()); ps.setInt(5, reserva.getIdUsuario()); ps.executeUpdate(); } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que actualiza los datos de una reserva * * @author <NAME> * * @param reserva objeto Reserva * @throws ConexionBDRemotaCloudLibException */ public void updateReserva(Reserva reserva) throws ConexionBDRemotaCloudLibException { PreparedStatement ps; try { //Preparamos la consulta String consulta = "UPDATE reserva SET fecha_reserva=?, fecha_caducidad=?, observaciones=?, " + "estado=?, id_ejemplar=?, id_usuario=? WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, getFechaHoraFormatoBD(reserva.getFechaReserva())); ps.setString(2, getFechaHoraFormatoBD(reserva.getFechaCaducidad())); ps.setString(3, reserva.getObservaciones()); ps.setInt(4, reserva.getEstado()); ps.setInt(5, reserva.getIdEjemplar()); ps.setInt(6, reserva.getIdUsuario()); ps.setInt(7, reserva.getId()); int executeUpdate = ps.executeUpdate(); if (executeUpdate < 1) { throw new ConexionBDRemotaCloudLibException("Error: El objeto con id=" + reserva.getId() + " no se ha podido actualizar"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de sanciones * * @author <NAME> * * @return listado de objetos Sancion * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Sancion> getAllSancion() throws ConexionBDRemotaCloudLibException { ResultSet rs; Statement st; ArrayList<Sancion> listadoSancion; try { //Preparamos la consulta String consulta = "SELECT * FROM sancion ORDER BY descripcion ASC"; st = (Statement) conexion.createStatement(); //Y ejecutamos rs = st.executeQuery(consulta); //Obtenemos el unico resultado. if (rs.next()) { listadoSancion = new ArrayList<>(); do { Sancion sancion = new Sancion(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getInt(4), rs.getInt(5)); listadoSancion.add(sancion); } while (rs.next()); return listadoSancion; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene todas las sanciones de un usuario * * @author <NAME> * * @param idUsuario identificador del usuario * @return listado de sanciones de un usuario * @throws ConexionBDRemotaCloudLibException */ public ArrayList<SancionUsuario> getSancionesUsuario(int idUsuario) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<SancionUsuario> listadoSancionesUsuario; try { //Preparamos la consulta String consulta = "SELECT * FROM sancion_usuario WHERE id_usuario=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idUsuario); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoSancionesUsuario = new ArrayList<>(); do { SancionUsuario sancionUsuario = new SancionUsuario(rs.getInt(1), rs.getDate(2), rs.getDate(3), rs.getInt(4), rs.getInt(5)); listadoSancionesUsuario.add(sancionUsuario); } while (rs.next()); return listadoSancionesUsuario; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que construye la url de conexión con la base de datos a partir de * las variables de la clase * * @author <NAME> * * @return URL de conexión con la base de datos */ private String getUrlConexion() { StringBuilder builder = new StringBuilder(); builder.append("jdbc:mysql://"); builder.append(this.ip); builder.append(":"); builder.append(this.port); builder.append("/"); builder.append(this.nombreBD); return builder.toString(); } /** * Método que obtiene una hora y fecha en formato 'agradable' para la base * de datos * * @author <NAME> * * @param fecha fecha * @return texto con la fecha */ private String getFechaHoraFormatoBD(Date fecha) { String formato = "yyyy-MM-dd HH:mm:ss"; SimpleDateFormat formatData = new SimpleDateFormat(formato, Locale.ROOT); String fechaConFormato = formatData.format(fecha); return fechaConFormato; } /** * Método que obtiene un listado de ejemplares disponibles del título solicitado * @author <NAME> * * @param titulo Título solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorTitulo(String titulo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where titulo LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, titulo); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles relacionados con el título solicitado * @author <NAME> * * @param titulo Título solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesRelacionadosPorTitulo(String titulo) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where titulo LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. String tituloParecido = "%" + titulo + "%"; ps.setString(1, tituloParecido); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles del autor solicitado * @author <NAME> * * @param autor Autor solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorAutor(String autor) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where autor LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, autor); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles relacionados con el autor solicitado * @author <NAME> * * @param autor Autor solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesRelacionadosPorAutor(String autor) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where autor LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. String autorParecido = "%" + autor + "%"; ps.setString(1, autorParecido); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles de la editorial solicitada * @author <NAME> * * @param editorial Editorial solicitada * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorEditorial(String editorial) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where editorial LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, editorial); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles de la editorial solicitada * @author <NAME> * * @param editorial Editorial solicitada * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesRelacionadosPorEditorial(String editorial) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro in (select _id from libro where editorial LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. String editorialParecida = "%" + editorial + "%"; ps.setString(1, editorialParecida); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles del isbn solicitado * @author <NAME> * * @param isbn Isbn solicitado * @return Listado de objetos Disponible * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Disponible> verDisponiblesPorIsbn(String isbn) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Disponible> listadoBibliotecasConEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select distinct b._id, b.nombre, b.direccion, " + "b.descripcion, l.titulo, l.autor, l.editorial, l.edicion " + "from biblioteca b join ejemplar e on b._id=e.id_biblioteca " + "join libro l on e.id_libro=l._id " + "where e.id_libro=(select _id from libro where isbn LIKE ?) " + "and e.estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setString(1, isbn); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoBibliotecasConEjemplaresDisponibles = new ArrayList<>(); do { Disponible disponible = new Disponible(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getInt(8)); listadoBibliotecasConEjemplaresDisponibles.add(disponible); } while (rs.next()); return listadoBibliotecasConEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares disponibles * @author <NAME> * * @param idBiblioteca Identificador de la biblioteca * @param idLibro Identificador del libro * @return Listado de objetos Ejemplar * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Ejemplar> getEjemplaresDisponibles(int idBiblioteca, int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Ejemplar> listadoEjemplaresDisponibles; try { //Preparamos la consulta String consulta = "select * from ejemplar where id_biblioteca=? and id_libro=? and estado=0"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idBiblioteca); ps.setInt(2, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoEjemplaresDisponibles = new ArrayList<>(); do { Ejemplar ejemplar = new Ejemplar(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)); listadoEjemplaresDisponibles.add(ejemplar); } while (rs.next()); return listadoEjemplaresDisponibles; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un objeto Ejemplar * * @author <NAME> * * @param idEjemplar identificador de ejemplar * @return objeto Ejemplar * @throws ConexionBDRemotaCloudLibException */ public Ejemplar getEjemplar(int idEjemplar) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Ejemplar ejemplar; try { //Preparamos la consulta String consulta = "SELECT * FROM ejemplar WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idEjemplar); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { ejemplar = new Ejemplar(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)); return ejemplar; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un listado de ejemplares * @author <NAME> * * @param idLibro Identificador del libro al que pertenecen * @return listado de objetos Ejemplar * @throws ConexionBDRemotaCloudLibException */ public ArrayList<Ejemplar> getEjemplares(int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; ArrayList<Ejemplar> listadoEjemplar; try { //Preparamos la consulta String consulta = "SELECT * FROM ejemplar WHERE id_libro=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { listadoEjemplar = new ArrayList<>(); do { Ejemplar ejemplar = new Ejemplar(rs.getInt(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5)); listadoEjemplar.add(ejemplar); } while (rs.next()); return listadoEjemplar; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } /** * Método que obtiene un libro * * @author <NAME> * * @param idLibro identificador del libro * @return objeto Libro * @throws ConexionBDRemotaCloudLibException */ public Libro getLibro(int idLibro) throws ConexionBDRemotaCloudLibException { ResultSet rs; PreparedStatement ps; Libro libro; try { //Preparamos la consulta String consulta = "SELECT * FROM libro WHERE _id=?"; ps = (PreparedStatement) conexion.prepareStatement(consulta); //Añadimos los parametros y ejecutamos. ps.setInt(1, idLibro); rs = ps.executeQuery(); //Obtenemos el unico resultado. if (rs.next()) { libro = new Libro(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getInt(7), rs.getString(8)); return libro; } else { throw new ConexionBDRemotaCloudLibException("No se han obtenido resultados"); } } catch (SQLException sqle) { throw new ConexionBDRemotaCloudLibException(sqle.getMessage(), sqle); } } }
59,752
0.596604
0.591605
1,586
37.093948
30.366457
136
false
false
0
0
0
0
0
0
0.562421
false
false
13
b2bd557ba2a538071e1db3d69d55723c69cb78eb
7,670,811,636,457
d2fee7f57c5d4a3f1f4ecdd58b4562257e41c984
/DisplaySummary.java
6a90df688278fb7f89c3219e5ccae3f6de14ba1f
[]
no_license
slasch9615/Slasch-Finance
https://github.com/slasch9615/Slasch-Finance
1d91e255689ee71e3314c9e26f93aa77204db642
d6b0d8de09850a932a9ef23744748e132553e1a5
refs/heads/master
2020-05-16T09:09:29.231000
2019-04-26T00:51:29
2019-04-26T00:51:29
182,939,963
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Date; import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.chart.PieChart; import javafx.scene.control.ScrollPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TitledPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; /* Slasch Finance * Version 1.0 * Author: Sam Lasch * Date: 04/19/2019 * Licensing Information: You are free to use or extend this project for personal purposes provided that * it is not distributed or published for profit * * * DisplaySummary Class: Builds summary data for financial information */ public class DisplaySummary { private static TabPane tpane = new TabPane(); /* Method: buildHistoryTabs * Parameters: Month month, Year year * month: The month for the current Transactions to be displayed for * year: The year which the scene is for * * Return: TabPane: tabpane with the tabs for budget summary and transaction history * * Description: builds the tab pane with tabs for summary and transaction history * */ public static TabPane buildHistoryTabs(Month month, Year year) { ScrollPane sp = new ScrollPane(); sp.setHbarPolicy(ScrollBarPolicy.NEVER); sp.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); TabPane tabPane = new TabPane(); tabPane.setMinWidth(50); tabPane.setPrefWidth(50); tabPane.setMaxWidth(20000); Tab budgetSummary = new Tab("Budget Summary"); VBox vbox = new VBox(); vbox = buildBudgetSummary(month); vbox.setPadding(new Insets(15, 27, 15, 15)); vbox.prefWidthProperty().bind(sp.widthProperty()); vbox.minHeightProperty().bind(sp.heightProperty()); sp.setContent(vbox); sp.minHeightProperty().bind(tabPane.heightProperty().subtract(30)); sp.maxWidthProperty().bind(tabPane.widthProperty()); budgetSummary.setContent(sp); budgetSummary.setClosable(false); VBox vbox1 = new VBox(); vbox1.maxHeightProperty().bind(tabPane.heightProperty()); vbox1.maxWidthProperty().bind(tabPane.widthProperty()); //Build history tab for each of the three transactions Tab tranHistory = new Tab("Transaction History"); vbox1 = DisplayTransactionData.buildTransactionHistory(month.getTransactionList().getExpenseList(), 0, "Expense", month, year); tranHistory.setContent(vbox1); tranHistory.setClosable(false); Tab reimHistory = new Tab("Reimburstment History"); vbox1 = DisplayTransactionData.buildTransactionHistory(month.getTransactionList().getReimbursementList(), 1, "Reimbursement", month, year); reimHistory.setContent(vbox1); reimHistory.setClosable(false); Tab incomeHistory = new Tab("Income History"); vbox1 = DisplayTransactionData.buildTransactionHistory(month.getTransactionList().getIncomeList(), 2, "Income", month, year); incomeHistory.setContent(vbox1); incomeHistory.setClosable(false); //Stores the tabpane from the "Total" month including the unused month's transactions if(month.getName().equalsIgnoreCase("Total")) { DisplayTransactionData.applyChanged(year); vbox1 = DisplayTransactionData.getChangedData(year); Tab changedTab = new Tab("Unused Transactions"); changedTab.setContent(vbox1); changedTab.setClosable(false); tabPane.getTabs().add(budgetSummary); tabPane.getTabs().add(tranHistory); tabPane.getTabs().add(reimHistory); tabPane.getTabs().add(incomeHistory); tabPane.getTabs().add(changedTab); DisplaySummary.tpane = tabPane; } else { tabPane.getTabs().add(budgetSummary); tabPane.getTabs().add(tranHistory); tabPane.getTabs().add(reimHistory); tabPane.getTabs().add(incomeHistory); } return tabPane; } /* Method: displayChangedTransactions * Parameters:Year year * year: The year which the scene is for * * Return: Void * * Description: updates the unused month that displays unused transactions * */ public static void displayChangedTransactions(Year year) { DisplayTransactionData.applyChanged(year); DisplayTransactionData.updateChangedTable(year); } /* Summary builder Methods*/ /* Method: buildBudgetSummary * Parameters:Month month * Month: data to use to summarize * * Return: Vbox containing the budget summaries * * Description: Builds the summary tables for the month * */ public static VBox buildBudgetSummary(Month month) { VBox vbox = new VBox(); TableView<?> tblView = new TableView<Object>(); //Build gross income summary table tblView = buildIncomeSummary(month.getCatIncomeList()); month.addTblView(tblView); TitledPane income = new TitledPane("Gross Income Summary",tblView); //Build Expense Summary table tblView = buildTransactionSummary(month.getCategoryList()); month.setTblViewListExpenseSummary((TableView<Category>) tblView); TitledPane spending = new TitledPane("Expense Summary", tblView); //Build Spending By Transaction Type table tblView = buildSpendingTypeSummary(month); month.addTblView(tblView); TitledPane spendingType = new TitledPane("Spending By Transaction Type", tblView); //Build Net income summary table tblView = buildNetIncomeSummary(month); month.addTblView(tblView); TitledPane netIncome = new TitledPane("Net Income Summary", tblView); //Build Withdrawal Summary table tblView =buildWithdrawl(month.getTransactionList().getReimbursementList()); month.setTblViewWithdrawal((TableView<Reimbursement>) tblView); TitledPane withdrawal = new TitledPane("Withdrawal Summary", tblView); //Determines if there is data to display in the pie chart Category cat = null; boolean hasData = false; for(int i = 0; i < month.getCategoryList().size()-1; i++) { cat = month.getCategoryList().get(i); int portion = (int) cat.getCategoryNetSpending().intValue(); if(portion > 0) { hasData = true; } } vbox.getChildren().add(income); vbox.getChildren().add(netIncome); vbox.getChildren().add(spending); vbox.getChildren().add(spendingType); vbox.getChildren().add(withdrawal); vbox.setSpacing(15); //build pie chart with data only if there is data to enter if(hasData) { PieChart pie = buildChart(month); vbox.getChildren().add(pie); } else { PieChart pie = new PieChart(); month.setChart(pie); vbox.getChildren().add(pie); } return vbox; } /* Method: buildNetIncomeSummary * Parameters:Month month * Month: data to use to summarize * * Return: Tableview displaying net income summary data * * Description: Builds Tableview displaying net income summary data * */ private static TableView<?> buildNetIncomeSummary(Month month) { //Add month to the list to access data ObservableList<Month> tblList = FXCollections.observableArrayList(); tblList.add( month); TableView<Month> tblView = new TableView<Month>(); tblView.setItems(tblList); //Create columns TableColumn<Month, Double> netInc = new TableColumn<Month, Double>("Net Income"); TableColumn<Month, Double> netSpend = new TableColumn<Month, Double>("Net Spending"); TableColumn<Month, Double> grossInc = new TableColumn<Month, Double>("Gross Income"); TableColumn<Month, Double> grossSpend = new TableColumn<Month, Double>("Gross Spending"); TableColumn<Month, Double> reimbursement = new TableColumn<Month, Double>("Reimbursement Total"); netInc.setCellValueFactory(new PropertyValueFactory<Month, Double>("netIncome")); netSpend.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingTotal")); grossInc.setCellValueFactory(new PropertyValueFactory<Month, Double>("grossIncome")); grossSpend.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingGross")); reimbursement.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingReimbursement")); //Build Tableview tblView.getColumns().addAll(netInc, grossInc, netSpend, grossSpend, reimbursement); netInc.setMinWidth(0); netSpend.setMinWidth(0); grossInc.setMinWidth(0); grossSpend.setMinWidth(0); reimbursement.setMinWidth(0); //Make tableview size fit number of entries tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Method: buildSpendingTypeSummary * Parameters:Month month * Month: data to use to summarize * * Return: Tableview displaying Spending by Transaction Type summary data * * Description: Builds Tableview displaying Spending by Transaction Type summary data * */ private static TableView buildSpendingTypeSummary(Month month) { //Add month to the list to access data ObservableList<Month> tblList = FXCollections.observableArrayList(); tblList.add( month); TableView<Month> tblView = new TableView<Month>(); tblView.setItems(tblList); //Create columns TableColumn<Month, Double> net = new TableColumn<Month, Double>("Net Spending"); TableColumn<Month, Double> cash = new TableColumn<Month, Double>("Cash Spending"); TableColumn<Month, Double> check = new TableColumn<Month, Double>("Check Spending"); TableColumn<Month, Double> credit = new TableColumn<Month, Double>("Credit Spending"); TableColumn<Month, Double> debit = new TableColumn<Month, Double>("Debit Spending"); net.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingTotal")); cash.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingCash")); check.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingCheck")); credit.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingCredit")); debit.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingDebit")); //Build tableview tblView.getColumns().addAll(net, cash, check, credit, debit); net.setMinWidth(0); cash.setMinWidth(0); credit.setMinWidth(0); check.setMinWidth(0); debit.setMinWidth(0); //Make tableview size fit number of entries tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Method: buildChart * Parameters:Month month * Month: data to use to summarize * * Return: piechart displaying Spending by Category * * Description: Builds piechart displaying Spending by Category * */ public static PieChart buildChart(Month month) { //Get total spending from each category to make portion of graph ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(); Category cat = null; for(int i = 0; i < month.getCategoryList().size()-1; i++) { cat = month.getCategoryList().get(i); int portion = (int) cat.getCategoryNetSpending().intValue(); if(portion > 0) { pieChartData.add( new PieChart.Data(cat.getCategoryName(), portion)); } } //Build pie chart PieChart chart = new PieChart(pieChartData); chart.setTitle("Spending Per Category"); month.setChart(chart); return chart; } /* Method: buildWithdrawl * Parameters:ArrayList<Reimbursement> list * List: list of reimbursements to pull withdrawals from * * Return: Tableview displaying withdrawal summary data * * Description: Builds Tableview displaying withdrawal summary data * */ public static TableView<Reimbursement> buildWithdrawl(ArrayList<Reimbursement> list) { //Gets the withdrawal transactions from the reimbursement list ObservableList<Reimbursement> tblList = FXCollections.observableArrayList(); for(int i = 0; i < list.size(); i++) { if(list.get(i).getWithdrawal().equalsIgnoreCase("Yes")) { tblList.add( list.get(i)); } } TableView<Reimbursement> tblView = new TableView<Reimbursement>(); tblView.setItems(tblList); //Build Columns TableColumn<Reimbursement, Date> date = new TableColumn<Reimbursement, Date>("Date"); TableColumn<Reimbursement, String> vendor = new TableColumn<Reimbursement, String>("Vendor"); TableColumn<Reimbursement, Double> amount = new TableColumn<Reimbursement, Double>("Amount"); date.setCellValueFactory(new PropertyValueFactory<Reimbursement, Date>("date")); vendor.setCellValueFactory(new PropertyValueFactory<Reimbursement, String>("vendor")); amount.setCellValueFactory(new PropertyValueFactory<Reimbursement, Double>("amount")); //Build Tableview tblView.getColumns().addAll(date,vendor, amount); date.setMinWidth(0); vendor.setMinWidth(0); amount.setMinWidth(0); tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); //Make tableview size fit number of entries tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); tblView.setMinHeight(50); return tblView; } /* Method: buildTransactionSummary * Parameters:ArrayList<Category> list * List: list of categories to gather data from * * Return: Tableview displaying Spending by category summary data * * Description: Builds Tableview displaying Spending by category summary data * */ public static TableView buildTransactionSummary(ArrayList<Category> list) { //build list of categories to display data ObservableList<Category> tblList = FXCollections.observableArrayList(); for(int i = 0; i < list.size(); i++) { tblList.add( list.get(i)); } TableView<Category> tblView = new TableView<Category>(); tblView.setItems(tblList); //Build columns TableColumn<Category, String> category = new TableColumn<Category, String>("Category"); TableColumn<Category, Double> gross = new TableColumn<Category, Double>("Gross Spending"); TableColumn<Category, Double> net = new TableColumn<Category, Double>("Net Spending"); TableColumn<Category, Double> reim = new TableColumn<Category, Double>("Reimbursement Amount"); category.setCellValueFactory(new PropertyValueFactory<Category, String>("categoryName")); gross.setCellValueFactory(new PropertyValueFactory<Category, Double>("categorySpending")); net.setCellValueFactory(new PropertyValueFactory<Category, Double>("categoryNetSpending")); reim.setCellValueFactory(new PropertyValueFactory<Category, Double>("categoryReimbursement")); //Build Table tblView.getColumns().addAll(category,reim, gross, net); category.setMinWidth(0); gross.setMinWidth(0); net.setMinWidth(0); //Set size of tableview to equal size of content tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Method: buildTransactionSummary * Parameters:ArrayList<CategoryIncome> list * List: list of categoryIncome to get income data from * * Return: Tableview displaying Spending by category summary data * * Description: Builds Tableview displaying Spending by category summary data * */ public static TableView buildIncomeSummary(ArrayList<CategoryIncome> list) { //build list of categoryImcome to get the income data ObservableList<CategoryIncome> tblList = FXCollections.observableArrayList(); for(int i = 0; i < list.size(); i++) { tblList.add( list.get(i)); } TableView<CategoryIncome> tblView = new TableView<CategoryIncome>(); tblView.setItems(tblList); //Build columns TableColumn<CategoryIncome, String> categoryIncome = new TableColumn<CategoryIncome, String>("Category"); TableColumn<CategoryIncome, Double> totalIncome = new TableColumn<CategoryIncome, Double>("Amount Income"); TableColumn<CategoryIncome, Double> cashIncome = new TableColumn<CategoryIncome, Double>("Amount Cash"); TableColumn<CategoryIncome, Double> checkIncome = new TableColumn<CategoryIncome, Double>("Amount Check"); TableColumn<CategoryIncome, Double> debitIncome = new TableColumn<CategoryIncome, Double>("Amount Debit"); categoryIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, String>("name")); totalIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeTotal")); cashIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeCash")); checkIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeCheck")); debitIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeDebit")); //Build Table tblView.getColumns().addAll(categoryIncome,totalIncome, cashIncome, checkIncome, debitIncome); categoryIncome.setMinWidth(0); totalIncome.setMinWidth(0); cashIncome.setMinWidth(0); checkIncome.setMinWidth(0); debitIncome.setMinWidth(0); //Set size of tableview to equal size of content tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Getters and Setters */ public TabPane getTpane() { return tpane; } public void setTpane(TabPane tpane) { this.tpane = tpane; } }
UTF-8
Java
17,948
java
DisplaySummary.java
Java
[ { "context": ";\r\n\r\n/* Slasch Finance\r\n * Version 1.0\r\n * Author: Sam Lasch\r\n * Date: 04/19/2019\r\n * Licensing Information: Y", "end": 688, "score": 0.9997841715812683, "start": 679, "tag": "NAME", "value": "Sam Lasch" } ]
null
[]
import java.util.ArrayList; import java.util.Date; import javafx.beans.binding.Bindings; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.chart.PieChart; import javafx.scene.control.ScrollPane; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TitledPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; /* Slasch Finance * Version 1.0 * Author: <NAME> * Date: 04/19/2019 * Licensing Information: You are free to use or extend this project for personal purposes provided that * it is not distributed or published for profit * * * DisplaySummary Class: Builds summary data for financial information */ public class DisplaySummary { private static TabPane tpane = new TabPane(); /* Method: buildHistoryTabs * Parameters: Month month, Year year * month: The month for the current Transactions to be displayed for * year: The year which the scene is for * * Return: TabPane: tabpane with the tabs for budget summary and transaction history * * Description: builds the tab pane with tabs for summary and transaction history * */ public static TabPane buildHistoryTabs(Month month, Year year) { ScrollPane sp = new ScrollPane(); sp.setHbarPolicy(ScrollBarPolicy.NEVER); sp.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); TabPane tabPane = new TabPane(); tabPane.setMinWidth(50); tabPane.setPrefWidth(50); tabPane.setMaxWidth(20000); Tab budgetSummary = new Tab("Budget Summary"); VBox vbox = new VBox(); vbox = buildBudgetSummary(month); vbox.setPadding(new Insets(15, 27, 15, 15)); vbox.prefWidthProperty().bind(sp.widthProperty()); vbox.minHeightProperty().bind(sp.heightProperty()); sp.setContent(vbox); sp.minHeightProperty().bind(tabPane.heightProperty().subtract(30)); sp.maxWidthProperty().bind(tabPane.widthProperty()); budgetSummary.setContent(sp); budgetSummary.setClosable(false); VBox vbox1 = new VBox(); vbox1.maxHeightProperty().bind(tabPane.heightProperty()); vbox1.maxWidthProperty().bind(tabPane.widthProperty()); //Build history tab for each of the three transactions Tab tranHistory = new Tab("Transaction History"); vbox1 = DisplayTransactionData.buildTransactionHistory(month.getTransactionList().getExpenseList(), 0, "Expense", month, year); tranHistory.setContent(vbox1); tranHistory.setClosable(false); Tab reimHistory = new Tab("Reimburstment History"); vbox1 = DisplayTransactionData.buildTransactionHistory(month.getTransactionList().getReimbursementList(), 1, "Reimbursement", month, year); reimHistory.setContent(vbox1); reimHistory.setClosable(false); Tab incomeHistory = new Tab("Income History"); vbox1 = DisplayTransactionData.buildTransactionHistory(month.getTransactionList().getIncomeList(), 2, "Income", month, year); incomeHistory.setContent(vbox1); incomeHistory.setClosable(false); //Stores the tabpane from the "Total" month including the unused month's transactions if(month.getName().equalsIgnoreCase("Total")) { DisplayTransactionData.applyChanged(year); vbox1 = DisplayTransactionData.getChangedData(year); Tab changedTab = new Tab("Unused Transactions"); changedTab.setContent(vbox1); changedTab.setClosable(false); tabPane.getTabs().add(budgetSummary); tabPane.getTabs().add(tranHistory); tabPane.getTabs().add(reimHistory); tabPane.getTabs().add(incomeHistory); tabPane.getTabs().add(changedTab); DisplaySummary.tpane = tabPane; } else { tabPane.getTabs().add(budgetSummary); tabPane.getTabs().add(tranHistory); tabPane.getTabs().add(reimHistory); tabPane.getTabs().add(incomeHistory); } return tabPane; } /* Method: displayChangedTransactions * Parameters:Year year * year: The year which the scene is for * * Return: Void * * Description: updates the unused month that displays unused transactions * */ public static void displayChangedTransactions(Year year) { DisplayTransactionData.applyChanged(year); DisplayTransactionData.updateChangedTable(year); } /* Summary builder Methods*/ /* Method: buildBudgetSummary * Parameters:Month month * Month: data to use to summarize * * Return: Vbox containing the budget summaries * * Description: Builds the summary tables for the month * */ public static VBox buildBudgetSummary(Month month) { VBox vbox = new VBox(); TableView<?> tblView = new TableView<Object>(); //Build gross income summary table tblView = buildIncomeSummary(month.getCatIncomeList()); month.addTblView(tblView); TitledPane income = new TitledPane("Gross Income Summary",tblView); //Build Expense Summary table tblView = buildTransactionSummary(month.getCategoryList()); month.setTblViewListExpenseSummary((TableView<Category>) tblView); TitledPane spending = new TitledPane("Expense Summary", tblView); //Build Spending By Transaction Type table tblView = buildSpendingTypeSummary(month); month.addTblView(tblView); TitledPane spendingType = new TitledPane("Spending By Transaction Type", tblView); //Build Net income summary table tblView = buildNetIncomeSummary(month); month.addTblView(tblView); TitledPane netIncome = new TitledPane("Net Income Summary", tblView); //Build Withdrawal Summary table tblView =buildWithdrawl(month.getTransactionList().getReimbursementList()); month.setTblViewWithdrawal((TableView<Reimbursement>) tblView); TitledPane withdrawal = new TitledPane("Withdrawal Summary", tblView); //Determines if there is data to display in the pie chart Category cat = null; boolean hasData = false; for(int i = 0; i < month.getCategoryList().size()-1; i++) { cat = month.getCategoryList().get(i); int portion = (int) cat.getCategoryNetSpending().intValue(); if(portion > 0) { hasData = true; } } vbox.getChildren().add(income); vbox.getChildren().add(netIncome); vbox.getChildren().add(spending); vbox.getChildren().add(spendingType); vbox.getChildren().add(withdrawal); vbox.setSpacing(15); //build pie chart with data only if there is data to enter if(hasData) { PieChart pie = buildChart(month); vbox.getChildren().add(pie); } else { PieChart pie = new PieChart(); month.setChart(pie); vbox.getChildren().add(pie); } return vbox; } /* Method: buildNetIncomeSummary * Parameters:Month month * Month: data to use to summarize * * Return: Tableview displaying net income summary data * * Description: Builds Tableview displaying net income summary data * */ private static TableView<?> buildNetIncomeSummary(Month month) { //Add month to the list to access data ObservableList<Month> tblList = FXCollections.observableArrayList(); tblList.add( month); TableView<Month> tblView = new TableView<Month>(); tblView.setItems(tblList); //Create columns TableColumn<Month, Double> netInc = new TableColumn<Month, Double>("Net Income"); TableColumn<Month, Double> netSpend = new TableColumn<Month, Double>("Net Spending"); TableColumn<Month, Double> grossInc = new TableColumn<Month, Double>("Gross Income"); TableColumn<Month, Double> grossSpend = new TableColumn<Month, Double>("Gross Spending"); TableColumn<Month, Double> reimbursement = new TableColumn<Month, Double>("Reimbursement Total"); netInc.setCellValueFactory(new PropertyValueFactory<Month, Double>("netIncome")); netSpend.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingTotal")); grossInc.setCellValueFactory(new PropertyValueFactory<Month, Double>("grossIncome")); grossSpend.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingGross")); reimbursement.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingReimbursement")); //Build Tableview tblView.getColumns().addAll(netInc, grossInc, netSpend, grossSpend, reimbursement); netInc.setMinWidth(0); netSpend.setMinWidth(0); grossInc.setMinWidth(0); grossSpend.setMinWidth(0); reimbursement.setMinWidth(0); //Make tableview size fit number of entries tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Method: buildSpendingTypeSummary * Parameters:Month month * Month: data to use to summarize * * Return: Tableview displaying Spending by Transaction Type summary data * * Description: Builds Tableview displaying Spending by Transaction Type summary data * */ private static TableView buildSpendingTypeSummary(Month month) { //Add month to the list to access data ObservableList<Month> tblList = FXCollections.observableArrayList(); tblList.add( month); TableView<Month> tblView = new TableView<Month>(); tblView.setItems(tblList); //Create columns TableColumn<Month, Double> net = new TableColumn<Month, Double>("Net Spending"); TableColumn<Month, Double> cash = new TableColumn<Month, Double>("Cash Spending"); TableColumn<Month, Double> check = new TableColumn<Month, Double>("Check Spending"); TableColumn<Month, Double> credit = new TableColumn<Month, Double>("Credit Spending"); TableColumn<Month, Double> debit = new TableColumn<Month, Double>("Debit Spending"); net.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingTotal")); cash.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingCash")); check.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingCheck")); credit.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingCredit")); debit.setCellValueFactory(new PropertyValueFactory<Month, Double>("spendingDebit")); //Build tableview tblView.getColumns().addAll(net, cash, check, credit, debit); net.setMinWidth(0); cash.setMinWidth(0); credit.setMinWidth(0); check.setMinWidth(0); debit.setMinWidth(0); //Make tableview size fit number of entries tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Method: buildChart * Parameters:Month month * Month: data to use to summarize * * Return: piechart displaying Spending by Category * * Description: Builds piechart displaying Spending by Category * */ public static PieChart buildChart(Month month) { //Get total spending from each category to make portion of graph ObservableList<PieChart.Data> pieChartData = FXCollections.observableArrayList(); Category cat = null; for(int i = 0; i < month.getCategoryList().size()-1; i++) { cat = month.getCategoryList().get(i); int portion = (int) cat.getCategoryNetSpending().intValue(); if(portion > 0) { pieChartData.add( new PieChart.Data(cat.getCategoryName(), portion)); } } //Build pie chart PieChart chart = new PieChart(pieChartData); chart.setTitle("Spending Per Category"); month.setChart(chart); return chart; } /* Method: buildWithdrawl * Parameters:ArrayList<Reimbursement> list * List: list of reimbursements to pull withdrawals from * * Return: Tableview displaying withdrawal summary data * * Description: Builds Tableview displaying withdrawal summary data * */ public static TableView<Reimbursement> buildWithdrawl(ArrayList<Reimbursement> list) { //Gets the withdrawal transactions from the reimbursement list ObservableList<Reimbursement> tblList = FXCollections.observableArrayList(); for(int i = 0; i < list.size(); i++) { if(list.get(i).getWithdrawal().equalsIgnoreCase("Yes")) { tblList.add( list.get(i)); } } TableView<Reimbursement> tblView = new TableView<Reimbursement>(); tblView.setItems(tblList); //Build Columns TableColumn<Reimbursement, Date> date = new TableColumn<Reimbursement, Date>("Date"); TableColumn<Reimbursement, String> vendor = new TableColumn<Reimbursement, String>("Vendor"); TableColumn<Reimbursement, Double> amount = new TableColumn<Reimbursement, Double>("Amount"); date.setCellValueFactory(new PropertyValueFactory<Reimbursement, Date>("date")); vendor.setCellValueFactory(new PropertyValueFactory<Reimbursement, String>("vendor")); amount.setCellValueFactory(new PropertyValueFactory<Reimbursement, Double>("amount")); //Build Tableview tblView.getColumns().addAll(date,vendor, amount); date.setMinWidth(0); vendor.setMinWidth(0); amount.setMinWidth(0); tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); //Make tableview size fit number of entries tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); tblView.setMinHeight(50); return tblView; } /* Method: buildTransactionSummary * Parameters:ArrayList<Category> list * List: list of categories to gather data from * * Return: Tableview displaying Spending by category summary data * * Description: Builds Tableview displaying Spending by category summary data * */ public static TableView buildTransactionSummary(ArrayList<Category> list) { //build list of categories to display data ObservableList<Category> tblList = FXCollections.observableArrayList(); for(int i = 0; i < list.size(); i++) { tblList.add( list.get(i)); } TableView<Category> tblView = new TableView<Category>(); tblView.setItems(tblList); //Build columns TableColumn<Category, String> category = new TableColumn<Category, String>("Category"); TableColumn<Category, Double> gross = new TableColumn<Category, Double>("Gross Spending"); TableColumn<Category, Double> net = new TableColumn<Category, Double>("Net Spending"); TableColumn<Category, Double> reim = new TableColumn<Category, Double>("Reimbursement Amount"); category.setCellValueFactory(new PropertyValueFactory<Category, String>("categoryName")); gross.setCellValueFactory(new PropertyValueFactory<Category, Double>("categorySpending")); net.setCellValueFactory(new PropertyValueFactory<Category, Double>("categoryNetSpending")); reim.setCellValueFactory(new PropertyValueFactory<Category, Double>("categoryReimbursement")); //Build Table tblView.getColumns().addAll(category,reim, gross, net); category.setMinWidth(0); gross.setMinWidth(0); net.setMinWidth(0); //Set size of tableview to equal size of content tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Method: buildTransactionSummary * Parameters:ArrayList<CategoryIncome> list * List: list of categoryIncome to get income data from * * Return: Tableview displaying Spending by category summary data * * Description: Builds Tableview displaying Spending by category summary data * */ public static TableView buildIncomeSummary(ArrayList<CategoryIncome> list) { //build list of categoryImcome to get the income data ObservableList<CategoryIncome> tblList = FXCollections.observableArrayList(); for(int i = 0; i < list.size(); i++) { tblList.add( list.get(i)); } TableView<CategoryIncome> tblView = new TableView<CategoryIncome>(); tblView.setItems(tblList); //Build columns TableColumn<CategoryIncome, String> categoryIncome = new TableColumn<CategoryIncome, String>("Category"); TableColumn<CategoryIncome, Double> totalIncome = new TableColumn<CategoryIncome, Double>("Amount Income"); TableColumn<CategoryIncome, Double> cashIncome = new TableColumn<CategoryIncome, Double>("Amount Cash"); TableColumn<CategoryIncome, Double> checkIncome = new TableColumn<CategoryIncome, Double>("Amount Check"); TableColumn<CategoryIncome, Double> debitIncome = new TableColumn<CategoryIncome, Double>("Amount Debit"); categoryIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, String>("name")); totalIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeTotal")); cashIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeCash")); checkIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeCheck")); debitIncome.setCellValueFactory(new PropertyValueFactory<CategoryIncome, Double>("incomeDebit")); //Build Table tblView.getColumns().addAll(categoryIncome,totalIncome, cashIncome, checkIncome, debitIncome); categoryIncome.setMinWidth(0); totalIncome.setMinWidth(0); cashIncome.setMinWidth(0); checkIncome.setMinWidth(0); debitIncome.setMinWidth(0); //Set size of tableview to equal size of content tblView.setColumnResizePolicy(tblView.CONSTRAINED_RESIZE_POLICY); tblView.setFixedCellSize(25); tblView.prefHeightProperty().bind(tblView.fixedCellSizeProperty().multiply(Bindings.size(tblView.getItems()).add(1.1))); return tblView; } /* Getters and Setters */ public TabPane getTpane() { return tpane; } public void setTpane(TabPane tpane) { this.tpane = tpane; } }
17,945
0.736628
0.731224
466
36.519314
31.937248
141
false
false
0
0
0
0
0
0
2.156652
false
false
13