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
5dd9d77c332d7641cb21b8f5f9de49968ac01837
36,309,653,547,998
0a4e1525253b4907012c0488b22f99383276e4ad
/microservicecloud-consumer-dept-feign/src/main/java/com/fanlun/springcloud/controller/DeptController_Consumer.java
103b19d24ddfe45c36540c2f2fb3dd8f2f59bd1f
[]
no_license
fanlun007/springCloud2018-learnDemo
https://github.com/fanlun007/springCloud2018-learnDemo
f51fc1787661c1b9cef2abee2d7575647ad7ec82
c310b4350ea8b8da4cbf3a930f7a0a962d1dfcb7
refs/heads/master
2022-07-20T17:53:32.377000
2019-05-28T10:25:23
2019-05-28T10:25:23
189,006,275
0
0
null
false
2022-06-21T01:11:10
2019-05-28T10:24:52
2019-05-28T10:25:35
2022-06-21T01:11:06
62
0
0
4
Java
false
false
package com.fanlun.springcloud.controller; import com.fanlun.springcloud.Entity.Dept; import com.fanlun.springcloud.service.DeptClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class DeptController_Consumer { @Autowired public DeptClientService clientService; @GetMapping(value = "/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return clientService.get(id); } @GetMapping("/consumer/dept/list") public List<Dept> list() { return clientService.list(); } @PostMapping("/consumer/dept/add") public Object add(Dept dept) { return clientService.add(dept); } }
UTF-8
Java
976
java
DeptController_Consumer.java
Java
[]
null
[]
package com.fanlun.springcloud.controller; import com.fanlun.springcloud.Entity.Dept; import com.fanlun.springcloud.service.DeptClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class DeptController_Consumer { @Autowired public DeptClientService clientService; @GetMapping(value = "/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return clientService.get(id); } @GetMapping("/consumer/dept/list") public List<Dept> list() { return clientService.list(); } @PostMapping("/consumer/dept/add") public Object add(Dept dept) { return clientService.add(dept); } }
976
0.747951
0.747951
35
26.885714
22.615761
62
false
false
0
0
0
0
0
0
0.371429
false
false
10
26f619c4c4dabf3b5ed4f91ef7128e415566e1c1
36,833,639,554,396
bfa28aaf277bbcd65d8eed6c832fef8ddcb1103c
/Pinterest/source/src/com/squareup/okhttp/internal/http/HttpConnection$ChunkedSource.java
8a970b0fb0eb3a27e1baa8c1c36389dd6f86283c
[]
no_license
TheFinestArtist/JAVA-Android-Learning
https://github.com/TheFinestArtist/JAVA-Android-Learning
bfc26dd8928019884bad0fdd97319afbcd27e515
a0182eb967b8cec9774bbf2cbff0a3953f7be3f9
refs/heads/master
2020-12-28T23:16:55.096000
2015-09-11T09:07:32
2015-09-11T09:07:32
35,862,779
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.squareup.okhttp.internal.http; import java.io.IOException; import java.net.CacheRequest; import java.net.ProtocolException; import okio.Buffer; import okio.BufferedSource; import okio.Source; import okio.Timeout; // Referenced classes of package com.squareup.okhttp.internal.http: // HttpConnection, HttpEngine class g extends implements Source { final HttpConnection d; private int e; private boolean f; private final HttpEngine g; public final Timeout a() { return HttpConnection.g(d).a(); } public final long b(Buffer buffer, long l) { if (l < 0L) { throw new IllegalArgumentException((new StringBuilder("byteCount < 0: ")).append(l).toString()); } if (b) { throw new IllegalStateException("closed"); } if (f) goto _L2; else goto _L1 _L1: return -1L; _L2: if (e != 0 && e != -1) { break; /* Loop/switch isn't completed */ } if (e != -1) { HttpConnection.g(d).m(); } String s = HttpConnection.g(d).m(); int i = s.indexOf(";"); Object obj = s; if (i != -1) { obj = s.substring(0, i); } try { e = Integer.parseInt(((String) (obj)).trim(), 16); } // Misplaced declaration of an exception variable catch (Buffer buffer) { throw new ProtocolException((new StringBuilder("Expected a hex chunk size but was ")).append(((String) (obj))).toString()); } if (e == 0) { f = false; obj = new com.squareup.okhttp.ChunkedSource.f(); d.a(((com.squareup.okhttp.a) (obj))); g.a(((com.squareup.okhttp.ChunkedSource.g) (obj)).g()); a(true); } if (!f) goto _L1; else goto _L3 _L3: l = HttpConnection.g(d).b(buffer, Math.min(l, e)); if (l == -1L) { a_(); throw new IOException("unexpected end of stream"); } else { e = (int)((long)e - l); a(buffer, l); return l; } } public void close() { if (b) { return; } if (f && !d.a(this)) { a_(); } b = true; } (HttpConnection httpconnection, CacheRequest cacherequest, HttpEngine httpengine) { d = httpconnection; super(httpconnection, cacherequest); e = -1; f = true; g = httpengine; } }
UTF-8
Java
2,813
java
HttpConnection$ChunkedSource.java
Java
[ { "context": "// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.geocities.com/kpdus", "end": 61, "score": 0.9996566772460938, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.squareup.okhttp.internal.http; import java.io.IOException; import java.net.CacheRequest; import java.net.ProtocolException; import okio.Buffer; import okio.BufferedSource; import okio.Source; import okio.Timeout; // Referenced classes of package com.squareup.okhttp.internal.http: // HttpConnection, HttpEngine class g extends implements Source { final HttpConnection d; private int e; private boolean f; private final HttpEngine g; public final Timeout a() { return HttpConnection.g(d).a(); } public final long b(Buffer buffer, long l) { if (l < 0L) { throw new IllegalArgumentException((new StringBuilder("byteCount < 0: ")).append(l).toString()); } if (b) { throw new IllegalStateException("closed"); } if (f) goto _L2; else goto _L1 _L1: return -1L; _L2: if (e != 0 && e != -1) { break; /* Loop/switch isn't completed */ } if (e != -1) { HttpConnection.g(d).m(); } String s = HttpConnection.g(d).m(); int i = s.indexOf(";"); Object obj = s; if (i != -1) { obj = s.substring(0, i); } try { e = Integer.parseInt(((String) (obj)).trim(), 16); } // Misplaced declaration of an exception variable catch (Buffer buffer) { throw new ProtocolException((new StringBuilder("Expected a hex chunk size but was ")).append(((String) (obj))).toString()); } if (e == 0) { f = false; obj = new com.squareup.okhttp.ChunkedSource.f(); d.a(((com.squareup.okhttp.a) (obj))); g.a(((com.squareup.okhttp.ChunkedSource.g) (obj)).g()); a(true); } if (!f) goto _L1; else goto _L3 _L3: l = HttpConnection.g(d).b(buffer, Math.min(l, e)); if (l == -1L) { a_(); throw new IOException("unexpected end of stream"); } else { e = (int)((long)e - l); a(buffer, l); return l; } } public void close() { if (b) { return; } if (f && !d.a(this)) { a_(); } b = true; } (HttpConnection httpconnection, CacheRequest cacherequest, HttpEngine httpengine) { d = httpconnection; super(httpconnection, cacherequest); e = -1; f = true; g = httpengine; } }
2,803
0.510843
0.501244
114
23.675438
22.686844
135
false
false
0
0
0
0
0
0
0.491228
false
false
10
ede92e2d7ba8c1cadba9fab8ada27e43f1070a08
36,283,883,755,255
c05dc7c24eff421627557b2174e132a663da03a5
/src/figurePainter4j/Main.java
103ea3df7ad6fc1a0799a7ea9446548a54bfca9d
[]
no_license
andreaskunz/figurePainter4j
https://github.com/andreaskunz/figurePainter4j
05cf4e80ab5995c860bd9736eb2a30a441e85d3b
c775c234fdac1e401c496a0576ebcfdc305d93e1
refs/heads/master
2020-03-11T04:17:17.525000
2018-04-16T16:51:31
2018-04-16T16:51:31
129,772,939
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package figurePainter4j; import java.awt.Color; import java.awt.Dimension; import java.awt.Point; //TODO make a nice example public class Main { public static void main(String[] args) { Dimension dimension = new Dimension(1920, 1080); FPCanvas canvas = new FPCanvas(dimension, Color.BLACK); FPJFrame frame = new FPJFrame(canvas, dimension); canvas.initialize(); FPRectangle rectangle1 = new FPRectangle(new Point(0, 500), new Dimension(1920,50), Color.WHITE); //FPRectangle rectangle2 = new FPRectangle(new Point(150, 250), new Dimension(100,200), Color.GREEN, true); canvas.paintFigure(rectangle1); //canvas.paintFigure(rectangle2); //canvas.repaint(); //Zeichnung z = new Zeichnung(); // z.zeichne(); try { Thread.sleep(1000); System.out.println(rectangle1.getLocation()); rectangle1.setLocation(new Point(0, 600)); System.out.println(rectangle1.getLocation()); rectangle1.setSize(new Dimension(1920, 100)); canvas.delete(); frame.setTitle("new Title"); canvas.paintFigure(rectangle1); //canvas.repaint(); //z.inSchwarzWeissAendern(); Thread.sleep(1000); canvas.delete(); //canvas.repaint(); //z.inFarbeAendern(); } catch (InterruptedException e) { e.printStackTrace(); } } }
UTF-8
Java
1,266
java
Main.java
Java
[]
null
[]
package figurePainter4j; import java.awt.Color; import java.awt.Dimension; import java.awt.Point; //TODO make a nice example public class Main { public static void main(String[] args) { Dimension dimension = new Dimension(1920, 1080); FPCanvas canvas = new FPCanvas(dimension, Color.BLACK); FPJFrame frame = new FPJFrame(canvas, dimension); canvas.initialize(); FPRectangle rectangle1 = new FPRectangle(new Point(0, 500), new Dimension(1920,50), Color.WHITE); //FPRectangle rectangle2 = new FPRectangle(new Point(150, 250), new Dimension(100,200), Color.GREEN, true); canvas.paintFigure(rectangle1); //canvas.paintFigure(rectangle2); //canvas.repaint(); //Zeichnung z = new Zeichnung(); // z.zeichne(); try { Thread.sleep(1000); System.out.println(rectangle1.getLocation()); rectangle1.setLocation(new Point(0, 600)); System.out.println(rectangle1.getLocation()); rectangle1.setSize(new Dimension(1920, 100)); canvas.delete(); frame.setTitle("new Title"); canvas.paintFigure(rectangle1); //canvas.repaint(); //z.inSchwarzWeissAendern(); Thread.sleep(1000); canvas.delete(); //canvas.repaint(); //z.inFarbeAendern(); } catch (InterruptedException e) { e.printStackTrace(); } } }
1,266
0.701422
0.654818
45
27.133333
22.943991
109
false
false
0
0
0
0
0
0
2.755556
false
false
10
c8ac19d49182c47c5790cc3e9531d3d8ed7ad046
32,384,053,480,775
55292bf50244b756ba3e67a9ff60354cf6f82b0d
/Exercicios/src/streams/Filter.java
7c1915019f64d2c44a44e5f56e0a44d52a173254
[]
no_license
diego-bernardesb/PrimeirosPassosEmJava
https://github.com/diego-bernardesb/PrimeirosPassosEmJava
745afaeef1ab464ee311ca1afeefd9fe0278968c
d5b6e102d460314f6593c2dd1877ffc533c6c74b
refs/heads/master
2023-09-03T18:40:48.661000
2021-10-25T15:49:52
2021-10-25T15:49:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package streams; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public class Filter { public static void main(String[] args) { Aluno a1 = new Aluno("Ana", 9.8); Aluno a2 = new Aluno("Bia", 7.8); Aluno a3 = new Aluno("Daniel", 4.8); Aluno a4 = new Aluno("Gui", 5.2); Aluno a5 = new Aluno("Rebeca", 6.4); Aluno a6 = new Aluno("Pedro", 9.2); Consumer<Object> print = System.out::println; List<Aluno> alunos = Arrays.asList(a1, a2, a3, a4, a5, a6); Predicate<Aluno> aprovado = a -> a.nota >= 7; Function<Aluno, String> saudacao = a -> "Parabéns " + a.nome + " você está aprovado(a) !"; alunos.stream() .filter(aprovado) //filtra todos os campos que atendem a condição criando uma nova array .map(saudacao) .forEach(print); } }
ISO-8859-1
Java
884
java
Filter.java
Java
[ { "context": "id main(String[] args) {\n\n\t\tAluno a1 = new Aluno(\"Ana\", 9.8);\n\t\tAluno a2 = new Aluno(\"Bia\", 7.8);\n\t\tAlu", "end": 269, "score": 0.999792218208313, "start": 266, "tag": "NAME", "value": "Ana" }, { "context": " = new Aluno(\"Ana\", 9.8);\n\t\tAluno a2 = new Aluno(\"Bia\", 7.8);\n\t\tAluno a3 = new Aluno(\"Daniel\", 4.8);\n\t\t", "end": 305, "score": 0.9998327493667603, "start": 302, "tag": "NAME", "value": "Bia" }, { "context": " = new Aluno(\"Bia\", 7.8);\n\t\tAluno a3 = new Aluno(\"Daniel\", 4.8);\n\t\tAluno a4 = new Aluno(\"Gui\", 5.2);\n\t\tAlu", "end": 344, "score": 0.9997921586036682, "start": 338, "tag": "NAME", "value": "Daniel" }, { "context": "new Aluno(\"Daniel\", 4.8);\n\t\tAluno a4 = new Aluno(\"Gui\", 5.2);\n\t\tAluno a5 = new Aluno(\"Rebeca\", 6.4);\n\t\t", "end": 380, "score": 0.9985247850418091, "start": 377, "tag": "NAME", "value": "Gui" }, { "context": " = new Aluno(\"Gui\", 5.2);\n\t\tAluno a5 = new Aluno(\"Rebeca\", 6.4);\n\t\tAluno a6 = new Aluno(\"Pedro\", 9.2);\n\n\t\t", "end": 419, "score": 0.9998316168785095, "start": 413, "tag": "NAME", "value": "Rebeca" }, { "context": "new Aluno(\"Rebeca\", 6.4);\n\t\tAluno a6 = new Aluno(\"Pedro\", 9.2);\n\n\t\tConsumer<Object> print = System.out::p", "end": 457, "score": 0.9998142123222351, "start": 452, "tag": "NAME", "value": "Pedro" } ]
null
[]
package streams; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public class Filter { public static void main(String[] args) { Aluno a1 = new Aluno("Ana", 9.8); Aluno a2 = new Aluno("Bia", 7.8); Aluno a3 = new Aluno("Daniel", 4.8); Aluno a4 = new Aluno("Gui", 5.2); Aluno a5 = new Aluno("Rebeca", 6.4); Aluno a6 = new Aluno("Pedro", 9.2); Consumer<Object> print = System.out::println; List<Aluno> alunos = Arrays.asList(a1, a2, a3, a4, a5, a6); Predicate<Aluno> aprovado = a -> a.nota >= 7; Function<Aluno, String> saudacao = a -> "Parabéns " + a.nome + " você está aprovado(a) !"; alunos.stream() .filter(aprovado) //filtra todos os campos que atendem a condição criando uma nova array .map(saudacao) .forEach(print); } }
884
0.665529
0.637088
33
25.636364
24.160847
92
false
false
0
0
0
0
0
0
2
false
false
10
632e2422c12cfa3396d90927c4d86d7a1bc8f9fe
38,585,986,211,405
eb6591fe1de24487d9193d0e8cc272c6814bd7cb
/src/changeofResponsability/DespacharSolicitud.java
0d522dcfd7652cc627d56387e8e8525bf7ccd626
[]
no_license
angreyes/ArquitecturaS
https://github.com/angreyes/ArquitecturaS
57378d8fbc8d8567763d107666a98a4275dfc327
0d81101a8295a65a48976a3ec451f2afbde65bd1
refs/heads/master
2020-05-20T00:19:57.450000
2015-04-05T23:57:35
2015-04-05T23:57:35
32,524,050
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 changeofResponsability; /** * * @author angie */ public class DespacharSolicitud implements Task { private Task next; @Override public Task getnext() { return next; } @Override public void estadoSolicitud(int solicitud) { // despachar soliictud if (solicitud >=1000) System.out.println("La solicitud N° " + solicitud + " fue aprobada, Felicitaciones!"); } @Override public void setnext(Task tarea) { this.next = tarea; } }
UTF-8
Java
742
java
DespacharSolicitud.java
Java
[ { "context": "age changeofResponsability;\r\n\r\n/**\r\n *\r\n * @author angie\r\n */\r\npublic class DespacharSolicitud implements ", "end": 250, "score": 0.999221682548523, "start": 245, "tag": "USERNAME", "value": "angie" } ]
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 changeofResponsability; /** * * @author angie */ public class DespacharSolicitud implements Task { private Task next; @Override public Task getnext() { return next; } @Override public void estadoSolicitud(int solicitud) { // despachar soliictud if (solicitud >=1000) System.out.println("La solicitud N° " + solicitud + " fue aprobada, Felicitaciones!"); } @Override public void setnext(Task tarea) { this.next = tarea; } }
742
0.616734
0.611336
32
21.15625
25.062559
98
false
false
0
0
0
0
0
0
0.28125
false
false
10
36eeede51ee22e47e1496f6721ece2408e3b57c2
39,539,468,928,119
5113ec6e0eb241cef2c8101061569367ef7ecf34
/src/main/java/com/demo/www/springbootdemo/module/mongdb/EcosSytemEntity.java
1f8ea7553fafc692ae79d66f6dfda587a398418a
[]
no_license
chenrushui/SpringBootProject
https://github.com/chenrushui/SpringBootProject
0e2c2cd1e1f7704ed42b82800d385c1f0f9bf5b5
d68320327b4110ba64710ab3fd9b57182137a237
refs/heads/master
2022-07-09T11:34:04.175000
2020-11-13T02:25:06
2020-11-13T02:25:06
177,903,814
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.www.springbootdemo.module.mongdb; /** * Created on 2019/10/21 17:45 * author:crs * Description:XXX */ public class EcosSytemEntity { private String adminCaption; private String adminId; //生态圈中包含的机构 private String hierarchy; //生态圈名称 private String name; public String getAdminCaption() { return adminCaption; } public void setAdminCaption(String adminCaption) { this.adminCaption = adminCaption; } public String getAdminId() { return adminId; } public void setAdminId(String adminId) { this.adminId = adminId; } public String getHierarchy() { return hierarchy; } public void setHierarchy(String hierarchy) { this.hierarchy = hierarchy; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "EcosSytemEntity{" + "adminCaption='" + adminCaption + '\'' + ", adminId='" + adminId + '\'' + ", hierarchy='" + hierarchy + '\'' + ", name='" + name + '\'' + '}'; } }
UTF-8
Java
1,256
java
EcosSytemEntity.java
Java
[ { "context": "db;\n\n/**\n * Created on 2019/10/21 17:45\n * author:crs\n * Description:XXX\n */\npublic class EcosSytemEnti", "end": 100, "score": 0.9991920590400696, "start": 97, "tag": "USERNAME", "value": "crs" } ]
null
[]
package com.demo.www.springbootdemo.module.mongdb; /** * Created on 2019/10/21 17:45 * author:crs * Description:XXX */ public class EcosSytemEntity { private String adminCaption; private String adminId; //生态圈中包含的机构 private String hierarchy; //生态圈名称 private String name; public String getAdminCaption() { return adminCaption; } public void setAdminCaption(String adminCaption) { this.adminCaption = adminCaption; } public String getAdminId() { return adminId; } public void setAdminId(String adminId) { this.adminId = adminId; } public String getHierarchy() { return hierarchy; } public void setHierarchy(String hierarchy) { this.hierarchy = hierarchy; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "EcosSytemEntity{" + "adminCaption='" + adminCaption + '\'' + ", adminId='" + adminId + '\'' + ", hierarchy='" + hierarchy + '\'' + ", name='" + name + '\'' + '}'; } }
1,256
0.563518
0.553746
57
20.543859
17.228159
56
false
false
0
0
0
0
0
0
0.298246
false
false
10
59b4e54918faba3439bbfd3ec5fbe55d26f693c4
35,837,207,160,466
33abd60d0a0542d0d3310af680e7e9848094a6f0
/src/test/java/leetCode/medium/LeetCode116.java
f0ec9009d876ec5eac09e9d5b6dcc9a8c535a39a
[]
no_license
bestchenwu/SparkStudy
https://github.com/bestchenwu/SparkStudy
ceefb42c3c65743ee4e0cfeffe0feb3f21ab7e11
93b4a970ed90269bbcfbee0aca047ffde2e2bfbf
refs/heads/master
2023-06-22T00:15:08.062000
2023-06-16T21:13:40
2023-06-16T21:13:40
163,280,000
0
0
null
false
2023-04-21T20:43:42
2018-12-27T10:17:14
2021-11-30T09:47:02
2023-04-21T20:43:42
3,316
0
0
7
Java
false
false
package leetCode.medium; import org.junit.Test; import java.util.ArrayList; import java.util.List; //给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: // // //struct Node { // int val; // Node *left; // Node *right; // Node *next; //} // // 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 // // 初始状态下,所有 next 指针都被设置为 NULL。 // // // // 进阶: // // // 你只能使用常量级额外空间。 // 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。 // // // // // 示例: // // // // //输入:root = [1,2,3,4,5,6,7] //输出:[1,#,2,3,#,4,5,6,7,#] //解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 //next 指针连接,'#' 标志着每一层的结束。 public class LeetCode116 { private void helpConnect(List<LinkTreeNode> nodeList) { if (nodeList.isEmpty()) { return; } List<LinkTreeNode> newNodeList = new ArrayList<>(); int size = nodeList.size(); for (int i = 0; i < size; i++) { LinkTreeNode tmp = nodeList.get(i); if (i + 1 < size) { tmp.next = nodeList.get(i + 1); } else { tmp.next = null; } if (tmp.left != null) { newNodeList.add(tmp.left); } if (tmp.right != null) { newNodeList.add(tmp.right); } } helpConnect(newNodeList); } /** * 广度优先遍历 * * @param root * @return */ public LinkTreeNode connect(LinkTreeNode root) { if(root == null){ return null; } List<LinkTreeNode> nodeList = new ArrayList<>(); nodeList.add(root); helpConnect(nodeList); return root; } @Test public void testConnect() { LinkTreeNode root = new LinkTreeNode(1); root.left = new LinkTreeNode(2, new LinkTreeNode(4), new LinkTreeNode(5)); root.right = new LinkTreeNode(3, new LinkTreeNode(6), new LinkTreeNode(7)); LinkTreeNode newRoot = connect(root); System.out.println("newRoot=" + newRoot); } }
UTF-8
Java
2,540
java
LeetCode116.java
Java
[]
null
[]
package leetCode.medium; import org.junit.Test; import java.util.ArrayList; import java.util.List; //给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: // // //struct Node { // int val; // Node *left; // Node *right; // Node *next; //} // // 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 // // 初始状态下,所有 next 指针都被设置为 NULL。 // // // // 进阶: // // // 你只能使用常量级额外空间。 // 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。 // // // // // 示例: // // // // //输入:root = [1,2,3,4,5,6,7] //输出:[1,#,2,3,#,4,5,6,7,#] //解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化的输出按层序遍历排列,同一层节点由 //next 指针连接,'#' 标志着每一层的结束。 public class LeetCode116 { private void helpConnect(List<LinkTreeNode> nodeList) { if (nodeList.isEmpty()) { return; } List<LinkTreeNode> newNodeList = new ArrayList<>(); int size = nodeList.size(); for (int i = 0; i < size; i++) { LinkTreeNode tmp = nodeList.get(i); if (i + 1 < size) { tmp.next = nodeList.get(i + 1); } else { tmp.next = null; } if (tmp.left != null) { newNodeList.add(tmp.left); } if (tmp.right != null) { newNodeList.add(tmp.right); } } helpConnect(newNodeList); } /** * 广度优先遍历 * * @param root * @return */ public LinkTreeNode connect(LinkTreeNode root) { if(root == null){ return null; } List<LinkTreeNode> nodeList = new ArrayList<>(); nodeList.add(root); helpConnect(nodeList); return root; } @Test public void testConnect() { LinkTreeNode root = new LinkTreeNode(1); root.left = new LinkTreeNode(2, new LinkTreeNode(4), new LinkTreeNode(5)); root.right = new LinkTreeNode(3, new LinkTreeNode(6), new LinkTreeNode(7)); LinkTreeNode newRoot = connect(root); System.out.println("newRoot=" + newRoot); } }
2,540
0.545768
0.53248
92
21.086956
20.421989
83
false
false
0
0
0
0
0
0
0.521739
false
false
10
b691de74f6867c80b2d11eec00655f1c0544a0dd
35,390,530,565,954
3b69012b9b30b172447e521090f49318fc5c510d
/ChessJButton.java
a0ee7f4ab13dcf9f1304349825b78da92051f768
[]
no_license
ask7708/JavaGuiChess
https://github.com/ask7708/JavaGuiChess
c887cf88afabcba38f29daf0b3e17d03fa48e615
7800e8ddaf0afcecfb2c2038f14497a989a57035
refs/heads/master
2016-09-05T13:18:02.976000
2015-05-07T04:54:17
2015-05-07T04:54:17
35,199,563
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.swing.JButton; /* * * $Id: ChessJButton.java,v 1.1 2014/12/10 20:19:08 ask7708 Exp $ * * $Log: ChessJButton.java,v $ * Revision 1.1 2014/12/10 20:19:08 ask7708 * Created helper class for JButtons * * */ /** * Adds a JButton to a 1D grid. This class takes in position and treats it as a * corresponding position on a 1D grid. * * @author Arshdeep Khalsa * */ public class ChessJButton extends JButton { /** * The position of the button on the 1D grid. * */ Integer pos; /** * Sets the given position to the corresponding button's position. * * @param location */ public ChessJButton(int location) { this.pos = location; } /** * Returns the position of the button. * * @return position on 1D grid. */ public Integer getPos() { return pos; } }
UTF-8
Java
819
java
ChessJButton.java
Java
[ { "context": "orresponding position on a 1D grid.\n * \n * @author Arshdeep Khalsa\n * \n */\npublic class ChessJButton extends JButton", "end": 386, "score": 0.9998946785926819, "start": 371, "tag": "NAME", "value": "Arshdeep Khalsa" } ]
null
[]
import javax.swing.JButton; /* * * $Id: ChessJButton.java,v 1.1 2014/12/10 20:19:08 ask7708 Exp $ * * $Log: ChessJButton.java,v $ * Revision 1.1 2014/12/10 20:19:08 ask7708 * Created helper class for JButtons * * */ /** * Adds a JButton to a 1D grid. This class takes in position and treats it as a * corresponding position on a 1D grid. * * @author <NAME> * */ public class ChessJButton extends JButton { /** * The position of the button on the 1D grid. * */ Integer pos; /** * Sets the given position to the corresponding button's position. * * @param location */ public ChessJButton(int location) { this.pos = location; } /** * Returns the position of the button. * * @return position on 1D grid. */ public Integer getPos() { return pos; } }
810
0.642247
0.588523
47
16.425531
20.274441
79
false
false
0
0
0
0
0
0
0.617021
false
false
10
ca7a418d21fc09cb3fef70bad6f29c888fac5349
34,454,227,705,326
b47f4c0e24cfa2cc5c746d6bc2eb233de5b00126
/app/src/main/java/cn/cassia/sugar/land/ui/map/MapModule.java
03a7869f30a0dd15ae0cb43d10c94139acb4bfa5
[]
no_license
HYTCTony/land
https://github.com/HYTCTony/land
0ee0b42d2cd1bbec14daed9c239f388cdbbefdce
f5ace6056e67eb8c7cc50b272061eb1c2b9ec5d7
refs/heads/master
2020-07-24T18:51:05.141000
2019-09-12T09:34:27
2019-09-12T09:34:27
208,014,626
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.cassia.sugar.land.ui.map; import cn.cassia.sugar.land.mvp.BaseModule; /** * Created by qingjie on 2018-05-25.0025. */ public class MapModule extends BaseModule implements MapContract.IMapModule { @Override public void getData(int uid, String pwd, MapPresenter presenter) { } }
UTF-8
Java
306
java
MapModule.java
Java
[ { "context": "ssia.sugar.land.mvp.BaseModule;\n\n/**\n * Created by qingjie on 2018-05-25.0025.\n */\npublic class MapModule ex", "end": 108, "score": 0.9995706081390381, "start": 101, "tag": "USERNAME", "value": "qingjie" } ]
null
[]
package cn.cassia.sugar.land.ui.map; import cn.cassia.sugar.land.mvp.BaseModule; /** * Created by qingjie on 2018-05-25.0025. */ public class MapModule extends BaseModule implements MapContract.IMapModule { @Override public void getData(int uid, String pwd, MapPresenter presenter) { } }
306
0.732026
0.69281
14
20.857143
26.427414
77
false
false
0
0
0
0
0
0
0.285714
false
false
10
fa698e49f4bd9998a3715b2f0b9edec19f0a3cc4
6,665,789,253,101
9bcaa36726479edab8cc475f9837830744b82f98
/DemoOld/modules/annotations/src/main/java/com/example/CustomAnno.java
bed08d21e61762f32ff1ca05337d60f9e0d62b7b
[ "MIT" ]
permissive
JoS-Marvel/android1
https://github.com/JoS-Marvel/android1
cd1ce3cd71a9584d9823450e8c5e416252f2812f
18e5c057aca4abf6aab30a87c955ea746c44056d
refs/heads/master
2023-06-21T10:46:02.199000
2021-07-23T13:28:01
2021-07-23T13:28:01
381,923,517
0
1
MIT
true
2021-07-01T05:47:05
2021-07-01T05:47:04
2021-06-29T17:47:14
2021-06-29T17:47:11
6,169
0
0
0
null
false
false
package com.example; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by ttdevs * 2017-08-06 (android) * https://github.com/ttdevs */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CustomAnno { }
UTF-8
Java
363
java
CustomAnno.java
Java
[ { "context": "rt java.lang.annotation.Target;\n\n/**\n * Created by ttdevs\n * 2017-08-06 (android)\n * https://github.com/ttd", "end": 208, "score": 0.9995477199554443, "start": 202, "tag": "USERNAME", "value": "ttdevs" }, { "context": "evs\n * 2017-08-06 (android)\n * https://github.com/ttdevs\n */\n@Retention(RetentionPolicy.RUNTIME)\n@Target(E", "end": 261, "score": 0.9993158578872681, "start": 255, "tag": "USERNAME", "value": "ttdevs" } ]
null
[]
package com.example; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by ttdevs * 2017-08-06 (android) * https://github.com/ttdevs */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface CustomAnno { }
363
0.779614
0.757576
16
21.6875
15.135715
44
false
false
0
0
0
0
0
0
0.3125
false
false
10
565aee35c1ec87b1ec3078791788e083e4c2d809
1,829,656,082,660
23521342b047dd06211fccdc3a8f56924d01a94c
/common-foundation/src/main/java/com/ezcoding/common/foundation/core/tools/verification/ImageVerificationCode.java
603537b31477464c59ae706f917705e1f174b407
[]
no_license
MinChiang/ezcoding
https://github.com/MinChiang/ezcoding
0fc18b88ee27e9bf62d4ca2f8d7a3d91439377b3
3545a6216039976a657f115393357baea0cf3f12
refs/heads/master
2023-06-19T01:30:44.641000
2021-07-19T10:28:16
2021-07-19T10:28:16
372,782,300
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ezcoding.common.foundation.core.tools.verification; import java.util.Objects; /** * @author MinChiang * @version 1.0.0 * @date 2018-07-14 17:08 */ public class ImageVerificationCode extends VerificationCode { private static final long serialVersionUID = -6551416325744919047L; private final int height; private final int width; private final int codeLength; public ImageVerificationCode(char[] code, byte[] data, int height, int width, int codeLength) { super(code, data); this.height = height; this.width = width; this.codeLength = codeLength; } public int getHeight() { return height; } public int getWidth() { return width; } public int getCodeLength() { return codeLength; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ImageVerificationCode that = (ImageVerificationCode) o; return height == that.height && width == that.width && codeLength == that.codeLength; } @Override public int hashCode() { return Objects.hash(super.hashCode(), height, width, codeLength); } }
UTF-8
Java
1,401
java
ImageVerificationCode.java
Java
[ { "context": "cation;\n\nimport java.util.Objects;\n\n/**\n * @author MinChiang\n * @version 1.0.0\n * @date 2018-07-14 17:08\n */\np", "end": 116, "score": 0.9978509545326233, "start": 107, "tag": "NAME", "value": "MinChiang" } ]
null
[]
package com.ezcoding.common.foundation.core.tools.verification; import java.util.Objects; /** * @author MinChiang * @version 1.0.0 * @date 2018-07-14 17:08 */ public class ImageVerificationCode extends VerificationCode { private static final long serialVersionUID = -6551416325744919047L; private final int height; private final int width; private final int codeLength; public ImageVerificationCode(char[] code, byte[] data, int height, int width, int codeLength) { super(code, data); this.height = height; this.width = width; this.codeLength = codeLength; } public int getHeight() { return height; } public int getWidth() { return width; } public int getCodeLength() { return codeLength; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ImageVerificationCode that = (ImageVerificationCode) o; return height == that.height && width == that.width && codeLength == that.codeLength; } @Override public int hashCode() { return Objects.hash(super.hashCode(), height, width, codeLength); } }
1,401
0.589579
0.56531
59
22.745762
21.753311
99
false
false
0
0
0
0
0
0
0.491525
false
false
10
bf7f70889df85612e9b59be9306fba38229aba96
11,596,411,702,686
1268b5ad8b7fff8114e7b015326e4bb1a1a772a2
/src/ru/progwards/java2/lessons/basetypes/BiDirList.java
ea4fe3f04b2aad86d1990c77eef2a68011a66947
[]
no_license
Ikastru/java1
https://github.com/Ikastru/java1
3012dbd92318d207ecdf333738e426b1389e0cce
6249f5b98cf3d3528578d878510dcfd665b8c3e6
refs/heads/master
2023-01-05T21:34:05.103000
2020-10-24T17:41:48
2020-10-24T17:41:48
255,942,409
0
1
null
false
2020-10-13T23:56:51
2020-04-15T14:29:02
2020-10-12T14:58:46
2020-10-13T23:56:49
5,428
0
1
2
Java
false
false
package ru.progwards.java2.lessons.basetypes; /** * Реализовать класс BiDirList - двунаправленный связный список * * Методы * * 1.1 public void addLast(T item) - добавить в конец списка * * 1.2 public void addFirst(T item)- добавить в начало списка * * 1.3 public void remove(T item) - удалить * * 1.4 public T at(int i) - получить элемент по индексу * * 1.5 public int size() - получить количество элементов * * 1.6 public static<T> BiDirList<T> from(T[] array) - конструктор из массива * * 1.7 public static<T> BiDirList<T> of(T...array) - конструктор из массива * * 1.8 public static void toArray(T[] array) - скопировать в массив * * 1.9 public Iterator<BiDirList<T>> getIterator() - получить итератор */ import java.util.Iterator; import java.util.NoSuchElementException; public class BiDirList<T extends Comparable> implements Iterable<T> { private int quan; private ListItem<T> first; private ListItem<T> last; BiDirList() { quan = 0; first = null; last = null; } BiDirList(T data) { first = last = new ListItem<T>(data); quan = 1; } public static<T extends Comparable> BiDirList<T> from(T[] array){ BiDirList<T> list = new BiDirList<>(); for (T element : array) list.addLast(element); return list; } public static<T extends Comparable> BiDirList<T> of(T...array){ BiDirList<T> list = new BiDirList<>(); for (int i = 0; i < array.length ; i++) list.addLast(array[i]); return list; } public void toArray(T[] array){ for (int i = 0; i < array.length ; i++) { array[i++] = this.at(i); } } public void addLast(T data) { ListItem<T> li = new ListItem<T>(data); if (first == null) { first = li; last = li; } else { last.setNext(li); li.setPrev(last); last = li; } quan++; } public void addFirst(T data) { ListItem<T> li = new ListItem<T>(data); if (first == null) { first = li; last = li; } else { first.setPrev(li); li.setNext(first); first = li; } quan++; } public ListItem<T> get(T item) { if (item.compareTo(quan)==1) { return null; } else { ListItem<T> li = first; for (int j=1; item.compareTo(j)==1; j++) { li = li.getNext(); } return li; } } public T at(int i){ if (i>quan) { return null; } else { ListItem<T> li = first; for (int j=1; j<i; j++) { li = li.getNext(); } return (T)li; } } public void remove(T item) { if (item.compareTo(quan) ==-1 || item.compareTo(quan) ==0) { ListItem<T> li = get(item); ListItem<T> prev = li.getPrev(); ListItem<T> next = li.getNext(); if (prev != null) { prev.setNext(next); } if (next != null) { next.setPrev(prev); if (item.compareTo(1) ==0) { first = next; } } quan--; } } public int getSize() { return quan; } public ListItem<T> getFirst() { return first; } public ListItem<T> getLast() { return last; } public Iterator<BiDirList<T>> getIterator(){ return new IteratorNew(first); } class IteratorNew<T> implements Iterator<T> { ListItem<T> elem; IteratorNew(ListItem<T> elem){ this.elem = elem; } public boolean hasNext() { if (first == null) return false; if (elem == null) return false; return true; } public T next() { if (first == null) throw new NoSuchElementException(); T rezult = elem.data; elem = elem.getNext(); return rezult; } } @Override public Iterator<T> iterator() { return new IteratorNew<>(first); } }
UTF-8
Java
4,571
java
BiDirList.java
Java
[]
null
[]
package ru.progwards.java2.lessons.basetypes; /** * Реализовать класс BiDirList - двунаправленный связный список * * Методы * * 1.1 public void addLast(T item) - добавить в конец списка * * 1.2 public void addFirst(T item)- добавить в начало списка * * 1.3 public void remove(T item) - удалить * * 1.4 public T at(int i) - получить элемент по индексу * * 1.5 public int size() - получить количество элементов * * 1.6 public static<T> BiDirList<T> from(T[] array) - конструктор из массива * * 1.7 public static<T> BiDirList<T> of(T...array) - конструктор из массива * * 1.8 public static void toArray(T[] array) - скопировать в массив * * 1.9 public Iterator<BiDirList<T>> getIterator() - получить итератор */ import java.util.Iterator; import java.util.NoSuchElementException; public class BiDirList<T extends Comparable> implements Iterable<T> { private int quan; private ListItem<T> first; private ListItem<T> last; BiDirList() { quan = 0; first = null; last = null; } BiDirList(T data) { first = last = new ListItem<T>(data); quan = 1; } public static<T extends Comparable> BiDirList<T> from(T[] array){ BiDirList<T> list = new BiDirList<>(); for (T element : array) list.addLast(element); return list; } public static<T extends Comparable> BiDirList<T> of(T...array){ BiDirList<T> list = new BiDirList<>(); for (int i = 0; i < array.length ; i++) list.addLast(array[i]); return list; } public void toArray(T[] array){ for (int i = 0; i < array.length ; i++) { array[i++] = this.at(i); } } public void addLast(T data) { ListItem<T> li = new ListItem<T>(data); if (first == null) { first = li; last = li; } else { last.setNext(li); li.setPrev(last); last = li; } quan++; } public void addFirst(T data) { ListItem<T> li = new ListItem<T>(data); if (first == null) { first = li; last = li; } else { first.setPrev(li); li.setNext(first); first = li; } quan++; } public ListItem<T> get(T item) { if (item.compareTo(quan)==1) { return null; } else { ListItem<T> li = first; for (int j=1; item.compareTo(j)==1; j++) { li = li.getNext(); } return li; } } public T at(int i){ if (i>quan) { return null; } else { ListItem<T> li = first; for (int j=1; j<i; j++) { li = li.getNext(); } return (T)li; } } public void remove(T item) { if (item.compareTo(quan) ==-1 || item.compareTo(quan) ==0) { ListItem<T> li = get(item); ListItem<T> prev = li.getPrev(); ListItem<T> next = li.getNext(); if (prev != null) { prev.setNext(next); } if (next != null) { next.setPrev(prev); if (item.compareTo(1) ==0) { first = next; } } quan--; } } public int getSize() { return quan; } public ListItem<T> getFirst() { return first; } public ListItem<T> getLast() { return last; } public Iterator<BiDirList<T>> getIterator(){ return new IteratorNew(first); } class IteratorNew<T> implements Iterator<T> { ListItem<T> elem; IteratorNew(ListItem<T> elem){ this.elem = elem; } public boolean hasNext() { if (first == null) return false; if (elem == null) return false; return true; } public T next() { if (first == null) throw new NoSuchElementException(); T rezult = elem.data; elem = elem.getNext(); return rezult; } } @Override public Iterator<T> iterator() { return new IteratorNew<>(first); } }
4,571
0.49241
0.485281
178
23.421349
18.944538
77
false
false
0
0
0
0
0
0
0.398876
false
false
10
5a488176280cf0d62d1ac51ec416e6e4552e47dd
18,373,870,128,574
cdb762ef466b0fe1df7ec484d009f30503a4cb10
/web/src/gnete/card/dao/impl/.svn/text-base/IcCardParaModifyRegDAOImpl.java.svn-base
80663df5beba2a3c8f5cbd358f16d0de6f5f7b73
[]
no_license
GoogleClick/shangyingtong
https://github.com/GoogleClick/shangyingtong
3c8a6a8e4bd256c9cff926fe88df959496e72e27
5b500dfdaab623b27f1a256ab9fa7cce0d73b443
refs/heads/master
2018-01-07T07:14:03.869000
2018-01-06T10:37:42
2018-01-06T10:37:42
32,841,163
5
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package gnete.card.dao.impl; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import flink.util.Paginater; import gnete.card.dao.IcCardParaModifyRegDAO; import gnete.card.entity.IcCardParaModifyReg; @Repository public class IcCardParaModifyRegDAOImpl extends BaseDAOIbatisImpl implements IcCardParaModifyRegDAO { public String getNamespace() { return "IcCardParaModifyReg"; } public Paginater findPage(Map<String, Object> params, int pageNumber, int pageSize) { return this.queryForPage("findPage", params, pageNumber, pageSize); } public List<IcCardParaModifyReg> findList(Map<String, Object> params) { return this.queryForList("findPage", params); } public IcCardParaModifyReg findByRandomSessionId(String randomSessionId) { return (IcCardParaModifyReg) this.queryForObject("findByRandomSessionId", randomSessionId); } }
UTF-8
Java
949
IcCardParaModifyRegDAOImpl.java.svn-base
Java
[]
null
[]
package gnete.card.dao.impl; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import flink.util.Paginater; import gnete.card.dao.IcCardParaModifyRegDAO; import gnete.card.entity.IcCardParaModifyReg; @Repository public class IcCardParaModifyRegDAOImpl extends BaseDAOIbatisImpl implements IcCardParaModifyRegDAO { public String getNamespace() { return "IcCardParaModifyReg"; } public Paginater findPage(Map<String, Object> params, int pageNumber, int pageSize) { return this.queryForPage("findPage", params, pageNumber, pageSize); } public List<IcCardParaModifyReg> findList(Map<String, Object> params) { return this.queryForList("findPage", params); } public IcCardParaModifyReg findByRandomSessionId(String randomSessionId) { return (IcCardParaModifyReg) this.queryForObject("findByRandomSessionId", randomSessionId); } }
949
0.758693
0.758693
31
29.645161
30.625257
101
false
false
0
0
0
0
0
0
0.806452
false
false
10
3eb6c6c6404371fda7b7ed868d01ecbd01543a86
23,364,622,101,816
70daf318d027f371ada3abeaaa31dd47651640d7
/src/action/inw/client/SpcOdiDspnd.java
c12e976e0eafcdcd15832c642962e9e95e6a6656
[]
no_license
wangqing123654/web
https://github.com/wangqing123654/web
00613f6db653562e2e8edc14327649dc18b2aae6
bd447877400291d3f35715ca9c7c7b1e79653531
refs/heads/master
2023-04-07T15:23:34.705000
2020-11-02T10:10:57
2020-11-02T10:10:57
309,329,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package action.inw.client; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for spcOdiDspnd complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="spcOdiDspnd"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="barCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="barcode1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="barcode2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="barcode3" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="batchCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="billFlg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="boxEslId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="cancelrsnCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="caseNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="cashierCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="cashierDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="dcDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="dcNsCheckDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="dosageQty" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="dosageUnit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="execDeptCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="execNote" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ibsCaseNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ibsCaseNoSeq" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="intgmedNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="invCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="mediQty" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="mediUnit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecCodeReal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDateReal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDcCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDcDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsUser" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nurseDispenseFlg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="optDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="optTerm" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="optUser" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderDatetime" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderSeq" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="phaDispenseCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDispenseDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDispenseNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDosageCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDosageDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaRetnCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaRetnDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="serviceLevel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="stopcheckDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="stopcheckUser" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="takemedNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="takemedOrg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="totAmt" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="transmitRsnCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="treatEndTime" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="treatStartTime" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "spcOdiDspnd", propOrder = { "barCode", "barcode1", "barcode2", "barcode3", "batchCode", "billFlg", "boxEslId", "cancelrsnCode", "caseNo", "cashierCode", "cashierDate", "dcDate", "dcNsCheckDate", "dosageQty", "dosageUnit", "execDeptCode", "execNote", "ibsCaseNo", "ibsCaseNoSeq", "intgmedNo", "invCode", "mediQty", "mediUnit", "nsExecCode", "nsExecCodeReal", "nsExecDate", "nsExecDateReal", "nsExecDcCode", "nsExecDcDate", "nsUser", "nurseDispenseFlg", "optDate", "optTerm", "optUser", "orderCode", "orderDate", "orderDatetime", "orderNo", "orderSeq", "phaDispenseCode", "phaDispenseDate", "phaDispenseNo", "phaDosageCode", "phaDosageDate", "phaRetnCode", "phaRetnDate", "serviceLevel", "stopcheckDate", "stopcheckUser", "takemedNo", "takemedOrg", "totAmt", "transmitRsnCode", "treatEndTime", "treatStartTime" }) public class SpcOdiDspnd { protected String barCode; protected String barcode1; protected String barcode2; protected String barcode3; protected String batchCode; protected String billFlg; protected String boxEslId; protected String cancelrsnCode; protected String caseNo; protected String cashierCode; protected String cashierDate; protected String dcDate; protected String dcNsCheckDate; protected double dosageQty; protected String dosageUnit; protected String execDeptCode; protected String execNote; protected String ibsCaseNo; protected String ibsCaseNoSeq; protected String intgmedNo; protected String invCode; protected double mediQty; protected String mediUnit; protected String nsExecCode; protected String nsExecCodeReal; protected String nsExecDate; protected String nsExecDateReal; protected String nsExecDcCode; protected String nsExecDcDate; protected String nsUser; protected String nurseDispenseFlg; protected String optDate; protected String optTerm; protected String optUser; protected String orderCode; protected String orderDate; protected String orderDatetime; protected String orderNo; protected int orderSeq; protected String phaDispenseCode; protected String phaDispenseDate; protected String phaDispenseNo; protected String phaDosageCode; protected String phaDosageDate; protected String phaRetnCode; protected String phaRetnDate; protected String serviceLevel; protected String stopcheckDate; protected String stopcheckUser; protected String takemedNo; protected String takemedOrg; protected double totAmt; protected String transmitRsnCode; protected String treatEndTime; protected String treatStartTime; /** * Gets the value of the barCode property. * * @return * possible object is * {@link String } * */ public String getBarCode() { return barCode; } /** * Sets the value of the barCode property. * * @param value * allowed object is * {@link String } * */ public void setBarCode(String value) { this.barCode = value; } /** * Gets the value of the barcode1 property. * * @return * possible object is * {@link String } * */ public String getBarcode1() { return barcode1; } /** * Sets the value of the barcode1 property. * * @param value * allowed object is * {@link String } * */ public void setBarcode1(String value) { this.barcode1 = value; } /** * Gets the value of the barcode2 property. * * @return * possible object is * {@link String } * */ public String getBarcode2() { return barcode2; } /** * Sets the value of the barcode2 property. * * @param value * allowed object is * {@link String } * */ public void setBarcode2(String value) { this.barcode2 = value; } /** * Gets the value of the barcode3 property. * * @return * possible object is * {@link String } * */ public String getBarcode3() { return barcode3; } /** * Sets the value of the barcode3 property. * * @param value * allowed object is * {@link String } * */ public void setBarcode3(String value) { this.barcode3 = value; } /** * Gets the value of the batchCode property. * * @return * possible object is * {@link String } * */ public String getBatchCode() { return batchCode; } /** * Sets the value of the batchCode property. * * @param value * allowed object is * {@link String } * */ public void setBatchCode(String value) { this.batchCode = value; } /** * Gets the value of the billFlg property. * * @return * possible object is * {@link String } * */ public String getBillFlg() { return billFlg; } /** * Sets the value of the billFlg property. * * @param value * allowed object is * {@link String } * */ public void setBillFlg(String value) { this.billFlg = value; } /** * Gets the value of the boxEslId property. * * @return * possible object is * {@link String } * */ public String getBoxEslId() { return boxEslId; } /** * Sets the value of the boxEslId property. * * @param value * allowed object is * {@link String } * */ public void setBoxEslId(String value) { this.boxEslId = value; } /** * Gets the value of the cancelrsnCode property. * * @return * possible object is * {@link String } * */ public String getCancelrsnCode() { return cancelrsnCode; } /** * Sets the value of the cancelrsnCode property. * * @param value * allowed object is * {@link String } * */ public void setCancelrsnCode(String value) { this.cancelrsnCode = value; } /** * Gets the value of the caseNo property. * * @return * possible object is * {@link String } * */ public String getCaseNo() { return caseNo; } /** * Sets the value of the caseNo property. * * @param value * allowed object is * {@link String } * */ public void setCaseNo(String value) { this.caseNo = value; } /** * Gets the value of the cashierCode property. * * @return * possible object is * {@link String } * */ public String getCashierCode() { return cashierCode; } /** * Sets the value of the cashierCode property. * * @param value * allowed object is * {@link String } * */ public void setCashierCode(String value) { this.cashierCode = value; } /** * Gets the value of the cashierDate property. * * @return * possible object is * {@link String } * */ public String getCashierDate() { return cashierDate; } /** * Sets the value of the cashierDate property. * * @param value * allowed object is * {@link String } * */ public void setCashierDate(String value) { this.cashierDate = value; } /** * Gets the value of the dcDate property. * * @return * possible object is * {@link String } * */ public String getDcDate() { return dcDate; } /** * Sets the value of the dcDate property. * * @param value * allowed object is * {@link String } * */ public void setDcDate(String value) { this.dcDate = value; } /** * Gets the value of the dcNsCheckDate property. * * @return * possible object is * {@link String } * */ public String getDcNsCheckDate() { return dcNsCheckDate; } /** * Sets the value of the dcNsCheckDate property. * * @param value * allowed object is * {@link String } * */ public void setDcNsCheckDate(String value) { this.dcNsCheckDate = value; } /** * Gets the value of the dosageQty property. * */ public double getDosageQty() { return dosageQty; } /** * Sets the value of the dosageQty property. * */ public void setDosageQty(double value) { this.dosageQty = value; } /** * Gets the value of the dosageUnit property. * * @return * possible object is * {@link String } * */ public String getDosageUnit() { return dosageUnit; } /** * Sets the value of the dosageUnit property. * * @param value * allowed object is * {@link String } * */ public void setDosageUnit(String value) { this.dosageUnit = value; } /** * Gets the value of the execDeptCode property. * * @return * possible object is * {@link String } * */ public String getExecDeptCode() { return execDeptCode; } /** * Sets the value of the execDeptCode property. * * @param value * allowed object is * {@link String } * */ public void setExecDeptCode(String value) { this.execDeptCode = value; } /** * Gets the value of the execNote property. * * @return * possible object is * {@link String } * */ public String getExecNote() { return execNote; } /** * Sets the value of the execNote property. * * @param value * allowed object is * {@link String } * */ public void setExecNote(String value) { this.execNote = value; } /** * Gets the value of the ibsCaseNo property. * * @return * possible object is * {@link String } * */ public String getIbsCaseNo() { return ibsCaseNo; } /** * Sets the value of the ibsCaseNo property. * * @param value * allowed object is * {@link String } * */ public void setIbsCaseNo(String value) { this.ibsCaseNo = value; } /** * Gets the value of the ibsCaseNoSeq property. * * @return * possible object is * {@link String } * */ public String getIbsCaseNoSeq() { return ibsCaseNoSeq; } /** * Sets the value of the ibsCaseNoSeq property. * * @param value * allowed object is * {@link String } * */ public void setIbsCaseNoSeq(String value) { this.ibsCaseNoSeq = value; } /** * Gets the value of the intgmedNo property. * * @return * possible object is * {@link String } * */ public String getIntgmedNo() { return intgmedNo; } /** * Sets the value of the intgmedNo property. * * @param value * allowed object is * {@link String } * */ public void setIntgmedNo(String value) { this.intgmedNo = value; } /** * Gets the value of the invCode property. * * @return * possible object is * {@link String } * */ public String getInvCode() { return invCode; } /** * Sets the value of the invCode property. * * @param value * allowed object is * {@link String } * */ public void setInvCode(String value) { this.invCode = value; } /** * Gets the value of the mediQty property. * */ public double getMediQty() { return mediQty; } /** * Sets the value of the mediQty property. * */ public void setMediQty(double value) { this.mediQty = value; } /** * Gets the value of the mediUnit property. * * @return * possible object is * {@link String } * */ public String getMediUnit() { return mediUnit; } /** * Sets the value of the mediUnit property. * * @param value * allowed object is * {@link String } * */ public void setMediUnit(String value) { this.mediUnit = value; } /** * Gets the value of the nsExecCode property. * * @return * possible object is * {@link String } * */ public String getNsExecCode() { return nsExecCode; } /** * Sets the value of the nsExecCode property. * * @param value * allowed object is * {@link String } * */ public void setNsExecCode(String value) { this.nsExecCode = value; } /** * Gets the value of the nsExecCodeReal property. * * @return * possible object is * {@link String } * */ public String getNsExecCodeReal() { return nsExecCodeReal; } /** * Sets the value of the nsExecCodeReal property. * * @param value * allowed object is * {@link String } * */ public void setNsExecCodeReal(String value) { this.nsExecCodeReal = value; } /** * Gets the value of the nsExecDate property. * * @return * possible object is * {@link String } * */ public String getNsExecDate() { return nsExecDate; } /** * Sets the value of the nsExecDate property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDate(String value) { this.nsExecDate = value; } /** * Gets the value of the nsExecDateReal property. * * @return * possible object is * {@link String } * */ public String getNsExecDateReal() { return nsExecDateReal; } /** * Sets the value of the nsExecDateReal property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDateReal(String value) { this.nsExecDateReal = value; } /** * Gets the value of the nsExecDcCode property. * * @return * possible object is * {@link String } * */ public String getNsExecDcCode() { return nsExecDcCode; } /** * Sets the value of the nsExecDcCode property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDcCode(String value) { this.nsExecDcCode = value; } /** * Gets the value of the nsExecDcDate property. * * @return * possible object is * {@link String } * */ public String getNsExecDcDate() { return nsExecDcDate; } /** * Sets the value of the nsExecDcDate property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDcDate(String value) { this.nsExecDcDate = value; } /** * Gets the value of the nsUser property. * * @return * possible object is * {@link String } * */ public String getNsUser() { return nsUser; } /** * Sets the value of the nsUser property. * * @param value * allowed object is * {@link String } * */ public void setNsUser(String value) { this.nsUser = value; } /** * Gets the value of the nurseDispenseFlg property. * * @return * possible object is * {@link String } * */ public String getNurseDispenseFlg() { return nurseDispenseFlg; } /** * Sets the value of the nurseDispenseFlg property. * * @param value * allowed object is * {@link String } * */ public void setNurseDispenseFlg(String value) { this.nurseDispenseFlg = value; } /** * Gets the value of the optDate property. * * @return * possible object is * {@link String } * */ public String getOptDate() { return optDate; } /** * Sets the value of the optDate property. * * @param value * allowed object is * {@link String } * */ public void setOptDate(String value) { this.optDate = value; } /** * Gets the value of the optTerm property. * * @return * possible object is * {@link String } * */ public String getOptTerm() { return optTerm; } /** * Sets the value of the optTerm property. * * @param value * allowed object is * {@link String } * */ public void setOptTerm(String value) { this.optTerm = value; } /** * Gets the value of the optUser property. * * @return * possible object is * {@link String } * */ public String getOptUser() { return optUser; } /** * Sets the value of the optUser property. * * @param value * allowed object is * {@link String } * */ public void setOptUser(String value) { this.optUser = value; } /** * Gets the value of the orderCode property. * * @return * possible object is * {@link String } * */ public String getOrderCode() { return orderCode; } /** * Sets the value of the orderCode property. * * @param value * allowed object is * {@link String } * */ public void setOrderCode(String value) { this.orderCode = value; } /** * Gets the value of the orderDate property. * * @return * possible object is * {@link String } * */ public String getOrderDate() { return orderDate; } /** * Sets the value of the orderDate property. * * @param value * allowed object is * {@link String } * */ public void setOrderDate(String value) { this.orderDate = value; } /** * Gets the value of the orderDatetime property. * * @return * possible object is * {@link String } * */ public String getOrderDatetime() { return orderDatetime; } /** * Sets the value of the orderDatetime property. * * @param value * allowed object is * {@link String } * */ public void setOrderDatetime(String value) { this.orderDatetime = value; } /** * Gets the value of the orderNo property. * * @return * possible object is * {@link String } * */ public String getOrderNo() { return orderNo; } /** * Sets the value of the orderNo property. * * @param value * allowed object is * {@link String } * */ public void setOrderNo(String value) { this.orderNo = value; } /** * Gets the value of the orderSeq property. * */ public int getOrderSeq() { return orderSeq; } /** * Sets the value of the orderSeq property. * */ public void setOrderSeq(int value) { this.orderSeq = value; } /** * Gets the value of the phaDispenseCode property. * * @return * possible object is * {@link String } * */ public String getPhaDispenseCode() { return phaDispenseCode; } /** * Sets the value of the phaDispenseCode property. * * @param value * allowed object is * {@link String } * */ public void setPhaDispenseCode(String value) { this.phaDispenseCode = value; } /** * Gets the value of the phaDispenseDate property. * * @return * possible object is * {@link String } * */ public String getPhaDispenseDate() { return phaDispenseDate; } /** * Sets the value of the phaDispenseDate property. * * @param value * allowed object is * {@link String } * */ public void setPhaDispenseDate(String value) { this.phaDispenseDate = value; } /** * Gets the value of the phaDispenseNo property. * * @return * possible object is * {@link String } * */ public String getPhaDispenseNo() { return phaDispenseNo; } /** * Sets the value of the phaDispenseNo property. * * @param value * allowed object is * {@link String } * */ public void setPhaDispenseNo(String value) { this.phaDispenseNo = value; } /** * Gets the value of the phaDosageCode property. * * @return * possible object is * {@link String } * */ public String getPhaDosageCode() { return phaDosageCode; } /** * Sets the value of the phaDosageCode property. * * @param value * allowed object is * {@link String } * */ public void setPhaDosageCode(String value) { this.phaDosageCode = value; } /** * Gets the value of the phaDosageDate property. * * @return * possible object is * {@link String } * */ public String getPhaDosageDate() { return phaDosageDate; } /** * Sets the value of the phaDosageDate property. * * @param value * allowed object is * {@link String } * */ public void setPhaDosageDate(String value) { this.phaDosageDate = value; } /** * Gets the value of the phaRetnCode property. * * @return * possible object is * {@link String } * */ public String getPhaRetnCode() { return phaRetnCode; } /** * Sets the value of the phaRetnCode property. * * @param value * allowed object is * {@link String } * */ public void setPhaRetnCode(String value) { this.phaRetnCode = value; } /** * Gets the value of the phaRetnDate property. * * @return * possible object is * {@link String } * */ public String getPhaRetnDate() { return phaRetnDate; } /** * Sets the value of the phaRetnDate property. * * @param value * allowed object is * {@link String } * */ public void setPhaRetnDate(String value) { this.phaRetnDate = value; } /** * Gets the value of the serviceLevel property. * * @return * possible object is * {@link String } * */ public String getServiceLevel() { return serviceLevel; } /** * Sets the value of the serviceLevel property. * * @param value * allowed object is * {@link String } * */ public void setServiceLevel(String value) { this.serviceLevel = value; } /** * Gets the value of the stopcheckDate property. * * @return * possible object is * {@link String } * */ public String getStopcheckDate() { return stopcheckDate; } /** * Sets the value of the stopcheckDate property. * * @param value * allowed object is * {@link String } * */ public void setStopcheckDate(String value) { this.stopcheckDate = value; } /** * Gets the value of the stopcheckUser property. * * @return * possible object is * {@link String } * */ public String getStopcheckUser() { return stopcheckUser; } /** * Sets the value of the stopcheckUser property. * * @param value * allowed object is * {@link String } * */ public void setStopcheckUser(String value) { this.stopcheckUser = value; } /** * Gets the value of the takemedNo property. * * @return * possible object is * {@link String } * */ public String getTakemedNo() { return takemedNo; } /** * Sets the value of the takemedNo property. * * @param value * allowed object is * {@link String } * */ public void setTakemedNo(String value) { this.takemedNo = value; } /** * Gets the value of the takemedOrg property. * * @return * possible object is * {@link String } * */ public String getTakemedOrg() { return takemedOrg; } /** * Sets the value of the takemedOrg property. * * @param value * allowed object is * {@link String } * */ public void setTakemedOrg(String value) { this.takemedOrg = value; } /** * Gets the value of the totAmt property. * */ public double getTotAmt() { return totAmt; } /** * Sets the value of the totAmt property. * */ public void setTotAmt(double value) { this.totAmt = value; } /** * Gets the value of the transmitRsnCode property. * * @return * possible object is * {@link String } * */ public String getTransmitRsnCode() { return transmitRsnCode; } /** * Sets the value of the transmitRsnCode property. * * @param value * allowed object is * {@link String } * */ public void setTransmitRsnCode(String value) { this.transmitRsnCode = value; } /** * Gets the value of the treatEndTime property. * * @return * possible object is * {@link String } * */ public String getTreatEndTime() { return treatEndTime; } /** * Sets the value of the treatEndTime property. * * @param value * allowed object is * {@link String } * */ public void setTreatEndTime(String value) { this.treatEndTime = value; } /** * Gets the value of the treatStartTime property. * * @return * possible object is * {@link String } * */ public String getTreatStartTime() { return treatStartTime; } /** * Sets the value of the treatStartTime property. * * @param value * allowed object is * {@link String } * */ public void setTreatStartTime(String value) { this.treatStartTime = value; } }
UTF-8
Java
34,841
java
SpcOdiDspnd.java
Java
[]
null
[]
package action.inw.client; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for spcOdiDspnd complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="spcOdiDspnd"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="barCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="barcode1" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="barcode2" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="barcode3" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="batchCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="billFlg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="boxEslId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="cancelrsnCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="caseNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="cashierCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="cashierDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="dcDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="dcNsCheckDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="dosageQty" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="dosageUnit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="execDeptCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="execNote" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ibsCaseNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ibsCaseNoSeq" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="intgmedNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="invCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="mediQty" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="mediUnit" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecCodeReal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDateReal" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDcCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsExecDcDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nsUser" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nurseDispenseFlg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="optDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="optTerm" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="optUser" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderDatetime" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="orderSeq" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;element name="phaDispenseCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDispenseDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDispenseNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDosageCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaDosageDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaRetnCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="phaRetnDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="serviceLevel" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="stopcheckDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="stopcheckUser" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="takemedNo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="takemedOrg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="totAmt" type="{http://www.w3.org/2001/XMLSchema}double"/> * &lt;element name="transmitRsnCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="treatEndTime" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="treatStartTime" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "spcOdiDspnd", propOrder = { "barCode", "barcode1", "barcode2", "barcode3", "batchCode", "billFlg", "boxEslId", "cancelrsnCode", "caseNo", "cashierCode", "cashierDate", "dcDate", "dcNsCheckDate", "dosageQty", "dosageUnit", "execDeptCode", "execNote", "ibsCaseNo", "ibsCaseNoSeq", "intgmedNo", "invCode", "mediQty", "mediUnit", "nsExecCode", "nsExecCodeReal", "nsExecDate", "nsExecDateReal", "nsExecDcCode", "nsExecDcDate", "nsUser", "nurseDispenseFlg", "optDate", "optTerm", "optUser", "orderCode", "orderDate", "orderDatetime", "orderNo", "orderSeq", "phaDispenseCode", "phaDispenseDate", "phaDispenseNo", "phaDosageCode", "phaDosageDate", "phaRetnCode", "phaRetnDate", "serviceLevel", "stopcheckDate", "stopcheckUser", "takemedNo", "takemedOrg", "totAmt", "transmitRsnCode", "treatEndTime", "treatStartTime" }) public class SpcOdiDspnd { protected String barCode; protected String barcode1; protected String barcode2; protected String barcode3; protected String batchCode; protected String billFlg; protected String boxEslId; protected String cancelrsnCode; protected String caseNo; protected String cashierCode; protected String cashierDate; protected String dcDate; protected String dcNsCheckDate; protected double dosageQty; protected String dosageUnit; protected String execDeptCode; protected String execNote; protected String ibsCaseNo; protected String ibsCaseNoSeq; protected String intgmedNo; protected String invCode; protected double mediQty; protected String mediUnit; protected String nsExecCode; protected String nsExecCodeReal; protected String nsExecDate; protected String nsExecDateReal; protected String nsExecDcCode; protected String nsExecDcDate; protected String nsUser; protected String nurseDispenseFlg; protected String optDate; protected String optTerm; protected String optUser; protected String orderCode; protected String orderDate; protected String orderDatetime; protected String orderNo; protected int orderSeq; protected String phaDispenseCode; protected String phaDispenseDate; protected String phaDispenseNo; protected String phaDosageCode; protected String phaDosageDate; protected String phaRetnCode; protected String phaRetnDate; protected String serviceLevel; protected String stopcheckDate; protected String stopcheckUser; protected String takemedNo; protected String takemedOrg; protected double totAmt; protected String transmitRsnCode; protected String treatEndTime; protected String treatStartTime; /** * Gets the value of the barCode property. * * @return * possible object is * {@link String } * */ public String getBarCode() { return barCode; } /** * Sets the value of the barCode property. * * @param value * allowed object is * {@link String } * */ public void setBarCode(String value) { this.barCode = value; } /** * Gets the value of the barcode1 property. * * @return * possible object is * {@link String } * */ public String getBarcode1() { return barcode1; } /** * Sets the value of the barcode1 property. * * @param value * allowed object is * {@link String } * */ public void setBarcode1(String value) { this.barcode1 = value; } /** * Gets the value of the barcode2 property. * * @return * possible object is * {@link String } * */ public String getBarcode2() { return barcode2; } /** * Sets the value of the barcode2 property. * * @param value * allowed object is * {@link String } * */ public void setBarcode2(String value) { this.barcode2 = value; } /** * Gets the value of the barcode3 property. * * @return * possible object is * {@link String } * */ public String getBarcode3() { return barcode3; } /** * Sets the value of the barcode3 property. * * @param value * allowed object is * {@link String } * */ public void setBarcode3(String value) { this.barcode3 = value; } /** * Gets the value of the batchCode property. * * @return * possible object is * {@link String } * */ public String getBatchCode() { return batchCode; } /** * Sets the value of the batchCode property. * * @param value * allowed object is * {@link String } * */ public void setBatchCode(String value) { this.batchCode = value; } /** * Gets the value of the billFlg property. * * @return * possible object is * {@link String } * */ public String getBillFlg() { return billFlg; } /** * Sets the value of the billFlg property. * * @param value * allowed object is * {@link String } * */ public void setBillFlg(String value) { this.billFlg = value; } /** * Gets the value of the boxEslId property. * * @return * possible object is * {@link String } * */ public String getBoxEslId() { return boxEslId; } /** * Sets the value of the boxEslId property. * * @param value * allowed object is * {@link String } * */ public void setBoxEslId(String value) { this.boxEslId = value; } /** * Gets the value of the cancelrsnCode property. * * @return * possible object is * {@link String } * */ public String getCancelrsnCode() { return cancelrsnCode; } /** * Sets the value of the cancelrsnCode property. * * @param value * allowed object is * {@link String } * */ public void setCancelrsnCode(String value) { this.cancelrsnCode = value; } /** * Gets the value of the caseNo property. * * @return * possible object is * {@link String } * */ public String getCaseNo() { return caseNo; } /** * Sets the value of the caseNo property. * * @param value * allowed object is * {@link String } * */ public void setCaseNo(String value) { this.caseNo = value; } /** * Gets the value of the cashierCode property. * * @return * possible object is * {@link String } * */ public String getCashierCode() { return cashierCode; } /** * Sets the value of the cashierCode property. * * @param value * allowed object is * {@link String } * */ public void setCashierCode(String value) { this.cashierCode = value; } /** * Gets the value of the cashierDate property. * * @return * possible object is * {@link String } * */ public String getCashierDate() { return cashierDate; } /** * Sets the value of the cashierDate property. * * @param value * allowed object is * {@link String } * */ public void setCashierDate(String value) { this.cashierDate = value; } /** * Gets the value of the dcDate property. * * @return * possible object is * {@link String } * */ public String getDcDate() { return dcDate; } /** * Sets the value of the dcDate property. * * @param value * allowed object is * {@link String } * */ public void setDcDate(String value) { this.dcDate = value; } /** * Gets the value of the dcNsCheckDate property. * * @return * possible object is * {@link String } * */ public String getDcNsCheckDate() { return dcNsCheckDate; } /** * Sets the value of the dcNsCheckDate property. * * @param value * allowed object is * {@link String } * */ public void setDcNsCheckDate(String value) { this.dcNsCheckDate = value; } /** * Gets the value of the dosageQty property. * */ public double getDosageQty() { return dosageQty; } /** * Sets the value of the dosageQty property. * */ public void setDosageQty(double value) { this.dosageQty = value; } /** * Gets the value of the dosageUnit property. * * @return * possible object is * {@link String } * */ public String getDosageUnit() { return dosageUnit; } /** * Sets the value of the dosageUnit property. * * @param value * allowed object is * {@link String } * */ public void setDosageUnit(String value) { this.dosageUnit = value; } /** * Gets the value of the execDeptCode property. * * @return * possible object is * {@link String } * */ public String getExecDeptCode() { return execDeptCode; } /** * Sets the value of the execDeptCode property. * * @param value * allowed object is * {@link String } * */ public void setExecDeptCode(String value) { this.execDeptCode = value; } /** * Gets the value of the execNote property. * * @return * possible object is * {@link String } * */ public String getExecNote() { return execNote; } /** * Sets the value of the execNote property. * * @param value * allowed object is * {@link String } * */ public void setExecNote(String value) { this.execNote = value; } /** * Gets the value of the ibsCaseNo property. * * @return * possible object is * {@link String } * */ public String getIbsCaseNo() { return ibsCaseNo; } /** * Sets the value of the ibsCaseNo property. * * @param value * allowed object is * {@link String } * */ public void setIbsCaseNo(String value) { this.ibsCaseNo = value; } /** * Gets the value of the ibsCaseNoSeq property. * * @return * possible object is * {@link String } * */ public String getIbsCaseNoSeq() { return ibsCaseNoSeq; } /** * Sets the value of the ibsCaseNoSeq property. * * @param value * allowed object is * {@link String } * */ public void setIbsCaseNoSeq(String value) { this.ibsCaseNoSeq = value; } /** * Gets the value of the intgmedNo property. * * @return * possible object is * {@link String } * */ public String getIntgmedNo() { return intgmedNo; } /** * Sets the value of the intgmedNo property. * * @param value * allowed object is * {@link String } * */ public void setIntgmedNo(String value) { this.intgmedNo = value; } /** * Gets the value of the invCode property. * * @return * possible object is * {@link String } * */ public String getInvCode() { return invCode; } /** * Sets the value of the invCode property. * * @param value * allowed object is * {@link String } * */ public void setInvCode(String value) { this.invCode = value; } /** * Gets the value of the mediQty property. * */ public double getMediQty() { return mediQty; } /** * Sets the value of the mediQty property. * */ public void setMediQty(double value) { this.mediQty = value; } /** * Gets the value of the mediUnit property. * * @return * possible object is * {@link String } * */ public String getMediUnit() { return mediUnit; } /** * Sets the value of the mediUnit property. * * @param value * allowed object is * {@link String } * */ public void setMediUnit(String value) { this.mediUnit = value; } /** * Gets the value of the nsExecCode property. * * @return * possible object is * {@link String } * */ public String getNsExecCode() { return nsExecCode; } /** * Sets the value of the nsExecCode property. * * @param value * allowed object is * {@link String } * */ public void setNsExecCode(String value) { this.nsExecCode = value; } /** * Gets the value of the nsExecCodeReal property. * * @return * possible object is * {@link String } * */ public String getNsExecCodeReal() { return nsExecCodeReal; } /** * Sets the value of the nsExecCodeReal property. * * @param value * allowed object is * {@link String } * */ public void setNsExecCodeReal(String value) { this.nsExecCodeReal = value; } /** * Gets the value of the nsExecDate property. * * @return * possible object is * {@link String } * */ public String getNsExecDate() { return nsExecDate; } /** * Sets the value of the nsExecDate property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDate(String value) { this.nsExecDate = value; } /** * Gets the value of the nsExecDateReal property. * * @return * possible object is * {@link String } * */ public String getNsExecDateReal() { return nsExecDateReal; } /** * Sets the value of the nsExecDateReal property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDateReal(String value) { this.nsExecDateReal = value; } /** * Gets the value of the nsExecDcCode property. * * @return * possible object is * {@link String } * */ public String getNsExecDcCode() { return nsExecDcCode; } /** * Sets the value of the nsExecDcCode property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDcCode(String value) { this.nsExecDcCode = value; } /** * Gets the value of the nsExecDcDate property. * * @return * possible object is * {@link String } * */ public String getNsExecDcDate() { return nsExecDcDate; } /** * Sets the value of the nsExecDcDate property. * * @param value * allowed object is * {@link String } * */ public void setNsExecDcDate(String value) { this.nsExecDcDate = value; } /** * Gets the value of the nsUser property. * * @return * possible object is * {@link String } * */ public String getNsUser() { return nsUser; } /** * Sets the value of the nsUser property. * * @param value * allowed object is * {@link String } * */ public void setNsUser(String value) { this.nsUser = value; } /** * Gets the value of the nurseDispenseFlg property. * * @return * possible object is * {@link String } * */ public String getNurseDispenseFlg() { return nurseDispenseFlg; } /** * Sets the value of the nurseDispenseFlg property. * * @param value * allowed object is * {@link String } * */ public void setNurseDispenseFlg(String value) { this.nurseDispenseFlg = value; } /** * Gets the value of the optDate property. * * @return * possible object is * {@link String } * */ public String getOptDate() { return optDate; } /** * Sets the value of the optDate property. * * @param value * allowed object is * {@link String } * */ public void setOptDate(String value) { this.optDate = value; } /** * Gets the value of the optTerm property. * * @return * possible object is * {@link String } * */ public String getOptTerm() { return optTerm; } /** * Sets the value of the optTerm property. * * @param value * allowed object is * {@link String } * */ public void setOptTerm(String value) { this.optTerm = value; } /** * Gets the value of the optUser property. * * @return * possible object is * {@link String } * */ public String getOptUser() { return optUser; } /** * Sets the value of the optUser property. * * @param value * allowed object is * {@link String } * */ public void setOptUser(String value) { this.optUser = value; } /** * Gets the value of the orderCode property. * * @return * possible object is * {@link String } * */ public String getOrderCode() { return orderCode; } /** * Sets the value of the orderCode property. * * @param value * allowed object is * {@link String } * */ public void setOrderCode(String value) { this.orderCode = value; } /** * Gets the value of the orderDate property. * * @return * possible object is * {@link String } * */ public String getOrderDate() { return orderDate; } /** * Sets the value of the orderDate property. * * @param value * allowed object is * {@link String } * */ public void setOrderDate(String value) { this.orderDate = value; } /** * Gets the value of the orderDatetime property. * * @return * possible object is * {@link String } * */ public String getOrderDatetime() { return orderDatetime; } /** * Sets the value of the orderDatetime property. * * @param value * allowed object is * {@link String } * */ public void setOrderDatetime(String value) { this.orderDatetime = value; } /** * Gets the value of the orderNo property. * * @return * possible object is * {@link String } * */ public String getOrderNo() { return orderNo; } /** * Sets the value of the orderNo property. * * @param value * allowed object is * {@link String } * */ public void setOrderNo(String value) { this.orderNo = value; } /** * Gets the value of the orderSeq property. * */ public int getOrderSeq() { return orderSeq; } /** * Sets the value of the orderSeq property. * */ public void setOrderSeq(int value) { this.orderSeq = value; } /** * Gets the value of the phaDispenseCode property. * * @return * possible object is * {@link String } * */ public String getPhaDispenseCode() { return phaDispenseCode; } /** * Sets the value of the phaDispenseCode property. * * @param value * allowed object is * {@link String } * */ public void setPhaDispenseCode(String value) { this.phaDispenseCode = value; } /** * Gets the value of the phaDispenseDate property. * * @return * possible object is * {@link String } * */ public String getPhaDispenseDate() { return phaDispenseDate; } /** * Sets the value of the phaDispenseDate property. * * @param value * allowed object is * {@link String } * */ public void setPhaDispenseDate(String value) { this.phaDispenseDate = value; } /** * Gets the value of the phaDispenseNo property. * * @return * possible object is * {@link String } * */ public String getPhaDispenseNo() { return phaDispenseNo; } /** * Sets the value of the phaDispenseNo property. * * @param value * allowed object is * {@link String } * */ public void setPhaDispenseNo(String value) { this.phaDispenseNo = value; } /** * Gets the value of the phaDosageCode property. * * @return * possible object is * {@link String } * */ public String getPhaDosageCode() { return phaDosageCode; } /** * Sets the value of the phaDosageCode property. * * @param value * allowed object is * {@link String } * */ public void setPhaDosageCode(String value) { this.phaDosageCode = value; } /** * Gets the value of the phaDosageDate property. * * @return * possible object is * {@link String } * */ public String getPhaDosageDate() { return phaDosageDate; } /** * Sets the value of the phaDosageDate property. * * @param value * allowed object is * {@link String } * */ public void setPhaDosageDate(String value) { this.phaDosageDate = value; } /** * Gets the value of the phaRetnCode property. * * @return * possible object is * {@link String } * */ public String getPhaRetnCode() { return phaRetnCode; } /** * Sets the value of the phaRetnCode property. * * @param value * allowed object is * {@link String } * */ public void setPhaRetnCode(String value) { this.phaRetnCode = value; } /** * Gets the value of the phaRetnDate property. * * @return * possible object is * {@link String } * */ public String getPhaRetnDate() { return phaRetnDate; } /** * Sets the value of the phaRetnDate property. * * @param value * allowed object is * {@link String } * */ public void setPhaRetnDate(String value) { this.phaRetnDate = value; } /** * Gets the value of the serviceLevel property. * * @return * possible object is * {@link String } * */ public String getServiceLevel() { return serviceLevel; } /** * Sets the value of the serviceLevel property. * * @param value * allowed object is * {@link String } * */ public void setServiceLevel(String value) { this.serviceLevel = value; } /** * Gets the value of the stopcheckDate property. * * @return * possible object is * {@link String } * */ public String getStopcheckDate() { return stopcheckDate; } /** * Sets the value of the stopcheckDate property. * * @param value * allowed object is * {@link String } * */ public void setStopcheckDate(String value) { this.stopcheckDate = value; } /** * Gets the value of the stopcheckUser property. * * @return * possible object is * {@link String } * */ public String getStopcheckUser() { return stopcheckUser; } /** * Sets the value of the stopcheckUser property. * * @param value * allowed object is * {@link String } * */ public void setStopcheckUser(String value) { this.stopcheckUser = value; } /** * Gets the value of the takemedNo property. * * @return * possible object is * {@link String } * */ public String getTakemedNo() { return takemedNo; } /** * Sets the value of the takemedNo property. * * @param value * allowed object is * {@link String } * */ public void setTakemedNo(String value) { this.takemedNo = value; } /** * Gets the value of the takemedOrg property. * * @return * possible object is * {@link String } * */ public String getTakemedOrg() { return takemedOrg; } /** * Sets the value of the takemedOrg property. * * @param value * allowed object is * {@link String } * */ public void setTakemedOrg(String value) { this.takemedOrg = value; } /** * Gets the value of the totAmt property. * */ public double getTotAmt() { return totAmt; } /** * Sets the value of the totAmt property. * */ public void setTotAmt(double value) { this.totAmt = value; } /** * Gets the value of the transmitRsnCode property. * * @return * possible object is * {@link String } * */ public String getTransmitRsnCode() { return transmitRsnCode; } /** * Sets the value of the transmitRsnCode property. * * @param value * allowed object is * {@link String } * */ public void setTransmitRsnCode(String value) { this.transmitRsnCode = value; } /** * Gets the value of the treatEndTime property. * * @return * possible object is * {@link String } * */ public String getTreatEndTime() { return treatEndTime; } /** * Sets the value of the treatEndTime property. * * @param value * allowed object is * {@link String } * */ public void setTreatEndTime(String value) { this.treatEndTime = value; } /** * Gets the value of the treatStartTime property. * * @return * possible object is * {@link String } * */ public String getTreatStartTime() { return treatStartTime; } /** * Sets the value of the treatStartTime property. * * @param value * allowed object is * {@link String } * */ public void setTreatStartTime(String value) { this.treatStartTime = value; } }
34,841
0.535547
0.525272
1,485
22.461279
21.700735
110
false
false
0
0
0
0
0
0
0.193266
false
false
10
e4675de2393be2c7ad7d9f2d4234b52b22932b25
23,072,564,319,237
eac2d029488a693430d9b2ca36ff39e5a2194566
/src/main/java/com/plum/cmn/mapper/UserRegMapper.java
f212ef58e3f31515f46a88920843dbe35404f074
[]
no_license
rlagudals/plum
https://github.com/rlagudals/plum
ba20d795bcae293283ca81ad27ef466bd7c35fcd
b6b204c823ae2b454dbefba37a0e5e7f439ddedf
refs/heads/master
2021-07-22T11:46:19.290000
2021-07-16T07:18:07
2021-07-16T07:18:07
148,869,865
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.plum.cmn.mapper; import org.apache.ibatis.annotations.Mapper; import com.plum.cmn.model.*; @Mapper public interface UserRegMapper { // 회원가입 public int insertUserInfo(UserLoginInfo userLoginInfo); // 중복 아이디 체크 public UserLoginInfo getIdCheck(UserLoginInfo inputId); }
UTF-8
Java
326
java
UserRegMapper.java
Java
[]
null
[]
package com.plum.cmn.mapper; import org.apache.ibatis.annotations.Mapper; import com.plum.cmn.model.*; @Mapper public interface UserRegMapper { // 회원가입 public int insertUserInfo(UserLoginInfo userLoginInfo); // 중복 아이디 체크 public UserLoginInfo getIdCheck(UserLoginInfo inputId); }
326
0.740132
0.740132
15
18.266666
20.131126
56
false
false
0
0
0
0
0
0
0.666667
false
false
10
b5b6e161c45a52857034c30a24e46440b72b449e
30,820,685,385,993
f0c182fe246c20d28f34c7c9cf377917d356501e
/src/Cenario/Poca.java
b49b8cedff8ce092954aa70ef11a383a90f3f749
[]
no_license
Lucas5293/Mataka-RPG
https://github.com/Lucas5293/Mataka-RPG
c2bd7f9020b43678f7578115ed1043489c39e6fb
49f8ad58b523551a57383eb4e0481e0f72d20d42
refs/heads/master
2021-01-02T22:59:34.927000
2017-11-26T13:17:32
2017-11-26T13:17:32
99,431,889
1
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 Cenario; import Controlador.Principal; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; /** * * @author lucas */ public class Poca { public String sprite; public BufferedImage img; public Controlador.Sprite sImg; public int x=0; public int y=0; public Poca(){ Random aleatorio = new Random(); switch(aleatorio.nextInt(4)){ case 0: loadSprite("poca1.png"); break; case 1: loadSprite("poca2.png"); break; case 2: loadSprite("poca3.png"); break; case 3: loadSprite("poca4.png"); break; } drawSprite(); } public void drawSprite(){ sImg = new Controlador.Sprite(img,x, y); Principal.GUI.add(sImg); } public void loadSprite(String sprite){ try { img = ImageIO.read(getClass().getResourceAsStream("/Cenario/Imagens/"+sprite)); } catch (IOException e) { System.out.println(e); } } }
UTF-8
Java
1,426
java
Poca.java
Java
[ { "context": "port javax.imageio.ImageIO;\r\n\r\n/**\r\n *\r\n * @author lucas\r\n */\r\npublic class Poca {\r\n public String sprite", "end": 392, "score": 0.9812608957290649, "start": 387, "tag": "USERNAME", "value": "lucas" } ]
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 Cenario; import Controlador.Principal; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; /** * * @author lucas */ public class Poca { public String sprite; public BufferedImage img; public Controlador.Sprite sImg; public int x=0; public int y=0; public Poca(){ Random aleatorio = new Random(); switch(aleatorio.nextInt(4)){ case 0: loadSprite("poca1.png"); break; case 1: loadSprite("poca2.png"); break; case 2: loadSprite("poca3.png"); break; case 3: loadSprite("poca4.png"); break; } drawSprite(); } public void drawSprite(){ sImg = new Controlador.Sprite(img,x, y); Principal.GUI.add(sImg); } public void loadSprite(String sprite){ try { img = ImageIO.read(getClass().getResourceAsStream("/Cenario/Imagens/"+sprite)); } catch (IOException e) { System.out.println(e); } } }
1,426
0.538569
0.530856
56
23.464285
18.417736
90
false
false
0
0
0
0
0
0
0.535714
false
false
10
60a13febe803bbd6b13a417763f68f30522b1e55
5,866,925,328,110
1793f920d6bd99786fb96923916750e0d693ddf4
/linear01/main/Task16.java
296445ede1a41f8ae1e9ef805b46c2192232fa88
[]
no_license
vitalik94/JD1_Unit01
https://github.com/vitalik94/JD1_Unit01
ca130523a0168a627d3db69f6966f52efa35c75f
db6d085e34c30e91ac437d9b3bc4b439bf72bfeb
refs/heads/main
2021-06-30T04:25:35.365000
2020-12-31T17:18:25
2020-12-31T17:18:25
202,534,266
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.htp.linear01.main; // Найти произведение чисел заданного четырехзначного числа public class Task16 { public static void main(String[] args) { int x; int x1; int x2; int x3; int x4; int y; x = 1234; x1 = x / 1000; x2 = (x / 100) % 10; x3 = (x % 100) / 10; x4 = x % 10; y = x1 * x2 * x3 * x4; System.out.println("x1 = " + x1); System.out.println("x2 = " + x2); System.out.println("x3 = " + x3); System.out.println("x4 = " + x4); System.out.println("y = " + y); } }
UTF-8
Java
625
java
Task16.java
Java
[]
null
[]
package by.htp.linear01.main; // Найти произведение чисел заданного четырехзначного числа public class Task16 { public static void main(String[] args) { int x; int x1; int x2; int x3; int x4; int y; x = 1234; x1 = x / 1000; x2 = (x / 100) % 10; x3 = (x % 100) / 10; x4 = x % 10; y = x1 * x2 * x3 * x4; System.out.println("x1 = " + x1); System.out.println("x2 = " + x2); System.out.println("x3 = " + x3); System.out.println("x4 = " + x4); System.out.println("y = " + y); } }
625
0.505226
0.428571
35
14.4
15.027974
60
false
false
0
0
0
0
0
0
2
false
false
10
6e535194b90be9266fd125b546f5f1c8e2f7b347
25,245,817,810,203
771a1686dd76b7df875651adac9e1a89691f0b06
/src/main/java/com/charity/webservice/dto/ReceiptResponseDTO.java
af5123cf6df1536a6fcae35eaf337f9fcc1db15d
[]
no_license
devmsaleh/ras
https://github.com/devmsaleh/ras
d413308a25051e5d19d607fd520f35bc86b33af6
ed85f8f5776d21e35219a0626773adfe94b9764b
refs/heads/master
2023-03-09T22:24:14.476000
2021-02-13T20:34:23
2021-02-13T20:34:23
241,177,638
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.charity.webservice.dto; public class ReceiptResponseDTO { private Long receiptId; public ReceiptResponseDTO() { } public ReceiptResponseDTO(Long receiptId) { this.receiptId = receiptId; } public Long getReceiptId() { return receiptId; } public void setReceiptId(Long receiptId) { this.receiptId = receiptId; } }
UTF-8
Java
347
java
ReceiptResponseDTO.java
Java
[]
null
[]
package com.charity.webservice.dto; public class ReceiptResponseDTO { private Long receiptId; public ReceiptResponseDTO() { } public ReceiptResponseDTO(Long receiptId) { this.receiptId = receiptId; } public Long getReceiptId() { return receiptId; } public void setReceiptId(Long receiptId) { this.receiptId = receiptId; } }
347
0.737752
0.737752
23
14.086957
16.032339
44
false
false
0
0
0
0
0
0
0.869565
false
false
10
f5967d6fe65fd8dd73c1b212067741691669a7b8
14,980,845,930,286
5fd412ab11b8b6f08ee7a200203ef6e33d68ea30
/src/main/java/com/vlopatka/planetContest/service/PlanetInfoProvider.java
92078216989ab8d312993c6a0922cb231edf8c3d
[]
no_license
Vadym-Lopatka/effective-java
https://github.com/Vadym-Lopatka/effective-java
d72c62f9a70f6f4b1b659ab8bc97c2824af924f1
529a6ca90b4eaa2bdb24cb7954837de7c9cea2b4
refs/heads/master
2023-06-27T22:46:49.090000
2021-07-09T14:47:56
2021-07-09T14:47:56
348,773,016
0
0
null
false
2021-07-09T14:47:57
2021-03-17T16:12:16
2021-03-17T18:11:16
2021-07-09T14:47:56
14
0
0
0
Java
false
false
package com.vlopatka.planetContest.service; import com.vlopatka.planetContest.domain.Planet; public interface PlanetInfoProvider { Planet get(); }
UTF-8
Java
155
java
PlanetInfoProvider.java
Java
[]
null
[]
package com.vlopatka.planetContest.service; import com.vlopatka.planetContest.domain.Planet; public interface PlanetInfoProvider { Planet get(); }
155
0.787097
0.787097
9
16.222221
19.560606
48
false
false
0
0
0
0
0
0
0.333333
false
false
10
c294720a5baef25151700330fea0cc9a7a3bbd1d
23,519,240,918,622
da5e73817c469d6fc7e243b6d9b2bd516dd9927a
/src/main/java/infra/dto/authors/Works.java
c23c75d62338d1cf024971b67051fcb4c4ace77c
[]
no_license
mariusz84/book-storage
https://github.com/mariusz84/book-storage
e5b924ddd962878015c2781a603e42f829c73dea
b778cbef83d914e8281967e5a59d32cb4ab51cce
refs/heads/master
2020-03-30T15:34:14.332000
2019-01-04T07:28:25
2019-01-04T07:28:25
141,804,588
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package infra.dto.authors; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class Works { private List<String> works; public Works() { } public List<String> getWorks() { return works; } public void setWorks(List<String> works) { this.works = works; } }
UTF-8
Java
390
java
Works.java
Java
[]
null
[]
package infra.dto.authors; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class Works { private List<String> works; public Works() { } public List<String> getWorks() { return works; } public void setWorks(List<String> works) { this.works = works; } }
390
0.674359
0.674359
21
17.571428
17.81538
61
false
false
0
0
0
0
0
0
0.285714
false
false
10
2d9c1131b5eb99874a732b9b5ce7bf2677fb749b
34,677,566,002,473
fd4f21f9ac79a93f01fa1cdef30cc1bdc738694f
/src/test/java/com/statistic/checker/configuration/TestConfiguration.java
68c2a307648bf282ab0962e515a66c975196821c
[]
no_license
lovewithmind/ActiveMQ-Stats
https://github.com/lovewithmind/ActiveMQ-Stats
a4c2371f2ac614e53ac0d63c33ec013dce322535
527c1ba418305794092a35577187b9c07c87a9fc
refs/heads/master
2020-03-06T19:38:20.822000
2018-03-27T19:01:41
2018-03-27T19:01:41
127,033,429
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.statistic.checker.configuration; import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.plugin.StatisticsBrokerPlugin; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestConfiguration { @Bean public BrokerService broker(@Value("${spring.activemq.broker-url}") String uri) throws Exception { BrokerService brokerService = new BrokerService(); brokerService.addConnector(uri); brokerService.setPlugins(new BrokerPlugin[]{new StatisticsBrokerPlugin()}); brokerService.setDestinations(new ActiveMQDestination[]{new ActiveMQQueue("ActiveMQ.DLQ")}); return brokerService; } }
UTF-8
Java
967
java
TestConfiguration.java
Java
[]
null
[]
package com.statistic.checker.configuration; import org.apache.activemq.broker.BrokerPlugin; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.plugin.StatisticsBrokerPlugin; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestConfiguration { @Bean public BrokerService broker(@Value("${spring.activemq.broker-url}") String uri) throws Exception { BrokerService brokerService = new BrokerService(); brokerService.addConnector(uri); brokerService.setPlugins(new BrokerPlugin[]{new StatisticsBrokerPlugin()}); brokerService.setDestinations(new ActiveMQDestination[]{new ActiveMQQueue("ActiveMQ.DLQ")}); return brokerService; } }
967
0.792141
0.792141
25
37.68
30.737234
102
false
false
0
0
0
0
0
0
0.56
false
false
10
dc9e23518df7d672250268663f6b692b3121c207
4,140,348,519,244
15acf8bfa3b485f3cd706d51fe090e9183d36e2e
/app/src/main/java/com/example/asus/retrofitcrudtutorial/TampilData.java
89018b4f9db5a97091ccb315f46f419477161309
[]
no_license
RezaRamadhanIrianto/CrudAndroidWithRetrofit
https://github.com/RezaRamadhanIrianto/CrudAndroidWithRetrofit
fc846e7b754bc558e16f124aa0978da504d65def
d30e3f0d305b17a95edb6b197e5fa90b552e31e3
refs/heads/master
2020-06-23T04:53:47.756000
2019-07-23T23:03:29
2019-07-23T23:03:29
198,520,371
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.asus.retrofitcrudtutorial; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.telecom.Call; import android.util.Log; import com.example.asus.retrofitcrudtutorial.adapter.adapterData; import com.example.asus.retrofitcrudtutorial.api.ApiRequestBiodata; import com.example.asus.retrofitcrudtutorial.api.Retroserver; import com.example.asus.retrofitcrudtutorial.model.DataModel; import com.example.asus.retrofitcrudtutorial.model.ResponseModel; import java.util.ArrayList; import java.util.List; import retrofit2.Callback; import retrofit2.Response; public class TampilData extends AppCompatActivity { private RecyclerView mRecycler; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mManager; private List<DataModel> mItems = new ArrayList<>(); ProgressDialog pd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tampil_data); pd = new ProgressDialog(this); pd.setMessage("Loading...."); pd.setCancelable(false); pd.show(); mRecycler = (RecyclerView) findViewById(R.id.recyclerTemp); mManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL, false); mRecycler.setLayoutManager(mManager); ApiRequestBiodata api = Retroserver.getClient().create(ApiRequestBiodata.class); retrofit2.Call<ResponseModel> getData = api.getBiodata(); getData.enqueue(new Callback<ResponseModel>() { @Override public void onResponse(retrofit2.Call<ResponseModel> call, Response<ResponseModel> response) { pd.hide(); Log.d("RETRO", "onResponse: " + response.body().getKode()); mItems = response.body().getResult(); mAdapter = new adapterData(TampilData.this, mItems); mRecycler.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } @Override public void onFailure(retrofit2.Call<ResponseModel> call, Throwable t) { Log.d("RETRO", "onFailure: " + t); } }); } }
UTF-8
Java
2,380
java
TampilData.java
Java
[]
null
[]
package com.example.asus.retrofitcrudtutorial; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.telecom.Call; import android.util.Log; import com.example.asus.retrofitcrudtutorial.adapter.adapterData; import com.example.asus.retrofitcrudtutorial.api.ApiRequestBiodata; import com.example.asus.retrofitcrudtutorial.api.Retroserver; import com.example.asus.retrofitcrudtutorial.model.DataModel; import com.example.asus.retrofitcrudtutorial.model.ResponseModel; import java.util.ArrayList; import java.util.List; import retrofit2.Callback; import retrofit2.Response; public class TampilData extends AppCompatActivity { private RecyclerView mRecycler; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mManager; private List<DataModel> mItems = new ArrayList<>(); ProgressDialog pd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tampil_data); pd = new ProgressDialog(this); pd.setMessage("Loading...."); pd.setCancelable(false); pd.show(); mRecycler = (RecyclerView) findViewById(R.id.recyclerTemp); mManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL, false); mRecycler.setLayoutManager(mManager); ApiRequestBiodata api = Retroserver.getClient().create(ApiRequestBiodata.class); retrofit2.Call<ResponseModel> getData = api.getBiodata(); getData.enqueue(new Callback<ResponseModel>() { @Override public void onResponse(retrofit2.Call<ResponseModel> call, Response<ResponseModel> response) { pd.hide(); Log.d("RETRO", "onResponse: " + response.body().getKode()); mItems = response.body().getResult(); mAdapter = new adapterData(TampilData.this, mItems); mRecycler.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } @Override public void onFailure(retrofit2.Call<ResponseModel> call, Throwable t) { Log.d("RETRO", "onFailure: " + t); } }); } }
2,380
0.70084
0.697479
65
35.615383
26.53166
106
false
false
0
0
0
0
0
0
0.738462
false
false
10
8a25f8a9f782d6e25d6c2cced83fb0d3357ca620
4,088,808,911,516
fb1a4af9daa61d22908aa8814d0e1a50d08febb4
/src/main/java/hu/rycus/google/parser/csv/reflect/ClassParser.java
8598d021c174ee813d3cf924191598fa64d6f467
[ "Apache-2.0" ]
permissive
rycus86/google-http-client-csv
https://github.com/rycus86/google-http-client-csv
0001045fbe8da6b772ba2f3363dccab9afe1af62
2de40658fda5572d268af3be14f64d091f10ba2c
refs/heads/master
2021-01-25T07:28:36.355000
2017-05-15T20:11:45
2017-05-15T20:11:45
35,469,590
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package hu.rycus.google.parser.csv.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class ClassParser { private final Class<?> theClass; private final Map<String, TypeParser<?>> typeParsers = new HashMap<>(); private ExtraFieldsParser extraFieldsParser; public ClassParser(final Class<?> theClass) { this.theClass = theClass; } public void parseMetadata() throws ParseException { final List<FieldParser> collector = new LinkedList<>(); for (final FieldParser fieldParser : collectFieldParsers(theClass, collector)) { if (fieldParser.isExtraFields()) { setExtraFieldsParser(fieldParser); } else { typeParsers.put(fieldParser.getFieldId(), fieldParser.getTypeParser()); } } } private void setExtraFieldsParser(final FieldParser fieldParser) throws ParseException { if (extraFieldsParser != null) { throw new ParseException("Multiple ExtraFields defined in " + theClass); } else { extraFieldsParser = (ExtraFieldsParser) fieldParser.getTypeParser(); } } @SuppressWarnings("unchecked") public <T> T parseObject(final Map<String, String> values) throws ParseException { final T instance; try { final Constructor<?> constructor = theClass.getDeclaredConstructor(); final boolean accessible = constructor.isAccessible(); try { constructor.setAccessible(true); instance = (T) constructor.newInstance(); } finally { constructor.setAccessible(accessible); } } catch (Exception ex) { throw new ParseException(String.format("Failed to instantiate %s", theClass), ex); } for (final Map.Entry<String, String> entry : values.entrySet()) { final String name = entry.getKey(); final String value = entry.getValue(); final String id = FieldParser.toId(name); final TypeParser<?> parser = typeParsers.get(id); if (parser != null) { parser.writeField(instance, value); } else if (extraFieldsParser != null) { extraFieldsParser.writeField(instance, name, value); } } return instance; } private List<FieldParser> collectFieldParsers(final Class<?> aClass, final List<FieldParser> parsers) { for (final Field field : aClass.getDeclaredFields()) { final FieldParser parser = new FieldParser(field); if (parser.isValid()) { parsers.add(parser); } } final Class<?> superClass = aClass.getSuperclass(); if (superClass != null) { collectFieldParsers(superClass, parsers); } return parsers; } }
UTF-8
Java
3,027
java
ClassParser.java
Java
[]
null
[]
package hu.rycus.google.parser.csv.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class ClassParser { private final Class<?> theClass; private final Map<String, TypeParser<?>> typeParsers = new HashMap<>(); private ExtraFieldsParser extraFieldsParser; public ClassParser(final Class<?> theClass) { this.theClass = theClass; } public void parseMetadata() throws ParseException { final List<FieldParser> collector = new LinkedList<>(); for (final FieldParser fieldParser : collectFieldParsers(theClass, collector)) { if (fieldParser.isExtraFields()) { setExtraFieldsParser(fieldParser); } else { typeParsers.put(fieldParser.getFieldId(), fieldParser.getTypeParser()); } } } private void setExtraFieldsParser(final FieldParser fieldParser) throws ParseException { if (extraFieldsParser != null) { throw new ParseException("Multiple ExtraFields defined in " + theClass); } else { extraFieldsParser = (ExtraFieldsParser) fieldParser.getTypeParser(); } } @SuppressWarnings("unchecked") public <T> T parseObject(final Map<String, String> values) throws ParseException { final T instance; try { final Constructor<?> constructor = theClass.getDeclaredConstructor(); final boolean accessible = constructor.isAccessible(); try { constructor.setAccessible(true); instance = (T) constructor.newInstance(); } finally { constructor.setAccessible(accessible); } } catch (Exception ex) { throw new ParseException(String.format("Failed to instantiate %s", theClass), ex); } for (final Map.Entry<String, String> entry : values.entrySet()) { final String name = entry.getKey(); final String value = entry.getValue(); final String id = FieldParser.toId(name); final TypeParser<?> parser = typeParsers.get(id); if (parser != null) { parser.writeField(instance, value); } else if (extraFieldsParser != null) { extraFieldsParser.writeField(instance, name, value); } } return instance; } private List<FieldParser> collectFieldParsers(final Class<?> aClass, final List<FieldParser> parsers) { for (final Field field : aClass.getDeclaredFields()) { final FieldParser parser = new FieldParser(field); if (parser.isValid()) { parsers.add(parser); } } final Class<?> superClass = aClass.getSuperclass(); if (superClass != null) { collectFieldParsers(superClass, parsers); } return parsers; } }
3,027
0.611497
0.611497
89
33.011234
28.509605
107
false
false
0
0
0
0
0
0
0.52809
false
false
10
75c732a31ea93583c34e332d7119d8d3f7a1003b
1,116,691,529,959
4eefbc817a542463c3f309c3a578a3dc9003076b
/src/main/java/com/example/demo/Service/MemberService.java
17c547dc0945c145c89c1665227c83c15220ace0
[]
no_license
manujayarajkm/Library-Backend
https://github.com/manujayarajkm/Library-Backend
5c64feb4be2714c29b162b434f6929fd7b808f8d
c7b4e8e3838c464b2bd5a97a6d570580efb83cbc
refs/heads/master
2021-04-12T11:09:14.177000
2018-06-24T11:24:54
2018-06-24T11:24:54
126,562,604
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.demo.Service; import java.sql.SQLException; import com.example.demo.POJO.User; public interface MemberService { public String AddMember(String name,String email,String uname,String password,double phone)throws SQLException,ClassNotFoundException; public String RemoveMember(int userId)throws SQLException,ClassNotFoundException; public User login(String username,String password)throws SQLException,ClassNotFoundException; public String checkUsername(String username)throws SQLException,ClassNotFoundException; public int getUserId(String username)throws SQLException,ClassNotFoundException; }
UTF-8
Java
625
java
MemberService.java
Java
[]
null
[]
package com.example.demo.Service; import java.sql.SQLException; import com.example.demo.POJO.User; public interface MemberService { public String AddMember(String name,String email,String uname,String password,double phone)throws SQLException,ClassNotFoundException; public String RemoveMember(int userId)throws SQLException,ClassNotFoundException; public User login(String username,String password)throws SQLException,ClassNotFoundException; public String checkUsername(String username)throws SQLException,ClassNotFoundException; public int getUserId(String username)throws SQLException,ClassNotFoundException; }
625
0.8544
0.8544
15
40.666668
42.735882
135
false
false
0
0
0
0
0
0
1.6
false
false
10
ab763077c92b509d004b8e070c218dfb3d355f5b
12,343,736,040,923
9415e9945b280be69d21554913f0b797e921a5d1
/java8/src/test/java/java8/interfaces/InterfaceMethodsTest.java
916b4fa4a2c4171449cf4fd26df1837a92ba69f0
[]
no_license
monrealis/java-experiments
https://github.com/monrealis/java-experiments
5ec870679226eda26a3df617d1a0dc3814c362f0
662be443aaf32b101d1b986842bd61cc89e53918
refs/heads/master
2023-08-02T23:29:02.996000
2023-08-01T19:46:17
2023-08-01T19:46:17
29,835,460
0
0
null
false
2023-04-17T18:25:04
2015-01-25T23:03:41
2022-06-05T10:58:46
2023-04-17T18:24:59
1,686
0
0
7
Java
false
false
package java8.interfaces; import org.junit.Test; import static org.junit.Assert.assertEquals; public class InterfaceMethodsTest { private I i = new I() { }; @Test public void five() { assertEquals(5, i.five()); } @Test public void twoTimesFive() { assertEquals(10, I.twoTimesFive()); } public static interface I { public static int twoTimesFive() { return 5 * 2; } default int five() { return 5; } } }
UTF-8
Java
521
java
InterfaceMethodsTest.java
Java
[]
null
[]
package java8.interfaces; import org.junit.Test; import static org.junit.Assert.assertEquals; public class InterfaceMethodsTest { private I i = new I() { }; @Test public void five() { assertEquals(5, i.five()); } @Test public void twoTimesFive() { assertEquals(10, I.twoTimesFive()); } public static interface I { public static int twoTimesFive() { return 5 * 2; } default int five() { return 5; } } }
521
0.554703
0.541267
30
16.366667
14.808743
44
false
false
0
0
0
0
0
0
0.333333
false
false
10
01984ca66495d8ada08e843cc6224a6e4f9f9c1f
22,351,009,815,269
560b1a368a1a386963b1cbc0fcd8bca8f35cab48
/App/app/src/main/java/com/example/winedroid/ui/fichavino/Vino.java
b167bae3e925355a9a7f1b5dd8a10228a778e9ed
[ "MIT" ]
permissive
CIFP-Virgen-de-Gracia/ProyectoFinal
https://github.com/CIFP-Virgen-de-Gracia/ProyectoFinal
85f29c3c6cf7ea1b618d9541db0c28341af23bb6
59a885f19ec9b29e4318b0d8ad8fa3875f61820b
refs/heads/master
2023-02-13T16:35:34.073000
2021-01-14T16:29:02
2021-01-14T16:29:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.winedroid.ui.fichavino; import java.io.Serializable; import java.util.ArrayList; public class Vino implements Serializable { String nombre; String descripcion; String imagen; Integer valoracion; String denominacion; ArrayList<Comentario> listaComentarios = new ArrayList<Comentario>(); public Vino(String nombre, String descripcion, String imagen, Integer valoracion, String denominacion, ArrayList<Comentario> listaComentarios) { this.nombre = nombre; this.descripcion = descripcion; this.imagen = imagen; this.valoracion = valoracion; this.denominacion = denominacion; this.listaComentarios = listaComentarios; } public Vino(String nombre, String descripcion, String imagen, Integer valoracion, String denominacion) { this.nombre = nombre; this.descripcion = descripcion; this.imagen = imagen; this.valoracion = valoracion; this.denominacion = denominacion; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public Integer getValoracion() { return valoracion; } public void setValoracion(Integer valoracion) { this.valoracion = valoracion; } public String getDenominacion() { return denominacion; } public void setDenominacion(String denominacion) { this.denominacion = denominacion; } public ArrayList<Comentario> getListaComentarios() { return listaComentarios; } public void setListaComentarios(ArrayList<Comentario> listaComentarios) { this.listaComentarios = listaComentarios; } public void añadirComentario(Comentario c){ this.listaComentarios.add(c); } }
UTF-8
Java
2,144
java
Vino.java
Java
[]
null
[]
package com.example.winedroid.ui.fichavino; import java.io.Serializable; import java.util.ArrayList; public class Vino implements Serializable { String nombre; String descripcion; String imagen; Integer valoracion; String denominacion; ArrayList<Comentario> listaComentarios = new ArrayList<Comentario>(); public Vino(String nombre, String descripcion, String imagen, Integer valoracion, String denominacion, ArrayList<Comentario> listaComentarios) { this.nombre = nombre; this.descripcion = descripcion; this.imagen = imagen; this.valoracion = valoracion; this.denominacion = denominacion; this.listaComentarios = listaComentarios; } public Vino(String nombre, String descripcion, String imagen, Integer valoracion, String denominacion) { this.nombre = nombre; this.descripcion = descripcion; this.imagen = imagen; this.valoracion = valoracion; this.denominacion = denominacion; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } public Integer getValoracion() { return valoracion; } public void setValoracion(Integer valoracion) { this.valoracion = valoracion; } public String getDenominacion() { return denominacion; } public void setDenominacion(String denominacion) { this.denominacion = denominacion; } public ArrayList<Comentario> getListaComentarios() { return listaComentarios; } public void setListaComentarios(ArrayList<Comentario> listaComentarios) { this.listaComentarios = listaComentarios; } public void añadirComentario(Comentario c){ this.listaComentarios.add(c); } }
2,144
0.670089
0.670089
82
25.134146
25.418816
148
false
false
0
0
0
0
0
0
0.512195
false
false
10
1e66eb16571790a2b1131847fb5572be600d94a4
29,343,216,633,486
c3971d4d30fc7ac35eed4347c988002cb0ec5d50
/src/main/java/net/minestom/server/event/player/PlayerStopFlyingWithElytraEvent.java
314f16e227a8fcac883fa833099f72b69d2e5257
[ "Apache-2.0" ]
permissive
andrew-bilotti/Minestom
https://github.com/andrew-bilotti/Minestom
b28922c52ba0273c13992c98412e00eac1c8484b
a749f07a3f1480a7aee070f2c473c897275ba02f
refs/heads/master
2023-05-08T10:43:08.293000
2021-05-21T12:56:30
2021-05-21T12:56:30
370,536,129
0
0
Apache-2.0
true
2021-05-25T02:02:29
2021-05-25T02:02:28
2021-05-23T10:10:50
2021-05-24T21:39:27
69,098
0
0
0
null
false
false
package net.minestom.server.event.player; import net.minestom.server.entity.Player; import net.minestom.server.event.PlayerEvent; import org.jetbrains.annotations.NotNull; public class PlayerStopFlyingWithElytraEvent extends PlayerEvent { public PlayerStopFlyingWithElytraEvent(@NotNull Player player) { super(player); } }
UTF-8
Java
342
java
PlayerStopFlyingWithElytraEvent.java
Java
[]
null
[]
package net.minestom.server.event.player; import net.minestom.server.entity.Player; import net.minestom.server.event.PlayerEvent; import org.jetbrains.annotations.NotNull; public class PlayerStopFlyingWithElytraEvent extends PlayerEvent { public PlayerStopFlyingWithElytraEvent(@NotNull Player player) { super(player); } }
342
0.795322
0.795322
12
27.5
24.971651
68
false
false
0
0
0
0
0
0
0.416667
false
false
10
95fb5c640a8912efdd10186d3f95dca9513c7e53
29,343,216,635,687
a80eb16daf4f0fcd36be592cba8b08971004ab79
/src/main/java/com/decipherzone/usernotification/model/User.java
3882db703be8f536cc50c41289e3c67cae82823e
[]
no_license
03rohitj/SpringBoot-User-Notification
https://github.com/03rohitj/SpringBoot-User-Notification
0a879af45b93450bbc65bbb85c11c76f89fe13cd
00853e1cf6d077da40efc066e7c7859f4dbf7a9b
refs/heads/master
2023-04-26T15:34:37.290000
2021-05-19T09:54:21
2021-05-19T09:54:21
364,625,357
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.decipherzone.usernotification.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import javax.persistence.*; import java.util.HashSet; import java.util.Set; /** User model to store a user's information */ @RequiredArgsConstructor @NoArgsConstructor @Getter @Setter @ToString(exclude = "notifications") @Entity public @Data class User extends EntityId{ @NonNull @Column(nullable = false, length = 50) private String name; @NonNull @Column(nullable = false, length = 50, unique = true) private String email; @NonNull @Column(nullable = false, unique = true, scale = 10) private String phone; /** To store list of notifications sent to the user */ @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JsonIgnore private Set<Notification> notifications = new HashSet<>(); }
UTF-8
Java
897
java
User.java
Java
[]
null
[]
package com.decipherzone.usernotification.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import javax.persistence.*; import java.util.HashSet; import java.util.Set; /** User model to store a user's information */ @RequiredArgsConstructor @NoArgsConstructor @Getter @Setter @ToString(exclude = "notifications") @Entity public @Data class User extends EntityId{ @NonNull @Column(nullable = false, length = 50) private String name; @NonNull @Column(nullable = false, length = 50, unique = true) private String email; @NonNull @Column(nullable = false, unique = true, scale = 10) private String phone; /** To store list of notifications sent to the user */ @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JsonIgnore private Set<Notification> notifications = new HashSet<>(); }
897
0.715719
0.70903
36
23.916666
22.150213
85
false
false
0
0
0
0
0
0
0.472222
false
false
10
26b7d3856d5779a4f906b792f313429a7da6116c
13,795,434,997,680
9fac8f5186f4ef1633eebd71744cb0b74051a4b2
/nuxeo-features/rest-api/nuxeo-rest-api-test/src/test/java/org/nuxeo/ecm/restapi/test/SchemaTest.java
981ef49948f5e676e843d9c22d1eaf42e90da295
[ "Apache-2.0" ]
permissive
sampisamuel/nuxeo
https://github.com/sampisamuel/nuxeo
588e6f468b9cc4292a169f25e64f71edff811910
7ec7c164e508223eef05bb198066920399440efe
refs/heads/master
2020-05-25T13:11:33.468000
2019-05-19T12:15:45
2019-05-20T17:36:52
187,803,485
1
0
Apache-2.0
true
2019-05-21T09:16:14
2019-05-21T09:16:13
2019-05-20T17:37:00
2019-05-20T17:37:15
370,313
0
0
0
null
false
false
/* * (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * Guillaume Renard <grenard@nuxeo.com> */ package org.nuxeo.ecm.restapi.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.ecm.core.io.marshallers.json.types.SchemaJsonWriter; import org.nuxeo.ecm.core.test.annotations.Granularity; import org.nuxeo.ecm.core.test.annotations.RepositoryConfig; import org.nuxeo.jaxrs.test.CloseableClientResponse; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; import com.fasterxml.jackson.databind.JsonNode; import com.sun.jersey.core.util.MultivaluedMapImpl; /** * @since 9.1 */ @RunWith(FeaturesRunner.class) @Features({ RestServerFeature.class }) @RepositoryConfig(init = RestServerInit.class, cleanup = Granularity.METHOD) public class SchemaTest extends BaseTest { @Test public void testFieldsWithConstraintsFetch() throws IOException { // Given the dublincore // When I call the schema Rest endpoint MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.putSingle("fetch." + SchemaJsonWriter.ENTITY_TYPE, SchemaJsonWriter.FETCH_FIELDS); try (CloseableClientResponse response = getResponse(RequestType.GET, "/schema/dublincore", queryParams)) { // Then it returns the dublincore schema Json with constraints assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); JsonNode node = mapper.readTree(response.getEntityInputStream()); JsonNode fields = node.get("fields"); assertNotNull(fields); JsonNode creator = fields.get("creator"); assertNotNull(creator); JsonNode type = creator.get("type"); assertNotNull(type); assertEquals("string", type.textValue()); JsonNode constraints = creator.get("constraints"); assertNotNull(constraints); assertTrue(constraints.isArray()); assertTrue(constraints.size() > 0); JsonNode contributors = fields.get("contributors"); assertNotNull(contributors); type = contributors.get("type"); assertNotNull(type); assertEquals("string[]", type.textValue()); constraints = contributors.get("constraints"); assertNotNull(constraints); assertTrue(constraints.isArray()); JsonNode itemConstraints = contributors.get("itemConstraints"); assertNotNull(itemConstraints); assertTrue(itemConstraints.isArray()); assertTrue(itemConstraints.size() > 0); } } }
UTF-8
Java
3,518
java
SchemaTest.java
Java
[ { "context": "ions under the License.\n *\n * Contributors:\n * Guillaume Renard <grenard@nuxeo.com>\n */\npackage org.nuxeo.ecm.res", "end": 667, "score": 0.9998575448989868, "start": 651, "tag": "NAME", "value": "Guillaume Renard" }, { "context": "nse.\n *\n * Contributors:\n * Guillaume Renard <grenard@nuxeo.com>\n */\npackage org.nuxeo.ecm.restapi.test;\n\nimport ", "end": 686, "score": 0.9999253749847412, "start": 669, "tag": "EMAIL", "value": "grenard@nuxeo.com" } ]
null
[]
/* * (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * <NAME> <<EMAIL>> */ package org.nuxeo.ecm.restapi.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.ecm.core.io.marshallers.json.types.SchemaJsonWriter; import org.nuxeo.ecm.core.test.annotations.Granularity; import org.nuxeo.ecm.core.test.annotations.RepositoryConfig; import org.nuxeo.jaxrs.test.CloseableClientResponse; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; import com.fasterxml.jackson.databind.JsonNode; import com.sun.jersey.core.util.MultivaluedMapImpl; /** * @since 9.1 */ @RunWith(FeaturesRunner.class) @Features({ RestServerFeature.class }) @RepositoryConfig(init = RestServerInit.class, cleanup = Granularity.METHOD) public class SchemaTest extends BaseTest { @Test public void testFieldsWithConstraintsFetch() throws IOException { // Given the dublincore // When I call the schema Rest endpoint MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.putSingle("fetch." + SchemaJsonWriter.ENTITY_TYPE, SchemaJsonWriter.FETCH_FIELDS); try (CloseableClientResponse response = getResponse(RequestType.GET, "/schema/dublincore", queryParams)) { // Then it returns the dublincore schema Json with constraints assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); JsonNode node = mapper.readTree(response.getEntityInputStream()); JsonNode fields = node.get("fields"); assertNotNull(fields); JsonNode creator = fields.get("creator"); assertNotNull(creator); JsonNode type = creator.get("type"); assertNotNull(type); assertEquals("string", type.textValue()); JsonNode constraints = creator.get("constraints"); assertNotNull(constraints); assertTrue(constraints.isArray()); assertTrue(constraints.size() > 0); JsonNode contributors = fields.get("contributors"); assertNotNull(contributors); type = contributors.get("type"); assertNotNull(type); assertEquals("string[]", type.textValue()); constraints = contributors.get("constraints"); assertNotNull(constraints); assertTrue(constraints.isArray()); JsonNode itemConstraints = contributors.get("itemConstraints"); assertNotNull(itemConstraints); assertTrue(itemConstraints.isArray()); assertTrue(itemConstraints.size() > 0); } } }
3,498
0.698408
0.694997
95
36.031578
27.686764
114
false
false
0
0
0
0
0
0
0.6
false
false
10
2b6b1912363158cd369c3cb7f7609887634b6b9b
13,795,434,997,770
b00d27c2625d643b7b3ca0cea913c83c28806155
/src/Movement/LinearMovement.java
1c4c20da6448c9185f42e30fba66b7746aa12377
[]
no_license
Showyilu/Robot
https://github.com/Showyilu/Robot
f588a50f978c4ebd4ddbabc2072433602d4f0886
d742fe030488b7b5b97fd098872a7826462baf90
refs/heads/master
2020-05-20T18:48:36.439000
2013-11-03T09:22:50
2013-11-03T09:22:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Movement; import sample.SuperTank; import module.Movement; import module.Skeleton; public class LinearMovement extends Movement{ public LinearMovement(SuperTank superTank) { super(superTank); // TODO Auto-generated constructor stub } public void move(){ bot.ahead(200); bot.back(200); } }
UTF-8
Java
315
java
LinearMovement.java
Java
[]
null
[]
package Movement; import sample.SuperTank; import module.Movement; import module.Skeleton; public class LinearMovement extends Movement{ public LinearMovement(SuperTank superTank) { super(superTank); // TODO Auto-generated constructor stub } public void move(){ bot.ahead(200); bot.back(200); } }
315
0.746032
0.726984
19
15.578947
15.146011
45
false
false
0
0
0
0
0
0
1.052632
false
false
10
8a683f5802de33d73625ded00bac32aa3c5b9f06
3,899,830,367,313
a07ffe2a74135810a6eebf0308c017707493f5ae
/Android/MinBusTur/src/com/miracleas/minrute/TripLegDetailsActivity.java
429899d6369ce0b5272da54e4d5818d5c7da79f6
[]
no_license
kfn/MinBusTur
https://github.com/kfn/MinBusTur
636da008d924c26a043a56640d7db193b0486472
2a340378b7b30ae26b982b2882224db7247a665e
refs/heads/master
2016-09-10T13:51:30.094000
2013-07-01T17:27:08
2013-07-01T17:27:08
10,094,632
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.miracleas.minrute; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.miracleas.minrute.model.TripLeg; import com.miracleas.minrute.model.TripLegStop; import com.miracleas.minrute.model.TripRequest; import com.miracleas.minrute.provider.TripLegDetailMetaData; import com.miracleas.minrute.provider.StopImagesMetaData; import com.miracleas.minrute.provider.TripLegDetailStopMetaData; import com.miracleas.minrute.provider.TripLegMetaData; public class TripLegDetailsActivity extends GeofenceActivity implements TripLegDetailsFragment.Callbacks, TripLegMapFragment.Callbacks { private long mJourneyId = -1; private String mLegId = null; private String mTransportType = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_trip_leg_details); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); //actionBar.setTitle(null); // actionBar.setDisplayShowHomeEnabled(false); // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { showList(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getSupportMenuInflater().inflate(R.menu.activity_trip_leg_details, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // //finish(); //NavUtils.navigateUpFromSameTask(this); NavUtils.navigateUpTo(this, getIntent()); return true; case R.id.menu_notes: if(mJourneyId!=-1) { TripLegDetailNotesDialog.show(this, mJourneyId); } return true; case R.id.menu_map: if(mJourneyId!=-1) { /*Intent activity = new Intent(this, TripLegMapActivity.class); activity.putExtra(JourneyDetailMetaData.TableMetaData._ID, mJourneyId); activity.putExtra(JourneyDetailMetaData.TableMetaData.LEG_ID, mLegId); activity.putExtra(TripLegMetaData.TableMetaData.TYPE, mTransportType); startActivity(activity);*/ Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragmentTripLegDetailsContainer); if(f instanceof TripLegDetailsFragment) { showMap(); } else if(f instanceof TripLegMapFragment) { showList(); } } return true; default: return super.onOptionsItemSelected(item); } } private void showList() { Intent intent = getIntent(); /*String tripId = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.TRIP_ID); String legId = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.LEG_ID); String ref = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.REF); String transportType = intent.getStringExtra(TripLegMetaData.TableMetaData.TYPE); String nameOfLocation = intent.getStringExtra(TripLegMetaData.TableMetaData.ORIGIN_NAME);*/ TripLeg leg = intent.getParcelableExtra(TripLeg.tag); TripLegDetailsFragment fragment = TripLegDetailsFragment.createInstance(leg); getSupportFragmentManager().beginTransaction().replace(R.id.fragmentTripLegDetailsContainer, fragment).commit(); } private void showMap() { Intent intent = getIntent(); /*String legId = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.LEG_ID); String transportType = intent.getStringExtra(TripLegMetaData.TableMetaData.TYPE);*/ TripLeg leg = intent.getParcelableExtra(TripLeg.tag); TripLegMapFragment fragment = TripLegMapFragment.createInstance(mJourneyId+"", leg); getSupportFragmentManager().beginTransaction().replace(R.id.fragmentTripLegDetailsContainer, fragment).commit(); } @Override public void onStopSelected(TripLegStop stop, TripLeg leg) { Intent activity = new Intent(this, TripStopDetailsActivity.class); activity.putExtra(TripLegStop.tag, stop); activity.putExtra(TripLeg.tag, leg); startActivity(activity); } @Override public void setJourneyDetailId(long id, String legId, String transportType) { mJourneyId = id; mLegId = legId; mTransportType = transportType; } @Override protected void onServerResponse(boolean success) { // TODO Auto-generated method stub } }
UTF-8
Java
5,368
java
TripLegDetailsActivity.java
Java
[]
null
[]
package com.miracleas.minrute; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.miracleas.minrute.model.TripLeg; import com.miracleas.minrute.model.TripLegStop; import com.miracleas.minrute.model.TripRequest; import com.miracleas.minrute.provider.TripLegDetailMetaData; import com.miracleas.minrute.provider.StopImagesMetaData; import com.miracleas.minrute.provider.TripLegDetailStopMetaData; import com.miracleas.minrute.provider.TripLegMetaData; public class TripLegDetailsActivity extends GeofenceActivity implements TripLegDetailsFragment.Callbacks, TripLegMapFragment.Callbacks { private long mJourneyId = -1; private String mLegId = null; private String mTransportType = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_trip_leg_details); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); // Show the Up button in the action bar. actionBar.setDisplayHomeAsUpEnabled(true); //actionBar.setTitle(null); // actionBar.setDisplayShowHomeEnabled(false); // savedInstanceState is non-null when there is fragment state // saved from previous configurations of this activity // (e.g. when rotating the screen from portrait to landscape). // In this case, the fragment will automatically be re-added // to its container so we don't need to manually add it. // For more information, see the Fragments API guide at: // // http://developer.android.com/guide/components/fragments.html // if (savedInstanceState == null) { showList(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getSupportMenuInflater().inflate(R.menu.activity_trip_leg_details, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // //finish(); //NavUtils.navigateUpFromSameTask(this); NavUtils.navigateUpTo(this, getIntent()); return true; case R.id.menu_notes: if(mJourneyId!=-1) { TripLegDetailNotesDialog.show(this, mJourneyId); } return true; case R.id.menu_map: if(mJourneyId!=-1) { /*Intent activity = new Intent(this, TripLegMapActivity.class); activity.putExtra(JourneyDetailMetaData.TableMetaData._ID, mJourneyId); activity.putExtra(JourneyDetailMetaData.TableMetaData.LEG_ID, mLegId); activity.putExtra(TripLegMetaData.TableMetaData.TYPE, mTransportType); startActivity(activity);*/ Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragmentTripLegDetailsContainer); if(f instanceof TripLegDetailsFragment) { showMap(); } else if(f instanceof TripLegMapFragment) { showList(); } } return true; default: return super.onOptionsItemSelected(item); } } private void showList() { Intent intent = getIntent(); /*String tripId = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.TRIP_ID); String legId = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.LEG_ID); String ref = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.REF); String transportType = intent.getStringExtra(TripLegMetaData.TableMetaData.TYPE); String nameOfLocation = intent.getStringExtra(TripLegMetaData.TableMetaData.ORIGIN_NAME);*/ TripLeg leg = intent.getParcelableExtra(TripLeg.tag); TripLegDetailsFragment fragment = TripLegDetailsFragment.createInstance(leg); getSupportFragmentManager().beginTransaction().replace(R.id.fragmentTripLegDetailsContainer, fragment).commit(); } private void showMap() { Intent intent = getIntent(); /*String legId = intent.getStringExtra(JourneyDetailMetaData.TableMetaData.LEG_ID); String transportType = intent.getStringExtra(TripLegMetaData.TableMetaData.TYPE);*/ TripLeg leg = intent.getParcelableExtra(TripLeg.tag); TripLegMapFragment fragment = TripLegMapFragment.createInstance(mJourneyId+"", leg); getSupportFragmentManager().beginTransaction().replace(R.id.fragmentTripLegDetailsContainer, fragment).commit(); } @Override public void onStopSelected(TripLegStop stop, TripLeg leg) { Intent activity = new Intent(this, TripStopDetailsActivity.class); activity.putExtra(TripLegStop.tag, stop); activity.putExtra(TripLeg.tag, leg); startActivity(activity); } @Override public void setJourneyDetailId(long id, String legId, String transportType) { mJourneyId = id; mLegId = legId; mTransportType = transportType; } @Override protected void onServerResponse(boolean success) { // TODO Auto-generated method stub } }
5,368
0.763785
0.762854
157
33.191082
29.843569
134
false
false
0
0
0
0
0
0
2.401274
false
false
10
5c87a443c9772d7a7afb5c14990a33ec589bae6e
15,384,572,894,215
eee22a6478c37c18d861f6da30493b780bf713f0
/src/main/java/com/briup/jz/web/controller/UserController.java
ec36bdde818fd75eb6dbe6343ba6bfc2019fb825
[]
no_license
Sun-Yahui/jz
https://github.com/Sun-Yahui/jz
1a4e5816e424f4c043f76ec1da8bf7760cf1154c
a7770676dba57edfb42084ae861ac59895917049
refs/heads/master
2023-05-15T10:31:16.144000
2021-06-08T09:53:35
2021-06-08T09:53:35
378,433,104
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.briup.jz.web.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.briup.jz.bean.BaseUser; import com.briup.jz.bean.extend.BaseUserExtend; import com.briup.jz.service.IUserService; import com.briup.jz.utils.Message; import com.briup.jz.utils.MessageUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; @Api(description="用户信息相关接口") @Validated @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @ApiOperation(value = "查询用户信息") @GetMapping("query") @ApiImplicitParams({ @ApiImplicitParam(name="username",value = "用户名",paramType = "query"), @ApiImplicitParam(name="status",value = "实名制状态[正常、禁用]",paramType = "query"),}) public Message query(String username,String status){ List<BaseUser> list = userService.query(username,status); return MessageUtil.success(list); } @ApiOperation(value = "查询用户账户下所有信息") @GetMapping("selectByIdToAccount") public Message selectByIdToAccount(Long id){ return MessageUtil.success( userService.selectByIdToAccount(id)); } @ApiOperation(value = "查询用户信息") @GetMapping("read") @ApiImplicitParams({ @ApiImplicitParam(name="id",value = "id",paramType = "query",required=true)}) public Message read(long id){ BaseUserExtend list = userService.read(id); return MessageUtil.success(list); } @ApiOperation(value = "通过id删除") @GetMapping("deleteById") @ApiImplicitParams({ @ApiImplicitParam(name="id",value = "主键",paramType = "query", required=true), }) public Message deleteById(@NotNull Long id){ userService.deleteById(id); return MessageUtil.success("删除成功"); } @ApiOperation(value = "保存或更新用户信息") @ApiImplicitParams({ @ApiImplicitParam(name="id",value = "主键",paramType = "form",dataType="long"), @ApiImplicitParam(name="username",value = "用户名",paramType = "form",required=true), @ApiImplicitParam(name="password",value = "密码",paramType = "form",required=true), @ApiImplicitParam(name="telephone",value = "电话",paramType = "form"), @ApiImplicitParam(name="realname",value = "姓名",paramType = "form"), @ApiImplicitParam(name="gender",value = "性别",paramType = "form"), @ApiImplicitParam(name="birth",value = "生日",paramType = "form",dataType="long"), @ApiImplicitParam(name="email",value = "email",paramType = "form"), @ApiImplicitParam(name="status",value = "状态",paramType = "form"), @ApiImplicitParam(name="userFace",value = "用户头像",paramType = "form"), @ApiImplicitParam(name="registerCime",value = "注册时间",paramType = "form",dataType="long"), @ApiImplicitParam(name="nation",value = "民族",paramType = "form"), @ApiImplicitParam(name="idCard",value = "身份证号",paramType = "form"), @ApiImplicitParam(name="idcardPhotoPositive",value = "身份证正面",paramType = "form"), @ApiImplicitParam(name="idcardPhotoNegative",value = "身份证反面",paramType = "form"), @ApiImplicitParam(name="bankCard",value = "银行卡号",paramType = "form"), @ApiImplicitParam(name="bankCardPhoto",value = "银行卡照片",paramType = "form"), @ApiImplicitParam(name="balance",value = "账户余额",paramType = "form",dataType="long"), @ApiImplicitParam(name="certificationStatus",value = "实名制状态【正常、禁用】",paramType = "form"), @ApiImplicitParam(name="certificationTime",value = "实名制时间",paramType = "form",dataType="long") }) @PostMapping("saveOrUpdate") public Message saveOrUpdate(BaseUser baseUser){ userService.saveOrUpdate(baseUser); return MessageUtil.success("更新成功"); } // 这里是假登录 @PostMapping("login") public Message login(String username,String password) { Map<String, String> map = new HashMap<>(); map.put("token", "admin"); return MessageUtil.success(map); } // 这里是假获取用户信息 @GetMapping("info") public Message info(String token) { BaseUser user = new BaseUser(); user.setRealname("张三"); user.setUserFace("http://121.199.29.84:8888/group1/M00/00/16/rBD-SV_EpjyAa0qIAAA-lQCALyU911.jpg"); return MessageUtil.success(user); } // 这里是假退出 @PostMapping("logout") public Message logout() { return MessageUtil.success(null); } }
UTF-8
Java
5,450
java
UserController.java
Java
[ { "context": "ype=\"long\"),\r\n @ApiImplicitParam(name=\"username\",value = \"用户名\",paramType = \"form\",required=true),", "end": 2598, "score": 0.999559223651886, "start": 2590, "tag": "USERNAME", "value": "username" }, { "context": " @ApiImplicitParam(name=\"username\",value = \"用户名\",paramType = \"form\",required=true),\r\n ", "end": 2612, "score": 0.9994702339172363, "start": 2609, "tag": "USERNAME", "value": "用户名" }, { "context": " @ApiImplicitParam(name=\"password\",value = \"密码\",paramType = \"form\",required=true),\r\n ", "end": 2707, "score": 0.9968839287757874, "start": 2705, "tag": "PASSWORD", "value": "密码" }, { "context": "user = new BaseUser();\r\n user.setRealname(\"张三\");\r\n user.setUserFace(\"http://121.199.29.8", "end": 4844, "score": 0.9997310638427734, "start": 4842, "tag": "NAME", "value": "张三" }, { "context": "Realname(\"张三\");\r\n user.setUserFace(\"http://121.199.29.84:8888/group1/M00/00/16/rBD-SV_EpjyAa0qIAAA-lQCALyU", "end": 4895, "score": 0.9906985759735107, "start": 4882, "tag": "IP_ADDRESS", "value": "121.199.29.84" } ]
null
[]
package com.briup.jz.web.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.briup.jz.bean.BaseUser; import com.briup.jz.bean.extend.BaseUserExtend; import com.briup.jz.service.IUserService; import com.briup.jz.utils.Message; import com.briup.jz.utils.MessageUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; @Api(description="用户信息相关接口") @Validated @RestController @RequestMapping("/user") public class UserController { @Autowired private IUserService userService; @ApiOperation(value = "查询用户信息") @GetMapping("query") @ApiImplicitParams({ @ApiImplicitParam(name="username",value = "用户名",paramType = "query"), @ApiImplicitParam(name="status",value = "实名制状态[正常、禁用]",paramType = "query"),}) public Message query(String username,String status){ List<BaseUser> list = userService.query(username,status); return MessageUtil.success(list); } @ApiOperation(value = "查询用户账户下所有信息") @GetMapping("selectByIdToAccount") public Message selectByIdToAccount(Long id){ return MessageUtil.success( userService.selectByIdToAccount(id)); } @ApiOperation(value = "查询用户信息") @GetMapping("read") @ApiImplicitParams({ @ApiImplicitParam(name="id",value = "id",paramType = "query",required=true)}) public Message read(long id){ BaseUserExtend list = userService.read(id); return MessageUtil.success(list); } @ApiOperation(value = "通过id删除") @GetMapping("deleteById") @ApiImplicitParams({ @ApiImplicitParam(name="id",value = "主键",paramType = "query", required=true), }) public Message deleteById(@NotNull Long id){ userService.deleteById(id); return MessageUtil.success("删除成功"); } @ApiOperation(value = "保存或更新用户信息") @ApiImplicitParams({ @ApiImplicitParam(name="id",value = "主键",paramType = "form",dataType="long"), @ApiImplicitParam(name="username",value = "用户名",paramType = "form",required=true), @ApiImplicitParam(name="password",value = "密码",paramType = "form",required=true), @ApiImplicitParam(name="telephone",value = "电话",paramType = "form"), @ApiImplicitParam(name="realname",value = "姓名",paramType = "form"), @ApiImplicitParam(name="gender",value = "性别",paramType = "form"), @ApiImplicitParam(name="birth",value = "生日",paramType = "form",dataType="long"), @ApiImplicitParam(name="email",value = "email",paramType = "form"), @ApiImplicitParam(name="status",value = "状态",paramType = "form"), @ApiImplicitParam(name="userFace",value = "用户头像",paramType = "form"), @ApiImplicitParam(name="registerCime",value = "注册时间",paramType = "form",dataType="long"), @ApiImplicitParam(name="nation",value = "民族",paramType = "form"), @ApiImplicitParam(name="idCard",value = "身份证号",paramType = "form"), @ApiImplicitParam(name="idcardPhotoPositive",value = "身份证正面",paramType = "form"), @ApiImplicitParam(name="idcardPhotoNegative",value = "身份证反面",paramType = "form"), @ApiImplicitParam(name="bankCard",value = "银行卡号",paramType = "form"), @ApiImplicitParam(name="bankCardPhoto",value = "银行卡照片",paramType = "form"), @ApiImplicitParam(name="balance",value = "账户余额",paramType = "form",dataType="long"), @ApiImplicitParam(name="certificationStatus",value = "实名制状态【正常、禁用】",paramType = "form"), @ApiImplicitParam(name="certificationTime",value = "实名制时间",paramType = "form",dataType="long") }) @PostMapping("saveOrUpdate") public Message saveOrUpdate(BaseUser baseUser){ userService.saveOrUpdate(baseUser); return MessageUtil.success("更新成功"); } // 这里是假登录 @PostMapping("login") public Message login(String username,String password) { Map<String, String> map = new HashMap<>(); map.put("token", "admin"); return MessageUtil.success(map); } // 这里是假获取用户信息 @GetMapping("info") public Message info(String token) { BaseUser user = new BaseUser(); user.setRealname("张三"); user.setUserFace("http://172.16.58.3:8888/group1/M00/00/16/rBD-SV_EpjyAa0qIAAA-lQCALyU911.jpg"); return MessageUtil.success(user); } // 这里是假退出 @PostMapping("logout") public Message logout() { return MessageUtil.success(null); } }
5,448
0.661725
0.656847
122
40.032787
30.062757
106
false
false
0
0
0
0
0
0
1.065574
false
false
10
a82b14630640b0f9ad56fe9cb742f6d53afc3576
26,130,581,062,022
06b9c570f14800deb01eb01f19f038a6b4b0e3d1
/src/main/java/com/onsemi/dots/config/DotsFtpConfigOld.java
980ac3b747ee849ceebef2f91e01d7e479a8912f
[]
no_license
farhannazri27/dots
https://github.com/farhannazri27/dots
72540f6aa6c9c1666b1ad0d9863d02d3b05bd0f3
562575e66003924895217083f5061cfd6bf04a13
refs/heads/master
2021-01-11T11:44:26.201000
2018-08-13T02:02:33
2018-08-13T02:02:33
76,820,269
0
1
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.onsemi.dots.config; import com.onsemi.dots.dao.LotPenangDAO; import com.onsemi.dots.dao.RequestDAO; import com.onsemi.dots.model.FinalRequestTemp; import com.onsemi.dots.model.LotPenang; import com.onsemi.dots.model.LotPenangTemp; import com.onsemi.dots.model.Request; import com.onsemi.dots.model.RequestTemp; import com.onsemi.dots.tools.CSV; import com.onsemi.dots.tools.EmailSender; import com.onsemi.dots.tools.QueryResult; import com.opencsv.CSVReader; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.servlet.ServletContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; /** * * @author fg79cj */ //@Configuration //@EnableScheduling public class DotsFtpConfigOld { private static final Logger LOGGER = LoggerFactory.getLogger(DotsFtpConfigOld.class); @Autowired ServletContext servletContext; // @Scheduled(cron = "0 20 * * * *") //every hour 30 minutes public void DownloadCsv() throws IOException { CSVReader csvReader = null; // LOGGER.info("cron detected!!!"); try { /** * Reading the CSV File Delimiter is comma Start reading from line 1 * */ File file = new File("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); // File file = new File("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); if (file.exists()) { LOGGER.info("File dots_rms_ftp found!!!"); csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); String[] inventory = null; //Create List for holding Employee objects List<RequestTemp> empList = new ArrayList<RequestTemp>(); while ((inventory = csvReader.readNext()) != null) { //Save the employee details in Employee object RequestTemp emp = new RequestTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7], inventory[8], inventory[9], inventory[10], inventory[11]); empList.add(emp); } //Lets print the Inventory List for (RequestTemp e : empList) { // check rms_event + interval exist or not RequestDAO reqD = new RequestDAO(); // int countRms = reqD.getCountRequestRmsLotEventInterval(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); int countRms = reqD.getCountRequestRmsLotEventIntervalRmsId(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval(), e.getRmsId()); if (countRms == 0) { Request req = new Request(); req.setRms(e.getRms()); req.setEvent(e.getEvent()); req.setLotId(e.getLotId()); req.setDevice(e.getDevice()); req.setPackages(e.getPackages()); req.setInterval(e.getInterval()); if (e.getQuantity() != null) { if (!"".equals(e.getQuantity())) { req.setQuantity(e.getQuantity()); } else { req.setQuantity("0"); } } else { req.setQuantity("0"); } String expectedCondition = ""; if (!"".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " / " + e.getExpectedMaxCondition() + " `C"; } else if (!"".equals(e.getExpectedMinCondition()) && "".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " `C"; } else if ("".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMaxCondition() + " `C"; } else { expectedCondition = ""; } req.setExpectedTestCondition(expectedCondition); String shortLoadingDate = null; String shortUnloadingDate = null; if (!"".equals(e.getExpectedLoading())) { DateFormat shortFormatLoading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatLoading = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); String loadingdate = e.getExpectedLoading(); shortLoadingDate = shortFormatLoading.format(mediumFormatLoading.parse(loadingdate)); } if (!"".equals(e.getExpectedUnloading())) { DateFormat shortFormatUnloading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatUnloading = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); String unloadingdate = e.getExpectedUnloading(); shortUnloadingDate = shortFormatUnloading.format(mediumFormatUnloading.parse(unloadingdate)); } req.setLoadingDate(shortLoadingDate); req.setUnloadingDate(shortUnloadingDate); req.setStatus("New"); String rms_event = e.getRms() + e.getLotId() + "_" + e.getEvent(); req.setRmsEvent(rms_event); req.setRmsId(e.getRmsId()); req.setFlag("0"); req.setCreatedBy("From Ftp"); reqD = new RequestDAO(); // QueryResult add = reqD.insertRequestFromFtp(req); QueryResult add2 = reqD.insertRequestWithRmsIdFromFtp(req); if (add2.getGeneratedKey().equals("0")) { LOGGER.info("Fail to insert data from FTP"); } else { // LOGGER.info("succeed to insert data from FTP"); } } else if (countRms > 1) { LOGGER.info("Data have more than 1 in DB. Please re-check"); } else { //update existing interval reqD = new RequestDAO(); // Request request = reqD.getRequestByRmsLotEventIntervalForFtp(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); Request request = reqD.getRequestByRmsLotEventIntervalRmsIdForFtp(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval(), e.getRmsId()); String shortLoadingDateDb = ""; String shortLoadingDateFtp = ""; String shortUnloadingDateDb = ""; String shortUnloadingDateFtp = ""; if (!"".equals(e.getExpectedLoading())) { DateFormat shortFormatLoadingFtp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingFtp = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); shortLoadingDateFtp = shortFormatLoadingFtp.format(mediumFormatLoadingFtp.parse(e.getExpectedLoading())); } if (request.getLoadingDate() != null) { DateFormat shortFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); shortLoadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(request.getLoadingDate())); } if (!"".equals(e.getExpectedUnloading())) { DateFormat shortFormatLoadingFtp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingFtp = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); shortUnloadingDateFtp = shortFormatLoadingFtp.format(mediumFormatLoadingFtp.parse(e.getExpectedUnloading())); } if (request.getUnloadingDate() != null) { DateFormat shortFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); shortUnloadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(request.getUnloadingDate())); } if (!"".equals(shortLoadingDateFtp) && (!shortLoadingDateDb.equals(shortLoadingDateFtp) || !shortUnloadingDateDb.equals(shortUnloadingDateFtp)) && "0".equals(request.getFlag())) { LOGGER.info("first stage..loadingFtp" + shortLoadingDateFtp + ", shortLoadingDateDb - " + shortLoadingDateDb + ", shortUnloadingDateDb - " + shortUnloadingDateDb + ", shortUnloadingDateFtp - " + shortUnloadingDateFtp); Request req = new Request(); DateFormat shortFormatLoading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatLoading = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); String loadingdate = e.getExpectedLoading(); String shortLoadingDate = shortFormatLoading.format(mediumFormatLoading.parse(loadingdate)); DateFormat shortFormatUnloading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatUnloading = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); String unloadingdate = e.getExpectedUnloading(); String shortUnloadingDate = shortFormatUnloading.format(mediumFormatUnloading.parse(unloadingdate)); req.setLoadingDate(shortLoadingDate); req.setUnloadingDate(shortUnloadingDate); req.setRms(e.getRms()); req.setLotId(e.getLotId()); req.setEvent(e.getEvent()); req.setInterval(e.getInterval()); req.setModifiedBy("From FTP"); reqD = new RequestDAO(); QueryResult update = reqD.updateRequestLoadingAndUnloadingDateFTP(req); if (update.getResult() == 0) { LOGGER.info("Fail to update data from FTP"); } else { LOGGER.info("update rmsFtp [" + e.getRms() + e.getLotId() + "_" + e.getEvent() + " - " + e.getInterval() + "]"); } } String expectedCondition = ""; if (!"".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " / " + e.getExpectedMaxCondition() + " `C"; } else if (!"".equals(e.getExpectedMinCondition()) && "".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " `C"; } else if ("".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMaxCondition() + " `C"; } else { expectedCondition = ""; LOGGER.info("No expectedCondition..."); } if (request.getExpectedTestCondition() == null) { // LOGGER.info("Second Stage..."); Request req = new Request(); req.setExpectedTestCondition(expectedCondition); req.setRms(e.getRms()); req.setLotId(e.getLotId()); req.setEvent(e.getEvent()); req.setInterval(e.getInterval()); req.setModifiedBy("From FTP"); reqD = new RequestDAO(); QueryResult update = reqD.updateRequestExpectedConditionFTP(req); if (update.getResult() == 0) { LOGGER.info("Fail to update expected condition data from FTP"); } else { LOGGER.info("succeed to update expected condition data from FTP"); } } } } } else { LOGGER.info("csv file not found!"); } } catch (Exception ee) { ee.printStackTrace(); } } // @Scheduled(cron = "0 22 * * * *") //every hour 30 minutes public void updateCSV() throws IOException { CSVReader csvReader = null; try { //update csv File filePenang = new File("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"); if (filePenang.exists()) { LOGGER.info("dh ada header"); FileWriter fileWriter = null; FileReader fileReader = null; try { fileWriter = new FileWriter("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv", true); fileReader = new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"); String targetLocation = "\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"; BufferedReader bufferedReader = new BufferedReader(fileReader); String data = bufferedReader.readLine(); StringBuilder buff = new StringBuilder(); boolean flag = false; boolean sentEmail = false; int row = 0; while (data != null && flag == false) { buff.append(data).append(System.getProperty("line.separator")); String[] split = data.split(","); FinalRequestTemp inventoryPenang = new FinalRequestTemp( split[0], split[1], split[2], split[3], split[4], split[5], split[6], split[7], split[8], split[9], split[10], split[11], split[12], split[13], split[14], split[15], split[16], split[17], split[18] //status = [18] ); RequestDAO lotD = new RequestDAO(); int count = lotD.getCountRequestID(split[0]); if (count == 1) { lotD = new RequestDAO(); Request lot = lotD.getRequest(split[0]); // LOGGER.info("id = " + split[0] + ", loadingDateCsv = " + split[13] + ", loadingDateDb = " + lot.getLoadingDate() + ", unloadingDate = " + split[14]); DateFormat shortFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String shortLoadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(lot.getLoadingDate())); String shortLoadingDateCsv = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(split[13])); String shortUnloadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(lot.getUnloadingDate())); String shortUnloadingDateCsv = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(split[14])); if ((!shortLoadingDateDb.equals(shortLoadingDateCsv)) || (!shortUnloadingDateDb.equals(shortUnloadingDateCsv))) { CSV csv = new CSV(); csv.open(new File(targetLocation)); csv.put(13, row, lot.getLoadingDate()); csv.put(14, row, lot.getUnloadingDate()); csv.save(new File(targetLocation)); sentEmail = true; LOGGER.info("update csv loading & unloading [" + split[0] + "]"); } else { flag = false; LOGGER.info("no update: " + split[13] + " = " + lot.getLoadingDate()); } } data = bufferedReader.readLine(); row++; } bufferedReader.close(); fileReader.close(); if (sentEmail == true) { EmailSender emailSenderToHIMSSF = new EmailSender(); com.onsemi.dots.model.User user = new com.onsemi.dots.model.User(); user.setFullname("POTS"); String[] to = {"potspenang@gmail.com", "fg79cj@onsemi.com"}; emailSenderToHIMSSF.htmlEmailWithAttachment( servletContext, // user name user, // to to, // attachment file new File("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"), // subject "List of RMS_event Ship from Rel Lab", // msg "List of RMS_event Ship from Rel Lab. " ); } } catch (Exception ee) { System.out.println("Error 1 occured while append the fileWriter"); } finally { try { fileWriter.close(); } catch (IOException ie) { System.out.println("Error 2 occured while closing the fileWriter"); } } } else { LOGGER.info("File dots_planner not exists................."); } } catch (Exception ee) { ee.printStackTrace(); } } //update from pots_receive.csv // @Scheduled(cron = "0 */3 * * * *") //every 3 minutes public void updatePotsReceiveCsv() throws IOException { CSVReader csvReader = null; // LOGGER.info("cron detected222!!!"); try { File file = new File("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_receive.csv"); // File file = new File("C:\\Users\\fg79cj\\Documents\\test_receive.csv"); // File file = new File("D:\\DOTS\\POTS_CSV\\pots_receive.csv"); if (file.exists()) { csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_receive.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("C:\\Users\\fg79cj\\Documents\\test_receive.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\POTS_CSV\\pots_receive.csv"), ',', '"', 1); String[] inventory = null; //Create List for holding Employee objects List<LotPenangTemp> empList = new ArrayList<LotPenangTemp>(); while ((inventory = csvReader.readNext()) != null) { //Save the employee details in Employee object LotPenangTemp emp = new LotPenangTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7], inventory[8], inventory[9], inventory[10], inventory[11], inventory[12], inventory[13], inventory[14], inventory[15], inventory[16], inventory[17], inventory[18], inventory[19]); empList.add(emp); } for (LotPenangTemp e : empList) { LotPenangDAO lotD = new LotPenangDAO(); LotPenang lot = lotD.getLotPenangByRequestId(e.getRequestId()); if (lot.getReceivedDate() == null && !"null".equals(e.getReceivedDate())) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getReceivedDate(); String shortReceivedDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); DateFormat actualFormatVerification = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat originalFormatVerification = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String verificationDate = e.getReceivedVerificationDate(); String actualVerificationDate = actualFormatVerification.format(originalFormatVerification.parse(verificationDate)); LotPenang lotR = new LotPenang(); lotR.setStatus("Received in Penang"); lotR.setReceivedBy(e.getReceivedBy()); lotR.setReceivedDate(shortReceivedDate); lotR.setReceivedQuantity(e.getReceivedQuantity()); lotR.setReceivedVerificationStatus(e.getReceivedVerificationStatus()); lotR.setReceivedVerificationDate(actualVerificationDate); lotR.setReceivedMixStatus(e.getReceivedMixStatus()); lotR.setReceivedMixRemarks(e.getReceivedMixRemarks()); lotR.setReceivedDemountStatus(e.getReceivedDemountStatus()); lotR.setReceivedDemountRemarks(e.getReceivedDemountRemarks()); lotR.setReceivedBrokenStatus(e.getReceivedBrokenStatus()); lotR.setReceivedBrokenRemarks(e.getReceivedBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenPenangReceived(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_receive FTP"); } else { Request req = new Request(); req.setStatus("Received in Penang"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_receive FTP FTP"); } } else if (lot.getReceivedDate() != null && !"null".equals(e.getReceivedDate())) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getReceivedDate(); String actualReceivedDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm", Locale.ENGLISH); String receivedDateftp = e.getReceivedDate(); String actualReceivedDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualReceivedDateftp.equals(actualReceivedDatedb)) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getReceivedDate(); String shortReceivedDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); DateFormat actualFormatVerification = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat originalFormatVerification = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String verificationDate = e.getReceivedVerificationDate(); String actualVerificationDate = actualFormatVerification.format(originalFormatVerification.parse(verificationDate)); LotPenang lotR = new LotPenang(); lotR.setStatus("Received in Penang"); lotR.setReceivedBy(e.getReceivedBy()); lotR.setReceivedDate(shortReceivedDate); lotR.setReceivedQuantity(e.getReceivedQuantity()); lotR.setReceivedVerificationStatus(e.getReceivedVerificationStatus()); lotR.setReceivedVerificationDate(actualVerificationDate); lotR.setReceivedMixStatus(e.getReceivedMixStatus()); lotR.setReceivedMixRemarks(e.getReceivedMixRemarks()); lotR.setReceivedDemountStatus(e.getReceivedDemountStatus()); lotR.setReceivedDemountRemarks(e.getReceivedDemountRemarks()); lotR.setReceivedBrokenStatus(e.getReceivedBrokenStatus()); lotR.setReceivedBrokenRemarks(e.getReceivedBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenPenangReceived(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_receive FTP"); } else { Request req = new Request(); req.setStatus("Received in Penang"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_receive FTP FTP"); } } else { // LOGGER.info("no update from POTS_receive FTP FTP"); } } else { // LOGGER.info("no data received from POTS_receive FTP FTP"); } } } else { LOGGER.info("pots_receive csv file not found!"); } //pots_process File filePotProcess = new File("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_process.csv"); // File filePotProcess = new File("C:\\Users\\fg79cj\\Documents\\test_process.csv"); // File filePotProcess = new File("D:\\DOTS\\POTS_CSV\\pots_process.csv"); if (filePotProcess.exists()) { csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_process.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("C:\\Users\\fg79cj\\Documents\\test_process.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\POTS_CSV\\pots_process.csv"), ',', '"', 1); String[] inventory = null; List<LotPenangTemp> empList = new ArrayList<LotPenangTemp>(); while ((inventory = csvReader.readNext()) != null) { LotPenangTemp emp = new LotPenangTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7], inventory[8], inventory[9], inventory[10], inventory[11], inventory[12], inventory[13], inventory[14], inventory[15], inventory[16], inventory[17], inventory[18], inventory[19], inventory[20], inventory[21]); empList.add(emp); } for (LotPenangTemp e : empList) { LotPenangDAO lotD = new LotPenangDAO(); LotPenang lot = lotD.getLotPenangByRequestId(e.getRequestId()); //loading if (lot.getLoadingDate() == null && !"null".equals(e.getLoadingDate())) { LotPenang lotR = new LotPenang(); DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getLoadingDate(); String shortLoadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); lotR.setLoadingDate(shortLoadingDate); lotR.setStatus("Loading Process"); lotR.setChamberId(e.getChamberId()); lotR.setChamberLevel(e.getChamberLevel()); lotR.setTestCondition(e.getTestCondition()); lotR.setLoadingRemarks(e.getLoadingRemarks()); lotR.setLoadingBy(e.getLoadingBy()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenLoading(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data loading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Loading Process"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data loading from POTS_process FTP FTP"); } } else if (!"null".equals(e.getLoadingDate()) && lot.getLoadingDate() != null) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getLoadingDate(); String actualLoadingDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm", Locale.ENGLISH); String receivedDateftp = e.getLoadingDate(); String actualLoadingDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualLoadingDateftp.equals(actualLoadingDatedb)) { LotPenang lotR = new LotPenang(); DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getLoadingDate(); String shortLoadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); lotR.setLoadingDate(shortLoadingDate); lotR.setStatus("Loading Process"); lotR.setChamberId(e.getChamberId()); lotR.setChamberLevel(e.getChamberLevel()); lotR.setTestCondition(e.getTestCondition()); lotR.setLoadingRemarks(e.getLoadingRemarks()); lotR.setLoadingBy(e.getLoadingBy()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenLoading(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data loading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Loading Process"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data loading from POTS_processs FTP FTP"); } } else { // LOGGER.info("no update loading from POTS_process FTP FTP"); } } else if ("null".equals(e.getLoadingDate()) && lot.getLoadingDate() != null) { // LOGGER.info("no data loading from POTS_process FTP FTP [ftp null]"); } else { // LOGGER.info("no data loading from POTS_process FTP FTP [both null]"); } //unloading if (lot.getUnloadingDate() == null && !"null".equals(e.getUnloadingDate())) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); // DateFormat mediumFormatReceived = new SimpleDateFormat("yyyy/MM/dd hh:mm a", Locale.ENGLISH); String receivedDate = e.getUnloadingDate(); String shortUnloadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); LotPenang lotR = new LotPenang(); lotR.setUnloadingDate(shortUnloadingDate); lotR.setStatus("Unloading Process"); lotR.setUnloadingRemarks(e.getUnloadingRemarks()); lotR.setUnloadingBy(e.getUnloadingBy()); lotR.setUnloadingMixStatus(e.getUnloadingMixStatus()); lotR.setUnloadingMixRemarks(e.getUnloadingMixRemarks()); lotR.setUnloadingDemountStatus(e.getUnloadingDemountStatus()); lotR.setUnloadingDemountRemarks(e.getUnloadingDemountRemarks()); lotR.setUnloadingBrokenStatus(e.getUnloadingBrokenStatus()); lotR.setUnloadingBrokenRemarks(e.getUnloadingBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); // QueryResult add = lotdD.updateLotPenangWhenUnloading(lotR); QueryResult add = lotdD.updateLotPenangWhenUnloadingWithVM(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data unloading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Unloading Process"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data unloading from POTS_process FTP FTP"); } } else if (lot.getUnloadingDate() != null && !"null".equals(e.getUnloadingDate())) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getUnloadingDate(); String actualLoadingDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm", Locale.ENGLISH); String receivedDateftp = e.getUnloadingDate(); String actualLoadingDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualLoadingDateftp.equals(actualLoadingDatedb)) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getUnloadingDate(); String shortUnloadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); LotPenang lotR = new LotPenang(); lotR.setUnloadingDate(shortUnloadingDate); lotR.setStatus("Unloading Process"); lotR.setUnloadingRemarks(e.getUnloadingRemarks()); lotR.setUnloadingBy(e.getUnloadingBy()); lotR.setUnloadingMixStatus(e.getUnloadingMixStatus()); lotR.setUnloadingMixRemarks(e.getUnloadingMixRemarks()); lotR.setUnloadingDemountStatus(e.getUnloadingDemountStatus()); lotR.setUnloadingDemountRemarks(e.getUnloadingDemountRemarks()); lotR.setUnloadingBrokenStatus(e.getUnloadingBrokenStatus()); lotR.setUnloadingBrokenRemarks(e.getUnloadingBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); // QueryResult add = lotdD.updateLotPenangWhenUnloading(lotR); QueryResult add = lotdD.updateLotPenangWhenUnloadingWithVM(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data unloading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Unloading Process"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data unloading from POTS_processs FTP FTP"); } } else { // LOGGER.info("no update unloading from POTS_process FTP FTP"); } } else if ("null".equals(e.getUnloadingDate()) && lot.getUnloadingDate() != null) { // LOGGER.info("no data unloading from POTS_process FTP FTP [ftp null]"); } else { // LOGGER.info("no data unloading from POTS_process FTP FTP [both null]"); } } } else { LOGGER.info("csv pot_proecss file not found!"); } //shipment from penang File filePotsShipment = new File("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_shipment.csv"); // File filePotsShipment = new File("D:\\DOTS\\POTS_CSV\\pots_shipment.csv"); if (filePotsShipment.exists()) { csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_shipment.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\POTS_CSV\\pots_shipment.csv"), ',', '"', 1); String[] inventory = null; //Create List for holding Employee objects List<LotPenangTemp> empList = new ArrayList<LotPenangTemp>(); while ((inventory = csvReader.readNext()) != null) { //Save the employee details in Employee object LotPenangTemp emp = new LotPenangTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7]); empList.add(emp); } for (LotPenangTemp e : empList) { LotPenangDAO lotD = new LotPenangDAO(); LotPenang lot = lotD.getLotPenangByRequestId(e.getRequestId()); if (lot.getShipmentDate() == null && !"null".equals(e.getShipmentDate())) { LotPenang lotR = new LotPenang(); DateFormat actualReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat ftpFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getShipmentDate(); String actualReceivedDate = actualReceived.format(ftpFormatReceived.parse(receivedDate)); lotR.setStatus("Ship to Rel Lab"); lotR.setShipmentBy(e.getShipmentBy()); lotR.setShipmentDate(actualReceivedDate); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenShipToRel(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_shipment FTP"); } else { Request req = new Request(); req.setStatus("Ship to Rel Lab"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_shipment FTP FTP"); } } else if (lot.getShipmentDate() != null && !"null".equals(e.getShipmentDate())) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getShipmentDate(); String actualReceivedDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDateftp = e.getShipmentDate(); String actualReceivedDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualReceivedDateftp.equals(actualReceivedDatedb)) { LotPenang lotR = new LotPenang(); DateFormat actualReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat ftpFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getShipmentDate(); String actualReceivedDate = actualReceived.format(ftpFormatReceived.parse(receivedDate)); lotR.setStatus("Ship to Rel Lab"); lotR.setShipmentBy(e.getShipmentBy()); lotR.setShipmentDate(actualReceivedDate); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenShipToRel(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_shipment FTP"); } else { Request req = new Request(); req.setStatus("Ship to Rel Lab"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_shipment FTP FTP"); } } else { // LOGGER.info("no update from POTS_shipment FTP FTP"); } } else { // LOGGER.info("no data received from POTS_shipment FTP FTP"); } } } else { LOGGER.info("pots_shipment csv file not found!"); } } catch (Exception ee) { ee.printStackTrace(); } } //temporary for update rmsid // @Scheduled(cron = "0 42 * * * *") //every hour 30 minutes // public void updateRmsIdFtp() throws IOException { // // CSVReader csvReader = null; // // LOGGER.info("cron detected!!!"); // // try { // /** // * Reading the CSV File Delimiter is comma Start reading from line 1 // * // */ // // File file = new File("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); // // File file = new File("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); // // if (file.exists()) { // LOGGER.info("File dots_rms_ftp found!!!"); // csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); // // csvReader = new CSVReader(new FileReader("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); // // String[] inventory = null; // //Create List for holding Employee objects // List<RequestTemp> empList = new ArrayList<RequestTemp>(); // // while ((inventory = csvReader.readNext()) != null) { // //Save the employee details in Employee object // RequestTemp emp = new RequestTemp(inventory[0], // inventory[1], inventory[2], // inventory[3], inventory[4], // inventory[5], inventory[6], // inventory[7], inventory[8], inventory[9], inventory[10], inventory[11]); // empList.add(emp); // } // // //Lets print the Inventory List // for (RequestTemp e : empList) { // // // check rms_event + interval exist or not // RequestDAO reqD = new RequestDAO(); // int countRms = reqD.getCountRequestRmsLotEventInterval(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); // if (countRms > 1) { // LOGGER.info("Data have more than 1 in DB. Please re-check"); // } else if (countRms == 0) { // Request req = new Request(); // req.setRms(e.getRms()); // req.setEvent(e.getEvent()); // req.setLotId(e.getLotId()); // req.setDevice(e.getDevice()); // req.setPackages(e.getPackages()); // req.setInterval(e.getInterval()); // if (e.getQuantity() != null) { // if (!"".equals(e.getQuantity())) { // req.setQuantity(e.getQuantity()); // } else { // req.setQuantity("0"); // } // } else { // req.setQuantity("0"); // } // String expectedCondition = ""; // if (!"".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { // expectedCondition = e.getExpectedMinCondition() + " / " + e.getExpectedMaxCondition() + " `C"; // } else if (!"".equals(e.getExpectedMinCondition()) && "".equals(e.getExpectedMaxCondition())) { // expectedCondition = e.getExpectedMinCondition() + " `C"; // } else if ("".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { // expectedCondition = e.getExpectedMaxCondition() + " `C"; // // } else { // expectedCondition = ""; // } // req.setExpectedTestCondition(expectedCondition); // String shortLoadingDate = null; // String shortUnloadingDate = null; // if (!"".equals(e.getExpectedLoading())) { // DateFormat shortFormatLoading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); // DateFormat mediumFormatLoading = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); // String loadingdate = e.getExpectedLoading(); // shortLoadingDate = shortFormatLoading.format(mediumFormatLoading.parse(loadingdate)); // } // if (!"".equals(e.getExpectedUnloading())) { // DateFormat shortFormatUnloading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); // DateFormat mediumFormatUnloading = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); // String unloadingdate = e.getExpectedUnloading(); // shortUnloadingDate = shortFormatUnloading.format(mediumFormatUnloading.parse(unloadingdate)); // } // // req.setLoadingDate(shortLoadingDate); // req.setUnloadingDate(shortUnloadingDate); // req.setStatus("New"); // // String rms_event = e.getRms() + e.getLotId() + "_" + e.getEvent(); // req.setRmsEvent(rms_event); // req.setRmsId(e.getRmsId()); // req.setFlag("0"); // req.setCreatedBy("From Ftp"); // reqD = new RequestDAO(); // QueryResult add = reqD.insertRequestWithRmsIdFromFtp(req); // if (add.getGeneratedKey().equals("0")) { // LOGGER.info("Fail to insert data from FTP"); // } else { // // LOGGER.info("succeed to insert data from FTP"); // } // } else { // // reqD = new RequestDAO(); // Request request = reqD.getRequestByRmsLotEventIntervalForFtp(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); // // //update rmsid // if (request.getRmsId() == null) { // Request requestRmsId = new Request(); // requestRmsId.setRmsId(e.getRmsId()); // requestRmsId.setId(request.getId()); // reqD = new RequestDAO(); // QueryResult updateRmsId = reqD.updateRequestRmsIdFTP(requestRmsId); // } // } // } // // } else { // LOGGER.info("csv file not found!"); // } // // } catch (Exception ee) { // ee.printStackTrace(); // } // // } }
UTF-8
Java
59,049
java
DotsFtpConfigOld.java
Java
[ { "context": "uling.annotation.Scheduled;\r\n\r\n/**\r\n *\r\n * @author fg79cj\r\n */\r\n//@Configuration\r\n//@EnableScheduling\r\npubl", "end": 1372, "score": 0.9995549917221069, "start": 1366, "tag": "USERNAME", "value": "fg79cj" }, { "context": "ser();\r\n user.setFullname(\"POTS\");\r\n String[] to = {\"potsp", "end": 19518, "score": 0.9972284436225891, "start": 19514, "tag": "NAME", "value": "POTS" }, { "context": "\"POTS\");\r\n String[] to = {\"potspenang@gmail.com\", \"fg79cj@onsemi.com\"};\r\n ", "end": 19583, "score": 0.9999260902404785, "start": 19563, "tag": "EMAIL", "value": "potspenang@gmail.com" }, { "context": " String[] to = {\"potspenang@gmail.com\", \"fg79cj@onsemi.com\"};\r\n emailSenderToHIMSSF.h", "end": 19604, "score": 0.9999291300773621, "start": 19587, "tag": "EMAIL", "value": "fg79cj@onsemi.com" }, { "context": " // File file = new File(\"C:\\\\Users\\\\fg79cj\\\\Documents\\\\test_receive.csv\");\r\n // ", "end": 21457, "score": 0.9988433718681335, "start": 21451, "tag": "USERNAME", "value": "fg79cj" }, { "context": "Reader = new CSVReader(new FileReader(\"C:\\\\Users\\\\fg79cj\\\\Documents\\\\test_receive.csv\"), ',', '\"', 1);\r\n ", "end": 21853, "score": 0.9989745616912842, "start": 21847, "tag": "USERNAME", "value": "fg79cj" }, { "context": ";\r\n req.setModifiedBy(\"Penang CSV\");\r\n req.setId(e.getRe", "end": 25852, "score": 0.9519274830818176, "start": 25842, "tag": "NAME", "value": "Penang CSV" }, { "context": " req.setModifiedBy(\"Penang CSV\");\r\n req.setId(e.g", "end": 29916, "score": 0.7152972221374512, "start": 29909, "tag": "NAME", "value": "ang CSV" }, { "context": " File filePotProcess = new File(\"C:\\\\Users\\\\fg79cj\\\\Documents\\\\test_process.csv\");\r\n // ", "end": 30980, "score": 0.9994709491729736, "start": 30974, "tag": "USERNAME", "value": "fg79cj" }, { "context": "Reader = new CSVReader(new FileReader(\"C:\\\\Users\\\\fg79cj\\\\Documents\\\\test_process.csv\"), ',', '\"', 1);\r\n ", "end": 31396, "score": 0.9994220733642578, "start": 31390, "tag": "USERNAME", "value": "fg79cj" }, { "context": ";\r\n req.setModifiedBy(\"Penang CSV\");\r\n req.setId(e.getRe", "end": 34384, "score": 0.924354612827301, "start": 34374, "tag": "NAME", "value": "Penang CSV" }, { "context": ";\r\n req.setModifiedBy(\"Penang CSV\");\r\n req.setId(e.getRe", "end": 40670, "score": 0.9948897361755371, "start": 40660, "tag": "NAME", "value": "Penang CSV" }, { "context": " req.setModifiedBy(\"Penang CSV\");\r\n req.setId(e.g", "end": 44212, "score": 0.998953640460968, "start": 44202, "tag": "NAME", "value": "Penang CSV" }, { "context": ";\r\n req.setModifiedBy(\"Penang CSV\");\r\n req.setId(e.getRe", "end": 48108, "score": 0.992168664932251, "start": 48098, "tag": "NAME", "value": "Penang CSV" }, { "context": " req.setModifiedBy(\"Penang CSV\");\r\n req.setId(e.g", "end": 50867, "score": 0.9992533326148987, "start": 50857, "tag": "NAME", "value": "Penang CSV" } ]
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.onsemi.dots.config; import com.onsemi.dots.dao.LotPenangDAO; import com.onsemi.dots.dao.RequestDAO; import com.onsemi.dots.model.FinalRequestTemp; import com.onsemi.dots.model.LotPenang; import com.onsemi.dots.model.LotPenangTemp; import com.onsemi.dots.model.Request; import com.onsemi.dots.model.RequestTemp; import com.onsemi.dots.tools.CSV; import com.onsemi.dots.tools.EmailSender; import com.onsemi.dots.tools.QueryResult; import com.opencsv.CSVReader; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.servlet.ServletContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; /** * * @author fg79cj */ //@Configuration //@EnableScheduling public class DotsFtpConfigOld { private static final Logger LOGGER = LoggerFactory.getLogger(DotsFtpConfigOld.class); @Autowired ServletContext servletContext; // @Scheduled(cron = "0 20 * * * *") //every hour 30 minutes public void DownloadCsv() throws IOException { CSVReader csvReader = null; // LOGGER.info("cron detected!!!"); try { /** * Reading the CSV File Delimiter is comma Start reading from line 1 * */ File file = new File("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); // File file = new File("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); if (file.exists()) { LOGGER.info("File dots_rms_ftp found!!!"); csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); String[] inventory = null; //Create List for holding Employee objects List<RequestTemp> empList = new ArrayList<RequestTemp>(); while ((inventory = csvReader.readNext()) != null) { //Save the employee details in Employee object RequestTemp emp = new RequestTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7], inventory[8], inventory[9], inventory[10], inventory[11]); empList.add(emp); } //Lets print the Inventory List for (RequestTemp e : empList) { // check rms_event + interval exist or not RequestDAO reqD = new RequestDAO(); // int countRms = reqD.getCountRequestRmsLotEventInterval(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); int countRms = reqD.getCountRequestRmsLotEventIntervalRmsId(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval(), e.getRmsId()); if (countRms == 0) { Request req = new Request(); req.setRms(e.getRms()); req.setEvent(e.getEvent()); req.setLotId(e.getLotId()); req.setDevice(e.getDevice()); req.setPackages(e.getPackages()); req.setInterval(e.getInterval()); if (e.getQuantity() != null) { if (!"".equals(e.getQuantity())) { req.setQuantity(e.getQuantity()); } else { req.setQuantity("0"); } } else { req.setQuantity("0"); } String expectedCondition = ""; if (!"".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " / " + e.getExpectedMaxCondition() + " `C"; } else if (!"".equals(e.getExpectedMinCondition()) && "".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " `C"; } else if ("".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMaxCondition() + " `C"; } else { expectedCondition = ""; } req.setExpectedTestCondition(expectedCondition); String shortLoadingDate = null; String shortUnloadingDate = null; if (!"".equals(e.getExpectedLoading())) { DateFormat shortFormatLoading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatLoading = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); String loadingdate = e.getExpectedLoading(); shortLoadingDate = shortFormatLoading.format(mediumFormatLoading.parse(loadingdate)); } if (!"".equals(e.getExpectedUnloading())) { DateFormat shortFormatUnloading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatUnloading = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); String unloadingdate = e.getExpectedUnloading(); shortUnloadingDate = shortFormatUnloading.format(mediumFormatUnloading.parse(unloadingdate)); } req.setLoadingDate(shortLoadingDate); req.setUnloadingDate(shortUnloadingDate); req.setStatus("New"); String rms_event = e.getRms() + e.getLotId() + "_" + e.getEvent(); req.setRmsEvent(rms_event); req.setRmsId(e.getRmsId()); req.setFlag("0"); req.setCreatedBy("From Ftp"); reqD = new RequestDAO(); // QueryResult add = reqD.insertRequestFromFtp(req); QueryResult add2 = reqD.insertRequestWithRmsIdFromFtp(req); if (add2.getGeneratedKey().equals("0")) { LOGGER.info("Fail to insert data from FTP"); } else { // LOGGER.info("succeed to insert data from FTP"); } } else if (countRms > 1) { LOGGER.info("Data have more than 1 in DB. Please re-check"); } else { //update existing interval reqD = new RequestDAO(); // Request request = reqD.getRequestByRmsLotEventIntervalForFtp(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); Request request = reqD.getRequestByRmsLotEventIntervalRmsIdForFtp(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval(), e.getRmsId()); String shortLoadingDateDb = ""; String shortLoadingDateFtp = ""; String shortUnloadingDateDb = ""; String shortUnloadingDateFtp = ""; if (!"".equals(e.getExpectedLoading())) { DateFormat shortFormatLoadingFtp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingFtp = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); shortLoadingDateFtp = shortFormatLoadingFtp.format(mediumFormatLoadingFtp.parse(e.getExpectedLoading())); } if (request.getLoadingDate() != null) { DateFormat shortFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); shortLoadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(request.getLoadingDate())); } if (!"".equals(e.getExpectedUnloading())) { DateFormat shortFormatLoadingFtp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingFtp = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); shortUnloadingDateFtp = shortFormatLoadingFtp.format(mediumFormatLoadingFtp.parse(e.getExpectedUnloading())); } if (request.getUnloadingDate() != null) { DateFormat shortFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); shortUnloadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(request.getUnloadingDate())); } if (!"".equals(shortLoadingDateFtp) && (!shortLoadingDateDb.equals(shortLoadingDateFtp) || !shortUnloadingDateDb.equals(shortUnloadingDateFtp)) && "0".equals(request.getFlag())) { LOGGER.info("first stage..loadingFtp" + shortLoadingDateFtp + ", shortLoadingDateDb - " + shortLoadingDateDb + ", shortUnloadingDateDb - " + shortUnloadingDateDb + ", shortUnloadingDateFtp - " + shortUnloadingDateFtp); Request req = new Request(); DateFormat shortFormatLoading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatLoading = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); String loadingdate = e.getExpectedLoading(); String shortLoadingDate = shortFormatLoading.format(mediumFormatLoading.parse(loadingdate)); DateFormat shortFormatUnloading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatUnloading = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); String unloadingdate = e.getExpectedUnloading(); String shortUnloadingDate = shortFormatUnloading.format(mediumFormatUnloading.parse(unloadingdate)); req.setLoadingDate(shortLoadingDate); req.setUnloadingDate(shortUnloadingDate); req.setRms(e.getRms()); req.setLotId(e.getLotId()); req.setEvent(e.getEvent()); req.setInterval(e.getInterval()); req.setModifiedBy("From FTP"); reqD = new RequestDAO(); QueryResult update = reqD.updateRequestLoadingAndUnloadingDateFTP(req); if (update.getResult() == 0) { LOGGER.info("Fail to update data from FTP"); } else { LOGGER.info("update rmsFtp [" + e.getRms() + e.getLotId() + "_" + e.getEvent() + " - " + e.getInterval() + "]"); } } String expectedCondition = ""; if (!"".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " / " + e.getExpectedMaxCondition() + " `C"; } else if (!"".equals(e.getExpectedMinCondition()) && "".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMinCondition() + " `C"; } else if ("".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { expectedCondition = e.getExpectedMaxCondition() + " `C"; } else { expectedCondition = ""; LOGGER.info("No expectedCondition..."); } if (request.getExpectedTestCondition() == null) { // LOGGER.info("Second Stage..."); Request req = new Request(); req.setExpectedTestCondition(expectedCondition); req.setRms(e.getRms()); req.setLotId(e.getLotId()); req.setEvent(e.getEvent()); req.setInterval(e.getInterval()); req.setModifiedBy("From FTP"); reqD = new RequestDAO(); QueryResult update = reqD.updateRequestExpectedConditionFTP(req); if (update.getResult() == 0) { LOGGER.info("Fail to update expected condition data from FTP"); } else { LOGGER.info("succeed to update expected condition data from FTP"); } } } } } else { LOGGER.info("csv file not found!"); } } catch (Exception ee) { ee.printStackTrace(); } } // @Scheduled(cron = "0 22 * * * *") //every hour 30 minutes public void updateCSV() throws IOException { CSVReader csvReader = null; try { //update csv File filePenang = new File("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"); if (filePenang.exists()) { LOGGER.info("dh ada header"); FileWriter fileWriter = null; FileReader fileReader = null; try { fileWriter = new FileWriter("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv", true); fileReader = new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"); String targetLocation = "\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"; BufferedReader bufferedReader = new BufferedReader(fileReader); String data = bufferedReader.readLine(); StringBuilder buff = new StringBuilder(); boolean flag = false; boolean sentEmail = false; int row = 0; while (data != null && flag == false) { buff.append(data).append(System.getProperty("line.separator")); String[] split = data.split(","); FinalRequestTemp inventoryPenang = new FinalRequestTemp( split[0], split[1], split[2], split[3], split[4], split[5], split[6], split[7], split[8], split[9], split[10], split[11], split[12], split[13], split[14], split[15], split[16], split[17], split[18] //status = [18] ); RequestDAO lotD = new RequestDAO(); int count = lotD.getCountRequestID(split[0]); if (count == 1) { lotD = new RequestDAO(); Request lot = lotD.getRequest(split[0]); // LOGGER.info("id = " + split[0] + ", loadingDateCsv = " + split[13] + ", loadingDateDb = " + lot.getLoadingDate() + ", unloadingDate = " + split[14]); DateFormat shortFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat mediumFormatLoadingDb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String shortLoadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(lot.getLoadingDate())); String shortLoadingDateCsv = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(split[13])); String shortUnloadingDateDb = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(lot.getUnloadingDate())); String shortUnloadingDateCsv = shortFormatLoadingDb.format(mediumFormatLoadingDb.parse(split[14])); if ((!shortLoadingDateDb.equals(shortLoadingDateCsv)) || (!shortUnloadingDateDb.equals(shortUnloadingDateCsv))) { CSV csv = new CSV(); csv.open(new File(targetLocation)); csv.put(13, row, lot.getLoadingDate()); csv.put(14, row, lot.getUnloadingDate()); csv.save(new File(targetLocation)); sentEmail = true; LOGGER.info("update csv loading & unloading [" + split[0] + "]"); } else { flag = false; LOGGER.info("no update: " + split[13] + " = " + lot.getLoadingDate()); } } data = bufferedReader.readLine(); row++; } bufferedReader.close(); fileReader.close(); if (sentEmail == true) { EmailSender emailSenderToHIMSSF = new EmailSender(); com.onsemi.dots.model.User user = new com.onsemi.dots.model.User(); user.setFullname("POTS"); String[] to = {"<EMAIL>", "<EMAIL>"}; emailSenderToHIMSSF.htmlEmailWithAttachment( servletContext, // user name user, // to to, // attachment file new File("\\\\mysed-rel-app03\\d$\\DOTS\\DOTS_CSV\\dots_planner.csv"), // subject "List of RMS_event Ship from Rel Lab", // msg "List of RMS_event Ship from Rel Lab. " ); } } catch (Exception ee) { System.out.println("Error 1 occured while append the fileWriter"); } finally { try { fileWriter.close(); } catch (IOException ie) { System.out.println("Error 2 occured while closing the fileWriter"); } } } else { LOGGER.info("File dots_planner not exists................."); } } catch (Exception ee) { ee.printStackTrace(); } } //update from pots_receive.csv // @Scheduled(cron = "0 */3 * * * *") //every 3 minutes public void updatePotsReceiveCsv() throws IOException { CSVReader csvReader = null; // LOGGER.info("cron detected222!!!"); try { File file = new File("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_receive.csv"); // File file = new File("C:\\Users\\fg79cj\\Documents\\test_receive.csv"); // File file = new File("D:\\DOTS\\POTS_CSV\\pots_receive.csv"); if (file.exists()) { csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_receive.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("C:\\Users\\fg79cj\\Documents\\test_receive.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\POTS_CSV\\pots_receive.csv"), ',', '"', 1); String[] inventory = null; //Create List for holding Employee objects List<LotPenangTemp> empList = new ArrayList<LotPenangTemp>(); while ((inventory = csvReader.readNext()) != null) { //Save the employee details in Employee object LotPenangTemp emp = new LotPenangTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7], inventory[8], inventory[9], inventory[10], inventory[11], inventory[12], inventory[13], inventory[14], inventory[15], inventory[16], inventory[17], inventory[18], inventory[19]); empList.add(emp); } for (LotPenangTemp e : empList) { LotPenangDAO lotD = new LotPenangDAO(); LotPenang lot = lotD.getLotPenangByRequestId(e.getRequestId()); if (lot.getReceivedDate() == null && !"null".equals(e.getReceivedDate())) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getReceivedDate(); String shortReceivedDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); DateFormat actualFormatVerification = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat originalFormatVerification = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String verificationDate = e.getReceivedVerificationDate(); String actualVerificationDate = actualFormatVerification.format(originalFormatVerification.parse(verificationDate)); LotPenang lotR = new LotPenang(); lotR.setStatus("Received in Penang"); lotR.setReceivedBy(e.getReceivedBy()); lotR.setReceivedDate(shortReceivedDate); lotR.setReceivedQuantity(e.getReceivedQuantity()); lotR.setReceivedVerificationStatus(e.getReceivedVerificationStatus()); lotR.setReceivedVerificationDate(actualVerificationDate); lotR.setReceivedMixStatus(e.getReceivedMixStatus()); lotR.setReceivedMixRemarks(e.getReceivedMixRemarks()); lotR.setReceivedDemountStatus(e.getReceivedDemountStatus()); lotR.setReceivedDemountRemarks(e.getReceivedDemountRemarks()); lotR.setReceivedBrokenStatus(e.getReceivedBrokenStatus()); lotR.setReceivedBrokenRemarks(e.getReceivedBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenPenangReceived(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_receive FTP"); } else { Request req = new Request(); req.setStatus("Received in Penang"); req.setModifiedBy("<NAME>"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_receive FTP FTP"); } } else if (lot.getReceivedDate() != null && !"null".equals(e.getReceivedDate())) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getReceivedDate(); String actualReceivedDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm", Locale.ENGLISH); String receivedDateftp = e.getReceivedDate(); String actualReceivedDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualReceivedDateftp.equals(actualReceivedDatedb)) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getReceivedDate(); String shortReceivedDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); DateFormat actualFormatVerification = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat originalFormatVerification = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String verificationDate = e.getReceivedVerificationDate(); String actualVerificationDate = actualFormatVerification.format(originalFormatVerification.parse(verificationDate)); LotPenang lotR = new LotPenang(); lotR.setStatus("Received in Penang"); lotR.setReceivedBy(e.getReceivedBy()); lotR.setReceivedDate(shortReceivedDate); lotR.setReceivedQuantity(e.getReceivedQuantity()); lotR.setReceivedVerificationStatus(e.getReceivedVerificationStatus()); lotR.setReceivedVerificationDate(actualVerificationDate); lotR.setReceivedMixStatus(e.getReceivedMixStatus()); lotR.setReceivedMixRemarks(e.getReceivedMixRemarks()); lotR.setReceivedDemountStatus(e.getReceivedDemountStatus()); lotR.setReceivedDemountRemarks(e.getReceivedDemountRemarks()); lotR.setReceivedBrokenStatus(e.getReceivedBrokenStatus()); lotR.setReceivedBrokenRemarks(e.getReceivedBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenPenangReceived(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_receive FTP"); } else { Request req = new Request(); req.setStatus("Received in Penang"); req.setModifiedBy("Pen<NAME>"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_receive FTP FTP"); } } else { // LOGGER.info("no update from POTS_receive FTP FTP"); } } else { // LOGGER.info("no data received from POTS_receive FTP FTP"); } } } else { LOGGER.info("pots_receive csv file not found!"); } //pots_process File filePotProcess = new File("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_process.csv"); // File filePotProcess = new File("C:\\Users\\fg79cj\\Documents\\test_process.csv"); // File filePotProcess = new File("D:\\DOTS\\POTS_CSV\\pots_process.csv"); if (filePotProcess.exists()) { csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_process.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("C:\\Users\\fg79cj\\Documents\\test_process.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\POTS_CSV\\pots_process.csv"), ',', '"', 1); String[] inventory = null; List<LotPenangTemp> empList = new ArrayList<LotPenangTemp>(); while ((inventory = csvReader.readNext()) != null) { LotPenangTemp emp = new LotPenangTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7], inventory[8], inventory[9], inventory[10], inventory[11], inventory[12], inventory[13], inventory[14], inventory[15], inventory[16], inventory[17], inventory[18], inventory[19], inventory[20], inventory[21]); empList.add(emp); } for (LotPenangTemp e : empList) { LotPenangDAO lotD = new LotPenangDAO(); LotPenang lot = lotD.getLotPenangByRequestId(e.getRequestId()); //loading if (lot.getLoadingDate() == null && !"null".equals(e.getLoadingDate())) { LotPenang lotR = new LotPenang(); DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getLoadingDate(); String shortLoadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); lotR.setLoadingDate(shortLoadingDate); lotR.setStatus("Loading Process"); lotR.setChamberId(e.getChamberId()); lotR.setChamberLevel(e.getChamberLevel()); lotR.setTestCondition(e.getTestCondition()); lotR.setLoadingRemarks(e.getLoadingRemarks()); lotR.setLoadingBy(e.getLoadingBy()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenLoading(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data loading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Loading Process"); req.setModifiedBy("<NAME>"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data loading from POTS_process FTP FTP"); } } else if (!"null".equals(e.getLoadingDate()) && lot.getLoadingDate() != null) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getLoadingDate(); String actualLoadingDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm", Locale.ENGLISH); String receivedDateftp = e.getLoadingDate(); String actualLoadingDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualLoadingDateftp.equals(actualLoadingDatedb)) { LotPenang lotR = new LotPenang(); DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getLoadingDate(); String shortLoadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); lotR.setLoadingDate(shortLoadingDate); lotR.setStatus("Loading Process"); lotR.setChamberId(e.getChamberId()); lotR.setChamberLevel(e.getChamberLevel()); lotR.setTestCondition(e.getTestCondition()); lotR.setLoadingRemarks(e.getLoadingRemarks()); lotR.setLoadingBy(e.getLoadingBy()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenLoading(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data loading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Loading Process"); req.setModifiedBy("Penang CSV"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data loading from POTS_processs FTP FTP"); } } else { // LOGGER.info("no update loading from POTS_process FTP FTP"); } } else if ("null".equals(e.getLoadingDate()) && lot.getLoadingDate() != null) { // LOGGER.info("no data loading from POTS_process FTP FTP [ftp null]"); } else { // LOGGER.info("no data loading from POTS_process FTP FTP [both null]"); } //unloading if (lot.getUnloadingDate() == null && !"null".equals(e.getUnloadingDate())) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); // DateFormat mediumFormatReceived = new SimpleDateFormat("yyyy/MM/dd hh:mm a", Locale.ENGLISH); String receivedDate = e.getUnloadingDate(); String shortUnloadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); LotPenang lotR = new LotPenang(); lotR.setUnloadingDate(shortUnloadingDate); lotR.setStatus("Unloading Process"); lotR.setUnloadingRemarks(e.getUnloadingRemarks()); lotR.setUnloadingBy(e.getUnloadingBy()); lotR.setUnloadingMixStatus(e.getUnloadingMixStatus()); lotR.setUnloadingMixRemarks(e.getUnloadingMixRemarks()); lotR.setUnloadingDemountStatus(e.getUnloadingDemountStatus()); lotR.setUnloadingDemountRemarks(e.getUnloadingDemountRemarks()); lotR.setUnloadingBrokenStatus(e.getUnloadingBrokenStatus()); lotR.setUnloadingBrokenRemarks(e.getUnloadingBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); // QueryResult add = lotdD.updateLotPenangWhenUnloading(lotR); QueryResult add = lotdD.updateLotPenangWhenUnloadingWithVM(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data unloading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Unloading Process"); req.setModifiedBy("<NAME>"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data unloading from POTS_process FTP FTP"); } } else if (lot.getUnloadingDate() != null && !"null".equals(e.getUnloadingDate())) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getUnloadingDate(); String actualLoadingDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm", Locale.ENGLISH); String receivedDateftp = e.getUnloadingDate(); String actualLoadingDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualLoadingDateftp.equals(actualLoadingDatedb)) { DateFormat shortFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat mediumFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getUnloadingDate(); String shortUnloadingDate = shortFormatReceived.format(mediumFormatReceived.parse(receivedDate)); LotPenang lotR = new LotPenang(); lotR.setUnloadingDate(shortUnloadingDate); lotR.setStatus("Unloading Process"); lotR.setUnloadingRemarks(e.getUnloadingRemarks()); lotR.setUnloadingBy(e.getUnloadingBy()); lotR.setUnloadingMixStatus(e.getUnloadingMixStatus()); lotR.setUnloadingMixRemarks(e.getUnloadingMixRemarks()); lotR.setUnloadingDemountStatus(e.getUnloadingDemountStatus()); lotR.setUnloadingDemountRemarks(e.getUnloadingDemountRemarks()); lotR.setUnloadingBrokenStatus(e.getUnloadingBrokenStatus()); lotR.setUnloadingBrokenRemarks(e.getUnloadingBrokenRemarks()); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); // QueryResult add = lotdD.updateLotPenangWhenUnloading(lotR); QueryResult add = lotdD.updateLotPenangWhenUnloadingWithVM(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data unloading from POTS_process FTP"); } else { Request req = new Request(); req.setStatus("Unloading Process"); req.setModifiedBy("<NAME>"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data unloading from POTS_processs FTP FTP"); } } else { // LOGGER.info("no update unloading from POTS_process FTP FTP"); } } else if ("null".equals(e.getUnloadingDate()) && lot.getUnloadingDate() != null) { // LOGGER.info("no data unloading from POTS_process FTP FTP [ftp null]"); } else { // LOGGER.info("no data unloading from POTS_process FTP FTP [both null]"); } } } else { LOGGER.info("csv pot_proecss file not found!"); } //shipment from penang File filePotsShipment = new File("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_shipment.csv"); // File filePotsShipment = new File("D:\\DOTS\\POTS_CSV\\pots_shipment.csv"); if (filePotsShipment.exists()) { csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\POTS_CSV\\pots_shipment.csv"), ',', '"', 1); // csvReader = new CSVReader(new FileReader("D:\\DOTS\\POTS_CSV\\pots_shipment.csv"), ',', '"', 1); String[] inventory = null; //Create List for holding Employee objects List<LotPenangTemp> empList = new ArrayList<LotPenangTemp>(); while ((inventory = csvReader.readNext()) != null) { //Save the employee details in Employee object LotPenangTemp emp = new LotPenangTemp(inventory[0], inventory[1], inventory[2], inventory[3], inventory[4], inventory[5], inventory[6], inventory[7]); empList.add(emp); } for (LotPenangTemp e : empList) { LotPenangDAO lotD = new LotPenangDAO(); LotPenang lot = lotD.getLotPenangByRequestId(e.getRequestId()); if (lot.getShipmentDate() == null && !"null".equals(e.getShipmentDate())) { LotPenang lotR = new LotPenang(); DateFormat actualReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat ftpFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getShipmentDate(); String actualReceivedDate = actualReceived.format(ftpFormatReceived.parse(receivedDate)); lotR.setStatus("Ship to Rel Lab"); lotR.setShipmentBy(e.getShipmentBy()); lotR.setShipmentDate(actualReceivedDate); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenShipToRel(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_shipment FTP"); } else { Request req = new Request(); req.setStatus("Ship to Rel Lab"); req.setModifiedBy("<NAME>"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_shipment FTP FTP"); } } else if (lot.getShipmentDate() != null && !"null".equals(e.getShipmentDate())) { DateFormat actualFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceiveddb = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); String receivedDatedb = lot.getShipmentDate(); String actualReceivedDatedb = actualFormatReceiveddb.format(originalFormatReceiveddb.parse(receivedDatedb)); DateFormat actualFormatReceivedftp = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH); DateFormat originalFormatReceivedftp = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDateftp = e.getShipmentDate(); String actualReceivedDateftp = actualFormatReceivedftp.format(originalFormatReceivedftp.parse(receivedDateftp)); if (!actualReceivedDateftp.equals(actualReceivedDatedb)) { LotPenang lotR = new LotPenang(); DateFormat actualReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); DateFormat ftpFormatReceived = new SimpleDateFormat("dd/MM/yy hh:mm a", Locale.ENGLISH); String receivedDate = e.getShipmentDate(); String actualReceivedDate = actualReceived.format(ftpFormatReceived.parse(receivedDate)); lotR.setStatus("Ship to Rel Lab"); lotR.setShipmentBy(e.getShipmentBy()); lotR.setShipmentDate(actualReceivedDate); lotR.setRequestId(e.getRequestId()); LotPenangDAO lotdD = new LotPenangDAO(); QueryResult add = lotdD.updateLotPenangWhenShipToRel(lotR); if (add.getResult() == 0) { LOGGER.info("Fail to insert data from POTS_shipment FTP"); } else { Request req = new Request(); req.setStatus("Ship to Rel Lab"); req.setModifiedBy("<NAME>"); req.setId(e.getRequestId()); RequestDAO reqD = new RequestDAO(); QueryResult reqStatus = reqD.updateRequestStatus(req); // LOGGER.info("succeed to insert data from POTS_shipment FTP FTP"); } } else { // LOGGER.info("no update from POTS_shipment FTP FTP"); } } else { // LOGGER.info("no data received from POTS_shipment FTP FTP"); } } } else { LOGGER.info("pots_shipment csv file not found!"); } } catch (Exception ee) { ee.printStackTrace(); } } //temporary for update rmsid // @Scheduled(cron = "0 42 * * * *") //every hour 30 minutes // public void updateRmsIdFtp() throws IOException { // // CSVReader csvReader = null; // // LOGGER.info("cron detected!!!"); // // try { // /** // * Reading the CSV File Delimiter is comma Start reading from line 1 // * // */ // // File file = new File("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); // // File file = new File("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"); // // if (file.exists()) { // LOGGER.info("File dots_rms_ftp found!!!"); // csvReader = new CSVReader(new FileReader("\\\\mysed-rel-app03\\d$\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); // // csvReader = new CSVReader(new FileReader("D:\\DOTS\\RMS_FTP\\dots_rms_ftp.csv"), ',', '"', 1); // // String[] inventory = null; // //Create List for holding Employee objects // List<RequestTemp> empList = new ArrayList<RequestTemp>(); // // while ((inventory = csvReader.readNext()) != null) { // //Save the employee details in Employee object // RequestTemp emp = new RequestTemp(inventory[0], // inventory[1], inventory[2], // inventory[3], inventory[4], // inventory[5], inventory[6], // inventory[7], inventory[8], inventory[9], inventory[10], inventory[11]); // empList.add(emp); // } // // //Lets print the Inventory List // for (RequestTemp e : empList) { // // // check rms_event + interval exist or not // RequestDAO reqD = new RequestDAO(); // int countRms = reqD.getCountRequestRmsLotEventInterval(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); // if (countRms > 1) { // LOGGER.info("Data have more than 1 in DB. Please re-check"); // } else if (countRms == 0) { // Request req = new Request(); // req.setRms(e.getRms()); // req.setEvent(e.getEvent()); // req.setLotId(e.getLotId()); // req.setDevice(e.getDevice()); // req.setPackages(e.getPackages()); // req.setInterval(e.getInterval()); // if (e.getQuantity() != null) { // if (!"".equals(e.getQuantity())) { // req.setQuantity(e.getQuantity()); // } else { // req.setQuantity("0"); // } // } else { // req.setQuantity("0"); // } // String expectedCondition = ""; // if (!"".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { // expectedCondition = e.getExpectedMinCondition() + " / " + e.getExpectedMaxCondition() + " `C"; // } else if (!"".equals(e.getExpectedMinCondition()) && "".equals(e.getExpectedMaxCondition())) { // expectedCondition = e.getExpectedMinCondition() + " `C"; // } else if ("".equals(e.getExpectedMinCondition()) && !"".equals(e.getExpectedMaxCondition())) { // expectedCondition = e.getExpectedMaxCondition() + " `C"; // // } else { // expectedCondition = ""; // } // req.setExpectedTestCondition(expectedCondition); // String shortLoadingDate = null; // String shortUnloadingDate = null; // if (!"".equals(e.getExpectedLoading())) { // DateFormat shortFormatLoading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); // DateFormat mediumFormatLoading = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.ENGLISH); // String loadingdate = e.getExpectedLoading(); // shortLoadingDate = shortFormatLoading.format(mediumFormatLoading.parse(loadingdate)); // } // if (!"".equals(e.getExpectedUnloading())) { // DateFormat shortFormatUnloading = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); // DateFormat mediumFormatUnloading = new SimpleDateFormat("dd-MMM-yy hh:mm a", Locale.ENGLISH); // String unloadingdate = e.getExpectedUnloading(); // shortUnloadingDate = shortFormatUnloading.format(mediumFormatUnloading.parse(unloadingdate)); // } // // req.setLoadingDate(shortLoadingDate); // req.setUnloadingDate(shortUnloadingDate); // req.setStatus("New"); // // String rms_event = e.getRms() + e.getLotId() + "_" + e.getEvent(); // req.setRmsEvent(rms_event); // req.setRmsId(e.getRmsId()); // req.setFlag("0"); // req.setCreatedBy("From Ftp"); // reqD = new RequestDAO(); // QueryResult add = reqD.insertRequestWithRmsIdFromFtp(req); // if (add.getGeneratedKey().equals("0")) { // LOGGER.info("Fail to insert data from FTP"); // } else { // // LOGGER.info("succeed to insert data from FTP"); // } // } else { // // reqD = new RequestDAO(); // Request request = reqD.getRequestByRmsLotEventIntervalForFtp(e.getRms(), e.getLotId(), e.getEvent(), e.getInterval()); // // //update rmsid // if (request.getRmsId() == null) { // Request requestRmsId = new Request(); // requestRmsId.setRmsId(e.getRmsId()); // requestRmsId.setId(request.getId()); // reqD = new RequestDAO(); // QueryResult updateRmsId = reqD.updateRequestRmsIdFTP(requestRmsId); // } // } // } // // } else { // LOGGER.info("csv file not found!"); // } // // } catch (Exception ee) { // ee.printStackTrace(); // } // // } }
59,001
0.487273
0.482904
980
58.254082
39.892811
246
false
false
0
0
0
0
0
0
0.796939
false
false
10
3c8537b219b89615d096fc4801f042593e8c0abe
28,475,633,228,586
191d48039777d47bc9fb296e5419925bd4b47d19
/Logical/collections/com/lara/HashSetDemo.java
f7240b27b3945e628d61375c942b000a58dd370a
[]
no_license
khetreJagdish/Logical
https://github.com/khetreJagdish/Logical
73155a8781e3215f74f31cf4cee60cb1777ef7fe
3b1ef5c43873a6c5617f83eb9b31de751c932385
refs/heads/master
2020-03-19T05:02:54.392000
2018-06-03T10:38:08
2018-06-03T10:38:08
135,894,796
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lara; import java.util.HashSet; import java.util.Iterator; public class HashSetDemo { public static void main(String[] args) { HashSet<Integer> hashSet = new HashSet<>(10); int[] array; for (int i = 0; i < 20; i++) { hashSet.add(i); Iterator<Integer> iterator = hashSet.iterator(); while (iterator.hasNext()) { Integer integer = (Integer) iterator.next(); System.out.println(integer); } } System.out.println(hashSet); } }
UTF-8
Java
488
java
HashSetDemo.java
Java
[]
null
[]
package com.lara; import java.util.HashSet; import java.util.Iterator; public class HashSetDemo { public static void main(String[] args) { HashSet<Integer> hashSet = new HashSet<>(10); int[] array; for (int i = 0; i < 20; i++) { hashSet.add(i); Iterator<Integer> iterator = hashSet.iterator(); while (iterator.hasNext()) { Integer integer = (Integer) iterator.next(); System.out.println(integer); } } System.out.println(hashSet); } }
488
0.635246
0.625
25
18.52
16.843088
52
false
false
0
0
0
0
0
0
2.28
false
false
10
e0a09b08b85e01f7dabb351d64de35f164110a14
11,493,332,502,302
3f0bc471522820ffabb132580f799538c4bb9d1a
/COJ_ACCEPTED/1355 - The Cross I.java
d420bb95c6e685acca1a95865b3171aee76d7eee
[]
no_license
luismoax/Competitive-Programming---luismo
https://github.com/luismoax/Competitive-Programming---luismo
d40267e7947d03a304355a1ff936c2ecb5460b77
63016024bdcff8755fe537be5eb8e46c6e6a18e6
refs/heads/master
2023-09-03T17:56:36.258000
2023-08-20T06:01:27
2023-08-20T06:01:27
250,821,058
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.Collection; import java.util.Collections; import java.util.Scanner; import java.util.Vector; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { //FileReader fr = new FileReader("d:\\in.lmo"); Scanner sc = new Scanner(System.in); while (sc.hasNext()) { double pi =3.141592653589793; double a = sc.nextDouble(); double AreaTriang = ((a/2) * (a/2 - a/3))/2; double AreaQuadCircunf = (pi*(Math.pow(a/3,2)))/4; double QuadSomber = Math.pow(a/2, 2) -(2*AreaTriang + AreaQuadCircunf); DecimalFormat df = new DecimalFormat("0.0000"); System.out.println(df.format(4*QuadSomber)); } } }
UTF-8
Java
869
java
1355 - The Cross I.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.Collection; import java.util.Collections; import java.util.Scanner; import java.util.Vector; public class Main { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { //FileReader fr = new FileReader("d:\\in.lmo"); Scanner sc = new Scanner(System.in); while (sc.hasNext()) { double pi =3.141592653589793; double a = sc.nextDouble(); double AreaTriang = ((a/2) * (a/2 - a/3))/2; double AreaQuadCircunf = (pi*(Math.pow(a/3,2)))/4; double QuadSomber = Math.pow(a/2, 2) -(2*AreaTriang + AreaQuadCircunf); DecimalFormat df = new DecimalFormat("0.0000"); System.out.println(df.format(4*QuadSomber)); } } }
869
0.690449
0.653625
34
24.588236
19.635078
74
false
false
0
0
0
0
0
0
1.823529
false
false
10
07d92117ec70fe0828e4e793025398ddcc7037fb
21,337,397,578,597
4e86753dd220add7ed25855214666dd506df18fd
/zadanie_rekr.java
7a40e7d95178479ad1aef68092000f207f360f9b
[]
no_license
dtarkowski/zadanie_prog
https://github.com/dtarkowski/zadanie_prog
6501722f89db671dd2f46e239c738fbfef6057ef
532e25f41851ce768716fdbc5d2962d024d6b61f
refs/heads/master
2021-01-01T03:56:38.117000
2016-05-12T14:20:10
2016-05-12T14:20:10
58,353,722
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class zadanie_rekr { public static void main(String[] args) { double kwota = 0; if (args.length > 0) { try { String nazwaPliku = args[0]; FileReader fileReader = new FileReader(nazwaPliku); BufferedReader reader = new BufferedReader(fileReader); String linia = null; while ((linia = reader.readLine()) != null) { if (linia != null && !linia.equals("")) { String wycinek = linia.substring(linia.indexOf("@amount:") + 8, linia.length()-3); if (wycinek != null && !wycinek.equals("")) { wycinek = wycinek.replace(",", "."); kwota += Double.parseDouble(wycinek); } } } } catch (FileNotFoundException ex) { System.out.println("brak pliku o podanej nazwie!"); } catch (IOException ex) { System.out.println("błąd odczytu pliku!"); } System.out.println(String.format("%.2f", kwota)); } else { System.out.println("brak pliku o podanej nazwie!"); } } }
UTF-8
Java
1,387
java
zadanie_rekr.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class zadanie_rekr { public static void main(String[] args) { double kwota = 0; if (args.length > 0) { try { String nazwaPliku = args[0]; FileReader fileReader = new FileReader(nazwaPliku); BufferedReader reader = new BufferedReader(fileReader); String linia = null; while ((linia = reader.readLine()) != null) { if (linia != null && !linia.equals("")) { String wycinek = linia.substring(linia.indexOf("@amount:") + 8, linia.length()-3); if (wycinek != null && !wycinek.equals("")) { wycinek = wycinek.replace(",", "."); kwota += Double.parseDouble(wycinek); } } } } catch (FileNotFoundException ex) { System.out.println("brak pliku o podanej nazwie!"); } catch (IOException ex) { System.out.println("błąd odczytu pliku!"); } System.out.println(String.format("%.2f", kwota)); } else { System.out.println("brak pliku o podanej nazwie!"); } } }
1,387
0.497473
0.493141
35
38.542858
24.990675
106
false
false
0
0
0
0
0
0
0.571429
false
false
10
a83b9913297be9534729c8a18cc4d6c7277951a1
5,626,407,158,250
ddbfd3f2df08e15951a4792ab96ac99a4136f613
/src/model/Car.java
0c3cee085590eacfe79a8c6eea907879efc50681
[]
no_license
lazyTai/BookMall
https://github.com/lazyTai/BookMall
189c7d4f23a9ff3287f122c32b449f5a1717e0e4
34e073830a1756cf56c48fe5ee485ef540a22308
refs/heads/master
2017-10-31T20:44:54.562000
2016-06-12T00:52:25
2016-06-12T00:52:25
60,905,648
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import java.util.HashSet; import java.util.Set; public class Car { int id; User user; Set<CarItem> carItems = new HashSet<>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Car(int id, User user, Book book) { super(); this.id = id; this.user = user; } public Set<CarItem> getCarItems() { return carItems; } public void setCarItems(Set<CarItem> carItems) { this.carItems = carItems; } public Car(int id) { super(); this.id = id; } public Car() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "Car [id=" + id + ", user=" + user + ", carItems=" + carItems + "]"; } }
UTF-8
Java
829
java
Car.java
Java
[]
null
[]
package model; import java.util.HashSet; import java.util.Set; public class Car { int id; User user; Set<CarItem> carItems = new HashSet<>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Car(int id, User user, Book book) { super(); this.id = id; this.user = user; } public Set<CarItem> getCarItems() { return carItems; } public void setCarItems(Set<CarItem> carItems) { this.carItems = carItems; } public Car(int id) { super(); this.id = id; } public Car() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "Car [id=" + id + ", user=" + user + ", carItems=" + carItems + "]"; } }
829
0.617612
0.617612
58
13.293103
14.940121
70
false
false
0
0
0
0
0
0
1.362069
false
false
10
5f5f363e9f38b946cff51d2fd9c0e1e212d88a27
16,234,976,432,617
0d26d715a0e66246d9a88d1ca77637c208089ec4
/fxadmin/src/main/java/com/ylxx/fx/utils/ErrorCode.java
49ec55662ef8b1527a7b729c23b0eb0d33267209
[]
no_license
lkp7321/sour
https://github.com/lkp7321/sour
ff997625c920ddbc8f8bd05307184afc748c22b7
06ac40e140bad1dc1e7b3590ce099bc02ae065f2
refs/heads/master
2021-04-12T12:18:22.408000
2018-04-26T06:22:26
2018-04-26T06:22:26
126,673,285
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ylxx.fx.utils; public enum ErrorCode { E_00("SUCCESS"), E_01("ERROR"), E_000("LOGINSUCCESS"), E_001("PRODUCTS"), E_002("PRODUCT"), E_0011("LOGINECOUNT"), E_0012("LOGINROLE"), E_0013("LOGINTIME"), E_0014("LOGINERROR"), E_0015("LOGINLOG"), E_0016("LOGINDAYS"), E_0017("LOGINFIRST"), E_0010("LOGINNONE"), E_0020("USERSUCCEESS"), E_0021("USERNONE"), E_0022("USERADD"), E_0023("USERUP"), E_0024("USERDE"), E_0025("ISUSER"), E_0026("COMITPS"), E_0027("USERFG"), E_0028("OLDPS"), E_0029("UPPS"), E_0030("DEERROR"), E_9990("NODEADMIN"), E_9991("NOFGADMIN"), E_9992("COMITADMIN"), E_9993("INITROLE"), E_9994("INITOG"), E_9995("USERUP1"), E_0031("ROLESUCCESS"), E_0032("ROLEADD"), E_0033("ROLEUP"), E_0034("ROLEDE"), E_0035("HASROLE"), E_0036("HASROLES"), E_0040("NRLRSUCCESS"), E_0041("NRLRADD"), E_0042("NRLRDE"), E_0043("NRLRFG1"), E_0044("NRLRFG2"), E_0045("NRLRNONE"), ; private String code; ErrorCode(String code){ this.code = code; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
UTF-8
Java
1,120
java
ErrorCode.java
Java
[]
null
[]
package com.ylxx.fx.utils; public enum ErrorCode { E_00("SUCCESS"), E_01("ERROR"), E_000("LOGINSUCCESS"), E_001("PRODUCTS"), E_002("PRODUCT"), E_0011("LOGINECOUNT"), E_0012("LOGINROLE"), E_0013("LOGINTIME"), E_0014("LOGINERROR"), E_0015("LOGINLOG"), E_0016("LOGINDAYS"), E_0017("LOGINFIRST"), E_0010("LOGINNONE"), E_0020("USERSUCCEESS"), E_0021("USERNONE"), E_0022("USERADD"), E_0023("USERUP"), E_0024("USERDE"), E_0025("ISUSER"), E_0026("COMITPS"), E_0027("USERFG"), E_0028("OLDPS"), E_0029("UPPS"), E_0030("DEERROR"), E_9990("NODEADMIN"), E_9991("NOFGADMIN"), E_9992("COMITADMIN"), E_9993("INITROLE"), E_9994("INITOG"), E_9995("USERUP1"), E_0031("ROLESUCCESS"), E_0032("ROLEADD"), E_0033("ROLEUP"), E_0034("ROLEDE"), E_0035("HASROLE"), E_0036("HASROLES"), E_0040("NRLRSUCCESS"), E_0041("NRLRADD"), E_0042("NRLRDE"), E_0043("NRLRFG1"), E_0044("NRLRFG2"), E_0045("NRLRNONE"), ; private String code; ErrorCode(String code){ this.code = code; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
1,120
0.613393
0.466964
65
16.215385
8.391374
35
false
false
0
0
0
0
0
0
1.707692
false
false
10
49decec7575f2fc9564e408afdf5aadb80c24abc
30,966,714,252,679
8ec9891b768212a69c0a1e9b5927666ddd026d08
/src/main/java/com/udf/ToLowerCase.java
125f55a134cd86c779ac24dcdc6035af007cf7dc
[]
no_license
liaoyusheng/hiveUDF1
https://github.com/liaoyusheng/hiveUDF1
cce6125016facfb30905d1db1b951620fe3765aa
cdde5c8454419e877b1ffe9ad299873d0a8f22ab
refs/heads/master
2022-07-10T11:00:11.501000
2020-01-01T09:11:46
2020-01-01T09:11:46
231,195,420
0
0
null
false
2022-07-01T17:43:02
2020-01-01T09:08:58
2020-01-01T09:11:49
2022-07-01T17:43:02
8
0
0
3
Java
false
false
package com.udf; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; /* * hive 用户自定义函数 * * */ public class ToLowerCase extends UDF { public Text evaluate(Text str) { if (null == str) { return null; } else if (str != null && str.getLength() <= 0) { return null; } return new Text(str.toString().toLowerCase()); } public static void main(String[] arg) { System.out.println(new ToLowerCase().evaluate(new Text(arg[0]))); } }
UTF-8
Java
547
java
ToLowerCase.java
Java
[]
null
[]
package com.udf; import org.apache.hadoop.hive.ql.exec.UDF; import org.apache.hadoop.io.Text; /* * hive 用户自定义函数 * * */ public class ToLowerCase extends UDF { public Text evaluate(Text str) { if (null == str) { return null; } else if (str != null && str.getLength() <= 0) { return null; } return new Text(str.toString().toLowerCase()); } public static void main(String[] arg) { System.out.println(new ToLowerCase().evaluate(new Text(arg[0]))); } }
547
0.581613
0.577861
25
20.32
21.023264
73
false
false
0
0
0
0
0
0
0.28
false
false
10
f1c1509155f2ccb2c80505549ba7257995f80543
4,363,686,824,160
1a132432388f4d8eee6fb9c74da8a88b99707c74
/src/main/java/com/belk/car/app/dao/hibernate/FulfillmentServiceNotesDaoHibernate.java
a2d543d90e1221c1469157ca9e9426d716481a9f
[]
no_license
Subbareddyg/CARS_new
https://github.com/Subbareddyg/CARS_new
7ed525e6f5470427e6343becd62e645e43558a6c
3024c932b54a7e0d808d887210b819bba2ccd1c1
refs/heads/master
2020-03-14T14:27:02.793000
2018-04-30T23:25:40
2018-04-30T23:25:40
131,653,774
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * @author afusy45 * Implementation of FulfillmentServiceNotesDao interface */ package com.belk.car.app.dao.hibernate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.springframework.dao.DataAccessException; import com.belk.car.app.dao.FulfillmentServiceNotesDao; import com.belk.car.app.model.Vendor; import com.belk.car.app.model.oma.FulfillmentService; import com.belk.car.app.model.oma.FulfillmentServiceNotes; import com.belk.car.app.model.oma.VendorFulfillmentNotes; @SuppressWarnings("unchecked") public class FulfillmentServiceNotesDaoHibernate extends CachedQueryDaoHibernate implements FulfillmentServiceNotesDao { /** * Returns list of all the notes for that fulfillment service from table * @param Fulfillment Service ID * @return List * @throws DataAccessException */ public List<FulfillmentServiceNotes> getFulfillmentServicesNotes (String fsID) { List<FulfillmentServiceNotes> fulfillmentServiceList = new ArrayList<FulfillmentServiceNotes>(); FulfillmentService fulfillmentService = new FulfillmentService(); fulfillmentService.setFulfillmentServiceID(new Long(fsID)); fulfillmentServiceList=getHibernateTemplate().find("FROM FulfillmentServiceNotes where fulfillmentServiceID1=?",fulfillmentService); return fulfillmentServiceList; } /** * Returns list of notes for the specific vendor ID * @param Vendor ID * @return List * @throws DataAccessException */ public List<VendorFulfillmentNotes> getVendorFulfillmentNotes(String venID) { List<VendorFulfillmentNotes> vendorFulfillmentNotesList = new ArrayList<VendorFulfillmentNotes>(); Vendor vendor=new Vendor(); vendor.setVendorId(new Long(venID)); return getHibernateTemplate().find("FROM VendorFulfillmentNotes where vendorID=?",vendor); } /** * Add/Update note to vendor fulfillment note table * @param VendorFulfillmentNotes */ public VendorFulfillmentNotes addVendorNote(VendorFulfillmentNotes vendorFulfillmentNotes) { getHibernateTemplate().saveOrUpdate(vendorFulfillmentNotes); getHibernateTemplate().flush(); return vendorFulfillmentNotes; } /** * Returns search result when searched by status,Subject and Fulfillment service ID * @return List * @param Subject, Status, FsID */ public List<FulfillmentServiceNotes> searchNoteBySubject(String subject,String fsID) { String likeFormat = "%%%1$s%%"; ArrayList<String> query = new ArrayList<String>(); ArrayList<Object> values = new ArrayList<Object>(); FulfillmentService fulfillmentService=new FulfillmentService(); fulfillmentService.setFulfillmentServiceID(new Long(fsID)); StringBuffer sqlB = new StringBuffer("from FulfillmentServiceNotes fs where fulfillmentServiceID1="+fulfillmentService.getFulfillmentServiceID()); if ((subject != null) && !(subject.equals(""))) { query.add("upper(fs.fulfillmentServiceNotesSubject) LIKE ?"); values.add(String.format(likeFormat,subject.toUpperCase(Locale.US)).toString()); } if (!query.isEmpty()) { int i=0; for(String s: query) { sqlB.append(" AND "); sqlB.append(s); i++; } } sqlB.append(" order by fs.fulfillmentServiceNoteID"); return getHibernateTemplate().find(sqlB.toString(), values.toArray()); } /** * Returns search result when searched by status,Subject and Vendor ID * @return List * @param Subject, Status, vendor ID */ public List<VendorFulfillmentNotes> searchNoteByVendorID(String subject, String venID){ String likeFormat = "%%%1$s%%"; ArrayList<String> query = new ArrayList<String>(); ArrayList<Object> values = new ArrayList<Object>(); Vendor vendor=new Vendor(); vendor.setVendorId((new Long(venID))); StringBuffer sqlB = new StringBuffer("from VendorFulfillmentNotes fs where vendorID="+vendor.getVendorId()); if (subject != null && !(subject.equals(""))) { query.add("upper(fs.vendorFulfillmentNotesSubject) LIKE ?"); values.add(String.format(likeFormat,subject.toUpperCase(Locale.US)).toString()); } if (!query.isEmpty()) { int i=0; for(String s: query) { sqlB.append(" AND "); sqlB.append(s); i++; } } sqlB.append(" order by fs.vendorFulfillmentNoteID"); return getHibernateTemplate().find(sqlB.toString(), values.toArray()); } /** * Add/Update Note to fulfillment Notes Table * @param Fulfillment Service Notes object * @throws DataAccessException */ public FulfillmentServiceNotes addNote(FulfillmentServiceNotes fulfillmentServiceNotes) { getHibernateTemplate().saveOrUpdate(fulfillmentServiceNotes); getHibernateTemplate().flush(); return fulfillmentServiceNotes; } public Map<String,Object> getNoteByID(Long fulfillmentServiceNoteID, boolean isFS){ Map<String,Object> newMap = new HashMap<String, Object>(); if(isFS){ List<FulfillmentServiceNotes> notesObject = new ArrayList<FulfillmentServiceNotes>(); notesObject = getHibernateTemplate().find("FROM FulfillmentServiceNotes where fulfillmentServiceNoteID=?",fulfillmentServiceNoteID); newMap.put("CreatedDate",notesObject.get(0).getCreatedDate()); newMap.put("CreatedBy",notesObject.get(0).getCreatedBy()); getHibernateTemplate().evict(notesObject.get(0)); }else{ List<VendorFulfillmentNotes> notesObject = new ArrayList<VendorFulfillmentNotes>(); notesObject = getHibernateTemplate().find("FROM VendorFulfillmentNotes where vendorFulfillmentNoteID=?",fulfillmentServiceNoteID); newMap.put("CreatedDate",notesObject.get(0).getCreatedDate()); newMap.put("CreatedBy",notesObject.get(0).getCreatedBy()); getHibernateTemplate().evict(notesObject.get(0)); } return newMap; } }
UTF-8
Java
5,697
java
FulfillmentServiceNotesDaoHibernate.java
Java
[ { "context": "/**\n * @author afusy45\n * Implementation of FulfillmentServiceNotesDao i", "end": 22, "score": 0.999647319316864, "start": 15, "tag": "USERNAME", "value": "afusy45" } ]
null
[]
/** * @author afusy45 * Implementation of FulfillmentServiceNotesDao interface */ package com.belk.car.app.dao.hibernate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.springframework.dao.DataAccessException; import com.belk.car.app.dao.FulfillmentServiceNotesDao; import com.belk.car.app.model.Vendor; import com.belk.car.app.model.oma.FulfillmentService; import com.belk.car.app.model.oma.FulfillmentServiceNotes; import com.belk.car.app.model.oma.VendorFulfillmentNotes; @SuppressWarnings("unchecked") public class FulfillmentServiceNotesDaoHibernate extends CachedQueryDaoHibernate implements FulfillmentServiceNotesDao { /** * Returns list of all the notes for that fulfillment service from table * @param Fulfillment Service ID * @return List * @throws DataAccessException */ public List<FulfillmentServiceNotes> getFulfillmentServicesNotes (String fsID) { List<FulfillmentServiceNotes> fulfillmentServiceList = new ArrayList<FulfillmentServiceNotes>(); FulfillmentService fulfillmentService = new FulfillmentService(); fulfillmentService.setFulfillmentServiceID(new Long(fsID)); fulfillmentServiceList=getHibernateTemplate().find("FROM FulfillmentServiceNotes where fulfillmentServiceID1=?",fulfillmentService); return fulfillmentServiceList; } /** * Returns list of notes for the specific vendor ID * @param Vendor ID * @return List * @throws DataAccessException */ public List<VendorFulfillmentNotes> getVendorFulfillmentNotes(String venID) { List<VendorFulfillmentNotes> vendorFulfillmentNotesList = new ArrayList<VendorFulfillmentNotes>(); Vendor vendor=new Vendor(); vendor.setVendorId(new Long(venID)); return getHibernateTemplate().find("FROM VendorFulfillmentNotes where vendorID=?",vendor); } /** * Add/Update note to vendor fulfillment note table * @param VendorFulfillmentNotes */ public VendorFulfillmentNotes addVendorNote(VendorFulfillmentNotes vendorFulfillmentNotes) { getHibernateTemplate().saveOrUpdate(vendorFulfillmentNotes); getHibernateTemplate().flush(); return vendorFulfillmentNotes; } /** * Returns search result when searched by status,Subject and Fulfillment service ID * @return List * @param Subject, Status, FsID */ public List<FulfillmentServiceNotes> searchNoteBySubject(String subject,String fsID) { String likeFormat = "%%%1$s%%"; ArrayList<String> query = new ArrayList<String>(); ArrayList<Object> values = new ArrayList<Object>(); FulfillmentService fulfillmentService=new FulfillmentService(); fulfillmentService.setFulfillmentServiceID(new Long(fsID)); StringBuffer sqlB = new StringBuffer("from FulfillmentServiceNotes fs where fulfillmentServiceID1="+fulfillmentService.getFulfillmentServiceID()); if ((subject != null) && !(subject.equals(""))) { query.add("upper(fs.fulfillmentServiceNotesSubject) LIKE ?"); values.add(String.format(likeFormat,subject.toUpperCase(Locale.US)).toString()); } if (!query.isEmpty()) { int i=0; for(String s: query) { sqlB.append(" AND "); sqlB.append(s); i++; } } sqlB.append(" order by fs.fulfillmentServiceNoteID"); return getHibernateTemplate().find(sqlB.toString(), values.toArray()); } /** * Returns search result when searched by status,Subject and Vendor ID * @return List * @param Subject, Status, vendor ID */ public List<VendorFulfillmentNotes> searchNoteByVendorID(String subject, String venID){ String likeFormat = "%%%1$s%%"; ArrayList<String> query = new ArrayList<String>(); ArrayList<Object> values = new ArrayList<Object>(); Vendor vendor=new Vendor(); vendor.setVendorId((new Long(venID))); StringBuffer sqlB = new StringBuffer("from VendorFulfillmentNotes fs where vendorID="+vendor.getVendorId()); if (subject != null && !(subject.equals(""))) { query.add("upper(fs.vendorFulfillmentNotesSubject) LIKE ?"); values.add(String.format(likeFormat,subject.toUpperCase(Locale.US)).toString()); } if (!query.isEmpty()) { int i=0; for(String s: query) { sqlB.append(" AND "); sqlB.append(s); i++; } } sqlB.append(" order by fs.vendorFulfillmentNoteID"); return getHibernateTemplate().find(sqlB.toString(), values.toArray()); } /** * Add/Update Note to fulfillment Notes Table * @param Fulfillment Service Notes object * @throws DataAccessException */ public FulfillmentServiceNotes addNote(FulfillmentServiceNotes fulfillmentServiceNotes) { getHibernateTemplate().saveOrUpdate(fulfillmentServiceNotes); getHibernateTemplate().flush(); return fulfillmentServiceNotes; } public Map<String,Object> getNoteByID(Long fulfillmentServiceNoteID, boolean isFS){ Map<String,Object> newMap = new HashMap<String, Object>(); if(isFS){ List<FulfillmentServiceNotes> notesObject = new ArrayList<FulfillmentServiceNotes>(); notesObject = getHibernateTemplate().find("FROM FulfillmentServiceNotes where fulfillmentServiceNoteID=?",fulfillmentServiceNoteID); newMap.put("CreatedDate",notesObject.get(0).getCreatedDate()); newMap.put("CreatedBy",notesObject.get(0).getCreatedBy()); getHibernateTemplate().evict(notesObject.get(0)); }else{ List<VendorFulfillmentNotes> notesObject = new ArrayList<VendorFulfillmentNotes>(); notesObject = getHibernateTemplate().find("FROM VendorFulfillmentNotes where vendorFulfillmentNoteID=?",fulfillmentServiceNoteID); newMap.put("CreatedDate",notesObject.get(0).getCreatedDate()); newMap.put("CreatedBy",notesObject.get(0).getCreatedBy()); getHibernateTemplate().evict(notesObject.get(0)); } return newMap; } }
5,697
0.757767
0.75531
165
33.527271
34.184448
148
false
false
0
0
0
0
0
0
1.854545
false
false
10
d796529f9703130c2ab126de48ecc799a0b88285
12,025,908,489,512
423d4f2ef7e7af8153e5143d7e410f519c73b431
/app/src/main/java/net/middledleeast/tamm/fragments/ForgotPasswordFragment.java
3af7cb4831c5c12f3d22da8d934ae6f1f5f71cdd
[]
no_license
Abd-Allah-muhammed-muhammed/FaceArApp
https://github.com/Abd-Allah-muhammed-muhammed/FaceArApp
5e1ca10d9d1bac86ad195415d17bcf00e5e6415a
0232f534ded0f15a91c55cd85416a996770261ee
refs/heads/master
2022-04-10T11:30:15.692000
2020-01-30T09:58:57
2020-01-30T09:58:57
216,262,702
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.middledleeast.tamm.fragments; import android.annotation.SuppressLint; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import androidx.fragment.app.Fragment; import net.middledleeast.tamm.R; /** * A simple {@link Fragment} subclass. */ public class ForgotPasswordFragment extends Fragment { public ForgotPasswordFragment() { // Required empty public constructor } private Button btnSendEmail; private EditText edtEmail; @SuppressLint("ClickableViewAccessibility") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_forgot_password, container, false); btnSendEmail = view.findViewById(R.id.btn_send_forgort_password_email); btnSendEmail.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN){ btnSendEmail.setBackgroundColor(Color.parseColor("#BE973B")); getActivity().getSupportFragmentManager().beginTransaction() .replace(R.id.welcome_container, new SuccessSendEmailFragment()) .addToBackStack("ForgotPassword").commit(); }else if (event.getAction() == MotionEvent.ACTION_UP){ btnSendEmail.setBackground(getActivity().getDrawable(R.drawable.border)); } return false; } }); return view; } }
UTF-8
Java
1,898
java
ForgotPasswordFragment.java
Java
[]
null
[]
package net.middledleeast.tamm.fragments; import android.annotation.SuppressLint; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import androidx.fragment.app.Fragment; import net.middledleeast.tamm.R; /** * A simple {@link Fragment} subclass. */ public class ForgotPasswordFragment extends Fragment { public ForgotPasswordFragment() { // Required empty public constructor } private Button btnSendEmail; private EditText edtEmail; @SuppressLint("ClickableViewAccessibility") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_forgot_password, container, false); btnSendEmail = view.findViewById(R.id.btn_send_forgort_password_email); btnSendEmail.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN){ btnSendEmail.setBackgroundColor(Color.parseColor("#BE973B")); getActivity().getSupportFragmentManager().beginTransaction() .replace(R.id.welcome_container, new SuccessSendEmailFragment()) .addToBackStack("ForgotPassword").commit(); }else if (event.getAction() == MotionEvent.ACTION_UP){ btnSendEmail.setBackground(getActivity().getDrawable(R.drawable.border)); } return false; } }); return view; } }
1,898
0.660695
0.659115
57
32.298244
28.360439
93
false
false
0
0
0
0
0
0
0.491228
false
false
10
690fb35ce815a344b44150ee3287201b083ccb02
18,528,488,968,884
5be6e6465170e0b74e07479570fb346bc7715c0e
/cobar-route/src/main/java/com/alibaba/cobar/route/ServerRouter.java
3ddec516905e20cfc1422e90f7c6328fdd951f18
[ "Apache-2.0" ]
permissive
lostdragon/cobar
https://github.com/lostdragon/cobar
cefa395434ec90e756a5c94f4cb7faad09f7e62a
f1c7b3aefff4aaf416473930a739bb5cb5e29602
refs/heads/master
2016-08-03T17:32:27.386000
2012-10-29T07:44:24
2012-10-29T07:44:24
6,434,628
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 1999-2012 Alibaba Group. * * 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.alibaba.cobar.route; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLNonTransientException; import java.sql.SQLSyntaxErrorException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import com.alibaba.cobar.route.util.RegexUtil; import org.apache.log4j.Logger; import com.alibaba.cobar.parser.ast.ASTNode; import com.alibaba.cobar.parser.ast.expression.Expression; import com.alibaba.cobar.parser.ast.expression.ReplacableExpression; import com.alibaba.cobar.parser.ast.expression.comparison.InExpression; import com.alibaba.cobar.parser.ast.expression.misc.InExpressionList; import com.alibaba.cobar.parser.ast.expression.primary.Identifier; import com.alibaba.cobar.parser.ast.expression.primary.RowExpression; import com.alibaba.cobar.parser.ast.stmt.SQLStatement; import com.alibaba.cobar.parser.ast.stmt.dal.DALShowStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLInsertReplaceStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLSelectStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLSelectUnionStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLUpdateStatement; import com.alibaba.cobar.parser.recognizer.SQLParserDelegate; import com.alibaba.cobar.parser.recognizer.syntax.SQLParser; import com.alibaba.cobar.parser.util.ArrayUtil; import com.alibaba.cobar.parser.util.Pair; import com.alibaba.cobar.parser.visitor.MySQLOutputASTVisitor; import com.alibaba.cobar.route.config.SchemaConfig; import com.alibaba.cobar.route.config.TableConfig; import com.alibaba.cobar.route.config.TableRuleConfig; import com.alibaba.cobar.route.config.TableRuleConfig.RuleConfig; import com.alibaba.cobar.route.hint.CobarHint; import com.alibaba.cobar.route.visitor.PartitionKeyVisitor; import com.alibaba.cobar.util.CollectionUtil; /** * @author xianmao.hexm * @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a> */ public final class ServerRouter { private static final Logger LOGGER = Logger.getLogger(ServerRouter.class); public static RouteResultset route(SchemaConfig schema, String stmt, String charset, Object info) throws SQLNonTransientException { RouteResultset rrs = new RouteResultset(stmt); // 检查是否含有cobar hint int prefixIndex = HintRouter.indexOfPrefix(stmt); if (prefixIndex >= 0) { HintRouter.routeFromHint(info, schema, rrs, prefixIndex, stmt); return rrs; } // 检查schema是否含有拆分库 if (schema.isNoSharding()) { if (schema.isKeepSqlSchema()) { SQLStatement ast = SQLParserDelegate.parse(stmt, charset == null ? SQLParser.DEFAULT_CHARSET : charset); PartitionKeyVisitor visitor = new PartitionKeyVisitor(schema.getTables()); visitor.setTrimSchema(schema.getName()); ast.accept(visitor); if (visitor.isSchemaTrimmed()) { stmt = genSQL(ast, stmt); } } RouteResultsetNode[] nodes = new RouteResultsetNode[1]; nodes[0] = new RouteResultsetNode(schema.getDataNode(), stmt); rrs.setNodes(nodes); return rrs; } // 生成和展开AST SQLStatement ast = SQLParserDelegate.parse(stmt, charset == null ? SQLParser.DEFAULT_CHARSET : charset); PartitionKeyVisitor visitor = new PartitionKeyVisitor(schema.getTables()); visitor.setTrimSchema(schema.isKeepSqlSchema() ? schema.getName() : null); ast.accept(visitor); // 如果sql包含用户自定义的schema,则路由到default节点 if (schema.isKeepSqlSchema() && visitor.isCustomedSchema()) { if (visitor.isSchemaTrimmed()) { stmt = genSQL(ast, stmt); } RouteResultsetNode[] nodes = new RouteResultsetNode[1]; nodes[0] = new RouteResultsetNode(schema.getDataNode(), stmt); rrs.setNodes(nodes); return rrs; } // 元数据语句路由 if (visitor.isTableMetaRead()) { MetaRouter.routeForTableMeta(rrs, schema, ast, visitor, stmt); if (visitor.isNeedRewriteField()) { rrs.setFlag(RouteResultset.REWRITE_FIELD); } return rrs; } // 匹配规则 TableConfig matchedTable = null; RuleConfig rule = null; Map<String, List<Object>> columnValues = null; Map<String, Map<String, List<Object>>> astExt = visitor.getColumnValue(); Map<String, TableConfig> tables = schema.getTables(); ft: for (Entry<String, Map<String, List<Object>>> e : astExt.entrySet()) { Map<String, List<Object>> col2Val = e.getValue(); // 增加正则支持 // TableConfig tc = tables.get(e.getKey()); TableConfig tc = RegexUtil.get(tables, e.getKey()); if (tc == null) { continue; } if (matchedTable == null) { matchedTable = tc; } if (col2Val == null || col2Val.isEmpty()) { continue; } TableRuleConfig tr = tc.getRule(); if (tr != null) { for (RuleConfig rc : tr.getRules()) { boolean match = true; for (String ruleColumn : rc.getColumns()) { match &= col2Val.containsKey(ruleColumn); } if (match) { columnValues = col2Val; rule = rc; matchedTable = tc; break ft; } } } } // 规则匹配处理,表级别和列级别。 if (matchedTable == null) { String sql = visitor.isSchemaTrimmed() ? genSQL(ast, stmt) : stmt; RouteResultsetNode[] rn = new RouteResultsetNode[1]; if ("".equals(schema.getDataNode()) && isSystemReadSQL(ast)) { rn[0] = new RouteResultsetNode(schema.getRandomDataNode(), sql); } else { rn[0] = new RouteResultsetNode(schema.getDataNode(), sql); } rrs.setNodes(rn); return rrs; } if (rule == null) { if (matchedTable.isRuleRequired()) { throw new IllegalArgumentException("route rule for table " + matchedTable.getName() + " is required: " + stmt); } String[] dataNodes = matchedTable.getDataNodes(); String sql = visitor.isSchemaTrimmed() ? genSQL(ast, stmt) : stmt; RouteResultsetNode[] rn = new RouteResultsetNode[dataNodes.length]; for (int i = 0; i < dataNodes.length; ++i) { rn[i] = new RouteResultsetNode(dataNodes[i], sql); } rrs.setNodes(rn); setGroupFlagAndLimit(rrs, visitor); return rrs; } // 规则计算 validateAST(ast, matchedTable, rule, visitor); Map<Integer, List<Object[]>> dnMap = ruleCalculate(matchedTable, rule, columnValues); if (dnMap == null || dnMap.isEmpty()) { throw new IllegalArgumentException("No target dataNode for rule " + rule); } // 判断路由结果是单库还是多库 if (dnMap.size() == 1) { String dataNode = matchedTable.getDataNodes()[dnMap.keySet().iterator().next()]; String sql = visitor.isSchemaTrimmed() ? genSQL(ast, stmt) : stmt; RouteResultsetNode[] rn = new RouteResultsetNode[1]; rn[0] = new RouteResultsetNode(dataNode, sql); rrs.setNodes(rn); } else { RouteResultsetNode[] rn = new RouteResultsetNode[dnMap.size()]; if (ast instanceof DMLInsertReplaceStatement) { DMLInsertReplaceStatement ir = (DMLInsertReplaceStatement) ast; dispatchInsertReplace(rn, ir, rule.getColumns(), dnMap, matchedTable, stmt, visitor); } else { dispatchWhereBasedStmt(rn, ast, rule.getColumns(), dnMap, matchedTable, stmt, visitor); } rrs.setNodes(rn); setGroupFlagAndLimit(rrs, visitor); } return rrs; } private static class HintRouter { public static int indexOfPrefix(String sql) { int i = 0; for (; i < sql.length(); ++i) { switch (sql.charAt(i)) { case ' ': case '\t': case '\r': case '\n': continue; } break; } if (sql.startsWith(CobarHint.COBAR_HINT_PREFIX, i)) { return i; } else { return -1; } } public static void routeFromHint(Object frontConn, SchemaConfig schema, RouteResultset rrs, int prefixIndex, final String sql) throws SQLSyntaxErrorException { CobarHint hint = CobarHint.parserCobarHint(sql, prefixIndex); final String outputSql = hint.getOutputSql(); final int replica = hint.getReplica(); final String table = hint.getTable(); final List<Pair<Integer, Integer>> dataNodes = hint.getDataNodes(); final Pair<String[], Object[][]> partitionOperand = hint.getPartitionOperand(); TableConfig tableConfig = null; if (table == null || schema.getTables() == null || (tableConfig = schema.getTables().get(table)) == null) { // table not indicated RouteResultsetNode[] nodes = new RouteResultsetNode[1]; rrs.setNodes(nodes); if (dataNodes != null && !dataNodes.isEmpty()) { Integer replicaIndex = dataNodes.get(0).getValue(); if (replicaIndex != null && RouteResultsetNode.DEFAULT_REPLICA_INDEX.intValue() != replicaIndex.intValue()) { // replica index indicated in dataNodes references nodes[0] = new RouteResultsetNode(schema.getDataNode(), replicaIndex, outputSql); logExplicitReplicaSet(frontConn, sql, rrs); return; } } nodes[0] = new RouteResultsetNode(schema.getDataNode(), replica, outputSql); if (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX) { logExplicitReplicaSet(frontConn, sql, rrs); } return; } if (dataNodes != null && !dataNodes.isEmpty()) { RouteResultsetNode[] nodes = new RouteResultsetNode[dataNodes.size()]; rrs.setNodes(nodes); int i = 0; boolean replicaSet = false; for (Pair<Integer, Integer> pair : dataNodes) { String dataNodeName = tableConfig.getDataNodes()[pair.getKey()]; Integer replicaIndex = dataNodes.get(i).getValue(); if (replicaIndex != null && RouteResultsetNode.DEFAULT_REPLICA_INDEX.intValue() != replicaIndex.intValue()) { replicaSet = true; nodes[i] = new RouteResultsetNode(dataNodeName, replicaIndex, outputSql); } else { replicaSet = replicaSet || (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX); nodes[i] = new RouteResultsetNode(dataNodeName, replica, outputSql); } ++i; } if (replicaSet) { logExplicitReplicaSet(frontConn, sql, rrs); } return; } if (partitionOperand == null) { String[] tableDataNodes = tableConfig.getDataNodes(); RouteResultsetNode[] nodes = new RouteResultsetNode[tableDataNodes.length]; rrs.setNodes(nodes); for (int i = 0; i < nodes.length; ++i) { nodes[i] = new RouteResultsetNode(tableDataNodes[i], replica, outputSql); } return; } String[] cols = partitionOperand.getKey(); Object[][] vals = partitionOperand.getValue(); if (cols == null || vals == null) { throw new SQLSyntaxErrorException("${partitionOperand} is invalid: " + sql); } RuleConfig rule = null; TableRuleConfig tr = tableConfig.getRule(); RuleConfig[] rules = tr == null ? null : tr.getRules(); if (rules != null) { for (RuleConfig r : rules) { String[] ruleCols = r.getColumns(); boolean match = true; for (String ruleCol : ruleCols) { match &= ArrayUtil.contains(cols, ruleCol); } if (match) { rule = r; break; } } } String[] tableDataNodes = tableConfig.getDataNodes(); if (rule == null) { RouteResultsetNode[] nodes = new RouteResultsetNode[tableDataNodes.length]; rrs.setNodes(nodes); boolean replicaSet = false; for (int i = 0; i < tableDataNodes.length; ++i) { replicaSet = replicaSet || (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX); nodes[i] = new RouteResultsetNode(tableDataNodes[i], replica, outputSql); } if (replicaSet) { logExplicitReplicaSet(frontConn, sql, rrs); } return; } Set<String> destDataNodes = calcHintDataNodes(rule, cols, vals, tableDataNodes); RouteResultsetNode[] nodes = new RouteResultsetNode[destDataNodes.size()]; rrs.setNodes(nodes); int i = 0; boolean replicaSet = false; for (String dataNode : destDataNodes) { replicaSet = replicaSet || (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX); nodes[i++] = new RouteResultsetNode(dataNode, replica, outputSql); } if (replicaSet) { logExplicitReplicaSet(frontConn, sql, rrs); } } private static Set<String> calcHintDataNodes(RuleConfig rule, String[] cols, Object[][] vals, String[] dataNodes) { Set<String> destDataNodes = new HashSet<String>(2, 1); Map<String, Object> parameter = new HashMap<String, Object>(cols.length, 1); for (Object[] val : vals) { for (int i = 0; i < cols.length; ++i) { parameter.put(cols[i], val[i]); } Integer[] dataNodeIndexes = calcDataNodeIndexesByFunction(rule.getAlgorithm(), parameter); for (Integer index : dataNodeIndexes) { destDataNodes.add(dataNodes[index]); } } return destDataNodes; } private static void logExplicitReplicaSet(Object frontConn, String sql, RouteResultset rrs) { if (frontConn != null && LOGGER.isInfoEnabled()) { StringBuilder s = new StringBuilder(); s.append(frontConn).append("Explicit data node replica set from, sql=["); s.append(sql).append(']'); LOGGER.info(s.toString()); } } } private static class MetaRouter { public static void routeForTableMeta(RouteResultset rrs, SchemaConfig schema, SQLStatement ast, PartitionKeyVisitor visitor, String stmt) { String sql = stmt; if (visitor.isSchemaTrimmed()) { sql = genSQL(ast, stmt); } String[] tables = visitor.getMetaReadTable(); if (tables == null) { throw new IllegalArgumentException("route err: tables[] is null for meta read table: " + stmt); } String[] dataNodes; if (tables.length <= 0) { dataNodes = schema.getMetaDataNodes(); } else if (tables.length == 1) { dataNodes = new String[1]; dataNodes[0] = getMetaReadDataNode(schema, tables[0]); } else { Set<String> dataNodeSet = new HashSet<String>(tables.length, 1); for (String table : tables) { String dataNode = getMetaReadDataNode(schema, table); dataNodeSet.add(dataNode); } dataNodes = new String[dataNodeSet.size()]; Iterator<String> iter = dataNodeSet.iterator(); for (int i = 0; i < dataNodes.length; ++i) { dataNodes[i] = iter.next(); } } RouteResultsetNode[] nodes = new RouteResultsetNode[dataNodes.length]; rrs.setNodes(nodes); for (int i = 0; i < dataNodes.length; ++i) { nodes[i] = new RouteResultsetNode(dataNodes[i], sql); } } private static String getMetaReadDataNode(SchemaConfig schema, String table) { String dataNode = schema.getDataNode(); Map<String, TableConfig> tables = schema.getTables(); TableConfig tc; if (tables != null && (tc = tables.get(table)) != null) { String[] dn = tc.getDataNodes(); if (dn != null && dn.length > 0) { dataNode = dn[0]; } } return dataNode; } } private static Integer[] calcDataNodeIndexesByFunction(Expression algorithm, Map<String, Object> parameter) { Integer[] dataNodeIndexes; Object calRst = algorithm.evaluation(parameter); if (calRst instanceof Number) { dataNodeIndexes = new Integer[1]; dataNodeIndexes[0] = ((Number) calRst).intValue(); } else if (calRst instanceof Integer[]) { dataNodeIndexes = (Integer[]) calRst; } else if (calRst instanceof int[]) { int[] intArray = (int[]) calRst; dataNodeIndexes = new Integer[intArray.length]; for (int i = 0; i < intArray.length; ++i) { dataNodeIndexes[i] = intArray[i]; } } else { throw new IllegalArgumentException("route err: result of route function is wrong type or null: " + calRst); } return dataNodeIndexes; } private static boolean equals(String str1, String str2) { if (str1 == null) { return str2 == null; } return str1.equals(str2); } private static void validateAST(SQLStatement ast, TableConfig tc, RuleConfig rule, PartitionKeyVisitor visitor) throws SQLNonTransientException { if (ast instanceof DMLUpdateStatement) { List<Identifier> columns = null; String[] ruleCols = rule.getColumns(); DMLUpdateStatement update = (DMLUpdateStatement) ast; for (Pair<Identifier, Expression> pair : update.getValues()) { for (String ruleCol : ruleCols) { if (equals(pair.getKey().getIdTextUpUnescape(), ruleCol)) { if (columns == null) { columns = new ArrayList<Identifier>(ruleCols.length); } columns.add(pair.getKey()); } } } if (columns == null) { return; } Map<String, String> alias = visitor.getTableAlias(); for (Identifier column : columns) { String table = column.getLevelUnescapeUpName(2); table = alias.get(table); if (table != null && table.equals(tc.getName())) { throw new SQLFeatureNotSupportedException("partition key cannot be changed"); } } } } private static boolean isSystemReadSQL(SQLStatement ast) { if (ast instanceof DALShowStatement) { return true; } DMLSelectStatement select = null; if (ast instanceof DMLSelectStatement) { select = (DMLSelectStatement) ast; } else if (ast instanceof DMLSelectUnionStatement) { DMLSelectUnionStatement union = (DMLSelectUnionStatement) ast; if (union.getSelectStmtList().size() == 1) { select = union.getSelectStmtList().get(0); } else { return false; } } else { return false; } return select.getTables() == null; } private static void setGroupFlagAndLimit(RouteResultset rrs, PartitionKeyVisitor visitor) { rrs.setLimitSize(visitor.getLimitSize()); switch (visitor.getGroupFuncType()) { case PartitionKeyVisitor.GROUP_SUM: rrs.setFlag(RouteResultset.SUM_FLAG); break; case PartitionKeyVisitor.GROUP_MAX: rrs.setFlag(RouteResultset.MAX_FLAG); break; case PartitionKeyVisitor.GROUP_MIN: rrs.setFlag(RouteResultset.MIN_FLAG); break; } } /** * @return dataNodeIndex -&gt; [partitionKeysValueTuple+] */ private static Map<Integer, List<Object[]>> ruleCalculate(TableConfig matchedTable, RuleConfig rule, Map<String, List<Object>> columnValues) { Map<Integer, List<Object[]>> map = new HashMap<Integer, List<Object[]>>(1, 1); Expression algorithm = rule.getAlgorithm(); String[] cols = rule.getColumns(); Map<String, Object> parameter = new HashMap<String, Object>(cols.length, 1); ArrayList<Iterator<Object>> colsValIter = new ArrayList<Iterator<Object>>(columnValues.size()); for (String rc : cols) { List<Object> list = columnValues.get(rc); if (list == null) { String msg = "route err: rule column " + rc + " dosn't exist in extract: " + columnValues; throw new IllegalArgumentException(msg); } colsValIter.add(list.iterator()); } try { for (Iterator<Object> mainIter = colsValIter.get(0); mainIter.hasNext();) { Object[] tuple = new Object[cols.length]; for (int i = 0; i < cols.length; ++i) { Object value = colsValIter.get(i).next(); tuple[i] = value; parameter.put(cols[i], value); } Integer[] dataNodeIndexes = calcDataNodeIndexesByFunction(algorithm, parameter); for (int i = 0; i < dataNodeIndexes.length; ++i) { Integer dataNodeIndex = dataNodeIndexes[i]; List<Object[]> list = map.get(dataNodeIndex); if (list == null) { list = new LinkedList<Object[]>(); map.put(dataNodeIndex, list); } list.add(tuple); } } } catch (NoSuchElementException e) { String msg = "route err: different rule columns should have same value number: " + columnValues; throw new IllegalArgumentException(msg, e); } return map; } private static void dispatchWhereBasedStmt(RouteResultsetNode[] rn, SQLStatement stmtAST, String[] ruleColumns, Map<Integer, List<Object[]>> dataNodeMap, TableConfig matchedTable, String originalSQL, PartitionKeyVisitor visitor) { // [perf tag] 11.617 us: sharding multivalue if (ruleColumns.length > 1) { String sql; if (visitor.isSchemaTrimmed()) { sql = genSQL(stmtAST, originalSQL); } else { sql = originalSQL; } int i = -1; for (Integer dataNodeId : dataNodeMap.keySet()) { String dataNode = matchedTable.getDataNodes()[dataNodeId]; rn[++i] = new RouteResultsetNode(dataNode, sql); } return; } final String table = matchedTable.getName(); Map<String, Map<Object, Set<Pair<Expression, ASTNode>>>> columnIndex = visitor.getColumnIndex(table); Map<Object, Set<Pair<Expression, ASTNode>>> valueMap = columnIndex.get(ruleColumns[0]); replacePartitionKeyOperand(columnIndex, ruleColumns); Map<InExpression, Set<Expression>> unreplacedInExpr = new HashMap<InExpression, Set<Expression>>(1, 1); Set<ReplacableExpression> unreplacedSingleExprs = new HashSet<ReplacableExpression>(); // [perf tag] 12.2755 us: sharding multivalue int nodeId = -1; for (Entry<Integer, List<Object[]>> en : dataNodeMap.entrySet()) { List<Object[]> tuples = en.getValue(); unreplacedSingleExprs.clear(); unreplacedInExpr.clear(); for (Object[] tuple : tuples) { Object value = tuple[0]; Set<Pair<Expression, ASTNode>> indexedExpressionPair = getExpressionSet(valueMap, value); for (Pair<Expression, ASTNode> pair : indexedExpressionPair) { Expression expr = pair.getKey(); ASTNode parent = pair.getValue(); if (PartitionKeyVisitor.isPartitionKeyOperandSingle(expr, parent)) { unreplacedSingleExprs.add((ReplacableExpression) expr); } else if (PartitionKeyVisitor.isPartitionKeyOperandIn(expr, parent)) { Set<Expression> newInSet = unreplacedInExpr.get(parent); if (newInSet == null) { newInSet = new HashSet<Expression>(indexedExpressionPair.size(), 1); unreplacedInExpr.put((InExpression) parent, newInSet); } newInSet.add(expr); } } } // [perf tag] 15.3745 us: sharding multivalue for (ReplacableExpression expr : unreplacedSingleExprs) { expr.clearReplaceExpr(); } for (Entry<InExpression, Set<Expression>> entemp : unreplacedInExpr.entrySet()) { InExpression in = entemp.getKey(); Set<Expression> set = entemp.getValue(); if (set == null || set.isEmpty()) { in.setReplaceExpr(ReplacableExpression.BOOL_FALSE); } else { in.clearReplaceExpr(); InExpressionList inlist = in.getInExpressionList(); if (inlist != null) inlist.setReplaceExpr(new ArrayList<Expression>(set)); } } // [perf tag] 16.506 us: sharding multivalue String sql = genSQL(stmtAST, originalSQL); // [perf tag] 21.3425 us: sharding multivalue String dataNodeName = matchedTable.getDataNodes()[en.getKey()]; rn[++nodeId] = new RouteResultsetNode(dataNodeName, sql); for (ReplacableExpression expr : unreplacedSingleExprs) { expr.setReplaceExpr(ReplacableExpression.BOOL_FALSE); } for (InExpression in : unreplacedInExpr.keySet()) { in.setReplaceExpr(ReplacableExpression.BOOL_FALSE); InExpressionList list = in.getInExpressionList(); if (list != null) list.clearReplaceExpr(); } // [perf tag] 22.0965 us: sharding multivalue } } private static void replacePartitionKeyOperand(Map<String, Map<Object, Set<Pair<Expression, ASTNode>>>> index, String[] cols) { if (cols == null) { return; } for (String col : cols) { Map<Object, Set<Pair<Expression, ASTNode>>> map = index.get(col); if (map == null) { continue; } for (Set<Pair<Expression, ASTNode>> set : map.values()) { if (set == null) { continue; } for (Pair<Expression, ASTNode> p : set) { Expression expr = p.getKey(); ASTNode parent = p.getValue(); if (PartitionKeyVisitor.isPartitionKeyOperandSingle(expr, parent)) { ((ReplacableExpression) expr).setReplaceExpr(ReplacableExpression.BOOL_FALSE); } else if (PartitionKeyVisitor.isPartitionKeyOperandIn(expr, parent)) { ((ReplacableExpression) parent).setReplaceExpr(ReplacableExpression.BOOL_FALSE); } } } } } @SuppressWarnings("unchecked") private static void dispatchInsertReplace(RouteResultsetNode[] rn, DMLInsertReplaceStatement stmt, String[] ruleColumns, Map<Integer, List<Object[]>> dataNodeMap, TableConfig matchedTable, String originalSQL, PartitionKeyVisitor visitor) { if (stmt.getSelect() != null) { dispatchWhereBasedStmt(rn, stmt, ruleColumns, dataNodeMap, matchedTable, originalSQL, visitor); return; } Map<String, Map<Object, Set<Pair<Expression, ASTNode>>>> colsIndex = visitor.getColumnIndex(stmt.getTable().getIdTextUpUnescape()); if (colsIndex == null || colsIndex.isEmpty()) { throw new IllegalArgumentException("columns index is empty: " + originalSQL); } ArrayList<Map<Object, Set<Pair<Expression, ASTNode>>>> colsIndexList = new ArrayList<Map<Object, Set<Pair<Expression, ASTNode>>>>(ruleColumns.length); for (int i = 0; i < ruleColumns.length; ++i) { colsIndexList.add(colsIndex.get(ruleColumns[i])); } int dataNodeId = -1; for (Entry<Integer, List<Object[]>> en : dataNodeMap.entrySet()) { List<Object[]> tuples = en.getValue(); HashSet<RowExpression> replaceRowList = new HashSet<RowExpression>(tuples.size()); for (Object[] tuple : tuples) { Set<Pair<Expression, ASTNode>> tupleExprs = null; for (int i = 0; i < tuple.length; ++i) { Map<Object, Set<Pair<Expression, ASTNode>>> valueMap = colsIndexList.get(i); Object value = tuple[i]; Set<Pair<Expression, ASTNode>> set = getExpressionSet(valueMap, value); tupleExprs = (Set<Pair<Expression, ASTNode>>) CollectionUtil.intersectSet(tupleExprs, set); } if (tupleExprs == null || tupleExprs.isEmpty()) { throw new IllegalArgumentException("route: empty expression list for insertReplace stmt: " + originalSQL); } for (Pair<Expression, ASTNode> p : tupleExprs) { if (p.getValue() == stmt && p.getKey() instanceof RowExpression) { replaceRowList.add((RowExpression) p.getKey()); } } } stmt.setReplaceRowList(new ArrayList<RowExpression>(replaceRowList)); String sql = genSQL(stmt, originalSQL); stmt.clearReplaceRowList(); String dataNodeName = matchedTable.getDataNodes()[en.getKey()]; rn[++dataNodeId] = new RouteResultsetNode(dataNodeName, sql); } } private static Set<Pair<Expression, ASTNode>> getExpressionSet(Map<Object, Set<Pair<Expression, ASTNode>>> map, Object value) { if (map == null || map.isEmpty()) { return Collections.emptySet(); } Set<Pair<Expression, ASTNode>> set = map.get(value); if (set == null) { return Collections.emptySet(); } return set; } private static String genSQL(SQLStatement ast, String orginalSql) { StringBuilder s = new StringBuilder(); ast.accept(new MySQLOutputASTVisitor(s)); return s.toString(); } }
UTF-8
Java
34,657
java
ServerRouter.java
Java
[ { "context": "alibaba.cobar.util.CollectionUtil;\n\n/**\n * @author xianmao.hexm\n * @author <a href=\"mailto:shuo.qius@alibaba-inc.", "end": 2683, "score": 0.9993638396263123, "start": 2671, "tag": "NAME", "value": "xianmao.hexm" }, { "context": "* @author xianmao.hexm\n * @author <a href=\"mailto:shuo.qius@alibaba-inc.com\">QIU Shuo</a>\n */\npublic final class ServerRouter", "end": 2736, "score": 0.9999147653579712, "start": 2711, "tag": "EMAIL", "value": "shuo.qius@alibaba-inc.com" }, { "context": "author <a href=\"mailto:shuo.qius@alibaba-inc.com\">QIU Shuo</a>\n */\npublic final class ServerRouter {\n pri", "end": 2746, "score": 0.9998234510421753, "start": 2738, "tag": "NAME", "value": "QIU Shuo" } ]
null
[]
/* * Copyright 1999-2012 Alibaba Group. * * 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.alibaba.cobar.route; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLNonTransientException; import java.sql.SQLSyntaxErrorException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import com.alibaba.cobar.route.util.RegexUtil; import org.apache.log4j.Logger; import com.alibaba.cobar.parser.ast.ASTNode; import com.alibaba.cobar.parser.ast.expression.Expression; import com.alibaba.cobar.parser.ast.expression.ReplacableExpression; import com.alibaba.cobar.parser.ast.expression.comparison.InExpression; import com.alibaba.cobar.parser.ast.expression.misc.InExpressionList; import com.alibaba.cobar.parser.ast.expression.primary.Identifier; import com.alibaba.cobar.parser.ast.expression.primary.RowExpression; import com.alibaba.cobar.parser.ast.stmt.SQLStatement; import com.alibaba.cobar.parser.ast.stmt.dal.DALShowStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLInsertReplaceStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLSelectStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLSelectUnionStatement; import com.alibaba.cobar.parser.ast.stmt.dml.DMLUpdateStatement; import com.alibaba.cobar.parser.recognizer.SQLParserDelegate; import com.alibaba.cobar.parser.recognizer.syntax.SQLParser; import com.alibaba.cobar.parser.util.ArrayUtil; import com.alibaba.cobar.parser.util.Pair; import com.alibaba.cobar.parser.visitor.MySQLOutputASTVisitor; import com.alibaba.cobar.route.config.SchemaConfig; import com.alibaba.cobar.route.config.TableConfig; import com.alibaba.cobar.route.config.TableRuleConfig; import com.alibaba.cobar.route.config.TableRuleConfig.RuleConfig; import com.alibaba.cobar.route.hint.CobarHint; import com.alibaba.cobar.route.visitor.PartitionKeyVisitor; import com.alibaba.cobar.util.CollectionUtil; /** * @author xianmao.hexm * @author <a href="mailto:<EMAIL>"><NAME></a> */ public final class ServerRouter { private static final Logger LOGGER = Logger.getLogger(ServerRouter.class); public static RouteResultset route(SchemaConfig schema, String stmt, String charset, Object info) throws SQLNonTransientException { RouteResultset rrs = new RouteResultset(stmt); // 检查是否含有cobar hint int prefixIndex = HintRouter.indexOfPrefix(stmt); if (prefixIndex >= 0) { HintRouter.routeFromHint(info, schema, rrs, prefixIndex, stmt); return rrs; } // 检查schema是否含有拆分库 if (schema.isNoSharding()) { if (schema.isKeepSqlSchema()) { SQLStatement ast = SQLParserDelegate.parse(stmt, charset == null ? SQLParser.DEFAULT_CHARSET : charset); PartitionKeyVisitor visitor = new PartitionKeyVisitor(schema.getTables()); visitor.setTrimSchema(schema.getName()); ast.accept(visitor); if (visitor.isSchemaTrimmed()) { stmt = genSQL(ast, stmt); } } RouteResultsetNode[] nodes = new RouteResultsetNode[1]; nodes[0] = new RouteResultsetNode(schema.getDataNode(), stmt); rrs.setNodes(nodes); return rrs; } // 生成和展开AST SQLStatement ast = SQLParserDelegate.parse(stmt, charset == null ? SQLParser.DEFAULT_CHARSET : charset); PartitionKeyVisitor visitor = new PartitionKeyVisitor(schema.getTables()); visitor.setTrimSchema(schema.isKeepSqlSchema() ? schema.getName() : null); ast.accept(visitor); // 如果sql包含用户自定义的schema,则路由到default节点 if (schema.isKeepSqlSchema() && visitor.isCustomedSchema()) { if (visitor.isSchemaTrimmed()) { stmt = genSQL(ast, stmt); } RouteResultsetNode[] nodes = new RouteResultsetNode[1]; nodes[0] = new RouteResultsetNode(schema.getDataNode(), stmt); rrs.setNodes(nodes); return rrs; } // 元数据语句路由 if (visitor.isTableMetaRead()) { MetaRouter.routeForTableMeta(rrs, schema, ast, visitor, stmt); if (visitor.isNeedRewriteField()) { rrs.setFlag(RouteResultset.REWRITE_FIELD); } return rrs; } // 匹配规则 TableConfig matchedTable = null; RuleConfig rule = null; Map<String, List<Object>> columnValues = null; Map<String, Map<String, List<Object>>> astExt = visitor.getColumnValue(); Map<String, TableConfig> tables = schema.getTables(); ft: for (Entry<String, Map<String, List<Object>>> e : astExt.entrySet()) { Map<String, List<Object>> col2Val = e.getValue(); // 增加正则支持 // TableConfig tc = tables.get(e.getKey()); TableConfig tc = RegexUtil.get(tables, e.getKey()); if (tc == null) { continue; } if (matchedTable == null) { matchedTable = tc; } if (col2Val == null || col2Val.isEmpty()) { continue; } TableRuleConfig tr = tc.getRule(); if (tr != null) { for (RuleConfig rc : tr.getRules()) { boolean match = true; for (String ruleColumn : rc.getColumns()) { match &= col2Val.containsKey(ruleColumn); } if (match) { columnValues = col2Val; rule = rc; matchedTable = tc; break ft; } } } } // 规则匹配处理,表级别和列级别。 if (matchedTable == null) { String sql = visitor.isSchemaTrimmed() ? genSQL(ast, stmt) : stmt; RouteResultsetNode[] rn = new RouteResultsetNode[1]; if ("".equals(schema.getDataNode()) && isSystemReadSQL(ast)) { rn[0] = new RouteResultsetNode(schema.getRandomDataNode(), sql); } else { rn[0] = new RouteResultsetNode(schema.getDataNode(), sql); } rrs.setNodes(rn); return rrs; } if (rule == null) { if (matchedTable.isRuleRequired()) { throw new IllegalArgumentException("route rule for table " + matchedTable.getName() + " is required: " + stmt); } String[] dataNodes = matchedTable.getDataNodes(); String sql = visitor.isSchemaTrimmed() ? genSQL(ast, stmt) : stmt; RouteResultsetNode[] rn = new RouteResultsetNode[dataNodes.length]; for (int i = 0; i < dataNodes.length; ++i) { rn[i] = new RouteResultsetNode(dataNodes[i], sql); } rrs.setNodes(rn); setGroupFlagAndLimit(rrs, visitor); return rrs; } // 规则计算 validateAST(ast, matchedTable, rule, visitor); Map<Integer, List<Object[]>> dnMap = ruleCalculate(matchedTable, rule, columnValues); if (dnMap == null || dnMap.isEmpty()) { throw new IllegalArgumentException("No target dataNode for rule " + rule); } // 判断路由结果是单库还是多库 if (dnMap.size() == 1) { String dataNode = matchedTable.getDataNodes()[dnMap.keySet().iterator().next()]; String sql = visitor.isSchemaTrimmed() ? genSQL(ast, stmt) : stmt; RouteResultsetNode[] rn = new RouteResultsetNode[1]; rn[0] = new RouteResultsetNode(dataNode, sql); rrs.setNodes(rn); } else { RouteResultsetNode[] rn = new RouteResultsetNode[dnMap.size()]; if (ast instanceof DMLInsertReplaceStatement) { DMLInsertReplaceStatement ir = (DMLInsertReplaceStatement) ast; dispatchInsertReplace(rn, ir, rule.getColumns(), dnMap, matchedTable, stmt, visitor); } else { dispatchWhereBasedStmt(rn, ast, rule.getColumns(), dnMap, matchedTable, stmt, visitor); } rrs.setNodes(rn); setGroupFlagAndLimit(rrs, visitor); } return rrs; } private static class HintRouter { public static int indexOfPrefix(String sql) { int i = 0; for (; i < sql.length(); ++i) { switch (sql.charAt(i)) { case ' ': case '\t': case '\r': case '\n': continue; } break; } if (sql.startsWith(CobarHint.COBAR_HINT_PREFIX, i)) { return i; } else { return -1; } } public static void routeFromHint(Object frontConn, SchemaConfig schema, RouteResultset rrs, int prefixIndex, final String sql) throws SQLSyntaxErrorException { CobarHint hint = CobarHint.parserCobarHint(sql, prefixIndex); final String outputSql = hint.getOutputSql(); final int replica = hint.getReplica(); final String table = hint.getTable(); final List<Pair<Integer, Integer>> dataNodes = hint.getDataNodes(); final Pair<String[], Object[][]> partitionOperand = hint.getPartitionOperand(); TableConfig tableConfig = null; if (table == null || schema.getTables() == null || (tableConfig = schema.getTables().get(table)) == null) { // table not indicated RouteResultsetNode[] nodes = new RouteResultsetNode[1]; rrs.setNodes(nodes); if (dataNodes != null && !dataNodes.isEmpty()) { Integer replicaIndex = dataNodes.get(0).getValue(); if (replicaIndex != null && RouteResultsetNode.DEFAULT_REPLICA_INDEX.intValue() != replicaIndex.intValue()) { // replica index indicated in dataNodes references nodes[0] = new RouteResultsetNode(schema.getDataNode(), replicaIndex, outputSql); logExplicitReplicaSet(frontConn, sql, rrs); return; } } nodes[0] = new RouteResultsetNode(schema.getDataNode(), replica, outputSql); if (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX) { logExplicitReplicaSet(frontConn, sql, rrs); } return; } if (dataNodes != null && !dataNodes.isEmpty()) { RouteResultsetNode[] nodes = new RouteResultsetNode[dataNodes.size()]; rrs.setNodes(nodes); int i = 0; boolean replicaSet = false; for (Pair<Integer, Integer> pair : dataNodes) { String dataNodeName = tableConfig.getDataNodes()[pair.getKey()]; Integer replicaIndex = dataNodes.get(i).getValue(); if (replicaIndex != null && RouteResultsetNode.DEFAULT_REPLICA_INDEX.intValue() != replicaIndex.intValue()) { replicaSet = true; nodes[i] = new RouteResultsetNode(dataNodeName, replicaIndex, outputSql); } else { replicaSet = replicaSet || (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX); nodes[i] = new RouteResultsetNode(dataNodeName, replica, outputSql); } ++i; } if (replicaSet) { logExplicitReplicaSet(frontConn, sql, rrs); } return; } if (partitionOperand == null) { String[] tableDataNodes = tableConfig.getDataNodes(); RouteResultsetNode[] nodes = new RouteResultsetNode[tableDataNodes.length]; rrs.setNodes(nodes); for (int i = 0; i < nodes.length; ++i) { nodes[i] = new RouteResultsetNode(tableDataNodes[i], replica, outputSql); } return; } String[] cols = partitionOperand.getKey(); Object[][] vals = partitionOperand.getValue(); if (cols == null || vals == null) { throw new SQLSyntaxErrorException("${partitionOperand} is invalid: " + sql); } RuleConfig rule = null; TableRuleConfig tr = tableConfig.getRule(); RuleConfig[] rules = tr == null ? null : tr.getRules(); if (rules != null) { for (RuleConfig r : rules) { String[] ruleCols = r.getColumns(); boolean match = true; for (String ruleCol : ruleCols) { match &= ArrayUtil.contains(cols, ruleCol); } if (match) { rule = r; break; } } } String[] tableDataNodes = tableConfig.getDataNodes(); if (rule == null) { RouteResultsetNode[] nodes = new RouteResultsetNode[tableDataNodes.length]; rrs.setNodes(nodes); boolean replicaSet = false; for (int i = 0; i < tableDataNodes.length; ++i) { replicaSet = replicaSet || (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX); nodes[i] = new RouteResultsetNode(tableDataNodes[i], replica, outputSql); } if (replicaSet) { logExplicitReplicaSet(frontConn, sql, rrs); } return; } Set<String> destDataNodes = calcHintDataNodes(rule, cols, vals, tableDataNodes); RouteResultsetNode[] nodes = new RouteResultsetNode[destDataNodes.size()]; rrs.setNodes(nodes); int i = 0; boolean replicaSet = false; for (String dataNode : destDataNodes) { replicaSet = replicaSet || (replica != RouteResultsetNode.DEFAULT_REPLICA_INDEX); nodes[i++] = new RouteResultsetNode(dataNode, replica, outputSql); } if (replicaSet) { logExplicitReplicaSet(frontConn, sql, rrs); } } private static Set<String> calcHintDataNodes(RuleConfig rule, String[] cols, Object[][] vals, String[] dataNodes) { Set<String> destDataNodes = new HashSet<String>(2, 1); Map<String, Object> parameter = new HashMap<String, Object>(cols.length, 1); for (Object[] val : vals) { for (int i = 0; i < cols.length; ++i) { parameter.put(cols[i], val[i]); } Integer[] dataNodeIndexes = calcDataNodeIndexesByFunction(rule.getAlgorithm(), parameter); for (Integer index : dataNodeIndexes) { destDataNodes.add(dataNodes[index]); } } return destDataNodes; } private static void logExplicitReplicaSet(Object frontConn, String sql, RouteResultset rrs) { if (frontConn != null && LOGGER.isInfoEnabled()) { StringBuilder s = new StringBuilder(); s.append(frontConn).append("Explicit data node replica set from, sql=["); s.append(sql).append(']'); LOGGER.info(s.toString()); } } } private static class MetaRouter { public static void routeForTableMeta(RouteResultset rrs, SchemaConfig schema, SQLStatement ast, PartitionKeyVisitor visitor, String stmt) { String sql = stmt; if (visitor.isSchemaTrimmed()) { sql = genSQL(ast, stmt); } String[] tables = visitor.getMetaReadTable(); if (tables == null) { throw new IllegalArgumentException("route err: tables[] is null for meta read table: " + stmt); } String[] dataNodes; if (tables.length <= 0) { dataNodes = schema.getMetaDataNodes(); } else if (tables.length == 1) { dataNodes = new String[1]; dataNodes[0] = getMetaReadDataNode(schema, tables[0]); } else { Set<String> dataNodeSet = new HashSet<String>(tables.length, 1); for (String table : tables) { String dataNode = getMetaReadDataNode(schema, table); dataNodeSet.add(dataNode); } dataNodes = new String[dataNodeSet.size()]; Iterator<String> iter = dataNodeSet.iterator(); for (int i = 0; i < dataNodes.length; ++i) { dataNodes[i] = iter.next(); } } RouteResultsetNode[] nodes = new RouteResultsetNode[dataNodes.length]; rrs.setNodes(nodes); for (int i = 0; i < dataNodes.length; ++i) { nodes[i] = new RouteResultsetNode(dataNodes[i], sql); } } private static String getMetaReadDataNode(SchemaConfig schema, String table) { String dataNode = schema.getDataNode(); Map<String, TableConfig> tables = schema.getTables(); TableConfig tc; if (tables != null && (tc = tables.get(table)) != null) { String[] dn = tc.getDataNodes(); if (dn != null && dn.length > 0) { dataNode = dn[0]; } } return dataNode; } } private static Integer[] calcDataNodeIndexesByFunction(Expression algorithm, Map<String, Object> parameter) { Integer[] dataNodeIndexes; Object calRst = algorithm.evaluation(parameter); if (calRst instanceof Number) { dataNodeIndexes = new Integer[1]; dataNodeIndexes[0] = ((Number) calRst).intValue(); } else if (calRst instanceof Integer[]) { dataNodeIndexes = (Integer[]) calRst; } else if (calRst instanceof int[]) { int[] intArray = (int[]) calRst; dataNodeIndexes = new Integer[intArray.length]; for (int i = 0; i < intArray.length; ++i) { dataNodeIndexes[i] = intArray[i]; } } else { throw new IllegalArgumentException("route err: result of route function is wrong type or null: " + calRst); } return dataNodeIndexes; } private static boolean equals(String str1, String str2) { if (str1 == null) { return str2 == null; } return str1.equals(str2); } private static void validateAST(SQLStatement ast, TableConfig tc, RuleConfig rule, PartitionKeyVisitor visitor) throws SQLNonTransientException { if (ast instanceof DMLUpdateStatement) { List<Identifier> columns = null; String[] ruleCols = rule.getColumns(); DMLUpdateStatement update = (DMLUpdateStatement) ast; for (Pair<Identifier, Expression> pair : update.getValues()) { for (String ruleCol : ruleCols) { if (equals(pair.getKey().getIdTextUpUnescape(), ruleCol)) { if (columns == null) { columns = new ArrayList<Identifier>(ruleCols.length); } columns.add(pair.getKey()); } } } if (columns == null) { return; } Map<String, String> alias = visitor.getTableAlias(); for (Identifier column : columns) { String table = column.getLevelUnescapeUpName(2); table = alias.get(table); if (table != null && table.equals(tc.getName())) { throw new SQLFeatureNotSupportedException("partition key cannot be changed"); } } } } private static boolean isSystemReadSQL(SQLStatement ast) { if (ast instanceof DALShowStatement) { return true; } DMLSelectStatement select = null; if (ast instanceof DMLSelectStatement) { select = (DMLSelectStatement) ast; } else if (ast instanceof DMLSelectUnionStatement) { DMLSelectUnionStatement union = (DMLSelectUnionStatement) ast; if (union.getSelectStmtList().size() == 1) { select = union.getSelectStmtList().get(0); } else { return false; } } else { return false; } return select.getTables() == null; } private static void setGroupFlagAndLimit(RouteResultset rrs, PartitionKeyVisitor visitor) { rrs.setLimitSize(visitor.getLimitSize()); switch (visitor.getGroupFuncType()) { case PartitionKeyVisitor.GROUP_SUM: rrs.setFlag(RouteResultset.SUM_FLAG); break; case PartitionKeyVisitor.GROUP_MAX: rrs.setFlag(RouteResultset.MAX_FLAG); break; case PartitionKeyVisitor.GROUP_MIN: rrs.setFlag(RouteResultset.MIN_FLAG); break; } } /** * @return dataNodeIndex -&gt; [partitionKeysValueTuple+] */ private static Map<Integer, List<Object[]>> ruleCalculate(TableConfig matchedTable, RuleConfig rule, Map<String, List<Object>> columnValues) { Map<Integer, List<Object[]>> map = new HashMap<Integer, List<Object[]>>(1, 1); Expression algorithm = rule.getAlgorithm(); String[] cols = rule.getColumns(); Map<String, Object> parameter = new HashMap<String, Object>(cols.length, 1); ArrayList<Iterator<Object>> colsValIter = new ArrayList<Iterator<Object>>(columnValues.size()); for (String rc : cols) { List<Object> list = columnValues.get(rc); if (list == null) { String msg = "route err: rule column " + rc + " dosn't exist in extract: " + columnValues; throw new IllegalArgumentException(msg); } colsValIter.add(list.iterator()); } try { for (Iterator<Object> mainIter = colsValIter.get(0); mainIter.hasNext();) { Object[] tuple = new Object[cols.length]; for (int i = 0; i < cols.length; ++i) { Object value = colsValIter.get(i).next(); tuple[i] = value; parameter.put(cols[i], value); } Integer[] dataNodeIndexes = calcDataNodeIndexesByFunction(algorithm, parameter); for (int i = 0; i < dataNodeIndexes.length; ++i) { Integer dataNodeIndex = dataNodeIndexes[i]; List<Object[]> list = map.get(dataNodeIndex); if (list == null) { list = new LinkedList<Object[]>(); map.put(dataNodeIndex, list); } list.add(tuple); } } } catch (NoSuchElementException e) { String msg = "route err: different rule columns should have same value number: " + columnValues; throw new IllegalArgumentException(msg, e); } return map; } private static void dispatchWhereBasedStmt(RouteResultsetNode[] rn, SQLStatement stmtAST, String[] ruleColumns, Map<Integer, List<Object[]>> dataNodeMap, TableConfig matchedTable, String originalSQL, PartitionKeyVisitor visitor) { // [perf tag] 11.617 us: sharding multivalue if (ruleColumns.length > 1) { String sql; if (visitor.isSchemaTrimmed()) { sql = genSQL(stmtAST, originalSQL); } else { sql = originalSQL; } int i = -1; for (Integer dataNodeId : dataNodeMap.keySet()) { String dataNode = matchedTable.getDataNodes()[dataNodeId]; rn[++i] = new RouteResultsetNode(dataNode, sql); } return; } final String table = matchedTable.getName(); Map<String, Map<Object, Set<Pair<Expression, ASTNode>>>> columnIndex = visitor.getColumnIndex(table); Map<Object, Set<Pair<Expression, ASTNode>>> valueMap = columnIndex.get(ruleColumns[0]); replacePartitionKeyOperand(columnIndex, ruleColumns); Map<InExpression, Set<Expression>> unreplacedInExpr = new HashMap<InExpression, Set<Expression>>(1, 1); Set<ReplacableExpression> unreplacedSingleExprs = new HashSet<ReplacableExpression>(); // [perf tag] 12.2755 us: sharding multivalue int nodeId = -1; for (Entry<Integer, List<Object[]>> en : dataNodeMap.entrySet()) { List<Object[]> tuples = en.getValue(); unreplacedSingleExprs.clear(); unreplacedInExpr.clear(); for (Object[] tuple : tuples) { Object value = tuple[0]; Set<Pair<Expression, ASTNode>> indexedExpressionPair = getExpressionSet(valueMap, value); for (Pair<Expression, ASTNode> pair : indexedExpressionPair) { Expression expr = pair.getKey(); ASTNode parent = pair.getValue(); if (PartitionKeyVisitor.isPartitionKeyOperandSingle(expr, parent)) { unreplacedSingleExprs.add((ReplacableExpression) expr); } else if (PartitionKeyVisitor.isPartitionKeyOperandIn(expr, parent)) { Set<Expression> newInSet = unreplacedInExpr.get(parent); if (newInSet == null) { newInSet = new HashSet<Expression>(indexedExpressionPair.size(), 1); unreplacedInExpr.put((InExpression) parent, newInSet); } newInSet.add(expr); } } } // [perf tag] 15.3745 us: sharding multivalue for (ReplacableExpression expr : unreplacedSingleExprs) { expr.clearReplaceExpr(); } for (Entry<InExpression, Set<Expression>> entemp : unreplacedInExpr.entrySet()) { InExpression in = entemp.getKey(); Set<Expression> set = entemp.getValue(); if (set == null || set.isEmpty()) { in.setReplaceExpr(ReplacableExpression.BOOL_FALSE); } else { in.clearReplaceExpr(); InExpressionList inlist = in.getInExpressionList(); if (inlist != null) inlist.setReplaceExpr(new ArrayList<Expression>(set)); } } // [perf tag] 16.506 us: sharding multivalue String sql = genSQL(stmtAST, originalSQL); // [perf tag] 21.3425 us: sharding multivalue String dataNodeName = matchedTable.getDataNodes()[en.getKey()]; rn[++nodeId] = new RouteResultsetNode(dataNodeName, sql); for (ReplacableExpression expr : unreplacedSingleExprs) { expr.setReplaceExpr(ReplacableExpression.BOOL_FALSE); } for (InExpression in : unreplacedInExpr.keySet()) { in.setReplaceExpr(ReplacableExpression.BOOL_FALSE); InExpressionList list = in.getInExpressionList(); if (list != null) list.clearReplaceExpr(); } // [perf tag] 22.0965 us: sharding multivalue } } private static void replacePartitionKeyOperand(Map<String, Map<Object, Set<Pair<Expression, ASTNode>>>> index, String[] cols) { if (cols == null) { return; } for (String col : cols) { Map<Object, Set<Pair<Expression, ASTNode>>> map = index.get(col); if (map == null) { continue; } for (Set<Pair<Expression, ASTNode>> set : map.values()) { if (set == null) { continue; } for (Pair<Expression, ASTNode> p : set) { Expression expr = p.getKey(); ASTNode parent = p.getValue(); if (PartitionKeyVisitor.isPartitionKeyOperandSingle(expr, parent)) { ((ReplacableExpression) expr).setReplaceExpr(ReplacableExpression.BOOL_FALSE); } else if (PartitionKeyVisitor.isPartitionKeyOperandIn(expr, parent)) { ((ReplacableExpression) parent).setReplaceExpr(ReplacableExpression.BOOL_FALSE); } } } } } @SuppressWarnings("unchecked") private static void dispatchInsertReplace(RouteResultsetNode[] rn, DMLInsertReplaceStatement stmt, String[] ruleColumns, Map<Integer, List<Object[]>> dataNodeMap, TableConfig matchedTable, String originalSQL, PartitionKeyVisitor visitor) { if (stmt.getSelect() != null) { dispatchWhereBasedStmt(rn, stmt, ruleColumns, dataNodeMap, matchedTable, originalSQL, visitor); return; } Map<String, Map<Object, Set<Pair<Expression, ASTNode>>>> colsIndex = visitor.getColumnIndex(stmt.getTable().getIdTextUpUnescape()); if (colsIndex == null || colsIndex.isEmpty()) { throw new IllegalArgumentException("columns index is empty: " + originalSQL); } ArrayList<Map<Object, Set<Pair<Expression, ASTNode>>>> colsIndexList = new ArrayList<Map<Object, Set<Pair<Expression, ASTNode>>>>(ruleColumns.length); for (int i = 0; i < ruleColumns.length; ++i) { colsIndexList.add(colsIndex.get(ruleColumns[i])); } int dataNodeId = -1; for (Entry<Integer, List<Object[]>> en : dataNodeMap.entrySet()) { List<Object[]> tuples = en.getValue(); HashSet<RowExpression> replaceRowList = new HashSet<RowExpression>(tuples.size()); for (Object[] tuple : tuples) { Set<Pair<Expression, ASTNode>> tupleExprs = null; for (int i = 0; i < tuple.length; ++i) { Map<Object, Set<Pair<Expression, ASTNode>>> valueMap = colsIndexList.get(i); Object value = tuple[i]; Set<Pair<Expression, ASTNode>> set = getExpressionSet(valueMap, value); tupleExprs = (Set<Pair<Expression, ASTNode>>) CollectionUtil.intersectSet(tupleExprs, set); } if (tupleExprs == null || tupleExprs.isEmpty()) { throw new IllegalArgumentException("route: empty expression list for insertReplace stmt: " + originalSQL); } for (Pair<Expression, ASTNode> p : tupleExprs) { if (p.getValue() == stmt && p.getKey() instanceof RowExpression) { replaceRowList.add((RowExpression) p.getKey()); } } } stmt.setReplaceRowList(new ArrayList<RowExpression>(replaceRowList)); String sql = genSQL(stmt, originalSQL); stmt.clearReplaceRowList(); String dataNodeName = matchedTable.getDataNodes()[en.getKey()]; rn[++dataNodeId] = new RouteResultsetNode(dataNodeName, sql); } } private static Set<Pair<Expression, ASTNode>> getExpressionSet(Map<Object, Set<Pair<Expression, ASTNode>>> map, Object value) { if (map == null || map.isEmpty()) { return Collections.emptySet(); } Set<Pair<Expression, ASTNode>> set = map.get(value); if (set == null) { return Collections.emptySet(); } return set; } private static String genSQL(SQLStatement ast, String orginalSql) { StringBuilder s = new StringBuilder(); ast.accept(new MySQLOutputASTVisitor(s)); return s.toString(); } }
34,637
0.541105
0.537712
772
43.669689
29.276438
123
false
false
0
0
0
0
0
0
0.799223
false
false
10
6accccec0d1843b880a4b68c20f5e2c8af2d11cd
18,528,488,968,910
8a6a9139a19004b826af83b9ac151f4737865262
/back-end/src/main/java/com/webservice/bookstore/exception/SimpleFieldError.java
a3776c72a69bf60f128c8fd752bb1099013eb365
[]
no_license
localBookStore/bookstore
https://github.com/localBookStore/bookstore
008fe5430b9ceb059be0afc36d77224974b1408c
262f8df88a601ded8faba0e31f632ef3ce09f770
refs/heads/develop
2023-04-12T10:56:10.165000
2021-05-20T13:52:04
2021-05-20T13:52:04
331,920,408
0
0
null
false
2021-05-14T16:36:56
2021-01-22T11:03:49
2021-05-14T16:31:53
2021-05-14T16:36:56
16,060
0
0
0
Java
false
false
package com.webservice.bookstore.exception; import lombok.Getter; import org.springframework.validation.FieldError; @Getter public class SimpleFieldError extends FieldError { public SimpleFieldError(String field, String message) { super(field, field, message); } }
UTF-8
Java
283
java
SimpleFieldError.java
Java
[]
null
[]
package com.webservice.bookstore.exception; import lombok.Getter; import org.springframework.validation.FieldError; @Getter public class SimpleFieldError extends FieldError { public SimpleFieldError(String field, String message) { super(field, field, message); } }
283
0.770318
0.770318
12
22.666666
22.268562
59
false
false
0
0
0
0
0
0
0.583333
false
false
10
0018d51fcd4a56c1bf43cf98bf81d8d6061f7ccc
27,384,711,549,913
44aa1e21a94aa949fc7bea61c769d760b7f3d46e
/app/src/main/java/com/example/android/myquizapp/CorrectAnswers.java
26be0df15dce2e867ec3496d2b604cf4d6d05404
[]
no_license
marvin-t/QuizApp
https://github.com/marvin-t/QuizApp
9596ce8e878e491bddfd4156681a3ba53ad0fd52
87a80e3dcdff6f7822b7e145b445817b76325660
refs/heads/master
2020-08-27T20:31:00.499000
2019-10-25T08:02:05
2019-10-25T08:02:05
217,482,333
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android.myquizapp; public class CorrectAnswers { public static final String CorrectAnswer1 = "Captain Marvel"; public static final String CorrectAnswer2 = "Death Stone"; public static final String CorrectAnswer3 = "Morgan"; public static final String CorrectAnswer4 = "Mjolnir"; public static final String CorrectAnswer5 = "Nebula and Rocket"; public static final String CorrectAnswer6 = "Norway"; public static final String CorrectAnswer7 = "A rat"; public static final String CorrectAnswer8 = "Thor"; public static final String CorrectAnswer9 = "2012"; public static final String CorrectAnswer10 = "Captain America"; }
UTF-8
Java
684
java
CorrectAnswers.java
Java
[ { "context": "\n public static final String CorrectAnswer3 = \"Morgan\";\n public static final String CorrectAnswer4 =", "end": 254, "score": 0.9928061962127686, "start": 248, "tag": "NAME", "value": "Morgan" }, { "context": "\n public static final String CorrectAnswer4 = \"Mjolnir\";\n public static final String CorrectAnswer5 =", "end": 313, "score": 0.9967324733734131, "start": 306, "tag": "NAME", "value": "Mjolnir" } ]
null
[]
package com.example.android.myquizapp; public class CorrectAnswers { public static final String CorrectAnswer1 = "Captain Marvel"; public static final String CorrectAnswer2 = "Death Stone"; public static final String CorrectAnswer3 = "Morgan"; public static final String CorrectAnswer4 = "Mjolnir"; public static final String CorrectAnswer5 = "Nebula and Rocket"; public static final String CorrectAnswer6 = "Norway"; public static final String CorrectAnswer7 = "A rat"; public static final String CorrectAnswer8 = "Thor"; public static final String CorrectAnswer9 = "2012"; public static final String CorrectAnswer10 = "Captain America"; }
684
0.748538
0.726608
16
41.75
25.771835
68
false
false
0
0
0
0
0
0
0.6875
false
false
10
0f63f66fd5aa77669e04f2d3d4accc02685b2c8c
30,227,979,886,268
72bbfad26533b5c807448a53db60290d926f4872
/src/main/java/timetracker/services/MarkDAO.java
66178fc34bd654cf7e0aa9a616eb595ac9c1fb86
[]
no_license
multiscripter/time-tracker
https://github.com/multiscripter/time-tracker
e63f12b54813faf96af263c8c3667af216186f01
5c79ab7fdb95919e4a6051d916a82ae5bbf72eb4
refs/heads/master
2022-07-19T16:24:47.487000
2020-10-13T07:42:06
2020-10-13T07:42:06
129,295,938
0
0
null
false
2022-06-20T23:08:25
2018-04-12T18:39:17
2021-04-26T10:55:19
2022-06-20T23:08:25
122
0
0
3
Java
false
false
package timetracker.services; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedList; import java.util.TimeZone; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import timetracker.models.Mark; import timetracker.utils.DBDriver; /** * Класс MarkDAO реализует слой DAO для сущности Метка времени. * * @author Goureev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-04-11 * @since 2018-04-07 */ public class MarkDAO { /** * Драйвер бд. */ private final DBDriver db = DBDriver.getInstance(); /** * Логгер. */ private Logger logger = LogManager.getLogger(this.getClass().getName()); /** * Добавляет запись с меткой времени. * @param mark запись с меткой времени. * @return true если запись с меткой времени добавлена в бд. Иначе false. * @throws SQLException исключение SQL. */ public boolean create(Mark mark) throws SQLException { boolean result = false; String query = String.format("insert into %s (user_id, wday, mark, state) values (%d, '%s', '%s', %s)", this.db.getProperty("tbl_marks"), mark.getUserId(), mark.getWdayStr(), mark.getMarkStr(), mark.getState()); HashMap<String, Integer> entries = this.db.insert(query); if (entries.get("affected") > 0) { result = true; } return result; } /** * Удаляет запись с меткой времени. * @param mark запись с меткой времени. * @return true если запись с меткой времени удалёна из бд. Иначе false. * @throws SQLException исключение SQL. */ public boolean delete(Mark mark) throws SQLException { boolean result = false; String query = String.format("delete from %s where user_id = '%d' and mark = '%s'", this.db.getProperty("tbl_marks"), mark.getUserId(), mark.getMarkStr()); if (this.db.delete(query) > 0) { result = true; } return result; } /** * Получает все записи с меткой времени по токену. * @param token токен. * @return список записей. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. */ public LinkedList<Mark> read(final String token) throws SQLException, ParseException { String query = String.format("select * from %1$s, %2$s where %1$s.user_id = %2$s.user_id and %1$s.wday = %2$s.wday and %1$s.token = '%3$s' order by mark", this.db.getProperty("tbl_tokens"), this.db.getProperty("tbl_marks"), token); LinkedList<HashMap<String, String>> rl = this.db.select(query); return this.processResult(rl); } /** * Обрабатывает результат запроса select. * @param result результат запроса select. * @return коллекция записей. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. */ private LinkedList<Mark> processResult(LinkedList<HashMap<String, String>> result) throws SQLException, ParseException { LinkedList<Mark> marks = new LinkedList<>(); if (!result.isEmpty()) { int userId = Integer.parseInt(result.getFirst().get("user_id")); TimeZone tz = this.getTimeZone(userId); for (HashMap<String, String> entry : result) { GregorianCalendar calWday = new GregorianCalendar(); SimpleDateFormat sdfWday = new SimpleDateFormat("yyyy-MM-dd"); String strWday = entry.get("wday"); Date dateWday = sdfWday.parse(strWday); calWday.setTime(dateWday); GregorianCalendar calMark = new GregorianCalendar(tz); SimpleDateFormat sdfMark = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strMark = entry.get("mark"); Date dateMark = sdfMark.parse(strMark); calMark.setTime(dateMark); boolean state = entry.get("state").equals("1"); marks.add(new Mark(userId, calWday, calMark, state)); } } return marks; } /** * Получает часовой пояс. * @param userId . * @return часовой пояс. * @throws SQLException исключение SQL. */ public TimeZone getTimeZone(int userId) throws SQLException { LinkedList<HashMap<String, String>> rl = this.db.select(String.format("select gmt from %s where id = %d", this.db.getProperty("tbl_users"), userId)); String gmt = rl.getFirst().get("gmt"); String tzStr = String.format("GMT%s", gmt); return TimeZone.getTimeZone(tzStr); } /** * Обновляет метку времени. * @param mark запись с меткой времени. * @return true если запись с меткой времени обновлена в бд. Иначе false. * @throws SQLException исключение SQL. */ public boolean update(Mark mark) throws SQLException { boolean result = false; String query = String.format("update %s set mark = current_timestamp where user_id = %d and wday = '%s' and mark = '%s'", this.db.getProperty("tbl_marks"), mark.getUserId(), mark.getWdayStr(), mark.getMarkStr()); if (this.db.update(query) > 0) { result = true; } return result; } }
UTF-8
Java
5,858
java
MarkDAO.java
Java
[ { "context": "слой DAO для сущности Метка времени.\n *\n * @author Goureev Ilya (mailto:ill-jah@yandex.ru)\n * @version 2018-04-11", "end": 516, "score": 0.9998804926872253, "start": 504, "tag": "NAME", "value": "Goureev Ilya" }, { "context": "Метка времени.\n *\n * @author Goureev Ilya (mailto:ill-jah@yandex.ru)\n * @version 2018-04-11\n * @since 2018-04-07\n */\n", "end": 542, "score": 0.9999280571937561, "start": 525, "tag": "EMAIL", "value": "ill-jah@yandex.ru" }, { "context": "r_id and %1$s.wday = %2$s.wday and %1$s.token = '%3$s' order by mark\", this.db.getProperty(\"tbl_tokens\"", "end": 2561, "score": 0.9537014961242676, "start": 2558, "tag": "PASSWORD", "value": "3$s" } ]
null
[]
package timetracker.services; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.LinkedList; import java.util.TimeZone; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import timetracker.models.Mark; import timetracker.utils.DBDriver; /** * Класс MarkDAO реализует слой DAO для сущности Метка времени. * * @author <NAME> (mailto:<EMAIL>) * @version 2018-04-11 * @since 2018-04-07 */ public class MarkDAO { /** * Драйвер бд. */ private final DBDriver db = DBDriver.getInstance(); /** * Логгер. */ private Logger logger = LogManager.getLogger(this.getClass().getName()); /** * Добавляет запись с меткой времени. * @param mark запись с меткой времени. * @return true если запись с меткой времени добавлена в бд. Иначе false. * @throws SQLException исключение SQL. */ public boolean create(Mark mark) throws SQLException { boolean result = false; String query = String.format("insert into %s (user_id, wday, mark, state) values (%d, '%s', '%s', %s)", this.db.getProperty("tbl_marks"), mark.getUserId(), mark.getWdayStr(), mark.getMarkStr(), mark.getState()); HashMap<String, Integer> entries = this.db.insert(query); if (entries.get("affected") > 0) { result = true; } return result; } /** * Удаляет запись с меткой времени. * @param mark запись с меткой времени. * @return true если запись с меткой времени удалёна из бд. Иначе false. * @throws SQLException исключение SQL. */ public boolean delete(Mark mark) throws SQLException { boolean result = false; String query = String.format("delete from %s where user_id = '%d' and mark = '%s'", this.db.getProperty("tbl_marks"), mark.getUserId(), mark.getMarkStr()); if (this.db.delete(query) > 0) { result = true; } return result; } /** * Получает все записи с меткой времени по токену. * @param token токен. * @return список записей. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. */ public LinkedList<Mark> read(final String token) throws SQLException, ParseException { String query = String.format("select * from %1$s, %2$s where %1$s.user_id = %2$s.user_id and %1$s.wday = %2$s.wday and %1$s.token = '%3$s' order by mark", this.db.getProperty("tbl_tokens"), this.db.getProperty("tbl_marks"), token); LinkedList<HashMap<String, String>> rl = this.db.select(query); return this.processResult(rl); } /** * Обрабатывает результат запроса select. * @param result результат запроса select. * @return коллекция записей. * @throws SQLException исключение SQL. * @throws ParseException исключение парсинга. */ private LinkedList<Mark> processResult(LinkedList<HashMap<String, String>> result) throws SQLException, ParseException { LinkedList<Mark> marks = new LinkedList<>(); if (!result.isEmpty()) { int userId = Integer.parseInt(result.getFirst().get("user_id")); TimeZone tz = this.getTimeZone(userId); for (HashMap<String, String> entry : result) { GregorianCalendar calWday = new GregorianCalendar(); SimpleDateFormat sdfWday = new SimpleDateFormat("yyyy-MM-dd"); String strWday = entry.get("wday"); Date dateWday = sdfWday.parse(strWday); calWday.setTime(dateWday); GregorianCalendar calMark = new GregorianCalendar(tz); SimpleDateFormat sdfMark = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strMark = entry.get("mark"); Date dateMark = sdfMark.parse(strMark); calMark.setTime(dateMark); boolean state = entry.get("state").equals("1"); marks.add(new Mark(userId, calWday, calMark, state)); } } return marks; } /** * Получает часовой пояс. * @param userId . * @return часовой пояс. * @throws SQLException исключение SQL. */ public TimeZone getTimeZone(int userId) throws SQLException { LinkedList<HashMap<String, String>> rl = this.db.select(String.format("select gmt from %s where id = %d", this.db.getProperty("tbl_users"), userId)); String gmt = rl.getFirst().get("gmt"); String tzStr = String.format("GMT%s", gmt); return TimeZone.getTimeZone(tzStr); } /** * Обновляет метку времени. * @param mark запись с меткой времени. * @return true если запись с меткой времени обновлена в бд. Иначе false. * @throws SQLException исключение SQL. */ public boolean update(Mark mark) throws SQLException { boolean result = false; String query = String.format("update %s set mark = current_timestamp where user_id = %d and wday = '%s' and mark = '%s'", this.db.getProperty("tbl_marks"), mark.getUserId(), mark.getWdayStr(), mark.getMarkStr()); if (this.db.update(query) > 0) { result = true; } return result; } }
5,842
0.639811
0.634151
128
40.414063
40.063725
239
false
false
0
0
0
0
0
0
0.828125
false
false
10
1fe80cad2fffa751350ddeb368d897325b42a674
8,967,891,766,212
651a8ee4faeef92b061699b845c0cf4e8c152111
/app/src/main/java/com/kadiraltinok/flickrclient/presenter/MainPresenterImpl.java
707f21047c0c543025b5e81939bbbc766c097440
[]
no_license
kadiraltinok/FlickrClientAndroid
https://github.com/kadiraltinok/FlickrClientAndroid
69beb31687b9ab8ee7db73b1a991bd2a5c571e13
7765feccf3decd56639a76678c1e37e3942d22ff
refs/heads/master
2020-12-25T14:58:06.578000
2016-08-24T21:12:20
2016-08-24T21:12:20
66,217,418
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kadiraltinok.flickrclient.presenter; import android.content.Intent; import com.kadiraltinok.flickrclient.activity.BaseActivity; import com.kadiraltinok.flickrclient.activity.FullScreenActivity; import com.kadiraltinok.flickrclient.constant.AppConstant; import com.kadiraltinok.flickrclient.interactor.MainInteractor; import com.kadiraltinok.flickrclient.interactor.MainInteractorImpl; import com.kadiraltinok.flickrclient.listener.MainPageListener; import com.kadiraltinok.flickrclient.model.AdapterRow; import com.kadiraltinok.flickrclient.model.Photo; import com.kadiraltinok.flickrclient.utils.Utils; import com.kadiraltinok.flickrclient.view.MainView; import java.util.ArrayList; import java.util.List; /** * Created by kadiraltinok on 21/08/16. */ public class MainPresenterImpl implements MainPresenter, MainPageListener { private MainView mView; private MainInteractor mInteractor; public MainPresenterImpl(MainView mainView) { this.mView = mainView; mInteractor = new MainInteractorImpl(); } @Override public void onItemClicked(BaseActivity activity, int position, AdapterRow photo) { //go to detail Intent intent = FullScreenActivity.getIntent(activity, photo.getImageUrl()); activity.startActivity(intent); } @Override public void getTimeLine(int page) { if (mView != null) { mView.showProgress(); } mInteractor.serviceTimeLine(page, this); } @Override public void getFilterByTag(int page, String tag) { if (mView != null) { mView.showProgress(); } mInteractor.serviceFilterByTag(page, tag, this); } @Override public void onFinished(List<Photo> list) { if (mView != null) { List<AdapterRow> tempList = new ArrayList<>(); for (Photo photo : list) { if (photo.getMedia().equals(AppConstant.MEDIA_TYPE)) tempList.add(new AdapterRow(Utils.getUserImageUrl(photo), photo.getOwnername(), photo.getImageUrl(), Utils.getFormattedDate(photo), Utils.getFirstTag(photo))); } mView.setItems(tempList); mView.dismissProgress(); } } @Override public void onFinishedFilterByTag(List<Photo> list, String tag) { if (mView != null) { List<AdapterRow> tempList = new ArrayList<>(); for (Photo photo : list) { if (photo.getMedia().equals(AppConstant.MEDIA_TYPE)) tempList.add(new AdapterRow(Utils.getUserImageUrl(photo), photo.getOwnername(), photo.getImageUrl(), Utils.getFormattedDate(photo), tag)); } mView.setItems(tempList); mView.dismissProgress(); } } @Override public void empty() { if (mView != null) { mView.dismissProgress(); mView.emptyMode(); } } @Override public void onDefaultError(String message) { if (mView != null) { mView.onDefaultAlert(message); } } }
UTF-8
Java
3,093
java
MainPresenterImpl.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by kadiraltinok on 21/08/16.\n */\n\npublic class MainPresenterImpl ", "end": 753, "score": 0.9991763234138489, "start": 741, "tag": "USERNAME", "value": "kadiraltinok" } ]
null
[]
package com.kadiraltinok.flickrclient.presenter; import android.content.Intent; import com.kadiraltinok.flickrclient.activity.BaseActivity; import com.kadiraltinok.flickrclient.activity.FullScreenActivity; import com.kadiraltinok.flickrclient.constant.AppConstant; import com.kadiraltinok.flickrclient.interactor.MainInteractor; import com.kadiraltinok.flickrclient.interactor.MainInteractorImpl; import com.kadiraltinok.flickrclient.listener.MainPageListener; import com.kadiraltinok.flickrclient.model.AdapterRow; import com.kadiraltinok.flickrclient.model.Photo; import com.kadiraltinok.flickrclient.utils.Utils; import com.kadiraltinok.flickrclient.view.MainView; import java.util.ArrayList; import java.util.List; /** * Created by kadiraltinok on 21/08/16. */ public class MainPresenterImpl implements MainPresenter, MainPageListener { private MainView mView; private MainInteractor mInteractor; public MainPresenterImpl(MainView mainView) { this.mView = mainView; mInteractor = new MainInteractorImpl(); } @Override public void onItemClicked(BaseActivity activity, int position, AdapterRow photo) { //go to detail Intent intent = FullScreenActivity.getIntent(activity, photo.getImageUrl()); activity.startActivity(intent); } @Override public void getTimeLine(int page) { if (mView != null) { mView.showProgress(); } mInteractor.serviceTimeLine(page, this); } @Override public void getFilterByTag(int page, String tag) { if (mView != null) { mView.showProgress(); } mInteractor.serviceFilterByTag(page, tag, this); } @Override public void onFinished(List<Photo> list) { if (mView != null) { List<AdapterRow> tempList = new ArrayList<>(); for (Photo photo : list) { if (photo.getMedia().equals(AppConstant.MEDIA_TYPE)) tempList.add(new AdapterRow(Utils.getUserImageUrl(photo), photo.getOwnername(), photo.getImageUrl(), Utils.getFormattedDate(photo), Utils.getFirstTag(photo))); } mView.setItems(tempList); mView.dismissProgress(); } } @Override public void onFinishedFilterByTag(List<Photo> list, String tag) { if (mView != null) { List<AdapterRow> tempList = new ArrayList<>(); for (Photo photo : list) { if (photo.getMedia().equals(AppConstant.MEDIA_TYPE)) tempList.add(new AdapterRow(Utils.getUserImageUrl(photo), photo.getOwnername(), photo.getImageUrl(), Utils.getFormattedDate(photo), tag)); } mView.setItems(tempList); mView.dismissProgress(); } } @Override public void empty() { if (mView != null) { mView.dismissProgress(); mView.emptyMode(); } } @Override public void onDefaultError(String message) { if (mView != null) { mView.onDefaultAlert(message); } } }
3,093
0.657937
0.655997
95
31.557896
30.596771
179
false
false
0
0
0
0
0
0
0.547368
false
false
10
9646ffce012ee229afc63473177f5175ff9c09c8
33,097,017,993,393
ca329673f1e01e6597b9f47e61fb7ecb6be415fd
/Java2/Ques1/Ques1.java
d20bc49b52f2d3c54e9da81375e74b6588a866fb
[]
no_license
yashttn/Introduction-to-Java
https://github.com/yashttn/Introduction-to-Java
8ad42e16e76fc5f3272f852192a944259ef9d216
05f0bf541bd79f1f0c9b40a41ccc4c10f8d9af92
refs/heads/master
2020-04-24T02:57:55.229000
2019-04-01T05:45:42
2019-04-01T05:45:42
171,655,666
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Java2.Ques1; import java.util.Scanner; class Ques1 { public static void main(String args[]) { Librarian librarian = new Librarian(); do { System.out.println("MENU"); System.out.println("1.Issue books"); System.out.println("2.Return books"); System.out.println("3.Show book details"); System.out.println("4.Exit"); System.out.println("Enter choice: "); Scanner sc = new Scanner(System.in); int choice = sc.nextInt(); switch (choice) { case 1: librarian.issueBooks(); break; case 2: librarian.returnBooks(); break; case 3: librarian.showBooks(); break; } } while (true); } }
UTF-8
Java
905
java
Ques1.java
Java
[]
null
[]
package Java2.Ques1; import java.util.Scanner; class Ques1 { public static void main(String args[]) { Librarian librarian = new Librarian(); do { System.out.println("MENU"); System.out.println("1.Issue books"); System.out.println("2.Return books"); System.out.println("3.Show book details"); System.out.println("4.Exit"); System.out.println("Enter choice: "); Scanner sc = new Scanner(System.in); int choice = sc.nextInt(); switch (choice) { case 1: librarian.issueBooks(); break; case 2: librarian.returnBooks(); break; case 3: librarian.showBooks(); break; } } while (true); } }
905
0.461878
0.450829
33
26.454546
17.404442
54
false
false
0
0
0
0
0
0
0.545455
false
false
10
0fa86da62d8f175321938041792e0953cb6ebd7c
22,351,009,853,362
3bac2eef8a78836864c7e3994880779bddde2051
/app/src/main/java/ru/merkulyevsasha/easytodo/service/TasksService.java
115f63ceb32ab2bdff0522e7644077c048a25ddb
[]
no_license
sashamerkulev/EasyTodo
https://github.com/sashamerkulev/EasyTodo
de9abf986ef823aa302991d1d0bad8138ea932bc
525c2cfd42971a60460a583994ebd52a32dc71fd
refs/heads/master
2021-01-21T10:19:18.077000
2017-03-03T12:32:24
2017-03-03T12:32:24
83,404,902
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.merkulyevsasha.easytodo.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import ru.merkulyevsasha.core.callback.TasksCallback; import ru.merkulyevsasha.core.domain.TaskModel; import ru.merkulyevsasha.core.domain.TasksInteractor; import ru.merkulyevsasha.easytodo.TodoApp; public class TasksService extends Service{ @Inject public TasksInteractor interactor; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { ((TodoApp)getApplication()).getComponent().inject(this); new Thread(new Runnable() { @Override public void run() { try { interactor.loadExpiredTasks(new TasksCallback.LoadTasksCallback() { @Override public void loadTasksCallback(List<TaskModel> models) { ArrayList<Integer> ids = new ArrayList<>(); for (TaskModel model : models) { ids.add((int) model.getId()); } if (ids.size() > 0) { AlarmHelper.setNotification(TasksService.this, ids); } } }, new TasksCallback.LoadTasksFailureCallback() { @Override public void loadTasksFailureCallback(Exception e) { } }); } catch(Exception e){ e.printStackTrace(); } finally { AlarmHelper.register(TasksService.this); stopSelf(); } } }).start(); return super.onStartCommand(intent, flags, startId); } }
UTF-8
Java
2,124
java
TasksService.java
Java
[]
null
[]
package ru.merkulyevsasha.easytodo.service; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import ru.merkulyevsasha.core.callback.TasksCallback; import ru.merkulyevsasha.core.domain.TaskModel; import ru.merkulyevsasha.core.domain.TasksInteractor; import ru.merkulyevsasha.easytodo.TodoApp; public class TasksService extends Service{ @Inject public TasksInteractor interactor; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { ((TodoApp)getApplication()).getComponent().inject(this); new Thread(new Runnable() { @Override public void run() { try { interactor.loadExpiredTasks(new TasksCallback.LoadTasksCallback() { @Override public void loadTasksCallback(List<TaskModel> models) { ArrayList<Integer> ids = new ArrayList<>(); for (TaskModel model : models) { ids.add((int) model.getId()); } if (ids.size() > 0) { AlarmHelper.setNotification(TasksService.this, ids); } } }, new TasksCallback.LoadTasksFailureCallback() { @Override public void loadTasksFailureCallback(Exception e) { } }); } catch(Exception e){ e.printStackTrace(); } finally { AlarmHelper.register(TasksService.this); stopSelf(); } } }).start(); return super.onStartCommand(intent, flags, startId); } }
2,124
0.52919
0.528719
68
30.235294
23.869818
87
false
false
0
0
0
0
0
0
0.441176
false
false
10
92b6dd3b67126e5f8f18e24d55ee408a5f045ee5
3,745,211,515,320
222aa69a4dea7c1f747bbf5b980f6f69fa179e4c
/Java/--=A-Journey=--/Map.java
6d2841b3d55835a74a6cd63c48d17e907d7d57e0
[]
no_license
AAAdamovich/aaa-academic
https://github.com/AAAdamovich/aaa-academic
870f12d19f58b335c1e7b7d7e6adb4b4d88912a4
79471b340bfeaab120e1c377cfe6ecc9d0e6d7a6
refs/heads/master
2023-01-09T19:39:51.440000
2020-11-16T02:06:17
2020-11-16T02:06:17
35,231,982
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// Anton Adamovich // Project Started: 12-13-12 // This Class Created: 12-18-12 public class Map implements Item { private String name; public Map(){ name = "Map"; } public String getName(){ return name; } public void use(Inventory inven, Player player, ForestRoom room) { } public void inspect() { System.out.println("A piece of paper"); } }
UTF-8
Java
366
java
Map.java
Java
[ { "context": "// Anton Adamovich\n// Project Started: 12-13-12\n// This Class Create", "end": 18, "score": 0.9998559951782227, "start": 3, "tag": "NAME", "value": "Anton Adamovich" } ]
null
[]
// <NAME> // Project Started: 12-13-12 // This Class Created: 12-18-12 public class Map implements Item { private String name; public Map(){ name = "Map"; } public String getName(){ return name; } public void use(Inventory inven, Player player, ForestRoom room) { } public void inspect() { System.out.println("A piece of paper"); } }
357
0.669399
0.636612
23
14.956522
16.796682
67
false
false
0
0
0
0
0
0
1.043478
false
false
10
4bfb9d3a37a9b387bc8477f1b8597e543330754e
13,786,845,022,272
27026b02a72296fe7bb9660b6f4e9d776c3d3727
/src/LinkedPurchaseList.java
f0b67eccb90b271fdfb4750f354ec6576f4041a5
[]
no_license
SemenTolstov/Hibernate
https://github.com/SemenTolstov/Hibernate
7155e3f707bb348690d6b107869e3a82c750876e
b71b0058ea39d5ab7bee52e6c26f01ea1fb78769
refs/heads/master
2023-04-09T23:25:04.957000
2021-04-20T12:14:02
2021-04-20T12:14:02
359,798,219
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "LinkedPurchaseList") public class LinkedPurchaseList { public LinkedPurchaseList(KeySubscriptions id) { this.id = id; // this.courseId = courseId; // this.studentId = studentId; } @EmbeddedId private KeySubscriptions id; public KeySubscriptions getId() { return id; } public void setId(KeySubscriptions id) { this.id = id; } }
UTF-8
Java
563
java
LinkedPurchaseList.java
Java
[]
null
[]
import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "LinkedPurchaseList") public class LinkedPurchaseList { public LinkedPurchaseList(KeySubscriptions id) { this.id = id; // this.courseId = courseId; // this.studentId = studentId; } @EmbeddedId private KeySubscriptions id; public KeySubscriptions getId() { return id; } public void setId(KeySubscriptions id) { this.id = id; } }
563
0.674956
0.674956
29
18.413794
16.57692
52
false
false
0
0
0
0
0
0
0.344828
false
false
10
3d480024d299a013bc5ca9305ea884098ff8b269
27,857,157,887,464
92b42bec5e80479ba4b5aba3ea87e12e9ef5708f
/src/test/java/pl/sda/refactoring/customers/CustomerFacadeTest.java
98b263374e45642f12d722cb298d1b905b9df1b9
[]
no_license
kamil-jasek/clean-code-1
https://github.com/kamil-jasek/clean-code-1
dd64460f4a2651b9ffbafe88c352536e5abc68af
1e223db4dd7acf9923ae89d154350cfb84f37e24
refs/heads/master
2023-03-06T13:09:50.254000
2021-02-05T15:42:38
2021-02-05T15:42:38
335,257,676
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.sda.refactoring.customers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.Test; import pl.sda.refactoring.customers.dto.CustomerVerifier; import pl.sda.refactoring.customers.dto.Email; import pl.sda.refactoring.customers.dto.Name; import pl.sda.refactoring.customers.dto.Pesel; import pl.sda.refactoring.customers.dto.RegisterCompany; import pl.sda.refactoring.customers.dto.RegisterPerson; import pl.sda.refactoring.customers.dto.UpdateAddress; import pl.sda.refactoring.customers.dto.UpdatedAddress; import pl.sda.refactoring.customers.dto.Vat; import pl.sda.refactoring.customers.exceptions.CustomerExistsException; import pl.sda.refactoring.customers.exceptions.CustomerNotExistsException; class CustomerFacadeTest { private final TestCustomerFacadeConfig config = new TestCustomerFacadeConfig(); private final CustomerFacade facade = config.facade(); @Test void shouldNotRegisterPersonWhenAlreadyExists() { // given given(config.dao().emailExists(any())).willReturn(true); given(config.dao().peselExists(any())).willReturn(true); // when assertThrows(CustomerExistsException.class, () -> facade.registerPerson(new RegisterPerson( Email.of("em@test.com"), Name.of("Jan"), Name.of("Kowalski"), Pesel.of("92893202093"), false))); } @Test void shouldRegisterNotVerifiedPerson() { // when final var registeredPerson = facade.registerPerson( new RegisterPerson(Email.of("em@test.com"), Name.of("Jan"), Name.of("Kowalski"), Pesel.of("92893202093"), false)); // then assertNotNull(registeredPerson); assertNotNull(registeredPerson.getId()); assertFalse(registeredPerson.isVerified()); assertEquals("em@test.com", registeredPerson.getEmail()); assertEquals("Jan", registeredPerson.getFirstName()); assertEquals("Kowalski", registeredPerson.getLastName()); assertEquals("92893202093", registeredPerson.getPesel()); assertNotNull(registeredPerson.getCreateTime()); } @Test void shouldRegisterVerifiedPerson() { // when final var registeredPerson = facade.registerPerson( new RegisterPerson(Email.of("em@test.com"), Name.of("Jan"), Name.of("Kowalski"), Pesel.of("92893202093"), true)); // then assertNotNull(registeredPerson.getId()); assertNotNull(registeredPerson.getCreateTime()); assertTrue(registeredPerson.isVerified()); assertNotNull(registeredPerson.getVerification().getVerificationTime()); assertEquals(CustomerVerifier.AUTO_EMAIL, registeredPerson.getVerification().getVerifier()); assertEquals("em@test.com", registeredPerson.getEmail()); assertEquals("Jan", registeredPerson.getFirstName()); assertEquals("Kowalski", registeredPerson.getLastName()); assertEquals("92893202093", registeredPerson.getPesel()); } @Test void shouldNotRegisterCompanyIfExists() { // given given(config.dao().emailExists(any())).willReturn(true); given(config.dao().vatExists(any())).willReturn(true); // when assertThrows(CustomerExistsException.class, () -> facade.registerCompany(new RegisterCompany( Email.of("em@test.com"), Name.of("Test S.A."), Vat.of("8384783833"), false))); } @Test void shouldRegisterNotVerifiedCompany() { // when final var registeredCompany = facade.registerCompany( new RegisterCompany(Email.of("em@test.com"), Name.of("Test S.A."), Vat.of("8384783833"), false)); // then assertNotNull(registeredCompany); assertNotNull(registeredCompany.getId()); assertNotNull(registeredCompany.getCreateTime()); assertFalse(registeredCompany.isVerified()); assertEquals("em@test.com", registeredCompany.getEmail()); assertEquals("Test S.A.", registeredCompany.getName()); assertEquals("8384783833", registeredCompany.getVat()); } @Test void shouldRegisterVerifiedCompany() { // when final var customer = facade.registerCompany(new RegisterCompany( Email.of("em@test.com"), Name.of("Test S.A."), Vat.of("8384783833"), true)); // then assertNotNull(customer); assertNotNull(customer.getId()); assertNotNull(customer.getCreateTime()); assertTrue(customer.isVerified()); assertNotNull(customer.getVerification().getVerificationTime()); assertEquals(CustomerVerifier.AUTO_EMAIL, customer.getVerification().getVerifier()); assertEquals("em@test.com", customer.getEmail()); assertEquals("Test S.A.", customer.getName()); assertEquals("8384783833", customer.getVat()); } @Test void shouldNotUpdateAddressIfCustomerNotExists() { // given given(config.dao().findById(any())).willReturn(Optional.empty()); // when assertThrows(CustomerNotExistsException.class, () -> facade.updateAddress(new UpdateAddress(UUID.randomUUID(), "str", "02-303", "Wawa", "PL"))); } @Test void shouldUpdateAddress() { // given given(config.dao().findById(any())).willReturn(Optional.of(new Person(Email.of("em@test.com"), Name.of("test"), Name.of("test"), Pesel.of("19393929329")))); final var customerId = UUID.fromString("df55ad5d-6d50-4e52-8599-b4abb23a27d1"); // when final var updatedAddress = facade.updateAddress(new UpdateAddress(customerId, "str", "02-303", "Wawa", "PL")); // then assertNotNull(updatedAddress); assertEquals(new UpdatedAddress(customerId, "str", "02-303", "Wawa", "PL"), updatedAddress); } }
UTF-8
Java
6,574
java
CustomerFacadeTest.java
Java
[ { "context": "rPerson(new RegisterPerson(\n Email.of(\"em@test.com\"),\n Name.of(\"Jan\"),\n Name.o", "end": 1660, "score": 0.9999153017997742, "start": 1649, "tag": "EMAIL", "value": "em@test.com" }, { "context": " Email.of(\"em@test.com\"),\n Name.of(\"Jan\"),\n Name.of(\"Kowalski\"),\n P", "end": 1688, "score": 0.9998615980148315, "start": 1685, "tag": "NAME", "value": "Jan" }, { "context": "\n Name.of(\"Jan\"),\n Name.of(\"Kowalski\"),\n Pesel.of(\"92893202093\"),\n ", "end": 1721, "score": 0.9966174960136414, "start": 1713, "tag": "NAME", "value": "Kowalski" }, { "context": "rPerson(\n new RegisterPerson(Email.of(\"em@test.com\"),\n Name.of(\"Jan\"),\n ", "end": 1974, "score": 0.9988099932670593, "start": 1963, "tag": "EMAIL", "value": "em@test.com" }, { "context": "Email.of(\"em@test.com\"),\n Name.of(\"Jan\"),\n Name.of(\"Kowalski\"),\n ", "end": 2006, "score": 0.9998118877410889, "start": 2003, "tag": "NAME", "value": "Jan" }, { "context": " Name.of(\"Jan\"),\n Name.of(\"Kowalski\"),\n Pesel.of(\"92893202093\"),\n ", "end": 2043, "score": 0.9992741942405701, "start": 2035, "tag": "NAME", "value": "Kowalski" }, { "context": "steredPerson.isVerified());\n assertEquals(\"em@test.com\", registeredPerson.getEmail());\n assertEqu", "end": 2305, "score": 0.9999204874038696, "start": 2294, "tag": "EMAIL", "value": "em@test.com" }, { "context": "gisteredPerson.getEmail());\n assertEquals(\"Jan\", registeredPerson.getFirstName());\n asser", "end": 2363, "score": 0.999458372592926, "start": 2360, "tag": "NAME", "value": "Jan" }, { "context": "eredPerson.getFirstName());\n assertEquals(\"Kowalski\", registeredPerson.getLastName());\n assert", "end": 2430, "score": 0.9993564486503601, "start": 2422, "tag": "NAME", "value": "Kowalski" }, { "context": "rPerson(\n new RegisterPerson(Email.of(\"em@test.com\"),\n Name.of(\"Jan\"),\n ", "end": 2776, "score": 0.9999170303344727, "start": 2765, "tag": "EMAIL", "value": "em@test.com" }, { "context": "Email.of(\"em@test.com\"),\n Name.of(\"Jan\"),\n Name.of(\"Kowalski\"),\n ", "end": 2808, "score": 0.999774158000946, "start": 2805, "tag": "NAME", "value": "Jan" }, { "context": " Name.of(\"Jan\"),\n Name.of(\"Kowalski\"),\n Pesel.of(\"92893202093\"),\n ", "end": 2845, "score": 0.9995590448379517, "start": 2837, "tag": "NAME", "value": "Kowalski" }, { "context": "ification().getVerifier());\n assertEquals(\"em@test.com\", registeredPerson.getEmail());\n assertEqu", "end": 3303, "score": 0.9999200105667114, "start": 3292, "tag": "EMAIL", "value": "em@test.com" }, { "context": "gisteredPerson.getEmail());\n assertEquals(\"Jan\", registeredPerson.getFirstName());\n asser", "end": 3361, "score": 0.9996333122253418, "start": 3358, "tag": "NAME", "value": "Jan" }, { "context": "eredPerson.getFirstName());\n assertEquals(\"Kowalski\", registeredPerson.getLastName());\n assert", "end": 3428, "score": 0.9995226263999939, "start": 3420, "tag": "NAME", "value": "Kowalski" }, { "context": "ompany(new RegisterCompany(\n Email.of(\"em@test.com\"),\n Name.of(\"Test S.A.\"),\n ", "end": 3890, "score": 0.9999157786369324, "start": 3879, "tag": "EMAIL", "value": "em@test.com" }, { "context": "ompany(\n new RegisterCompany(Email.of(\"em@test.com\"),\n Name.of(\"Test S.A.\"),\n ", "end": 4178, "score": 0.9999223947525024, "start": 4167, "tag": "EMAIL", "value": "em@test.com" }, { "context": "Email.of(\"em@test.com\"),\n Name.of(\"Test S.A.\"),\n Vat.of(\"8384783833\"),\n ", "end": 4215, "score": 0.6733137369155884, "start": 4207, "tag": "NAME", "value": "Test S.A" }, { "context": "teredCompany.isVerified());\n assertEquals(\"em@test.com\", registeredCompany.getEmail());\n assertEq", "end": 4536, "score": 0.9999271631240845, "start": 4525, "tag": "EMAIL", "value": "em@test.com" }, { "context": "redCompany.getEmail());\n assertEquals(\"Test S.A.\", registeredCompany.getName());\n assertEq", "end": 4600, "score": 0.7429311871528625, "start": 4597, "tag": "NAME", "value": "S.A" }, { "context": "ompany(new RegisterCompany(\n Email.of(\"em@test.com\"),\n Name.of(\"Test S.A.\"),\n ", "end": 4880, "score": 0.9999276995658875, "start": 4869, "tag": "EMAIL", "value": "em@test.com" }, { "context": " Email.of(\"em@test.com\"),\n Name.of(\"Test S.A.\"),\n Vat.of(\"8384783833\"),\n tru", "end": 4913, "score": 0.9725459814071655, "start": 4905, "tag": "NAME", "value": "Test S.A" }, { "context": "ification().getVerifier());\n assertEquals(\"em@test.com\", customer.getEmail());\n assertEquals(\"Tes", "end": 5354, "score": 0.9999244809150696, "start": 5343, "tag": "EMAIL", "value": "em@test.com" }, { "context": "com\", customer.getEmail());\n assertEquals(\"Test S.A.\", customer.getName());\n assertEquals(\"838478", "end": 5409, "score": 0.861497700214386, "start": 5401, "tag": "NAME", "value": "Test S.A" }, { "context": "y())).willReturn(Optional.of(new Person(Email.of(\"em@test.com\"),\n Name.of(\"test\"),\n Name.", "end": 6036, "score": 0.9999279975891113, "start": 6025, "tag": "EMAIL", "value": "em@test.com" }, { "context": "son(Email.of(\"em@test.com\"),\n Name.of(\"test\"),\n Name.of(\"test\"),\n Pesel", "end": 6065, "score": 0.9034273028373718, "start": 6061, "tag": "NAME", "value": "test" }, { "context": " Name.of(\"test\"),\n Name.of(\"test\"),\n Pesel.of(\"19393929329\"))));\n ", "end": 6094, "score": 0.8205479383468628, "start": 6090, "tag": "NAME", "value": "test" } ]
null
[]
package pl.sda.refactoring.customers; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Matchers.any; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.Test; import pl.sda.refactoring.customers.dto.CustomerVerifier; import pl.sda.refactoring.customers.dto.Email; import pl.sda.refactoring.customers.dto.Name; import pl.sda.refactoring.customers.dto.Pesel; import pl.sda.refactoring.customers.dto.RegisterCompany; import pl.sda.refactoring.customers.dto.RegisterPerson; import pl.sda.refactoring.customers.dto.UpdateAddress; import pl.sda.refactoring.customers.dto.UpdatedAddress; import pl.sda.refactoring.customers.dto.Vat; import pl.sda.refactoring.customers.exceptions.CustomerExistsException; import pl.sda.refactoring.customers.exceptions.CustomerNotExistsException; class CustomerFacadeTest { private final TestCustomerFacadeConfig config = new TestCustomerFacadeConfig(); private final CustomerFacade facade = config.facade(); @Test void shouldNotRegisterPersonWhenAlreadyExists() { // given given(config.dao().emailExists(any())).willReturn(true); given(config.dao().peselExists(any())).willReturn(true); // when assertThrows(CustomerExistsException.class, () -> facade.registerPerson(new RegisterPerson( Email.of("<EMAIL>"), Name.of("Jan"), Name.of("Kowalski"), Pesel.of("92893202093"), false))); } @Test void shouldRegisterNotVerifiedPerson() { // when final var registeredPerson = facade.registerPerson( new RegisterPerson(Email.of("<EMAIL>"), Name.of("Jan"), Name.of("Kowalski"), Pesel.of("92893202093"), false)); // then assertNotNull(registeredPerson); assertNotNull(registeredPerson.getId()); assertFalse(registeredPerson.isVerified()); assertEquals("<EMAIL>", registeredPerson.getEmail()); assertEquals("Jan", registeredPerson.getFirstName()); assertEquals("Kowalski", registeredPerson.getLastName()); assertEquals("92893202093", registeredPerson.getPesel()); assertNotNull(registeredPerson.getCreateTime()); } @Test void shouldRegisterVerifiedPerson() { // when final var registeredPerson = facade.registerPerson( new RegisterPerson(Email.of("<EMAIL>"), Name.of("Jan"), Name.of("Kowalski"), Pesel.of("92893202093"), true)); // then assertNotNull(registeredPerson.getId()); assertNotNull(registeredPerson.getCreateTime()); assertTrue(registeredPerson.isVerified()); assertNotNull(registeredPerson.getVerification().getVerificationTime()); assertEquals(CustomerVerifier.AUTO_EMAIL, registeredPerson.getVerification().getVerifier()); assertEquals("<EMAIL>", registeredPerson.getEmail()); assertEquals("Jan", registeredPerson.getFirstName()); assertEquals("Kowalski", registeredPerson.getLastName()); assertEquals("92893202093", registeredPerson.getPesel()); } @Test void shouldNotRegisterCompanyIfExists() { // given given(config.dao().emailExists(any())).willReturn(true); given(config.dao().vatExists(any())).willReturn(true); // when assertThrows(CustomerExistsException.class, () -> facade.registerCompany(new RegisterCompany( Email.of("<EMAIL>"), Name.of("Test S.A."), Vat.of("8384783833"), false))); } @Test void shouldRegisterNotVerifiedCompany() { // when final var registeredCompany = facade.registerCompany( new RegisterCompany(Email.of("<EMAIL>"), Name.of("<NAME>."), Vat.of("8384783833"), false)); // then assertNotNull(registeredCompany); assertNotNull(registeredCompany.getId()); assertNotNull(registeredCompany.getCreateTime()); assertFalse(registeredCompany.isVerified()); assertEquals("<EMAIL>", registeredCompany.getEmail()); assertEquals("Test S.A.", registeredCompany.getName()); assertEquals("8384783833", registeredCompany.getVat()); } @Test void shouldRegisterVerifiedCompany() { // when final var customer = facade.registerCompany(new RegisterCompany( Email.of("<EMAIL>"), Name.of("<NAME>."), Vat.of("8384783833"), true)); // then assertNotNull(customer); assertNotNull(customer.getId()); assertNotNull(customer.getCreateTime()); assertTrue(customer.isVerified()); assertNotNull(customer.getVerification().getVerificationTime()); assertEquals(CustomerVerifier.AUTO_EMAIL, customer.getVerification().getVerifier()); assertEquals("<EMAIL>", customer.getEmail()); assertEquals("<NAME>.", customer.getName()); assertEquals("8384783833", customer.getVat()); } @Test void shouldNotUpdateAddressIfCustomerNotExists() { // given given(config.dao().findById(any())).willReturn(Optional.empty()); // when assertThrows(CustomerNotExistsException.class, () -> facade.updateAddress(new UpdateAddress(UUID.randomUUID(), "str", "02-303", "Wawa", "PL"))); } @Test void shouldUpdateAddress() { // given given(config.dao().findById(any())).willReturn(Optional.of(new Person(Email.of("<EMAIL>"), Name.of("test"), Name.of("test"), Pesel.of("19393929329")))); final var customerId = UUID.fromString("df55ad5d-6d50-4e52-8599-b4abb23a27d1"); // when final var updatedAddress = facade.updateAddress(new UpdateAddress(customerId, "str", "02-303", "Wawa", "PL")); // then assertNotNull(updatedAddress); assertEquals(new UpdatedAddress(customerId, "str", "02-303", "Wawa", "PL"), updatedAddress); } }
6,524
0.646486
0.623669
176
36.357956
26.597853
118
false
false
0
0
0
0
0
0
0.738636
false
false
10
2fa20e4d11db9c4d92f9034fff2c06a035628f4b
23,639,500,008,192
db456b6453e4539ae1ebeea2179250d4533aa588
/app/src/main/java/com/ssn/ssn_yrc/activities/NotificationDetailActivity.java
8b39deb470991c0e67ce7c2a834ea986836cbdef
[]
no_license
rajakumaran1203/SSNYRC
https://github.com/rajakumaran1203/SSNYRC
0b9c7e1f27d4a3de2fd4692df889fa54abfaad1d
ebe73bd5bdc605cc5c0fafe18148696b3508af03
refs/heads/master
2020-04-20T17:05:29.685000
2019-02-03T20:40:09
2019-02-03T20:40:09
168,978,748
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2017 Adithya J * * 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.ssn.ssn_yrc.activities; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.annotation.NonNull; import android.support.customtabs.CustomTabsIntent; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.ssn.ssn_yrc.R; import com.ssn.ssn_yrc.model.Post; import com.ssn.ssn_yrc.utils.FileDownloader; import com.ssn.ssn_yrc.utils.LogHelper; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import butterknife.BindView; import butterknife.ButterKnife; public class NotificationDetailActivity extends AppCompatActivity { private static final String TAG = LogHelper.makeLogTag(NotificationDetailActivity.class); private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 0; TextView contentEmail1; ImageView postImageView; private String title, content, fileName, date; private TextView dispContent, dispNo1, dispUrl1, dispUrl2, dispTitle, dispPdf, dispDate; private Post post; private ArrayList<String> links; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification_details); ButterKnife.bind(this); getSupportActionBar().setTitle("Notifications"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); dispTitle = (TextView) findViewById(R.id.alert_title); dispContent = (TextView) findViewById(R.id.content_activity); dispNo1 = (TextView) findViewById(R.id.content_contact1); dispUrl1 = (TextView) findViewById(R.id.content_url1); dispUrl2 = (TextView) findViewById(R.id.content_url2); dispPdf = (TextView) findViewById(R.id.content_pdf); dispDate = (TextView) findViewById(R.id.postdate); post = new Gson().fromJson(getIntent().getStringExtra("post"), Post.class); title = post.getTitle(); content = post.getDescription(); dispTitle.setText(title); Date date = new Date(post.getDate()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aaa 'on' EEE, dd MMM"); dispDate.setText(simpleDateFormat.format(date)); links = extractUrls(); dispUrls(); dispNos(); dispContent.setText(content); if (!post.getFileURL().equals("")) { fileName = post.getFileName(); if (fileName.contains(".pdf")) { dispPdf.setText(fileName); dispPdf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(NotificationDetailActivity.this, "Downloading..", Toast.LENGTH_SHORT).show(); if (ContextCompat.checkSelfPermission(NotificationDetailActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(NotificationDetailActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); } else { new DownloadFile().execute(post.getFileURL(), post.getFileName()); } } }); postImageView.setVisibility(View.GONE); } else if (fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".png")) { Glide.with(this).load(post.getFileURL()).into(postImageView); dispPdf.setVisibility(View.GONE); } } else { dispPdf.setVisibility(View.GONE); postImageView.setVisibility(View.GONE); } if (!post.getEmail().equals("")) { contentEmail1.setText(post.getEmail()); contentEmail1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + post.getEmail())); startActivity(Intent.createChooser(emailIntent, "Send Email")); } }); } else contentEmail1.setVisibility(View.GONE); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { new DownloadFile().execute(post.getFileURL(), post.getFileName()); } } else { Toast.makeText(this, "Permission to open file denied!", Toast.LENGTH_LONG).show(); } } private void dispUrls() { if (links.size() == 2) { dispUrl1.setText(links.get(0)); dispUrl2.setText(links.get(1)); dispUrl1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startUrlIntent(dispUrl1.getText().toString()); } }); dispUrl2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startUrlIntent(dispUrl2.getText().toString()); } }); } else if (links.size() == 1) { dispUrl1.setText(links.get(0)); dispUrl2.setVisibility(View.GONE); dispUrl1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startUrlIntent(dispUrl1.getText().toString()); } }); } else { dispUrl1.setVisibility(View.GONE); dispUrl2.setVisibility(View.GONE); } } private void dispNos() { if (!post.getContactno().equals("")) { dispNo1.setText(post.getContactno()); dispNo1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + dispNo1.getText().toString().trim()))); } }); } else dispNo1.setVisibility(View.GONE); } private ArrayList<String> extractUrls() { ArrayList<String> result = new ArrayList<String>(); Pattern pattern = Pattern.compile( "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.|coe1.|coe2.)" + "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov|co|in" + "|mil|biz|info|mobi|name|aero|jobs|edu|museum" + "|travel|[a-z]{2}))(:[\\d]{1,5})?" + "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" + "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" + "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b"); Matcher matcher = pattern.matcher(content); while (matcher.find()) { result.add(matcher.group()); content = content.replace(matcher.group(), ""); } return result; } private void startUrlIntent(String textViewString) { if (!(textViewString.contains("http://") || textViewString.contains("https://"))) { textViewString = "http://" + textViewString; } CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); builder.setShowTitle(true); CustomTabsIntent customTabsIntent = builder.build(); customTabsIntent.launchUrl(this, Uri.parse(textViewString)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private class DownloadFile extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... strings) { String fileUrl = strings[0]; String fileName = strings[1]; String status; String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); File folder = new File(extStorageDirectory, "TheSSNApp"); folder.mkdir(); File pdfFile = new File(folder, fileName); try { pdfFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } status = FileDownloader.downloadFile(fileUrl, pdfFile); if (status.equals("Success")) return fileName; else return "Failure"; } @Override protected void onPostExecute(String fileName) { if (fileName.equals("Failure")) Toast.makeText(NotificationDetailActivity.this, "I/O Error!", Toast.LENGTH_LONG).show(); else { File pdfFile = new File(Environment.getExternalStorageDirectory() + "/TheSSNApp/" + fileName); Uri path = FileProvider.getUriForFile(NotificationDetailActivity.this, getApplicationContext().getPackageName() + ".provider", pdfFile); Intent pdfIntent = new Intent(Intent.ACTION_VIEW); pdfIntent.setDataAndType(path, "application/pdf"); pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(pdfIntent); } catch (ActivityNotFoundException e) { Toast.makeText(NotificationDetailActivity.this, "Cannot find application to open PDF!", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } } } }
UTF-8
Java
12,005
java
NotificationDetailActivity.java
Java
[ { "context": "/*\n * Copyright (C) 2017 Adithya J\n *\n * This program is free software: you can ", "end": 39, "score": 0.9995855689048767, "start": 30, "tag": "NAME", "value": "Adithya J" } ]
null
[]
/* * Copyright (C) 2017 <NAME> * * 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.ssn.ssn_yrc.activities; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.annotation.NonNull; import android.support.customtabs.CustomTabsIntent; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.gson.Gson; import com.ssn.ssn_yrc.R; import com.ssn.ssn_yrc.model.Post; import com.ssn.ssn_yrc.utils.FileDownloader; import com.ssn.ssn_yrc.utils.LogHelper; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import butterknife.BindView; import butterknife.ButterKnife; public class NotificationDetailActivity extends AppCompatActivity { private static final String TAG = LogHelper.makeLogTag(NotificationDetailActivity.class); private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 0; TextView contentEmail1; ImageView postImageView; private String title, content, fileName, date; private TextView dispContent, dispNo1, dispUrl1, dispUrl2, dispTitle, dispPdf, dispDate; private Post post; private ArrayList<String> links; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification_details); ButterKnife.bind(this); getSupportActionBar().setTitle("Notifications"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); dispTitle = (TextView) findViewById(R.id.alert_title); dispContent = (TextView) findViewById(R.id.content_activity); dispNo1 = (TextView) findViewById(R.id.content_contact1); dispUrl1 = (TextView) findViewById(R.id.content_url1); dispUrl2 = (TextView) findViewById(R.id.content_url2); dispPdf = (TextView) findViewById(R.id.content_pdf); dispDate = (TextView) findViewById(R.id.postdate); post = new Gson().fromJson(getIntent().getStringExtra("post"), Post.class); title = post.getTitle(); content = post.getDescription(); dispTitle.setText(title); Date date = new Date(post.getDate()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aaa 'on' EEE, dd MMM"); dispDate.setText(simpleDateFormat.format(date)); links = extractUrls(); dispUrls(); dispNos(); dispContent.setText(content); if (!post.getFileURL().equals("")) { fileName = post.getFileName(); if (fileName.contains(".pdf")) { dispPdf.setText(fileName); dispPdf.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(NotificationDetailActivity.this, "Downloading..", Toast.LENGTH_SHORT).show(); if (ContextCompat.checkSelfPermission(NotificationDetailActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(NotificationDetailActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE); } else { new DownloadFile().execute(post.getFileURL(), post.getFileName()); } } }); postImageView.setVisibility(View.GONE); } else if (fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".png")) { Glide.with(this).load(post.getFileURL()).into(postImageView); dispPdf.setVisibility(View.GONE); } } else { dispPdf.setVisibility(View.GONE); postImageView.setVisibility(View.GONE); } if (!post.getEmail().equals("")) { contentEmail1.setText(post.getEmail()); contentEmail1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + post.getEmail())); startActivity(Intent.createChooser(emailIntent, "Send Email")); } }); } else contentEmail1.setVisibility(View.GONE); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { new DownloadFile().execute(post.getFileURL(), post.getFileName()); } } else { Toast.makeText(this, "Permission to open file denied!", Toast.LENGTH_LONG).show(); } } private void dispUrls() { if (links.size() == 2) { dispUrl1.setText(links.get(0)); dispUrl2.setText(links.get(1)); dispUrl1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startUrlIntent(dispUrl1.getText().toString()); } }); dispUrl2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startUrlIntent(dispUrl2.getText().toString()); } }); } else if (links.size() == 1) { dispUrl1.setText(links.get(0)); dispUrl2.setVisibility(View.GONE); dispUrl1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startUrlIntent(dispUrl1.getText().toString()); } }); } else { dispUrl1.setVisibility(View.GONE); dispUrl2.setVisibility(View.GONE); } } private void dispNos() { if (!post.getContactno().equals("")) { dispNo1.setText(post.getContactno()); dispNo1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + dispNo1.getText().toString().trim()))); } }); } else dispNo1.setVisibility(View.GONE); } private ArrayList<String> extractUrls() { ArrayList<String> result = new ArrayList<String>(); Pattern pattern = Pattern.compile( "\\b(((ht|f)tp(s?)\\:\\/\\/|~\\/|\\/)|www.|coe1.|coe2.)" + "(\\w+:\\w+@)?(([-\\w]+\\.)+(com|org|net|gov|co|in" + "|mil|biz|info|mobi|name|aero|jobs|edu|museum" + "|travel|[a-z]{2}))(:[\\d]{1,5})?" + "(((\\/([-\\w~!$+|.,=]|%[a-f\\d]{2})+)+|\\/)+|\\?|#)?" + "((\\?([-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)" + "(&(?:[-\\w~!$+|.,*:]|%[a-f\\d{2}])+=?" + "([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)*)*" + "(#([-\\w~!$+|.,*:=]|%[a-f\\d]{2})*)?\\b"); Matcher matcher = pattern.matcher(content); while (matcher.find()) { result.add(matcher.group()); content = content.replace(matcher.group(), ""); } return result; } private void startUrlIntent(String textViewString) { if (!(textViewString.contains("http://") || textViewString.contains("https://"))) { textViewString = "http://" + textViewString; } CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); builder.setToolbarColor(getResources().getColor(R.color.colorPrimary)); builder.setShowTitle(true); CustomTabsIntent customTabsIntent = builder.build(); customTabsIntent.launchUrl(this, Uri.parse(textViewString)); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } private class DownloadFile extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... strings) { String fileUrl = strings[0]; String fileName = strings[1]; String status; String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); File folder = new File(extStorageDirectory, "TheSSNApp"); folder.mkdir(); File pdfFile = new File(folder, fileName); try { pdfFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } status = FileDownloader.downloadFile(fileUrl, pdfFile); if (status.equals("Success")) return fileName; else return "Failure"; } @Override protected void onPostExecute(String fileName) { if (fileName.equals("Failure")) Toast.makeText(NotificationDetailActivity.this, "I/O Error!", Toast.LENGTH_LONG).show(); else { File pdfFile = new File(Environment.getExternalStorageDirectory() + "/TheSSNApp/" + fileName); Uri path = FileProvider.getUriForFile(NotificationDetailActivity.this, getApplicationContext().getPackageName() + ".provider", pdfFile); Intent pdfIntent = new Intent(Intent.ACTION_VIEW); pdfIntent.setDataAndType(path, "application/pdf"); pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(pdfIntent); } catch (ActivityNotFoundException e) { Toast.makeText(NotificationDetailActivity.this, "Cannot find application to open PDF!", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } } } }
12,002
0.586839
0.581924
310
37.72258
30.202229
146
false
false
0
0
0
0
0
0
0.751613
false
false
10
a2e4b35a010583385b5d371bf2b5fb68d5471780
498,216,243,755
fa75b0d1cb18e9d92e6b7f9c6e732881dee90b20
/micro/micro-portal/src/main/java/com/cloud/portal/archive/csgz/service/CsgzService.java
38f12fc152415bd38956a3161562cc819b99e81e
[]
no_license
zhongym/clound
https://github.com/zhongym/clound
ea083d9b27a7e76c831208bba41deb9c329d5e64
29b25ac0cf743fdaf9a119792cdbd8153b6c7f75
refs/heads/master
2022-02-25T21:29:41.034000
2019-10-08T08:02:55
2019-10-08T08:02:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cloud.portal.archive.csgz.service; import com.cloud.portal.archive.common.base.service.DataService; import com.cloud.portal.archive.csgz.model.Csgz; /** * @author lvlinc * @date Created in 2019/5/22 10:22:00 * @description: 特行场所关注信息 * @modified By:lvlinc */ public interface CsgzService extends DataService<Csgz> { /** * 添加场所关注 * @param csgz * @return */ boolean savecsgz(Csgz csgz); /** * 是否场所关注 * @param csgz * @return */ int getis (Csgz csgz); /** * 取消场所关注 * @param csdwbh * @param userid * @return */ boolean remove(String csdwbh,String userid); }
UTF-8
Java
714
java
CsgzService.java
Java
[ { "context": "ud.portal.archive.csgz.model.Csgz;\n\n/**\n * @author lvlinc\n * @date Created in 2019/5/22 10:22:00\n * @descri", "end": 184, "score": 0.9997144341468811, "start": 178, "tag": "USERNAME", "value": "lvlinc" }, { "context": "0:22:00\n * @description: 特行场所关注信息\n * @modified By:lvlinc\n */\npublic interface CsgzService extends DataServ", "end": 272, "score": 0.9997270703315735, "start": 266, "tag": "USERNAME", "value": "lvlinc" } ]
null
[]
package com.cloud.portal.archive.csgz.service; import com.cloud.portal.archive.common.base.service.DataService; import com.cloud.portal.archive.csgz.model.Csgz; /** * @author lvlinc * @date Created in 2019/5/22 10:22:00 * @description: 特行场所关注信息 * @modified By:lvlinc */ public interface CsgzService extends DataService<Csgz> { /** * 添加场所关注 * @param csgz * @return */ boolean savecsgz(Csgz csgz); /** * 是否场所关注 * @param csgz * @return */ int getis (Csgz csgz); /** * 取消场所关注 * @param csdwbh * @param userid * @return */ boolean remove(String csdwbh,String userid); }
714
0.614804
0.595166
34
18.470589
16.938011
64
false
false
0
0
0
0
0
0
0.205882
false
false
10
09d1f449a3d3e8a8684f3a9efe7d5b1b8b2fc640
30,099,130,881,671
1e07946fe25d9d123cb8ce117302f1b67277d0e8
/app/src/main/java/com/example/sembakopaktoyib/SembakoData.java
c6b77142d6a7f52ad592e626e9b13005a278a17b
[]
no_license
gabrillukita1/Tugas3-GabrilCahyaLukita-124190026
https://github.com/gabrillukita1/Tugas3-GabrilCahyaLukita-124190026
253e253575360e0d6d4a27b6f57882eb644bfd92
8ea5a097a9499866dceab614d41debb69fd28c61
refs/heads/master
2023-04-06T23:56:41.851000
2021-04-13T17:38:41
2021-04-13T17:38:41
357,638,814
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sembakopaktoyib; import java.util.ArrayList; public class SembakoData { private static String[] nama = new String[]{"Beras | 8500/Kg", "indomie | 2500/Pcs", "Minyak | 12000/L", "Telur | 20000/Kg", "Marlboro | 27000/Bks", "Sprite / 10000/Ltr"}; private static int[] gambar = new int[]{R.drawable.beras, R.drawable.indomie, R.drawable.minyak, R.drawable.telur, R.drawable.malboro, R.drawable.sprite}; public static ArrayList<SembakoModel> getListData(){ SembakoModel sembakoModel = null; ArrayList<SembakoModel> list = new ArrayList<>(); for (int i = 0; i < nama.length; i++){ sembakoModel = new SembakoModel(); sembakoModel.setIcon(gambar[i]); sembakoModel.setNamabarang(nama[i]); list.add(sembakoModel); } return list; } public String getNama(int position) { return nama[position]; } public int getGambar(int position) { return gambar[position]; } }
UTF-8
Java
1,037
java
SembakoData.java
Java
[]
null
[]
package com.example.sembakopaktoyib; import java.util.ArrayList; public class SembakoData { private static String[] nama = new String[]{"Beras | 8500/Kg", "indomie | 2500/Pcs", "Minyak | 12000/L", "Telur | 20000/Kg", "Marlboro | 27000/Bks", "Sprite / 10000/Ltr"}; private static int[] gambar = new int[]{R.drawable.beras, R.drawable.indomie, R.drawable.minyak, R.drawable.telur, R.drawable.malboro, R.drawable.sprite}; public static ArrayList<SembakoModel> getListData(){ SembakoModel sembakoModel = null; ArrayList<SembakoModel> list = new ArrayList<>(); for (int i = 0; i < nama.length; i++){ sembakoModel = new SembakoModel(); sembakoModel.setIcon(gambar[i]); sembakoModel.setNamabarang(nama[i]); list.add(sembakoModel); } return list; } public String getNama(int position) { return nama[position]; } public int getGambar(int position) { return gambar[position]; } }
1,037
0.621022
0.593057
32
31.40625
28.924318
100
false
false
0
0
0
0
0
0
0.9375
false
false
10
8d7c3b0204ea59012c4fe5cba3985c4c39e4b1da
21,680,994,912,865
6c0e50f926a00738754a846fe1f5101f628917bd
/bpel-connectors/src/main/java/com/taras/chornyi/bpel/connectors/retry/BpelState.java
fc561dc1f4bccd0dc90d1c0731df6c62da1c1ff2
[ "MIT" ]
permissive
reftch/bpel-process
https://github.com/reftch/bpel-process
978868ea4d2f5e10ad2118fc9bb859c22b95bb58
79a490ee617e77f33acd145e598dd4c2dd029fb9
refs/heads/main
2023-03-30T10:46:11.203000
2021-03-27T11:54:45
2021-03-27T11:54:45
352,060,296
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.taras.chornyi.bpel.connectors.retry; /** * BPEL process state * * @author Taras Chornyi */ public enum BpelState { NEW, RUNNING, FAILED, RETRY, OUTDATED, FINISHED }
UTF-8
Java
186
java
BpelState.java
Java
[ { "context": "rs.retry;\n\n/**\n * BPEL process state\n *\n * @author Taras Chornyi\n */\npublic enum BpelState {\n NEW, RUNNING, FAI", "end": 103, "score": 0.9998820424079895, "start": 90, "tag": "NAME", "value": "Taras Chornyi" } ]
null
[]
package com.taras.chornyi.bpel.connectors.retry; /** * BPEL process state * * @author <NAME> */ public enum BpelState { NEW, RUNNING, FAILED, RETRY, OUTDATED, FINISHED }
179
0.704301
0.704301
10
17.6
18.374983
51
false
false
0
0
0
0
0
0
0.6
false
false
10
bd08b66f367ff663cf82735cae3417d5f7d6f95c
13,151,189,909,866
e45495d795d866d33da6c1ac69e83d2ff61eb4a3
/ScriptExplorer/src/org/carnegiesciencecenter/buhl/SlewProjector.java
c36e16c362f311294b06bd5585f0629cacb4f47e
[]
no_license
letrianh/S2DS
https://github.com/letrianh/S2DS
84c420a2a4d1b29faf3e6be7c58380da54e5bb4a
a4123142af4df4a2498ee06e9c7095d1443ba5cd
refs/heads/master
2020-06-26T21:10:04.487000
2012-04-24T03:16:52
2012-04-24T03:16:52
3,358,103
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.carnegiesciencecenter.buhl; import java.util.ArrayList; public class SlewProjector extends SlideProjector { Motor zoomMotor; Slew xSlew, ySlew; SlewProjector(String name, String ch, ArrayList<DeviceStatus> l, int max) { super(name, ch, l, max); type = DeviceTypes.SLEW_PROJECTOR; zoomMotor = null; xSlew = null; ySlew = null; } SlewProjector(String name, String ch, ArrayList<DeviceStatus> l) { this(name, ch, l, DEFAULT_MAX_NUM); } public void updateViewPosition() { setViewPosition(xSlew.getValue(), ySlew.getValue(), 0, zoomMotor.getWidth(), zoomMotor.getHeight()); } public void repaint(int t0, int T) { updateViewPosition(); getStatus().atTime = t0; DeviceManager.equivCmds.add(DsCmd.cmdLocate(getStatus().clockId, getStatus().atTime, objName(), T, DEFAULT_AZIMUTH, DEFAULT_ELEVATION, DEFAULT_ROTATION, DEFAULT_WIDTH, DEFAULT_HEIGHT)); } public void repaintNaturally(int t0, int T) { updateViewPosition(); getStatus().atTime = t0; DeviceManager.equivCmds.add(DsCmd.cmdLocateNaturally(getStatus().clockId, getStatus().atTime, objName(), T, DEFAULT_AZIMUTH, DEFAULT_ELEVATION, DEFAULT_ROTATION, DEFAULT_WIDTH, DEFAULT_HEIGHT)); } public void setup(Slew x, Slew y, Motor m) { zoomMotor = m; xSlew = x; ySlew = y; x.currentProjector = this; y.currentProjector = this; m.currentProjector = this; x.peerSlew = y; y.peerSlew = x; } }
UTF-8
Java
1,429
java
SlewProjector.java
Java
[]
null
[]
package org.carnegiesciencecenter.buhl; import java.util.ArrayList; public class SlewProjector extends SlideProjector { Motor zoomMotor; Slew xSlew, ySlew; SlewProjector(String name, String ch, ArrayList<DeviceStatus> l, int max) { super(name, ch, l, max); type = DeviceTypes.SLEW_PROJECTOR; zoomMotor = null; xSlew = null; ySlew = null; } SlewProjector(String name, String ch, ArrayList<DeviceStatus> l) { this(name, ch, l, DEFAULT_MAX_NUM); } public void updateViewPosition() { setViewPosition(xSlew.getValue(), ySlew.getValue(), 0, zoomMotor.getWidth(), zoomMotor.getHeight()); } public void repaint(int t0, int T) { updateViewPosition(); getStatus().atTime = t0; DeviceManager.equivCmds.add(DsCmd.cmdLocate(getStatus().clockId, getStatus().atTime, objName(), T, DEFAULT_AZIMUTH, DEFAULT_ELEVATION, DEFAULT_ROTATION, DEFAULT_WIDTH, DEFAULT_HEIGHT)); } public void repaintNaturally(int t0, int T) { updateViewPosition(); getStatus().atTime = t0; DeviceManager.equivCmds.add(DsCmd.cmdLocateNaturally(getStatus().clockId, getStatus().atTime, objName(), T, DEFAULT_AZIMUTH, DEFAULT_ELEVATION, DEFAULT_ROTATION, DEFAULT_WIDTH, DEFAULT_HEIGHT)); } public void setup(Slew x, Slew y, Motor m) { zoomMotor = m; xSlew = x; ySlew = y; x.currentProjector = this; y.currentProjector = this; m.currentProjector = this; x.peerSlew = y; y.peerSlew = x; } }
1,429
0.712386
0.708887
52
26.48077
27.822577
110
false
false
0
0
0
0
0
0
2.557692
false
false
10
bd7cddea15f322e30d81f0609ed4dc18ef0bd608
13,219,909,383,976
e0fd595a98ca7a23ecf90f4c08801bf7e0361bf2
/results_without_immortals/annotated/GnuParser/1/GnuParser.java
b55f6c8bb9dfd7c9a2c066fa6556ca3865edf953
[]
no_license
amchristi/AdFL
https://github.com/amchristi/AdFL
690699a1c3d0d0e84e412b79826aa1b51b572979
40c879e7fe5f87afbf4abc29e442a6e37b1e6541
refs/heads/master
2021-12-15T11:43:07.539000
2019-07-18T05:56:21
2019-07-18T05:56:21
176,834,877
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.apache.commons.cli; import java.util.ArrayList; import java.util.List; import java.io.*; /** * The class GnuParser provides an implementation of the * {@link Parser#flatten(Options, String[], boolean) flatten} method. * * @version $Id: GnuParser.java 1445352 2013-02-12 20:48:19Z tn $ * @deprecated since 1.3, use the {@link DefaultParser} instead */ @Deprecated public class GnuParser extends Parser { /** * This flatten method does so using the following rules: * <ol> * <li>If an {@link Option} exists for the first character of * the <code>arguments</code> entry <b>AND</b> an {@link Option} * does not exist for the whole <code>argument</code> then * add the first character as an option to the processed tokens * list e.g. "-D" and add the rest of the entry to the also.</li> * <li>Otherwise just add the token to the processed tokens list.</li> * </ol> * * @param options The Options to parse the arguments by. * @param arguments The arguments that have to be flattened. * @param stopAtNonOption specifies whether to stop flattening when * a non option has been encountered * @return a String array of the flattened arguments */ @Override protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "93fec767-a480-4b7c-8189-74439af18b2f"); List<String> tokens = new ArrayList<String>(); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "ab16bef6-7b92-4483-aaaa-668f9bea8c43"); boolean eatTheRest = false; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "004af11a-9646-4966-a483-1a3322c80dda"); for (int i = 0; i < arguments.length; i++) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "f1228b22-92bb-46a4-b72f-c124e50288fe"); String arg = arguments[i]; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "93cd7a03-04e2-4dda-8104-1c2086fc5c3d"); if ("--".equals(arg)) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "338e0c10-2452-4117-bd13-a18f95652b8d"); eatTheRest = true; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "e9bebb27-72bd-4821-8317-7ec16c3af30d"); tokens.add("--"); } else if ("-".equals(arg)) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "27202e58-d03e-4524-90fe-540dba20686b"); tokens.add("-"); } else if (arg.startsWith("-")) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "a697fe65-abf5-494b-9e5e-79925d89bb4f"); String opt = Util.stripLeadingHyphens(arg); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "d0dc248a-85c4-4528-afa2-6a88e1bafa47"); if (options.hasOption(opt)) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "c4084bab-dfef-469d-977d-276525482fc2"); tokens.add(arg); } else { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "78c966c8-d4c8-4410-be99-cef4c4e0239e"); if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('=')))) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "3a1c6464-39d9-4b9e-a26a-c2860110d8ae"); tokens.add(arg.substring(0, arg.indexOf('='))); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "14b24b05-de92-4e83-829f-55d7931428cd"); tokens.add(arg.substring(arg.indexOf('=') + 1)); } else if (options.hasOption(arg.substring(0, 2))) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "11be51e1-2e7b-4b1b-853d-b19b157cc194"); tokens.add(arg.substring(0, 2)); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "fdef1933-8cd4-4ff3-aa7e-7cda5a358b23"); tokens.add(arg.substring(2)); } else { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "4e39a1de-e3fd-4598-aa83-e858c5da6118"); eatTheRest = stopAtNonOption; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "632e3812-49ab-45e3-bb2b-a249e529f4fd"); tokens.add(arg); } } } else { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "604733d7-165a-43f9-af47-4b25d281aad1"); tokens.add(arg); } writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "f2546cab-2c4d-4598-8889-9c66ff90f939"); if (eatTheRest) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "3a2c85ff-62bc-468a-936e-7e81edca97ce"); for (i++; i < arguments.length; i++) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "0b49e947-c98d-4c04-8bd5-317e51eb8e6f"); tokens.add(arguments[i]); } } } writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "d96b46fd-0c0c-4b1b-9a00-2b1a2f48e1c3"); return tokens.toArray(new String[tokens.size()]); } public void writeline(String fullFilePath, String text) { try { java.io.File file = new File(fullFilePath); FileWriter fileWriter = new FileWriter(file, true); BufferedWriter output = new BufferedWriter(fileWriter); output.append(text); output.newLine(); output.close(); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
6,420
java
GnuParser.java
Java
[]
null
[]
package org.apache.commons.cli; import java.util.ArrayList; import java.util.List; import java.io.*; /** * The class GnuParser provides an implementation of the * {@link Parser#flatten(Options, String[], boolean) flatten} method. * * @version $Id: GnuParser.java 1445352 2013-02-12 20:48:19Z tn $ * @deprecated since 1.3, use the {@link DefaultParser} instead */ @Deprecated public class GnuParser extends Parser { /** * This flatten method does so using the following rules: * <ol> * <li>If an {@link Option} exists for the first character of * the <code>arguments</code> entry <b>AND</b> an {@link Option} * does not exist for the whole <code>argument</code> then * add the first character as an option to the processed tokens * list e.g. "-D" and add the rest of the entry to the also.</li> * <li>Otherwise just add the token to the processed tokens list.</li> * </ol> * * @param options The Options to parse the arguments by. * @param arguments The arguments that have to be flattened. * @param stopAtNonOption specifies whether to stop flattening when * a non option has been encountered * @return a String array of the flattened arguments */ @Override protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "93fec767-a480-4b7c-8189-74439af18b2f"); List<String> tokens = new ArrayList<String>(); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "ab16bef6-7b92-4483-aaaa-668f9bea8c43"); boolean eatTheRest = false; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "004af11a-9646-4966-a483-1a3322c80dda"); for (int i = 0; i < arguments.length; i++) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "f1228b22-92bb-46a4-b72f-c124e50288fe"); String arg = arguments[i]; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "93cd7a03-04e2-4dda-8104-1c2086fc5c3d"); if ("--".equals(arg)) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "338e0c10-2452-4117-bd13-a18f95652b8d"); eatTheRest = true; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "e9bebb27-72bd-4821-8317-7ec16c3af30d"); tokens.add("--"); } else if ("-".equals(arg)) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "27202e58-d03e-4524-90fe-540dba20686b"); tokens.add("-"); } else if (arg.startsWith("-")) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "a697fe65-abf5-494b-9e5e-79925d89bb4f"); String opt = Util.stripLeadingHyphens(arg); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "d0dc248a-85c4-4528-afa2-6a88e1bafa47"); if (options.hasOption(opt)) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "c4084bab-dfef-469d-977d-276525482fc2"); tokens.add(arg); } else { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "78c966c8-d4c8-4410-be99-cef4c4e0239e"); if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('=')))) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "3a1c6464-39d9-4b9e-a26a-c2860110d8ae"); tokens.add(arg.substring(0, arg.indexOf('='))); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "14b24b05-de92-4e83-829f-55d7931428cd"); tokens.add(arg.substring(arg.indexOf('=') + 1)); } else if (options.hasOption(arg.substring(0, 2))) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "11be51e1-2e7b-4b1b-853d-b19b157cc194"); tokens.add(arg.substring(0, 2)); writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "fdef1933-8cd4-4ff3-aa7e-7cda5a358b23"); tokens.add(arg.substring(2)); } else { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "4e39a1de-e3fd-4598-aa83-e858c5da6118"); eatTheRest = stopAtNonOption; writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "632e3812-49ab-45e3-bb2b-a249e529f4fd"); tokens.add(arg); } } } else { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "604733d7-165a-43f9-af47-4b25d281aad1"); tokens.add(arg); } writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "f2546cab-2c4d-4598-8889-9c66ff90f939"); if (eatTheRest) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "3a2c85ff-62bc-468a-936e-7e81edca97ce"); for (i++; i < arguments.length; i++) { writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "0b49e947-c98d-4c04-8bd5-317e51eb8e6f"); tokens.add(arguments[i]); } } } writeline("/home/ubuntu/results/coverage/GnuParser/GnuParser_1_10.coverage", "d96b46fd-0c0c-4b1b-9a00-2b1a2f48e1c3"); return tokens.toArray(new String[tokens.size()]); } public void writeline(String fullFilePath, String text) { try { java.io.File file = new File(fullFilePath); FileWriter fileWriter = new FileWriter(file, true); BufferedWriter output = new BufferedWriter(fileWriter); output.append(text); output.newLine(); output.close(); } catch (IOException e) { e.printStackTrace(); } } }
6,420
0.615265
0.527103
108
58.444443
45.212326
141
false
false
0
0
0
0
0
0
0.824074
false
false
10
d81b412c271dc55e5bee7fad411e01591cb7279d
15,195,594,345,637
c68c5720e52c4c8315496218a689e066b527d594
/testJava/src/java200/to100/in99/n093/StringMethodMain1.java
826fb4e9fdd422dfd33a5d1981810176015c659c
[]
no_license
s-jinipark/first
https://github.com/s-jinipark/first
0941ca45a6483b9dbdb24ebb04271283b87294fc
2aec08afe3e233ee394e09e3fb2dc74e2e6d482d
refs/heads/master
2021-06-17T01:13:18.326000
2019-05-21T03:24:15
2019-05-21T03:24:15
111,877,617
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package java200.to100.in99.n093; public class StringMethodMain1 { // 093 String 이해하기 public static void main(String[] args) { // TODO Auto-generated method stub // 1. String immutable String st = "hello"; System.out.println(st+st.hashCode()); st.replace('h', 'H'); System.out.println(st+st.hashCode()); st = st.replace('h', 'H'); System.out.println(st+st.hashCode()); // * hashCode 변경 // 2. String 의 위치 메서드 인덱스는 0 부터 String test1 = "Hello my nick name is totoro.\n"; test1 += "I'm 29 years old.\n"; test1 += "I'm a good boy."; System.out.println("이 글의 길이 : " + test1.length() ); // 문자열의 길이를 구하는 메서드 System.out.println("첫번째 . 위치 : " + test1.indexOf('.') ); // 문자열이 있는 위치, 자리는 0부터 시작 System.out.println("마지막 . 위치 : " + test1.lastIndexOf('.') ); System.out.println("첫번째 years 위치 : " + test1.indexOf("years") ); // 3. 위치에 있는 한글자씩 부르기 for (int i=0; i<test1.length(); i++) { System.out.println(test1.charAt(i) ); } // 4. 원하는 문자열 배열 String[] a = test1.split("\n"); System.out.println(a.length); System.out.println(a[0]); // 5. 문자열 나누기. index 는 0부터 시작한다 String b = test1.substring(4,8); String c = test1.substring(0,5); String bb = test1.substring(4); System.out.println(b); System.out.println(c); System.out.println(bb); } }
UHC
Java
1,501
java
StringMethodMain1.java
Java
[ { "context": " 인덱스는 0 부터\n\t\tString test1 = \"Hello my nick name is totoro.\\n\";\n\t\t\ttest1 += \"I'm 29 years old.\\n\";\n\t\t\tt", "end": 483, "score": 0.768887996673584, "start": 482, "tag": "USERNAME", "value": "t" }, { "context": "덱스는 0 부터\n\t\tString test1 = \"Hello my nick name is totoro.\\n\";\n\t\t\ttest1 += \"I'm 29 years old.\\n\";\n\t\t\ttest1 ", "end": 488, "score": 0.8554890155792236, "start": 483, "tag": "NAME", "value": "otoro" } ]
null
[]
package java200.to100.in99.n093; public class StringMethodMain1 { // 093 String 이해하기 public static void main(String[] args) { // TODO Auto-generated method stub // 1. String immutable String st = "hello"; System.out.println(st+st.hashCode()); st.replace('h', 'H'); System.out.println(st+st.hashCode()); st = st.replace('h', 'H'); System.out.println(st+st.hashCode()); // * hashCode 변경 // 2. String 의 위치 메서드 인덱스는 0 부터 String test1 = "Hello my nick name is totoro.\n"; test1 += "I'm 29 years old.\n"; test1 += "I'm a good boy."; System.out.println("이 글의 길이 : " + test1.length() ); // 문자열의 길이를 구하는 메서드 System.out.println("첫번째 . 위치 : " + test1.indexOf('.') ); // 문자열이 있는 위치, 자리는 0부터 시작 System.out.println("마지막 . 위치 : " + test1.lastIndexOf('.') ); System.out.println("첫번째 years 위치 : " + test1.indexOf("years") ); // 3. 위치에 있는 한글자씩 부르기 for (int i=0; i<test1.length(); i++) { System.out.println(test1.charAt(i) ); } // 4. 원하는 문자열 배열 String[] a = test1.split("\n"); System.out.println(a.length); System.out.println(a[0]); // 5. 문자열 나누기. index 는 0부터 시작한다 String b = test1.substring(4,8); String c = test1.substring(0,5); String bb = test1.substring(4); System.out.println(b); System.out.println(c); System.out.println(bb); } }
1,501
0.617805
0.583269
43
29.302326
19.746693
84
false
false
0
0
0
0
0
0
2.55814
false
false
10
3634f92872e2fab0939ec39c0cf57e4da409d073
8,126,078,185,266
f8f596b433f6796d9961074bfcf5ec71cee11484
/java-orders/src/main/java/com/lambdaschool/javaorders/services/AgentServicesImpl.java
ebae0b2024b20ecfecf9a21dfcd4917b240f4507
[ "MIT" ]
permissive
aldenho52/java-crudyorders
https://github.com/aldenho52/java-crudyorders
84fb0056fd3adb33d4f0f59421929d6f605fa5d8
0cc46d144f2d66a544da746cb67791fe2336a81d
refs/heads/master
2023-01-24T23:22:49.338000
2020-12-09T21:58:58
2020-12-09T21:58:58
320,046,730
0
0
MIT
true
2020-12-09T21:58:59
2020-12-09T18:37:05
2020-12-09T18:52:34
2020-12-09T21:58:58
504
0
0
0
Java
false
false
package com.lambdaschool.javaorders.services; import com.lambdaschool.javaorders.models.Agent; import com.lambdaschool.javaorders.repositories.AgentsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.EntityNotFoundException; import javax.transaction.Transactional; @Transactional @Service(value = "agentservices") public class AgentServicesImpl implements AgentServices { @Autowired private AgentsRepository agentsRepository; @Override public Agent findById(long id) { Agent a = agentsRepository.findById(id) .orElseThrow(() -> new EntityNotFoundException("Restaurant " + id + " Not Found!")); return a; } @Transactional @Override public Agent save(Agent agent) { return agentsRepository.save(agent); } }
UTF-8
Java
883
java
AgentServicesImpl.java
Java
[]
null
[]
package com.lambdaschool.javaorders.services; import com.lambdaschool.javaorders.models.Agent; import com.lambdaschool.javaorders.repositories.AgentsRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.EntityNotFoundException; import javax.transaction.Transactional; @Transactional @Service(value = "agentservices") public class AgentServicesImpl implements AgentServices { @Autowired private AgentsRepository agentsRepository; @Override public Agent findById(long id) { Agent a = agentsRepository.findById(id) .orElseThrow(() -> new EntityNotFoundException("Restaurant " + id + " Not Found!")); return a; } @Transactional @Override public Agent save(Agent agent) { return agentsRepository.save(agent); } }
883
0.747452
0.747452
32
26.59375
24.538057
96
false
false
0
0
0
0
0
0
0.34375
false
false
10
ca9c1e1caa21d341cd0e37226479ad9dc158152b
35,003,983,501,455
5e517335642aee98b640e842ac05ea505246bf91
/javagrpc/src/main/java/com/syscho/grpc/server/GRPCServer.java
ee7da9b1aca91702240950f3f2b0b104f79076b6
[]
no_license
ps1437/java-grpc
https://github.com/ps1437/java-grpc
4bf6af06ea8736a3b820eb544e58c51b88aa5798
dbb1788872f3ebb2ef446cf69ebafe967b3614a4
refs/heads/master
2023-06-03T08:48:20.044000
2021-06-22T07:36:39
2021-06-22T07:36:39
378,360,044
0
0
null
false
2021-06-21T04:34:21
2021-06-19T08:15:12
2021-06-19T08:18:05
2021-06-21T04:34:21
22
0
0
0
Java
false
false
package com.syscho.grpc.server; import com.syscho.grpc.exception.ExceptionHandler; import com.syscho.grpc.service.ProductAdaptor; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.IOException; public class GRPCServer { public static final int PORT = 9091; public static void main(String args[]) throws IOException, InterruptedException { Server server = ServerBuilder.forPort(PORT) .addService(new ProductAdaptor()) .intercept(new ExceptionHandler()) .build(); server.start(); System.out.println("Server started on " + server.getPort()); server.awaitTermination(); } }
UTF-8
Java
688
java
GRPCServer.java
Java
[]
null
[]
package com.syscho.grpc.server; import com.syscho.grpc.exception.ExceptionHandler; import com.syscho.grpc.service.ProductAdaptor; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.IOException; public class GRPCServer { public static final int PORT = 9091; public static void main(String args[]) throws IOException, InterruptedException { Server server = ServerBuilder.forPort(PORT) .addService(new ProductAdaptor()) .intercept(new ExceptionHandler()) .build(); server.start(); System.out.println("Server started on " + server.getPort()); server.awaitTermination(); } }
688
0.675872
0.670058
28
23.607143
23.858721
85
false
false
0
0
0
0
0
0
0.428571
false
false
10
2654c5774383292bcdffa95b94deee221227f342
17,884,243,886,783
471d6ab365acafeb22278dbe341c1b9eea930ce9
/src/sstart/AGHello.java
b8eb9daceb2e9f64d860333f1305835a4d1f2e96
[]
no_license
Drlilou/dmandrak-wumpus
https://github.com/Drlilou/dmandrak-wumpus
e02509ae43c0724939998845f5f6cc27b7e001d0
f189f997ceddcbdbe504fc63b6a034d98cc1a578
refs/heads/master
2018-01-08T00:15:50.772000
2010-02-01T08:51:13
2010-02-01T08:51:13
43,419,460
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sstart; import jade.core.Agent; import jade.domain.DFService; import jade.domain.FIPAAgentManagement.*; import jade.domain.FIPAException; public class AGHello extends Agent { private static final long serialVersionUID = 1L; // Please eclipse, do not complain protected void setup() { System.out.println("Hello World! My name is "+getLocalName()); /** Registration with the DF */ DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("HelloWorldAgent"); sd.setName(getName()); dfd.addServices(sd); dfd.setName(getAID()); try { DFService.register(this,dfd); } catch (FIPAException e) { System.err.println(getLocalName()+" registration with DF unsucceeded. Reason: "+e.getMessage()); doDelete(); } /** End registration with the DF **/ System.out.println(getLocalName()+ " succeeded in registration with DF"); //ADD Behavior // Make this agent terminate //doDelete(); } }
UTF-8
Java
1,038
java
AGHello.java
Java
[]
null
[]
package sstart; import jade.core.Agent; import jade.domain.DFService; import jade.domain.FIPAAgentManagement.*; import jade.domain.FIPAException; public class AGHello extends Agent { private static final long serialVersionUID = 1L; // Please eclipse, do not complain protected void setup() { System.out.println("Hello World! My name is "+getLocalName()); /** Registration with the DF */ DFAgentDescription dfd = new DFAgentDescription(); ServiceDescription sd = new ServiceDescription(); sd.setType("HelloWorldAgent"); sd.setName(getName()); dfd.addServices(sd); dfd.setName(getAID()); try { DFService.register(this,dfd); } catch (FIPAException e) { System.err.println(getLocalName()+" registration with DF unsucceeded. Reason: "+e.getMessage()); doDelete(); } /** End registration with the DF **/ System.out.println(getLocalName()+ " succeeded in registration with DF"); //ADD Behavior // Make this agent terminate //doDelete(); } }
1,038
0.681118
0.680154
37
27.054054
25.292822
102
false
false
0
0
0
0
0
0
0.72973
false
false
10
357853dd778a660a8d5f0907df6a503559a0dfa0
17,884,243,887,071
b44bb8026e769f089f1129a64a86581fed097d9e
/de.parkand.hardware/src/main/java/de/parkand/hardware/pin/io/WritePinException.java
98c594809fe27ea7375a1547990dec958fba756e
[]
no_license
IngoReimund/cfs
https://github.com/IngoReimund/cfs
162763ffea25da2ed39a81f1b7165cd70840819e
e62617e3d1919046a75416371f919bdce8cc27a1
refs/heads/master
2016-09-09T15:26:44.810000
2014-12-24T01:52:46
2014-12-24T02:02:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.parkand.hardware.pin.io; public class WritePinException extends RuntimeException { private static final long serialVersionUID = 2409713487109117481L; public WritePinException(String message) { super(message); } }
UTF-8
Java
233
java
WritePinException.java
Java
[]
null
[]
package de.parkand.hardware.pin.io; public class WritePinException extends RuntimeException { private static final long serialVersionUID = 2409713487109117481L; public WritePinException(String message) { super(message); } }
233
0.798283
0.716738
11
20.181818
24.542423
67
false
false
0
0
0
0
0
0
0.727273
false
false
10
918c0fcd0de345497e2a48e292513f57853574d7
17,884,243,888,753
450e7783a0b1cc7dd7c5387f05a23b5811b0bcbb
/assisPoor/src/main/java/com/ai/ui/assispoor/reportforms/ActivityExcel.java
5f2b80d158a0ef5195c2ba435856d687f223c79d
[]
no_license
MrCarlosYang/AssisPoor
https://github.com/MrCarlosYang/AssisPoor
216fde6344f566d24c1b8b0cd51acb24c5719177
64aa27327129cb10dbba14aae4851070a1efbc26
refs/heads/master
2017-12-27T02:42:54.917000
2016-10-30T10:43:00
2016-10-30T10:43:00
72,343,270
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ai.ui.assispoor.reportforms; import android.app.AlertDialog.Builder; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnKeyListener; import android.content.res.Configuration; import android.os.Bundle; import android.text.TextUtils; import android.view.Display; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.DatePicker; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.ai.assispoor.R; import com.ai.ui.comm.CustomProgressDialog; import com.ai.utils.ToastUtil; import com.ai.view.dialog.DialogNumberPicker; import com.ailk.data.ChartItemHead; import com.ailk.data.excel.Cell; import com.ailk.data.excel.CellData; import com.ailk.data.excel.CellHeader; import com.ailk.data.excel.DataReportTable; import com.ailk.data.itsurport.Constant; import com.ailk.data.itsurport.ImgTable; import com.ailk.data.json.DrillURL; import com.ailk.data.json.ReportReq; import com.ailk.event.excel.CellEventListner; import com.ailk.event.excel.ScrollEventListner; import com.ailk.main.SuperBaseActivity; import com.ailk.task.GenericTask; import com.ailk.task.TaskListener; import com.ailk.task.TaskParams; import com.ailk.task.itsurport.TaskExcel; import com.ailk.tools.security.Base64; import com.ailk.tools.security.DESUtils; import com.ailk.tools.utils.TextHelper; import com.ailk.tools.utils.ToolsUtils; import com.ailk.view.excel.ViewExcel_AILK; import com.google.gson.Gson; import java.io.StringReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.Vector; import butterknife.Bind; import butterknife.ButterKnife; /** * @author MrJing * @ClassName: ActivityExcel * @Description: 表格数据 * @date 2012-3-2 下午9:41:05 */ public class ActivityExcel extends SuperBaseActivity implements CellEventListner, ScrollEventListner { @Bind(R.id.page_no) TextView pageNo; @Bind(R.id.page_up) TextView pageUp; @Bind(R.id.page_down) TextView pageDown; @Bind(R.id.tv_total) TextView tvTotal; /** * */ private ViewExcel_AILK viewExcel; private String titleName[]; /** * 列标题名字的解释 */ private String titleExplain[]; /** * 存储json 串,用于上钻,下钻,日期变更 */ private Vector<String> stackJson = new Vector<String>(); /** * 存储网格名字 */ private Vector<String> stackName = new Vector<String>(); /** * 顶部状态栏 */ private LinearLayout topTitle_LinearLayout; /** * 底部状态栏 */ private LinearLayout bottom_LinearLayout; /** * 维度上钻 */ private Button parentButton; /** * 刷新按钮 */ private Button btn_fresh; /** * 没有必要重新初始化界面 */ public boolean isNotInit; /** * 返回首页 */ private ImageButton homeButton; /** * 发邮件按钮 */ private ImageButton mailButton; /** * 按日查询按钮 */ private ImageButton selectTimeButton; private TextView ChartNameTitle; private TextView ChartTime; /** * 关联表 */ private Button button_childChart; /** * 图表的控制按钮 */ private ImageButton button_chart_img; /** * 控制 表格数据和表图 之间的切换 变量 */ private boolean isShowChartImage = false; /** * 正在展示的表头 */ public ChartItemHead aChartItemHead; /** * 后一天 */ private ImageButton nextButton; /** * 前一日按钮 */ private ImageButton preButton; private CustomProgressDialog nProgressDialog; private int pageNoNow = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); nProgressDialog = CustomProgressDialog.createDialog(context); nProgressDialog.setCancelable(true); nProgressDialog.setCanceledOnTouchOutside(false); this.aChartItemHead = businessHandler.aChartItemHead; aChartItemHead.reportcycle = "d"; stackJson.add(aChartItemHead.url); stackName.add("第一层"); loadData(); } /** * 判断是否为移网实时发展量的报表 */ private boolean checkIsYWSSFZL() { String tmpChartName = ((TextView) findViewById(R.id.ChartName)).getText().toString(); if (tmpChartName.equals("移网实时发展量")) { return true; } else { return false; } } /** * @param * @return void 返回类型 * @throws * @Title: init * @Description: 初始化 类文件 * @author MrJing * @date 2012-3-4 上午1:19:19 */ public void init() { setContentView(R.layout.excel); ButterKnife.bind(this); viewExcel = (ViewExcel_AILK) findViewById(R.id.myExcel); viewExcel.setOnClickCellEventListner(this); viewExcel.setOnScrollEventListner(this); ChartNameTitle = (TextView) findViewById(R.id.ChartNameTitle); ChartTime = (TextView) findViewById(R.id.ChartTime); /** * 顶部 状态栏 */ topTitle_LinearLayout = (LinearLayout) findViewById(R.id.TopTitle_LinearLayout); /** * 底部 状态栏 */ bottom_LinearLayout = (LinearLayout) findViewById(R.id.Bottom_LinearLayout); // 子报表按钮 button_childChart = (Button) findViewById(R.id.button_child_chart); // 控制子报表的切换 button_childChart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (checkIsYWSSFZL()) { colclass_operate_fun(); return; } if (!isShowChartImage) { showDialog(DIALOG_CHART); } else { if (aChartItemHead.aList_chart_graphics != null && aChartItemHead.aList_chart_graphics.size() > 1) { // 图表 大于一个的时候 showDialog(DIALOG_CHART_IMG); } } } }); /** * 数据表格 */ // relativeLayout = (RelativeLayout) // findViewById(R.id.RelativeLayout01_excel); // 初始化浏览器 mWebView = (WebView) findViewById(R.id.show_webv); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setPluginState(WebSettings.PluginState.ON); // mWebView.getSettings().setSupportZoom(true); mWebView.getSettings().setBuiltInZoomControls(true); /** * 图表 */ button_chart_img = (ImageButton) findViewById(R.id.button_chart_img); /** * 图表切换按钮 */ button_chart_img.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { isShowChartImage = !isShowChartImage; // if(!isShowChartImage) // { // // mWebView.setVisibility(View.GONE); // relativeLayout.setVisibility(View.VISIBLE); // }else{ // // webView(); // relativeLayout.setVisibility(View.GONE); // mWebView.setVisibility(View.VISIBLE); // } // 重新初始化和加载数据 loadData(); } }); // no understand configurationChanged(getResources().getConfiguration()); // 发邮件 mailButton = (ImageButton) findViewById(R.id.button_send_mail); mailButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // // log("seend mail"); String tableName = aChartItemHead.reportName; ToolsUtils.takeScreenShotToEmail(ActivityExcel.this, ActivityExcel.this, tableName); } }); homeButton = (ImageButton) findViewById(R.id.button_home); homeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Intent intent = new Intent(); // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // intent.setClass(ExcelActivity.this, CatalogActivity.class); // 暂时没有使用此方法 startActivity finish(); clearData(); } }); // 时间查询 selectTimeButton = (ImageButton) findViewById(R.id.button_select_time); selectTimeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // log("time time time!"); showDialog(0); } }); // 前一天 preButton = (ImageButton) findViewById(R.id.button_left); preButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //此方法会导致崩溃,暂时未用到 // try { dateChange(-1); // }catch (Exception e){ // e.printStackTrace(); // } } }); // 后一天 nextButton = (ImageButton) findViewById(R.id.button_right); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //此方法会导致崩溃,暂时未用到 // try { dateChange(1); // }catch (Exception e){ // e.printStackTrace(); // } } }); parentButton = (Button) findViewById(R.id.ParentButton); parentButton.setEnabled(true); /** * 上钻按钮 */ parentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 弹出返回列表 if (stackJson.size() > 1) { // if(stackJson.size()) // aChartItemHead.url = stackJson.pop(); // dimensionChange(aChartItemHead, null); if (stackJson.size() == 2) { // 上钻 aChartItemHead.url = stackJson.get(0); stackName.remove(1); stackJson.remove(1); dimensionChange(aChartItemHead, null); } else { showReturnDialog(); } } else { finish(); clearData(); } } }); btn_fresh = (Button) findViewById(R.id.button_refresh); btn_fresh.setEnabled(true); /** * 上钻按钮 */ btn_fresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doTaskExcel(); // dimensionChange(aChartItemHead, null); } }); } protected void dimensionChange(ChartItemHead aChartItemHead2, Object object) { pageNoNow = 1; aChartItemHead.pageNo = "" + pageNoNow; doTaskExcel(); } /** * @param @param i 设定文件 * @return void 返回类型 * @throws * @Title: dateChange * @Description: 日期切换 * @author MrJing * @date 2012-3-14 下午7:19:52 */ private void dateChange(int direction) { String date = null; int d = 0; int m = 0; int y = 0; if (direction == 1) { // 更改日期 if (aChartItemHead.reportcycle.toLowerCase().equals("m")) { d = 0; m = 1; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("d")) { // aChartItemHead._day +=1; d = 1; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("w")) { // aChartItemHead._day +=1; d = 7; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("q")) { // aChartItemHead._day +=1; d = 0; m = 3; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("y")) { // aChartItemHead._day +=1; d = 0; m = 0; y = 1; } // date = aChartItemHead.chartNextTime; } else if (direction == -1) { // // date = aChartItemHead.chartPreTime; if (aChartItemHead.reportcycle.toLowerCase().equals("m")) { d = 0; m = -1; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("d")) { // aChartItemHead._day +=1; d = -1; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("w")) { // aChartItemHead._day +=1; d = -7; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("q")) { // aChartItemHead._day +=1; d = 0; m = -3; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("y")) { // aChartItemHead._day +=1; d = 0; m = 0; y = -1; } } aChartItemHead.cDate.set(Calendar.DATE, aChartItemHead.cDate.get(Calendar.DATE) + d); // 前一天( // 减1) aChartItemHead.cDate.set(Calendar.MONTH, aChartItemHead.cDate.get(Calendar.MONTH) + m); aChartItemHead.cDate.set(Calendar.YEAR, aChartItemHead.cDate.get(Calendar.YEAR) + y); aChartItemHead._year = aChartItemHead.cDate.get(Calendar.YEAR); aChartItemHead._month = aChartItemHead.cDate.get(Calendar.MONTH) + 1; aChartItemHead._day = aChartItemHead.cDate.get(Calendar.DATE); date = "" + aChartItemHead._year; if (aChartItemHead._month < 10) { date += "0" + aChartItemHead._month; } else { date += "" + aChartItemHead._month; } if (aChartItemHead._day < 10) { date += "0" + aChartItemHead._day; } else { date += aChartItemHead._day; } // date = // ""+aChartItemHead._year+aChartItemHead._month+aChartItemHead._day; // log("date==" + date); aChartItemHead.date = date; // log("dateChange::" + aChartItemHead.chartNextTime + "::" // + aChartItemHead.chartEndTime + "::" + date); if (date != null) { doTaskExcel(); } } /** * 返回对话框 */ public void showReturnDialog() { Dialog dialog = null; final String[] namesTable = new String[stackJson.size()]; final String[] valueTable = new String[stackJson.size()]; // 获取内容 for (int i = 0; i < stackJson.size(); i++) { namesTable[i] = stackName.elementAt(i); valueTable[i] = stackJson.elementAt(i); } builder = new Builder(this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("请选择"); selectChartId = namesTable.length - 1; // 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(namesTable, selectChartId, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { selectChartId = which; } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // log("=selectId==============" + selectChartId); if (selectChartId < valueTable.length - 1) { // 不只是对url替换还需要解密,对aChartItemHead其他属 aChartItemHead.url = valueTable[selectChartId]; // 复原 // fromUrlJson("", aChartItemHead); for (int i = selectChartId + 1; i < namesTable.length; i++) { // log("=selectId===i===========" + i // + ",stackJson=" + stackJson.size()); stackJson.remove(valueTable[i]); stackName.remove(namesTable[i]); } dimensionChange(aChartItemHead, null); } selectChartId = 0; } }); // 创建一个单选按钮对话框 dialog = builder.create(); dialog.show(); } private OnCancelListener cc = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // } }; /** * 获取报表任务监听器 */ TaskListener iTaskListenerExcel = new TaskListener() { @Override public void onPreExecute(final GenericTask task) { dismissAllDialogs(); nProgressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { task.cancel(true); stackName.remove(stackName.size() - 1); stackJson.remove(stackJson.size() - 1); } }); nProgressDialog.show(); // dismissAllDialogs(); // showProgressDialog("获取报表", " 正在连接服务器...", ProgressDialog.STYLE_HORIZONTAL, false, cc); } @Override public void onPostExecute(GenericTask task, String result) { // nProgressDialog.dismiss(); dismissAllDialogs(); if (result.equals(Constant.rspCode_OK)) { loadData(); } else { // // 失败 (重新尝试登录) // // 是 按钮 // DialogInterface.OnClickListener onYesClickListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // businessHandler.userConfig.mIMSI="460015910647328"; // // doLogin(); // doTaskExcel(); // } // }; // // 否按钮 // DialogInterface.OnClickListener onNoClickListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // } // }; // String msg = getErrorMessage(result); // showYesNoAlertDialog("信息提示", msg, "重试", "取消", onYesClickListener, // onNoClickListener); ToastUtil.show("获取数据失败,请重试"); } } @Override public void onProgressUpdate(GenericTask task, Object... values) { // super.onProgressUpdate(task, values); // int total = (Integer) values[0]; // int current = (Integer) values[1]; // showUpdateProgress(total, current); // if (current > 0) { // // 设置的次数过多,效率不高 // setProgressDialogMessage("正在下载数据..."); // } // if (total > 0 && total == current) { // setProgressDialogMessage("正在解析数据..."); // } } @Override public void onCancelled(GenericTask task) { // } @Override public String getName() { // return "doTaskExcel"; } }; // private RelativeLayout relativeLayout; public void doTaskExcel() { TaskExcel taskExcel = new TaskExcel(this); taskExcel.setListener(iTaskListenerExcel); TaskParams params = new TaskParams(); // 对 url进行处理,比如翻页等信息处理 // businessHandler.aChartItemHead.url; if (businessHandler.aChartItemHead == null || businessHandler.aChartItemHead.url == null || businessHandler.aChartItemHead.url.equals("")) { showToast("报表不存在"); return; } params.put("First", false); taskExcel.execute(params); } /** * @param * @return void 返回类型 * @throws * @Title: reload * @Description: 加载数据 * @author MrJing * @date 2012-3-4 上午1:18:48 */ public void loadData() { this.aChartItemHead = businessHandler.aChartItemHead; if (this.aChartItemHead == null) { return; } if (!isNotInit) { init(); } else { isNotInit = false; } DialogInterface.OnClickListener onOkClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }; // handleViewLoadPage(); // handleLoadViewTopMenu(); // handleLoadViewRealTimeChart(); // handleLoadViewChartImage(); if (businessHandler.dataReport == null || businessHandler.dataReport.getList_tableHeaders() == null || businessHandler.dataReport.getList_tableHeaders().size() <= 0 || businessHandler.dataReport.getList_reportData() == null || businessHandler.dataReport.getList_reportData().size() <= 0) { viewExcel.clear(); showOkAlertDialog("信息提示", "对不起,当前没有数据!", onOkClickListener); // return ; } handleViewLoadPage(); if (pageNoNow > 1) { pageUp.setVisibility(View.VISIBLE); pageUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pageChange(--pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } }); } else { pageUp.setVisibility(View.INVISIBLE); pageUp.setOnClickListener(null); } if (pageNoNow < totalNoPage) { pageDown.setVisibility(View.VISIBLE); pageDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pageChange(++pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } }); } else { pageDown.setVisibility(View.INVISIBLE); pageDown.setOnClickListener(null); } SimpleDateFormat oldformat = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat newformat = new SimpleDateFormat("yyyy年MM月dd日"); if (businessHandler.dataReport != null) { if (!TextUtils.isEmpty(businessHandler.dataReport.reportTitle)) { ChartNameTitle.setText(businessHandler.dataReport.reportTitle); ChartTime.setText(""); try { ChartTime.setText(newformat.format(oldformat.parse(businessHandler.dataReport.reportTime))); } catch (ParseException e) { e.printStackTrace(); } tvTotal.setText("共"+businessHandler.dataReport.totalCnt+"条"); } else { ChartNameTitle.setText("报表"); ChartTime.setText(""); } pageNo.setText("第" + pageNoNow + "页"); if (totalNoPage>1) { pageNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { final DialogNumberPicker dialogNumberPicker=new DialogNumberPicker(context,"跳转到",pageNoNow,totalNoPage); dialogNumberPicker.setOnLeftClick(new OnClickListener() { @Override public void onClick(View view) { pageNoNow=Integer.valueOf(dialogNumberPicker.getPageNo()); pageChange(pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); dialogNumberPicker.dismiss(); } }); dialogNumberPicker.show(); } }); } else { pageNo.setOnClickListener(null); // pageNo.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // final DialogNumberPicker dialogNumberPicker=new DialogNumberPicker(context,"跳转到",pageNoNow,300); // dialogNumberPicker.setOnLeftClick(new OnClickListener() { // @Override // public void onClick(View view) { // pageNoNow=dialogNumberPicker.getPageNo(); // pageChange(pageNoNow); // showToast(pageNoNow + "/" + totalNoPage + "页"); // dialogNumberPicker.dismiss(); // } // }); // dialogNumberPicker.show(); // } // }); } fillData(businessHandler.dataReport); } else { showToast("报表数据为空"); } } /** * 关于加载翻页的处理 */ private void handleViewLoadPage() { // 关于翻页 int t = 0; totalNoPage = 1; try { t = Integer.parseInt(aChartItemHead.totalCnt); } catch (Exception e) { } if (t > Integer.parseInt(Constant.pageMaxLine)) { /** * 计算页码 */ int maxLine = Integer.parseInt(Constant.pageMaxLine); if (t % maxLine == 0) { totalNoPage = t / maxLine; } else { totalNoPage = t / maxLine + 1; } } } private void clearData() { this.aChartItemHead = null; businessHandler.aChartItemHead = null; businessHandler.aChartType = null; businessHandler.dataReport = null; viewExcel = null; System.gc(); } /** * @param pageNo * @Description: 翻页 * @author jingwen * @date 2011-9-15 下午8:55:38 */ private void pageChange(int pageNo) { // String pageNoShow = pageNo + "/" + totalNoPage; // log("pageNoShow===" + pageNoShow); // page_tv.setText(pageNoShow); aChartItemHead.pageNo = "" + pageNo; doTaskExcel(); } /** * 关于加载实时报表界面 */ private void handleLoadViewRealTimeChart() { /** * 关于刷新按钮 根据列表中得切换周期值R来确定是否屏蔽前一天,后一天,日期查询按钮 */ /*if (aChartItemHead.reportcycle.toLowerCase().equals("r") || !TextHelper.isEmpty(aChartItemHead.queryType)) { preButton.setBackgroundResource(R.drawable.icon_arrow_leftno); preButton.setEnabled(false); nextButton.setBackgroundResource(R.drawable.icon_arrow_rightno); nextButton.setEnabled(false); selectTimeButton.setBackgroundResource(R.drawable.icon_timeno); selectTimeButton.setEnabled(false); btn_fresh.setVisibility(Button.VISIBLE); } else { btn_fresh.setVisibility(Button.GONE); preButton.setBackgroundResource(R.drawable.arrow_l_bk); preButton.setEnabled(true); nextButton.setBackgroundResource(R.drawable.arrow_r_bk); nextButton.setEnabled(true); selectTimeButton.setBackgroundResource(R.drawable.icon_time_bk); selectTimeButton.setEnabled(true); }*/ } /** * 设置报表上边的 属性 */ private void handleLoadViewTopMenu() { if (businessHandler.aChartType != null && businessHandler.aChartType.chartItemHeads != null && businessHandler.aChartType.chartItemHeads.size() > 1) { button_childChart.setVisibility(View.VISIBLE); } else { button_childChart.setVisibility(View.GONE); } // 报表的日期 // Log.e("xxx", "r"); /*if (!TextHelper.isEmpty(aChartItemHead.date)) { String dt = ToolsUtils.dateFormat(aChartItemHead.date); Log.e("xxxdt", "" + dt); Log.e("xxxr", "" + aChartItemHead.reportcycle); if (dt != null) { if (aChartItemHead.reportcycle.toLowerCase().equals("m")) { // Log.e("xxx", "m"); // 月 dt = dt.substring(0, dt.length() - 3); } else if (aChartItemHead.reportcycle.toLowerCase().equals("r")) { // 实时 // Log.e("xxx", "r"); dt = aChartItemHead.statisticTime; } *//** * 日期 *//* ((TextView) findViewById(R.id.ChartTime)).setText(dt); } } else { // 木有日期的时候,就填写列表的数据 Log.e("xxx", "n"); ((TextView) findViewById(R.id.ChartTime)).setText(businessHandler.aChartType.lastdate); }*/ // 正常日期不做去了 // 维度栈 返回按钮 if (stackJson.size() <= 1) { parentButton.setVisibility(View.GONE); stackJson.clear(); stackName.clear(); //stackJson.add(aChartItemHead.url); stackName.add("第一层"); } else { // 只有一级有子表,其他级没有子表 button_childChart.setVisibility(View.GONE); parentButton.setVisibility(View.VISIBLE); } /** * 设置专题名字 *//* ((TextView) findViewById(R.id.ChartName)).setText(aChartItemHead.chartTypeName); *//** * 设置具体表名字 *//* TextView tv = (TextView) findViewById(R.id.ChartNameTitle); tv.setText(aChartItemHead.reportName);*/ } private void handleLoadViewChartImage() { if (aChartItemHead.aList_chart_graphics == null || aChartItemHead.aList_chart_graphics.size() < 1) { isShowChartImage = false; } /** * 设置报表gif图是否可见 */ if (aChartItemHead.hasImage != null && aChartItemHead.hasImage.equals("1")) { button_chart_img.setVisibility(View.VISIBLE); } else { button_chart_img.setVisibility(View.GONE); } if (isShowChartImage) { // 显示 报表图表 webView(); mWebView.setVisibility(View.VISIBLE); viewExcel.setVisibility(View.GONE); if (aChartItemHead.aList_chart_graphics.size() > 1) { // 报表视图多于一个 button_childChart.setVisibility(View.VISIBLE); } // 是否隐藏刷新按钮 if (btn_fresh.isShown()) { btn_fresh.setVisibility(View.GONE); } // 标题 findViewById(R.id.TopTextTitle_LinearLayout).setVisibility(View.GONE); this.button_chart_img.setBackgroundResource(R.drawable.datatable_bk); } else { // if (!aChartItemHead.hasData) { // // dialogInfo(R.string.all_chart_nochartData, false); // } // 显示报表数据 mWebView.setVisibility(View.GONE); // relativeLayout.setVisibility(View.VISIBLE); viewExcel.setVisibility(View.VISIBLE); findViewById(R.id.TopTextTitle_LinearLayout).setVisibility(View.VISIBLE); this.button_chart_img.setBackgroundResource(R.drawable.imgtable_bk); } } private WebView mWebView; /** * chart view设置报表试图 */ public void webView() { // mWebView.loadUrl("http://wap.sohu.com"); ImgTable item = aChartItemHead.aList_chart_graphics.get(selectChartImageId); String url = item.url; // des解密 url = DESUtils.decrypt(url); String requestJson = DESUtils.decrypt(aChartItemHead.url); // requestJson base64 requestJson = Base64.encode(requestJson.getBytes()); // 替换 url = url.replace("QueryStr&", requestJson + "&"); // url // ="http://130.38.27.143:7711/mapp/bus/chart2nsmp.action?QueryStr=eyJyZXBvcnRJZCI6IjEyNjQiLCJyb3ciOiIiLCJ1c2VySWQiOiIiLCJkaW1WYWx1ZSI6IiIsIndoZXJlIjoiW0pZMTAxMl0gPSAnMzg2JyAgQU5EIFtKWTEwMDhdID0gJzM4NjAwMScgIiwic3RhcnREYXRlIjoiIiwicGFnZVNpemUiOiIzMCIsInBhZ2VhYmxlIjoidHJ1ZSIsIm51bSI6IiIsInVzZXJTdGF0aW9uIjoiIiwiZnJvbSI6Ik5TTVAuTU9CSUxFIiwidXNlciI6IjU5MDAwMTU1IiwicGFnZU5vIjoiMSIsImVuZERhdGUiOiIiLCJkYXRlIjoiMjAxMTExMjIifQ==&ChartName=%e5%9c%a8%e7%bd%91%e7%94%a8%e6%88%b7%e6%95%b0%ef%bc%88%e6%88%b7%ef%bc%89&chartType=Column2D&Table=C-JY1001-JY10006"; mWebView.loadUrl(url); // progressDialog = builderProgressDialog("获取数据", "正在图表...", // MyProgressDialog.STYLE_SPINNER, false, cc); // progressDialog.show(); mWebView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { if (progress == 100) { progressDialogDismiss(); if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } } }); mWebView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // Handle // the // error progressDialogDismiss(); } public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); } @Override protected void onResume() { super.onResume(); // if (isLogin()) { // Intent intent = new Intent(this, ActivityLogin.class); // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // startActivity(intent); // Intent i = new Intent(BroadcastCloseSelf); // sendBroadcast(i); // // } } public int fillData(DataReportTable dataReport) { viewExcel.clear(); float font_size = getResources().getDimension(R.dimen.font_size); boolean islength = false; int cellWidth = (int) ((Cell.maxLineFontNum + 1) * ToolsUtils.dip2px(this, font_size)), cellHeight = (int) (2 * ToolsUtils.dip2px(this, font_size)); int oldWidth = cellWidth; /* if (aChartItemHead.chartTypeName.indexOf("月报") != -1 || aChartItemHead.chartTypeName.indexOf("经营总览") != -1) { islength = true; cellWidth = cellWidth * 3 / 2; }*/ // 行数 标题 int rows_header = 0; // 固定列数 // 除去固定列之后的列数 int cols_right = 0; // 除去标题之后的行数 // int rows_data = 0; // 左上 固定列 标题 List<List<CellHeader>> list_tableHeaders = dataReport.getList_tableHeaders(); aChartItemHead.crollDrills = dataReport.aList_CrollssDrill; if (list_tableHeaders != null && list_tableHeaders.size() == 2)// 2级表头的情况 { List<List<CellHeader>> new_list_tableHeaders = new ArrayList<List<CellHeader>>(); List<CellHeader> list_rowLeaf = new ArrayList<CellHeader>(); List<CellHeader> list_rowHeader = new ArrayList<CellHeader>(); for (int i = 0; i < list_tableHeaders.size(); i++) for (int j = 0; j < list_tableHeaders.get(i).size(); j++) { CellHeader cellHeader = list_tableHeaders.get(i).get(j); if (cellHeader.leaf) list_rowLeaf.add(cellHeader); else list_rowHeader.add(cellHeader); } for (int i = 0; i < list_rowHeader.size(); i++) { String headerId = list_rowHeader.get(i).headerId; for (int j = 0; j < list_rowLeaf.size(); j++) { String parentHeaderId = list_rowLeaf.get(j).parentHeaderId; if (parentHeaderId.equals(headerId)) { list_rowLeaf.get(j).label = list_rowHeader.get(i).label + list_rowLeaf.get(j).label; } } } for (CellHeader item : list_rowLeaf) { if (item.label.length() > 18) { item.label = item.label.substring(0, 8) + "..." + item.label.substring(item.label.length() - 8, item.label.length()); } } new_list_tableHeaders.add(list_rowLeaf); list_tableHeaders = null; list_tableHeaders = new_list_tableHeaders; } if (list_tableHeaders == null || list_tableHeaders.size() != 1) { // 说明没有表头或者多个表头 return 1; } // zhuht3...begin WindowManager windowManager = this.getWindowManager(); Display display = windowManager.getDefaultDisplay(); int ScreenWidth = display.getWidth(); int ScreenHeight = display.getHeight(); int tmpcols = list_tableHeaders.get(0).size(); if (tmpcols > 0 && tmpcols * cellWidth < ScreenWidth) { cellWidth = ScreenWidth / tmpcols; } // zhuht3...end rows_header = list_tableHeaders.size(); // cols_fixed = 1;//固定列只有一列 titleName = new String[list_tableHeaders.get(0).size()]; titleExplain = new String[list_tableHeaders.get(0).size()]; /** * 列标题名字的解释 */ // 目前只有所有表头行的列数都是一样的() CellHeader[][] dataHeader = new CellHeader[rows_header][1]; // 左上 标题 for (int i = 0; i < dataHeader.length; i++) { for (int j = 0; j < dataHeader[i].length; j++) { CellHeader cellHeader = list_tableHeaders.get(i).get(j); dataHeader[i][j] = cellHeader; cellHeader.value = cellHeader.label; titleExplain[j] = cellHeader.title; titleName[j] = cellHeader.label; if (islength) { cellHeader.width = oldWidth; } else { cellHeader.width = cellWidth; } cellHeader.heihgt = cellHeight * 4 / 3; cellHeader.bgResId = R.drawable.form_header; cellHeader.fontColor = 0xff000000; cellHeader.fontSize = font_size; if (checkIsYWSSFZL()) { cellHeader.bgResId = R.drawable.form_header_ys01; } } } // data[0][0].gravity=Cell.LEFT|Cell.BOTTOM; viewExcel.fillData(dataHeader, ViewExcel_AILK.FILL_MODE_LEFT_TITLE);//绘制左标题 cols_right = list_tableHeaders.get(0).size() - 1;// 把固定列一列去掉 // 右上固定标题 dataHeader = new CellHeader[rows_header][cols_right]; if (checkIsYWSSFZL()) { button_childChart.setVisibility(View.GONE); } for (int i = 0; i < dataHeader.length; i++) for (int j = 0; j < dataHeader[0].length; j++) { { CellHeader cellHeader = list_tableHeaders.get(0).get(j + 1); // aListCellHeader 第一个元素为固定列 所以j+1 dataHeader[i][j] = cellHeader; cellHeader.value = cellHeader.label;// 格子显示的名称和value值不同 cellHeader.width = cellWidth; cellHeader.heihgt = cellHeight * 4 / 3; titleExplain[j + 1] = cellHeader.title; titleName[j + 1] = cellHeader.label; if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_DIGIT)) { // 处理 数值列 if (aChartItemHead.sort != null && aChartItemHead.sort.equalsIgnoreCase(cellHeader.name)) { if (TextHelper.isEmpty(aChartItemHead.sortType)) { cellHeader.bgResId = R.drawable.form_header_sort; } else if (aChartItemHead.sortType.equalsIgnoreCase(Constant.ASC)) { cellHeader.isASC = true; cellHeader.bgResId = R.drawable.form_header_sort_asc; } else if (aChartItemHead.sortType.equalsIgnoreCase(Constant.DESC)) { cellHeader.isASC = false; cellHeader.bgResId = R.drawable.form_header_sort_desc; } } else { cellHeader.bgResId = R.drawable.form_header_sort; } } else { cellHeader.bgResId = R.drawable.form_header; if (checkIsYWSSFZL()) { if (cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_OPERATE)) { cellHeader.bgResId = R.drawable.form_header_ys02; } } } cellHeader.fontColor = 0xff000000; if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_OPERATE)) { // 处理操作列 if (dataReport.aList_CrollssDrill != null && dataReport.aList_CrollssDrill.size() > 0) { cellHeader.fontColor = 0xff036DCA; if (checkIsYWSSFZL()) { button_childChart.setVisibility(View.VISIBLE); } } } cellHeader.fontSize = font_size; } } viewExcel.fillData(dataHeader, ViewExcel_AILK.FILL_MODE_RIGHT_TITLE);//绘制右标题 // 左下 固定列 内容 List<Map<String, CellData>> list_reportData = dataReport.getList_reportData(); if (list_reportData == null || list_reportData.size() <= 0) { // 没有内容数据 return 2; } // 填充数据区填充数据区填充数据区填充数据区填充数据区填充数据区填充数据区填充数据区 // 左下 固定列 内容 Cell[][] data = null; { if (dataReport.total) { // 合计 多一行 data = new Cell[list_reportData.size() + 1][1]; } else { data = new Cell[list_reportData.size()][1]; } for (int i = 0; i < data.length; i++) { // 获取数据 且赋值 CellData cellData; if (i == data.length - 1 && dataReport.total) { cellData = dataReport.getMap_totalData().get(list_tableHeaders.get(0).get(0).name); } else { String name = list_tableHeaders.get(0).get(0).name;// 查询索引 cellData = list_reportData.get(i).get(name); } if (cellData == null) { // 不能取出数据 cellData = new CellData(); if (i == data.length - 1 && dataReport.total) { cellData.value = "合计"; } else { cellData.value = "-"; } } else { cellData.value = cellData.colValue;// 表格显示名称和json的名称不一致 if (TextHelper.isEmpty(cellData.value)) { cellData.value = "-"; } cellData.href = cellData.drillURL; } data[i][0] = cellData;// 对象赋值 if (islength) { cellData.width = oldWidth; } else { cellData.width = cellWidth; } cellData.heihgt = cellHeight; cellData.bgResId = R.drawable.form_right; cellData.fontColor = 0xff000000; if (!TextHelper.isEmpty(cellData.href)) { cellData.fontColor = 0xff036DCA; } cellData.fontSize = font_size; } viewExcel.fillData(data, ViewExcel_AILK.FILL_MODE_LEFT_DATA);//填充左边第一列 } // 右下内容右下内容右下内容右下内容右下内容右下内容右下内容右下内容右下内容右下内容 { // 去掉下一列 if (dataReport.total) { // 有合计就多开辟一行 data = new Cell[list_reportData.size() + 1][list_tableHeaders.get(0).size() - 1]; } else { data = new Cell[list_reportData.size()][list_tableHeaders.get(0).size() - 1]; } for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { data[i][j] = new Cell(); CellData cellData = null; CellHeader cellHeader = list_tableHeaders.get(0).get(j + 1); if (i == data.length - 1 && dataReport.total) { // 有合计且是最后一行 cellData = dataReport.getMap_totalData().get(list_tableHeaders.get(0).get(j + 1).name); } else { cellData = list_reportData.get(i).get(list_tableHeaders.get(0).get(j + 1).name); } if (cellData == null) { // 不能取出数据 cellData = new CellData(); cellData.value = "-"; data[i][j] = cellData; } else { data[i][j] = cellData; cellData.value = cellData.colValue;// 表格显示名称和json的名称不一致 cellData.href = cellData.drillURL; if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equals(Constant.COLCLASS_DIGIT)) { cellData.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT; } else if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equals(Constant.COLCLASS_OPERATE)) {// 操作列需要特殊处理 String str_json = cellData.drillURL; if (!TextHelper.isEmpty(str_json)) { Gson gson = new Gson(); DrillURL drillUrl = null; if (str_json.indexOf("|") != -1) { str_json = str_json.substring(0, str_json.indexOf("|")); cellData.href = str_json;// 截取有效数据 } try { drillUrl = gson.fromJson(str_json, DrillURL.class); cellData.value = drillUrl.name; } catch (Exception e) { e.printStackTrace(); } } } } cellData.width = cellWidth; cellData.heihgt = cellHeight; cellData.bgResId = R.drawable.form_right; cellData.fontColor = 0xff000000; if (cellData != null && !TextHelper.isEmpty(cellData.href)) { // 如果是能下钻的话,就把颜色的值设置成下面的颜色 cellData.fontColor = 0xff036DCA; } cellData.fontSize = font_size; } } viewExcel.fillData(data, ViewExcel_AILK.FILL_MODE_RIGHT_DATA);//填充除左起第一列之外的列数据 } return 0; } /** * 报表的选择项 */ int selectChartId = 0; /** * 报表的图选项 */ int selectChartImageId = 0; public final int DIALOG_CHART = 1;// 子报表 public final int DIALOG_Return = 2;// 子报表 public final int DIALOG_CHART_IMG = 3;// 子报表 private int totalNoPage; private Builder builder; /** * 子表切换框 */ protected Dialog onCreateDialog(int id) { Dialog dialog = null; Builder builder = null; switch (id) { case DIALOG_Return: break; case DIALOG_CHART_IMG: final String names_img[] = new String[aChartItemHead.aList_chart_graphics.size()]; for (int i = 0; i < names_img.length; i++) { names_img[i] = aChartItemHead.aList_chart_graphics.get(i).name; } // builder = new Builder(this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("切换报表图"); // 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(names_img, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { selectChartImageId = which; } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadData(); } }); builder.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { ActivityExcel.this.finish(); clearData(); // log(" public boolean onKey(DialogInterface dialog, int keyCode"); // 重新启动ExcelActivity // Intent intent = new Intent(); // intent.setClass(ExcelActivity.this, // CatalogActivity.class); // // intent.setFlags(Intent.f) // ExcelActivity.this.startActivity(intent); } return false; } }); // 创建一个单选按钮对话框 dialog = builder.create(); break; case DIALOG_CHART: // 开辟子报表的空间 final String[] names = new String[businessHandler.aChartType.chartItemHeads.size()]; for (int i = 0; i < names.length; i++) { names[i] = businessHandler.aChartType.chartItemHeads.get(i).reportName; } builder = new Builder(this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("切换子报表"); // 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(names, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { selectChartId = which; } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 添加一个确定按钮 builder.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { ActivityExcel.this.finish(); clearData(); // log(" public boolean onKey(DialogInterface dialog, int keyCode"); // 重新启动ExcelActivity // Intent intent = new Intent(); // intent.setClass(ExcelActivity.this, // CatalogActivity.class); // // intent.setFlags(Intent.f) // ExcelActivity.this.startActivity(intent); } return false; } }); // 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // if (aChartItemHead.tableId != selectChartId) { // // 不是当前报表,就切换子报表 // } // System.out.println("businessHandler.aChartType.chartItemHeads===size="+businessHandler.aChartType.chartItemHeads.size()+","+selectChartId+","+selectChartId); ChartItemHead tChartItemHead = null; tChartItemHead = businessHandler.aChartType.chartItemHeads.get(selectChartId); aChartItemHead.reportId = tChartItemHead.reportId; aChartItemHead.reportName = tChartItemHead.reportName; aChartItemHead.reportcycle = tChartItemHead.reportcycle; aChartItemHead.url = tChartItemHead.url; // 此报表是否有图 aChartItemHead.hasImage = tChartItemHead.hasImage; // 表创建的时间 aChartItemHead.createtime = tChartItemHead.createtime; doTaskExcel(); } }); // 创建一个单选按钮对话框 dialog = builder.create(); break; case 0:// //////////////////////时间 try { return new MyDatePickDialog(this, new OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { //onDateSet在4.X版本有重载2次的BUG,需重写onStop String date = ""; aChartItemHead._year = year; aChartItemHead._month = monthOfYear + 1; aChartItemHead._day = dayOfMonth; date += aChartItemHead._year; if (aChartItemHead._month < 10) { date += "0" + aChartItemHead._month; } else { date += "" + aChartItemHead._month; } if (aChartItemHead._day < 10) { date += "0" + aChartItemHead._day; } else { date += aChartItemHead._day; } // log("timePicker" + aChartItemHead._year + ":" // + (aChartItemHead._month + 1) + ":" // + aChartItemHead._day + " date" + date); aChartItemHead.date = date; doTaskExcel(); } }, aChartItemHead._year, aChartItemHead._month - 1, aChartItemHead._day); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } return dialog; } @Override public void onConfigurationChanged(Configuration newConfig) { // log("orientation::::" + newConfig.orientation); configurationChanged(newConfig); super.onConfigurationChanged(newConfig); } /** * @param newConfig * @Description: 横竖屏切换时调用此方法 * @author jingwen * @date 2011-8-9 下午8:08:43 */ private void configurationChanged(Configuration newConfig) { if ((newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) || (newConfig.orientation == Configuration.KEYBOARDHIDDEN_YES)) { if ((topTitle_LinearLayout != null) && (bottom_LinearLayout != null)) { topTitle_LinearLayout.setVisibility(View.GONE); bottom_LinearLayout.setVisibility(View.GONE); } } else { if ((topTitle_LinearLayout != null) && (bottom_LinearLayout != null)) { // topTitle_LinearLayout.setVisibility(View.VISIBLE); // bottom_LinearLayout.setVisibility(View.VISIBLE); topTitle_LinearLayout.setVisibility(View.VISIBLE); bottom_LinearLayout.setVisibility(View.GONE); } } } @Override public void onScrollEnvent_Top(boolean isScrollTop) { // if (isScrollTop) { if (pageNoNow > 1) { pageNoNow--; pageChange(pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } } } @Override public void onScrollEnvent_Bottom(boolean isScrollBottom) { // if (isScrollBottom) { if (pageNoNow < totalNoPage) { pageNoNow++; pageChange(pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } } } @Override public void onScrollEnvent_Left(boolean isScrollLeft) { // } @Override public void onScrollEnvent_Right(boolean isScrolRight) { // // showToast("right"+pageNo); } boolean isClick; private String[] namess; int index = 0; private void colclass_operate_fun() { if (aChartItemHead.crollDrills == null || aChartItemHead.crollDrills.size() <= 0) { return; } namess = new String[aChartItemHead.crollDrills.size()];// aChartItemHead.crollDrills.; for (int i = 0; i < namess.length; i++) { namess[i] = aChartItemHead.crollDrills.get(i).name; } Builder builder = new Builder(ActivityExcel.this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("请选择"); index = 0; // 跨级钻取 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(namess, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { index = which; } }); // 跨级钻取 添加取消按钮 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 跨级钻取 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { { Gson gosn = new Gson(); String urljson = DESUtils.decrypt(aChartItemHead.url); // log(selectIndex+"=url start==="+urljson); ReportReq req = gosn.fromJson(new StringReader(urljson), ReportReq.class); // 操作列1 跨级 DrillURL drillRul = gosn.fromJson(new StringReader(aChartItemHead.crollDrills.get(index).drillURL), DrillURL.class); // 替换 req.setReportId(drillRul.reportId); req.setWhere(drillRul.where); req.setDate(drillRul.date); urljson = gosn.toJson(req); // log("url 1 end==="+urljson); String url = DESUtils.encrypt(urljson); aChartItemHead.url = url; if (!stackJson.contains(aChartItemHead.url)) { stackName.add(aChartItemHead.crollDrills.get(index).name); stackJson.add(aChartItemHead.url); } doTaskExcel(); } } }); // 创建一个单选按钮对话框 builder.create().show(); } int colSortLast = -1; @Override public void onClickCellEnvent(Cell cell, TextView tv) { if (cell instanceof CellHeader) { CellHeader cellHeader = (CellHeader) cell; if (TextHelper.isEmpty(cellHeader.colClass)) { // cellHeader.colClass为空值 return; } if (cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_OPERATE)) { colclass_operate_fun(); } else if (cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_DIGIT)) { Gson gosn = new Gson(); String urljson = DESUtils.decrypt(aChartItemHead.url); // log(selectIndex+"=url start==="+urljson); ReportReq req = gosn.fromJson(new StringReader(urljson), ReportReq.class); if (colSortLast != cellHeader.col) { cellHeader.isASC = false; } else { cellHeader.isASC = !cellHeader.isASC; } colSortLast = cellHeader.col; if (cellHeader.isASC) { req.sortType = Constant.ASC; cellHeader.sortType = Constant.ASC; } else { req.sortType = Constant.DESC; cellHeader.sortType = Constant.DESC; } req.sort = cellHeader.name; urljson = gosn.toJson(req); String url = DESUtils.encrypt(urljson); aChartItemHead.url = url; isNotInit = true;// 排序的时候没有 必要初始化化界面 doTaskExcel(); } } else if (!TextHelper.isEmpty(cell.href)) { // showToast(cell.href); if (cell.href != null && !cell.href.equals("")) { tv.setTextColor(0xff0000ff); aChartItemHead.level = "2";// 下一级 Gson gosn = new Gson(); DrillURL drillRul = gosn.fromJson(new StringReader(cell.href), DrillURL.class); String urljson = DESUtils.decrypt(this.businessHandler.aChartItemHead.url); ReportReq req = gosn.fromJson(new StringReader(urljson), ReportReq.class); /** * reportId 表示目标的reportId; * * desDim 表示目标报表的列替换目前报表的列; 前一个值是目前报表列;后一个值是新报表列; 如果有多个需要替换的列,用 @ * 分割; * * name:表示,显示在页面上的文字,即可以点击区显示的内容; * * where:钻取目标报表的条件; * * date:数据帐期; * * * * 如果需要钻取,生成新的请求串 方法; * * reportId 替换 原来请求串的reportId * * where 替换 原来请求串的where * * date 替换 原来请求串的 date; * */ // 替换 req.setReportId(drillRul.reportId); req.setWhere(drillRul.where); req.setDate(drillRul.date); /** * 替换 digDim dimValue为了BI的钻取 */ req.digDim = drillRul.digDim; req.dimValue = drillRul.dimValue; req.sort = ""; req.sortType = ""; // 重新组装新的json串 urljson = gosn.toJson(req); String url = DESUtils.encrypt(urljson); aChartItemHead.url = url; // 下钻 dimensionChange(aChartItemHead, null); // if (!stackJson.contains(aChartItemHead.url)) { stackName.add(cell.value); stackJson.add(aChartItemHead.url); // } } } else { if (cell.value.length() > Cell.maxLineFontNum) { showToast(cell.value); } } } @Override public void onLongClickCellEnvent(Cell cell, TextView tv) { // // if (cell instanceof CellHeader) { // Intent intent = new Intent(); // Bundle b = new Bundle(); // b.putStringArray("title", titleName);// 表体 // b.putStringArray("explain", titleExplain);// 解释 // intent.putExtras(b); // // b.putb // // intent.putExtras(extras); // intent.setClass(ActivityExcel.this, IndexesExplainActivity.class); // ActivityExcel.this.startActivity(intent); // // } } public static class MyDatePickDialog extends DatePickerDialog { public MyDatePickDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, callBack, year, monthOfYear, dayOfMonth); // TODO Auto-generated constructor stub } public MyDatePickDialog(Context context, int theme, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, theme, callBack, year, monthOfYear, dayOfMonth); // TODO Auto-generated constructor stub } @Override protected void onStop() { // TODO Auto-generated method stub } } }
UTF-8
Java
70,650
java
ActivityExcel.java
Java
[ { "context": "import butterknife.ButterKnife;\r\n\r\n/**\r\n * @author MrJing\r\n * @ClassName: ActivityExcel\r\n * @Description: 表", "end": 2387, "score": 0.9571337699890137, "start": 2381, "tag": "USERNAME", "value": "MrJing" }, { "context": "init\r\n * @Description: 初始化 类文件\r\n * @author MrJing\r\n * @date 2012-3-4 上午1:19:19\r\n */\r\n pu", "end": 5375, "score": 0.6739339232444763, "start": 5369, "tag": "USERNAME", "value": "MrJing" }, { "context": "eChange\r\n * @Description: 日期切换\r\n * @author MrJing\r\n * @date 2012-3-14 下午7:19:52\r\n */\r\n p", "end": 12301, "score": 0.788053035736084, "start": 12295, "tag": "NAME", "value": "MrJing" }, { "context": " reload\r\n * @Description: 加载数据\r\n * @author MrJing\r\n * @date 2012-3-4 上午1:18:48\r\n */\r\n ", "end": 21572, "score": 0.8884959816932678, "start": 21570, "tag": "NAME", "value": "Mr" }, { "context": "load\r\n * @Description: 加载数据\r\n * @author MrJing\r\n * @date 2012-3-4 上午1:18:48\r\n */\r\n ", "end": 21573, "score": 0.612184464931488, "start": 21572, "tag": "USERNAME", "value": "J" }, { "context": "oad\r\n * @Description: 加载数据\r\n * @author MrJing\r\n * @date 2012-3-4 上午1:18:48\r\n */\r\n pu", "end": 21576, "score": 0.5274012088775635, "start": 21573, "tag": "NAME", "value": "ing" }, { "context": "am pageNo\r\n * @Description: 翻页\r\n * @author jingwen\r\n * @date 2011-9-15 下午8:55:38\r\n */\r\n p", "end": 27736, "score": 0.9966354370117188, "start": 27729, "tag": "USERNAME", "value": "jingwen" }, { "context": "on + \"&\");\r\n\r\n // url\r\n // =\"http://130.38.27.143:7711/mapp/bus/chart2nsmp.action?QueryStr=eyJyZXBv", "end": 33387, "score": 0.9991505146026611, "start": 33374, "tag": "IP_ADDRESS", "value": "130.38.27.143" }, { "context": "8.27.143:7711/mapp/bus/chart2nsmp.action?QueryStr=eyJyZXBvcnRJZCI6IjEyNjQiLCJyb3ciOiIiLCJ1c2VySWQiOiIiLCJkaW1WYWx1ZSI6IiIsIndoZXJlIjoiW0pZMTAxMl0gPSAnMzg2JyAgQU5EIFtKWTEwMDhdID0gJzM4NjAwMScgIiwic3RhcnREYXRlIjoiIiwicGFnZVNpemUiOiIzMCIsInBhZ2VhYmxlIjoidHJ1ZSIsIm51bSI6IiIsInVzZXJTdGF0aW9uIjoiIiwiZnJvbSI6Ik5TTVAuTU9CSUxFIiwidXNlciI6IjU5MDAwMTU1IiwicGFnZU5vIjoiMSIsImVuZERhdGUiOiIiLCJkYXRlIjoiMjAxMTExMjIifQ==&ChartName=%e5%9c%a8%e7%bd%91%e7%94%a8%e6%88%b7%e6", "end": 33785, "score": 0.9996315836906433, "start": 33429, "tag": "KEY", "value": "eyJyZXBvcnRJZCI6IjEyNjQiLCJyb3ciOiIiLCJ1c2VySWQiOiIiLCJkaW1WYWx1ZSI6IiIsIndoZXJlIjoiW0pZMTAxMl0gPSAnMzg2JyAgQU5EIFtKWTEwMDhdID0gJzM4NjAwMScgIiwic3RhcnREYXRlIjoiIiwicGFnZVNpemUiOiIzMCIsInBhZ2VhYmxlIjoidHJ1ZSIsIm51bSI6IiIsInVzZXJTdGF0aW9uIjoiIiwiZnJvbSI6Ik5TTVAuTU9CSUxFIiwidXNlciI6IjU5MDAwMTU1IiwicGFnZU5vIjoiMSIsImVuZERhdGUiOiIiLCJkYXRlIjoiMjAxMTExMjIifQ==" }, { "context": "\r\n * @Description: 横竖屏切换时调用此方法\r\n * @author jingwen\r\n * @date 2011-8-9 下午8:08:43\r\n */\r\n pr", "end": 57779, "score": 0.9990184903144836, "start": 57772, "tag": "USERNAME", "value": "jingwen" } ]
null
[]
package com.ai.ui.assispoor.reportforms; import android.app.AlertDialog.Builder; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnKeyListener; import android.content.res.Configuration; import android.os.Bundle; import android.text.TextUtils; import android.view.Display; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.DatePicker; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.ai.assispoor.R; import com.ai.ui.comm.CustomProgressDialog; import com.ai.utils.ToastUtil; import com.ai.view.dialog.DialogNumberPicker; import com.ailk.data.ChartItemHead; import com.ailk.data.excel.Cell; import com.ailk.data.excel.CellData; import com.ailk.data.excel.CellHeader; import com.ailk.data.excel.DataReportTable; import com.ailk.data.itsurport.Constant; import com.ailk.data.itsurport.ImgTable; import com.ailk.data.json.DrillURL; import com.ailk.data.json.ReportReq; import com.ailk.event.excel.CellEventListner; import com.ailk.event.excel.ScrollEventListner; import com.ailk.main.SuperBaseActivity; import com.ailk.task.GenericTask; import com.ailk.task.TaskListener; import com.ailk.task.TaskParams; import com.ailk.task.itsurport.TaskExcel; import com.ailk.tools.security.Base64; import com.ailk.tools.security.DESUtils; import com.ailk.tools.utils.TextHelper; import com.ailk.tools.utils.ToolsUtils; import com.ailk.view.excel.ViewExcel_AILK; import com.google.gson.Gson; import java.io.StringReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.Vector; import butterknife.Bind; import butterknife.ButterKnife; /** * @author MrJing * @ClassName: ActivityExcel * @Description: 表格数据 * @date 2012-3-2 下午9:41:05 */ public class ActivityExcel extends SuperBaseActivity implements CellEventListner, ScrollEventListner { @Bind(R.id.page_no) TextView pageNo; @Bind(R.id.page_up) TextView pageUp; @Bind(R.id.page_down) TextView pageDown; @Bind(R.id.tv_total) TextView tvTotal; /** * */ private ViewExcel_AILK viewExcel; private String titleName[]; /** * 列标题名字的解释 */ private String titleExplain[]; /** * 存储json 串,用于上钻,下钻,日期变更 */ private Vector<String> stackJson = new Vector<String>(); /** * 存储网格名字 */ private Vector<String> stackName = new Vector<String>(); /** * 顶部状态栏 */ private LinearLayout topTitle_LinearLayout; /** * 底部状态栏 */ private LinearLayout bottom_LinearLayout; /** * 维度上钻 */ private Button parentButton; /** * 刷新按钮 */ private Button btn_fresh; /** * 没有必要重新初始化界面 */ public boolean isNotInit; /** * 返回首页 */ private ImageButton homeButton; /** * 发邮件按钮 */ private ImageButton mailButton; /** * 按日查询按钮 */ private ImageButton selectTimeButton; private TextView ChartNameTitle; private TextView ChartTime; /** * 关联表 */ private Button button_childChart; /** * 图表的控制按钮 */ private ImageButton button_chart_img; /** * 控制 表格数据和表图 之间的切换 变量 */ private boolean isShowChartImage = false; /** * 正在展示的表头 */ public ChartItemHead aChartItemHead; /** * 后一天 */ private ImageButton nextButton; /** * 前一日按钮 */ private ImageButton preButton; private CustomProgressDialog nProgressDialog; private int pageNoNow = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); nProgressDialog = CustomProgressDialog.createDialog(context); nProgressDialog.setCancelable(true); nProgressDialog.setCanceledOnTouchOutside(false); this.aChartItemHead = businessHandler.aChartItemHead; aChartItemHead.reportcycle = "d"; stackJson.add(aChartItemHead.url); stackName.add("第一层"); loadData(); } /** * 判断是否为移网实时发展量的报表 */ private boolean checkIsYWSSFZL() { String tmpChartName = ((TextView) findViewById(R.id.ChartName)).getText().toString(); if (tmpChartName.equals("移网实时发展量")) { return true; } else { return false; } } /** * @param * @return void 返回类型 * @throws * @Title: init * @Description: 初始化 类文件 * @author MrJing * @date 2012-3-4 上午1:19:19 */ public void init() { setContentView(R.layout.excel); ButterKnife.bind(this); viewExcel = (ViewExcel_AILK) findViewById(R.id.myExcel); viewExcel.setOnClickCellEventListner(this); viewExcel.setOnScrollEventListner(this); ChartNameTitle = (TextView) findViewById(R.id.ChartNameTitle); ChartTime = (TextView) findViewById(R.id.ChartTime); /** * 顶部 状态栏 */ topTitle_LinearLayout = (LinearLayout) findViewById(R.id.TopTitle_LinearLayout); /** * 底部 状态栏 */ bottom_LinearLayout = (LinearLayout) findViewById(R.id.Bottom_LinearLayout); // 子报表按钮 button_childChart = (Button) findViewById(R.id.button_child_chart); // 控制子报表的切换 button_childChart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (checkIsYWSSFZL()) { colclass_operate_fun(); return; } if (!isShowChartImage) { showDialog(DIALOG_CHART); } else { if (aChartItemHead.aList_chart_graphics != null && aChartItemHead.aList_chart_graphics.size() > 1) { // 图表 大于一个的时候 showDialog(DIALOG_CHART_IMG); } } } }); /** * 数据表格 */ // relativeLayout = (RelativeLayout) // findViewById(R.id.RelativeLayout01_excel); // 初始化浏览器 mWebView = (WebView) findViewById(R.id.show_webv); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setPluginState(WebSettings.PluginState.ON); // mWebView.getSettings().setSupportZoom(true); mWebView.getSettings().setBuiltInZoomControls(true); /** * 图表 */ button_chart_img = (ImageButton) findViewById(R.id.button_chart_img); /** * 图表切换按钮 */ button_chart_img.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { isShowChartImage = !isShowChartImage; // if(!isShowChartImage) // { // // mWebView.setVisibility(View.GONE); // relativeLayout.setVisibility(View.VISIBLE); // }else{ // // webView(); // relativeLayout.setVisibility(View.GONE); // mWebView.setVisibility(View.VISIBLE); // } // 重新初始化和加载数据 loadData(); } }); // no understand configurationChanged(getResources().getConfiguration()); // 发邮件 mailButton = (ImageButton) findViewById(R.id.button_send_mail); mailButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // // log("seend mail"); String tableName = aChartItemHead.reportName; ToolsUtils.takeScreenShotToEmail(ActivityExcel.this, ActivityExcel.this, tableName); } }); homeButton = (ImageButton) findViewById(R.id.button_home); homeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Intent intent = new Intent(); // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // intent.setClass(ExcelActivity.this, CatalogActivity.class); // 暂时没有使用此方法 startActivity finish(); clearData(); } }); // 时间查询 selectTimeButton = (ImageButton) findViewById(R.id.button_select_time); selectTimeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // log("time time time!"); showDialog(0); } }); // 前一天 preButton = (ImageButton) findViewById(R.id.button_left); preButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //此方法会导致崩溃,暂时未用到 // try { dateChange(-1); // }catch (Exception e){ // e.printStackTrace(); // } } }); // 后一天 nextButton = (ImageButton) findViewById(R.id.button_right); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //此方法会导致崩溃,暂时未用到 // try { dateChange(1); // }catch (Exception e){ // e.printStackTrace(); // } } }); parentButton = (Button) findViewById(R.id.ParentButton); parentButton.setEnabled(true); /** * 上钻按钮 */ parentButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 弹出返回列表 if (stackJson.size() > 1) { // if(stackJson.size()) // aChartItemHead.url = stackJson.pop(); // dimensionChange(aChartItemHead, null); if (stackJson.size() == 2) { // 上钻 aChartItemHead.url = stackJson.get(0); stackName.remove(1); stackJson.remove(1); dimensionChange(aChartItemHead, null); } else { showReturnDialog(); } } else { finish(); clearData(); } } }); btn_fresh = (Button) findViewById(R.id.button_refresh); btn_fresh.setEnabled(true); /** * 上钻按钮 */ btn_fresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doTaskExcel(); // dimensionChange(aChartItemHead, null); } }); } protected void dimensionChange(ChartItemHead aChartItemHead2, Object object) { pageNoNow = 1; aChartItemHead.pageNo = "" + pageNoNow; doTaskExcel(); } /** * @param @param i 设定文件 * @return void 返回类型 * @throws * @Title: dateChange * @Description: 日期切换 * @author MrJing * @date 2012-3-14 下午7:19:52 */ private void dateChange(int direction) { String date = null; int d = 0; int m = 0; int y = 0; if (direction == 1) { // 更改日期 if (aChartItemHead.reportcycle.toLowerCase().equals("m")) { d = 0; m = 1; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("d")) { // aChartItemHead._day +=1; d = 1; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("w")) { // aChartItemHead._day +=1; d = 7; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("q")) { // aChartItemHead._day +=1; d = 0; m = 3; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("y")) { // aChartItemHead._day +=1; d = 0; m = 0; y = 1; } // date = aChartItemHead.chartNextTime; } else if (direction == -1) { // // date = aChartItemHead.chartPreTime; if (aChartItemHead.reportcycle.toLowerCase().equals("m")) { d = 0; m = -1; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("d")) { // aChartItemHead._day +=1; d = -1; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("w")) { // aChartItemHead._day +=1; d = -7; m = 0; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("q")) { // aChartItemHead._day +=1; d = 0; m = -3; y = 0; } else if (aChartItemHead.reportcycle.toLowerCase().equals("y")) { // aChartItemHead._day +=1; d = 0; m = 0; y = -1; } } aChartItemHead.cDate.set(Calendar.DATE, aChartItemHead.cDate.get(Calendar.DATE) + d); // 前一天( // 减1) aChartItemHead.cDate.set(Calendar.MONTH, aChartItemHead.cDate.get(Calendar.MONTH) + m); aChartItemHead.cDate.set(Calendar.YEAR, aChartItemHead.cDate.get(Calendar.YEAR) + y); aChartItemHead._year = aChartItemHead.cDate.get(Calendar.YEAR); aChartItemHead._month = aChartItemHead.cDate.get(Calendar.MONTH) + 1; aChartItemHead._day = aChartItemHead.cDate.get(Calendar.DATE); date = "" + aChartItemHead._year; if (aChartItemHead._month < 10) { date += "0" + aChartItemHead._month; } else { date += "" + aChartItemHead._month; } if (aChartItemHead._day < 10) { date += "0" + aChartItemHead._day; } else { date += aChartItemHead._day; } // date = // ""+aChartItemHead._year+aChartItemHead._month+aChartItemHead._day; // log("date==" + date); aChartItemHead.date = date; // log("dateChange::" + aChartItemHead.chartNextTime + "::" // + aChartItemHead.chartEndTime + "::" + date); if (date != null) { doTaskExcel(); } } /** * 返回对话框 */ public void showReturnDialog() { Dialog dialog = null; final String[] namesTable = new String[stackJson.size()]; final String[] valueTable = new String[stackJson.size()]; // 获取内容 for (int i = 0; i < stackJson.size(); i++) { namesTable[i] = stackName.elementAt(i); valueTable[i] = stackJson.elementAt(i); } builder = new Builder(this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("请选择"); selectChartId = namesTable.length - 1; // 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(namesTable, selectChartId, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { selectChartId = which; } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // log("=selectId==============" + selectChartId); if (selectChartId < valueTable.length - 1) { // 不只是对url替换还需要解密,对aChartItemHead其他属 aChartItemHead.url = valueTable[selectChartId]; // 复原 // fromUrlJson("", aChartItemHead); for (int i = selectChartId + 1; i < namesTable.length; i++) { // log("=selectId===i===========" + i // + ",stackJson=" + stackJson.size()); stackJson.remove(valueTable[i]); stackName.remove(namesTable[i]); } dimensionChange(aChartItemHead, null); } selectChartId = 0; } }); // 创建一个单选按钮对话框 dialog = builder.create(); dialog.show(); } private OnCancelListener cc = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // } }; /** * 获取报表任务监听器 */ TaskListener iTaskListenerExcel = new TaskListener() { @Override public void onPreExecute(final GenericTask task) { dismissAllDialogs(); nProgressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { task.cancel(true); stackName.remove(stackName.size() - 1); stackJson.remove(stackJson.size() - 1); } }); nProgressDialog.show(); // dismissAllDialogs(); // showProgressDialog("获取报表", " 正在连接服务器...", ProgressDialog.STYLE_HORIZONTAL, false, cc); } @Override public void onPostExecute(GenericTask task, String result) { // nProgressDialog.dismiss(); dismissAllDialogs(); if (result.equals(Constant.rspCode_OK)) { loadData(); } else { // // 失败 (重新尝试登录) // // 是 按钮 // DialogInterface.OnClickListener onYesClickListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // businessHandler.userConfig.mIMSI="460015910647328"; // // doLogin(); // doTaskExcel(); // } // }; // // 否按钮 // DialogInterface.OnClickListener onNoClickListener = new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // // } // }; // String msg = getErrorMessage(result); // showYesNoAlertDialog("信息提示", msg, "重试", "取消", onYesClickListener, // onNoClickListener); ToastUtil.show("获取数据失败,请重试"); } } @Override public void onProgressUpdate(GenericTask task, Object... values) { // super.onProgressUpdate(task, values); // int total = (Integer) values[0]; // int current = (Integer) values[1]; // showUpdateProgress(total, current); // if (current > 0) { // // 设置的次数过多,效率不高 // setProgressDialogMessage("正在下载数据..."); // } // if (total > 0 && total == current) { // setProgressDialogMessage("正在解析数据..."); // } } @Override public void onCancelled(GenericTask task) { // } @Override public String getName() { // return "doTaskExcel"; } }; // private RelativeLayout relativeLayout; public void doTaskExcel() { TaskExcel taskExcel = new TaskExcel(this); taskExcel.setListener(iTaskListenerExcel); TaskParams params = new TaskParams(); // 对 url进行处理,比如翻页等信息处理 // businessHandler.aChartItemHead.url; if (businessHandler.aChartItemHead == null || businessHandler.aChartItemHead.url == null || businessHandler.aChartItemHead.url.equals("")) { showToast("报表不存在"); return; } params.put("First", false); taskExcel.execute(params); } /** * @param * @return void 返回类型 * @throws * @Title: reload * @Description: 加载数据 * @author MrJing * @date 2012-3-4 上午1:18:48 */ public void loadData() { this.aChartItemHead = businessHandler.aChartItemHead; if (this.aChartItemHead == null) { return; } if (!isNotInit) { init(); } else { isNotInit = false; } DialogInterface.OnClickListener onOkClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }; // handleViewLoadPage(); // handleLoadViewTopMenu(); // handleLoadViewRealTimeChart(); // handleLoadViewChartImage(); if (businessHandler.dataReport == null || businessHandler.dataReport.getList_tableHeaders() == null || businessHandler.dataReport.getList_tableHeaders().size() <= 0 || businessHandler.dataReport.getList_reportData() == null || businessHandler.dataReport.getList_reportData().size() <= 0) { viewExcel.clear(); showOkAlertDialog("信息提示", "对不起,当前没有数据!", onOkClickListener); // return ; } handleViewLoadPage(); if (pageNoNow > 1) { pageUp.setVisibility(View.VISIBLE); pageUp.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pageChange(--pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } }); } else { pageUp.setVisibility(View.INVISIBLE); pageUp.setOnClickListener(null); } if (pageNoNow < totalNoPage) { pageDown.setVisibility(View.VISIBLE); pageDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pageChange(++pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } }); } else { pageDown.setVisibility(View.INVISIBLE); pageDown.setOnClickListener(null); } SimpleDateFormat oldformat = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat newformat = new SimpleDateFormat("yyyy年MM月dd日"); if (businessHandler.dataReport != null) { if (!TextUtils.isEmpty(businessHandler.dataReport.reportTitle)) { ChartNameTitle.setText(businessHandler.dataReport.reportTitle); ChartTime.setText(""); try { ChartTime.setText(newformat.format(oldformat.parse(businessHandler.dataReport.reportTime))); } catch (ParseException e) { e.printStackTrace(); } tvTotal.setText("共"+businessHandler.dataReport.totalCnt+"条"); } else { ChartNameTitle.setText("报表"); ChartTime.setText(""); } pageNo.setText("第" + pageNoNow + "页"); if (totalNoPage>1) { pageNo.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { final DialogNumberPicker dialogNumberPicker=new DialogNumberPicker(context,"跳转到",pageNoNow,totalNoPage); dialogNumberPicker.setOnLeftClick(new OnClickListener() { @Override public void onClick(View view) { pageNoNow=Integer.valueOf(dialogNumberPicker.getPageNo()); pageChange(pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); dialogNumberPicker.dismiss(); } }); dialogNumberPicker.show(); } }); } else { pageNo.setOnClickListener(null); // pageNo.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View view) { // final DialogNumberPicker dialogNumberPicker=new DialogNumberPicker(context,"跳转到",pageNoNow,300); // dialogNumberPicker.setOnLeftClick(new OnClickListener() { // @Override // public void onClick(View view) { // pageNoNow=dialogNumberPicker.getPageNo(); // pageChange(pageNoNow); // showToast(pageNoNow + "/" + totalNoPage + "页"); // dialogNumberPicker.dismiss(); // } // }); // dialogNumberPicker.show(); // } // }); } fillData(businessHandler.dataReport); } else { showToast("报表数据为空"); } } /** * 关于加载翻页的处理 */ private void handleViewLoadPage() { // 关于翻页 int t = 0; totalNoPage = 1; try { t = Integer.parseInt(aChartItemHead.totalCnt); } catch (Exception e) { } if (t > Integer.parseInt(Constant.pageMaxLine)) { /** * 计算页码 */ int maxLine = Integer.parseInt(Constant.pageMaxLine); if (t % maxLine == 0) { totalNoPage = t / maxLine; } else { totalNoPage = t / maxLine + 1; } } } private void clearData() { this.aChartItemHead = null; businessHandler.aChartItemHead = null; businessHandler.aChartType = null; businessHandler.dataReport = null; viewExcel = null; System.gc(); } /** * @param pageNo * @Description: 翻页 * @author jingwen * @date 2011-9-15 下午8:55:38 */ private void pageChange(int pageNo) { // String pageNoShow = pageNo + "/" + totalNoPage; // log("pageNoShow===" + pageNoShow); // page_tv.setText(pageNoShow); aChartItemHead.pageNo = "" + pageNo; doTaskExcel(); } /** * 关于加载实时报表界面 */ private void handleLoadViewRealTimeChart() { /** * 关于刷新按钮 根据列表中得切换周期值R来确定是否屏蔽前一天,后一天,日期查询按钮 */ /*if (aChartItemHead.reportcycle.toLowerCase().equals("r") || !TextHelper.isEmpty(aChartItemHead.queryType)) { preButton.setBackgroundResource(R.drawable.icon_arrow_leftno); preButton.setEnabled(false); nextButton.setBackgroundResource(R.drawable.icon_arrow_rightno); nextButton.setEnabled(false); selectTimeButton.setBackgroundResource(R.drawable.icon_timeno); selectTimeButton.setEnabled(false); btn_fresh.setVisibility(Button.VISIBLE); } else { btn_fresh.setVisibility(Button.GONE); preButton.setBackgroundResource(R.drawable.arrow_l_bk); preButton.setEnabled(true); nextButton.setBackgroundResource(R.drawable.arrow_r_bk); nextButton.setEnabled(true); selectTimeButton.setBackgroundResource(R.drawable.icon_time_bk); selectTimeButton.setEnabled(true); }*/ } /** * 设置报表上边的 属性 */ private void handleLoadViewTopMenu() { if (businessHandler.aChartType != null && businessHandler.aChartType.chartItemHeads != null && businessHandler.aChartType.chartItemHeads.size() > 1) { button_childChart.setVisibility(View.VISIBLE); } else { button_childChart.setVisibility(View.GONE); } // 报表的日期 // Log.e("xxx", "r"); /*if (!TextHelper.isEmpty(aChartItemHead.date)) { String dt = ToolsUtils.dateFormat(aChartItemHead.date); Log.e("xxxdt", "" + dt); Log.e("xxxr", "" + aChartItemHead.reportcycle); if (dt != null) { if (aChartItemHead.reportcycle.toLowerCase().equals("m")) { // Log.e("xxx", "m"); // 月 dt = dt.substring(0, dt.length() - 3); } else if (aChartItemHead.reportcycle.toLowerCase().equals("r")) { // 实时 // Log.e("xxx", "r"); dt = aChartItemHead.statisticTime; } *//** * 日期 *//* ((TextView) findViewById(R.id.ChartTime)).setText(dt); } } else { // 木有日期的时候,就填写列表的数据 Log.e("xxx", "n"); ((TextView) findViewById(R.id.ChartTime)).setText(businessHandler.aChartType.lastdate); }*/ // 正常日期不做去了 // 维度栈 返回按钮 if (stackJson.size() <= 1) { parentButton.setVisibility(View.GONE); stackJson.clear(); stackName.clear(); //stackJson.add(aChartItemHead.url); stackName.add("第一层"); } else { // 只有一级有子表,其他级没有子表 button_childChart.setVisibility(View.GONE); parentButton.setVisibility(View.VISIBLE); } /** * 设置专题名字 *//* ((TextView) findViewById(R.id.ChartName)).setText(aChartItemHead.chartTypeName); *//** * 设置具体表名字 *//* TextView tv = (TextView) findViewById(R.id.ChartNameTitle); tv.setText(aChartItemHead.reportName);*/ } private void handleLoadViewChartImage() { if (aChartItemHead.aList_chart_graphics == null || aChartItemHead.aList_chart_graphics.size() < 1) { isShowChartImage = false; } /** * 设置报表gif图是否可见 */ if (aChartItemHead.hasImage != null && aChartItemHead.hasImage.equals("1")) { button_chart_img.setVisibility(View.VISIBLE); } else { button_chart_img.setVisibility(View.GONE); } if (isShowChartImage) { // 显示 报表图表 webView(); mWebView.setVisibility(View.VISIBLE); viewExcel.setVisibility(View.GONE); if (aChartItemHead.aList_chart_graphics.size() > 1) { // 报表视图多于一个 button_childChart.setVisibility(View.VISIBLE); } // 是否隐藏刷新按钮 if (btn_fresh.isShown()) { btn_fresh.setVisibility(View.GONE); } // 标题 findViewById(R.id.TopTextTitle_LinearLayout).setVisibility(View.GONE); this.button_chart_img.setBackgroundResource(R.drawable.datatable_bk); } else { // if (!aChartItemHead.hasData) { // // dialogInfo(R.string.all_chart_nochartData, false); // } // 显示报表数据 mWebView.setVisibility(View.GONE); // relativeLayout.setVisibility(View.VISIBLE); viewExcel.setVisibility(View.VISIBLE); findViewById(R.id.TopTextTitle_LinearLayout).setVisibility(View.VISIBLE); this.button_chart_img.setBackgroundResource(R.drawable.imgtable_bk); } } private WebView mWebView; /** * chart view设置报表试图 */ public void webView() { // mWebView.loadUrl("http://wap.sohu.com"); ImgTable item = aChartItemHead.aList_chart_graphics.get(selectChartImageId); String url = item.url; // des解密 url = DESUtils.decrypt(url); String requestJson = DESUtils.decrypt(aChartItemHead.url); // requestJson base64 requestJson = Base64.encode(requestJson.getBytes()); // 替换 url = url.replace("QueryStr&", requestJson + "&"); // url // ="http://172.16.17.32:7711/mapp/bus/chart2nsmp.action?QueryStr=<KEY>&ChartName=%e5%9c%a8%e7%bd%91%e7%94%a8%e6%88%b7%e6%95%b0%ef%bc%88%e6%88%b7%ef%bc%89&chartType=Column2D&Table=C-JY1001-JY10006"; mWebView.loadUrl(url); // progressDialog = builderProgressDialog("获取数据", "正在图表...", // MyProgressDialog.STYLE_SPINNER, false, cc); // progressDialog.show(); mWebView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { if (progress == 100) { progressDialogDismiss(); if (progressDialog != null) { progressDialog.dismiss(); progressDialog = null; } } } }); mWebView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // Handle // the // error progressDialogDismiss(); } public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); } @Override protected void onResume() { super.onResume(); // if (isLogin()) { // Intent intent = new Intent(this, ActivityLogin.class); // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); // startActivity(intent); // Intent i = new Intent(BroadcastCloseSelf); // sendBroadcast(i); // // } } public int fillData(DataReportTable dataReport) { viewExcel.clear(); float font_size = getResources().getDimension(R.dimen.font_size); boolean islength = false; int cellWidth = (int) ((Cell.maxLineFontNum + 1) * ToolsUtils.dip2px(this, font_size)), cellHeight = (int) (2 * ToolsUtils.dip2px(this, font_size)); int oldWidth = cellWidth; /* if (aChartItemHead.chartTypeName.indexOf("月报") != -1 || aChartItemHead.chartTypeName.indexOf("经营总览") != -1) { islength = true; cellWidth = cellWidth * 3 / 2; }*/ // 行数 标题 int rows_header = 0; // 固定列数 // 除去固定列之后的列数 int cols_right = 0; // 除去标题之后的行数 // int rows_data = 0; // 左上 固定列 标题 List<List<CellHeader>> list_tableHeaders = dataReport.getList_tableHeaders(); aChartItemHead.crollDrills = dataReport.aList_CrollssDrill; if (list_tableHeaders != null && list_tableHeaders.size() == 2)// 2级表头的情况 { List<List<CellHeader>> new_list_tableHeaders = new ArrayList<List<CellHeader>>(); List<CellHeader> list_rowLeaf = new ArrayList<CellHeader>(); List<CellHeader> list_rowHeader = new ArrayList<CellHeader>(); for (int i = 0; i < list_tableHeaders.size(); i++) for (int j = 0; j < list_tableHeaders.get(i).size(); j++) { CellHeader cellHeader = list_tableHeaders.get(i).get(j); if (cellHeader.leaf) list_rowLeaf.add(cellHeader); else list_rowHeader.add(cellHeader); } for (int i = 0; i < list_rowHeader.size(); i++) { String headerId = list_rowHeader.get(i).headerId; for (int j = 0; j < list_rowLeaf.size(); j++) { String parentHeaderId = list_rowLeaf.get(j).parentHeaderId; if (parentHeaderId.equals(headerId)) { list_rowLeaf.get(j).label = list_rowHeader.get(i).label + list_rowLeaf.get(j).label; } } } for (CellHeader item : list_rowLeaf) { if (item.label.length() > 18) { item.label = item.label.substring(0, 8) + "..." + item.label.substring(item.label.length() - 8, item.label.length()); } } new_list_tableHeaders.add(list_rowLeaf); list_tableHeaders = null; list_tableHeaders = new_list_tableHeaders; } if (list_tableHeaders == null || list_tableHeaders.size() != 1) { // 说明没有表头或者多个表头 return 1; } // zhuht3...begin WindowManager windowManager = this.getWindowManager(); Display display = windowManager.getDefaultDisplay(); int ScreenWidth = display.getWidth(); int ScreenHeight = display.getHeight(); int tmpcols = list_tableHeaders.get(0).size(); if (tmpcols > 0 && tmpcols * cellWidth < ScreenWidth) { cellWidth = ScreenWidth / tmpcols; } // zhuht3...end rows_header = list_tableHeaders.size(); // cols_fixed = 1;//固定列只有一列 titleName = new String[list_tableHeaders.get(0).size()]; titleExplain = new String[list_tableHeaders.get(0).size()]; /** * 列标题名字的解释 */ // 目前只有所有表头行的列数都是一样的() CellHeader[][] dataHeader = new CellHeader[rows_header][1]; // 左上 标题 for (int i = 0; i < dataHeader.length; i++) { for (int j = 0; j < dataHeader[i].length; j++) { CellHeader cellHeader = list_tableHeaders.get(i).get(j); dataHeader[i][j] = cellHeader; cellHeader.value = cellHeader.label; titleExplain[j] = cellHeader.title; titleName[j] = cellHeader.label; if (islength) { cellHeader.width = oldWidth; } else { cellHeader.width = cellWidth; } cellHeader.heihgt = cellHeight * 4 / 3; cellHeader.bgResId = R.drawable.form_header; cellHeader.fontColor = 0xff000000; cellHeader.fontSize = font_size; if (checkIsYWSSFZL()) { cellHeader.bgResId = R.drawable.form_header_ys01; } } } // data[0][0].gravity=Cell.LEFT|Cell.BOTTOM; viewExcel.fillData(dataHeader, ViewExcel_AILK.FILL_MODE_LEFT_TITLE);//绘制左标题 cols_right = list_tableHeaders.get(0).size() - 1;// 把固定列一列去掉 // 右上固定标题 dataHeader = new CellHeader[rows_header][cols_right]; if (checkIsYWSSFZL()) { button_childChart.setVisibility(View.GONE); } for (int i = 0; i < dataHeader.length; i++) for (int j = 0; j < dataHeader[0].length; j++) { { CellHeader cellHeader = list_tableHeaders.get(0).get(j + 1); // aListCellHeader 第一个元素为固定列 所以j+1 dataHeader[i][j] = cellHeader; cellHeader.value = cellHeader.label;// 格子显示的名称和value值不同 cellHeader.width = cellWidth; cellHeader.heihgt = cellHeight * 4 / 3; titleExplain[j + 1] = cellHeader.title; titleName[j + 1] = cellHeader.label; if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_DIGIT)) { // 处理 数值列 if (aChartItemHead.sort != null && aChartItemHead.sort.equalsIgnoreCase(cellHeader.name)) { if (TextHelper.isEmpty(aChartItemHead.sortType)) { cellHeader.bgResId = R.drawable.form_header_sort; } else if (aChartItemHead.sortType.equalsIgnoreCase(Constant.ASC)) { cellHeader.isASC = true; cellHeader.bgResId = R.drawable.form_header_sort_asc; } else if (aChartItemHead.sortType.equalsIgnoreCase(Constant.DESC)) { cellHeader.isASC = false; cellHeader.bgResId = R.drawable.form_header_sort_desc; } } else { cellHeader.bgResId = R.drawable.form_header_sort; } } else { cellHeader.bgResId = R.drawable.form_header; if (checkIsYWSSFZL()) { if (cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_OPERATE)) { cellHeader.bgResId = R.drawable.form_header_ys02; } } } cellHeader.fontColor = 0xff000000; if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_OPERATE)) { // 处理操作列 if (dataReport.aList_CrollssDrill != null && dataReport.aList_CrollssDrill.size() > 0) { cellHeader.fontColor = 0xff036DCA; if (checkIsYWSSFZL()) { button_childChart.setVisibility(View.VISIBLE); } } } cellHeader.fontSize = font_size; } } viewExcel.fillData(dataHeader, ViewExcel_AILK.FILL_MODE_RIGHT_TITLE);//绘制右标题 // 左下 固定列 内容 List<Map<String, CellData>> list_reportData = dataReport.getList_reportData(); if (list_reportData == null || list_reportData.size() <= 0) { // 没有内容数据 return 2; } // 填充数据区填充数据区填充数据区填充数据区填充数据区填充数据区填充数据区填充数据区 // 左下 固定列 内容 Cell[][] data = null; { if (dataReport.total) { // 合计 多一行 data = new Cell[list_reportData.size() + 1][1]; } else { data = new Cell[list_reportData.size()][1]; } for (int i = 0; i < data.length; i++) { // 获取数据 且赋值 CellData cellData; if (i == data.length - 1 && dataReport.total) { cellData = dataReport.getMap_totalData().get(list_tableHeaders.get(0).get(0).name); } else { String name = list_tableHeaders.get(0).get(0).name;// 查询索引 cellData = list_reportData.get(i).get(name); } if (cellData == null) { // 不能取出数据 cellData = new CellData(); if (i == data.length - 1 && dataReport.total) { cellData.value = "合计"; } else { cellData.value = "-"; } } else { cellData.value = cellData.colValue;// 表格显示名称和json的名称不一致 if (TextHelper.isEmpty(cellData.value)) { cellData.value = "-"; } cellData.href = cellData.drillURL; } data[i][0] = cellData;// 对象赋值 if (islength) { cellData.width = oldWidth; } else { cellData.width = cellWidth; } cellData.heihgt = cellHeight; cellData.bgResId = R.drawable.form_right; cellData.fontColor = 0xff000000; if (!TextHelper.isEmpty(cellData.href)) { cellData.fontColor = 0xff036DCA; } cellData.fontSize = font_size; } viewExcel.fillData(data, ViewExcel_AILK.FILL_MODE_LEFT_DATA);//填充左边第一列 } // 右下内容右下内容右下内容右下内容右下内容右下内容右下内容右下内容右下内容右下内容 { // 去掉下一列 if (dataReport.total) { // 有合计就多开辟一行 data = new Cell[list_reportData.size() + 1][list_tableHeaders.get(0).size() - 1]; } else { data = new Cell[list_reportData.size()][list_tableHeaders.get(0).size() - 1]; } for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { data[i][j] = new Cell(); CellData cellData = null; CellHeader cellHeader = list_tableHeaders.get(0).get(j + 1); if (i == data.length - 1 && dataReport.total) { // 有合计且是最后一行 cellData = dataReport.getMap_totalData().get(list_tableHeaders.get(0).get(j + 1).name); } else { cellData = list_reportData.get(i).get(list_tableHeaders.get(0).get(j + 1).name); } if (cellData == null) { // 不能取出数据 cellData = new CellData(); cellData.value = "-"; data[i][j] = cellData; } else { data[i][j] = cellData; cellData.value = cellData.colValue;// 表格显示名称和json的名称不一致 cellData.href = cellData.drillURL; if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equals(Constant.COLCLASS_DIGIT)) { cellData.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT; } else if (!TextHelper.isEmpty(cellHeader.colClass) && cellHeader.colClass.equals(Constant.COLCLASS_OPERATE)) {// 操作列需要特殊处理 String str_json = cellData.drillURL; if (!TextHelper.isEmpty(str_json)) { Gson gson = new Gson(); DrillURL drillUrl = null; if (str_json.indexOf("|") != -1) { str_json = str_json.substring(0, str_json.indexOf("|")); cellData.href = str_json;// 截取有效数据 } try { drillUrl = gson.fromJson(str_json, DrillURL.class); cellData.value = drillUrl.name; } catch (Exception e) { e.printStackTrace(); } } } } cellData.width = cellWidth; cellData.heihgt = cellHeight; cellData.bgResId = R.drawable.form_right; cellData.fontColor = 0xff000000; if (cellData != null && !TextHelper.isEmpty(cellData.href)) { // 如果是能下钻的话,就把颜色的值设置成下面的颜色 cellData.fontColor = 0xff036DCA; } cellData.fontSize = font_size; } } viewExcel.fillData(data, ViewExcel_AILK.FILL_MODE_RIGHT_DATA);//填充除左起第一列之外的列数据 } return 0; } /** * 报表的选择项 */ int selectChartId = 0; /** * 报表的图选项 */ int selectChartImageId = 0; public final int DIALOG_CHART = 1;// 子报表 public final int DIALOG_Return = 2;// 子报表 public final int DIALOG_CHART_IMG = 3;// 子报表 private int totalNoPage; private Builder builder; /** * 子表切换框 */ protected Dialog onCreateDialog(int id) { Dialog dialog = null; Builder builder = null; switch (id) { case DIALOG_Return: break; case DIALOG_CHART_IMG: final String names_img[] = new String[aChartItemHead.aList_chart_graphics.size()]; for (int i = 0; i < names_img.length; i++) { names_img[i] = aChartItemHead.aList_chart_graphics.get(i).name; } // builder = new Builder(this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("切换报表图"); // 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(names_img, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { selectChartImageId = which; } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadData(); } }); builder.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { ActivityExcel.this.finish(); clearData(); // log(" public boolean onKey(DialogInterface dialog, int keyCode"); // 重新启动ExcelActivity // Intent intent = new Intent(); // intent.setClass(ExcelActivity.this, // CatalogActivity.class); // // intent.setFlags(Intent.f) // ExcelActivity.this.startActivity(intent); } return false; } }); // 创建一个单选按钮对话框 dialog = builder.create(); break; case DIALOG_CHART: // 开辟子报表的空间 final String[] names = new String[businessHandler.aChartType.chartItemHeads.size()]; for (int i = 0; i < names.length; i++) { names[i] = businessHandler.aChartType.chartItemHeads.get(i).reportName; } builder = new Builder(this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("切换子报表"); // 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(names, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { selectChartId = which; } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 添加一个确定按钮 builder.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // if (keyCode == KeyEvent.KEYCODE_BACK) { ActivityExcel.this.finish(); clearData(); // log(" public boolean onKey(DialogInterface dialog, int keyCode"); // 重新启动ExcelActivity // Intent intent = new Intent(); // intent.setClass(ExcelActivity.this, // CatalogActivity.class); // // intent.setFlags(Intent.f) // ExcelActivity.this.startActivity(intent); } return false; } }); // 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // if (aChartItemHead.tableId != selectChartId) { // // 不是当前报表,就切换子报表 // } // System.out.println("businessHandler.aChartType.chartItemHeads===size="+businessHandler.aChartType.chartItemHeads.size()+","+selectChartId+","+selectChartId); ChartItemHead tChartItemHead = null; tChartItemHead = businessHandler.aChartType.chartItemHeads.get(selectChartId); aChartItemHead.reportId = tChartItemHead.reportId; aChartItemHead.reportName = tChartItemHead.reportName; aChartItemHead.reportcycle = tChartItemHead.reportcycle; aChartItemHead.url = tChartItemHead.url; // 此报表是否有图 aChartItemHead.hasImage = tChartItemHead.hasImage; // 表创建的时间 aChartItemHead.createtime = tChartItemHead.createtime; doTaskExcel(); } }); // 创建一个单选按钮对话框 dialog = builder.create(); break; case 0:// //////////////////////时间 try { return new MyDatePickDialog(this, new OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { //onDateSet在4.X版本有重载2次的BUG,需重写onStop String date = ""; aChartItemHead._year = year; aChartItemHead._month = monthOfYear + 1; aChartItemHead._day = dayOfMonth; date += aChartItemHead._year; if (aChartItemHead._month < 10) { date += "0" + aChartItemHead._month; } else { date += "" + aChartItemHead._month; } if (aChartItemHead._day < 10) { date += "0" + aChartItemHead._day; } else { date += aChartItemHead._day; } // log("timePicker" + aChartItemHead._year + ":" // + (aChartItemHead._month + 1) + ":" // + aChartItemHead._day + " date" + date); aChartItemHead.date = date; doTaskExcel(); } }, aChartItemHead._year, aChartItemHead._month - 1, aChartItemHead._day); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } return dialog; } @Override public void onConfigurationChanged(Configuration newConfig) { // log("orientation::::" + newConfig.orientation); configurationChanged(newConfig); super.onConfigurationChanged(newConfig); } /** * @param newConfig * @Description: 横竖屏切换时调用此方法 * @author jingwen * @date 2011-8-9 下午8:08:43 */ private void configurationChanged(Configuration newConfig) { if ((newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) || (newConfig.orientation == Configuration.KEYBOARDHIDDEN_YES)) { if ((topTitle_LinearLayout != null) && (bottom_LinearLayout != null)) { topTitle_LinearLayout.setVisibility(View.GONE); bottom_LinearLayout.setVisibility(View.GONE); } } else { if ((topTitle_LinearLayout != null) && (bottom_LinearLayout != null)) { // topTitle_LinearLayout.setVisibility(View.VISIBLE); // bottom_LinearLayout.setVisibility(View.VISIBLE); topTitle_LinearLayout.setVisibility(View.VISIBLE); bottom_LinearLayout.setVisibility(View.GONE); } } } @Override public void onScrollEnvent_Top(boolean isScrollTop) { // if (isScrollTop) { if (pageNoNow > 1) { pageNoNow--; pageChange(pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } } } @Override public void onScrollEnvent_Bottom(boolean isScrollBottom) { // if (isScrollBottom) { if (pageNoNow < totalNoPage) { pageNoNow++; pageChange(pageNoNow); showToast(pageNoNow + "/" + totalNoPage + "页"); } } } @Override public void onScrollEnvent_Left(boolean isScrollLeft) { // } @Override public void onScrollEnvent_Right(boolean isScrolRight) { // // showToast("right"+pageNo); } boolean isClick; private String[] namess; int index = 0; private void colclass_operate_fun() { if (aChartItemHead.crollDrills == null || aChartItemHead.crollDrills.size() <= 0) { return; } namess = new String[aChartItemHead.crollDrills.size()];// aChartItemHead.crollDrills.; for (int i = 0; i < namess.length; i++) { namess[i] = aChartItemHead.crollDrills.get(i).name; } Builder builder = new Builder(ActivityExcel.this); // 设置对话框的图标 // builder.setIcon(R.drawable.icon); // 设置对话框的标题 builder.setTitle("请选择"); index = 0; // 跨级钻取 0: 默认第一个单选按钮被选中 builder.setSingleChoiceItems(namess, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { index = which; } }); // 跨级钻取 添加取消按钮 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); // 跨级钻取 添加一个确定按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { { Gson gosn = new Gson(); String urljson = DESUtils.decrypt(aChartItemHead.url); // log(selectIndex+"=url start==="+urljson); ReportReq req = gosn.fromJson(new StringReader(urljson), ReportReq.class); // 操作列1 跨级 DrillURL drillRul = gosn.fromJson(new StringReader(aChartItemHead.crollDrills.get(index).drillURL), DrillURL.class); // 替换 req.setReportId(drillRul.reportId); req.setWhere(drillRul.where); req.setDate(drillRul.date); urljson = gosn.toJson(req); // log("url 1 end==="+urljson); String url = DESUtils.encrypt(urljson); aChartItemHead.url = url; if (!stackJson.contains(aChartItemHead.url)) { stackName.add(aChartItemHead.crollDrills.get(index).name); stackJson.add(aChartItemHead.url); } doTaskExcel(); } } }); // 创建一个单选按钮对话框 builder.create().show(); } int colSortLast = -1; @Override public void onClickCellEnvent(Cell cell, TextView tv) { if (cell instanceof CellHeader) { CellHeader cellHeader = (CellHeader) cell; if (TextHelper.isEmpty(cellHeader.colClass)) { // cellHeader.colClass为空值 return; } if (cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_OPERATE)) { colclass_operate_fun(); } else if (cellHeader.colClass.equalsIgnoreCase(Constant.COLCLASS_DIGIT)) { Gson gosn = new Gson(); String urljson = DESUtils.decrypt(aChartItemHead.url); // log(selectIndex+"=url start==="+urljson); ReportReq req = gosn.fromJson(new StringReader(urljson), ReportReq.class); if (colSortLast != cellHeader.col) { cellHeader.isASC = false; } else { cellHeader.isASC = !cellHeader.isASC; } colSortLast = cellHeader.col; if (cellHeader.isASC) { req.sortType = Constant.ASC; cellHeader.sortType = Constant.ASC; } else { req.sortType = Constant.DESC; cellHeader.sortType = Constant.DESC; } req.sort = cellHeader.name; urljson = gosn.toJson(req); String url = DESUtils.encrypt(urljson); aChartItemHead.url = url; isNotInit = true;// 排序的时候没有 必要初始化化界面 doTaskExcel(); } } else if (!TextHelper.isEmpty(cell.href)) { // showToast(cell.href); if (cell.href != null && !cell.href.equals("")) { tv.setTextColor(0xff0000ff); aChartItemHead.level = "2";// 下一级 Gson gosn = new Gson(); DrillURL drillRul = gosn.fromJson(new StringReader(cell.href), DrillURL.class); String urljson = DESUtils.decrypt(this.businessHandler.aChartItemHead.url); ReportReq req = gosn.fromJson(new StringReader(urljson), ReportReq.class); /** * reportId 表示目标的reportId; * * desDim 表示目标报表的列替换目前报表的列; 前一个值是目前报表列;后一个值是新报表列; 如果有多个需要替换的列,用 @ * 分割; * * name:表示,显示在页面上的文字,即可以点击区显示的内容; * * where:钻取目标报表的条件; * * date:数据帐期; * * * * 如果需要钻取,生成新的请求串 方法; * * reportId 替换 原来请求串的reportId * * where 替换 原来请求串的where * * date 替换 原来请求串的 date; * */ // 替换 req.setReportId(drillRul.reportId); req.setWhere(drillRul.where); req.setDate(drillRul.date); /** * 替换 digDim dimValue为了BI的钻取 */ req.digDim = drillRul.digDim; req.dimValue = drillRul.dimValue; req.sort = ""; req.sortType = ""; // 重新组装新的json串 urljson = gosn.toJson(req); String url = DESUtils.encrypt(urljson); aChartItemHead.url = url; // 下钻 dimensionChange(aChartItemHead, null); // if (!stackJson.contains(aChartItemHead.url)) { stackName.add(cell.value); stackJson.add(aChartItemHead.url); // } } } else { if (cell.value.length() > Cell.maxLineFontNum) { showToast(cell.value); } } } @Override public void onLongClickCellEnvent(Cell cell, TextView tv) { // // if (cell instanceof CellHeader) { // Intent intent = new Intent(); // Bundle b = new Bundle(); // b.putStringArray("title", titleName);// 表体 // b.putStringArray("explain", titleExplain);// 解释 // intent.putExtras(b); // // b.putb // // intent.putExtras(extras); // intent.setClass(ActivityExcel.this, IndexesExplainActivity.class); // ActivityExcel.this.startActivity(intent); // // } } public static class MyDatePickDialog extends DatePickerDialog { public MyDatePickDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, callBack, year, monthOfYear, dayOfMonth); // TODO Auto-generated constructor stub } public MyDatePickDialog(Context context, int theme, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, theme, callBack, year, monthOfYear, dayOfMonth); // TODO Auto-generated constructor stub } @Override protected void onStop() { // TODO Auto-generated method stub } } }
70,298
0.502432
0.496055
1,914
33.22884
29.897961
558
false
false
0
0
0
0
365
0.005413
0.706897
false
false
10
05e2c86c3e04fe244e21fa4d421971fcaa195a86
36,352,603,210,408
96f480bc21f6b8dd85d10e154ba4dc856375dd23
/app/src/main/java/com/yibao/music/model/MusicStatusBean.java
3465327f390bd0e3821f2e3fa36668d6eb8c5417
[]
no_license
SagarDep/SmartisanMusicPlayer
https://github.com/SagarDep/SmartisanMusicPlayer
9a58aec6d117a6e470ca71333d147ea22f1f14f5
bb468bb3e8deda9aaf0fe9170ba9253e063968bc
refs/heads/master
2020-03-29T02:36:58.264000
2018-09-07T15:33:09
2018-09-07T15:33:09
149,445,779
0
1
null
true
2018-09-19T12:16:12
2018-09-19T12:16:09
2018-09-07T15:37:22
2018-09-07T15:37:21
19,592
0
0
0
null
false
null
package com.yibao.music.model; /** * Author:Sid * Des:${TODO} * Time:2017/8/13 06:53 * * @author Stran */ public class MusicStatusBean { /** * position 用来判断触发 MusicPlayDialogFag弹出的源头, * < 0 >表示是通知栏播放和暂停按钮发出, * 1 表示从通知栏的音乐控制面板触发弹出。从通知栏打开音列表,即整个通知栏布局的监听。 * 2 表示终止播放音乐 ,在通知栏关闭通知栏 */ public int type; public boolean isPlay; public MusicStatusBean(int type, boolean isPlay) { this.type = type; this.isPlay = isPlay; } public int getType() { return type; } public boolean isPlay() { return isPlay; } }
UTF-8
Java
774
java
MusicStatusBean.java
Java
[ { "context": "package com.yibao.music.model;\n\n/**\n * Author:Sid\n * Des:${TODO}\n * Time:2017/8/13 06:53\n *\n * @aut", "end": 49, "score": 0.6498371362686157, "start": 46, "tag": "NAME", "value": "Sid" }, { "context": " Des:${TODO}\n * Time:2017/8/13 06:53\n *\n * @author Stran\n */\npublic class MusicStatusBean {\n /**\n *", "end": 108, "score": 0.5408551692962646, "start": 103, "tag": "NAME", "value": "Stran" } ]
null
[]
package com.yibao.music.model; /** * Author:Sid * Des:${TODO} * Time:2017/8/13 06:53 * * @author Stran */ public class MusicStatusBean { /** * position 用来判断触发 MusicPlayDialogFag弹出的源头, * < 0 >表示是通知栏播放和暂停按钮发出, * 1 表示从通知栏的音乐控制面板触发弹出。从通知栏打开音列表,即整个通知栏布局的监听。 * 2 表示终止播放音乐 ,在通知栏关闭通知栏 */ public int type; public boolean isPlay; public MusicStatusBean(int type, boolean isPlay) { this.type = type; this.isPlay = isPlay; } public int getType() { return type; } public boolean isPlay() { return isPlay; } }
774
0.6
0.576667
33
17.181818
15.016061
54
false
false
0
0
0
0
0
0
0.272727
false
false
10
ea3b0224d59da1ed2ccf806df06b1de902de789d
35,588,099,019,745
251d69ef1871b5c63b3384d1ff6b4e3affb1e002
/plugins/org.corpus-tools.atomic.grideditor/src/main/java/org/corpus_tools/atomic/grideditor/commands/NewTokenHandler.java
d3a3b8d2ae1169bbe9f3c2aee95559abe0a2d82c
[ "Apache-2.0" ]
permissive
infraling/atomic
https://github.com/infraling/atomic
97c76523b6c4cb091750e70409101c5d6f66a2a7
2017c1361cbb14748d6f6cda04029ce5daa67de2
refs/heads/development
2020-05-22T04:26:49.309000
2020-01-15T18:58:29
2020-01-15T18:58:29
13,563,804
14
5
null
false
2017-10-16T09:44:23
2013-10-14T14:37:58
2017-10-06T12:14:56
2017-10-16T09:44:23
10,183
11
6
38
Java
null
null
/** * */ package org.corpus_tools.atomic.grideditor.commands; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.corpus_tools.atomic.grideditor.GridEditor; import org.corpus_tools.atomic.grideditor.data.annotationgrid.AnnotationGrid; import org.corpus_tools.atomic.grideditor.data.annotationgrid.AnnotationGrid.Row; import org.corpus_tools.atomic.grideditor.gui.TokenTextInputDialog; import org.corpus_tools.salt.SaltFactory; import org.corpus_tools.salt.common.SDocumentGraph; import org.corpus_tools.salt.common.SOrderRelation; import org.corpus_tools.salt.common.STextualDS; import org.corpus_tools.salt.common.STextualRelation; import org.corpus_tools.salt.common.SToken; import org.corpus_tools.salt.core.SRelation; import org.corpus_tools.salt.graph.Node; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.window.Window; import org.eclipse.nebula.widgets.nattable.NatTable; import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.ui.handlers.HandlerUtil; /** * // TODO Add description * Adds a token before the clicked cell, unless addafterlast. * * @author Stephan Druskat <[mail@sdruskat.net](mailto:mail@sdruskat.net)> * */ public class NewTokenHandler extends AbstractHandler { /** * - Get new token text * - Create token on graph * - Change DS * * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { NatTable table = (NatTable) ((Event) event.getTrigger()).widget; ILayerCell clickedCell = (ILayerCell) ((Object[]) ((Event) event.getTrigger()).data)[0]; final int clickIndex = clickedCell.getRowIndex(); /* * Must be a token, otherwise the command couldn't have * been fired due to MenuItemState restrictions (checks * whether clicked cell contains a token). */ SToken clickedToken = (SToken) clickedCell.getDataValue(); AnnotationGrid grid = (AnnotationGrid) ((Object[]) ((Event) event.getTrigger()).data)[1]; SDocumentGraph graph = grid.getGraph(); boolean addBeforeFirst = (boolean) ((Object[]) ((Event) event.getTrigger()).data)[2]; // Query token text String newTokenText = null; boolean addWhitespace = false; TokenTextInputDialog inputDial = new TokenTextInputDialog(Display.getDefault().getActiveShell()); if (inputDial.open() == Window.OK) { newTokenText = inputDial.getValue().trim(); addWhitespace = inputDial.addWhitespace(); } else { return null; } @SuppressWarnings("rawtypes") List<SRelation> clickedTokenOutRelations = clickedToken.getOutRelations(); STextualRelation clickedTokenTextRel = null; relLoop: for (@SuppressWarnings("rawtypes") SRelation rel : clickedTokenOutRelations) { if (rel instanceof STextualRelation) { clickedTokenTextRel = (STextualRelation) rel; break relLoop; } } // Change STextualDS STextualDS ds = clickedTokenTextRel.getTarget(); int clickedTokenEndIndex = clickedTokenTextRel.getEnd(); String originalText = ds.getText(); // Is the clicked token followed by a whitespace? boolean clickedTokenFollowedByWhitespace = originalText.substring(clickedTokenEndIndex).startsWith(" "); // Is the new token to be the new last token? boolean createNewLastToken = originalText.length() == clickedTokenEndIndex; /* * FIXME: Move to JavaDoc for method * * Unless the new token is to be the new first token, where the start * index will always be 0, the following applies. If the clicked token * is followed by a whitespace, this whitespace is preserved in the * source text, but will not be covered by the new token, i.e., the new token * text will be inserted between the clicked token and the following whitespace. */ int newTokenStartIndex = 0; if (!addBeforeFirst) { newTokenStartIndex = clickedTokenEndIndex; /* * FIXME Move to JavaDoc * * If the new token should be surrounded by whitespaces (as per * dialog setting), the new token text prefixed with a whitespace. */ if (addWhitespace) { newTokenText = " " + newTokenText; } } /* * FIXME Move to JavaDoc * * If the new token will be the new last token, i.e., will cover the end * of the data source text, no whitespace will be appended, independent * of the `addWhiteSpace` value. Else, the new token text will be * appended with a whitespace if it should be surrounded with * whitespaces and the preceding token is not already followed by a * whitespace, which would at this stage be placed after the new token. */ if (!createNewLastToken && addWhitespace && (!clickedTokenFollowedByWhitespace || addBeforeFirst)) { newTokenText = newTokenText + " "; } // Calculate the end index of the new token int newTokenTextLength = newTokenText.length(); String newText = new StringBuilder(originalText).insert(newTokenStartIndex, newTokenText).toString(); ds.setText(newText); // Change indices for following tokens List<SToken> sortedTokens = graph.getSortedTokenByText(); List<SToken> tokenChangeList = addBeforeFirst ? sortedTokens : sortedTokens.subList(clickedCell.getRowIndex() + 1, sortedTokens.size()); tokenChangeList.stream().forEach(t -> { t.getOutRelations().forEach(r -> { if (r instanceof STextualRelation) { Integer oldStart = ((STextualRelation) r).getStart(); Integer oldEnd = ((STextualRelation) r).getEnd(); ((STextualRelation) r).setStart(oldStart + newTokenTextLength); ((STextualRelation) r).setEnd(oldEnd + newTokenTextLength); } }); }); // Create new token SToken newToken = createToken(newTokenStartIndex, newTokenText, ds, graph, addBeforeFirst, clickedToken); // Update grid int key = addBeforeFirst ? 0 : clickIndex + 1; Map<Integer, Row> tempRowMap = new HashMap<>(); // For each row from key `key`, add row to temp map at key + 1 and remove it from original grid for (Iterator<Entry<Integer, Row>> iterator = grid.getRowMap().entrySet().iterator(); iterator.hasNext();) { Entry<Integer, Row> entry = iterator.next(); if (entry.getKey() >= key) { tempRowMap.put(entry.getKey() + 1, entry.getValue()); iterator.remove(); } } // Remove grid.getRowMap().remove(key); // Add the new token at `key` grid.record(key, 0, "Token", newToken); // Write the temp map entries to the original grid tempRowMap.entrySet().stream().forEach(e -> grid.getRowMap().put(e.getKey(), e.getValue())); // Refresh visualization and make editor dirty table.refresh(); ((GridEditor) HandlerUtil.getActiveEditor(event)).setDirty(true); return null; } private SToken createToken(int startIndex, String newTokenText, STextualDS ds, SDocumentGraph graph, boolean addBeforeFirst, SToken clickedToken) { SToken token = SaltFactory.createSToken(); graph.addNode(token); STextualRelation textRel = SaltFactory.createSTextualRelation(); textRel.setSource(token); textRel.setTarget(ds); textRel.setStart(startIndex); // If the new token text includes a whitespace suffix, the latter // shouldn't be covered by the SToken int tokenLength = newTokenText.endsWith(" ") ? newTokenText.length() - 1 : newTokenText.length(); int end = startIndex + tokenLength; textRel.setEnd(end); graph.addRelation(textRel); // Change/add order relations SToken nextToken = null; SOrderRelation oldOrderRelation = null; if (!addBeforeFirst) { for (SRelation<?, ?> outRel : clickedToken.getOutRelations()) { if (outRel instanceof SOrderRelation) { Node target = outRel.getTarget(); if (target instanceof SToken) { nextToken = (SToken) target; oldOrderRelation = (SOrderRelation) outRel; } } } String type = null; if (nextToken != null && oldOrderRelation != null) { oldOrderRelation.setSource(token); if (oldOrderRelation.getType() != null) { type = oldOrderRelation.getType(); } } SOrderRelation newOrderRelation = SaltFactory.createSOrderRelation(); newOrderRelation.setSource(clickedToken); newOrderRelation.setTarget(token); if (type != null) { newOrderRelation.setType(type); } graph.addRelation(newOrderRelation); } return token; } }
UTF-8
Java
8,518
java
NewTokenHandler.java
Java
[ { "context": "e clicked cell, unless addafterlast.\n *\n * @author Stephan Druskat <[mail@sdruskat.net](mailto:mail@sdruskat.net)>\n ", "end": 1409, "score": 0.9998854398727417, "start": 1394, "tag": "NAME", "value": "Stephan Druskat" }, { "context": "ess addafterlast.\n *\n * @author Stephan Druskat <[mail@sdruskat.net](mailto:mail@sdruskat.net)>\n * \n */\npublic class ", "end": 1429, "score": 0.9998975396156311, "start": 1412, "tag": "EMAIL", "value": "mail@sdruskat.net" }, { "context": "uthor Stephan Druskat <[mail@sdruskat.net](mailto:mail@sdruskat.net)>\n * \n */\npublic class NewTokenHandler extends Ab", "end": 1455, "score": 0.9998804926872253, "start": 1438, "tag": "EMAIL", "value": "mail@sdruskat.net" } ]
null
[]
/** * */ package org.corpus_tools.atomic.grideditor.commands; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.corpus_tools.atomic.grideditor.GridEditor; import org.corpus_tools.atomic.grideditor.data.annotationgrid.AnnotationGrid; import org.corpus_tools.atomic.grideditor.data.annotationgrid.AnnotationGrid.Row; import org.corpus_tools.atomic.grideditor.gui.TokenTextInputDialog; import org.corpus_tools.salt.SaltFactory; import org.corpus_tools.salt.common.SDocumentGraph; import org.corpus_tools.salt.common.SOrderRelation; import org.corpus_tools.salt.common.STextualDS; import org.corpus_tools.salt.common.STextualRelation; import org.corpus_tools.salt.common.SToken; import org.corpus_tools.salt.core.SRelation; import org.corpus_tools.salt.graph.Node; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.jface.window.Window; import org.eclipse.nebula.widgets.nattable.NatTable; import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.ui.handlers.HandlerUtil; /** * // TODO Add description * Adds a token before the clicked cell, unless addafterlast. * * @author <NAME> <[<EMAIL>](mailto:<EMAIL>)> * */ public class NewTokenHandler extends AbstractHandler { /** * - Get new token text * - Create token on graph * - Change DS * * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent) */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { NatTable table = (NatTable) ((Event) event.getTrigger()).widget; ILayerCell clickedCell = (ILayerCell) ((Object[]) ((Event) event.getTrigger()).data)[0]; final int clickIndex = clickedCell.getRowIndex(); /* * Must be a token, otherwise the command couldn't have * been fired due to MenuItemState restrictions (checks * whether clicked cell contains a token). */ SToken clickedToken = (SToken) clickedCell.getDataValue(); AnnotationGrid grid = (AnnotationGrid) ((Object[]) ((Event) event.getTrigger()).data)[1]; SDocumentGraph graph = grid.getGraph(); boolean addBeforeFirst = (boolean) ((Object[]) ((Event) event.getTrigger()).data)[2]; // Query token text String newTokenText = null; boolean addWhitespace = false; TokenTextInputDialog inputDial = new TokenTextInputDialog(Display.getDefault().getActiveShell()); if (inputDial.open() == Window.OK) { newTokenText = inputDial.getValue().trim(); addWhitespace = inputDial.addWhitespace(); } else { return null; } @SuppressWarnings("rawtypes") List<SRelation> clickedTokenOutRelations = clickedToken.getOutRelations(); STextualRelation clickedTokenTextRel = null; relLoop: for (@SuppressWarnings("rawtypes") SRelation rel : clickedTokenOutRelations) { if (rel instanceof STextualRelation) { clickedTokenTextRel = (STextualRelation) rel; break relLoop; } } // Change STextualDS STextualDS ds = clickedTokenTextRel.getTarget(); int clickedTokenEndIndex = clickedTokenTextRel.getEnd(); String originalText = ds.getText(); // Is the clicked token followed by a whitespace? boolean clickedTokenFollowedByWhitespace = originalText.substring(clickedTokenEndIndex).startsWith(" "); // Is the new token to be the new last token? boolean createNewLastToken = originalText.length() == clickedTokenEndIndex; /* * FIXME: Move to JavaDoc for method * * Unless the new token is to be the new first token, where the start * index will always be 0, the following applies. If the clicked token * is followed by a whitespace, this whitespace is preserved in the * source text, but will not be covered by the new token, i.e., the new token * text will be inserted between the clicked token and the following whitespace. */ int newTokenStartIndex = 0; if (!addBeforeFirst) { newTokenStartIndex = clickedTokenEndIndex; /* * FIXME Move to JavaDoc * * If the new token should be surrounded by whitespaces (as per * dialog setting), the new token text prefixed with a whitespace. */ if (addWhitespace) { newTokenText = " " + newTokenText; } } /* * FIXME Move to JavaDoc * * If the new token will be the new last token, i.e., will cover the end * of the data source text, no whitespace will be appended, independent * of the `addWhiteSpace` value. Else, the new token text will be * appended with a whitespace if it should be surrounded with * whitespaces and the preceding token is not already followed by a * whitespace, which would at this stage be placed after the new token. */ if (!createNewLastToken && addWhitespace && (!clickedTokenFollowedByWhitespace || addBeforeFirst)) { newTokenText = newTokenText + " "; } // Calculate the end index of the new token int newTokenTextLength = newTokenText.length(); String newText = new StringBuilder(originalText).insert(newTokenStartIndex, newTokenText).toString(); ds.setText(newText); // Change indices for following tokens List<SToken> sortedTokens = graph.getSortedTokenByText(); List<SToken> tokenChangeList = addBeforeFirst ? sortedTokens : sortedTokens.subList(clickedCell.getRowIndex() + 1, sortedTokens.size()); tokenChangeList.stream().forEach(t -> { t.getOutRelations().forEach(r -> { if (r instanceof STextualRelation) { Integer oldStart = ((STextualRelation) r).getStart(); Integer oldEnd = ((STextualRelation) r).getEnd(); ((STextualRelation) r).setStart(oldStart + newTokenTextLength); ((STextualRelation) r).setEnd(oldEnd + newTokenTextLength); } }); }); // Create new token SToken newToken = createToken(newTokenStartIndex, newTokenText, ds, graph, addBeforeFirst, clickedToken); // Update grid int key = addBeforeFirst ? 0 : clickIndex + 1; Map<Integer, Row> tempRowMap = new HashMap<>(); // For each row from key `key`, add row to temp map at key + 1 and remove it from original grid for (Iterator<Entry<Integer, Row>> iterator = grid.getRowMap().entrySet().iterator(); iterator.hasNext();) { Entry<Integer, Row> entry = iterator.next(); if (entry.getKey() >= key) { tempRowMap.put(entry.getKey() + 1, entry.getValue()); iterator.remove(); } } // Remove grid.getRowMap().remove(key); // Add the new token at `key` grid.record(key, 0, "Token", newToken); // Write the temp map entries to the original grid tempRowMap.entrySet().stream().forEach(e -> grid.getRowMap().put(e.getKey(), e.getValue())); // Refresh visualization and make editor dirty table.refresh(); ((GridEditor) HandlerUtil.getActiveEditor(event)).setDirty(true); return null; } private SToken createToken(int startIndex, String newTokenText, STextualDS ds, SDocumentGraph graph, boolean addBeforeFirst, SToken clickedToken) { SToken token = SaltFactory.createSToken(); graph.addNode(token); STextualRelation textRel = SaltFactory.createSTextualRelation(); textRel.setSource(token); textRel.setTarget(ds); textRel.setStart(startIndex); // If the new token text includes a whitespace suffix, the latter // shouldn't be covered by the SToken int tokenLength = newTokenText.endsWith(" ") ? newTokenText.length() - 1 : newTokenText.length(); int end = startIndex + tokenLength; textRel.setEnd(end); graph.addRelation(textRel); // Change/add order relations SToken nextToken = null; SOrderRelation oldOrderRelation = null; if (!addBeforeFirst) { for (SRelation<?, ?> outRel : clickedToken.getOutRelations()) { if (outRel instanceof SOrderRelation) { Node target = outRel.getTarget(); if (target instanceof SToken) { nextToken = (SToken) target; oldOrderRelation = (SOrderRelation) outRel; } } } String type = null; if (nextToken != null && oldOrderRelation != null) { oldOrderRelation.setSource(token); if (oldOrderRelation.getType() != null) { type = oldOrderRelation.getType(); } } SOrderRelation newOrderRelation = SaltFactory.createSOrderRelation(); newOrderRelation.setSource(clickedToken); newOrderRelation.setTarget(token); if (type != null) { newOrderRelation.setType(type); } graph.addRelation(newOrderRelation); } return token; } }
8,489
0.72881
0.727401
215
38.618603
29.247042
148
false
false
0
0
0
0
0
0
2.6
false
false
10
56ac4f51c744d897001c3807bd30e0892d84f956
26,740,466,455,338
331dd7eca263e8eede7d66850f77796aa067b288
/private_public_protected_default/src/com/jjt/access_levels_extra/Programeer.java
34c355de1d914aa91633412ef9753608a7d6328c
[]
no_license
kholczhauser/junior_training_solved_examples
https://github.com/kholczhauser/junior_training_solved_examples
b6a75448961adbcf8243130eeaa17d71347f60e5
4836721f6f5d92f301299253f5c19690672a5f07
refs/heads/master
2016-08-08T08:28:37.620000
2014-07-18T06:52:42
2014-07-18T06:52:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jjt.access_levels_extra; import com.jjt.access_levels.Human; /* * public class Human { private int age; public int numberOfChildren; protected String name; int heigh; } */ public class Programeer extends Human { public Programeer() { // age = 8; numberOfChildren = 5; name = "I`m a programeer"; // heigh = 4; // can`t reach height, because it is default } }
UTF-8
Java
398
java
Programeer.java
Java
[ { "context": "{\n\t\t// age = 8;\n\t\tnumberOfChildren = 5;\n\t\tname = \"I`m a programeer\"; \n\t\t// heigh = 4;\n\t\t// can`t reac", "end": 310, "score": 0.6050401329994202, "start": 309, "tag": "NAME", "value": "I" }, { "context": "/ age = 8;\n\t\tnumberOfChildren = 5;\n\t\tname = \"I`m a programeer\"; \n\t\t// heigh = 4;\n\t\t// can`t reach height, becau", "end": 325, "score": 0.8472027778625488, "start": 315, "tag": "NAME", "value": "programeer" } ]
null
[]
package com.jjt.access_levels_extra; import com.jjt.access_levels.Human; /* * public class Human { private int age; public int numberOfChildren; protected String name; int heigh; } */ public class Programeer extends Human { public Programeer() { // age = 8; numberOfChildren = 5; name = "I`m a programeer"; // heigh = 4; // can`t reach height, because it is default } }
398
0.668342
0.660804
26
14.307693
14.325258
46
false
false
0
0
0
0
0
0
0.884615
false
false
10
6267e94e9be60777f397b5a33af1bea290e80e23
32,220,844,674,862
64a895809f44a85f03748bc2854307649849f408
/java/l2n/game/model/entity/l2auction/L2AuctionConfig.java
2350d8a7c5c531fe55d46995da289f7bab008f31
[]
no_license
NoobsDevelopers/L2Nextgen
https://github.com/NoobsDevelopers/L2Nextgen
ed764229a4191e7bd69078fc81668ee70f2ba6cf
1c562199f9a428c8e467a4154242190fbb8ef51c
refs/heads/master
2016-03-23T05:31:03.207000
2015-09-02T14:48:52
2015-09-02T14:48:52
41,800,903
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package l2n.game.model.entity.l2auction; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger; /** * Конфигурация системы аукционов * Created 30.10.2009 23:15:13 * * @author Alexey Lahtadir mailto: <a href="mailto:alexey_lahtadir@mail.ru">alexey_lahtadir@mail.ru</a> */ public class L2AuctionConfig { protected static Logger logger = Logger.getLogger("l2auction"); /** Путь до конфигурационного файла */ public static final String AUCTION_CONFIG_FILE = "./config/auction.ini"; /** Ставка на лот по умолчанию */ public static int LOT_BET = 50000; /** Количество секунд, на которые увеличивает ставка время до окончания аукциона */ public static int TIME_STEP = 30; /** Номинал ставки в аденах */ public static int BET = 1; /** Количество стартовых секунд до завершения лота */ public static int START_LOT_TIME = 10 * 60; /** Минимальное количество игроков на сервере, при котором происходит публикация очередного лота */ public static int CRITICAL_MASS = 250; /** Время старта аукциона по умолчанию */ public static String DEFAULT_START_TIME = "12:00"; /** Время окончания объявления лотов */ public static String DEFAULT_STOP_TIME = "24:00"; /** Время между публикациями лотов */ public static int AUCTION_STEP_TIME = 30; /** Комиссия при возврате ставок, если лот выставлен так, чтобы проигравшие получали свои деньги обратно. */ public static int LOT_PROCENT = 30; /** Указывает - может ли участник регистрироваться на лот после того, как начальное время вышло. */ public static boolean LOT_REGISTER = true; /** Загрузка параметров из файла */ public static void load() { try { Properties auctionSettings = new Properties(); InputStream is = new FileInputStream(new File(AUCTION_CONFIG_FILE)); auctionSettings.load(is); is.close(); LOT_BET = Integer.valueOf(auctionSettings.getProperty("lot_bet", String.valueOf(LOT_BET))); TIME_STEP = Integer.valueOf(auctionSettings.getProperty("time_step", String.valueOf(TIME_STEP))); BET = Integer.valueOf(auctionSettings.getProperty("bet", String.valueOf(BET))); START_LOT_TIME = Integer.valueOf(auctionSettings.getProperty("start_lot_time", String.valueOf(START_LOT_TIME))); AUCTION_STEP_TIME = Integer.valueOf(auctionSettings.getProperty("auction_step_time", String.valueOf(AUCTION_STEP_TIME))); CRITICAL_MASS = Integer.valueOf(auctionSettings.getProperty("critical_mass", String.valueOf(CRITICAL_MASS))); DEFAULT_START_TIME = auctionSettings.getProperty("auction_start_time", DEFAULT_START_TIME); DEFAULT_STOP_TIME = auctionSettings.getProperty("auction_stop_time", DEFAULT_STOP_TIME); LOT_PROCENT = Integer.valueOf(auctionSettings.getProperty("lot_procent", String.valueOf(LOT_PROCENT))); LOT_REGISTER = Boolean.valueOf(auctionSettings.getProperty("lot_register", String.valueOf(LOT_REGISTER))); } catch(Exception e) { logger.severe(e.getMessage()); } } }
UTF-8
Java
3,543
java
L2AuctionConfig.java
Java
[ { "context": "онов\n * Created 30.10.2009 23:15:13\n * \n * @author Alexey Lahtadir mailto: <a href=\"mailto:alexey_lahtadir@mail.ru\">", "end": 285, "score": 0.9998835325241089, "start": 270, "tag": "NAME", "value": "Alexey Lahtadir" }, { "context": "* @author Alexey Lahtadir mailto: <a href=\"mailto:alexey_lahtadir@mail.ru\">alexey_lahtadir@mail.ru</a>\n */\npublic class L2A", "end": 333, "score": 0.9999335408210754, "start": 310, "tag": "EMAIL", "value": "alexey_lahtadir@mail.ru" }, { "context": " mailto: <a href=\"mailto:alexey_lahtadir@mail.ru\">alexey_lahtadir@mail.ru</a>\n */\npublic class L2AuctionConfig\n{\n\tprotected", "end": 358, "score": 0.9999352693557739, "start": 335, "tag": "EMAIL", "value": "alexey_lahtadir@mail.ru" } ]
null
[]
package l2n.game.model.entity.l2auction; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger; /** * Конфигурация системы аукционов * Created 30.10.2009 23:15:13 * * @author <NAME> mailto: <a href="mailto:<EMAIL>"><EMAIL></a> */ public class L2AuctionConfig { protected static Logger logger = Logger.getLogger("l2auction"); /** Путь до конфигурационного файла */ public static final String AUCTION_CONFIG_FILE = "./config/auction.ini"; /** Ставка на лот по умолчанию */ public static int LOT_BET = 50000; /** Количество секунд, на которые увеличивает ставка время до окончания аукциона */ public static int TIME_STEP = 30; /** Номинал ставки в аденах */ public static int BET = 1; /** Количество стартовых секунд до завершения лота */ public static int START_LOT_TIME = 10 * 60; /** Минимальное количество игроков на сервере, при котором происходит публикация очередного лота */ public static int CRITICAL_MASS = 250; /** Время старта аукциона по умолчанию */ public static String DEFAULT_START_TIME = "12:00"; /** Время окончания объявления лотов */ public static String DEFAULT_STOP_TIME = "24:00"; /** Время между публикациями лотов */ public static int AUCTION_STEP_TIME = 30; /** Комиссия при возврате ставок, если лот выставлен так, чтобы проигравшие получали свои деньги обратно. */ public static int LOT_PROCENT = 30; /** Указывает - может ли участник регистрироваться на лот после того, как начальное время вышло. */ public static boolean LOT_REGISTER = true; /** Загрузка параметров из файла */ public static void load() { try { Properties auctionSettings = new Properties(); InputStream is = new FileInputStream(new File(AUCTION_CONFIG_FILE)); auctionSettings.load(is); is.close(); LOT_BET = Integer.valueOf(auctionSettings.getProperty("lot_bet", String.valueOf(LOT_BET))); TIME_STEP = Integer.valueOf(auctionSettings.getProperty("time_step", String.valueOf(TIME_STEP))); BET = Integer.valueOf(auctionSettings.getProperty("bet", String.valueOf(BET))); START_LOT_TIME = Integer.valueOf(auctionSettings.getProperty("start_lot_time", String.valueOf(START_LOT_TIME))); AUCTION_STEP_TIME = Integer.valueOf(auctionSettings.getProperty("auction_step_time", String.valueOf(AUCTION_STEP_TIME))); CRITICAL_MASS = Integer.valueOf(auctionSettings.getProperty("critical_mass", String.valueOf(CRITICAL_MASS))); DEFAULT_START_TIME = auctionSettings.getProperty("auction_start_time", DEFAULT_START_TIME); DEFAULT_STOP_TIME = auctionSettings.getProperty("auction_stop_time", DEFAULT_STOP_TIME); LOT_PROCENT = Integer.valueOf(auctionSettings.getProperty("lot_procent", String.valueOf(LOT_PROCENT))); LOT_REGISTER = Boolean.valueOf(auctionSettings.getProperty("lot_register", String.valueOf(LOT_REGISTER))); } catch(Exception e) { logger.severe(e.getMessage()); } } }
3,502
0.744389
0.729313
68
42.89706
36.171623
124
false
false
0
0
0
0
0
0
1.941176
false
false
10
ba2f4d4b4d271a43e48fc2dcf372e19078da0301
9,380,208,609,561
dc36fcd2611451066cb13755a37b7b2a7c7ac279
/src/PgkPresentacion/FrmPublicarInmueble.java
7068a532a88b9e992829626689ccf7d24e5004f5
[]
no_license
BrisetGarcia1/py_RedSocialInmobiliaria
https://github.com/BrisetGarcia1/py_RedSocialInmobiliaria
bbaec3929c36ead8b8af0d1f52b0762e003de97f
4b17897c243ab2141d4c864967185fa7adc6fa7f
refs/heads/main
2023-07-17T20:33:12.014000
2021-08-19T23:20:04
2021-08-19T23:20:04
398,098,199
1
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 PgkPresentacion; import PkgEntidad.ClsInmuebleE; import PkgEntidad.ClsPersonaE; import PkgNegocio.ClsInmuebleN; import PkgNegocio.ClsPersonaN; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author smoke */ public class FrmPublicarInmueble extends javax.swing.JInternalFrame { /** * Creates new form FrmPublicarInmueble1 */ public static int seleccion; public DefaultTableModel modelo; public FrmPublicarInmueble() { initComponents(); tbinmueble.setDefaultRenderer(Object.class,new RenderTabla()); MtdListarNopublicados(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tbinmueble = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); txtId = new LIB.FSTexFieldMD(); txtDireccion = new LIB.FSTexFieldMD(); txtNumHabitaciones = new LIB.FSTexFieldMD(); txtCiudad = new LIB.FSTexFieldMD(); txtPrecio = new LIB.FSTexFieldMD(); jLabel8 = new javax.swing.JLabel(); txtTipo = new LIB.FSTexFieldMD(); btnPublicarInmueble = new LIB.FSButtonMD(); jEImagePanel1 = new LIB.JEImagePanel(); jLabel9 = new javax.swing.JLabel(); txtDescripcion = new LIB.FSTexFieldMD(); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setText("Publicar Inmueble"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 0, 310, 50)); tbinmueble.setBorder(new javax.swing.border.MatteBorder(null)); tbinmueble.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tbinmueble.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbinmuebleMouseClicked(evt); } }); jScrollPane1.setViewportView(tbinmueble); jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, 760, 190)); jLabel2.setText("Id Inmueble:"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 270, -1, -1)); jLabel3.setText("Direccion:"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 320, -1, -1)); jLabel4.setText("Nro de Habitaciones:"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 360, -1, -1)); jLabel5.setText("Ciudad:"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 410, -1, -1)); jLabel6.setText("Tipo:"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 460, -1, -1)); jLabel7.setText("Descripcion:"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 330, -1, -1)); txtId.setEditable(false); txtId.setForeground(new java.awt.Color(51, 51, 51)); txtId.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtId.setPlaceholder("0"); jPanel1.add(txtId, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 250, 160, 40)); txtDireccion.setEditable(false); txtDireccion.setForeground(new java.awt.Color(51, 51, 51)); txtDireccion.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtDireccion.setPlaceholder("Av. Pinto 1000"); jPanel1.add(txtDireccion, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 300, 160, 40)); txtNumHabitaciones.setEditable(false); txtNumHabitaciones.setForeground(new java.awt.Color(51, 51, 51)); txtNumHabitaciones.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtNumHabitaciones.setPlaceholder("2"); jPanel1.add(txtNumHabitaciones, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 350, 160, 40)); txtCiudad.setEditable(false); txtCiudad.setForeground(new java.awt.Color(51, 51, 51)); txtCiudad.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtCiudad.setPlaceholder("Tacna"); jPanel1.add(txtCiudad, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 400, 160, 40)); txtPrecio.setEditable(false); txtPrecio.setForeground(new java.awt.Color(51, 51, 51)); txtPrecio.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtPrecio.setPlaceholder("S/. 999"); jPanel1.add(txtPrecio, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 250, 160, 40)); jLabel8.setText("Precio:"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 270, -1, -1)); txtTipo.setEditable(false); txtTipo.setForeground(new java.awt.Color(51, 51, 51)); txtTipo.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtTipo.setPlaceholder("Departamento"); jPanel1.add(txtTipo, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 450, 160, 40)); btnPublicarInmueble.setBackground(new java.awt.Color(0, 0, 0)); btnPublicarInmueble.setBorder(new javax.swing.border.MatteBorder(null)); btnPublicarInmueble.setText("Publicar Inmueble"); btnPublicarInmueble.setColorNormal(new java.awt.Color(0, 0, 0)); btnPublicarInmueble.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPublicarInmuebleActionPerformed(evt); } }); jPanel1.add(btnPublicarInmueble, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 470, -1, -1)); jEImagePanel1.setBorder(new javax.swing.border.MatteBorder(null)); javax.swing.GroupLayout jEImagePanel1Layout = new javax.swing.GroupLayout(jEImagePanel1); jEImagePanel1.setLayout(jEImagePanel1Layout); jEImagePanel1Layout.setHorizontalGroup( jEImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 158, Short.MAX_VALUE) ); jEImagePanel1Layout.setVerticalGroup( jEImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 158, Short.MAX_VALUE) ); jPanel1.add(jEImagePanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 270, 160, 160)); jLabel9.setText("Imagen"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(840, 460, -1, -1)); txtDescripcion.setEditable(false); txtDescripcion.setForeground(new java.awt.Color(51, 51, 51)); txtDescripcion.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtDescripcion.setPlaceholder("Departamento"); jPanel1.add(txtDescripcion, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 300, 160, 130)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 798, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tbinmuebleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbinmuebleMouseClicked // TODO add your handling code here: seleccion = tbinmueble.rowAtPoint(evt.getPoint()); txtId.setText(String.valueOf(tbinmueble.getValueAt(seleccion,0))); txtDireccion.setText(String.valueOf(tbinmueble.getValueAt(seleccion,2))); txtNumHabitaciones.setText(String.valueOf(tbinmueble.getValueAt(seleccion,4))); txtCiudad.setText(String.valueOf(tbinmueble.getValueAt(seleccion,5))); txtDescripcion.setText(String.valueOf(tbinmueble.getValueAt(seleccion,6))); txtTipo.setText(String.valueOf(tbinmueble.getValueAt(seleccion,7))); txtPrecio.setText(String.valueOf(tbinmueble.getValueAt(seleccion,8))); }//GEN-LAST:event_tbinmuebleMouseClicked private void btnPublicarInmuebleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPublicarInmuebleActionPerformed // TODO add your handling code here: ClsInmuebleE objInmE=new ClsInmuebleE(); ClsInmuebleN objInmN=new ClsInmuebleN(); objInmE.setInmuebleid(Integer.parseInt(txtId.getText())); objInmE.setEstado("Publicado"); if (objInmN.MtdAcPublicarInmueble(objInmE)== true) { JOptionPane.showMessageDialog(null, "Inmueble Publicado Correctamente..."); MtdLimpiar(); MtdListarNopublicados(); }else{ JOptionPane.showMessageDialog(null, "Error de Datos..."); } }//GEN-LAST:event_btnPublicarInmuebleActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private LIB.FSButtonMD btnPublicarInmueble; private LIB.JEImagePanel jEImagePanel1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tbinmueble; private LIB.FSTexFieldMD txtCiudad; private LIB.FSTexFieldMD txtDescripcion; private LIB.FSTexFieldMD txtDireccion; private LIB.FSTexFieldMD txtId; private LIB.FSTexFieldMD txtNumHabitaciones; private LIB.FSTexFieldMD txtPrecio; private LIB.FSTexFieldMD txtTipo; // End of variables declaration//GEN-END:variables private void MtdListarNopublicados() { modelo=new DefaultTableModel(); modelo.addColumn("CODIGO"); modelo.addColumn("COD_USUARIO"); modelo.addColumn("DIRECCION"); modelo.addColumn("ESTADO"); modelo.addColumn("NroHABITACIONES"); modelo.addColumn("CIUDAD"); modelo.addColumn("DESCRIOCION"); modelo.addColumn("CATEGORIA"); modelo.addColumn("PRECIO"); modelo.addColumn("FOTO"); ClsInmuebleN objInmuebleN=new ClsInmuebleN(); Object[] datos=new Object[10]; for (ClsInmuebleE objInmE : objInmuebleN.MtdListarInmuebleNoPublicado()) { datos[0]=String.valueOf(objInmE.getInmuebleid()); datos[1]=String.valueOf(objInmE.getUsuarioid()); datos[2]=objInmE.getDireccioninmueble(); datos[3]=objInmE.getEstado(); datos[4]=String.valueOf(objInmE .getNrohabitaciones()); datos[5]=objInmE.getCiudad(); datos[6]=objInmE.getDescripcion(); datos[7]=objInmE.getCategoria(); datos[8]=String.valueOf(objInmE.getPrecio()); try{ byte[] bi = objInmE.getFoto(); BufferedImage image = null; InputStream in = new ByteArrayInputStream(bi); image = ImageIO.read(in); ImageIcon imgi = new ImageIcon(image.getScaledInstance(60, 60, 0)); datos[9] = new JLabel(imgi); }catch(Exception ex){ datos[9] = new JLabel("No imagen"); } modelo.addRow(datos); } this.tbinmueble.setModel(modelo); } private void MtdLimpiar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
UTF-8
Java
13,521
java
FrmPublicarInmueble.java
Java
[ { "context": ".swing.table.DefaultTableModel;\n\n/**\n *\n * @author smoke\n */\npublic class FrmPublicarInmueble extends java", "end": 626, "score": 0.9995359778404236, "start": 621, "tag": "USERNAME", "value": "smoke" } ]
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 PgkPresentacion; import PkgEntidad.ClsInmuebleE; import PkgEntidad.ClsPersonaE; import PkgNegocio.ClsInmuebleN; import PkgNegocio.ClsPersonaN; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author smoke */ public class FrmPublicarInmueble extends javax.swing.JInternalFrame { /** * Creates new form FrmPublicarInmueble1 */ public static int seleccion; public DefaultTableModel modelo; public FrmPublicarInmueble() { initComponents(); tbinmueble.setDefaultRenderer(Object.class,new RenderTabla()); MtdListarNopublicados(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tbinmueble = new javax.swing.JTable(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); txtId = new LIB.FSTexFieldMD(); txtDireccion = new LIB.FSTexFieldMD(); txtNumHabitaciones = new LIB.FSTexFieldMD(); txtCiudad = new LIB.FSTexFieldMD(); txtPrecio = new LIB.FSTexFieldMD(); jLabel8 = new javax.swing.JLabel(); txtTipo = new LIB.FSTexFieldMD(); btnPublicarInmueble = new LIB.FSButtonMD(); jEImagePanel1 = new LIB.JEImagePanel(); jLabel9 = new javax.swing.JLabel(); txtDescripcion = new LIB.FSTexFieldMD(); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setText("Publicar Inmueble"); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 0, 310, 50)); tbinmueble.setBorder(new javax.swing.border.MatteBorder(null)); tbinmueble.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tbinmueble.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbinmuebleMouseClicked(evt); } }); jScrollPane1.setViewportView(tbinmueble); jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 50, 760, 190)); jLabel2.setText("Id Inmueble:"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 270, -1, -1)); jLabel3.setText("Direccion:"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 320, -1, -1)); jLabel4.setText("Nro de Habitaciones:"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 360, -1, -1)); jLabel5.setText("Ciudad:"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 410, -1, -1)); jLabel6.setText("Tipo:"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 460, -1, -1)); jLabel7.setText("Descripcion:"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 330, -1, -1)); txtId.setEditable(false); txtId.setForeground(new java.awt.Color(51, 51, 51)); txtId.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtId.setPlaceholder("0"); jPanel1.add(txtId, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 250, 160, 40)); txtDireccion.setEditable(false); txtDireccion.setForeground(new java.awt.Color(51, 51, 51)); txtDireccion.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtDireccion.setPlaceholder("Av. Pinto 1000"); jPanel1.add(txtDireccion, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 300, 160, 40)); txtNumHabitaciones.setEditable(false); txtNumHabitaciones.setForeground(new java.awt.Color(51, 51, 51)); txtNumHabitaciones.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtNumHabitaciones.setPlaceholder("2"); jPanel1.add(txtNumHabitaciones, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 350, 160, 40)); txtCiudad.setEditable(false); txtCiudad.setForeground(new java.awt.Color(51, 51, 51)); txtCiudad.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtCiudad.setPlaceholder("Tacna"); jPanel1.add(txtCiudad, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 400, 160, 40)); txtPrecio.setEditable(false); txtPrecio.setForeground(new java.awt.Color(51, 51, 51)); txtPrecio.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtPrecio.setPlaceholder("S/. 999"); jPanel1.add(txtPrecio, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 250, 160, 40)); jLabel8.setText("Precio:"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 270, -1, -1)); txtTipo.setEditable(false); txtTipo.setForeground(new java.awt.Color(51, 51, 51)); txtTipo.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtTipo.setPlaceholder("Departamento"); jPanel1.add(txtTipo, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 450, 160, 40)); btnPublicarInmueble.setBackground(new java.awt.Color(0, 0, 0)); btnPublicarInmueble.setBorder(new javax.swing.border.MatteBorder(null)); btnPublicarInmueble.setText("Publicar Inmueble"); btnPublicarInmueble.setColorNormal(new java.awt.Color(0, 0, 0)); btnPublicarInmueble.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPublicarInmuebleActionPerformed(evt); } }); jPanel1.add(btnPublicarInmueble, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 470, -1, -1)); jEImagePanel1.setBorder(new javax.swing.border.MatteBorder(null)); javax.swing.GroupLayout jEImagePanel1Layout = new javax.swing.GroupLayout(jEImagePanel1); jEImagePanel1.setLayout(jEImagePanel1Layout); jEImagePanel1Layout.setHorizontalGroup( jEImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 158, Short.MAX_VALUE) ); jEImagePanel1Layout.setVerticalGroup( jEImagePanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 158, Short.MAX_VALUE) ); jPanel1.add(jEImagePanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(600, 270, 160, 160)); jLabel9.setText("Imagen"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(840, 460, -1, -1)); txtDescripcion.setEditable(false); txtDescripcion.setForeground(new java.awt.Color(51, 51, 51)); txtDescripcion.setBordeColorFocus(new java.awt.Color(102, 153, 255)); txtDescripcion.setPlaceholder("Departamento"); jPanel1.add(txtDescripcion, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 300, 160, 130)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 798, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void tbinmuebleMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbinmuebleMouseClicked // TODO add your handling code here: seleccion = tbinmueble.rowAtPoint(evt.getPoint()); txtId.setText(String.valueOf(tbinmueble.getValueAt(seleccion,0))); txtDireccion.setText(String.valueOf(tbinmueble.getValueAt(seleccion,2))); txtNumHabitaciones.setText(String.valueOf(tbinmueble.getValueAt(seleccion,4))); txtCiudad.setText(String.valueOf(tbinmueble.getValueAt(seleccion,5))); txtDescripcion.setText(String.valueOf(tbinmueble.getValueAt(seleccion,6))); txtTipo.setText(String.valueOf(tbinmueble.getValueAt(seleccion,7))); txtPrecio.setText(String.valueOf(tbinmueble.getValueAt(seleccion,8))); }//GEN-LAST:event_tbinmuebleMouseClicked private void btnPublicarInmuebleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPublicarInmuebleActionPerformed // TODO add your handling code here: ClsInmuebleE objInmE=new ClsInmuebleE(); ClsInmuebleN objInmN=new ClsInmuebleN(); objInmE.setInmuebleid(Integer.parseInt(txtId.getText())); objInmE.setEstado("Publicado"); if (objInmN.MtdAcPublicarInmueble(objInmE)== true) { JOptionPane.showMessageDialog(null, "Inmueble Publicado Correctamente..."); MtdLimpiar(); MtdListarNopublicados(); }else{ JOptionPane.showMessageDialog(null, "Error de Datos..."); } }//GEN-LAST:event_btnPublicarInmuebleActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private LIB.FSButtonMD btnPublicarInmueble; private LIB.JEImagePanel jEImagePanel1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tbinmueble; private LIB.FSTexFieldMD txtCiudad; private LIB.FSTexFieldMD txtDescripcion; private LIB.FSTexFieldMD txtDireccion; private LIB.FSTexFieldMD txtId; private LIB.FSTexFieldMD txtNumHabitaciones; private LIB.FSTexFieldMD txtPrecio; private LIB.FSTexFieldMD txtTipo; // End of variables declaration//GEN-END:variables private void MtdListarNopublicados() { modelo=new DefaultTableModel(); modelo.addColumn("CODIGO"); modelo.addColumn("COD_USUARIO"); modelo.addColumn("DIRECCION"); modelo.addColumn("ESTADO"); modelo.addColumn("NroHABITACIONES"); modelo.addColumn("CIUDAD"); modelo.addColumn("DESCRIOCION"); modelo.addColumn("CATEGORIA"); modelo.addColumn("PRECIO"); modelo.addColumn("FOTO"); ClsInmuebleN objInmuebleN=new ClsInmuebleN(); Object[] datos=new Object[10]; for (ClsInmuebleE objInmE : objInmuebleN.MtdListarInmuebleNoPublicado()) { datos[0]=String.valueOf(objInmE.getInmuebleid()); datos[1]=String.valueOf(objInmE.getUsuarioid()); datos[2]=objInmE.getDireccioninmueble(); datos[3]=objInmE.getEstado(); datos[4]=String.valueOf(objInmE .getNrohabitaciones()); datos[5]=objInmE.getCiudad(); datos[6]=objInmE.getDescripcion(); datos[7]=objInmE.getCategoria(); datos[8]=String.valueOf(objInmE.getPrecio()); try{ byte[] bi = objInmE.getFoto(); BufferedImage image = null; InputStream in = new ByteArrayInputStream(bi); image = ImageIO.read(in); ImageIcon imgi = new ImageIcon(image.getScaledInstance(60, 60, 0)); datos[9] = new JLabel(imgi); }catch(Exception ex){ datos[9] = new JLabel("No imagen"); } modelo.addRow(datos); } this.tbinmueble.setModel(modelo); } private void MtdLimpiar() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
13,521
0.670143
0.638192
302
43.771523
30.254179
137
false
false
0
0
0
0
0
0
1.145695
false
false
10
a6231cd6e87d4d7ffe6280a3969ffc9e0012cd05
33,088,428,114,080
e1b9d24bc7dce445e62e3da3e195dbd6766c23d5
/src/com/project/restaurant/my/Counter.java
2b86ea84b9b76c7eb11946c064cb308dc7029efe
[]
no_license
Sharatmaharjan/All1
https://github.com/Sharatmaharjan/All1
5ebf163f8a3d86f755352de8c6744dadfa102067
9b406ef6124b9128856825b4ae8e49eeee049a59
refs/heads/master
2021-01-22T17:39:37.716000
2017-03-15T04:19:59
2017-03-15T04:19:59
85,028,461
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.project.restaurant.my; import java.util.Scanner; public class Counter { public static void payMessage(){ System.out.println("Please enter P to pay your bill"); } public static void calculateTotalAmount(){ Scanner scanner=new Scanner(System.in); String pay=scanner.nextLine(); while(!pay.equalsIgnoreCase("p")){ System.out.println("Please enter P to pay your bill."); pay=scanner.nextLine(); } if(pay.equalsIgnoreCase("p")){ double amount=Waiter.itemsOrdered(); if(amount==1){ System.out.println("Your total amount is "+100); } else if (amount==2){ System.out.println("Your total amount is "+120); } else{ System.out.println("Your total amount is "+250); } } } }
UTF-8
Java
764
java
Counter.java
Java
[]
null
[]
package com.project.restaurant.my; import java.util.Scanner; public class Counter { public static void payMessage(){ System.out.println("Please enter P to pay your bill"); } public static void calculateTotalAmount(){ Scanner scanner=new Scanner(System.in); String pay=scanner.nextLine(); while(!pay.equalsIgnoreCase("p")){ System.out.println("Please enter P to pay your bill."); pay=scanner.nextLine(); } if(pay.equalsIgnoreCase("p")){ double amount=Waiter.itemsOrdered(); if(amount==1){ System.out.println("Your total amount is "+100); } else if (amount==2){ System.out.println("Your total amount is "+120); } else{ System.out.println("Your total amount is "+250); } } } }
764
0.650524
0.636126
30
23.466667
19.469177
58
false
false
0
0
0
0
0
0
2.266667
false
false
10
e5b4503e9f3c64a48ac9e71ca7826bf283c9129f
27,762,668,633,812
e60158032a879394ab66021733c70ed68ebe9f8b
/src/main/java/Main.java
a6df3d8886dfe5d3b9a316726c0bfd1b4a6bf36a
[]
no_license
xxMartinezz/Hibernate_RentalCar
https://github.com/xxMartinezz/Hibernate_RentalCar
d86889a84acd9512abf1bc286b88e381dd223560
bbcddc46658089037b8e90f6b52b0f5ae70f427d
refs/heads/master
2020-06-14T21:23:23.322000
2019-07-03T21:47:47
2019-07-03T21:47:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.persistence.EntityManager; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class Main { public static void main(String[] args) throws ParseException { EntityManager em = HibernateUtil.getEntityManager(); //tworzenie obiektow typu Car CarDao carDao = new CarDao(em); Car car1 = new Car(); Car car2 = new Car(); Car car3 = new Car(); //tworzenie obiektow typu Customer CustomerDao customerDao = new CustomerDao(em); Customer customer1 = new Customer(); Customer customer2 = new Customer(); Customer customer3 = new Customer(); //tworzenie adresow Address address1 = new Address("Polska", "Wrocław", "Grunwaldzka", "121"); Address address2 = new Address("Polska", "Wrocław", "Strzegomska", "321"); Address address3 = new Address("Polska", "Wrocław", "Prusa", "564"); Address address4 = new Address("Polska", "Wrocław", "Reja", "433"); //tworzenie dat Date date1 = new SimpleDateFormat("dd-MM-yyyy").parse("12-03-2018"); Date date2 = new SimpleDateFormat("dd-MM-yyyy").parse("13-03-2018"); Date date3 = new SimpleDateFormat("dd-MM-yyyy").parse("23-03-2018"); Date TRdate1 = new SimpleDateFormat("dd-MM-yyyy").parse("11-01-2018"); Date TRdate2 = new SimpleDateFormat("dd-MM-yyyy").parse("11-01-2019"); //ustawianie pol obiektow car1.setName("Fiat"); car1.setPlates("XXX1234"); car1.setAvailable(true); car1.setNumberOfSeats(5); car1.setColor(Color.GREEN); car1.setCarType(CarType.HATCHBACK); car1.setRentalDates(Collections.singleton(date1)); car1.setRentalAddress(Collections.singletonList(address1)); car1.getCustomers().add(customer3); car1.getCustomers().add(customer2); carDao.save(car1); car2.setName("Ford"); car2.setPlates("YYY1234"); car2.setAvailable(false); car2.setNumberOfSeats(5); car2.setColor(Color.BLUE); car2.setCarType(CarType.HATCHBACK); car2.setRentalDates(Collections.singleton(date2)); car2.setRentalAddress(Collections.singletonList(address1)); carDao.save(car2); car3.setName(" BMW"); car3.setPlates("ZZZ1234"); car3.setAvailable(true); car3.setNumberOfSeats(5); car3.setColor(Color.BLACK); car3.setCarType(CarType.SEDAN); car3.setRentalDates(Collections.singleton(date3)); car3.setRentalAddress(Collections.singletonList(address1)); carDao.save(car3); customer1.setName("Marian"); customer1.setSurname("Nowak"); customer1.setAge(46); customer1.setAddress(address2); customerDao.save(customer1); customer2.setName("Krzysztof"); customer2.setSurname("Kowalski"); customer2.setAge(47); customer2.setAddress(address3); customerDao.save(customer2); customer3.setName("Anna"); customer3.setSurname("Jankowska"); customer3.setAge(32); customer3.setAddress(address4); customer3.getCars().add(car1); customer3.getCars().add(car2); customerDao.save(customer3); //relacja OneToOne Rental - Invoice Invoice invoice = new Invoice(); invoice.setInvoiceNumber("F-VAT-01/2018"); invoice.setDate(new Date()); Rental rental = new Rental(); rental.setDateFrom(new Date()); // add reference from source (rental) to target (invoice) rental.setInvoice(invoice); // add reversed reference from target to source invoice.setRental(rental); RentalDao rentalDao = new RentalDao(em); rentalDao.save(rental); //relacja OneToMany Car - TechnicalReview //Car audi = new Car("Audi", Color.RED, CarType.HATCHBACK); TechnicalReview TechRev1 = new TechnicalReview(TechnicalReviewResultEnum.PASSED, TRdate1, TRdate2); TechnicalReview TechRev2 = new TechnicalReview(TechnicalReviewResultEnum.FAILED, TRdate2, null); car1.getTechnicalReview().add(TechRev1); car1.getTechnicalReview().add(TechRev2); carDao.save(car1); //dodawanie do bazy danych em.getTransaction().begin(); em.getTransaction().commit(); //System.out.println(customerDao.findAll()); //System.out.println(carDao.findAll()); //System.out.println("Wyszukanie auta o podanym numerze: " + carDao.findByPlate("QQQ1234")); //System.out.println(carDao.isAvailable()); //System.out.println(customerDao.findByNameAndSurname("Krzysztof", "Kowalski")); //System.out.println(customerDao.findAll()); //System.out.println(rentalDao.findAll()); //System.out.println(car1.getTechnicalReview()); //System.out.println(customer3.getCars()); System.out.println(car1.getCustomers()); em.close(); } }
UTF-8
Java
5,048
java
Main.java
Java
[ { "context": " //ustawianie pol obiektow\n car1.setName(\"Fiat\");\n car1.setPlates(\"XXX1234\");\n car", "end": 1510, "score": 0.9995759725570679, "start": 1506, "tag": "NAME", "value": "Fiat" }, { "context": " carDao.save(car1);\n\n car2.setName(\"Ford\");\n car2.setPlates(\"YYY1234\");\n car", "end": 1965, "score": 0.9940347075462341, "start": 1961, "tag": "NAME", "value": "Ford" }, { "context": " carDao.save(car2);\n\n car3.setName(\" BMW\");\n car3.setPlates(\"ZZZ1234\");\n car", "end": 2332, "score": 0.7494637370109558, "start": 2330, "tag": "NAME", "value": "MW" }, { "context": " carDao.save(car3);\n\n customer1.setName(\"Marian\");\n customer1.setSurname(\"Nowak\");\n ", "end": 2702, "score": 0.9998517036437988, "start": 2696, "tag": "NAME", "value": "Marian" }, { "context": ".setName(\"Marian\");\n customer1.setSurname(\"Nowak\");\n customer1.setAge(46);\n customer", "end": 2741, "score": 0.9982299208641052, "start": 2736, "tag": "NAME", "value": "Nowak" }, { "context": "rDao.save(customer1);\n\n customer2.setName(\"Krzysztof\");\n customer2.setSurname(\"Kowalski\");\n ", "end": 2889, "score": 0.9998464584350586, "start": 2880, "tag": "NAME", "value": "Krzysztof" }, { "context": "tName(\"Krzysztof\");\n customer2.setSurname(\"Kowalski\");\n customer2.setAge(47);\n customer", "end": 2931, "score": 0.9203235507011414, "start": 2923, "tag": "NAME", "value": "Kowalski" }, { "context": "rDao.save(customer2);\n\n customer3.setName(\"Anna\");\n customer3.setSurname(\"Jankowska\");\n ", "end": 3074, "score": 0.9998390674591064, "start": 3070, "tag": "NAME", "value": "Anna" }, { "context": "r3.setName(\"Anna\");\n customer3.setSurname(\"Jankowska\");\n customer3.setAge(32);\n customer", "end": 3117, "score": 0.9981541633605957, "start": 3108, "tag": "NAME", "value": "Jankowska" }, { "context": "r - TechnicalReview\n //Car audi = new Car(\"Audi\", Color.RED, CarType.HATCHBACK);\n Technica", "end": 3917, "score": 0.9994529485702515, "start": 3913, "tag": "NAME", "value": "Audi" }, { "context": "tem.out.println(customerDao.findByNameAndSurname(\"Krzysztof\", \"Kowalski\"));\n\n //System.out.println(cus", "end": 4732, "score": 0.9995419383049011, "start": 4723, "tag": "NAME", "value": "Krzysztof" }, { "context": "ln(customerDao.findByNameAndSurname(\"Krzysztof\", \"Kowalski\"));\n\n //System.out.println(customerDao.fin", "end": 4744, "score": 0.9981129765510559, "start": 4736, "tag": "NAME", "value": "Kowalski" } ]
null
[]
import javax.persistence.EntityManager; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class Main { public static void main(String[] args) throws ParseException { EntityManager em = HibernateUtil.getEntityManager(); //tworzenie obiektow typu Car CarDao carDao = new CarDao(em); Car car1 = new Car(); Car car2 = new Car(); Car car3 = new Car(); //tworzenie obiektow typu Customer CustomerDao customerDao = new CustomerDao(em); Customer customer1 = new Customer(); Customer customer2 = new Customer(); Customer customer3 = new Customer(); //tworzenie adresow Address address1 = new Address("Polska", "Wrocław", "Grunwaldzka", "121"); Address address2 = new Address("Polska", "Wrocław", "Strzegomska", "321"); Address address3 = new Address("Polska", "Wrocław", "Prusa", "564"); Address address4 = new Address("Polska", "Wrocław", "Reja", "433"); //tworzenie dat Date date1 = new SimpleDateFormat("dd-MM-yyyy").parse("12-03-2018"); Date date2 = new SimpleDateFormat("dd-MM-yyyy").parse("13-03-2018"); Date date3 = new SimpleDateFormat("dd-MM-yyyy").parse("23-03-2018"); Date TRdate1 = new SimpleDateFormat("dd-MM-yyyy").parse("11-01-2018"); Date TRdate2 = new SimpleDateFormat("dd-MM-yyyy").parse("11-01-2019"); //ustawianie pol obiektow car1.setName("Fiat"); car1.setPlates("XXX1234"); car1.setAvailable(true); car1.setNumberOfSeats(5); car1.setColor(Color.GREEN); car1.setCarType(CarType.HATCHBACK); car1.setRentalDates(Collections.singleton(date1)); car1.setRentalAddress(Collections.singletonList(address1)); car1.getCustomers().add(customer3); car1.getCustomers().add(customer2); carDao.save(car1); car2.setName("Ford"); car2.setPlates("YYY1234"); car2.setAvailable(false); car2.setNumberOfSeats(5); car2.setColor(Color.BLUE); car2.setCarType(CarType.HATCHBACK); car2.setRentalDates(Collections.singleton(date2)); car2.setRentalAddress(Collections.singletonList(address1)); carDao.save(car2); car3.setName(" BMW"); car3.setPlates("ZZZ1234"); car3.setAvailable(true); car3.setNumberOfSeats(5); car3.setColor(Color.BLACK); car3.setCarType(CarType.SEDAN); car3.setRentalDates(Collections.singleton(date3)); car3.setRentalAddress(Collections.singletonList(address1)); carDao.save(car3); customer1.setName("Marian"); customer1.setSurname("Nowak"); customer1.setAge(46); customer1.setAddress(address2); customerDao.save(customer1); customer2.setName("Krzysztof"); customer2.setSurname("Kowalski"); customer2.setAge(47); customer2.setAddress(address3); customerDao.save(customer2); customer3.setName("Anna"); customer3.setSurname("Jankowska"); customer3.setAge(32); customer3.setAddress(address4); customer3.getCars().add(car1); customer3.getCars().add(car2); customerDao.save(customer3); //relacja OneToOne Rental - Invoice Invoice invoice = new Invoice(); invoice.setInvoiceNumber("F-VAT-01/2018"); invoice.setDate(new Date()); Rental rental = new Rental(); rental.setDateFrom(new Date()); // add reference from source (rental) to target (invoice) rental.setInvoice(invoice); // add reversed reference from target to source invoice.setRental(rental); RentalDao rentalDao = new RentalDao(em); rentalDao.save(rental); //relacja OneToMany Car - TechnicalReview //Car audi = new Car("Audi", Color.RED, CarType.HATCHBACK); TechnicalReview TechRev1 = new TechnicalReview(TechnicalReviewResultEnum.PASSED, TRdate1, TRdate2); TechnicalReview TechRev2 = new TechnicalReview(TechnicalReviewResultEnum.FAILED, TRdate2, null); car1.getTechnicalReview().add(TechRev1); car1.getTechnicalReview().add(TechRev2); carDao.save(car1); //dodawanie do bazy danych em.getTransaction().begin(); em.getTransaction().commit(); //System.out.println(customerDao.findAll()); //System.out.println(carDao.findAll()); //System.out.println("Wyszukanie auta o podanym numerze: " + carDao.findByPlate("QQQ1234")); //System.out.println(carDao.isAvailable()); //System.out.println(customerDao.findByNameAndSurname("Krzysztof", "Kowalski")); //System.out.println(customerDao.findAll()); //System.out.println(rentalDao.findAll()); //System.out.println(car1.getTechnicalReview()); //System.out.println(customer3.getCars()); System.out.println(car1.getCustomers()); em.close(); } }
5,048
0.639175
0.605472
141
34.773048
24.908731
107
false
false
0
0
0
0
0
0
0.815603
false
false
10
b8ae7522d659037460c49eb4ecddaaf09988bfc5
17,480,516,930,750
6d50bb20cdd3ac95f5dd3e4075478ffebfbf97d0
/Homeworks/JavaCollections/Problem04LongestIncreasingSequence.java
0f848f68ce09d96aa610e62bd9c03bb77411ee7f
[]
no_license
ngeorgieva/JavaFundamentalsSoftUni
https://github.com/ngeorgieva/JavaFundamentalsSoftUni
69b693f48e80eecd8659288312181c510728b6a9
0719679d8fc97f1a6476061243ef549e4ea89edc
refs/heads/master
2021-01-10T06:28:09.190000
2016-04-18T14:28:36
2016-04-18T14:28:36
54,410,163
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Problem04LongestIncreasingSequence { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String[] strings = scan.nextLine().split(" "); int[] numbers = new int[strings.length]; for (int i = 0; i < numbers.length; i++) { numbers[i] = Integer.parseInt(strings[i]); } List<Integer> maxSequence = new ArrayList<>(); for (int i = 0; i < numbers.length; i++) { List<Integer> temp = new ArrayList<>(); temp.add(numbers[i]); while(i < numbers.length - 1 && numbers[i + 1] > numbers[i]){ temp.add(numbers[i + 1]); i++; } System.out.println(temp.toString().replace("[", "").replace("]", "").replace(",", "")); if (temp.size() > maxSequence.size()){ maxSequence.clear(); maxSequence.addAll(temp); } } System.out.printf("Longest: " + maxSequence.toString().replace("[", "").replace("]", "").replace(",", "")); } }
UTF-8
Java
1,165
java
Problem04LongestIncreasingSequence.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Problem04LongestIncreasingSequence { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String[] strings = scan.nextLine().split(" "); int[] numbers = new int[strings.length]; for (int i = 0; i < numbers.length; i++) { numbers[i] = Integer.parseInt(strings[i]); } List<Integer> maxSequence = new ArrayList<>(); for (int i = 0; i < numbers.length; i++) { List<Integer> temp = new ArrayList<>(); temp.add(numbers[i]); while(i < numbers.length - 1 && numbers[i + 1] > numbers[i]){ temp.add(numbers[i + 1]); i++; } System.out.println(temp.toString().replace("[", "").replace("]", "").replace(",", "")); if (temp.size() > maxSequence.size()){ maxSequence.clear(); maxSequence.addAll(temp); } } System.out.printf("Longest: " + maxSequence.toString().replace("[", "").replace("]", "").replace(",", "")); } }
1,165
0.519313
0.513305
33
34.303032
27.874702
115
false
false
0
0
0
0
0
0
0.848485
false
false
10
384a6dd79d0df9c657c168cb6a806229b83cfd6b
25,967,372,274,766
3e777fe6ab56dc0e587bee7fa7644ca6ab034c42
/src/main/java/com/cwbusinesservices/storage/IStorageService.java
2e62d564a01ce0f37295da6914fe5cfba7d841fe
[]
no_license
glibovet/cwbusinesservices
https://github.com/glibovet/cwbusinesservices
e411820cdee04ab8c5c466c76d8facfe4dc74f43
8e59ac73973037c7d0a3815cde6c2a344d0dcc39
refs/heads/master
2019-01-27T16:55:29.037000
2018-11-09T07:22:06
2018-11-09T07:22:06
98,194,117
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cwbusinesservices.storage; import com.cwbusinesservices.pojo.enums.FileEntityTypeEnum; import org.springframework.web.multipart.MultipartFile; import com.cwbusinesservices.exceptions.not_found.NoSuchEntityException; import com.cwbusinesservices.exceptions.service_error.ServiceErrorException; import com.cwbusinesservices.exceptions.service_error.StorageException; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.Map; /** * Created by Andrii on 05.10.2016. */ public interface IStorageService { Boolean uploadFile(int id, MultipartFile file, FileEntityTypeEnum type) throws ServiceErrorException; Boolean deleteFile(int id, FileEntityTypeEnum type) throws ServiceErrorException; void getFile(int id, HttpServletResponse response, FileEntityTypeEnum type) throws NoSuchEntityException, ServiceErrorException, StorageException; Boolean hasFile(int id, FileEntityTypeEnum type); Boolean uploadImage(MultipartFile file, String name) throws ServiceErrorException; Boolean deleteImage(int number) throws ServiceErrorException; void getImage(String name, HttpServletResponse response) throws NoSuchEntityException, ServiceErrorException, StorageException; int countImages(); List<String> getImagesData(); }
UTF-8
Java
1,301
java
IStorageService.java
Java
[ { "context": "til.List;\nimport java.util.Map;\n\n/**\n * Created by Andrii on 05.10.2016.\n */\npublic interface IStorageServi", "end": 496, "score": 0.998645007610321, "start": 490, "tag": "NAME", "value": "Andrii" } ]
null
[]
package com.cwbusinesservices.storage; import com.cwbusinesservices.pojo.enums.FileEntityTypeEnum; import org.springframework.web.multipart.MultipartFile; import com.cwbusinesservices.exceptions.not_found.NoSuchEntityException; import com.cwbusinesservices.exceptions.service_error.ServiceErrorException; import com.cwbusinesservices.exceptions.service_error.StorageException; import javax.servlet.http.HttpServletResponse; import java.util.List; import java.util.Map; /** * Created by Andrii on 05.10.2016. */ public interface IStorageService { Boolean uploadFile(int id, MultipartFile file, FileEntityTypeEnum type) throws ServiceErrorException; Boolean deleteFile(int id, FileEntityTypeEnum type) throws ServiceErrorException; void getFile(int id, HttpServletResponse response, FileEntityTypeEnum type) throws NoSuchEntityException, ServiceErrorException, StorageException; Boolean hasFile(int id, FileEntityTypeEnum type); Boolean uploadImage(MultipartFile file, String name) throws ServiceErrorException; Boolean deleteImage(int number) throws ServiceErrorException; void getImage(String name, HttpServletResponse response) throws NoSuchEntityException, ServiceErrorException, StorageException; int countImages(); List<String> getImagesData(); }
1,301
0.822444
0.816295
35
36.171429
40.536747
150
false
false
0
0
0
0
0
0
0.857143
false
false
13
8506056d49efc6cb610b33e2b90c689256104483
8,504,035,293,279
eb5f5353f49ee558e497e5caded1f60f32f536b5
/com/sun/corba/se/spi/ior/iiop/IIOPProfileTemplate.java
0b39a6f4622a9466b521dd3b8cee8adcc58ae379
[]
no_license
mohitrajvardhan17/java1.8.0_151
https://github.com/mohitrajvardhan17/java1.8.0_151
6fc53e15354d88b53bd248c260c954807d612118
6eeab0c0fd20be34db653f4778f8828068c50c92
refs/heads/master
2020-03-18T09:44:14.769000
2018-05-23T14:28:24
2018-05-23T14:28:24
134,578,186
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sun.corba.se.spi.ior.iiop; import com.sun.corba.se.spi.ior.TaggedProfileTemplate; public abstract interface IIOPProfileTemplate extends TaggedProfileTemplate { public abstract GIOPVersion getGIOPVersion(); public abstract IIOPAddress getPrimaryAddress(); } /* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\com\sun\corba\se\spi\ior\iiop\IIOPProfileTemplate.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
487
java
IIOPProfileTemplate.java
Java
[]
null
[]
package com.sun.corba.se.spi.ior.iiop; import com.sun.corba.se.spi.ior.TaggedProfileTemplate; public abstract interface IIOPProfileTemplate extends TaggedProfileTemplate { public abstract GIOPVersion getGIOPVersion(); public abstract IIOPAddress getPrimaryAddress(); } /* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\com\sun\corba\se\spi\ior\iiop\IIOPProfileTemplate.class * Java compiler version: 8 (52.0) * JD-Core Version: 0.7.1 */
487
0.735113
0.704312
17
27.705883
33.513412
134
false
false
0
0
0
0
0
0
0.235294
false
false
13
2ce57fa081f6678737b166973f41a994c464d0ea
2,456,721,364,456
44d80861961f8f41f37ac3c794b48fe00f7cc347
/Sensores/app/src/main/java/com/DyllanRiffo/sensores/MainActivity.java
b3a2f8aa1d7ff9cf1baf40a2f9ff083f87441ade
[]
no_license
DyllanRiffo/SensoresProgramacion-Android
https://github.com/DyllanRiffo/SensoresProgramacion-Android
ee207ed092393b3a3e207d9481c7cb6fab545fd1
44e6f43ba53d9c8dd271a2d38e0573017be6f81d
refs/heads/main
2023-08-24T14:25:48.735000
2021-10-26T22:36:02
2021-10-26T22:36:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.DyllanRiffo.sensores; import androidx.appcompat.app.AppCompatActivity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements SensorEventListener { TextView x,y,z; Sensor magnetico , giroscopio; SensorManager sm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); z = (TextView) findViewById(R.id.z); y = (TextView) findViewById(R.id.y); x = (TextView) findViewById(R.id.x); sm = (SensorManager) getSystemService(SENSOR_SERVICE); magnetico =(Sensor) sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); sm.registerListener(this,magnetico,SensorManager.SENSOR_DELAY_NORMAL); giroscopio =(Sensor) sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE); sm.registerListener(this,giroscopio,SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()){ case Sensor.TYPE_MAGNETIC_FIELD: x.setText(String.format("%f",event.values[0])); z.setText(String.format("%f",event.values[2])); break; case Sensor.TYPE_GYROSCOPE: y.setText(String.format("%f",event.values[1])); break; } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }
UTF-8
Java
1,674
java
MainActivity.java
Java
[ { "context": "package com.DyllanRiffo.sensores;\n\nimport androidx.appcompat.app.App", "end": 18, "score": 0.6179083585739136, "start": 16, "tag": "USERNAME", "value": "an" } ]
null
[]
package com.DyllanRiffo.sensores; import androidx.appcompat.app.AppCompatActivity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity implements SensorEventListener { TextView x,y,z; Sensor magnetico , giroscopio; SensorManager sm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); z = (TextView) findViewById(R.id.z); y = (TextView) findViewById(R.id.y); x = (TextView) findViewById(R.id.x); sm = (SensorManager) getSystemService(SENSOR_SERVICE); magnetico =(Sensor) sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); sm.registerListener(this,magnetico,SensorManager.SENSOR_DELAY_NORMAL); giroscopio =(Sensor) sm.getDefaultSensor(Sensor.TYPE_GYROSCOPE); sm.registerListener(this,giroscopio,SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()){ case Sensor.TYPE_MAGNETIC_FIELD: x.setText(String.format("%f",event.values[0])); z.setText(String.format("%f",event.values[2])); break; case Sensor.TYPE_GYROSCOPE: y.setText(String.format("%f",event.values[1])); break; } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } }
1,674
0.675627
0.673835
56
28.910715
25.892138
84
false
false
0
0
0
0
0
0
0.660714
false
false
13
8ea6fc85206964f66bcadfed6c5c3fe7153b7283
12,189,117,228,021
363539bc043edd61aed432e54e0c9bcfcbce4cd1
/test/unit/common/BaseUnit.java
d97027c736514cd4948f55749311f79eae832c80
[ "CC0-1.0" ]
permissive
adamconway/university-software-project
https://github.com/adamconway/university-software-project
7bab46f9c2f03bbd67f3b786ea8d6edd6b30280a
a28bf6a5e33bdadaf8d3d9b73b261fa617e8f829
refs/heads/master
2020-07-19T16:14:05.543000
2019-09-05T05:13:14
2019-09-05T05:13:14
206,478,722
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package unit.common; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Module; import models.User; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import play.Application; import play.ApplicationLoader; import play.Environment; import play.inject.guice.GuiceApplicationBuilder; import play.inject.guice.GuiceApplicationLoader; import play.test.Helpers; import play.test.WithApplication; public class BaseUnit extends WithApplication { public static Application app; @BeforeClass public static void setup() { Module testModule = new AbstractModule() { @Override public void configure() { } }; GuiceApplicationBuilder builder = new GuiceApplicationLoader() .builder(new ApplicationLoader.Context(Environment.simple())) .overrides(testModule); Guice.createInjector(builder.applicationModule()); app = builder.build(); Helpers.start(app); } /** * Tears down the fake app */ @AfterClass public static void tearDown() { Helpers.stop(app); } }
UTF-8
Java
1,195
java
BaseUnit.java
Java
[]
null
[]
package unit.common; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Module; import models.User; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import play.Application; import play.ApplicationLoader; import play.Environment; import play.inject.guice.GuiceApplicationBuilder; import play.inject.guice.GuiceApplicationLoader; import play.test.Helpers; import play.test.WithApplication; public class BaseUnit extends WithApplication { public static Application app; @BeforeClass public static void setup() { Module testModule = new AbstractModule() { @Override public void configure() { } }; GuiceApplicationBuilder builder = new GuiceApplicationLoader() .builder(new ApplicationLoader.Context(Environment.simple())) .overrides(testModule); Guice.createInjector(builder.applicationModule()); app = builder.build(); Helpers.start(app); } /** * Tears down the fake app */ @AfterClass public static void tearDown() { Helpers.stop(app); } }
1,195
0.684519
0.684519
49
23.387754
19.094625
77
false
false
0
0
0
0
0
0
0.44898
false
false
13
c7681eefbbfc725635e1adb45c729f6e709ad46d
13,554,916,828,618
f7c09191d7c560320c83918d1f3c8fdeb346420e
/src/main/java/com/miguan/burypoint/domain/entity/UserBuryingPointColumns.java
485f828f6ab134c246d12f0b9b44eed75ed84c4d
[]
no_license
chenwf1990/burypoint
https://github.com/chenwf1990/burypoint
18b595b82be1e8bf946aafe170390962a6d54e2f
4c8b64543f785eabc8ba0ac5ef87ad4deef76982
refs/heads/master
2022-09-22T12:03:19.355000
2020-05-28T08:52:44
2020-05-28T08:52:44
267,540,300
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.miguan.burypoint.domain.entity; import lombok.Data; @Data public class UserBuryingPointColumns { private String tableName; private String columnName; }
UTF-8
Java
176
java
UserBuryingPointColumns.java
Java
[]
null
[]
package com.miguan.burypoint.domain.entity; import lombok.Data; @Data public class UserBuryingPointColumns { private String tableName; private String columnName; }
176
0.772727
0.772727
12
13.75
16.207638
43
false
false
0
0
0
0
0
0
0.333333
false
false
13
7d15ddbbb2137b480b470082ee48304956c5af6b
36,644,660,977,166
0dfee1a1ac4143b03a63698f1919096a49444c0b
/BTP600Assignment2/src/btp600/game/command/PickUpBowCommand.java
84821169e309bdcaf5f01c33f1177eb50a98c461
[]
no_license
Ewlai/DesignPatterns-Example
https://github.com/Ewlai/DesignPatterns-Example
9124e2e83d00073f90bcbcf782dc9d4ccb859518
804944f0d712a7256e32698007916475f9700e38
refs/heads/master
2021-01-11T04:12:30.480000
2016-10-18T03:37:36
2016-10-18T03:37:36
71,207,066
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package btp600.game.command; public class PickUpBowCommand implements Command{ private PickUp pickup; public PickUpBowCommand(PickUp pick) { this.pickup = pick; } @Override // Command public void execute() { pickup.switchBow(); } }
UTF-8
Java
281
java
PickUpBowCommand.java
Java
[]
null
[]
package btp600.game.command; public class PickUpBowCommand implements Command{ private PickUp pickup; public PickUpBowCommand(PickUp pick) { this.pickup = pick; } @Override // Command public void execute() { pickup.switchBow(); } }
281
0.640569
0.629893
14
19.142857
15.528118
49
false
false
0
0
0
0
0
0
1
false
false
13
a7ccbe178f5c3cc7f79052038ff353e6ffd9db72
36,885,179,150,381
9b715d239e72103d49143cff7125ce07aae45ced
/database/src/main/java/io/hexaforce/dievas/database/DievasDataApplication.java
482ddf29cd2f97899503cdb45c6724ad0092ada3
[]
no_license
hexaforce/Dievas
https://github.com/hexaforce/Dievas
08f2832fd3c1d8d324db31ebc850091d860f47db
b922bd1e7d3a71020429c5bca6ec7b3f34e75c22
refs/heads/master
2021-09-13T23:16:03.209000
2018-02-12T09:21:34
2018-02-12T09:21:34
108,726,244
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.hexaforce.dievas.database; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DievasDataApplication { }
UTF-8
Java
178
java
DievasDataApplication.java
Java
[]
null
[]
package io.hexaforce.dievas.database; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DievasDataApplication { }
178
0.825843
0.825843
8
20.5
23.484037
68
false
false
0
0
0
0
0
0
0.25
false
false
13
cb8f6c4e3faa171b44455e7632990e0899071e78
8,443,905,752,805
2da3994f4c4b2be920f57eeb1ad08fb7ddc1bd36
/pp-viator-connector/src/main/java/com/viator/connector/domain/viator/tourgrades/ViatorTourgradesResInfo.java
e948b150ea2d0732441a4320e282fb84e98d77f6
[]
no_license
chanakakarunarathna/AET_PP_Modules
https://github.com/chanakakarunarathna/AET_PP_Modules
33e04632f171db71b810051df943b2da63e4957b
6f135b9e8de6a0a0df4c4ab332163ab154cdf8f8
refs/heads/master
2020-04-09T11:14:19.282000
2018-12-04T05:46:43
2018-12-04T05:46:43
160,301,184
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.viator.connector.domain.viator.tourgrades; import java.util.List; public class ViatorTourgradesResInfo { private Integer sortOrder; private String bookingDate; private List<ViatorTourgradesResAgeBandDetail> ageBands; private List<List<ViatorTourgradesResAgeBandsRequired>> ageBandsRequired = null; private Object langServices; //TODO private String unavailableReason; private String gradeCode; private String gradeTitle; private String gradeDescription; private String defaultLanguageCode; private String gradeDepartureTime; private Boolean available; private String currencyCode; private Integer retailPrice; private String retailPriceFormatted; private Integer merchantNetPrice; private String merchantNetPriceFormatted; public Integer getSortOrder() { return sortOrder; } public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; } public String getBookingDate() { return bookingDate; } public void setBookingDate(String bookingDate) { this.bookingDate = bookingDate; } public List<List<ViatorTourgradesResAgeBandsRequired>> getAgeBandsRequired() { return ageBandsRequired; } public void setAgeBandsRequired(List<List<ViatorTourgradesResAgeBandsRequired>> ageBandsRequired) { this.ageBandsRequired = ageBandsRequired; } public Object getLangServices() { return langServices; } public void setLangServices(Object langServices) { this.langServices = langServices; } public String getUnavailableReason() { return unavailableReason; } public void setUnavailableReason(String unavailableReason) { this.unavailableReason = unavailableReason; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeTitle() { return gradeTitle; } public void setGradeTitle(String gradeTitle) { this.gradeTitle = gradeTitle; } public String getGradeDescription() { return gradeDescription; } public void setGradeDescription(String gradeDescription) { this.gradeDescription = gradeDescription; } public String getDefaultLanguageCode() { return defaultLanguageCode; } public void setDefaultLanguageCode(String defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; } public String getGradeDepartureTime() { return gradeDepartureTime; } public void setGradeDepartureTime(String gradeDepartureTime) { this.gradeDepartureTime = gradeDepartureTime; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public Integer getRetailPrice() { return retailPrice; } public void setRetailPrice(Integer retailPrice) { this.retailPrice = retailPrice; } public String getRetailPriceFormatted() { return retailPriceFormatted; } public void setRetailPriceFormatted(String retailPriceFormatted) { this.retailPriceFormatted = retailPriceFormatted; } public Integer getMerchantNetPrice() { return merchantNetPrice; } public void setMerchantNetPrice(Integer merchantNetPrice) { this.merchantNetPrice = merchantNetPrice; } public String getMerchantNetPriceFormatted() { return merchantNetPriceFormatted; } public void setMerchantNetPriceFormatted(String merchantNetPriceFormatted) { this.merchantNetPriceFormatted = merchantNetPriceFormatted; } public List<ViatorTourgradesResAgeBandDetail> getAgeBands() { return ageBands; } public void setAgeBands(List<ViatorTourgradesResAgeBandDetail> ageBands) { this.ageBands = ageBands; } }
UTF-8
Java
4,214
java
ViatorTourgradesResInfo.java
Java
[]
null
[]
package com.viator.connector.domain.viator.tourgrades; import java.util.List; public class ViatorTourgradesResInfo { private Integer sortOrder; private String bookingDate; private List<ViatorTourgradesResAgeBandDetail> ageBands; private List<List<ViatorTourgradesResAgeBandsRequired>> ageBandsRequired = null; private Object langServices; //TODO private String unavailableReason; private String gradeCode; private String gradeTitle; private String gradeDescription; private String defaultLanguageCode; private String gradeDepartureTime; private Boolean available; private String currencyCode; private Integer retailPrice; private String retailPriceFormatted; private Integer merchantNetPrice; private String merchantNetPriceFormatted; public Integer getSortOrder() { return sortOrder; } public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; } public String getBookingDate() { return bookingDate; } public void setBookingDate(String bookingDate) { this.bookingDate = bookingDate; } public List<List<ViatorTourgradesResAgeBandsRequired>> getAgeBandsRequired() { return ageBandsRequired; } public void setAgeBandsRequired(List<List<ViatorTourgradesResAgeBandsRequired>> ageBandsRequired) { this.ageBandsRequired = ageBandsRequired; } public Object getLangServices() { return langServices; } public void setLangServices(Object langServices) { this.langServices = langServices; } public String getUnavailableReason() { return unavailableReason; } public void setUnavailableReason(String unavailableReason) { this.unavailableReason = unavailableReason; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeTitle() { return gradeTitle; } public void setGradeTitle(String gradeTitle) { this.gradeTitle = gradeTitle; } public String getGradeDescription() { return gradeDescription; } public void setGradeDescription(String gradeDescription) { this.gradeDescription = gradeDescription; } public String getDefaultLanguageCode() { return defaultLanguageCode; } public void setDefaultLanguageCode(String defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; } public String getGradeDepartureTime() { return gradeDepartureTime; } public void setGradeDepartureTime(String gradeDepartureTime) { this.gradeDepartureTime = gradeDepartureTime; } public Boolean getAvailable() { return available; } public void setAvailable(Boolean available) { this.available = available; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public Integer getRetailPrice() { return retailPrice; } public void setRetailPrice(Integer retailPrice) { this.retailPrice = retailPrice; } public String getRetailPriceFormatted() { return retailPriceFormatted; } public void setRetailPriceFormatted(String retailPriceFormatted) { this.retailPriceFormatted = retailPriceFormatted; } public Integer getMerchantNetPrice() { return merchantNetPrice; } public void setMerchantNetPrice(Integer merchantNetPrice) { this.merchantNetPrice = merchantNetPrice; } public String getMerchantNetPriceFormatted() { return merchantNetPriceFormatted; } public void setMerchantNetPriceFormatted(String merchantNetPriceFormatted) { this.merchantNetPriceFormatted = merchantNetPriceFormatted; } public List<ViatorTourgradesResAgeBandDetail> getAgeBands() { return ageBands; } public void setAgeBands(List<ViatorTourgradesResAgeBandDetail> ageBands) { this.ageBands = ageBands; } }
4,214
0.701234
0.701234
177
22.807909
23.662823
103
false
false
0
0
0
0
0
0
0.305085
false
false
13
1e3a4f7f23269649a1f37191977947a3388d30bf
23,656,679,910,048
a148e6661612ef1f069da65736fc67ef3577111a
/src/multi_threading/executors/dto/FactorialCallable.java
0e8fcd1ee8a6c08d762532ad20e6d4942ebc3580
[]
no_license
theabhishekmandal/non-gui
https://github.com/theabhishekmandal/non-gui
6e0f9b8997f7be12c9adc849ad3a640d839a37ff
f76e4bdc6e1c087ad8380334c0e3fff3cc59f027
refs/heads/master
2023-07-07T09:22:10.376000
2023-07-02T12:09:55
2023-07-02T12:09:55
110,258,906
4
0
null
false
2021-05-14T17:57:39
2017-11-10T14:57:30
2021-04-16T03:33:54
2021-05-14T17:57:38
4,705
3
0
0
Java
false
false
package multi_threading.executors.dto; import java.math.BigInteger; import java.util.concurrent.Callable; public class FactorialCallable implements Callable<BigInteger> { private final long inputNumber; private BigInteger result; public FactorialCallable(long inputNumber) { this.inputNumber = inputNumber; } public BigInteger getResult() { return this.result; } @Override public BigInteger call() throws Exception { System.out.println("Factorial calculation started"); BigInteger tempResult = BigInteger.ONE; for (long i = 2; i <= inputNumber; i++) { if (Thread.currentThread().isInterrupted()) { System.out.println("Factorial calculation interrupted"); return BigInteger.ZERO; } tempResult = tempResult.multiply(new BigInteger(String.valueOf(i))); this.result = tempResult; } System.out.println("Factorial calculation stopped"); return tempResult; } }
UTF-8
Java
1,041
java
FactorialCallable.java
Java
[]
null
[]
package multi_threading.executors.dto; import java.math.BigInteger; import java.util.concurrent.Callable; public class FactorialCallable implements Callable<BigInteger> { private final long inputNumber; private BigInteger result; public FactorialCallable(long inputNumber) { this.inputNumber = inputNumber; } public BigInteger getResult() { return this.result; } @Override public BigInteger call() throws Exception { System.out.println("Factorial calculation started"); BigInteger tempResult = BigInteger.ONE; for (long i = 2; i <= inputNumber; i++) { if (Thread.currentThread().isInterrupted()) { System.out.println("Factorial calculation interrupted"); return BigInteger.ZERO; } tempResult = tempResult.multiply(new BigInteger(String.valueOf(i))); this.result = tempResult; } System.out.println("Factorial calculation stopped"); return tempResult; } }
1,041
0.649376
0.648415
34
29.588236
23.479801
80
false
false
0
0
0
0
0
0
0.5
false
false
13
9e8a971f6dfb289e942663ccabf1568ef56140d6
16,973,710,770,985
441b16d5861b8239644007c3b64d56bdfd67bb92
/plugins/org.eclipse.osee.disposition.rest.test/src/org/eclipse/osee/disposition/rest/resources/DispoItemResourceTest.java
b53ee99c5ebc0d68c3849b907b84736f1e20b3ec
[]
no_license
sec00/osee-4
https://github.com/sec00/osee-4
baf9713306c7bfd6f5a12a153acb083bbdb2ce77
4644522f12d0e2a887434d09dffa55d32ed45f15
refs/heads/master
2021-05-19T04:04:07.608000
2018-11-15T23:29:55
2018-11-15T23:31:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright (c) 2013 Boein g. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Boeing - initial API and implementation *******************************************************************************/ package org.eclipse.osee.disposition.rest.resources; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import javax.ws.rs.core.Response; import org.eclipse.osee.disposition.model.DispoItem; import org.eclipse.osee.disposition.model.DispoItemData; import org.eclipse.osee.disposition.model.DispoMessages; import org.eclipse.osee.disposition.rest.DispoApi; import org.eclipse.osee.framework.core.data.BranchId; import org.eclipse.osee.framework.jdk.core.type.Identifiable; import org.eclipse.osee.orcs.data.ArtifactReadable; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** * @author Angel Avila */ public class DispoItemResourceTest { @Mock private DispoApi dispositionApi; @Mock private Identifiable<String> id1; @Mock private Identifiable<String> id2; @Mock private ArtifactReadable setArt; @Mock private BranchId branch; private DispoItemResource resource; @Before public void setUp() { MockitoAnnotations.initMocks(this); resource = new DispoItemResource(dispositionApi, branch, "setId"); when(id1.getGuid()).thenReturn("abcdef"); when(id2.getGuid()).thenReturn("fedcba"); when(setArt.getGuid()).thenReturn("setId"); } @Test public void testGetAll() throws Exception { // No Items List<DispoItem> emptyResultSet = new ArrayList<>(); when(dispositionApi.getDispoItems(branch, "setId", false)).thenReturn(emptyResultSet); Iterable<DispoItem> noItemsResponse = resource.getAllDispoItems(false); assertEquals(emptyResultSet, noItemsResponse); DispoItemData item = new DispoItemData(); item.setAnnotationsList(new ArrayList<>()); item.setDiscrepanciesList(new HashMap<>()); item.setGuid(id1.getGuid()); List<DispoItem> resultSet = Collections.singletonList((DispoItem) item); when(dispositionApi.getDispoItems(branch, "setId", false)).thenReturn(resultSet); Iterable<DispoItem> response = resource.getAllDispoItems(false); DispoItem itemFromResponse = response.iterator().next(); assertEquals(id1.getGuid(), itemFromResponse.getGuid()); } @Test public void testGetSingleSet() { // No items when(dispositionApi.getDispoItemById(branch, id2.getGuid())).thenReturn(null); DispoItem noItemsResponse = resource.getDispoItemsById(id2.getGuid()); assertEquals(null, noItemsResponse); DispoItemData expectedItem = new DispoItemData(); expectedItem.setGuid(id1.getGuid()); expectedItem.setName("Item"); expectedItem.setNeedsRerun(false); expectedItem.setTotalPoints("4"); when(dispositionApi.getDispoItemById(branch, expectedItem.getGuid())).thenReturn(expectedItem); DispoItem oneSetResponse = resource.getDispoItemsById(expectedItem.getGuid()); assertEquals(expectedItem.getGuid(), oneSetResponse.getGuid()); } @Test public void testPut() { DispoItemData newItem = new DispoItemData(); DispoItemData itemToEdt = new DispoItemData(); itemToEdt.setGuid(id1.getGuid()); when(dispositionApi.editDispoItem(branch, id1.getGuid(), newItem)).thenReturn(true); Response response = resource.putDispoItem(id1.getGuid(), newItem); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); when(dispositionApi.editDispoItem(branch, id1.getGuid(), newItem)).thenReturn(false); response = resource.putDispoItem(id1.getGuid(), newItem); String returnedMessage = (String) response.getEntity(); assertEquals(Response.Status.NOT_MODIFIED.getStatusCode(), response.getStatus()); assertEquals(DispoMessages.Item_NotFound, returnedMessage); } @Test public void testDelete() { DispoItemData itemToEdt = new DispoItemData(); itemToEdt.setGuid(id1.getGuid()); when(dispositionApi.deleteDispoItem(branch, id1.getGuid())).thenReturn(true); Response response = resource.deleteDispoItem(id1.getGuid()); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); when(dispositionApi.deleteDispoItem(branch, id1.getGuid())).thenReturn(false); response = resource.deleteDispoItem(id1.getGuid()); String returnedMessage = (String) response.getEntity(); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); assertEquals(DispoMessages.Item_NotFound, returnedMessage); } }
UTF-8
Java
5,103
java
DispoItemResourceTest.java
Java
[ { "context": "****************************\n * Copyright (c) 2013 Boein g.\n * All rights reserved. This program and the acc", "end": 110, "score": 0.9998109340667725, "start": 103, "tag": "NAME", "value": "Boein g" }, { "context": ".org/legal/epl-v10.html\n *\n * Contributors:\n * Boeing - initial API and implementation\n ***************", "end": 391, "score": 0.9997313618659973, "start": 385, "tag": "NAME", "value": "Boeing" }, { "context": "rt org.mockito.MockitoAnnotations;\n\n/**\n * @author Angel Avila\n */\npublic class DispoItemResourceTest {\n\n @Moc", "end": 1312, "score": 0.999852180480957, "start": 1301, "tag": "NAME", "value": "Angel Avila" } ]
null
[]
/******************************************************************************* * Copyright (c) 2013 <NAME>. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Boeing - initial API and implementation *******************************************************************************/ package org.eclipse.osee.disposition.rest.resources; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import javax.ws.rs.core.Response; import org.eclipse.osee.disposition.model.DispoItem; import org.eclipse.osee.disposition.model.DispoItemData; import org.eclipse.osee.disposition.model.DispoMessages; import org.eclipse.osee.disposition.rest.DispoApi; import org.eclipse.osee.framework.core.data.BranchId; import org.eclipse.osee.framework.jdk.core.type.Identifiable; import org.eclipse.osee.orcs.data.ArtifactReadable; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** * @author <NAME> */ public class DispoItemResourceTest { @Mock private DispoApi dispositionApi; @Mock private Identifiable<String> id1; @Mock private Identifiable<String> id2; @Mock private ArtifactReadable setArt; @Mock private BranchId branch; private DispoItemResource resource; @Before public void setUp() { MockitoAnnotations.initMocks(this); resource = new DispoItemResource(dispositionApi, branch, "setId"); when(id1.getGuid()).thenReturn("abcdef"); when(id2.getGuid()).thenReturn("fedcba"); when(setArt.getGuid()).thenReturn("setId"); } @Test public void testGetAll() throws Exception { // No Items List<DispoItem> emptyResultSet = new ArrayList<>(); when(dispositionApi.getDispoItems(branch, "setId", false)).thenReturn(emptyResultSet); Iterable<DispoItem> noItemsResponse = resource.getAllDispoItems(false); assertEquals(emptyResultSet, noItemsResponse); DispoItemData item = new DispoItemData(); item.setAnnotationsList(new ArrayList<>()); item.setDiscrepanciesList(new HashMap<>()); item.setGuid(id1.getGuid()); List<DispoItem> resultSet = Collections.singletonList((DispoItem) item); when(dispositionApi.getDispoItems(branch, "setId", false)).thenReturn(resultSet); Iterable<DispoItem> response = resource.getAllDispoItems(false); DispoItem itemFromResponse = response.iterator().next(); assertEquals(id1.getGuid(), itemFromResponse.getGuid()); } @Test public void testGetSingleSet() { // No items when(dispositionApi.getDispoItemById(branch, id2.getGuid())).thenReturn(null); DispoItem noItemsResponse = resource.getDispoItemsById(id2.getGuid()); assertEquals(null, noItemsResponse); DispoItemData expectedItem = new DispoItemData(); expectedItem.setGuid(id1.getGuid()); expectedItem.setName("Item"); expectedItem.setNeedsRerun(false); expectedItem.setTotalPoints("4"); when(dispositionApi.getDispoItemById(branch, expectedItem.getGuid())).thenReturn(expectedItem); DispoItem oneSetResponse = resource.getDispoItemsById(expectedItem.getGuid()); assertEquals(expectedItem.getGuid(), oneSetResponse.getGuid()); } @Test public void testPut() { DispoItemData newItem = new DispoItemData(); DispoItemData itemToEdt = new DispoItemData(); itemToEdt.setGuid(id1.getGuid()); when(dispositionApi.editDispoItem(branch, id1.getGuid(), newItem)).thenReturn(true); Response response = resource.putDispoItem(id1.getGuid(), newItem); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); when(dispositionApi.editDispoItem(branch, id1.getGuid(), newItem)).thenReturn(false); response = resource.putDispoItem(id1.getGuid(), newItem); String returnedMessage = (String) response.getEntity(); assertEquals(Response.Status.NOT_MODIFIED.getStatusCode(), response.getStatus()); assertEquals(DispoMessages.Item_NotFound, returnedMessage); } @Test public void testDelete() { DispoItemData itemToEdt = new DispoItemData(); itemToEdt.setGuid(id1.getGuid()); when(dispositionApi.deleteDispoItem(branch, id1.getGuid())).thenReturn(true); Response response = resource.deleteDispoItem(id1.getGuid()); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); when(dispositionApi.deleteDispoItem(branch, id1.getGuid())).thenReturn(false); response = resource.deleteDispoItem(id1.getGuid()); String returnedMessage = (String) response.getEntity(); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); assertEquals(DispoMessages.Item_NotFound, returnedMessage); } }
5,097
0.710954
0.705467
126
39.5
27.992275
101
false
false
0
0
0
0
0
0
0.809524
false
false
13
d99e9aaf7bdf53d391dc031d0b3b34355e4de3fe
11,218,454,585,899
d9547b55cdd57b99c3fc816098912b858d6147d9
/MapsforgePlatform/MapsForgeProjectDetectorModule/src/main/java/de/fub/maps/project/detector/model/inference/InferenceModelResultDataSet.java
9c90ce71e0c74f4f0690fb543c79191d332dbe6a
[]
no_license
tosuns/mapsforge-platform
https://github.com/tosuns/mapsforge-platform
22bcc15f2255730f0bae644714b0f274f97cf8f9
a4b4e502120cc3902a2edb6135f65bff9faf1f57
refs/heads/master
2020-05-04T10:36:39.578000
2013-11-19T18:00:31
2013-11-19T18:00:31
8,667,914
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2013 Serdar * * 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 de.fub.maps.project.detector.model.inference; import de.fub.maps.project.detector.model.gpx.TrackSegment; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * * @author Serdar */ public class InferenceModelResultDataSet { private final HashMap<String, HashSet<TrackSegment>> gpsTrackMap = new HashMap<String, HashSet<TrackSegment>>(); public int size() { return gpsTrackMap.size(); } public boolean isEmpty() { return gpsTrackMap.isEmpty(); } public boolean containsKey(String key) { return gpsTrackMap.containsKey(key); } public boolean containsValue(HashSet<TrackSegment> value) { return gpsTrackMap.containsValue(value); } public HashSet<TrackSegment> get(String key) { return gpsTrackMap.get(key); } public HashSet<TrackSegment> put(String key, HashSet<TrackSegment> value) { return gpsTrackMap.put(key, value); } public HashSet<TrackSegment> remove(String key) { return gpsTrackMap.remove(key); } public void clear() { gpsTrackMap.clear(); } public Set<String> keySet() { return Collections.unmodifiableSet(gpsTrackMap.keySet()); } public Collection<HashSet<TrackSegment>> values() { return gpsTrackMap.values(); } public Set<Map.Entry<String, HashSet<TrackSegment>>> entrySet() { return Collections.unmodifiableSet(gpsTrackMap.entrySet()); } }
UTF-8
Java
2,326
java
InferenceModelResultDataSet.java
Java
[ { "context": "/*\r\n * Copyright (C) 2013 Serdar\r\n *\r\n * This program is free software: you can re", "end": 32, "score": 0.9997700452804565, "start": 26, "tag": "NAME", "value": "Serdar" }, { "context": "Map;\r\nimport java.util.Set;\r\n\r\n/**\r\n *\r\n * @author Serdar\r\n */\r\npublic class InferenceModelResultDataSet {\r", "end": 1008, "score": 0.9997241497039795, "start": 1002, "tag": "NAME", "value": "Serdar" } ]
null
[]
/* * Copyright (C) 2013 Serdar * * 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 de.fub.maps.project.detector.model.inference; import de.fub.maps.project.detector.model.gpx.TrackSegment; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * * @author Serdar */ public class InferenceModelResultDataSet { private final HashMap<String, HashSet<TrackSegment>> gpsTrackMap = new HashMap<String, HashSet<TrackSegment>>(); public int size() { return gpsTrackMap.size(); } public boolean isEmpty() { return gpsTrackMap.isEmpty(); } public boolean containsKey(String key) { return gpsTrackMap.containsKey(key); } public boolean containsValue(HashSet<TrackSegment> value) { return gpsTrackMap.containsValue(value); } public HashSet<TrackSegment> get(String key) { return gpsTrackMap.get(key); } public HashSet<TrackSegment> put(String key, HashSet<TrackSegment> value) { return gpsTrackMap.put(key, value); } public HashSet<TrackSegment> remove(String key) { return gpsTrackMap.remove(key); } public void clear() { gpsTrackMap.clear(); } public Set<String> keySet() { return Collections.unmodifiableSet(gpsTrackMap.keySet()); } public Collection<HashSet<TrackSegment>> values() { return gpsTrackMap.values(); } public Set<Map.Entry<String, HashSet<TrackSegment>>> entrySet() { return Collections.unmodifiableSet(gpsTrackMap.entrySet()); } }
2,326
0.676698
0.674549
78
27.820513
27.208946
116
false
false
0
0
0
0
0
0
0.384615
false
false
13
32d365bf0cdd0667a504700c59f555d980870e13
11,819,750,004,259
20580780920836b90fbdc733cff359d5b7f33e33
/src/EPIC/AdditiveSequence.java
360c085f713c3ce77a781572348c6a1f8d3941d9
[]
no_license
SherryShuranHuang/LeetCodePractice
https://github.com/SherryShuranHuang/LeetCodePractice
23c0f8a2df1990588fa41809da4cf9779c8bafcb
0a1747fa171994a4cff7de75dab6f9d54b6e2b65
refs/heads/master
2021-01-25T07:33:55.526000
2015-04-14T21:02:03
2015-04-14T21:02:03
31,691,412
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package EPIC; import java.util.ArrayList; import java.util.List; /* An additive sequence is 1,2,3,5,8,13 where T(n) = T(n -1) + T(n - 2). A number range is given to you. Find the additive sequence number in that range. Given the start and an ending integer as user input, generate all integers with the following property. */ public class AdditiveSequence { public static void main(String[] args){ List<Integer> res = findAdditiveSequence(1,50); System.out.println(res); } public static List<Integer> findAdditiveSequence(int start, int end){ List<Integer> res = new ArrayList<Integer>(); if(end<start) return res; int f1 =1; int f2 =2; int f3= f1+f2; if(f1==start) res.add(f1); while(f2<=end){ if(f2>=start) res.add(f2); f1 = f2; f2 = f3; f3 = f1+f2; } return res; } }
UTF-8
Java
865
java
AdditiveSequence.java
Java
[]
null
[]
package EPIC; import java.util.ArrayList; import java.util.List; /* An additive sequence is 1,2,3,5,8,13 where T(n) = T(n -1) + T(n - 2). A number range is given to you. Find the additive sequence number in that range. Given the start and an ending integer as user input, generate all integers with the following property. */ public class AdditiveSequence { public static void main(String[] args){ List<Integer> res = findAdditiveSequence(1,50); System.out.println(res); } public static List<Integer> findAdditiveSequence(int start, int end){ List<Integer> res = new ArrayList<Integer>(); if(end<start) return res; int f1 =1; int f2 =2; int f3= f1+f2; if(f1==start) res.add(f1); while(f2<=end){ if(f2>=start) res.add(f2); f1 = f2; f2 = f3; f3 = f1+f2; } return res; } }
865
0.636994
0.601156
37
21.378378
24.548189
103
false
false
0
0
0
0
0
0
2.027027
false
false
13
ee30cf985703fb034324031a05955fd89d25ceb9
23,373,212,033,904
f189fcb1baf101fd6b2eef862b8a50ecc5802cd8
/DesignModeTest/src/main/java/com/factory_design/abstract_factory/AbsPizza.java
ba40893f0438d21ebf11558029143306406bbe6c
[]
no_license
kivensolo/JavaPracticeCode
https://github.com/kivensolo/JavaPracticeCode
ca41756575e194f79b2348bb75aed4ee5f4f271d
af32cc63c5fd733fbc355453954995f5a4ef17b2
refs/heads/master
2021-04-09T17:28:15.545000
2021-03-04T05:00:40
2021-03-04T05:00:40
51,904,960
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.factory_design.abstract_factory; /** * 抽象披萨产品 */ public abstract class AbsPizza extends CommonPizza { @Override public abstract void prepare(); @Override public abstract void bake(); @Override public abstract void cut(); @Override public abstract void box(); }
UTF-8
Java
324
java
AbsPizza.java
Java
[]
null
[]
package com.factory_design.abstract_factory; /** * 抽象披萨产品 */ public abstract class AbsPizza extends CommonPizza { @Override public abstract void prepare(); @Override public abstract void bake(); @Override public abstract void cut(); @Override public abstract void box(); }
324
0.673077
0.673077
18
16.333334
16.411379
52
false
false
0
0
0
0
0
0
0.277778
false
false
13
ecc1631b52af3e299df98614ff867ef507b5b312
17,609,365,932,252
260785497f1d4704d153866843a6add0cd432a1a
/target/generated-sources/annotations/com/inheritor/mycompany/quickcabsservice/model/Orders_.java
18d30be67fe0658c4a00fec06e6022901419ea4b
[]
no_license
ChathuraHansika/Project1
https://github.com/ChathuraHansika/Project1
c22db48d4226436969d89ddea8a63bc49f94ccd4
6b309f22954e8e56f3cb86095ba34aa3959100bc
refs/heads/master
2021-01-18T20:27:50.087000
2019-02-15T05:05:43
2019-02-15T05:05:43
86,969,398
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.inheritor.mycompany.quickcabsservice.model; import com.inheritor.mycompany.quickcabsservice.model.Car; import com.inheritor.mycompany.quickcabsservice.model.Customer; import com.inheritor.mycompany.quickcabsservice.model.Payment; import com.inheritor.mycompany.quickcabsservice.model.Vehiclehandover; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-09-30T20:00:10") @StaticMetamodel(Orders.class) public class Orders_ { public static volatile SingularAttribute<Orders, Date> pickupDateTime; public static volatile ListAttribute<Orders, Vehiclehandover> vehiclehandoverList; public static volatile SingularAttribute<Orders, Customer> cuid; public static volatile SingularAttribute<Orders, Car> caid; public static volatile SingularAttribute<Orders, Integer> oid; public static volatile SingularAttribute<Orders, Date> handOverDateTime; public static volatile SingularAttribute<Orders, Date> orderDate; public static volatile SingularAttribute<Orders, Date> upateDate; public static volatile SingularAttribute<Orders, String> status; public static volatile ListAttribute<Orders, Payment> paymentList; }
UTF-8
Java
1,386
java
Orders_.java
Java
[]
null
[]
package com.inheritor.mycompany.quickcabsservice.model; import com.inheritor.mycompany.quickcabsservice.model.Car; import com.inheritor.mycompany.quickcabsservice.model.Customer; import com.inheritor.mycompany.quickcabsservice.model.Payment; import com.inheritor.mycompany.quickcabsservice.model.Vehiclehandover; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.5.2.v20140319-rNA", date="2018-09-30T20:00:10") @StaticMetamodel(Orders.class) public class Orders_ { public static volatile SingularAttribute<Orders, Date> pickupDateTime; public static volatile ListAttribute<Orders, Vehiclehandover> vehiclehandoverList; public static volatile SingularAttribute<Orders, Customer> cuid; public static volatile SingularAttribute<Orders, Car> caid; public static volatile SingularAttribute<Orders, Integer> oid; public static volatile SingularAttribute<Orders, Date> handOverDateTime; public static volatile SingularAttribute<Orders, Date> orderDate; public static volatile SingularAttribute<Orders, Date> upateDate; public static volatile SingularAttribute<Orders, String> status; public static volatile ListAttribute<Orders, Payment> paymentList; }
1,386
0.823232
0.805195
28
48.535713
27.325396
86
false
false
0
0
0
0
0
0
1.107143
false
false
13
58168d8f2d74c03161353e76278fa31e5873312d
26,405,458,951,306
a0aab2303f82ae1aaa1e56956c7784e70dea6133
/2학기/ch01/Point.java
c2492fd28a95d611b4b78bf3f793baad405db963
[]
no_license
Chae-yun/Java-1
https://github.com/Chae-yun/Java-1
fbbf8001864eaab5943877750f226ad21d0aa9d2
281ec085ff132e6d450599b7807b83c6cbcee0e4
refs/heads/master
2021-01-19T00:41:27.913000
2017-04-04T15:13:30
2017-04-04T15:13:30
87,201,394
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Point { double x, y; //1. x, y 좌표를 입력 받아 점을 생성한다. Point(double x, double y){ //생성자함수 : 객체를 생성하고 값을 초기화, 안하면 jvm이 만들어주긴 하지만 고급만들려면 직접! this.x = x; //매개변수 x를 통해서 입력된 값을 생성된 객체의 멤버변수로 대입해라 this.y = y; } //속성으로 x, y를 받아 점을 생성 /*void MoveP(double x, double y){ double mx = 3.0, my = 5.0; System.out.println("이동 전 : (" + x + "), (" + y + ")"); x += mx; y += my; System.out.println("각각 " + mx + ", " + my + " 이동 후 : (" + x + "), (" + y + ")"); } 이코드는 x, y를 얻어 오라는 조건을 무시한 코드*/ /*double getX(){ return x; } //2. x값을 얻어온다. double getY(){ return y; } //3. y값을 얻어온다.*/ public String toString(){ //Object 클래스 toString 메서드 재정의 return ("점의 좌표 : (" + this.x + ", " + this.y + ")"); //return ("점의 좌표 : (" + x + ", " + y + ")"); 생략가능!! 근데 생성자함수에서는 안된당 } void moveXY(double dx, double dy){ x += dx; y += dy; } //4. x, y값을 이동시킨다. }
UHC
Java
1,198
java
Point.java
Java
[]
null
[]
class Point { double x, y; //1. x, y 좌표를 입력 받아 점을 생성한다. Point(double x, double y){ //생성자함수 : 객체를 생성하고 값을 초기화, 안하면 jvm이 만들어주긴 하지만 고급만들려면 직접! this.x = x; //매개변수 x를 통해서 입력된 값을 생성된 객체의 멤버변수로 대입해라 this.y = y; } //속성으로 x, y를 받아 점을 생성 /*void MoveP(double x, double y){ double mx = 3.0, my = 5.0; System.out.println("이동 전 : (" + x + "), (" + y + ")"); x += mx; y += my; System.out.println("각각 " + mx + ", " + my + " 이동 후 : (" + x + "), (" + y + ")"); } 이코드는 x, y를 얻어 오라는 조건을 무시한 코드*/ /*double getX(){ return x; } //2. x값을 얻어온다. double getY(){ return y; } //3. y값을 얻어온다.*/ public String toString(){ //Object 클래스 toString 메서드 재정의 return ("점의 좌표 : (" + this.x + ", " + this.y + ")"); //return ("점의 좌표 : (" + x + ", " + y + ")"); 생략가능!! 근데 생성자함수에서는 안된당 } void moveXY(double dx, double dy){ x += dx; y += dy; } //4. x, y값을 이동시킨다. }
1,198
0.512761
0.50348
34
24.352942
27.634039
122
false
false
0
0
0
0
0
0
1.970588
false
false
13
b045c8c82caf4b163ffde9a988292445e5d1984b
25,125,558,703,840
090d0052aad157fba9da24775813b5db107c37e2
/dht-root/dht-web/src/main/java/com/retailers/dht/web/controller/HomeAdvertisingController.java
5965d6c4e601e02e15b991dbc3b2d28562fa8142
[]
no_license
bellmit/dht
https://github.com/bellmit/dht
f2287a0db178cab4a630012892c66e1aafc241ff
6c7c189ee0e2742cfe4cbc431d855aff1442377d
refs/heads/master
2023-07-10T07:43:13.372000
2019-08-03T12:36:54
2019-08-03T12:36:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.retailers.dht.web.controller; import com.retailers.dht.common.service.HomeAdvertisingService; import com.retailers.dht.common.vo.HomeAdvertisingVo; import com.retailers.dht.web.base.BaseController; import com.retailers.mybatis.pagination.Pagination; import com.retailers.tools.utils.PageUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /** * Created by niconiconi on 2017/10/18. */ @Controller @RequestMapping("openHomeAdvertising") public class HomeAdvertisingController extends BaseController { @Autowired HomeAdvertisingService advertisingService; @RequestMapping("/queryAdvertisingLists") @ResponseBody public Map<String,Object> queryNavigationLists(String haName,Long haClient,Long haCountry,Long isShow,Long haRegion,PageUtils pageForm){ Map<String,Object> map = new HashMap<String,Object>(); map.put("isDelete",0); map.put("haName",haName); map.put("haClient", haClient); map.put("haCountry", haCountry); map.put("haRegion",haRegion); map.put("isShow",isShow); Pagination<HomeAdvertisingVo> advertisingPagination = advertisingService.queryHomeAdvertisingList(map,pageForm.getPageNo(),pageForm.getPageSize()); Map<String,Object> gtm = new HashMap<String,Object>(); gtm.put("total",advertisingPagination.getPageSize()); gtm.put("rows",advertisingPagination.getData()); return gtm; } }
UTF-8
Java
1,670
java
HomeAdvertisingController.java
Java
[ { "context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by niconiconi on 2017/10/18.\n */\n@Controller\n@RequestMapping(\"o", "end": 621, "score": 0.9996081590652466, "start": 611, "tag": "USERNAME", "value": "niconiconi" } ]
null
[]
package com.retailers.dht.web.controller; import com.retailers.dht.common.service.HomeAdvertisingService; import com.retailers.dht.common.vo.HomeAdvertisingVo; import com.retailers.dht.web.base.BaseController; import com.retailers.mybatis.pagination.Pagination; import com.retailers.tools.utils.PageUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /** * Created by niconiconi on 2017/10/18. */ @Controller @RequestMapping("openHomeAdvertising") public class HomeAdvertisingController extends BaseController { @Autowired HomeAdvertisingService advertisingService; @RequestMapping("/queryAdvertisingLists") @ResponseBody public Map<String,Object> queryNavigationLists(String haName,Long haClient,Long haCountry,Long isShow,Long haRegion,PageUtils pageForm){ Map<String,Object> map = new HashMap<String,Object>(); map.put("isDelete",0); map.put("haName",haName); map.put("haClient", haClient); map.put("haCountry", haCountry); map.put("haRegion",haRegion); map.put("isShow",isShow); Pagination<HomeAdvertisingVo> advertisingPagination = advertisingService.queryHomeAdvertisingList(map,pageForm.getPageNo(),pageForm.getPageSize()); Map<String,Object> gtm = new HashMap<String,Object>(); gtm.put("total",advertisingPagination.getPageSize()); gtm.put("rows",advertisingPagination.getData()); return gtm; } }
1,670
0.758084
0.752695
40
40.75
32.167336
155
false
false
0
0
0
0
0
0
1.125
false
false
13
3df38b8072f26c047dea2cfcce09e2d0bf2634dd
8,615,704,415,901
466d80e7d1db7728c246b4aa9149e1d185c2a7c7
/src/main/java/com/maxlong/study/zk/recipes/leader/api/Candidater.java
1709b0ba62e016ef7f27e878dfd230d4e4995c62
[]
no_license
huaya/studyDemo
https://github.com/huaya/studyDemo
f109159c44ef7898a99db42b52f2e037227185a6
1e5bb33be3219092c33aefdbb705cda6e419b7fc
refs/heads/master
2023-06-08T22:22:37.107000
2022-07-07T15:59:17
2022-07-07T15:59:17
128,028,627
1
0
null
false
2023-05-26T22:15:29
2018-04-04T08:01:52
2021-11-30T15:18:20
2023-05-26T22:15:28
4,625
0
1
12
Java
false
false
package com.maxlong.study.zk.recipes.leader.api; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * 候选人接口 * * @author ma.xl * @version 1.0.0 * @since 2015/6/17 16:39 * abacus-parent */ public interface Candidater { /** * 参入选举 * * @throws Exception */ void requireElection() throws Exception ; /** * 判断是否是Leader * * @return */ boolean isLeader(); /** * 获得Leader Id * * @return */ String getLeaderId() throws Exception; /** * 获取节点 * * @return */ String getNodeId(); /** * 等待选举结果(有结果立刻返回) * * @param timeout * @param unit * @return true 领导 false 非领导 * @throws InterruptedException */ boolean awaitElection(long timeout, TimeUnit unit) throws InterruptedException; /** * 释放参选资格关闭自己 * * @throws IOException */ void close() throws IOException; }
UTF-8
Java
1,058
java
Candidater.java
Java
[ { "context": "l.concurrent.TimeUnit;\n\n/**\n * 候选人接口\n *\n * @author ma.xl\n * @version 1.0.0\n * @since 2015/6/17 16:39\n * ab", "end": 149, "score": 0.9995437264442444, "start": 144, "tag": "USERNAME", "value": "ma.xl" } ]
null
[]
package com.maxlong.study.zk.recipes.leader.api; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * 候选人接口 * * @author ma.xl * @version 1.0.0 * @since 2015/6/17 16:39 * abacus-parent */ public interface Candidater { /** * 参入选举 * * @throws Exception */ void requireElection() throws Exception ; /** * 判断是否是Leader * * @return */ boolean isLeader(); /** * 获得Leader Id * * @return */ String getLeaderId() throws Exception; /** * 获取节点 * * @return */ String getNodeId(); /** * 等待选举结果(有结果立刻返回) * * @param timeout * @param unit * @return true 领导 false 非领导 * @throws InterruptedException */ boolean awaitElection(long timeout, TimeUnit unit) throws InterruptedException; /** * 释放参选资格关闭自己 * * @throws IOException */ void close() throws IOException; }
1,058
0.554054
0.539501
61
14.770492
15.096839
83
false
false
0
0
0
0
0
0
0.163934
false
false
13
ef0f7eb47ec89e8acf515aa29725d2520f522372
8,615,704,419,232
5f6eed53e1e108e7cae750a6ae20a8444d2723c2
/src/main/java/main/Principal.java
583096e9fb1659d402913697378a376ba3ed1ef5
[]
no_license
BryanSegoviano/SeguridadInformatica
https://github.com/BryanSegoviano/SeguridadInformatica
e3e98551aaced06a79d7ff6d842dba68b41d1f1f
4797e1234d3bc1f5943f85f619a19db86a12b6f5
refs/heads/main
2023-04-27T18:00:39.437000
2021-05-14T05:01:52
2021-05-14T05:01:52
367,253,565
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main; import daos.UsuarioJpaController; import objetosnegocio.Usuario; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Principal { public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("seguridadInformaticaBD"); UsuarioJpaController usuarioDAO = new UsuarioJpaController(factory); Usuario usuario = new Usuario("pancho2012", "panchopa", "Pancho Sergio", "Villa", "Hermosillo", "Sonora"); usuarioDAO.create(usuario); } }
UTF-8
Java
610
java
Principal.java
Java
[ { "context": ";\n \n Usuario usuario = new Usuario(\"pancho2012\", \"panchopa\", \"Pancho Sergio\", \"Villa\", \"Hermosil", "end": 486, "score": 0.9984579682350159, "start": 476, "tag": "USERNAME", "value": "pancho2012" }, { "context": " Usuario usuario = new Usuario(\"pancho2012\", \"panchopa\", \"Pancho Sergio\", \"Villa\", \"Hermosillo\", \"Sonora", "end": 498, "score": 0.9993012547492981, "start": 490, "tag": "USERNAME", "value": "panchopa" }, { "context": " usuario = new Usuario(\"pancho2012\", \"panchopa\", \"Pancho Sergio\", \"Villa\", \"Hermosillo\", \"Sonora\");\n \n ", "end": 515, "score": 0.999835729598999, "start": 502, "tag": "NAME", "value": "Pancho Sergio" }, { "context": "uario(\"pancho2012\", \"panchopa\", \"Pancho Sergio\", \"Villa\", \"Hermosillo\", \"Sonora\");\n \n usuar", "end": 524, "score": 0.999762773513794, "start": 519, "tag": "NAME", "value": "Villa" }, { "context": "ncho2012\", \"panchopa\", \"Pancho Sergio\", \"Villa\", \"Hermosillo\", \"Sonora\");\n \n usuarioDAO.create(u", "end": 538, "score": 0.9998346567153931, "start": 528, "tag": "NAME", "value": "Hermosillo" }, { "context": "nchopa\", \"Pancho Sergio\", \"Villa\", \"Hermosillo\", \"Sonora\");\n \n usuarioDAO.create(usuario);\n ", "end": 548, "score": 0.999792754650116, "start": 542, "tag": "NAME", "value": "Sonora" } ]
null
[]
package main; import daos.UsuarioJpaController; import objetosnegocio.Usuario; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Principal { public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory("seguridadInformaticaBD"); UsuarioJpaController usuarioDAO = new UsuarioJpaController(factory); Usuario usuario = new Usuario("pancho2012", "panchopa", "<NAME>", "Villa", "Hermosillo", "Sonora"); usuarioDAO.create(usuario); } }
603
0.716393
0.709836
20
29.5
33.012875
114
false
false
0
0
0
0
0
0
0.7
false
false
13
0ec42b698d4fed2722dad8f973439a10c811e1e7
14,955,076,134,330
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
/methods/Method_1004329.java
83d8c3b63fc93a262314101ae8643c9ca3157e41
[]
no_license
P79N6A/icse_20_user_study
https://github.com/P79N6A/icse_20_user_study
5b9c42c6384502fdc9588430899f257761f1f506
8a3676bc96059ea2c4f6d209016f5088a5628f3c
refs/heads/master
2020-06-24T08:25:22.606000
2019-07-25T15:31:16
2019-07-25T15:31:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
@SuppressWarnings("ResultOfMethodCallIgnored") private synchronized void activate(Optional<Callback<T>> callback){ switch (state.get()) { case IDLE: originalCallback.set(callback.orNull()); tracker.registerCall(this); callback.apply(new Action<Callback<T>>(){ @Override public void apply( @NotNull Callback<T> callback){ callback.onStatusEvent(StatusEvent.SCHEDULED); } } ); break; case CANCELED: throw new ApolloCanceledException("Call is cancelled."); case TERMINATED: case ACTIVE: throw new IllegalStateException("Already Executed"); default : throw new IllegalStateException("Unknown state"); } state.set(ACTIVE); }
UTF-8
Java
635
java
Method_1004329.java
Java
[]
null
[]
@SuppressWarnings("ResultOfMethodCallIgnored") private synchronized void activate(Optional<Callback<T>> callback){ switch (state.get()) { case IDLE: originalCallback.set(callback.orNull()); tracker.registerCall(this); callback.apply(new Action<Callback<T>>(){ @Override public void apply( @NotNull Callback<T> callback){ callback.onStatusEvent(StatusEvent.SCHEDULED); } } ); break; case CANCELED: throw new ApolloCanceledException("Call is cancelled."); case TERMINATED: case ACTIVE: throw new IllegalStateException("Already Executed"); default : throw new IllegalStateException("Unknown state"); } state.set(ACTIVE); }
635
0.766929
0.766929
22
27.863636
27.568584
114
false
false
0
0
0
0
0
0
0.409091
false
false
13
a4fede84c70554313ef64d6a1aa5489491cfee58
9,947,144,269,919
c82b3141deb9e1f894aeeba1fa09db4a788513d4
/Week5DesignPatterns/src/q1and2strategy/TextFormatter.java
9abc6dc65c6d545a6d52993fb7576fc026293a2a
[]
no_license
BBK-PiJ-2015-56/SDPExercises
https://github.com/BBK-PiJ-2015-56/SDPExercises
2b18219b33603a47bb66c8946cb3d86a2631993b
b6e9bfcf604a19bf582de832ef68e831d7441346
refs/heads/master
2016-09-01T08:43:44.801000
2016-02-07T17:17:22
2016-02-07T17:17:22
50,923,184
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package q1and2strategy; /** * Created by pdomok01 on 02/02/2016. */ /* public interface TextFormatter { void format(String text); } } */
UTF-8
Java
151
java
TextFormatter.java
Java
[ { "context": "package q1and2strategy;\n\n/**\n * Created by pdomok01 on 02/02/2016.\n */\n/*\npublic interface TextFormat", "end": 51, "score": 0.9995058178901672, "start": 43, "tag": "USERNAME", "value": "pdomok01" } ]
null
[]
package q1and2strategy; /** * Created by pdomok01 on 02/02/2016. */ /* public interface TextFormatter { void format(String text); } } */
151
0.635762
0.556291
11
12.818182
14.319841
37
false
false
0
0
0
0
0
0
0.181818
false
false
13
7e69bb19568190b30330ea55be9ecd05666fd88b
27,539,330,313,631
08beee298f66b25ce71d5152a51279b9119fec75
/src/com/myblog/web/struts/form/ArticleForm.java
2ffd9dea463b3f6f74b1470275e04c8578ef036a
[]
no_license
Switch-vov/MyBlog
https://github.com/Switch-vov/MyBlog
201b0b755c67e2d22ff8ddd7cb40397fa15ea30d
019a7395809097120a00e9e343126c7d97be8924
refs/heads/master
2021-01-01T04:00:15.381000
2016-04-26T04:55:55
2016-04-26T04:55:55
56,419,636
6
7
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myblog.web.struts.form; import org.apache.struts.action.ActionForm; public class ArticleForm extends ActionForm { /** * @Fields serialVersionUID : TODO */ private static final long serialVersionUID = -5003037702940222435L; private String articleId; private String userId; private String title; private String content; public String getArticleId() { return articleId; } public void setArticleId(String articleId) { this.articleId = articleId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
UTF-8
Java
828
java
ArticleForm.java
Java
[]
null
[]
package com.myblog.web.struts.form; import org.apache.struts.action.ActionForm; public class ArticleForm extends ActionForm { /** * @Fields serialVersionUID : TODO */ private static final long serialVersionUID = -5003037702940222435L; private String articleId; private String userId; private String title; private String content; public String getArticleId() { return articleId; } public void setArticleId(String articleId) { this.articleId = articleId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
828
0.731884
0.708937
39
20.256411
16.560251
68
false
false
0
0
0
0
0
0
1.461538
false
false
13
53651428707c3f17112dd33453178038ddb66653
17,772,574,681,836
1f05ae9642e63329751e3b8d06f3aa965ca78fdb
/rest-demo-master/src/main/java/demos/springdata/jsondemo/init/DataInitializer.java
6b549b2f1ebd040471f6c11ee6d0f3b12d3192b6
[ "Apache-2.0" ]
permissive
iproduct/spring-data
https://github.com/iproduct/spring-data
a5b0d0a60d82d419e2c1856e9b72b788a8637e55
6bb83d5848d3783cbcdcb569546e58256690f3af
refs/heads/master
2023-01-11T22:28:36.211000
2020-11-23T19:53:51
2020-11-23T19:53:51
242,131,522
15
17
Apache-2.0
false
2023-01-05T10:24:14
2020-02-21T12:13:13
2022-10-23T10:32:11
2023-01-05T10:24:12
7,943
11
13
36
Java
false
false
package demos.springdata.jsondemo.init; import demos.springdata.jsondemo.model.Post; import demos.springdata.jsondemo.model.User; import demos.springdata.jsondemo.service.PostService; import demos.springdata.jsondemo.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Component; import javax.validation.ConstraintViolationException; import java.util.Arrays; import java.util.List; @Component @Slf4j public class DataInitializer implements CommandLineRunner { private static final List<Post> mockPosts = Arrays.asList( new Post("Welcome to Spring 5", "Spring 5 is great beacuse ..."), new Post("Dependency Injection", "Should I use DI or lookup ..."), new Post("New in Spring 5", "There are several ways to configure Spring beans.") ); @Autowired PostService articleService; @Autowired UserService userService; @Autowired private NamedParameterJdbcTemplate jdbcTemplate; @Override public void run(String... args) throws Exception { // Users init long usersCount = userService.getUsersCount(); log.info("Users count: {}", usersCount); // if (usersCount == 0) { List<User> defaultUsers = Arrays.asList( new User("admin", "admin", "DEFAULT", "ADMIN", "ROLE_ADMIN"), new User("ivan", "ivan", "Ivan", "Petrov", "ROLE_USER") ); defaultUsers.stream().forEach(user -> userService.createUser(user)); // SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(users); // jdbcTemplate.batchUpdate(UserRepositoryImpl.INSERT_SQL, batch); } log.info("Querying for user records:"); List<User> users = userService.getUsers(); users.stream().forEach(user -> log.info("{}", user.getUsername())); // Posts init long countBefore = articleService.getPostsCount(); if (users.size() > 0) { User defaultUser = users.get(0); if (countBefore == 0 && users.size() > 0) { mockPosts.stream().forEach(article -> article.setAuthor(defaultUser)); try { List<Post> created = articleService.createPostsBatch(mockPosts); log.info(">>> Posts batch created: {}", created); } catch (ConstraintViolationException ex) { log.error(">>> Constraint violation inserting articles: {} - {}", mockPosts, ex.getMessage()); } long countAfter = articleService.getPostsCount(); log.info(">>> Total count of articles created: {}", countAfter - countBefore); } } } }
UTF-8
Java
2,933
java
DataInitializer.java
Java
[ { "context": "rs = Arrays.asList(\n new User(\"admin\", \"admin\", \"DEFAULT\", \"ADMIN\", \"ROLE_ADMIN\"),\n ", "end": 1494, "score": 0.7591519951820374, "start": 1489, "tag": "USERNAME", "value": "admin" }, { "context": "IN\", \"ROLE_ADMIN\"),\n new User(\"ivan\", \"ivan\", \"Ivan\", \"Petrov\", \"ROLE_USER\")\n ", "end": 1575, "score": 0.9834322929382324, "start": 1571, "tag": "USERNAME", "value": "ivan" }, { "context": "LE_ADMIN\"),\n new User(\"ivan\", \"ivan\", \"Ivan\", \"Petrov\", \"ROLE_USER\")\n );\n\n", "end": 1583, "score": 0.8509334921836853, "start": 1579, "tag": "USERNAME", "value": "ivan" }, { "context": "\"),\n new User(\"ivan\", \"ivan\", \"Ivan\", \"Petrov\", \"ROLE_USER\")\n );\n\n ", "end": 1591, "score": 0.9994392395019531, "start": 1587, "tag": "NAME", "value": "Ivan" }, { "context": " new User(\"ivan\", \"ivan\", \"Ivan\", \"Petrov\", \"ROLE_USER\")\n );\n\n defaul", "end": 1601, "score": 0.9994475841522217, "start": 1595, "tag": "NAME", "value": "Petrov" } ]
null
[]
package demos.springdata.jsondemo.init; import demos.springdata.jsondemo.model.Post; import demos.springdata.jsondemo.model.User; import demos.springdata.jsondemo.service.PostService; import demos.springdata.jsondemo.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Component; import javax.validation.ConstraintViolationException; import java.util.Arrays; import java.util.List; @Component @Slf4j public class DataInitializer implements CommandLineRunner { private static final List<Post> mockPosts = Arrays.asList( new Post("Welcome to Spring 5", "Spring 5 is great beacuse ..."), new Post("Dependency Injection", "Should I use DI or lookup ..."), new Post("New in Spring 5", "There are several ways to configure Spring beans.") ); @Autowired PostService articleService; @Autowired UserService userService; @Autowired private NamedParameterJdbcTemplate jdbcTemplate; @Override public void run(String... args) throws Exception { // Users init long usersCount = userService.getUsersCount(); log.info("Users count: {}", usersCount); // if (usersCount == 0) { List<User> defaultUsers = Arrays.asList( new User("admin", "admin", "DEFAULT", "ADMIN", "ROLE_ADMIN"), new User("ivan", "ivan", "Ivan", "Petrov", "ROLE_USER") ); defaultUsers.stream().forEach(user -> userService.createUser(user)); // SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(users); // jdbcTemplate.batchUpdate(UserRepositoryImpl.INSERT_SQL, batch); } log.info("Querying for user records:"); List<User> users = userService.getUsers(); users.stream().forEach(user -> log.info("{}", user.getUsername())); // Posts init long countBefore = articleService.getPostsCount(); if (users.size() > 0) { User defaultUser = users.get(0); if (countBefore == 0 && users.size() > 0) { mockPosts.stream().forEach(article -> article.setAuthor(defaultUser)); try { List<Post> created = articleService.createPostsBatch(mockPosts); log.info(">>> Posts batch created: {}", created); } catch (ConstraintViolationException ex) { log.error(">>> Constraint violation inserting articles: {} - {}", mockPosts, ex.getMessage()); } long countAfter = articleService.getPostsCount(); log.info(">>> Total count of articles created: {}", countAfter - countBefore); } } } }
2,933
0.639618
0.635868
76
37.592106
30.394848
114
false
false
0
0
0
0
0
0
0.723684
false
false
13
f7286a7a8a7f0398d9d87c3105ad40c750a41ee0
37,967,510,917,110
e50985cdabd48cadda392d5ed3606ea4488a333b
/Project1JSF-FUNCIONA/src/java/utng/manejador/LocationBean.java
3765a6fe017649a55c7bec854f7565a7f81a245d
[]
no_license
jomura/R2DAIIUni3
https://github.com/jomura/R2DAIIUni3
0f1d388b4ab3bf702e13bdb94fc3ddce745e00b8
8a037ba6cc30856ba8a76d44759a30043d0f5bd5
refs/heads/master
2020-06-14T04:30:44.910000
2016-11-30T22:55:24
2016-11-30T22:55:24
75,234,139
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package utng.manejador; import java.io.Serializable; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import utng.datos.LocationDAO; import utng.modelo.Location; @ManagedBean @SessionScoped public class LocationBean implements Serializable{ private List<Location> locations; private Location location; public LocationBean() { } public List<Location> getLocations(){ return locations; } public void setLocations(List<Location> locations) { this.locations = locations; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public String listar(){ LocationDAO dao=new LocationDAO(); try { locations = dao.getAll(); } catch (Exception e) { e.printStackTrace(); } return "Locations"; //cambiar por el nombre en plurara de la tabla } public String eliminar(){ LocationDAO dao = new LocationDAO(); try { dao.delete(location); locations=dao.getAll(); } catch (Exception e) { e.printStackTrace(); } return "Eliminar"; } public String iniciar(){ location= new Location(); return "Iniciar"; } public String guardar(){ LocationDAO dao = new LocationDAO(); try{ if(location.getIdLocation()!=0){ dao.update(location); }else{ dao.insert(location); } locations= dao.getAll(); }catch (Exception e){ e.printStackTrace(); } return "Guardar"; } public String cancelar(){ return "Cancelar"; } public String editar(Location location){ this.location= location; return "Editar"; } }
UTF-8
Java
2,047
java
LocationBean.java
Java
[]
null
[]
package utng.manejador; import java.io.Serializable; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import utng.datos.LocationDAO; import utng.modelo.Location; @ManagedBean @SessionScoped public class LocationBean implements Serializable{ private List<Location> locations; private Location location; public LocationBean() { } public List<Location> getLocations(){ return locations; } public void setLocations(List<Location> locations) { this.locations = locations; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public String listar(){ LocationDAO dao=new LocationDAO(); try { locations = dao.getAll(); } catch (Exception e) { e.printStackTrace(); } return "Locations"; //cambiar por el nombre en plurara de la tabla } public String eliminar(){ LocationDAO dao = new LocationDAO(); try { dao.delete(location); locations=dao.getAll(); } catch (Exception e) { e.printStackTrace(); } return "Eliminar"; } public String iniciar(){ location= new Location(); return "Iniciar"; } public String guardar(){ LocationDAO dao = new LocationDAO(); try{ if(location.getIdLocation()!=0){ dao.update(location); }else{ dao.insert(location); } locations= dao.getAll(); }catch (Exception e){ e.printStackTrace(); } return "Guardar"; } public String cancelar(){ return "Cancelar"; } public String editar(Location location){ this.location= location; return "Editar"; } }
2,047
0.549585
0.549096
91
20.494505
16.386389
76
false
false
0
0
0
0
0
0
0.362637
false
false
13
63aff1462abe848c1235f0c9ce306668e4d542ab
36,163,624,667,986
b6f48732494495e7f896469f164936d932c1724b
/src/main/java/org/lappsgrid/cdc/xmi/Xmi2Lif.java
7d7500d256cde7957021f3b0652c16ed99437c7b
[ "Apache-2.0" ]
permissive
lappsgrid-incubator/xmi-converter
https://github.com/lappsgrid-incubator/xmi-converter
7071ae083c5cb7dbacfacf92ccdd6707abda9790
b103432215420373fa0501ee97a83ceac4d21462
refs/heads/master
2021-08-30T18:54:21.123000
2017-12-19T02:27:45
2017-12-19T02:27:45
114,701,398
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.lappsgrid.cdc.xmi; import org.lappsgrid.cdc.ConversionException; import org.lappsgrid.cdc.Converter; import org.lappsgrid.serialization.Serializer; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * Reads an XMI file and return the corresponding LIF json file. */ public class Xmi2Lif implements Converter { private SAXParser parser; private Handler handler; public Xmi2Lif() throws ParserConfigurationException, SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newSAXParser(); handler = new Handler(); } public String convert(File file) throws ConversionException { try { return convert(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new ConversionException(e); } } public String convert(String string) throws ConversionException { return convert(new ByteArrayInputStream(string.getBytes())); } public String convert(InputStream stream) throws ConversionException { try { parser.parse(stream, handler); } catch (SAXException | IOException e) { throw new ConversionException(e); } return Serializer.toPrettyJson(handler.getContainer()); } public static void main(String[] args) { if (args.length == 0) { System.out.println("No input filename provided."); return; } try { File file = new File(args[0]); InputStream stream = new FileInputStream(file); System.out.println(new Xmi2Lif().convert(stream)); } catch (SAXException | ParserConfigurationException | IOException e) { e.printStackTrace(); } } }
UTF-8
Java
1,927
java
Xmi2Lif.java
Java
[]
null
[]
package org.lappsgrid.cdc.xmi; import org.lappsgrid.cdc.ConversionException; import org.lappsgrid.cdc.Converter; import org.lappsgrid.serialization.Serializer; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * Reads an XMI file and return the corresponding LIF json file. */ public class Xmi2Lif implements Converter { private SAXParser parser; private Handler handler; public Xmi2Lif() throws ParserConfigurationException, SAXException { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newSAXParser(); handler = new Handler(); } public String convert(File file) throws ConversionException { try { return convert(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new ConversionException(e); } } public String convert(String string) throws ConversionException { return convert(new ByteArrayInputStream(string.getBytes())); } public String convert(InputStream stream) throws ConversionException { try { parser.parse(stream, handler); } catch (SAXException | IOException e) { throw new ConversionException(e); } return Serializer.toPrettyJson(handler.getContainer()); } public static void main(String[] args) { if (args.length == 0) { System.out.println("No input filename provided."); return; } try { File file = new File(args[0]); InputStream stream = new FileInputStream(file); System.out.println(new Xmi2Lif().convert(stream)); } catch (SAXException | ParserConfigurationException | IOException e) { e.printStackTrace(); } } }
1,927
0.750908
0.748313
82
22.5
22.091412
69
false
false
0
0
0
0
0
0
1.682927
false
false
13
d0116aee39f5085145351bb61bba2859304b2ab6
38,732,015,095,357
8c640d1085c46e5be33584ee3ef51fcb0a06b7a6
/OOP2/src/javaEssence/Source18_BindingTest2.java
8b298e98b754b54153fe9200a58596bbf5c5e5aa
[]
no_license
xoasml/javaEssence
https://github.com/xoasml/javaEssence
764dd0e57f5f406c8c60734fd6c473aab9060afa
a54e8d79bdfb23ea9d97619573e92aab834f1ea5
refs/heads/master
2023-02-11T17:15:16.999000
2021-01-17T17:55:44
2021-01-17T17:55:44
317,114,013
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javaEssence; public class Source18_BindingTest2 { public static void main(String[] args) { Parent18 p = new Child18(); Child18 c = new Child18(); System.out.println(p.x); p.method(); System.out.println(c.x); c.method(); } } class Parent18{ int x = 100; void method() { System.out.println("부모"); } } class Child18 extends Parent18{ }
UTF-8
Java
398
java
Source18_BindingTest2.java
Java
[]
null
[]
package javaEssence; public class Source18_BindingTest2 { public static void main(String[] args) { Parent18 p = new Child18(); Child18 c = new Child18(); System.out.println(p.x); p.method(); System.out.println(c.x); c.method(); } } class Parent18{ int x = 100; void method() { System.out.println("부모"); } } class Child18 extends Parent18{ }
398
0.611675
0.560914
25
13.84
13.141324
41
false
false
0
0
0
0
0
0
1.28
false
false
13
b88636f9ce93cf80e2891037f23c893f8717c87c
38,663,295,612,086
d6acef6a13fdf85bc84ba893f639c52bbf4462c0
/src/main/java/seedu/duck/command/CommandResult.java
96050fdaf920f50f61ac937ee5be9a93619a546f
[]
no_license
wangqinNick/ip
https://github.com/wangqinNick/ip
053c3526a1c701cf708456e95094517058066ce6
62f58d0e6d3214bbb2b9f0629c32c58bd3668413
refs/heads/master
2022-12-18T15:19:06.862000
2020-10-01T01:53:37
2020-10-01T01:53:37
290,249,066
1
0
null
true
2020-09-19T15:26:25
2020-08-25T15:14:16
2020-09-19T15:09:39
2020-09-19T15:26:24
121,867
0
0
0
Java
false
false
package seedu.duck.command; /** Display the execute result, by constructing a CommandResult object */ public class CommandResult { private final String feedbackToUser; /** * Constructs the CommandResult with information String feedbackToUser * @param feedbackToUser feedback to user */ public CommandResult(String feedbackToUser) { this.feedbackToUser = feedbackToUser; } /** * Returns the feedback String in the command result * @return the feedback String */ public String getFeedbackToUser() { return feedbackToUser; } }
UTF-8
Java
600
java
CommandResult.java
Java
[]
null
[]
package seedu.duck.command; /** Display the execute result, by constructing a CommandResult object */ public class CommandResult { private final String feedbackToUser; /** * Constructs the CommandResult with information String feedbackToUser * @param feedbackToUser feedback to user */ public CommandResult(String feedbackToUser) { this.feedbackToUser = feedbackToUser; } /** * Returns the feedback String in the command result * @return the feedback String */ public String getFeedbackToUser() { return feedbackToUser; } }
600
0.691667
0.691667
22
26.318182
23.443134
74
false
false
0
0
0
0
0
0
0.227273
false
false
13
1fa4ba6457f0425f38b5cb5d8e389520589c59e6
37,658,273,275,283
92cfc984da66aeae8174bfe683bf4a5e030ac343
/src/main/java/com/jure/widgettest/MainActivity.java
ee19234388b579ecfa29292d0c979aaba427fd74
[]
no_license
JureBevc/IoT-Widget
https://github.com/JureBevc/IoT-Widget
39a7214a192d28983466816aea2a218e1e90eab9
2b803ce50f6ebd58b0f64cf17f3e47ddb68aba91
refs/heads/master
2021-06-21T11:50:12.893000
2021-06-10T00:33:27
2021-06-10T00:33:27
127,953,157
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jure.widgettest; import android.Manifest; import android.app.Activity; import android.app.ActivityManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RemoteViews; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Calendar; import java.util.GregorianCalendar; import layout.AppWidget; public class MainActivity extends Activity { /* This activity handles the input of the user data and starts the update service for each individual widget. */ UpdateService updateService; DataWriter writer; Intent serviceIntent; // Server data private String Channel_ID = "", API_Key = "", serverURL = "http://api.thingspeak.com"; // Update frequency in minutes private int updateInterval = 1; // Data we get from server String updateData = ""; // The id of the current widget int id; // An array of empty strings used to reset field values String[] empty = {"", "", "", "", "", "", "", ""}; // Timeout data boolean timeoutAlert = false; // Is timeout alert on boolean timeoutRepeat = false; // Is it on repeat int timeoutAlertMinutes = 0; // How many minutes of timeout before we alert // Alerts through meta data boolean metaAlert = false; // Is meta alert on boolean metaRepeat = false; // Is it on repeat // Repeat values for all 8 fields boolean[] alertRepeat = new boolean[8]; // The data object of the current widget WidgetData currentWidgetData; // Fields, spinners and switches of all options Spinner[] spinners; EditText[] upperText; EditText[] lowerText; Switch[] repeatSwitches; EditText[] decimalText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); permissions(); setContentView(R.layout.activity_main); // Create the data writer writer = new DataWriter(this); // Create the update service updateService = new UpdateService(this); // Get the id of current widget getIdOfCurrentWidget(savedInstanceState); // Load the widget data of current widget currentWidgetData = updateService.widgetDataFromPreferences(writer.sharedPreferences, id); // Set default URL of server if widget does not contain a server URL if (currentWidgetData.serverURL.isEmpty()) { currentWidgetData.serverURL = serverURL; } // initUI(); // Start listeners for all input fields, buttons, etc. seekBarListener(); timeoutListener(); metaListener(); repeatListener(); channelInputListener(); apiInputListener(); serverInputListener(); fieldListSelectionListener(); doneButtonListener(); cancelButtonListener(); // Restore widget options from previous sessions setWidgetOptions(); } private void permissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED) { Log.e("PERMISSION NOT GRANTED", "1"); // No explanation needed; request the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.VIBRATE}, 1); }else Log.e("PERMISSION GRANTED", "1"); if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) { Log.e("PERMISSION NOT GRANTED", "2"); // No explanation needed; request the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 1); }else Log.e("PERMISSION GRANTED", "2"); } void initUI() { // Fields, spinners and switches of all options spinners = new Spinner[]{ findViewById(R.id.spinner1), findViewById(R.id.spinner2), findViewById(R.id.spinner3), findViewById(R.id.spinner4), findViewById(R.id.spinner5), findViewById(R.id.spinner6), findViewById(R.id.spinner7), findViewById(R.id.spinner8) }; upperText = new EditText[]{ findViewById(R.id.upperAlert1), findViewById(R.id.upperAlert2), findViewById(R.id.upperAlert3), findViewById(R.id.upperAlert4), findViewById(R.id.upperAlert5), findViewById(R.id.upperAlert6), findViewById(R.id.upperAlert7), findViewById(R.id.upperAlert8) }; lowerText = new EditText[]{ findViewById(R.id.lowerAlert1), findViewById(R.id.lowerAlert2), findViewById(R.id.lowerAlert3), findViewById(R.id.lowerAlert4), findViewById(R.id.lowerAlert5), findViewById(R.id.lowerAlert6), findViewById(R.id.lowerAlert7), findViewById(R.id.lowerAlert8) }; repeatSwitches = new Switch[]{ findViewById(R.id.boundsRepeat1), findViewById(R.id.boundsRepeat2), findViewById(R.id.boundsRepeat3), findViewById(R.id.boundsRepeat4), findViewById(R.id.boundsRepeat5), findViewById(R.id.boundsRepeat6), findViewById(R.id.boundsRepeat7), findViewById(R.id.boundsRepeat8) }; decimalText = new EditText[]{ findViewById(R.id.decimalPlaces1), findViewById(R.id.decimalPlaces2), findViewById(R.id.decimalPlaces3), findViewById(R.id.decimalPlaces4), findViewById(R.id.decimalPlaces5), findViewById(R.id.decimalPlaces6), findViewById(R.id.decimalPlaces7), findViewById(R.id.decimalPlaces8) }; } // Restores widget options from previous sessions void setWidgetOptions() { WidgetData w = currentWidgetData; if (w != null) { // Restore channel id Channel_ID = w.Channel_ID; final EditText channelInput = findViewById(R.id.ChannelID); channelInput.setText(w.Channel_ID); // Restore API Key API_Key = w.API_Key; final EditText apiInput = findViewById(R.id.APIKey); apiInput.setText(w.API_Key); // Restore update frequency bar final SeekBar updateIntervalBar = findViewById(R.id.UpdateTimeBar); updateIntervalBar.setProgress(w.updateInterval - 1); // Restore timeout alert options final Switch timeoutAlert = findViewById(R.id.timeoutAlertSwitch); timeoutAlert.setChecked(w.timeoutAlert); final Switch timeoutAlertRepeat = findViewById(R.id.repeatTimeoutAlert); timeoutAlertRepeat.setChecked(w.repeatTimeout); final SeekBar timeoutAlertDelay = findViewById(R.id.timoutSeeker); timeoutAlertDelay.setProgress(w.timeoutAlertThreshold); // Restore meta alert options final Switch metaAlert = findViewById(R.id.metaAlertSwitch); metaAlert.setChecked(w.metaAlert); final Switch repeatMeta = findViewById(R.id.repeatMetaAlert); repeatMeta.setChecked(w.repeatMeta); // Restore server URL final EditText serverURL = findViewById(R.id.serverURLInput); serverURL.setText(w.serverURL); // Restore options of all 8 fields for (int i = 0; i < 8; i++) { int selection = (w.fieldsInOrder[i] >= 0) ? w.fieldsInOrder[i] : 0; spinners[i].setSelection(selection); if (w.upperBoundAlert[i]) upperText[i].setText(w.upperBound[i] + ""); if (w.lowerBoundAlert[i]) lowerText[i].setText(w.lowerBound[i] + ""); if (w.decimalPlaces[i] >= 0) decimalText[i].setText(w.decimalPlaces[i] + ""); repeatSwitches[i].setChecked(w.repeatBounds[i]); } } } // Sets the listener for meta alert options void metaListener() { // On/off switch final Switch metaSwitch = findViewById(R.id.metaAlertSwitch); final LinearLayout metaInputLayer = findViewById(R.id.metaAlertInputLayer); metaSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Make the options visible only when checked if (isChecked) { metaInputLayer.setVisibility(View.VISIBLE); metaAlert = true; } else { metaInputLayer.setVisibility(View.GONE); metaAlert = false; } } }); // Repeat switch final Switch metaAlertRepeat = findViewById(R.id.repeatMetaAlert); metaAlertRepeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { metaRepeat = true; } else { metaRepeat = false; } } }); } void timeoutListener() { // Switch final Switch timeoutSwitch = findViewById(R.id.timeoutAlertSwitch); final LinearLayout timoutSeekerLayout = findViewById(R.id.timeoutSeekerLayout); timeoutSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { timoutSeekerLayout.setVisibility(View.VISIBLE); timeoutAlert = true; } else { timoutSeekerLayout.setVisibility(View.GONE); timeoutAlert = false; } } }); // Seek bar SeekBar timeoutSeeker = findViewById(R.id.timoutSeeker); final TextView timeoutSeekerText = findViewById(R.id.timeoutSeekerText); timeoutSeeker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { timeoutSeekerText.setText(progress + " min"); timeoutAlertMinutes = progress; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); // Repeat final Switch timeoutAlertRepeat = findViewById(R.id.repeatTimeoutAlert); timeoutAlertRepeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { timeoutRepeat = true; } else { timeoutRepeat = false; } } }); } void repeatListener() { // Switches final Switch[] repeatSwitches = { findViewById(R.id.boundsRepeat1), findViewById(R.id.boundsRepeat2), findViewById(R.id.boundsRepeat3), findViewById(R.id.boundsRepeat4), findViewById(R.id.boundsRepeat5), findViewById(R.id.boundsRepeat6), findViewById(R.id.boundsRepeat7), findViewById(R.id.boundsRepeat8) }; for (int i = 0; i < 8; i++) { final int index = i; repeatSwitches[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { alertRepeat[index] = true; } else { alertRepeat[index] = false; } } }); } } void fieldListSelectionListener() { final LinearLayout[] fieldOptions = new LinearLayout[]{ findViewById(R.id.fieldOptions1), findViewById(R.id.fieldOptions2), findViewById(R.id.fieldOptions3), findViewById(R.id.fieldOptions4), findViewById(R.id.fieldOptions5), findViewById(R.id.fieldOptions6), findViewById(R.id.fieldOptions7), findViewById(R.id.fieldOptions8) }; for (int i = 0; i < 8; i++) { final int index = i; spinners[i].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { if (position == 0) { fieldOptions[index].setVisibility(View.GONE); } else { fieldOptions[index].setVisibility(View.VISIBLE); } } @Override public void onNothingSelected(AdapterView<?> parentView) { fieldOptions[index].setVisibility(View.GONE); } }); } } /** * Get the Id of Current Widget from the intent of the Widget **/ void getIdOfCurrentWidget(Bundle savedInstanceState) { // get the appwidget id from the intent Intent intent = getIntent(); id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); Log.e("Widget ID", "" + id); // if we weren't started properly, finish here if (id == AppWidgetManager.INVALID_APPWIDGET_ID) { Toast.makeText(this, "Open App through a widget", Toast.LENGTH_LONG).show(); finish(); } } public void seekBarListener() { SeekBar seekBar = findViewById(R.id.UpdateTimeBar); final TextView seekBarValue = findViewById(R.id.UpdateTimeBarText); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { seekBarValue.setText(String.valueOf(progress + 1)); updateInterval = progress + 1; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } public void channelInputListener() { final EditText channelInput = findViewById(R.id.ChannelID); channelInput.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { changeChannelName(""); changeFieldList(empty); Channel_ID = channelInput.getText().toString(); setData(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } public void serverInputListener() { final EditText serverInput = findViewById(R.id.serverURLInput); serverInput.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { changeChannelName(""); changeFieldList(empty); serverURL = serverInput.getText().toString(); setData(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } public void apiInputListener() { final EditText apiInput = findViewById(R.id.APIKey); apiInput.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { changeChannelName(""); changeFieldList(empty); API_Key = apiInput.getText().toString(); setData(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } public void doneButtonListener() { ImageButton doneButton = findViewById(R.id.DoneButton); doneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setAlerts(); setDecimals(); sendToWidget(); setRepeating(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }); } public void cancelButtonListener() { ImageButton cancelButton = findViewById(R.id.CancelButton); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void changeChannelName(String name) { RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.app_widget); // Change channel name remoteViews.setTextViewText(R.id.ChannelText, name); TextView channelText = findViewById(R.id.ChannelNameText); channelText.setText(name); } public void changeFieldList(String[] fieldNames) { String[] newFieldList = new String[9]; for (int i = 0; i < 9; i++) { if (i == 0) { newFieldList[i] = "-"; } else { newFieldList[i] = i + fieldNames[i - 1]; } } ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, newFieldList); spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); for (Spinner s : spinners) { if (s != null) { int selected = s.getSelectedItemPosition(); s.setAdapter(spinnerArrayAdapter); s.setSelection(selected); } } } // Returns selected fields in order public int[] getFields() { int[] fields = {-1, -1, -1, -1, -1, -1, -1, -1}; for (int i = 0; i < 8; i++) { Spinner s = spinners[i]; if (s != null && s.getSelectedItemPosition() != 0) { fields[i] = s.getSelectedItemPosition(); } } return fields; } boolean[] lowerBoundSet = new boolean[8]; boolean[] upperBoundSet = new boolean[8]; double[] lowerBoundValue = new double[8]; double[] upperBoundValue = new double[8]; boolean[] repeat = new boolean[8]; public void setAlerts() { for (int i = 0; i < 8; i++) { Spinner s = spinners[i]; if (s != null && s.getSelectedItemPosition() != 0) { if (!lowerText[i].getText().toString().equals("")) { lowerBoundSet[i] = true; lowerBoundValue[i] = Double.parseDouble(lowerText[i].getText().toString()); } else { lowerBoundSet[i] = false; } if (!upperText[i].getText().toString().equals("")) { upperBoundSet[i] = true; upperBoundValue[i] = Double.parseDouble(upperText[i].getText().toString()); } else { upperBoundSet[i] = false; } } } WidgetData w = currentWidgetData; if (w != null) { Log.e("DATA", "DATA"); w.setLowerBound(lowerBoundSet.clone(), lowerBoundValue.clone()); w.setUpperBound(upperBoundSet.clone(), upperBoundValue.clone()); w.setTimeoutAlert(timeoutAlert, timeoutAlertMinutes); w.setMetaAlert(metaAlert); w.setBoundsRepeat(alertRepeat); w.repeatTimeout = timeoutRepeat; w.repeatMeta = metaRepeat; } } int decimals[] = {-1, -1, -1, -1, -1, -1, -1, -1}; public void setDecimals() { for (int i = 0; i < 8; i++) { Spinner s = spinners[i]; if (s != null && s.getSelectedItemPosition() != 0) { if (!decimalText[i].getText().toString().equals("")) { decimals[i] = Integer.parseInt(decimalText[i].getText().toString()); } else { decimals[i] = -1; } } } WidgetData w = currentWidgetData; if (w != null) { w.setDecimalPlaces(decimals); } } void setRepeating() { updateService.addWidget(writer, currentWidgetData); updateService.saveWidgetData(writer, currentWidgetData, true); AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); serviceIntent = new Intent(this, AlarmTrigger.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT); //manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent); Calendar calendar = Calendar.getInstance(); manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60000, pendingIntent); //Calendar updateTime = Calendar.getInstance(); //manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), 60000, pendingIntent); } @Override protected void onDestroy() { if (serviceIntent != null) stopService(serviceIntent); super.onDestroy(); } void sendToWidget() { currentWidgetData.init(id, serverURL, Channel_ID, API_Key, updateInterval, getFields()); if (updateData.equals("netFail")) { WidgetData w = currentWidgetData; if (w != null) { w.netFail = true; } } else { Log.e("Widget update", "Application call."); Intent intent = new Intent(this, AppWidget.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra("updateAPIKey", API_Key); intent.putExtra("updateChannel", Channel_ID); intent.putExtra("updateURL", serverURL); intent.putExtra("updateID", id); intent.putExtra("updateData", updateData); int[] ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), AppWidget.class)); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); sendBroadcast(intent); } } RetrieveData currentTask = null; void setData() { if (currentTask != null) currentTask.cancel(true); currentTask = new RetrieveData(); currentTask.execute(); } class RetrieveData extends AsyncTask<String, String, String> { String ret = null; @Override protected String doInBackground(String... strings) { try { String urlString = serverURL + "/channels/" + Channel_ID + "/feed.json?metadata=true&api_key=" + API_Key; URL url = new URL(urlString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); System.out.print("Response code: " + con.getResponseCode()); // Get response BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); ret = ""; String line; while ((line = br.readLine()) != null) { ret += line + "\n"; } br.close(); } catch (Exception e) { System.out.println("Data retrieving error:"); ret = "netFail"; //e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); try { // Change channel name in app if (!ret.equals("netFail")) { try { JSONObject obj = new JSONObject(ret); String channelName = obj.getJSONObject("channel").getString("name"); changeChannelName(channelName); } catch (Exception e) { // No channel name changeChannelName(""); } // Change field names in lists String[] fieldNames = empty.clone(); try { JSONObject obj = new JSONObject(ret); for (int i = 0; i < 8; i++) { fieldNames[i] = ": " + obj.getJSONObject("channel").getString("field" + (i + 1)); } } catch (Exception e) { // Field name error } changeFieldList(fieldNames); } else { changeChannelName(""); changeFieldList(empty); } updateData = ret; } catch (Exception e) { e.printStackTrace(); changeChannelName(""); changeFieldList(empty); } } } }
UTF-8
Java
27,783
java
MainActivity.java
Java
[]
null
[]
package com.jure.widgettest; import android.Manifest; import android.app.Activity; import android.app.ActivityManager; import android.app.AlarmManager; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RemoteViews; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Calendar; import java.util.GregorianCalendar; import layout.AppWidget; public class MainActivity extends Activity { /* This activity handles the input of the user data and starts the update service for each individual widget. */ UpdateService updateService; DataWriter writer; Intent serviceIntent; // Server data private String Channel_ID = "", API_Key = "", serverURL = "http://api.thingspeak.com"; // Update frequency in minutes private int updateInterval = 1; // Data we get from server String updateData = ""; // The id of the current widget int id; // An array of empty strings used to reset field values String[] empty = {"", "", "", "", "", "", "", ""}; // Timeout data boolean timeoutAlert = false; // Is timeout alert on boolean timeoutRepeat = false; // Is it on repeat int timeoutAlertMinutes = 0; // How many minutes of timeout before we alert // Alerts through meta data boolean metaAlert = false; // Is meta alert on boolean metaRepeat = false; // Is it on repeat // Repeat values for all 8 fields boolean[] alertRepeat = new boolean[8]; // The data object of the current widget WidgetData currentWidgetData; // Fields, spinners and switches of all options Spinner[] spinners; EditText[] upperText; EditText[] lowerText; Switch[] repeatSwitches; EditText[] decimalText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); permissions(); setContentView(R.layout.activity_main); // Create the data writer writer = new DataWriter(this); // Create the update service updateService = new UpdateService(this); // Get the id of current widget getIdOfCurrentWidget(savedInstanceState); // Load the widget data of current widget currentWidgetData = updateService.widgetDataFromPreferences(writer.sharedPreferences, id); // Set default URL of server if widget does not contain a server URL if (currentWidgetData.serverURL.isEmpty()) { currentWidgetData.serverURL = serverURL; } // initUI(); // Start listeners for all input fields, buttons, etc. seekBarListener(); timeoutListener(); metaListener(); repeatListener(); channelInputListener(); apiInputListener(); serverInputListener(); fieldListSelectionListener(); doneButtonListener(); cancelButtonListener(); // Restore widget options from previous sessions setWidgetOptions(); } private void permissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.VIBRATE) != PackageManager.PERMISSION_GRANTED) { Log.e("PERMISSION NOT GRANTED", "1"); // No explanation needed; request the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.VIBRATE}, 1); }else Log.e("PERMISSION GRANTED", "1"); if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) { Log.e("PERMISSION NOT GRANTED", "2"); // No explanation needed; request the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, 1); }else Log.e("PERMISSION GRANTED", "2"); } void initUI() { // Fields, spinners and switches of all options spinners = new Spinner[]{ findViewById(R.id.spinner1), findViewById(R.id.spinner2), findViewById(R.id.spinner3), findViewById(R.id.spinner4), findViewById(R.id.spinner5), findViewById(R.id.spinner6), findViewById(R.id.spinner7), findViewById(R.id.spinner8) }; upperText = new EditText[]{ findViewById(R.id.upperAlert1), findViewById(R.id.upperAlert2), findViewById(R.id.upperAlert3), findViewById(R.id.upperAlert4), findViewById(R.id.upperAlert5), findViewById(R.id.upperAlert6), findViewById(R.id.upperAlert7), findViewById(R.id.upperAlert8) }; lowerText = new EditText[]{ findViewById(R.id.lowerAlert1), findViewById(R.id.lowerAlert2), findViewById(R.id.lowerAlert3), findViewById(R.id.lowerAlert4), findViewById(R.id.lowerAlert5), findViewById(R.id.lowerAlert6), findViewById(R.id.lowerAlert7), findViewById(R.id.lowerAlert8) }; repeatSwitches = new Switch[]{ findViewById(R.id.boundsRepeat1), findViewById(R.id.boundsRepeat2), findViewById(R.id.boundsRepeat3), findViewById(R.id.boundsRepeat4), findViewById(R.id.boundsRepeat5), findViewById(R.id.boundsRepeat6), findViewById(R.id.boundsRepeat7), findViewById(R.id.boundsRepeat8) }; decimalText = new EditText[]{ findViewById(R.id.decimalPlaces1), findViewById(R.id.decimalPlaces2), findViewById(R.id.decimalPlaces3), findViewById(R.id.decimalPlaces4), findViewById(R.id.decimalPlaces5), findViewById(R.id.decimalPlaces6), findViewById(R.id.decimalPlaces7), findViewById(R.id.decimalPlaces8) }; } // Restores widget options from previous sessions void setWidgetOptions() { WidgetData w = currentWidgetData; if (w != null) { // Restore channel id Channel_ID = w.Channel_ID; final EditText channelInput = findViewById(R.id.ChannelID); channelInput.setText(w.Channel_ID); // Restore API Key API_Key = w.API_Key; final EditText apiInput = findViewById(R.id.APIKey); apiInput.setText(w.API_Key); // Restore update frequency bar final SeekBar updateIntervalBar = findViewById(R.id.UpdateTimeBar); updateIntervalBar.setProgress(w.updateInterval - 1); // Restore timeout alert options final Switch timeoutAlert = findViewById(R.id.timeoutAlertSwitch); timeoutAlert.setChecked(w.timeoutAlert); final Switch timeoutAlertRepeat = findViewById(R.id.repeatTimeoutAlert); timeoutAlertRepeat.setChecked(w.repeatTimeout); final SeekBar timeoutAlertDelay = findViewById(R.id.timoutSeeker); timeoutAlertDelay.setProgress(w.timeoutAlertThreshold); // Restore meta alert options final Switch metaAlert = findViewById(R.id.metaAlertSwitch); metaAlert.setChecked(w.metaAlert); final Switch repeatMeta = findViewById(R.id.repeatMetaAlert); repeatMeta.setChecked(w.repeatMeta); // Restore server URL final EditText serverURL = findViewById(R.id.serverURLInput); serverURL.setText(w.serverURL); // Restore options of all 8 fields for (int i = 0; i < 8; i++) { int selection = (w.fieldsInOrder[i] >= 0) ? w.fieldsInOrder[i] : 0; spinners[i].setSelection(selection); if (w.upperBoundAlert[i]) upperText[i].setText(w.upperBound[i] + ""); if (w.lowerBoundAlert[i]) lowerText[i].setText(w.lowerBound[i] + ""); if (w.decimalPlaces[i] >= 0) decimalText[i].setText(w.decimalPlaces[i] + ""); repeatSwitches[i].setChecked(w.repeatBounds[i]); } } } // Sets the listener for meta alert options void metaListener() { // On/off switch final Switch metaSwitch = findViewById(R.id.metaAlertSwitch); final LinearLayout metaInputLayer = findViewById(R.id.metaAlertInputLayer); metaSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Make the options visible only when checked if (isChecked) { metaInputLayer.setVisibility(View.VISIBLE); metaAlert = true; } else { metaInputLayer.setVisibility(View.GONE); metaAlert = false; } } }); // Repeat switch final Switch metaAlertRepeat = findViewById(R.id.repeatMetaAlert); metaAlertRepeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { metaRepeat = true; } else { metaRepeat = false; } } }); } void timeoutListener() { // Switch final Switch timeoutSwitch = findViewById(R.id.timeoutAlertSwitch); final LinearLayout timoutSeekerLayout = findViewById(R.id.timeoutSeekerLayout); timeoutSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { timoutSeekerLayout.setVisibility(View.VISIBLE); timeoutAlert = true; } else { timoutSeekerLayout.setVisibility(View.GONE); timeoutAlert = false; } } }); // Seek bar SeekBar timeoutSeeker = findViewById(R.id.timoutSeeker); final TextView timeoutSeekerText = findViewById(R.id.timeoutSeekerText); timeoutSeeker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { timeoutSeekerText.setText(progress + " min"); timeoutAlertMinutes = progress; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); // Repeat final Switch timeoutAlertRepeat = findViewById(R.id.repeatTimeoutAlert); timeoutAlertRepeat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { timeoutRepeat = true; } else { timeoutRepeat = false; } } }); } void repeatListener() { // Switches final Switch[] repeatSwitches = { findViewById(R.id.boundsRepeat1), findViewById(R.id.boundsRepeat2), findViewById(R.id.boundsRepeat3), findViewById(R.id.boundsRepeat4), findViewById(R.id.boundsRepeat5), findViewById(R.id.boundsRepeat6), findViewById(R.id.boundsRepeat7), findViewById(R.id.boundsRepeat8) }; for (int i = 0; i < 8; i++) { final int index = i; repeatSwitches[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { alertRepeat[index] = true; } else { alertRepeat[index] = false; } } }); } } void fieldListSelectionListener() { final LinearLayout[] fieldOptions = new LinearLayout[]{ findViewById(R.id.fieldOptions1), findViewById(R.id.fieldOptions2), findViewById(R.id.fieldOptions3), findViewById(R.id.fieldOptions4), findViewById(R.id.fieldOptions5), findViewById(R.id.fieldOptions6), findViewById(R.id.fieldOptions7), findViewById(R.id.fieldOptions8) }; for (int i = 0; i < 8; i++) { final int index = i; spinners[i].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) { if (position == 0) { fieldOptions[index].setVisibility(View.GONE); } else { fieldOptions[index].setVisibility(View.VISIBLE); } } @Override public void onNothingSelected(AdapterView<?> parentView) { fieldOptions[index].setVisibility(View.GONE); } }); } } /** * Get the Id of Current Widget from the intent of the Widget **/ void getIdOfCurrentWidget(Bundle savedInstanceState) { // get the appwidget id from the intent Intent intent = getIntent(); id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); Log.e("Widget ID", "" + id); // if we weren't started properly, finish here if (id == AppWidgetManager.INVALID_APPWIDGET_ID) { Toast.makeText(this, "Open App through a widget", Toast.LENGTH_LONG).show(); finish(); } } public void seekBarListener() { SeekBar seekBar = findViewById(R.id.UpdateTimeBar); final TextView seekBarValue = findViewById(R.id.UpdateTimeBarText); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { seekBarValue.setText(String.valueOf(progress + 1)); updateInterval = progress + 1; } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } public void channelInputListener() { final EditText channelInput = findViewById(R.id.ChannelID); channelInput.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { changeChannelName(""); changeFieldList(empty); Channel_ID = channelInput.getText().toString(); setData(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } public void serverInputListener() { final EditText serverInput = findViewById(R.id.serverURLInput); serverInput.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { changeChannelName(""); changeFieldList(empty); serverURL = serverInput.getText().toString(); setData(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } public void apiInputListener() { final EditText apiInput = findViewById(R.id.APIKey); apiInput.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { changeChannelName(""); changeFieldList(empty); API_Key = apiInput.getText().toString(); setData(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } public void doneButtonListener() { ImageButton doneButton = findViewById(R.id.DoneButton); doneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setAlerts(); setDecimals(); sendToWidget(); setRepeating(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }); } public void cancelButtonListener() { ImageButton cancelButton = findViewById(R.id.CancelButton); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void changeChannelName(String name) { RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.app_widget); // Change channel name remoteViews.setTextViewText(R.id.ChannelText, name); TextView channelText = findViewById(R.id.ChannelNameText); channelText.setText(name); } public void changeFieldList(String[] fieldNames) { String[] newFieldList = new String[9]; for (int i = 0; i < 9; i++) { if (i == 0) { newFieldList[i] = "-"; } else { newFieldList[i] = i + fieldNames[i - 1]; } } ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, newFieldList); spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); for (Spinner s : spinners) { if (s != null) { int selected = s.getSelectedItemPosition(); s.setAdapter(spinnerArrayAdapter); s.setSelection(selected); } } } // Returns selected fields in order public int[] getFields() { int[] fields = {-1, -1, -1, -1, -1, -1, -1, -1}; for (int i = 0; i < 8; i++) { Spinner s = spinners[i]; if (s != null && s.getSelectedItemPosition() != 0) { fields[i] = s.getSelectedItemPosition(); } } return fields; } boolean[] lowerBoundSet = new boolean[8]; boolean[] upperBoundSet = new boolean[8]; double[] lowerBoundValue = new double[8]; double[] upperBoundValue = new double[8]; boolean[] repeat = new boolean[8]; public void setAlerts() { for (int i = 0; i < 8; i++) { Spinner s = spinners[i]; if (s != null && s.getSelectedItemPosition() != 0) { if (!lowerText[i].getText().toString().equals("")) { lowerBoundSet[i] = true; lowerBoundValue[i] = Double.parseDouble(lowerText[i].getText().toString()); } else { lowerBoundSet[i] = false; } if (!upperText[i].getText().toString().equals("")) { upperBoundSet[i] = true; upperBoundValue[i] = Double.parseDouble(upperText[i].getText().toString()); } else { upperBoundSet[i] = false; } } } WidgetData w = currentWidgetData; if (w != null) { Log.e("DATA", "DATA"); w.setLowerBound(lowerBoundSet.clone(), lowerBoundValue.clone()); w.setUpperBound(upperBoundSet.clone(), upperBoundValue.clone()); w.setTimeoutAlert(timeoutAlert, timeoutAlertMinutes); w.setMetaAlert(metaAlert); w.setBoundsRepeat(alertRepeat); w.repeatTimeout = timeoutRepeat; w.repeatMeta = metaRepeat; } } int decimals[] = {-1, -1, -1, -1, -1, -1, -1, -1}; public void setDecimals() { for (int i = 0; i < 8; i++) { Spinner s = spinners[i]; if (s != null && s.getSelectedItemPosition() != 0) { if (!decimalText[i].getText().toString().equals("")) { decimals[i] = Integer.parseInt(decimalText[i].getText().toString()); } else { decimals[i] = -1; } } } WidgetData w = currentWidgetData; if (w != null) { w.setDecimalPlaces(decimals); } } void setRepeating() { updateService.addWidget(writer, currentWidgetData); updateService.saveWidgetData(writer, currentWidgetData, true); AlarmManager manager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); serviceIntent = new Intent(this, AlarmTrigger.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT); //manager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent); Calendar calendar = Calendar.getInstance(); manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60000, pendingIntent); //Calendar updateTime = Calendar.getInstance(); //manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), 60000, pendingIntent); } @Override protected void onDestroy() { if (serviceIntent != null) stopService(serviceIntent); super.onDestroy(); } void sendToWidget() { currentWidgetData.init(id, serverURL, Channel_ID, API_Key, updateInterval, getFields()); if (updateData.equals("netFail")) { WidgetData w = currentWidgetData; if (w != null) { w.netFail = true; } } else { Log.e("Widget update", "Application call."); Intent intent = new Intent(this, AppWidget.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra("updateAPIKey", API_Key); intent.putExtra("updateChannel", Channel_ID); intent.putExtra("updateURL", serverURL); intent.putExtra("updateID", id); intent.putExtra("updateData", updateData); int[] ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), AppWidget.class)); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); sendBroadcast(intent); } } RetrieveData currentTask = null; void setData() { if (currentTask != null) currentTask.cancel(true); currentTask = new RetrieveData(); currentTask.execute(); } class RetrieveData extends AsyncTask<String, String, String> { String ret = null; @Override protected String doInBackground(String... strings) { try { String urlString = serverURL + "/channels/" + Channel_ID + "/feed.json?metadata=true&api_key=" + API_Key; URL url = new URL(urlString); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); System.out.print("Response code: " + con.getResponseCode()); // Get response BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); ret = ""; String line; while ((line = br.readLine()) != null) { ret += line + "\n"; } br.close(); } catch (Exception e) { System.out.println("Data retrieving error:"); ret = "netFail"; //e.printStackTrace(); } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); try { // Change channel name in app if (!ret.equals("netFail")) { try { JSONObject obj = new JSONObject(ret); String channelName = obj.getJSONObject("channel").getString("name"); changeChannelName(channelName); } catch (Exception e) { // No channel name changeChannelName(""); } // Change field names in lists String[] fieldNames = empty.clone(); try { JSONObject obj = new JSONObject(ret); for (int i = 0; i < 8; i++) { fieldNames[i] = ": " + obj.getJSONObject("channel").getString("field" + (i + 1)); } } catch (Exception e) { // Field name error } changeFieldList(fieldNames); } else { changeChannelName(""); changeFieldList(empty); } updateData = ret; } catch (Exception e) { e.printStackTrace(); changeChannelName(""); changeFieldList(empty); } } } }
27,783
0.568873
0.563942
770
35.081818
26.269527
141
false
false
0
0
0
0
0
0
0.625974
false
false
13
5cd48bb1c0a090842b4313c0a721d8fd1dcb6f93
39,204,461,483,461
47ddacee026af6f78f1ae5a521f4c2be9bd24832
/src/de/webdataplatform/viewmanager/processing/PreProcessing.java
fe3dc77b9b9e91967e3c6033230fb7acb04ee855
[]
no_license
uniquehwb/ViewMaintenanceInWDP
https://github.com/uniquehwb/ViewMaintenanceInWDP
094850c23d548af8993518ece1a65ccc1d49d3c4
95a65f76530689f32fa9f9c9fe5595484ba50937
refs/heads/master
2020-05-17T08:35:17.783000
2015-10-27T14:16:54
2015-10-27T14:16:54
41,363,789
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.webdataplatform.viewmanager.processing; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import de.webdataplatform.log.Log; import de.webdataplatform.settings.SystemConfig; import de.webdataplatform.storage.BaseTableUpdate; import de.webdataplatform.view.TableService; import de.webdataplatform.view.ViewDefinitions; public class PreProcessing implements Runnable{ private Queue<String> incomingQueue; private Queue<BaseTableUpdate> outgoingQueue; // private Queue<String> statusQueue; private ViewDefinitions getViews; private AnalyzeLoad analyzeLoad; private Log log; private long btuLastTimestamp=123l; private BaseTableUpdate btuLast=null; private String keyLast=""; public PreProcessing(Log log, Queue<String> incomingQueue, Queue<BaseTableUpdate> outgoingQueue){ this.incomingQueue = incomingQueue; this.outgoingQueue = outgoingQueue; // this.statusQueue = statusQueue; this.log = log; updatesReceived = new AtomicLong(); getViews = new ViewDefinitions(log, "viewdefinitions"); getViews.loadViewDefinitions(); updatesPreProcessed = new AtomicLong(); // analyzeLoad = new AnalyzeLoad(statusQueue); } private long lastMeasure= new Date().getTime(); private AtomicLong updatesReceived; private AtomicLong updatesPreProcessed; @Override public void run() { while(true){ String update=""; try{ long currentTime = new Date().getTime(); if((currentTime - lastMeasure) > SystemConfig.VIEWMANAGER_DISPLAYINTERVAL){ lastMeasure = currentTime; log.info(this.getClass()," ---------------------"); log.info(this.getClass()," input queue size: "+incomingQueue.size()); log.info(this.getClass()," updates received: "+updatesReceived.get()); // log.info(this.getClass()," load currently at "+outgoingQueue.size()); log.info(this.getClass()," ---------------------"); } if(outgoingQueue.size() < 5000){ update = incomingQueue.poll(); if(update != null){ if(SystemConfig.LOGGING_LOGUPDATES)log.info(this.getClass(),"pre-processing update: "+update); BaseTableUpdate baseTableUpdate = new BaseTableUpdate(log, update); if(baseTableUpdate.getBaseTable().startsWith(SystemConfig.MESSAGES_MARKERPREFIX)){ // log.info(this.getClass(),"marker received, putting to map: "+baseTableUpdate); outgoingQueue.add(baseTableUpdate); // markers.put(baseTableUpdate.getBaseTable(), baseTableUpdate.getRegionServer()); continue; } // if(btuLastTimestamp == Long.parseLong(baseTableUpdate.getTimestamp())&& keyLast.equals(baseTableUpdate.getKey())){ // log.info(this.getClass(), "Equal timestamp received:"+btuLastTimestamp+", old btu:"+btuLast); // log.info(this.getClass(), "Equal timestamp received:"+btuLastTimestamp+", new btu:"+baseTableUpdate); // // } // btuLastTimestamp = Long.parseLong(baseTableUpdate.getTimestamp()); // btuLast = baseTableUpdate; // keyLast = baseTableUpdate.getKey(); // if(baseTableUpdate.getColumns().containsKey("finishMarker")){ // //// TableService tableService = new TableService(log); //// //// Map<byte[],byte[]> cols = new HashMap<byte[], byte[]>(); //// cols.put(Bytes.toBytes("client"), Bytes.toBytes("client")); //// tableService.put(Bytes.toBytes("finish_markers"), Bytes.toBytes(baseTableUpdate.getKey().split(":")[1]), cols); // // log.info(this.getClass(),"finish marker received"); // // outgoingQueue.add(baseTableUpdate); // continue; // } updatesReceived.incrementAndGet(); // outgoingQueue.add(baseTableUpdate); // Here the next view is added into update. List<BaseTableUpdate> baseTableViewUpdates =getViews.process(baseTableUpdate); if(baseTableViewUpdates != null){ for(BaseTableUpdate baseTableViewUpdate : baseTableViewUpdates){ outgoingQueue.add(baseTableViewUpdate); log.update(this.getClass(), "baseTableUpdate pre-processed"+baseTableViewUpdate.toString()); } } updatesPreProcessed.incrementAndGet(); // analyzeLoad.process(outgoingQueue.size()); } } // if(outgoingQueue.size() > 5000){ // try { // Thread.sleep(Constants.UPDATE_POLLING_INTERVAL); // } catch (InterruptedException e) { // // e.printStackTrace(); // } // } }catch(Exception e){ log.error(this.getClass(), e); log.info(this.getClass(),"Exception caught for update: "+update); } } } public AtomicLong getUpdatesReceived() { return updatesReceived; } public void setUpdatesReceived(AtomicLong updatesReceived) { this.updatesReceived = updatesReceived; } public AtomicLong getUpdatesPreProcessed() { return updatesPreProcessed; } public void setUpdatesPreProcessed(AtomicLong updatesPreProcessed) { this.updatesPreProcessed = updatesPreProcessed; } }
UTF-8
Java
5,355
java
PreProcessing.java
Java
[]
null
[]
package de.webdataplatform.viewmanager.processing; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import de.webdataplatform.log.Log; import de.webdataplatform.settings.SystemConfig; import de.webdataplatform.storage.BaseTableUpdate; import de.webdataplatform.view.TableService; import de.webdataplatform.view.ViewDefinitions; public class PreProcessing implements Runnable{ private Queue<String> incomingQueue; private Queue<BaseTableUpdate> outgoingQueue; // private Queue<String> statusQueue; private ViewDefinitions getViews; private AnalyzeLoad analyzeLoad; private Log log; private long btuLastTimestamp=123l; private BaseTableUpdate btuLast=null; private String keyLast=""; public PreProcessing(Log log, Queue<String> incomingQueue, Queue<BaseTableUpdate> outgoingQueue){ this.incomingQueue = incomingQueue; this.outgoingQueue = outgoingQueue; // this.statusQueue = statusQueue; this.log = log; updatesReceived = new AtomicLong(); getViews = new ViewDefinitions(log, "viewdefinitions"); getViews.loadViewDefinitions(); updatesPreProcessed = new AtomicLong(); // analyzeLoad = new AnalyzeLoad(statusQueue); } private long lastMeasure= new Date().getTime(); private AtomicLong updatesReceived; private AtomicLong updatesPreProcessed; @Override public void run() { while(true){ String update=""; try{ long currentTime = new Date().getTime(); if((currentTime - lastMeasure) > SystemConfig.VIEWMANAGER_DISPLAYINTERVAL){ lastMeasure = currentTime; log.info(this.getClass()," ---------------------"); log.info(this.getClass()," input queue size: "+incomingQueue.size()); log.info(this.getClass()," updates received: "+updatesReceived.get()); // log.info(this.getClass()," load currently at "+outgoingQueue.size()); log.info(this.getClass()," ---------------------"); } if(outgoingQueue.size() < 5000){ update = incomingQueue.poll(); if(update != null){ if(SystemConfig.LOGGING_LOGUPDATES)log.info(this.getClass(),"pre-processing update: "+update); BaseTableUpdate baseTableUpdate = new BaseTableUpdate(log, update); if(baseTableUpdate.getBaseTable().startsWith(SystemConfig.MESSAGES_MARKERPREFIX)){ // log.info(this.getClass(),"marker received, putting to map: "+baseTableUpdate); outgoingQueue.add(baseTableUpdate); // markers.put(baseTableUpdate.getBaseTable(), baseTableUpdate.getRegionServer()); continue; } // if(btuLastTimestamp == Long.parseLong(baseTableUpdate.getTimestamp())&& keyLast.equals(baseTableUpdate.getKey())){ // log.info(this.getClass(), "Equal timestamp received:"+btuLastTimestamp+", old btu:"+btuLast); // log.info(this.getClass(), "Equal timestamp received:"+btuLastTimestamp+", new btu:"+baseTableUpdate); // // } // btuLastTimestamp = Long.parseLong(baseTableUpdate.getTimestamp()); // btuLast = baseTableUpdate; // keyLast = baseTableUpdate.getKey(); // if(baseTableUpdate.getColumns().containsKey("finishMarker")){ // //// TableService tableService = new TableService(log); //// //// Map<byte[],byte[]> cols = new HashMap<byte[], byte[]>(); //// cols.put(Bytes.toBytes("client"), Bytes.toBytes("client")); //// tableService.put(Bytes.toBytes("finish_markers"), Bytes.toBytes(baseTableUpdate.getKey().split(":")[1]), cols); // // log.info(this.getClass(),"finish marker received"); // // outgoingQueue.add(baseTableUpdate); // continue; // } updatesReceived.incrementAndGet(); // outgoingQueue.add(baseTableUpdate); // Here the next view is added into update. List<BaseTableUpdate> baseTableViewUpdates =getViews.process(baseTableUpdate); if(baseTableViewUpdates != null){ for(BaseTableUpdate baseTableViewUpdate : baseTableViewUpdates){ outgoingQueue.add(baseTableViewUpdate); log.update(this.getClass(), "baseTableUpdate pre-processed"+baseTableViewUpdate.toString()); } } updatesPreProcessed.incrementAndGet(); // analyzeLoad.process(outgoingQueue.size()); } } // if(outgoingQueue.size() > 5000){ // try { // Thread.sleep(Constants.UPDATE_POLLING_INTERVAL); // } catch (InterruptedException e) { // // e.printStackTrace(); // } // } }catch(Exception e){ log.error(this.getClass(), e); log.info(this.getClass(),"Exception caught for update: "+update); } } } public AtomicLong getUpdatesReceived() { return updatesReceived; } public void setUpdatesReceived(AtomicLong updatesReceived) { this.updatesReceived = updatesReceived; } public AtomicLong getUpdatesPreProcessed() { return updatesPreProcessed; } public void setUpdatesPreProcessed(AtomicLong updatesPreProcessed) { this.updatesPreProcessed = updatesPreProcessed; } }
5,355
0.666667
0.664426
186
26.790323
28.804012
121
false
false
0
0
0
0
0
0
3.139785
false
false
13
df426c1b38a892486243bf5ea0d0b06e615f3d59
39,204,461,485,823
4fbe12bae00fb6e7f977bd819131a2095d5fd2da
/ZeratulEJB/ejbModule/ejb/AnalistaTecnicoBean.java
aabada4ae245bbcafab272cd5da69e6c71781017
[]
no_license
normanhughes/Zeratul
https://github.com/normanhughes/Zeratul
5db1bae4000eaf60f25b49740544eba71c898e29
ccb172f4300c3f9e914900124a663b3c9dda7492
refs/heads/master
2016-09-09T23:55:15.790000
2015-12-02T22:18:20
2015-12-02T22:18:20
41,380,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ejb; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import dao.AnalistaTecnico; import dao.Fornecedor; /** * Session Bean implementation class AnalistaTecnicoBean */ @Stateless @LocalBean public class AnalistaTecnicoBean implements AnalistaTecnicoBeanLocal { // IMPORTANTE EM TODOS O @PERSITENSECONTEXT - copiar as duas linhas // seguintes. @PersistenceContext(name = "zeratulcontext") private EntityManager banco; public List<AnalistaTecnico> getTodosAnalistas() { Query consultaAnalistas = banco.createNamedQuery("todosAnalistas"); return consultaAnalistas.getResultList(); } public List<AnalistaTecnico> getAnalistaPorNome(String nomeAnalista) { Query consultaNome = banco.createNamedQuery("analistaPorNome"); consultaNome.setParameter("nomeTec", String.format("\\%%s\\%", nomeAnalista)); return consultaNome.getResultList(); } public void save(AnalistaTecnico tecnico) { if (banco.find(AnalistaTecnico.class, tecnico.getOid()) == null) { // insert banco.persist(tecnico); } else { // update banco.merge(tecnico); } } public void delete(AnalistaTecnico tecnico) { tecnico = banco.find(AnalistaTecnico.class, tecnico.getOid()); if (tecnico != null) { banco.remove(tecnico); } } public AnalistaTecnicoBean() { // TODO Auto-generated constructor stub } }
UTF-8
Java
1,535
java
AnalistaTecnicoBean.java
Java
[ { "context": "TecnicoBeanLocal {\r\n\t// IMPORTANTE EM TODOS O @PERSITENSECONTEXT - copiar as duas linhas\r\n\t// seguintes.\r\n\t@Persis", "end": 485, "score": 0.7351349592208862, "start": 471, "tag": "USERNAME", "value": "SITENSECONTEXT" } ]
null
[]
package ejb; import java.util.List; import javax.ejb.LocalBean; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import dao.AnalistaTecnico; import dao.Fornecedor; /** * Session Bean implementation class AnalistaTecnicoBean */ @Stateless @LocalBean public class AnalistaTecnicoBean implements AnalistaTecnicoBeanLocal { // IMPORTANTE EM TODOS O @PERSITENSECONTEXT - copiar as duas linhas // seguintes. @PersistenceContext(name = "zeratulcontext") private EntityManager banco; public List<AnalistaTecnico> getTodosAnalistas() { Query consultaAnalistas = banco.createNamedQuery("todosAnalistas"); return consultaAnalistas.getResultList(); } public List<AnalistaTecnico> getAnalistaPorNome(String nomeAnalista) { Query consultaNome = banco.createNamedQuery("analistaPorNome"); consultaNome.setParameter("nomeTec", String.format("\\%%s\\%", nomeAnalista)); return consultaNome.getResultList(); } public void save(AnalistaTecnico tecnico) { if (banco.find(AnalistaTecnico.class, tecnico.getOid()) == null) { // insert banco.persist(tecnico); } else { // update banco.merge(tecnico); } } public void delete(AnalistaTecnico tecnico) { tecnico = banco.find(AnalistaTecnico.class, tecnico.getOid()); if (tecnico != null) { banco.remove(tecnico); } } public AnalistaTecnicoBean() { // TODO Auto-generated constructor stub } }
1,535
0.729642
0.729642
57
24.929825
24.005745
80
false
false
0
0
0
0
0
0
1.350877
false
false
13