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
ecf17f0ed74fc96a19180dfce66a9417527175af
11,175,504,910,824
0c4bca8faa389fc283fc9b89493e44a32a0ae375
/spring-data-access/src/main/java/com/dee/web/spring/jdbc/dao/impl/JdbcTemplatePreStsSetterStudentDao.java
2b64e8c024821de678d0c553d2d3175017db6645
[]
no_license
DienNM/spring-showcases
https://github.com/DienNM/spring-showcases
2bc07cf113a456870e424cc606798752cc9dafeb
6b4d827737e343f35dbdad597c26a81ed1984bdb
refs/heads/master
2020-12-24T14:45:32.375000
2015-09-11T10:06:34
2015-09-11T10:06:34
41,835,785
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dee.web.spring.jdbc.dao.impl; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.stereotype.Repository; import com.dee.web.spring.jdbc.dao.StudentRowMapper; import com.dee.web.spring.jdbc.model.JdbcStudent; /** * @author dien.nguyen **/ @Repository("jdbcTemplatePreStsSetterStudentDao") public class JdbcTemplatePreStsSetterStudentDao extends JdbcTemplateStudentDaoSupport { @Override public JdbcStudent findByEmail(String email) { String sql = "SELECT id, name, email FROM STUDENT WHERE email = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate.queryForObject(sql, new StudentRowMapper(), email); } @Override public JdbcStudent findById(int studentId) { String sql = "SELECT id, name, email FROM STUDENT WHERE id = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List<JdbcStudent> students = jdbcTemplate.query(sql, new StudentRowMapper(), studentId); if (students.isEmpty()) { return null; } return students.get(0); } @Override public void insert(final JdbcStudent student) { String sql = "INSERT INTO STUDENT (id, name, email) VALUES(?, ?, ?)"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, student.getId()); ps.setString(2, student.getName()); ps.setString(3, student.getEmail()); } }); } @Override public void insert(final List<JdbcStudent> students) { String sql = "INSERT INTO STUDENT (id, name, email) VALUES(?, ?, ?)"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int index) throws SQLException { JdbcStudent student = students.get(index); ps.setInt(1, student.getId()); ps.setString(2, student.getName()); ps.setString(3, student.getEmail()); } @Override public int getBatchSize() { return students.size(); } }); } @Override public void update(final JdbcStudent student) { String sql = "UPDATE STUDENT SET name = ?, email = ? WHERE id = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, student.getName()); ps.setString(2, student.getEmail()); ps.setInt(3, student.getId()); } }); } @Override public void delete(final JdbcStudent student) { String sql = "DELETE FROM STUDENT WHERE id = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, student.getId()); } }); } }
UTF-8
Java
3,664
java
JdbcTemplatePreStsSetterStudentDao.java
Java
[ { "context": "web.spring.jdbc.model.JdbcStudent;\n\n/**\n * @author dien.nguyen\n **/\n\n@Repository(\"jdbcTemplatePreStsSetterSt", "end": 489, "score": 0.7227853536605835, "start": 482, "tag": "USERNAME", "value": "dien.ng" }, { "context": "ng.jdbc.model.JdbcStudent;\n\n/**\n * @author dien.nguyen\n **/\n\n@Repository(\"jdbcTemplatePreStsSetterStuden", "end": 493, "score": 0.6135602593421936, "start": 489, "tag": "NAME", "value": "uyen" } ]
null
[]
package com.dee.web.spring.jdbc.dao.impl; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.stereotype.Repository; import com.dee.web.spring.jdbc.dao.StudentRowMapper; import com.dee.web.spring.jdbc.model.JdbcStudent; /** * @author dien.nguyen **/ @Repository("jdbcTemplatePreStsSetterStudentDao") public class JdbcTemplatePreStsSetterStudentDao extends JdbcTemplateStudentDaoSupport { @Override public JdbcStudent findByEmail(String email) { String sql = "SELECT id, name, email FROM STUDENT WHERE email = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate.queryForObject(sql, new StudentRowMapper(), email); } @Override public JdbcStudent findById(int studentId) { String sql = "SELECT id, name, email FROM STUDENT WHERE id = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); List<JdbcStudent> students = jdbcTemplate.query(sql, new StudentRowMapper(), studentId); if (students.isEmpty()) { return null; } return students.get(0); } @Override public void insert(final JdbcStudent student) { String sql = "INSERT INTO STUDENT (id, name, email) VALUES(?, ?, ?)"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, student.getId()); ps.setString(2, student.getName()); ps.setString(3, student.getEmail()); } }); } @Override public void insert(final List<JdbcStudent> students) { String sql = "INSERT INTO STUDENT (id, name, email) VALUES(?, ?, ?)"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int index) throws SQLException { JdbcStudent student = students.get(index); ps.setInt(1, student.getId()); ps.setString(2, student.getName()); ps.setString(3, student.getEmail()); } @Override public int getBatchSize() { return students.size(); } }); } @Override public void update(final JdbcStudent student) { String sql = "UPDATE STUDENT SET name = ?, email = ? WHERE id = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1, student.getName()); ps.setString(2, student.getEmail()); ps.setInt(3, student.getId()); } }); } @Override public void delete(final JdbcStudent student) { String sql = "DELETE FROM STUDENT WHERE id = ?"; JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setInt(1, student.getId()); } }); } }
3,664
0.634825
0.631823
106
33.566036
27.980457
96
false
false
0
0
0
0
0
0
0.698113
false
false
2
54d4e068f0bb3fdbcbaa76a149f710e648a25997
30,142,080,525,279
600fb919623c779860121371ce5d1c5bd9dc094a
/desktop/src/main/java/var3d/net/demo/desktop/DesktopLauncher.java
301e478050e5e642d99659a4afa34cea9e1c8ba5
[]
no_license
Var3D/var3dframe
https://github.com/Var3D/var3dframe
cdb80a9b1d1827c5be33a6674e7e91007527142a
01b41c8f62cc415427a76923c4ed01e231a5e6ba
refs/heads/master
2021-08-14T22:33:05.394000
2021-08-08T02:05:10
2021-08-08T02:05:10
79,713,705
43
29
null
false
2019-08-18T12:36:49
2017-01-22T11:29:12
2019-07-27T01:26:35
2019-07-27T01:26:33
11,430
32
20
1
Java
false
false
package var3d.net.demo.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import var3d.net.center.desktop.VDesktopLauncher; import var3d.net.demo.Game; public class DesktopLauncher extends VDesktopLauncher { public static void main(String[] arg) { //autoTool();//开启工具模式 LwjglApplicationConfiguration config = getConfig(Size.iphoneX_w); new LwjglApplication(new Game(new DesktopLauncher()), config); } }
UTF-8
Java
537
java
DesktopLauncher.java
Java
[]
null
[]
package var3d.net.demo.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import var3d.net.center.desktop.VDesktopLauncher; import var3d.net.demo.Game; public class DesktopLauncher extends VDesktopLauncher { public static void main(String[] arg) { //autoTool();//开启工具模式 LwjglApplicationConfiguration config = getConfig(Size.iphoneX_w); new LwjglApplication(new Game(new DesktopLauncher()), config); } }
537
0.761905
0.75619
17
29.882353
27.41593
73
false
false
0
0
0
0
0
0
0.529412
false
false
2
235d6a1f3b9a294ee8e81b982a56ab31269da6e3
18,691,697,692,082
e5f0eb6b0f2830a43a8aef2a0a45814a080521e4
/src/main/java/com/proj/web/EtudiantController.java
81a3d159f4a45a5ef60076fb97706be136fd336a
[]
no_license
Hanane-IHOUM/System_notes_insea
https://github.com/Hanane-IHOUM/System_notes_insea
1599827830b0746b1e4b5b0d1e92a80c1a2d200f
cda49975963dc32b6725b828a32f35a08a20235e
refs/heads/master
2023-03-03T19:00:25.436000
2021-01-29T17:37:22
2021-01-29T17:37:22
332,555,943
1
1
null
false
2021-01-26T20:41:45
2021-01-24T21:05:40
2021-01-26T17:04:16
2021-01-26T20:41:44
231
1
1
0
Java
false
false
package com.proj.web; import java.security.Principal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.proj.dao.CompteRepository; import com.proj.dao.EtudiantRepository; import com.proj.dao.Exam_NormalRepository; import com.proj.dao.Exam_RattRepository; import com.proj.dao.Niv_FilRepository; import com.proj.dao.ProfesseurRepository; import com.proj.entities.Compte; import com.proj.entities.Element; import com.proj.entities.Etudiant; import com.proj.entities.Exam_Normal; import com.proj.entities.Exam_Ratt; import com.proj.entities.Module; import com.proj.entities.Niv_Fil; import com.proj.entities.Professeur; import com.proj.dao.ModuleRepository; import com.proj.dao.ElementRepository; @Controller @RequestMapping(value="/etudiant") public class EtudiantController { @Autowired private Niv_FilRepository niv_filRepository; @Autowired private CompteRepository compteRepository; @Autowired private EtudiantRepository etudiantRepository; @Autowired private Exam_RattRepository examRattRepository; @Autowired private ElementRepository elementRepository; @RequestMapping(value="/mesNotes") public String mesNotes(Model model, HttpServletRequest request) { Principal principal = request.getUserPrincipal(); Compte compte = compteRepository.chercherparEmail(principal.getName()); Etudiant etudiant = etudiantRepository.findByCompteId(compte.getId()); //List <Exam_Normal> notesNorm = examNormalRepository.chercherNoteNorm(etudiant.getId(), etudiant.getNiv_fil().getId()); List <Exam_Ratt> notesFin = examRattRepository.chercherNoteRatt(etudiant.getId(), etudiant.getNiv_fil().getId()); model.addAttribute("compte", compte); model.addAttribute("etudiant", etudiant); model.addAttribute("notesfinales", notesFin); return "MesNotes"; } @RequestMapping(value="/Calendrier") public String calendrier(Model model, HttpServletRequest request) { Principal principal = request.getUserPrincipal(); Compte compte = compteRepository.chercherparEmail(principal.getName()); Etudiant etudiant = etudiantRepository.findByCompteId(compte.getId()); //List <Exam_Normal> notesNorm = examNormalRepository.chercherNoteNorm(etudiant.getId(), etudiant.getNiv_fil().getId()); List <Element> calendrier = elementRepository.cherchercalendrier(etudiant.getNiv_fil().getId()); model.addAttribute("compte", compte); model.addAttribute("etudiant", etudiant); model.addAttribute("calendrier", calendrier); return "Calendrier"; } }
UTF-8
Java
3,252
java
EtudiantController.java
Java
[]
null
[]
package com.proj.web; import java.security.Principal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.proj.dao.CompteRepository; import com.proj.dao.EtudiantRepository; import com.proj.dao.Exam_NormalRepository; import com.proj.dao.Exam_RattRepository; import com.proj.dao.Niv_FilRepository; import com.proj.dao.ProfesseurRepository; import com.proj.entities.Compte; import com.proj.entities.Element; import com.proj.entities.Etudiant; import com.proj.entities.Exam_Normal; import com.proj.entities.Exam_Ratt; import com.proj.entities.Module; import com.proj.entities.Niv_Fil; import com.proj.entities.Professeur; import com.proj.dao.ModuleRepository; import com.proj.dao.ElementRepository; @Controller @RequestMapping(value="/etudiant") public class EtudiantController { @Autowired private Niv_FilRepository niv_filRepository; @Autowired private CompteRepository compteRepository; @Autowired private EtudiantRepository etudiantRepository; @Autowired private Exam_RattRepository examRattRepository; @Autowired private ElementRepository elementRepository; @RequestMapping(value="/mesNotes") public String mesNotes(Model model, HttpServletRequest request) { Principal principal = request.getUserPrincipal(); Compte compte = compteRepository.chercherparEmail(principal.getName()); Etudiant etudiant = etudiantRepository.findByCompteId(compte.getId()); //List <Exam_Normal> notesNorm = examNormalRepository.chercherNoteNorm(etudiant.getId(), etudiant.getNiv_fil().getId()); List <Exam_Ratt> notesFin = examRattRepository.chercherNoteRatt(etudiant.getId(), etudiant.getNiv_fil().getId()); model.addAttribute("compte", compte); model.addAttribute("etudiant", etudiant); model.addAttribute("notesfinales", notesFin); return "MesNotes"; } @RequestMapping(value="/Calendrier") public String calendrier(Model model, HttpServletRequest request) { Principal principal = request.getUserPrincipal(); Compte compte = compteRepository.chercherparEmail(principal.getName()); Etudiant etudiant = etudiantRepository.findByCompteId(compte.getId()); //List <Exam_Normal> notesNorm = examNormalRepository.chercherNoteNorm(etudiant.getId(), etudiant.getNiv_fil().getId()); List <Element> calendrier = elementRepository.cherchercalendrier(etudiant.getNiv_fil().getId()); model.addAttribute("compte", compte); model.addAttribute("etudiant", etudiant); model.addAttribute("calendrier", calendrier); return "Calendrier"; } }
3,252
0.759225
0.759225
102
30.892157
28.926176
128
false
false
0
0
0
0
0
0
1.039216
false
false
2
98e0d036a20254f62b228490d120affc59629b93
25,786,983,669,544
af8e5be761b673aed45f033f0312470911af3963
/library/src/main/java/org/zhx/common/camera/Constants.java
2152ccf88130291a7b9f435194613cae7175501b
[]
no_license
zhoulinxue/ZCamera
https://github.com/zhoulinxue/ZCamera
bef2af9ca49169e3ad58668c2b74fa7793167e7c
ca6365f6e7c0cc37232085374b619c6994773dfc
refs/heads/master
2022-10-29T12:02:41.056000
2022-10-24T13:42:14
2022-10-24T13:42:58
46,578,111
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.zhx.common.camera; public class Constants { public static final int CAMERA = 18001; public static final int STORAGE = 18002; public static final String FILE_DIR = "zCamera_"; public static final String HISTORE_PICTRUE = "bitmap"; }
UTF-8
Java
269
java
Constants.java
Java
[]
null
[]
package org.zhx.common.camera; public class Constants { public static final int CAMERA = 18001; public static final int STORAGE = 18002; public static final String FILE_DIR = "zCamera_"; public static final String HISTORE_PICTRUE = "bitmap"; }
269
0.698885
0.66171
8
31.625
20.717972
58
false
false
0
0
0
0
0
0
0.625
false
false
2
9b8c668dd7fed136ffc7a0a0bd8d0b916e3a35e0
2,147,483,717,969
9e0b8dce8d9a76b16a2b00959ccc33216b4e09fa
/MainController.java
918400cd6fad08dcf7cfaaca61a8d33779b5efa9
[]
no_license
UltronOne/MatheGame
https://github.com/UltronOne/MatheGame
c838190665a7f847ffa39875eee65a15608cb480
6ec654a60eddc60d0b9461f2de20eb458d946351
refs/heads/master
2020-05-29T14:03:59.704000
2019-07-10T08:30:26
2019-07-10T08:30:26
189,182,132
1
4
null
false
2019-07-10T08:12:32
2019-05-29T08:20:40
2019-07-10T08:06:45
2019-07-10T08:11:10
664
0
3
0
Java
false
false
import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.Parent; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.Node; import javafx.scene.text.Text; public class MainController { @FXML private ResourceBundle resources; @FXML private URL location; @FXML private Button btnCampain; @FXML private Button btnFreeplay; @FXML private Button btnScoreboard; @FXML private Text Menü; @FXML void actFreeplay(ActionEvent event) { } @FXML void actScoreboard(ActionEvent event) { } @FXML void actCampain(ActionEvent event) throws Exception{ Parent blah = FXMLLoader.load(getClass().getResource("view.fxml")); Scene scene = new Scene(blah); Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); appStage.setScene(scene); appStage.show(); } @FXML void initialize() { assert btnCampain != null : "fx:id=\"btnCampain\" was not injected: check your FXML file 'daw.fxml'."; assert btnFreeplay != null : "fx:id=\"btnFreeplay\" was not injected: check your FXML file 'daw.fxml'."; assert btnScoreboard != null : "fx:id=\"btnScoreboard\" was not injected: check your FXML file 'daw.fxml'."; } }
UTF-8
Java
1,478
java
MainController.java
Java
[]
null
[]
import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.Parent; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.Node; import javafx.scene.text.Text; public class MainController { @FXML private ResourceBundle resources; @FXML private URL location; @FXML private Button btnCampain; @FXML private Button btnFreeplay; @FXML private Button btnScoreboard; @FXML private Text Menü; @FXML void actFreeplay(ActionEvent event) { } @FXML void actScoreboard(ActionEvent event) { } @FXML void actCampain(ActionEvent event) throws Exception{ Parent blah = FXMLLoader.load(getClass().getResource("view.fxml")); Scene scene = new Scene(blah); Stage appStage = (Stage) ((Node) event.getSource()).getScene().getWindow(); appStage.setScene(scene); appStage.show(); } @FXML void initialize() { assert btnCampain != null : "fx:id=\"btnCampain\" was not injected: check your FXML file 'daw.fxml'."; assert btnFreeplay != null : "fx:id=\"btnFreeplay\" was not injected: check your FXML file 'daw.fxml'."; assert btnScoreboard != null : "fx:id=\"btnScoreboard\" was not injected: check your FXML file 'daw.fxml'."; } }
1,478
0.655383
0.655383
62
22.82258
27.45643
116
false
false
0
0
0
0
0
0
0.403226
false
false
2
ad10cab468778bd0403bf12fcf114ea0ac20cd77
2,147,483,718,318
1b7cf6337e5de121ae3ee5be95cf8635a8cdfdf7
/src/main/java/com/znyw/pojo/OwnerPojo.java
170c6893bfacb64421ac7fbabd2366bf1034dcd4
[]
no_license
ekuanquan/IMM
https://github.com/ekuanquan/IMM
45ae6ea8530a4efed87b0a55129cfb134a3fc84e
bdb756f10fed00dd4e5f519f249e9d3e60ec2b90
refs/heads/master
2020-04-15T10:09:14.115000
2019-01-08T06:53:44
2019-01-08T06:53:44
164,582,509
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.znyw.pojo; import java.util.ArrayList; import java.util.List; /** * 机主用户实体类 * * @author teclan * * email: tbj621@163.com * * 2017年11月17日 */ public class OwnerPojo { private String userAccount; // 用户帐号 private String userPwd; // 用户密码 private String createDate; // 创建日期 private String userId; // 用户编号 private String userName; // 用户名称 private String userType; // 用户类型 private String userAddr; // 用户地址 private String userProperty; // 用户属性 private String businessId; // 用户行业id private String businessName; // 用户行业名称 private String centerId; // 所属分中心id private String centerName; // 所属分中心(名称) private String payNO; // 口令 private String userServerType; // 用户服务类型 private String userServerTypeName; // 用户服务类型名称 private String contact; // 单位负责人 private String contactPayNO; // 负责人口令 private String cHmPhone; // 负责人家庭电话 private String cPhone; // 负责人电话 private String cMobile; // 负责人手机 private String pnlTel; // 联网电话 private String pnlHdTel;// 无线卡号 private String nomRpt; // 定期撤布防用户 private String engageTest; // 定期测试用户 private String nomTest; // 紧急按钮用户 private String isVideoCheck; // 短信转发 private String areaId; // 区域id//所属区域 private String areaName; // 区域名称 private String isInsurance; // 投保 private String hasBak; // 是否来电正常 private String isPay; // 缴费状态 private String usrAlmType; // 处警等级 private String uMem; // 处警注释 private String operName; // 录入人 private String define2; // 暂停时间 private String badMem; // 故障提示 private String road; // 道路标志 private String define3; // 布防时间 private String define1; // 子行业 private String define6; // 中心号 private String fMemo; // 备注 private String define4; // 备注4 private String instDate; // 安装日期 private String liveDate; // 入网日期 private String pnlTelType; // 入网类型 private String roleId; // 角色Id private String dataFrom; private String platformId;// 所属平台ID private String platformName;// 所属平台名称 private String masterDevId; // 主设备ID private String remoteDevId; // 远程控制设备ID private String serveEndTime;// 服务到期时间 private boolean switchUser;// 是否启用服务 public String getServeEndTime() { return serveEndTime; } public void setServeEndTime(String serveEndTime) { this.serveEndTime = serveEndTime; } public boolean isSwitchUser() { return switchUser; } public void setSwitchUser(boolean switchUser) { this.switchUser = switchUser; } public String getMasterDevId() { return masterDevId; } public void setMasterDevId(String masterDevId) { this.masterDevId = masterDevId; } public String getRemoteDevId() { return remoteDevId; } public void setRemoteDevId(String remoteDevId) { this.remoteDevId = remoteDevId; } public String getPlatformId() { return platformId; } public void setPlatformId(String platformId) { this.platformId = platformId; } public String getPlatformName() { return platformName; } public void setPlatformName(String platformName) { this.platformName = platformName; } public String getDataFrom() { return dataFrom; } public void setDataFrom(String dataFrom) { this.dataFrom = dataFrom; } /** * 关联的设备编号 */ private List<String> devIds = new ArrayList<String>(); public String getcHmPhone() { return cHmPhone; } public void setcHmPhone(String cHmPhone) { this.cHmPhone = cHmPhone; } public String getcPhone() { return cPhone; } public void setcPhone(String cPhone) { this.cPhone = cPhone; } public String getcMobile() { return cMobile; } public void setcMobile(String cMobile) { this.cMobile = cMobile; } public List<String> getDevIds() { return devIds; } public void setDevIds(List<String> devIds) { this.devIds = devIds; } public String getPnlHdTel() { return pnlHdTel; } public void setPnlHdTel(String pnlHdTel) { this.pnlHdTel = pnlHdTel; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getUserAddr() { return userAddr; } public void setUserAddr(String userAddr) { this.userAddr = userAddr; } public String getUserProperty() { return userProperty; } public void setUserProperty(String userProperty) { this.userProperty = userProperty; } public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public String getBusinessName() { return businessName; } public void setBusinessName(String businessName) { this.businessName = businessName; } public String getCenterId() { return centerId; } public void setCenterId(String centerId) { this.centerId = centerId; } public String getCenterName() { return centerName; } public void setCenterName(String centerName) { this.centerName = centerName; } public String getPayNO() { return payNO; } public void setPayNO(String payNO) { this.payNO = payNO; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactPayNO() { return contactPayNO; } public void setContactPayNO(String contactPayNO) { this.contactPayNO = contactPayNO; } public String getCHmPhone() { return cHmPhone; } public void setCHmPhone(String cHmPhone) { this.cHmPhone = cHmPhone; } public String getCPhone() { return cPhone; } public void setCPhone(String cPhone) { this.cPhone = cPhone; } public String getCMobile() { return cMobile; } public void setCMobile(String cMobile) { this.cMobile = cMobile; } public String getNomRpt() { return nomRpt; } public void setNomRpt(String nomRpt) { this.nomRpt = nomRpt; } public String getEngageTest() { return engageTest; } public void setEngageTest(String engageTest) { this.engageTest = engageTest; } public String getNomTest() { return nomTest; } public void setNomTest(String nomTest) { this.nomTest = nomTest; } public String getIsVideoCheck() { return isVideoCheck; } public void setIsVideoCheck(String isVideoCheck) { this.isVideoCheck = isVideoCheck; } public String getAreaId() { return areaId; } public void setAreaId(String areaId) { this.areaId = areaId; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public String getIsInsurance() { return isInsurance; } public void setIsInsurance(String isInsurance) { this.isInsurance = isInsurance; } public String getHasBak() { return hasBak; } public void setHasBak(String hasBak) { this.hasBak = hasBak; } public String getIsPay() { return isPay; } public void setIsPay(String isPay) { this.isPay = isPay; } public String getUsrAlmType() { return usrAlmType; } public void setUsrAlmType(String usrAlmType) { this.usrAlmType = usrAlmType; } public String getuMem() { return uMem; } public void setuMem(String uMem) { this.uMem = uMem; } public String getOperName() { return operName; } public void setOperName(String operName) { this.operName = operName; } public String getDefine2() { return define2; } public void setDefine2(String define2) { this.define2 = define2; } public String getBadMem() { return badMem; } public void setBadMem(String badMem) { this.badMem = badMem; } public String getRoad() { return road; } public void setRoad(String road) { this.road = road; } public String getDefine3() { return define3; } public void setDefine3(String define3) { this.define3 = define3; } public String getDefine1() { return define1; } public void setDefine1(String define1) { this.define1 = define1; } public String getDefine6() { return define6; } public void setDefine6(String define6) { this.define6 = define6; } public String getfMemo() { return fMemo; } public void setfMemo(String fMemo) { this.fMemo = fMemo; } public String getDefine4() { return define4; } public void setDefine4(String define4) { this.define4 = define4; } public String getInstDate() { return instDate; } public void setInstDate(String instDate) { this.instDate = instDate; } public String getLiveDate() { return liveDate; } public void setLiveDate(String liveDate) { this.liveDate = liveDate; } public String getPnlTelType() { return pnlTelType; } public void setPnlTelType(String pnlTelType) { this.pnlTelType = pnlTelType; } public String getUserServerType() { return userServerType; } public void setUserServerType(String userServerType) { this.userServerType = userServerType; } public String getUserServerTypeName() { return userServerTypeName; } public void setUserServerTypeName(String userServerTypeName) { this.userServerTypeName = userServerTypeName; } public String getPnlTel() { return pnlTel; } public void setPnlTel(String pnlTel) { this.pnlTel = pnlTel; } // @Override // public String toString() { // return "OwnerPojo [userAccount=" + userAccount + ", userPwd=" + userPwd // + ", createDate=" + createDate + ", userId=" + userId // + ", userName=" + userName + ", userType=" + userType // + ", userAddr=" + userAddr + ", userProperty=" + userProperty // + ", businessId=" + businessId + ", businessName=" // + businessName + ", centerId=" + centerId + ", centerName=" // + centerName + ", payNO=" + payNO + ", contact=" + contact // + ", contactPayNO=" + contactPayNO + ", cHmPhone=" + cHmPhone // + ", cPhone=" + cPhone + ", cMobile=" + cMobile + ", nomRpt=" // + nomRpt + ", engageTest=" + engageTest + ", nomTest=" // + nomTest + ", isVideoCheck=" + isVideoCheck + ", areaId=" // + areaId + ", areaName=" + areaName + ", isInsurance=" // + isInsurance + ", hasBak=" + hasBak + ", isPay=" + isPay // + ", usrAlmType=" + usrAlmType + ", uMem=" + uMem // + ", operName=" + operName + ", define2=" + define2 // + ", badMem=" + badMem + ", road=" + road + ", define3=" // + define3 + ", define1=" + define1 + ", define6=" + define6 // + ", fMemo=" + fMemo + ", define4=" + define4 + ", instDate=" // + instDate + ", liveDate=" + liveDate + ", pnlTelType=" // + pnlTelType + ", roleId=" + roleId + ", pnlTel=" + pnlTel // + "]"; // } public String toLog() { StringBuffer sbf = new StringBuffer(); sbf.append("[userId=" + userId); sbf.append("userName=" + userName); sbf.append("userType=" + userType); sbf.append("areaId=" + areaId); sbf.append("areaName=" + areaName); sbf.append("createDate=" + createDate + "]"); return sbf.toString(); } @Override public String toString() { return "OwnerPojo [userAccount=" + userAccount + ", userPwd=" + userPwd + ", createDate=" + createDate + ", userId=" + userId + ", userName=" + userName + ", userType=" + userType + ", userAddr=" + userAddr + ", userProperty=" + userProperty + ", businessId=" + businessId + ", businessName=" + businessName + ", centerId=" + centerId + ", centerName=" + centerName + ", payNO=" + payNO + ", userServerType=" + userServerType + ", userServerTypeName=" + userServerTypeName + ", contact=" + contact + ", contactPayNO=" + contactPayNO + ", cHmPhone=" + cHmPhone + ", cPhone=" + cPhone + ", cMobile=" + cMobile + ", pnlTel=" + pnlTel + ", pnlHdTel=" + pnlHdTel + ", nomRpt=" + nomRpt + ", engageTest=" + engageTest + ", nomTest=" + nomTest + ", isVideoCheck=" + isVideoCheck + ", areaId=" + areaId + ", areaName=" + areaName + ", isInsurance=" + isInsurance + ", hasBak=" + hasBak + ", isPay=" + isPay + ", usrAlmType=" + usrAlmType + ", uMem=" + uMem + ", operName=" + operName + ", define2=" + define2 + ", badMem=" + badMem + ", road=" + road + ", define3=" + define3 + ", define1=" + define1 + ", define6=" + define6 + ", fMemo=" + fMemo + ", define4=" + define4 + ", instDate=" + instDate + ", liveDate=" + liveDate + ", pnlTelType=" + pnlTelType + ", roleId=" + roleId + ", dataFrom=" + dataFrom + ", platformId=" + platformId + ", platformName=" + platformName + ", masterDevId=" + masterDevId + ", remoteDevId=" + remoteDevId + ", serveEndTime=" + serveEndTime + ", switchUser=" + switchUser + ", devIds=" + devIds + "]"; } }
UTF-8
Java
13,501
java
OwnerPojo.java
Java
[ { "context": "ort java.util.List;\n\n/**\n * 机主用户实体类\n * \n * @author teclan\n * \n * email: tbj621@163.com\n *\n * ", "end": 112, "score": 0.9997010827064514, "start": 106, "tag": "USERNAME", "value": "teclan" }, { "context": "主用户实体类\n * \n * @author teclan\n * \n * email: tbj621@163.com\n *\n * 2017年11月17日\n */\npublic class OwnerP", "end": 149, "score": 0.9999215602874756, "start": 135, "tag": "EMAIL", "value": "tbj621@163.com" }, { "context": ") {\n\t\tthis.userId = userId;\n\t}\n\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\tpublic void setUserNa", "end": 4471, "score": 0.8958200812339783, "start": 4463, "tag": "USERNAME", "value": "UserName" }, { "context": "serId;\n\t}\n\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\tpublic void setUserName(String userName) {\n", "end": 4493, "score": 0.9918302893638611, "start": 4485, "tag": "USERNAME", "value": "userName" }, { "context": "turn userName;\n\t}\n\n\tpublic void setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\n\tpublic String", "end": 4539, "score": 0.6788164973258972, "start": 4531, "tag": "USERNAME", "value": "userName" }, { "context": "d setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\n\tpublic String getUserType() {\n\t\treturn user", "end": 4569, "score": 0.9920924305915833, "start": 4561, "tag": "USERNAME", "value": "userName" }, { "context": "Pojo [userAccount=\" + userAccount + \", userPwd=\" + userPwd\n\t// + \", createDate=\" + createDate + \", userId", "end": 9810, "score": 0.9904834628105164, "start": 9806, "tag": "PASSWORD", "value": "user" }, { "context": "eDate + \", userId=\" + userId\n\t// + \", userName=\" + userName + \", userType=\" + userType\n\t// + \", userAddr=\" + ", "end": 9902, "score": 0.9966189861297607, "start": 9894, "tag": "USERNAME", "value": "userName" }, { "context": "d(\"[userId=\" + userId);\n\t\tsbf.append(\"userName=\" + userName);\n\t\tsbf.append(\"userType=\" + userType);\n\t\tsbf.app", "end": 11131, "score": 0.9972785115242004, "start": 11123, "tag": "USERNAME", "value": "userName" }, { "context": "eDate + \", userId=\" + userId\n\t\t\t\t+ \", userName=\" + userName + \", userType=\" + userType\n\t\t\t\t+ \", userAddr=\" + ", "end": 11522, "score": 0.9961729049682617, "start": 11514, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.znyw.pojo; import java.util.ArrayList; import java.util.List; /** * 机主用户实体类 * * @author teclan * * email: <EMAIL> * * 2017年11月17日 */ public class OwnerPojo { private String userAccount; // 用户帐号 private String userPwd; // 用户密码 private String createDate; // 创建日期 private String userId; // 用户编号 private String userName; // 用户名称 private String userType; // 用户类型 private String userAddr; // 用户地址 private String userProperty; // 用户属性 private String businessId; // 用户行业id private String businessName; // 用户行业名称 private String centerId; // 所属分中心id private String centerName; // 所属分中心(名称) private String payNO; // 口令 private String userServerType; // 用户服务类型 private String userServerTypeName; // 用户服务类型名称 private String contact; // 单位负责人 private String contactPayNO; // 负责人口令 private String cHmPhone; // 负责人家庭电话 private String cPhone; // 负责人电话 private String cMobile; // 负责人手机 private String pnlTel; // 联网电话 private String pnlHdTel;// 无线卡号 private String nomRpt; // 定期撤布防用户 private String engageTest; // 定期测试用户 private String nomTest; // 紧急按钮用户 private String isVideoCheck; // 短信转发 private String areaId; // 区域id//所属区域 private String areaName; // 区域名称 private String isInsurance; // 投保 private String hasBak; // 是否来电正常 private String isPay; // 缴费状态 private String usrAlmType; // 处警等级 private String uMem; // 处警注释 private String operName; // 录入人 private String define2; // 暂停时间 private String badMem; // 故障提示 private String road; // 道路标志 private String define3; // 布防时间 private String define1; // 子行业 private String define6; // 中心号 private String fMemo; // 备注 private String define4; // 备注4 private String instDate; // 安装日期 private String liveDate; // 入网日期 private String pnlTelType; // 入网类型 private String roleId; // 角色Id private String dataFrom; private String platformId;// 所属平台ID private String platformName;// 所属平台名称 private String masterDevId; // 主设备ID private String remoteDevId; // 远程控制设备ID private String serveEndTime;// 服务到期时间 private boolean switchUser;// 是否启用服务 public String getServeEndTime() { return serveEndTime; } public void setServeEndTime(String serveEndTime) { this.serveEndTime = serveEndTime; } public boolean isSwitchUser() { return switchUser; } public void setSwitchUser(boolean switchUser) { this.switchUser = switchUser; } public String getMasterDevId() { return masterDevId; } public void setMasterDevId(String masterDevId) { this.masterDevId = masterDevId; } public String getRemoteDevId() { return remoteDevId; } public void setRemoteDevId(String remoteDevId) { this.remoteDevId = remoteDevId; } public String getPlatformId() { return platformId; } public void setPlatformId(String platformId) { this.platformId = platformId; } public String getPlatformName() { return platformName; } public void setPlatformName(String platformName) { this.platformName = platformName; } public String getDataFrom() { return dataFrom; } public void setDataFrom(String dataFrom) { this.dataFrom = dataFrom; } /** * 关联的设备编号 */ private List<String> devIds = new ArrayList<String>(); public String getcHmPhone() { return cHmPhone; } public void setcHmPhone(String cHmPhone) { this.cHmPhone = cHmPhone; } public String getcPhone() { return cPhone; } public void setcPhone(String cPhone) { this.cPhone = cPhone; } public String getcMobile() { return cMobile; } public void setcMobile(String cMobile) { this.cMobile = cMobile; } public List<String> getDevIds() { return devIds; } public void setDevIds(List<String> devIds) { this.devIds = devIds; } public String getPnlHdTel() { return pnlHdTel; } public void setPnlHdTel(String pnlHdTel) { this.pnlHdTel = pnlHdTel; } public String getRoleId() { return roleId; } public void setRoleId(String roleId) { this.roleId = roleId; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public String getCreateDate() { return createDate; } public void setCreateDate(String createDate) { this.createDate = createDate; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getUserAddr() { return userAddr; } public void setUserAddr(String userAddr) { this.userAddr = userAddr; } public String getUserProperty() { return userProperty; } public void setUserProperty(String userProperty) { this.userProperty = userProperty; } public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } public String getBusinessName() { return businessName; } public void setBusinessName(String businessName) { this.businessName = businessName; } public String getCenterId() { return centerId; } public void setCenterId(String centerId) { this.centerId = centerId; } public String getCenterName() { return centerName; } public void setCenterName(String centerName) { this.centerName = centerName; } public String getPayNO() { return payNO; } public void setPayNO(String payNO) { this.payNO = payNO; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactPayNO() { return contactPayNO; } public void setContactPayNO(String contactPayNO) { this.contactPayNO = contactPayNO; } public String getCHmPhone() { return cHmPhone; } public void setCHmPhone(String cHmPhone) { this.cHmPhone = cHmPhone; } public String getCPhone() { return cPhone; } public void setCPhone(String cPhone) { this.cPhone = cPhone; } public String getCMobile() { return cMobile; } public void setCMobile(String cMobile) { this.cMobile = cMobile; } public String getNomRpt() { return nomRpt; } public void setNomRpt(String nomRpt) { this.nomRpt = nomRpt; } public String getEngageTest() { return engageTest; } public void setEngageTest(String engageTest) { this.engageTest = engageTest; } public String getNomTest() { return nomTest; } public void setNomTest(String nomTest) { this.nomTest = nomTest; } public String getIsVideoCheck() { return isVideoCheck; } public void setIsVideoCheck(String isVideoCheck) { this.isVideoCheck = isVideoCheck; } public String getAreaId() { return areaId; } public void setAreaId(String areaId) { this.areaId = areaId; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public String getIsInsurance() { return isInsurance; } public void setIsInsurance(String isInsurance) { this.isInsurance = isInsurance; } public String getHasBak() { return hasBak; } public void setHasBak(String hasBak) { this.hasBak = hasBak; } public String getIsPay() { return isPay; } public void setIsPay(String isPay) { this.isPay = isPay; } public String getUsrAlmType() { return usrAlmType; } public void setUsrAlmType(String usrAlmType) { this.usrAlmType = usrAlmType; } public String getuMem() { return uMem; } public void setuMem(String uMem) { this.uMem = uMem; } public String getOperName() { return operName; } public void setOperName(String operName) { this.operName = operName; } public String getDefine2() { return define2; } public void setDefine2(String define2) { this.define2 = define2; } public String getBadMem() { return badMem; } public void setBadMem(String badMem) { this.badMem = badMem; } public String getRoad() { return road; } public void setRoad(String road) { this.road = road; } public String getDefine3() { return define3; } public void setDefine3(String define3) { this.define3 = define3; } public String getDefine1() { return define1; } public void setDefine1(String define1) { this.define1 = define1; } public String getDefine6() { return define6; } public void setDefine6(String define6) { this.define6 = define6; } public String getfMemo() { return fMemo; } public void setfMemo(String fMemo) { this.fMemo = fMemo; } public String getDefine4() { return define4; } public void setDefine4(String define4) { this.define4 = define4; } public String getInstDate() { return instDate; } public void setInstDate(String instDate) { this.instDate = instDate; } public String getLiveDate() { return liveDate; } public void setLiveDate(String liveDate) { this.liveDate = liveDate; } public String getPnlTelType() { return pnlTelType; } public void setPnlTelType(String pnlTelType) { this.pnlTelType = pnlTelType; } public String getUserServerType() { return userServerType; } public void setUserServerType(String userServerType) { this.userServerType = userServerType; } public String getUserServerTypeName() { return userServerTypeName; } public void setUserServerTypeName(String userServerTypeName) { this.userServerTypeName = userServerTypeName; } public String getPnlTel() { return pnlTel; } public void setPnlTel(String pnlTel) { this.pnlTel = pnlTel; } // @Override // public String toString() { // return "OwnerPojo [userAccount=" + userAccount + ", userPwd=" + <PASSWORD>Pwd // + ", createDate=" + createDate + ", userId=" + userId // + ", userName=" + userName + ", userType=" + userType // + ", userAddr=" + userAddr + ", userProperty=" + userProperty // + ", businessId=" + businessId + ", businessName=" // + businessName + ", centerId=" + centerId + ", centerName=" // + centerName + ", payNO=" + payNO + ", contact=" + contact // + ", contactPayNO=" + contactPayNO + ", cHmPhone=" + cHmPhone // + ", cPhone=" + cPhone + ", cMobile=" + cMobile + ", nomRpt=" // + nomRpt + ", engageTest=" + engageTest + ", nomTest=" // + nomTest + ", isVideoCheck=" + isVideoCheck + ", areaId=" // + areaId + ", areaName=" + areaName + ", isInsurance=" // + isInsurance + ", hasBak=" + hasBak + ", isPay=" + isPay // + ", usrAlmType=" + usrAlmType + ", uMem=" + uMem // + ", operName=" + operName + ", define2=" + define2 // + ", badMem=" + badMem + ", road=" + road + ", define3=" // + define3 + ", define1=" + define1 + ", define6=" + define6 // + ", fMemo=" + fMemo + ", define4=" + define4 + ", instDate=" // + instDate + ", liveDate=" + liveDate + ", pnlTelType=" // + pnlTelType + ", roleId=" + roleId + ", pnlTel=" + pnlTel // + "]"; // } public String toLog() { StringBuffer sbf = new StringBuffer(); sbf.append("[userId=" + userId); sbf.append("userName=" + userName); sbf.append("userType=" + userType); sbf.append("areaId=" + areaId); sbf.append("areaName=" + areaName); sbf.append("createDate=" + createDate + "]"); return sbf.toString(); } @Override public String toString() { return "OwnerPojo [userAccount=" + userAccount + ", userPwd=" + userPwd + ", createDate=" + createDate + ", userId=" + userId + ", userName=" + userName + ", userType=" + userType + ", userAddr=" + userAddr + ", userProperty=" + userProperty + ", businessId=" + businessId + ", businessName=" + businessName + ", centerId=" + centerId + ", centerName=" + centerName + ", payNO=" + payNO + ", userServerType=" + userServerType + ", userServerTypeName=" + userServerTypeName + ", contact=" + contact + ", contactPayNO=" + contactPayNO + ", cHmPhone=" + cHmPhone + ", cPhone=" + cPhone + ", cMobile=" + cMobile + ", pnlTel=" + pnlTel + ", pnlHdTel=" + pnlHdTel + ", nomRpt=" + nomRpt + ", engageTest=" + engageTest + ", nomTest=" + nomTest + ", isVideoCheck=" + isVideoCheck + ", areaId=" + areaId + ", areaName=" + areaName + ", isInsurance=" + isInsurance + ", hasBak=" + hasBak + ", isPay=" + isPay + ", usrAlmType=" + usrAlmType + ", uMem=" + uMem + ", operName=" + operName + ", define2=" + define2 + ", badMem=" + badMem + ", road=" + road + ", define3=" + define3 + ", define1=" + define1 + ", define6=" + define6 + ", fMemo=" + fMemo + ", define4=" + define4 + ", instDate=" + instDate + ", liveDate=" + liveDate + ", pnlTelType=" + pnlTelType + ", roleId=" + roleId + ", dataFrom=" + dataFrom + ", platformId=" + platformId + ", platformName=" + platformName + ", masterDevId=" + masterDevId + ", remoteDevId=" + remoteDevId + ", serveEndTime=" + serveEndTime + ", switchUser=" + switchUser + ", devIds=" + devIds + "]"; } }
13,500
0.678514
0.673129
598
20.737457
19.49358
75
false
false
0
0
0
0
0
0
1.571906
false
false
2
6710bea45b52c7dfa0ef4ac2bbdd4e10ba8e74b2
10,703,058,548,757
a3a3b511bcd85e324854179943b1804c9673f9ac
/app/src/main/java/com/cui/android/jianchengdichan/http/bean/RenovationBean.java
94db6db1277ce3468a9db62a1526975fbb988a12
[]
no_license
cuijiehui/jianchangDiChan
https://github.com/cuijiehui/jianchangDiChan
45d72b015cfbf7bb3da8675bd8fdc21ce8152255
ba30e59e694404e3f18d80bc9b4237888405e635
refs/heads/master
2020-03-17T20:57:18.726000
2019-07-04T05:59:27
2019-07-04T05:59:27
133,936,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cui.android.jianchengdichan.http.bean; public class RenovationBean { /** * id : 1 * company : 测试公司 * startdate : 2018-06-06 * enddate : 2018-07-06 * status : 1 * create_time : 2018-06-06 */ private int id; private String company; private String startdate; private String enddate; private int status; private String create_time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } public String getEnddate() { return enddate; } public void setEnddate(String enddate) { this.enddate = enddate; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } }
UTF-8
Java
1,292
java
RenovationBean.java
Java
[]
null
[]
package com.cui.android.jianchengdichan.http.bean; public class RenovationBean { /** * id : 1 * company : 测试公司 * startdate : 2018-06-06 * enddate : 2018-07-06 * status : 1 * create_time : 2018-06-06 */ private int id; private String company; private String startdate; private String enddate; private int status; private String create_time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getStartdate() { return startdate; } public void setStartdate(String startdate) { this.startdate = startdate; } public String getEnddate() { return enddate; } public void setEnddate(String enddate) { this.enddate = enddate; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } }
1,292
0.584112
0.563863
68
17.882353
15.323502
52
false
false
0
0
0
0
0
0
0.279412
false
false
2
ff65aa46abb1f905eef05c9223e637ae92372647
12,704,513,282,691
0ed1a7d603520e4a575c0e1b9d64e3d89021fc73
/src/main/java/org/spideruci/tacoco/cli/ReaderCli.java
12648b158fa974a14d3f19e93de26616f3d1c302
[ "MIT" ]
permissive
spideruci/tacoco
https://github.com/spideruci/tacoco
3ba57f457751210bd0caa329e57b445aee40783b
c82d4c352a40fc69cd654b2df80cd99b59c8d1fe
refs/heads/master
2023-05-25T02:51:45.242000
2023-05-21T19:43:55
2023-05-21T19:43:55
35,289,775
9
8
MIT
false
2023-05-23T20:18:36
2015-05-08T16:29:23
2023-05-21T19:44:06
2023-05-23T20:18:34
6,240
8
7
28
Java
false
false
package org.spideruci.tacoco.cli; public class ReaderCli extends AbstractCli { public static String readArgumentValue(String arg) { return READER_CLI.readArgumentValueInternal(arg); } public static String readOptionalArgumentValue(String arg, String defolt) { return READER_CLI.readOptionalArgumentValueInternal(arg, defolt); } public String getHelpMenu(final String errorMessage) { final String error = errorMessage == null ? null : ("ERROR! " + errorMessage + "\nRefer to the following commandline arguments.\n"); final String helpMessage = "\nTacoco: Coverage Json-file Reader\n"+ "usage: mvn exec:java -q -Preader [arguments]\n\nArguments:\n" + PREFIX + JSON + "=<*.json> (Required) Absolute-path of per-test coverage file.\n" + PREFIX + OUT + "=<*.json> Absolute-path of per-sourcefile coverage matrix.\n" + PREFIX + PP + " Pretty prints coverage data to json file.\n" + PREFIX + HELP + " Prints this message and exits (with 0).\n"; if(error != null) { return error + helpMessage; } return helpMessage; } }
UTF-8
Java
1,109
java
ReaderCli.java
Java
[]
null
[]
package org.spideruci.tacoco.cli; public class ReaderCli extends AbstractCli { public static String readArgumentValue(String arg) { return READER_CLI.readArgumentValueInternal(arg); } public static String readOptionalArgumentValue(String arg, String defolt) { return READER_CLI.readOptionalArgumentValueInternal(arg, defolt); } public String getHelpMenu(final String errorMessage) { final String error = errorMessage == null ? null : ("ERROR! " + errorMessage + "\nRefer to the following commandline arguments.\n"); final String helpMessage = "\nTacoco: Coverage Json-file Reader\n"+ "usage: mvn exec:java -q -Preader [arguments]\n\nArguments:\n" + PREFIX + JSON + "=<*.json> (Required) Absolute-path of per-test coverage file.\n" + PREFIX + OUT + "=<*.json> Absolute-path of per-sourcefile coverage matrix.\n" + PREFIX + PP + " Pretty prints coverage data to json file.\n" + PREFIX + HELP + " Prints this message and exits (with 0).\n"; if(error != null) { return error + helpMessage; } return helpMessage; } }
1,109
0.681695
0.680794
30
36
30.262188
90
false
false
0
0
0
0
0
0
2.466667
false
false
2
80b3518f1014a36bd110c45e86ae3b4948691f88
27,805,618,307,231
db3d8fab212ea78ac3ad9d3234933d5aa11a07c0
/loan-app-thymeleaf/src/main/java/com/gittigidiyor/quixotic95/loanappthymeleaf/model/ExceptionLog.java
a88377fe6e4fbd81ab6d6f50afcd69756b1b839b
[ "MIT" ]
permissive
Quixotic95/gittigidiyor-graduation-project-Quixotic95
https://github.com/Quixotic95/gittigidiyor-graduation-project-Quixotic95
aa8bd2c9bf2d22b9f78239547fda1348a9e27cf4
9d161747c8d9f1a36112f14871ae9d8b9ec108bd
refs/heads/main
2023-08-11T06:20:26.175000
2021-09-29T19:59:46
2021-09-29T19:59:46
412,771,876
0
1
MIT
true
2021-10-02T11:07:20
2021-10-02T11:07:20
2021-10-01T10:53:09
2021-09-29T19:59:50
454
0
0
0
null
false
false
package com.gittigidiyor.quixotic95.loanappthymeleaf.model; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ExceptionLog { private String timestamp; private String status; private String error; private String message; private String path; }
UTF-8
Java
294
java
ExceptionLog.java
Java
[ { "context": "package com.gittigidiyor.quixotic95.loanappthymeleaf.model;\n\nimport lombok", "end": 24, "score": 0.9646286368370056, "start": 12, "tag": "USERNAME", "value": "gittigidiyor" } ]
null
[]
package com.gittigidiyor.quixotic95.loanappthymeleaf.model; import lombok.Getter; import lombok.Setter; @Getter @Setter public class ExceptionLog { private String timestamp; private String status; private String error; private String message; private String path; }
294
0.748299
0.741497
20
13.7
15.62722
59
false
false
0
0
0
0
0
0
0.4
false
false
2
911ecd45354e38b677f748035efef38ea31ce5d7
32,985,348,888,076
3ca9cb83b8cebb32c310138e058e5460ba15de30
/src/main/java/future/models/data/Users.java
453c4e44b65dbd9f954eb44d06df9cf2daf63f10
[]
no_license
mateuszkonik/authorizationEngine
https://github.com/mateuszkonik/authorizationEngine
6c6d31e68eb2f1627b9ab8e0a7105ae77ff92bc0
fc9fe48a9bfa5786dcb4530f0cbbb5900e0063ec
refs/heads/master
2021-07-01T10:34:58.620000
2017-09-22T15:16:47
2017-09-22T15:16:47
104,487,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package future.models.data; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import future.util.totp.TOTPTools; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.UUID; @Table(name = "users") public class Users { //todo: appID aktualnie nie uzywane @PartitionKey(0) @Column(name = "app_id") private UUID appId; @PartitionKey(1) @Column(name = "user_id") private UUID userId; private String login; private String password; private String email; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; private Set<String> permissions; private Language language; @Column(name = "email_verified") private Boolean emailVerified = false; @Column(name = "account_confirmed") private Boolean accountConfirmed = false; @Column(name = "2fa_method") private String twoFactorMethod = "none"; @Column(name = "2fa_required_permissions") private Set<String> twoFactorRequiredPermissions = new HashSet<>(); @Column(name = "ga_secret") private String gaSecret; @Column(name = "default_currency") private String defaultCurrency; @Column(name = "helpline_pin") private Integer helplinePin; @Column(name = "account_type") private String accountType; @Column(name = "company_name") private String companyName; @Column(name = "company_street") private String companyStreet; @Column(name = "company_postal_code") private String companyPostalCode; @Column(name = "company_city") private String companyCity; @Column(name = "company_country") private String companyCountry; @Column(name = "company_nip") private String companyNip; @Column(name = "company_documents_scans") private Set<String> companyDocumentsScans; @Column(name = "street") private String street; @Column(name = "postal_code") private String postalCode; @Column(name = "country") private String country; @Column(name = "identity_card_number") private String identityCardNumber; @Column(name = "identity_card_issue_date") private Date identityCardIssueDate; @Column(name = "identity_card_expiration_date") private Date identityCardExpirationDate; @Column(name = "birth_date") private Date birthDate; @Column(name = "identity_card_scans") private Set<String> identityCardScans; @Column(name = "address_confirmation_scans") private Set<String> addressConfirmationScans; @Column(name = "marketing_agreement") private Boolean marketingAgreement; @Column(name = "enabled_notifications_types") private Set<String> enabledEotificationsTypes; @Column(name = "notification_sound") private String notificationSound; @Column(name = "phone_number") private String phoneNumber; public static Users createNew(Config config) { Users user = new Users(); user.setAppId(config.getAppId()); user.setUserId(UUID.randomUUID()); /* user.setEmail(email); user.setLogin(login); user.setPassword(Passwords.hash(password));*/ user.setPermissions(config.getDefaultPermissions()); user.setTwoFactorRequiredPermissions(config.getDefaultTwoFactorAuthRequiredPermissions()); /*user.setLanguage(lang);*/ user.setGaSecret(TOTPTools.getRandomSecretKey()); return user; } @Override public String toString() { return "User [userId : "+this.getUserId()+" email : "+this.getEmail()+" login : "+this.getLogin()+"]"; } //GETTERS AND SETTERS public String getDefaultCurrency() { return defaultCurrency; } public void setDefaultCurrency(String defaultCurrency) { this.defaultCurrency = defaultCurrency; } public Integer getHelplinePin() { return helplinePin; } public void setHelplinePin(Integer helplinePin) { this.helplinePin = helplinePin; } public String getAccountType() { return accountType; } public void setAccountType(String accountType) { this.accountType = accountType; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCompanyStreet() { return companyStreet; } public void setCompanyStreet(String companyStreet) { this.companyStreet = companyStreet; } public String getCompanyPostalCode() { return companyPostalCode; } public void setCompanyPostalCode(String companyPostalCode) { this.companyPostalCode = companyPostalCode; } public String getCompanyCity() { return companyCity; } public void setCompanyCity(String companyCity) { this.companyCity = companyCity; } public String getCompanyCountry() { return companyCountry; } public void setCompanyCountry(String companyCountry) { this.companyCountry = companyCountry; } public String getCompanyNip() { return companyNip; } public void setCompanyNip(String companyNip) { this.companyNip = companyNip; } public Set<String> getCompanyDocumentsScans() { return companyDocumentsScans; } public void setCompanyDocumentsScans(Set<String> companyDocumentsScans) { this.companyDocumentsScans = companyDocumentsScans; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getIdentityCardNumber() { return identityCardNumber; } public void setIdentityCardNumber(String identityCardNumber) { this.identityCardNumber = identityCardNumber; } public Date getIdentityCardIssueDate() { return identityCardIssueDate; } public void setIdentityCardIssueDate(Date identityCardIssueDate) { this.identityCardIssueDate = identityCardIssueDate; } public Date getIdentityCardExpirationDate() { return identityCardExpirationDate; } public void setIdentityCardExpirationDate(Date identityCardExpirationDate) { this.identityCardExpirationDate = identityCardExpirationDate; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Set<String> getIdentityCardScans() { return identityCardScans; } public void setIdentityCardScans(Set<String> identityCardScans) { this.identityCardScans = identityCardScans; } public Set<String> getAddressConfirmationScans() { return addressConfirmationScans; } public void setAddressConfirmationScans(Set<String> addressConfirmationScans) { this.addressConfirmationScans = addressConfirmationScans; } public UUID getAppId() { return appId; } public void setAppId(UUID appId) { this.appId = appId; } public UUID getUserId() { return userId; } public void setUserId(UUID userId) { this.userId = userId; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setPasswordHash(String password) { this.setPassword(Passwords.hash(password)); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Set<String> getPermissions() { return permissions; } public void setPermissions(Set<String> permissions) { this.permissions = permissions; } public void appendPermissions(Set<String> permissions) { this.permissions.addAll(permissions); } public Language getLanguage() { return language; } public void setLanguage(Language language) { this.language = language; } public Boolean getEmailVerified() { return emailVerified; } public void setEmailVerified(Boolean emailVerified) { this.emailVerified = emailVerified; } public String getTwoFactorMethod() { return twoFactorMethod; } public void setTwoFactorMethod(String twoFactorMethod) { this.twoFactorMethod = twoFactorMethod; } public Set<String> getTwoFactorRequiredPermissions() { return twoFactorRequiredPermissions; } public void setTwoFactorRequiredPermissions(Set<String> twoFactorRequiredPermissions) { this.twoFactorRequiredPermissions = twoFactorRequiredPermissions; } public Boolean getAccountConfirmed() { return accountConfirmed; } public void setAccountConfirmed(Boolean accountConfirmed) { this.accountConfirmed = accountConfirmed; } public String getGaSecret() { return gaSecret; } public void setGaSecret(String gaSecret) { this.gaSecret = gaSecret; } public Boolean getMarketingAgreement() { return marketingAgreement; } public void setMarketingAgreement(Boolean marketingAgreement) { this.marketingAgreement = marketingAgreement; } public Set<String> getEnabledEotificationsTypes() { return enabledEotificationsTypes; } public void setEnabledEotificationsTypes(Set<String> enabledEotificationsTypes) { this.enabledEotificationsTypes = enabledEotificationsTypes; } public String getNotificationSound() { return notificationSound; } public void setNotificationSound(String notificationSound) { this.notificationSound = notificationSound; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
UTF-8
Java
9,747
java
Users.java
Java
[ { "context": " user.setLogin(login);\n user.setPassword(Passwords.hash(password));*/\n\t\tuser.setPermissions(config.getDef", "end": 3088, "score": 0.9372300505638123, "start": 3074, "tag": "PASSWORD", "value": "Passwords.hash" } ]
null
[]
package future.models.data; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import future.util.totp.TOTPTools; import java.util.Date; import java.util.HashSet; import java.util.Set; import java.util.UUID; @Table(name = "users") public class Users { //todo: appID aktualnie nie uzywane @PartitionKey(0) @Column(name = "app_id") private UUID appId; @PartitionKey(1) @Column(name = "user_id") private UUID userId; private String login; private String password; private String email; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; private Set<String> permissions; private Language language; @Column(name = "email_verified") private Boolean emailVerified = false; @Column(name = "account_confirmed") private Boolean accountConfirmed = false; @Column(name = "2fa_method") private String twoFactorMethod = "none"; @Column(name = "2fa_required_permissions") private Set<String> twoFactorRequiredPermissions = new HashSet<>(); @Column(name = "ga_secret") private String gaSecret; @Column(name = "default_currency") private String defaultCurrency; @Column(name = "helpline_pin") private Integer helplinePin; @Column(name = "account_type") private String accountType; @Column(name = "company_name") private String companyName; @Column(name = "company_street") private String companyStreet; @Column(name = "company_postal_code") private String companyPostalCode; @Column(name = "company_city") private String companyCity; @Column(name = "company_country") private String companyCountry; @Column(name = "company_nip") private String companyNip; @Column(name = "company_documents_scans") private Set<String> companyDocumentsScans; @Column(name = "street") private String street; @Column(name = "postal_code") private String postalCode; @Column(name = "country") private String country; @Column(name = "identity_card_number") private String identityCardNumber; @Column(name = "identity_card_issue_date") private Date identityCardIssueDate; @Column(name = "identity_card_expiration_date") private Date identityCardExpirationDate; @Column(name = "birth_date") private Date birthDate; @Column(name = "identity_card_scans") private Set<String> identityCardScans; @Column(name = "address_confirmation_scans") private Set<String> addressConfirmationScans; @Column(name = "marketing_agreement") private Boolean marketingAgreement; @Column(name = "enabled_notifications_types") private Set<String> enabledEotificationsTypes; @Column(name = "notification_sound") private String notificationSound; @Column(name = "phone_number") private String phoneNumber; public static Users createNew(Config config) { Users user = new Users(); user.setAppId(config.getAppId()); user.setUserId(UUID.randomUUID()); /* user.setEmail(email); user.setLogin(login); user.setPassword(<PASSWORD>(password));*/ user.setPermissions(config.getDefaultPermissions()); user.setTwoFactorRequiredPermissions(config.getDefaultTwoFactorAuthRequiredPermissions()); /*user.setLanguage(lang);*/ user.setGaSecret(TOTPTools.getRandomSecretKey()); return user; } @Override public String toString() { return "User [userId : "+this.getUserId()+" email : "+this.getEmail()+" login : "+this.getLogin()+"]"; } //GETTERS AND SETTERS public String getDefaultCurrency() { return defaultCurrency; } public void setDefaultCurrency(String defaultCurrency) { this.defaultCurrency = defaultCurrency; } public Integer getHelplinePin() { return helplinePin; } public void setHelplinePin(Integer helplinePin) { this.helplinePin = helplinePin; } public String getAccountType() { return accountType; } public void setAccountType(String accountType) { this.accountType = accountType; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCompanyStreet() { return companyStreet; } public void setCompanyStreet(String companyStreet) { this.companyStreet = companyStreet; } public String getCompanyPostalCode() { return companyPostalCode; } public void setCompanyPostalCode(String companyPostalCode) { this.companyPostalCode = companyPostalCode; } public String getCompanyCity() { return companyCity; } public void setCompanyCity(String companyCity) { this.companyCity = companyCity; } public String getCompanyCountry() { return companyCountry; } public void setCompanyCountry(String companyCountry) { this.companyCountry = companyCountry; } public String getCompanyNip() { return companyNip; } public void setCompanyNip(String companyNip) { this.companyNip = companyNip; } public Set<String> getCompanyDocumentsScans() { return companyDocumentsScans; } public void setCompanyDocumentsScans(Set<String> companyDocumentsScans) { this.companyDocumentsScans = companyDocumentsScans; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getIdentityCardNumber() { return identityCardNumber; } public void setIdentityCardNumber(String identityCardNumber) { this.identityCardNumber = identityCardNumber; } public Date getIdentityCardIssueDate() { return identityCardIssueDate; } public void setIdentityCardIssueDate(Date identityCardIssueDate) { this.identityCardIssueDate = identityCardIssueDate; } public Date getIdentityCardExpirationDate() { return identityCardExpirationDate; } public void setIdentityCardExpirationDate(Date identityCardExpirationDate) { this.identityCardExpirationDate = identityCardExpirationDate; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Set<String> getIdentityCardScans() { return identityCardScans; } public void setIdentityCardScans(Set<String> identityCardScans) { this.identityCardScans = identityCardScans; } public Set<String> getAddressConfirmationScans() { return addressConfirmationScans; } public void setAddressConfirmationScans(Set<String> addressConfirmationScans) { this.addressConfirmationScans = addressConfirmationScans; } public UUID getAppId() { return appId; } public void setAppId(UUID appId) { this.appId = appId; } public UUID getUserId() { return userId; } public void setUserId(UUID userId) { this.userId = userId; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public void setPasswordHash(String password) { this.setPassword(Passwords.hash(password)); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Set<String> getPermissions() { return permissions; } public void setPermissions(Set<String> permissions) { this.permissions = permissions; } public void appendPermissions(Set<String> permissions) { this.permissions.addAll(permissions); } public Language getLanguage() { return language; } public void setLanguage(Language language) { this.language = language; } public Boolean getEmailVerified() { return emailVerified; } public void setEmailVerified(Boolean emailVerified) { this.emailVerified = emailVerified; } public String getTwoFactorMethod() { return twoFactorMethod; } public void setTwoFactorMethod(String twoFactorMethod) { this.twoFactorMethod = twoFactorMethod; } public Set<String> getTwoFactorRequiredPermissions() { return twoFactorRequiredPermissions; } public void setTwoFactorRequiredPermissions(Set<String> twoFactorRequiredPermissions) { this.twoFactorRequiredPermissions = twoFactorRequiredPermissions; } public Boolean getAccountConfirmed() { return accountConfirmed; } public void setAccountConfirmed(Boolean accountConfirmed) { this.accountConfirmed = accountConfirmed; } public String getGaSecret() { return gaSecret; } public void setGaSecret(String gaSecret) { this.gaSecret = gaSecret; } public Boolean getMarketingAgreement() { return marketingAgreement; } public void setMarketingAgreement(Boolean marketingAgreement) { this.marketingAgreement = marketingAgreement; } public Set<String> getEnabledEotificationsTypes() { return enabledEotificationsTypes; } public void setEnabledEotificationsTypes(Set<String> enabledEotificationsTypes) { this.enabledEotificationsTypes = enabledEotificationsTypes; } public String getNotificationSound() { return notificationSound; } public void setNotificationSound(String notificationSound) { this.notificationSound = notificationSound; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } }
9,743
0.753565
0.753155
453
20.516556
20.744698
104
false
false
0
0
0
0
0
0
1.174393
false
false
2
a3d4673c00ddfc17cb6f9bfffd32fc10d5027fef
24,206,435,682,590
41b7e06423a8a1cf564ea74cd02e2cd99fc9c4a0
/sic-api/src/test/java/sic/integration/FlujoCuentaCorrienteIntegrationTest.java
978928538527421500ccd28125cdc25c3c38a7af
[]
no_license
belluccifranco/sic
https://github.com/belluccifranco/sic
2c4a7afc78045ae912a391462e8dab29e1fec3c2
26143606dde4f528fed163c20f1607e04103ebc5
refs/heads/master
2020-01-18T02:32:41.691000
2017-10-31T01:09:07
2017-10-31T01:09:07
19,440,641
9
9
null
false
2017-10-14T00:21:45
2014-05-05T01:41:25
2017-08-07T17:27:47
2017-10-14T00:21:45
31,293
5
7
68
Java
null
null
package sic.integration; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Assert; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRequest; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestClientResponseException; import sic.builder.ClienteBuilder; import sic.builder.CondicionIVABuilder; import sic.builder.EmpresaBuilder; import sic.builder.FormaDePagoBuilder; import sic.builder.LocalidadBuilder; import sic.builder.MedidaBuilder; import sic.builder.ProductoBuilder; import sic.builder.ProveedorBuilder; import sic.builder.RubroBuilder; import sic.builder.TransportistaBuilder; import sic.builder.UsuarioBuilder; import sic.modelo.Cliente; import sic.modelo.CondicionIVA; import sic.modelo.Credencial; import sic.modelo.Empresa; import sic.modelo.FacturaVenta; import sic.modelo.FormaDePago; import sic.modelo.Localidad; import sic.modelo.Medida; import sic.modelo.Movimiento; import sic.modelo.NotaCredito; import sic.modelo.NotaDebito; import sic.modelo.Pago; import sic.modelo.Pais; import sic.modelo.Producto; import sic.modelo.Proveedor; import sic.modelo.Provincia; import sic.modelo.RenglonFactura; import sic.modelo.RenglonNotaCredito; import sic.modelo.RenglonNotaDebito; import sic.modelo.Rol; import sic.modelo.Rubro; import sic.modelo.TipoDeComprobante; import sic.modelo.Transportista; import sic.modelo.Usuario; import sic.modelo.dto.FacturaVentaDTO; import sic.modelo.dto.NotaCreditoDTO; import sic.modelo.dto.NotaDebitoDTO; import sic.repository.UsuarioRepository; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class FlujoCuentaCorrienteIntegrationTest { @Autowired private UsuarioRepository usuarioRepository; @Autowired private TestRestTemplate restTemplate; private String token; private final String apiPrefix = "/api/v1"; @Before public void setup() { String md5Test = "098f6bcd4621d373cade4e832627b4f6"; usuarioRepository.save(new UsuarioBuilder().withNombre("test").withPassword(md5Test).build()); // Interceptor de RestTemplate para JWT List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add((ClientHttpRequestInterceptor) (HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> { request.getHeaders().set("Authorization", "Bearer " + token); return execution.execute(request, body); }); restTemplate.getRestTemplate().setInterceptors(interceptors); // ErrorHandler para RestTemplate restTemplate.getRestTemplate().setErrorHandler(new ResponseErrorHandler() { @Override public boolean hasError(ClientHttpResponse response) throws IOException { HttpStatus.Series series = response.getStatusCode().series(); return (HttpStatus.Series.CLIENT_ERROR.equals(series) || HttpStatus.Series.SERVER_ERROR.equals(series)); } @Override public void handleError(ClientHttpResponse response) throws IOException { String mensaje = IOUtils.toString(response.getBody()); throw new RestClientResponseException(mensaje, response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, Charset.defaultCharset()); } }); } @Test public void testCuentaCorriente() { this.token = restTemplate.postForEntity(apiPrefix + "/login", new Credencial("test", "test"), String.class).getBody(); Localidad localidad = new LocalidadBuilder().build(); localidad.getProvincia().setPais(restTemplate.postForObject(apiPrefix + "/paises", localidad.getProvincia().getPais(), Pais.class)); localidad.setProvincia(restTemplate.postForObject(apiPrefix + "/provincias", localidad.getProvincia(), Provincia.class)); CondicionIVA condicionIVA = new CondicionIVABuilder().build(); Empresa empresa = new EmpresaBuilder() .withLocalidad(restTemplate.postForObject(apiPrefix + "/localidades", localidad, Localidad.class)) .withCondicionIVA(restTemplate.postForObject(apiPrefix + "/condiciones-iva", condicionIVA, CondicionIVA.class)) .build(); empresa = restTemplate.postForObject(apiPrefix + "/empresas", empresa, Empresa.class); FormaDePago formaDePago = new FormaDePagoBuilder() .withAfectaCaja(false) .withEmpresa(empresa) .withPredeterminado(true) .withNombre("Efectivo") .build(); formaDePago = restTemplate.postForObject(apiPrefix + "/formas-de-pago", formaDePago, FormaDePago.class); Usuario credencial = new UsuarioBuilder() .withId_Usuario(1) .withEliminado(false) .withNombre("Marcelo Cruz") .withPassword("marce") .withToken("yJhbGci1NiIsInR5cCI6IkpXVCJ9.eyJub21icmUiOiJjZWNpbGlvIn0.MCfaorSC7Wdc8rSW7BJizasfzsa") .withRol(new ArrayList<>()) .build(); Usuario viajante = new UsuarioBuilder() .withId_Usuario(1) .withEliminado(false) .withNombre("Fernando Aguirre") .withPassword("fernando") .withToken("yJhbGci1NiIsInR5cCI6IkpXVCJ9.eyJub21icmUiOiJjZWNpbGlvIn0.MCfaorSC7Wdc8rSW7BJizasfzsb") .withRol(new ArrayList<>(Arrays.asList(Rol.VIAJANTE))) .build(); Cliente cliente = new ClienteBuilder() .withEmpresa(empresa) .withCondicionIVA(empresa.getCondicionIVA()) .withLocalidad(empresa.getLocalidad()) .withPredeterminado(true) .withCredencial(credencial) .withViajante(viajante) .build(); cliente = restTemplate.postForObject(apiPrefix + "/clientes", cliente, Cliente.class); Transportista transportista = new TransportistaBuilder() .withEmpresa(empresa) .withLocalidad(empresa.getLocalidad()) .build(); transportista = restTemplate.postForObject(apiPrefix + "/transportistas", transportista, Transportista.class); Medida medida = new MedidaBuilder().withEmpresa(empresa).build(); medida = restTemplate.postForObject(apiPrefix + "/medidas", medida, Medida.class); Proveedor proveedor = new ProveedorBuilder().withEmpresa(empresa) .withLocalidad(empresa.getLocalidad()) .withCondicionIVA(empresa.getCondicionIVA()) .build(); proveedor = restTemplate.postForObject(apiPrefix + "/proveedores", proveedor, Proveedor.class); Rubro rubro = new RubroBuilder().withEmpresa(empresa).build(); rubro = restTemplate.postForObject(apiPrefix + "/rubros", rubro, Rubro.class); Producto productoUno = new ProductoBuilder() .withCodigo("1") .withDescripcion("uno") .withCantidad(10) .withVentaMinima(1) .withPrecioVentaPublico(1000) .withIva_porcentaje(21.0) .withIva_neto(210) .withPrecioLista(1210) .withEmpresa(empresa) .withMedida(medida) .withProveedor(proveedor) .withRubro(rubro) .build(); Producto productoDos = new ProductoBuilder() .withCodigo("2") .withDescripcion("dos") .withCantidad(6) .withVentaMinima(1) .withPrecioVentaPublico(1000) .withIva_porcentaje(10.5) .withIva_neto(105) .withPrecioLista(1105) .withEmpresa(empresa) .withMedida(medida) .withProveedor(proveedor) .withRubro(rubro) .build(); productoUno = restTemplate.postForObject(apiPrefix + "/productos", productoUno, Producto.class); productoDos = restTemplate.postForObject(apiPrefix + "/productos", productoDos, Producto.class); Assert.assertTrue(restTemplate.getForObject(apiPrefix + "/productos/" + productoUno.getId_Producto() + "/stock/disponibilidad?cantidad=10", Boolean.class)); Assert.assertTrue(restTemplate.getForObject(apiPrefix + "/productos/" + productoDos.getId_Producto() + "/stock/disponibilidad?cantidad=6", Boolean.class)); RenglonFactura renglonUno = restTemplate.getForObject(apiPrefix + "/facturas/renglon?" + "idProducto=" + productoUno.getId_Producto() + "&tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&movimiento=" + Movimiento.VENTA + "&cantidad=5" + "&descuentoPorcentaje=20", RenglonFactura.class); RenglonFactura renglonDos = restTemplate.getForObject(apiPrefix + "/facturas/renglon?" + "idProducto=" + productoDos.getId_Producto() + "&tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&movimiento=" + Movimiento.VENTA + "&cantidad=2" + "&descuentoPorcentaje=0", RenglonFactura.class); List<RenglonFactura> renglones = new ArrayList<>(); renglones.add(renglonUno); renglones.add(renglonDos); int size = renglones.size(); double[] importes = new double[size]; double[] cantidades = new double[size]; double[] ivaPorcentajeRenglones = new double[size]; double[] ivaNetoRenglones = new double[size]; int indice = 0; for (RenglonFactura renglon : renglones) { importes[indice] = renglon.getImporte(); cantidades[indice] = renglon.getCantidad(); ivaPorcentajeRenglones[indice] = renglon.getIva_porcentaje(); ivaNetoRenglones[indice] = renglon.getIva_neto(); indice++; } double subTotal = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/subtotal?" + "importe=" + Arrays.toString(importes).substring(1, Arrays.toString(importes).length() - 1), double.class); double descuentoPorcentaje = 25; double recargoPorcentaje = 10; double descuento_neto = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/descuento-neto?" + "subTotal=" + subTotal + "&descuentoPorcentaje=" + descuentoPorcentaje, double.class); double recargo_neto = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/recargo-neto?" + "subTotal=" + subTotal + "&recargoPorcentaje=" + recargoPorcentaje, double.class); double iva_105_netoFactura = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/iva-neto?" + "tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&cantidades=" + Arrays.toString(cantidades).substring(1, Arrays.toString(cantidades).length() - 1) + "&ivaPorcentajeRenglones=" + Arrays.toString(ivaPorcentajeRenglones).substring(1, Arrays.toString(ivaPorcentajeRenglones).length() - 1) + "&ivaNetoRenglones=" + Arrays.toString(ivaNetoRenglones).substring(1, Arrays.toString(ivaNetoRenglones).length() - 1) + "&ivaPorcentaje=10.5" + "&descuentoPorcentaje=" + descuentoPorcentaje + "&recargoPorcentaje=" + recargoPorcentaje, double.class); double iva_21_netoFactura = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/iva-neto?" + "tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&cantidades=" + Arrays.toString(cantidades).substring(1, Arrays.toString(cantidades).length() - 1) + "&ivaPorcentajeRenglones=" + Arrays.toString(ivaPorcentajeRenglones).substring(1, Arrays.toString(ivaPorcentajeRenglones).length() - 1) + "&ivaNetoRenglones=" + Arrays.toString(ivaNetoRenglones).substring(1, Arrays.toString(ivaNetoRenglones).length() - 1) + "&ivaPorcentaje=21" + "&descuentoPorcentaje=" + descuentoPorcentaje + "&recargoPorcentaje=" + recargoPorcentaje, double.class); double subTotalBruto = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/subtotal-bruto?" + "tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&subTotal=" + subTotal + "&recargoNeto=" + recargo_neto + "&descuentoNeto=" + descuento_neto + "&iva105Neto=" + iva_105_netoFactura + "&iva21Neto=" + iva_21_netoFactura, double.class); double total = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/total?" + "subTotalBruto=" + subTotalBruto + "&iva105Neto=" + iva_105_netoFactura + "&iva21Neto=" + iva_21_netoFactura, double.class); FacturaVentaDTO facturaVentaB = new FacturaVentaDTO(); facturaVentaB.setTipoComprobante(TipoDeComprobante.FACTURA_B); facturaVentaB.setCliente(cliente); facturaVentaB.setEmpresa(empresa); facturaVentaB.setTransportista(transportista); facturaVentaB.setUsuario(restTemplate.getForObject(apiPrefix + "/usuarios/busqueda?nombre=test", Usuario.class)); facturaVentaB.setRenglones(renglones); facturaVentaB.setSubTotal(subTotal); facturaVentaB.setRecargo_porcentaje(recargoPorcentaje); facturaVentaB.setRecargo_neto(recargo_neto); facturaVentaB.setDescuento_porcentaje(descuentoPorcentaje); facturaVentaB.setDescuento_neto(descuento_neto); facturaVentaB.setSubTotal_bruto(subTotalBruto); facturaVentaB.setIva_105_neto(iva_105_netoFactura); facturaVentaB.setIva_21_neto(iva_21_netoFactura); facturaVentaB.setTotal(total); restTemplate.postForObject(apiPrefix + "/facturas/venta", facturaVentaB, FacturaVenta[].class); assertEquals(0, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo?hasta=1451617200000", Double.class), 0); assertEquals(-5992.5, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); List<FacturaVenta> facturasRecuperadas = restTemplate .exchange(apiPrefix + "/facturas/venta/busqueda/criteria?idEmpresa=1&tipoFactura=B&nroSerie=0&nroFactura=1", HttpMethod.GET, null, new ParameterizedTypeReference<PaginaRespuestaRest<FacturaVenta>>() { }) .getBody().getContent(); Pago pago = new Pago(); pago.setEmpresa(empresa); pago.setFactura(facturasRecuperadas.get(0)); pago.setFecha(new Date()); pago.setFormaDePago(formaDePago); pago.setMonto(5992.5); pago = restTemplate.postForObject(apiPrefix + "/pagos/facturas/1", pago, Pago.class); assertEquals(0, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); NotaDebitoDTO notaDebito = new NotaDebitoDTO(); notaDebito.setCliente(cliente); notaDebito.setEmpresa(empresa); notaDebito.setFecha(new Date()); notaDebito.setPagoId(pago.getId_Pago()); List<RenglonNotaDebito> renglonesCalculados = Arrays.asList(restTemplate.getForObject(apiPrefix + "/notas/renglon/debito/pago/1?monto=100&ivaPorcentaje=21", RenglonNotaDebito[].class)); notaDebito.setRenglonesNotaDebito(renglonesCalculados); notaDebito.setIva105Neto(0); notaDebito.setIva21Neto(21); notaDebito.setMontoNoGravado(5992.5); notaDebito.setMotivo("Test alta nota debito - Cheque rechazado"); notaDebito.setSubTotalBruto(100); notaDebito.setTotal(6113.5); notaDebito.setUsuario(credencial); notaDebito.setFacturaVenta(null); NotaDebito nd = restTemplate.postForObject(apiPrefix + "/notas/debito/empresa/1/cliente/1/usuario/1/pago/1", notaDebito, NotaDebito.class); assertEquals(-6113.5, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); pago = new Pago(); pago.setEmpresa(empresa); pago.setNotaDebito(nd); pago.setFecha(new Date()); pago.setFormaDePago(formaDePago); pago.setMonto(6113.5); restTemplate.postForObject(apiPrefix + "/pagos/notas/1", pago, Pago.class); assertEquals(0, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); List<RenglonNotaCredito> renglonesNotaCredito = Arrays.asList(restTemplate.getForObject(apiPrefix + "/notas/renglon/credito/producto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&cantidad=5&idRenglonFactura=1", RenglonNotaCredito[].class)); NotaCreditoDTO notaCredito = new NotaCreditoDTO(); notaCredito.setRenglonesNotaCredito(renglonesNotaCredito); notaCredito.setFacturaVenta(facturasRecuperadas.get(0)); notaCredito.setFecha(new Date()); notaCredito.setSubTotal(restTemplate.getForObject(apiPrefix +"/notas/credito/sub-total?importe=" + renglonesNotaCredito.get(0).getImporteNeto(), Double.class)); notaCredito.setRecargoPorcentaje(facturasRecuperadas.get(0).getRecargo_porcentaje()); notaCredito.setRecargoNeto(restTemplate.getForObject(apiPrefix +"/notas/credito/recargo-neto?subTotal=" + notaCredito.getSubTotal() + "&recargoPorcentaje=" + notaCredito.getRecargoPorcentaje(), Double.class)); notaCredito.setDescuentoPorcentaje(facturasRecuperadas.get(0).getDescuento_porcentaje()); notaCredito.setDescuentoNeto(restTemplate.getForObject(apiPrefix +"/notas/credito/descuento-neto?subTotal=" + notaCredito.getSubTotal() + "&descuentoPorcentaje=" + notaCredito.getDescuentoPorcentaje(), Double.class)); notaCredito.setIva21Neto(restTemplate.getForObject(apiPrefix + "/notas/credito/iva-neto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&cantidades=" + renglonesNotaCredito.get(0).getCantidad() + "&ivaPorcentajeRenglones=" + renglonesNotaCredito.get(0).getIvaPorcentaje() + "&ivaNetoRenglones=" + renglonesNotaCredito.get(0).getIvaNeto() + "&ivaPorcentaje=21" + "&descuentoPorcentaje=" + facturasRecuperadas.get(0).getDescuento_porcentaje() + "&recargoPorcentaje=" + facturasRecuperadas.get(0).getRecargo_porcentaje(), Double.class)); notaCredito.setIva105Neto(restTemplate.getForObject(apiPrefix + "/notas/credito/iva-neto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&cantidades=" + renglonesNotaCredito.get(0).getCantidad() + "&ivaPorcentajeRenglones=" + renglonesNotaCredito.get(0).getIvaPorcentaje() + "&ivaNetoRenglones=" + renglonesNotaCredito.get(0).getIvaNeto() + "&ivaPorcentaje=10.5" + "&descuentoPorcentaje=" + facturasRecuperadas.get(0).getDescuento_porcentaje() + "&recargoPorcentaje=" + facturasRecuperadas.get(0).getRecargo_porcentaje(), Double.class)); notaCredito.setSubTotalBruto(restTemplate.getForObject(apiPrefix + "/notas/credito/sub-total-bruto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&subTotal=" + notaCredito.getSubTotal() + "&recargoNeto=" + notaCredito.getRecargoNeto() + "&descuentoNeto=" + notaCredito.getDescuentoNeto() + "&iva21Neto=" + notaCredito.getIva21Neto() + "&iva105Neto=" + notaCredito.getIva105Neto(), Double.class)); notaCredito.setTotal(restTemplate.getForObject(apiPrefix + "/notas/credito/total?subTotalBruto=" + notaCredito.getSubTotalBruto() + "&iva21Neto=" + notaCredito.getIva21Neto() + "&iva105Neto=" + notaCredito.getIva105Neto(), Double.class)); restTemplate.postForObject(apiPrefix + "/notas/credito/empresa/1/cliente/1/usuario/1/factura/1?modificarStock=false", notaCredito, NotaCredito.class); assertEquals(4114, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); } }
UTF-8
Java
21,976
java
FlujoCuentaCorrienteIntegrationTest.java
Java
[ { "context": "oRepository.save(new UsuarioBuilder().withNombre(\"test\").withPassword(md5Test).build());\n // Inte", "end": 3083, "score": 0.5050004124641418, "start": 3079, "tag": "USERNAME", "value": "test" }, { "context": " UsuarioBuilder().withNombre(\"test\").withPassword(md5Test).build());\n // Interceptor de RestTemplate", "end": 3106, "score": 0.9776999354362488, "start": 3099, "tag": "PASSWORD", "value": "md5Test" }, { "context": "withEliminado(false)\n .withNombre(\"Marcelo Cruz\")\n .withPassword(\"marce\")\n ", "end": 6027, "score": 0.9998566508293152, "start": 6015, "tag": "NAME", "value": "Marcelo Cruz" }, { "context": "re(\"Marcelo Cruz\")\n .withPassword(\"marce\")\n .withToken(\"yJhbGci1NiIsInR5cCI", "end": 6066, "score": 0.9991012811660767, "start": 6061, "tag": "PASSWORD", "value": "marce" }, { "context": "withPassword(\"marce\")\n .withToken(\"yJhbGci1NiIsInR5cCI6IkpXVCJ9.eyJub21icmUiOiJjZWNpbGlvIn0.MCfaorSC7Wdc8rSW7BJizasfzsa\")\n .withRol(new ArrayList<>())\n ", "end": 6181, "score": 0.9433315396308899, "start": 6097, "tag": "KEY", "value": "yJhbGci1NiIsInR5cCI6IkpXVCJ9.eyJub21icmUiOiJjZWNpbGlvIn0.MCfaorSC7Wdc8rSW7BJizasfzsa" }, { "context": "withEliminado(false)\n .withNombre(\"Fernando Aguirre\")\n .withPassword(\"fernando\")\n ", "end": 6420, "score": 0.9998631477355957, "start": 6404, "tag": "NAME", "value": "Fernando Aguirre" }, { "context": "Fernando Aguirre\")\n .withPassword(\"fernando\")\n .withToken(\"yJhbGci1NiIsInR5cCI", "end": 6462, "score": 0.9987075924873352, "start": 6454, "tag": "PASSWORD", "value": "fernando" }, { "context": "hPassword(\"fernando\")\n .withToken(\"yJhbGci1NiIsInR5cCI6IkpXVCJ9.eyJub21icmUiOiJjZWNpbGlvIn0.MCfaorSC7Wdc8rSW7BJizasfzsb\")\n .withRol(new ArrayList<>(Arrays", "end": 6577, "score": 0.9995743632316589, "start": 6493, "tag": "KEY", "value": "yJhbGci1NiIsInR5cCI6IkpXVCJ9.eyJub21icmUiOiJjZWNpbGlvIn0.MCfaorSC7Wdc8rSW7BJizasfzsb" }, { "context": "tForObject(apiPrefix + \"/usuarios/busqueda?nombre=test\", Usuario.class));\n facturaVentaB.setRengl", "end": 14745, "score": 0.5075057744979858, "start": 14741, "tag": "NAME", "value": "test" }, { "context": "tTotal(6113.5);\n notaDebito.setUsuario(credencial);\n notaDebito.setFacturaVenta(null);\n ", "end": 17302, "score": 0.47943785786628723, "start": 17296, "tag": "USERNAME", "value": "encial" } ]
null
[]
package sic.integration; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Assert; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRequest; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestClientResponseException; import sic.builder.ClienteBuilder; import sic.builder.CondicionIVABuilder; import sic.builder.EmpresaBuilder; import sic.builder.FormaDePagoBuilder; import sic.builder.LocalidadBuilder; import sic.builder.MedidaBuilder; import sic.builder.ProductoBuilder; import sic.builder.ProveedorBuilder; import sic.builder.RubroBuilder; import sic.builder.TransportistaBuilder; import sic.builder.UsuarioBuilder; import sic.modelo.Cliente; import sic.modelo.CondicionIVA; import sic.modelo.Credencial; import sic.modelo.Empresa; import sic.modelo.FacturaVenta; import sic.modelo.FormaDePago; import sic.modelo.Localidad; import sic.modelo.Medida; import sic.modelo.Movimiento; import sic.modelo.NotaCredito; import sic.modelo.NotaDebito; import sic.modelo.Pago; import sic.modelo.Pais; import sic.modelo.Producto; import sic.modelo.Proveedor; import sic.modelo.Provincia; import sic.modelo.RenglonFactura; import sic.modelo.RenglonNotaCredito; import sic.modelo.RenglonNotaDebito; import sic.modelo.Rol; import sic.modelo.Rubro; import sic.modelo.TipoDeComprobante; import sic.modelo.Transportista; import sic.modelo.Usuario; import sic.modelo.dto.FacturaVentaDTO; import sic.modelo.dto.NotaCreditoDTO; import sic.modelo.dto.NotaDebitoDTO; import sic.repository.UsuarioRepository; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) public class FlujoCuentaCorrienteIntegrationTest { @Autowired private UsuarioRepository usuarioRepository; @Autowired private TestRestTemplate restTemplate; private String token; private final String apiPrefix = "/api/v1"; @Before public void setup() { String md5Test = "098f6bcd4621d373cade4e832627b4f6"; usuarioRepository.save(new UsuarioBuilder().withNombre("test").withPassword(<PASSWORD>).build()); // Interceptor de RestTemplate para JWT List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add((ClientHttpRequestInterceptor) (HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> { request.getHeaders().set("Authorization", "Bearer " + token); return execution.execute(request, body); }); restTemplate.getRestTemplate().setInterceptors(interceptors); // ErrorHandler para RestTemplate restTemplate.getRestTemplate().setErrorHandler(new ResponseErrorHandler() { @Override public boolean hasError(ClientHttpResponse response) throws IOException { HttpStatus.Series series = response.getStatusCode().series(); return (HttpStatus.Series.CLIENT_ERROR.equals(series) || HttpStatus.Series.SERVER_ERROR.equals(series)); } @Override public void handleError(ClientHttpResponse response) throws IOException { String mensaje = IOUtils.toString(response.getBody()); throw new RestClientResponseException(mensaje, response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, Charset.defaultCharset()); } }); } @Test public void testCuentaCorriente() { this.token = restTemplate.postForEntity(apiPrefix + "/login", new Credencial("test", "test"), String.class).getBody(); Localidad localidad = new LocalidadBuilder().build(); localidad.getProvincia().setPais(restTemplate.postForObject(apiPrefix + "/paises", localidad.getProvincia().getPais(), Pais.class)); localidad.setProvincia(restTemplate.postForObject(apiPrefix + "/provincias", localidad.getProvincia(), Provincia.class)); CondicionIVA condicionIVA = new CondicionIVABuilder().build(); Empresa empresa = new EmpresaBuilder() .withLocalidad(restTemplate.postForObject(apiPrefix + "/localidades", localidad, Localidad.class)) .withCondicionIVA(restTemplate.postForObject(apiPrefix + "/condiciones-iva", condicionIVA, CondicionIVA.class)) .build(); empresa = restTemplate.postForObject(apiPrefix + "/empresas", empresa, Empresa.class); FormaDePago formaDePago = new FormaDePagoBuilder() .withAfectaCaja(false) .withEmpresa(empresa) .withPredeterminado(true) .withNombre("Efectivo") .build(); formaDePago = restTemplate.postForObject(apiPrefix + "/formas-de-pago", formaDePago, FormaDePago.class); Usuario credencial = new UsuarioBuilder() .withId_Usuario(1) .withEliminado(false) .withNombre("<NAME>") .withPassword("<PASSWORD>") .withToken("<KEY>") .withRol(new ArrayList<>()) .build(); Usuario viajante = new UsuarioBuilder() .withId_Usuario(1) .withEliminado(false) .withNombre("<NAME>") .withPassword("<PASSWORD>") .withToken("<KEY>") .withRol(new ArrayList<>(Arrays.asList(Rol.VIAJANTE))) .build(); Cliente cliente = new ClienteBuilder() .withEmpresa(empresa) .withCondicionIVA(empresa.getCondicionIVA()) .withLocalidad(empresa.getLocalidad()) .withPredeterminado(true) .withCredencial(credencial) .withViajante(viajante) .build(); cliente = restTemplate.postForObject(apiPrefix + "/clientes", cliente, Cliente.class); Transportista transportista = new TransportistaBuilder() .withEmpresa(empresa) .withLocalidad(empresa.getLocalidad()) .build(); transportista = restTemplate.postForObject(apiPrefix + "/transportistas", transportista, Transportista.class); Medida medida = new MedidaBuilder().withEmpresa(empresa).build(); medida = restTemplate.postForObject(apiPrefix + "/medidas", medida, Medida.class); Proveedor proveedor = new ProveedorBuilder().withEmpresa(empresa) .withLocalidad(empresa.getLocalidad()) .withCondicionIVA(empresa.getCondicionIVA()) .build(); proveedor = restTemplate.postForObject(apiPrefix + "/proveedores", proveedor, Proveedor.class); Rubro rubro = new RubroBuilder().withEmpresa(empresa).build(); rubro = restTemplate.postForObject(apiPrefix + "/rubros", rubro, Rubro.class); Producto productoUno = new ProductoBuilder() .withCodigo("1") .withDescripcion("uno") .withCantidad(10) .withVentaMinima(1) .withPrecioVentaPublico(1000) .withIva_porcentaje(21.0) .withIva_neto(210) .withPrecioLista(1210) .withEmpresa(empresa) .withMedida(medida) .withProveedor(proveedor) .withRubro(rubro) .build(); Producto productoDos = new ProductoBuilder() .withCodigo("2") .withDescripcion("dos") .withCantidad(6) .withVentaMinima(1) .withPrecioVentaPublico(1000) .withIva_porcentaje(10.5) .withIva_neto(105) .withPrecioLista(1105) .withEmpresa(empresa) .withMedida(medida) .withProveedor(proveedor) .withRubro(rubro) .build(); productoUno = restTemplate.postForObject(apiPrefix + "/productos", productoUno, Producto.class); productoDos = restTemplate.postForObject(apiPrefix + "/productos", productoDos, Producto.class); Assert.assertTrue(restTemplate.getForObject(apiPrefix + "/productos/" + productoUno.getId_Producto() + "/stock/disponibilidad?cantidad=10", Boolean.class)); Assert.assertTrue(restTemplate.getForObject(apiPrefix + "/productos/" + productoDos.getId_Producto() + "/stock/disponibilidad?cantidad=6", Boolean.class)); RenglonFactura renglonUno = restTemplate.getForObject(apiPrefix + "/facturas/renglon?" + "idProducto=" + productoUno.getId_Producto() + "&tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&movimiento=" + Movimiento.VENTA + "&cantidad=5" + "&descuentoPorcentaje=20", RenglonFactura.class); RenglonFactura renglonDos = restTemplate.getForObject(apiPrefix + "/facturas/renglon?" + "idProducto=" + productoDos.getId_Producto() + "&tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&movimiento=" + Movimiento.VENTA + "&cantidad=2" + "&descuentoPorcentaje=0", RenglonFactura.class); List<RenglonFactura> renglones = new ArrayList<>(); renglones.add(renglonUno); renglones.add(renglonDos); int size = renglones.size(); double[] importes = new double[size]; double[] cantidades = new double[size]; double[] ivaPorcentajeRenglones = new double[size]; double[] ivaNetoRenglones = new double[size]; int indice = 0; for (RenglonFactura renglon : renglones) { importes[indice] = renglon.getImporte(); cantidades[indice] = renglon.getCantidad(); ivaPorcentajeRenglones[indice] = renglon.getIva_porcentaje(); ivaNetoRenglones[indice] = renglon.getIva_neto(); indice++; } double subTotal = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/subtotal?" + "importe=" + Arrays.toString(importes).substring(1, Arrays.toString(importes).length() - 1), double.class); double descuentoPorcentaje = 25; double recargoPorcentaje = 10; double descuento_neto = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/descuento-neto?" + "subTotal=" + subTotal + "&descuentoPorcentaje=" + descuentoPorcentaje, double.class); double recargo_neto = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/recargo-neto?" + "subTotal=" + subTotal + "&recargoPorcentaje=" + recargoPorcentaje, double.class); double iva_105_netoFactura = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/iva-neto?" + "tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&cantidades=" + Arrays.toString(cantidades).substring(1, Arrays.toString(cantidades).length() - 1) + "&ivaPorcentajeRenglones=" + Arrays.toString(ivaPorcentajeRenglones).substring(1, Arrays.toString(ivaPorcentajeRenglones).length() - 1) + "&ivaNetoRenglones=" + Arrays.toString(ivaNetoRenglones).substring(1, Arrays.toString(ivaNetoRenglones).length() - 1) + "&ivaPorcentaje=10.5" + "&descuentoPorcentaje=" + descuentoPorcentaje + "&recargoPorcentaje=" + recargoPorcentaje, double.class); double iva_21_netoFactura = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/iva-neto?" + "tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&cantidades=" + Arrays.toString(cantidades).substring(1, Arrays.toString(cantidades).length() - 1) + "&ivaPorcentajeRenglones=" + Arrays.toString(ivaPorcentajeRenglones).substring(1, Arrays.toString(ivaPorcentajeRenglones).length() - 1) + "&ivaNetoRenglones=" + Arrays.toString(ivaNetoRenglones).substring(1, Arrays.toString(ivaNetoRenglones).length() - 1) + "&ivaPorcentaje=21" + "&descuentoPorcentaje=" + descuentoPorcentaje + "&recargoPorcentaje=" + recargoPorcentaje, double.class); double subTotalBruto = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/subtotal-bruto?" + "tipoDeComprobante=" + TipoDeComprobante.FACTURA_B + "&subTotal=" + subTotal + "&recargoNeto=" + recargo_neto + "&descuentoNeto=" + descuento_neto + "&iva105Neto=" + iva_105_netoFactura + "&iva21Neto=" + iva_21_netoFactura, double.class); double total = restTemplate.getRestTemplate().getForObject(apiPrefix + "/facturas/total?" + "subTotalBruto=" + subTotalBruto + "&iva105Neto=" + iva_105_netoFactura + "&iva21Neto=" + iva_21_netoFactura, double.class); FacturaVentaDTO facturaVentaB = new FacturaVentaDTO(); facturaVentaB.setTipoComprobante(TipoDeComprobante.FACTURA_B); facturaVentaB.setCliente(cliente); facturaVentaB.setEmpresa(empresa); facturaVentaB.setTransportista(transportista); facturaVentaB.setUsuario(restTemplate.getForObject(apiPrefix + "/usuarios/busqueda?nombre=test", Usuario.class)); facturaVentaB.setRenglones(renglones); facturaVentaB.setSubTotal(subTotal); facturaVentaB.setRecargo_porcentaje(recargoPorcentaje); facturaVentaB.setRecargo_neto(recargo_neto); facturaVentaB.setDescuento_porcentaje(descuentoPorcentaje); facturaVentaB.setDescuento_neto(descuento_neto); facturaVentaB.setSubTotal_bruto(subTotalBruto); facturaVentaB.setIva_105_neto(iva_105_netoFactura); facturaVentaB.setIva_21_neto(iva_21_netoFactura); facturaVentaB.setTotal(total); restTemplate.postForObject(apiPrefix + "/facturas/venta", facturaVentaB, FacturaVenta[].class); assertEquals(0, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo?hasta=1451617200000", Double.class), 0); assertEquals(-5992.5, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); List<FacturaVenta> facturasRecuperadas = restTemplate .exchange(apiPrefix + "/facturas/venta/busqueda/criteria?idEmpresa=1&tipoFactura=B&nroSerie=0&nroFactura=1", HttpMethod.GET, null, new ParameterizedTypeReference<PaginaRespuestaRest<FacturaVenta>>() { }) .getBody().getContent(); Pago pago = new Pago(); pago.setEmpresa(empresa); pago.setFactura(facturasRecuperadas.get(0)); pago.setFecha(new Date()); pago.setFormaDePago(formaDePago); pago.setMonto(5992.5); pago = restTemplate.postForObject(apiPrefix + "/pagos/facturas/1", pago, Pago.class); assertEquals(0, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); NotaDebitoDTO notaDebito = new NotaDebitoDTO(); notaDebito.setCliente(cliente); notaDebito.setEmpresa(empresa); notaDebito.setFecha(new Date()); notaDebito.setPagoId(pago.getId_Pago()); List<RenglonNotaDebito> renglonesCalculados = Arrays.asList(restTemplate.getForObject(apiPrefix + "/notas/renglon/debito/pago/1?monto=100&ivaPorcentaje=21", RenglonNotaDebito[].class)); notaDebito.setRenglonesNotaDebito(renglonesCalculados); notaDebito.setIva105Neto(0); notaDebito.setIva21Neto(21); notaDebito.setMontoNoGravado(5992.5); notaDebito.setMotivo("Test alta nota debito - Cheque rechazado"); notaDebito.setSubTotalBruto(100); notaDebito.setTotal(6113.5); notaDebito.setUsuario(credencial); notaDebito.setFacturaVenta(null); NotaDebito nd = restTemplate.postForObject(apiPrefix + "/notas/debito/empresa/1/cliente/1/usuario/1/pago/1", notaDebito, NotaDebito.class); assertEquals(-6113.5, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); pago = new Pago(); pago.setEmpresa(empresa); pago.setNotaDebito(nd); pago.setFecha(new Date()); pago.setFormaDePago(formaDePago); pago.setMonto(6113.5); restTemplate.postForObject(apiPrefix + "/pagos/notas/1", pago, Pago.class); assertEquals(0, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); List<RenglonNotaCredito> renglonesNotaCredito = Arrays.asList(restTemplate.getForObject(apiPrefix + "/notas/renglon/credito/producto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&cantidad=5&idRenglonFactura=1", RenglonNotaCredito[].class)); NotaCreditoDTO notaCredito = new NotaCreditoDTO(); notaCredito.setRenglonesNotaCredito(renglonesNotaCredito); notaCredito.setFacturaVenta(facturasRecuperadas.get(0)); notaCredito.setFecha(new Date()); notaCredito.setSubTotal(restTemplate.getForObject(apiPrefix +"/notas/credito/sub-total?importe=" + renglonesNotaCredito.get(0).getImporteNeto(), Double.class)); notaCredito.setRecargoPorcentaje(facturasRecuperadas.get(0).getRecargo_porcentaje()); notaCredito.setRecargoNeto(restTemplate.getForObject(apiPrefix +"/notas/credito/recargo-neto?subTotal=" + notaCredito.getSubTotal() + "&recargoPorcentaje=" + notaCredito.getRecargoPorcentaje(), Double.class)); notaCredito.setDescuentoPorcentaje(facturasRecuperadas.get(0).getDescuento_porcentaje()); notaCredito.setDescuentoNeto(restTemplate.getForObject(apiPrefix +"/notas/credito/descuento-neto?subTotal=" + notaCredito.getSubTotal() + "&descuentoPorcentaje=" + notaCredito.getDescuentoPorcentaje(), Double.class)); notaCredito.setIva21Neto(restTemplate.getForObject(apiPrefix + "/notas/credito/iva-neto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&cantidades=" + renglonesNotaCredito.get(0).getCantidad() + "&ivaPorcentajeRenglones=" + renglonesNotaCredito.get(0).getIvaPorcentaje() + "&ivaNetoRenglones=" + renglonesNotaCredito.get(0).getIvaNeto() + "&ivaPorcentaje=21" + "&descuentoPorcentaje=" + facturasRecuperadas.get(0).getDescuento_porcentaje() + "&recargoPorcentaje=" + facturasRecuperadas.get(0).getRecargo_porcentaje(), Double.class)); notaCredito.setIva105Neto(restTemplate.getForObject(apiPrefix + "/notas/credito/iva-neto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&cantidades=" + renglonesNotaCredito.get(0).getCantidad() + "&ivaPorcentajeRenglones=" + renglonesNotaCredito.get(0).getIvaPorcentaje() + "&ivaNetoRenglones=" + renglonesNotaCredito.get(0).getIvaNeto() + "&ivaPorcentaje=10.5" + "&descuentoPorcentaje=" + facturasRecuperadas.get(0).getDescuento_porcentaje() + "&recargoPorcentaje=" + facturasRecuperadas.get(0).getRecargo_porcentaje(), Double.class)); notaCredito.setSubTotalBruto(restTemplate.getForObject(apiPrefix + "/notas/credito/sub-total-bruto?" + "tipoDeComprobante=" + facturasRecuperadas.get(0).getTipoComprobante().name() + "&subTotal=" + notaCredito.getSubTotal() + "&recargoNeto=" + notaCredito.getRecargoNeto() + "&descuentoNeto=" + notaCredito.getDescuentoNeto() + "&iva21Neto=" + notaCredito.getIva21Neto() + "&iva105Neto=" + notaCredito.getIva105Neto(), Double.class)); notaCredito.setTotal(restTemplate.getForObject(apiPrefix + "/notas/credito/total?subTotalBruto=" + notaCredito.getSubTotalBruto() + "&iva21Neto=" + notaCredito.getIva21Neto() + "&iva105Neto=" + notaCredito.getIva105Neto(), Double.class)); restTemplate.postForObject(apiPrefix + "/notas/credito/empresa/1/cliente/1/usuario/1/factura/1?modificarStock=false", notaCredito, NotaCredito.class); assertEquals(4114, restTemplate.getForObject(apiPrefix + "/cuentas-corrientes/clientes/1/saldo", Double.class), 0); } }
21,812
0.66609
0.652849
378
57.140213
34.436337
193
false
false
0
0
0
0
0
0
0.798942
false
false
2
c7bdf8a252a1e33d5ef584a3078a9e43c62d7b08
25,950,192,463,333
56e55124ae8f1df8072a6b77ec830f120a9211e9
/ngsi-ld/src/main/java/br/imd/ngsi_ld/dao/NgsiLdDao.java
29e54aa22443bba9979beb8a7830c4330255ddd3
[]
no_license
JorgePereiraUFRN/smartmetropolis-ngsi-ld
https://github.com/JorgePereiraUFRN/smartmetropolis-ngsi-ld
456af837dcd0bfdc9f6c2a634c8cc29e17931b93
9f241bfc06ff7c465a27c50d8472cb35da7e21ec
refs/heads/master
2022-11-19T03:18:53.017000
2019-06-06T10:53:01
2019-06-06T10:53:01
190,250,687
0
0
null
false
2022-11-16T09:54:11
2019-06-04T17:41:17
2019-06-06T10:53:04
2022-11-16T09:54:08
45
0
0
2
Java
false
false
package br.imd.ngsi_ld.dao; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.mongodb.BasicDBObject; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.Updates; import br.imd.ngsi_ld.exception.DaoException; import br.imd.ngsi_ld.exception.EntitySerializerException; import br.imd.ngsi_ld.exception.ObjectNullException; import br.imd.ngsi_ld.model.Entity; import br.imd.ngsi_ld.model.Property; import br.imd.ngsi_ld.model.PropertyType; import br.imd.ngsi_ld.model.Relationaship; import br.imd.ngsi_ld.util.DataTypeUtil; import br.imd.ngsi_ld.util.DateFormatUtil; import br.imd.ngsi_ld.util.EntitySerializer; import static com.mongodb.client.model.Filters.*; import static com.mongodb.client.model.Updates.*; public class NgsiLdDao implements NgsiLdDaoInterface { private static final String collectionName = "ngsi_ld"; public NgsiLdDao() { } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#save(java.lang.String, * ngsi_ld.model.Entity) */ public void save(Entity entity) throws DaoException { try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document document = Document.parse(entity.toJson()); document.put("createdAt", new Date()); document.remove("modifiedAt"); document.put("_id", entity.getId()); // document.remove("id"); collection.insertOne(document); } catch (JsonProcessingException e) { throw new DaoException(e.getMessage()); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#update(java.lang.String, * ngsi_ld.model.Entity) */ public void update(Entity entity) throws DaoException { try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document document = Document.parse(entity.toJson()); document.put("createdAt", findById(entity.getId()).getCreatedAt()); document.remove("modifiedAt"); document.put("modifiedAt", new Date()); collection.replaceOne(new Document("_id", entity.getId()), document, new UpdateOptions().upsert(true)); } catch (JsonProcessingException e) { throw new DaoException(e.getMessage()); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#findById(java.lang. * String, java.lang.String) */ public Entity findById(String id) throws DaoException { try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document document = collection.find(Filters.eq("_id", id)).first(); if (document != null) { Entity entity = new EntitySerializer().documentToEntity(document); return entity; } else { return null; } } catch (ParseException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } } public List<Entity> findByPropertyFilter(String field, String operator, String value, int limit, int offset) throws DaoException { List<Entity> ret = new ArrayList<Entity>(); try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document queryDoc = new Document(); if (DataTypeUtil.isBoolean(value)) { queryDoc.append("properties." + field, new Document("$" + operator, Boolean.parseBoolean(value))); } else if (DataTypeUtil.isDate(value)) { queryDoc.append("properties." + field, new Document("$" + operator, DateFormatUtil.parse(value))); } else if (DataTypeUtil.isInteger(value)) { queryDoc.append("properties." + field, new Document("$" + operator, Integer.parseInt(value))); } else if (DataTypeUtil.isDouble(value)) { queryDoc.append("properties." + field, new Document("$" + operator, Double.parseDouble(value))); } else { queryDoc.append("properties." + field, new Document("$" + operator, value)); } FindIterable<Document> entities = collection.find(queryDoc).skip(offset).limit(limit); MongoCursor<Document> cursor = entities.iterator(); EntitySerializer serializer = new EntitySerializer(); try { while (cursor.hasNext()) { ret.add(serializer.documentToEntity(cursor.next())); } } finally { cursor.close(); } } catch (ParseException e) { throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } return ret; } public List<Entity> findByRelationashipByFilter( String field, String operator, String value, int limit, int offset) throws DaoException { List<Entity> ret = new ArrayList<Entity>(); try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document queryDoc = new Document(); if (DataTypeUtil.isBoolean(value)) { queryDoc.append("relationaships." + field, new Document("$" + operator, Boolean.parseBoolean(value))); } else if (DataTypeUtil.isDate(value)) { queryDoc.append("relationaships." + field, new Document("$" + operator, DateFormatUtil.parse(value))); } else if (DataTypeUtil.isDouble(value)) { queryDoc.append("relationaships." + field, new Document("$" + operator, Double.parseDouble(value))); } else if (DataTypeUtil.isInteger(value)) { queryDoc.append(field, new Document("$" + operator, Integer.parseInt(value))); } else { queryDoc.append("relationaships." + field, new Document("$" + operator, value)); } FindIterable<Document> entities = collection.find(queryDoc).skip(offset).limit(limit); MongoCursor<Document> cursor = entities.iterator(); EntitySerializer serializer = new EntitySerializer(); try { while (cursor.hasNext()) { ret.add(serializer.documentToEntity(cursor.next())); } } finally { cursor.close(); } } catch (ParseException e) { throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } return ret; } public List<Entity> findAll(int limit, int offset) throws DaoException { List<Entity> ret = new ArrayList<Entity>(); try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); FindIterable<Document> entities = collection.find().limit(limit).skip(offset); MongoCursor<Document> cursor = entities.iterator(); EntitySerializer serializer = new EntitySerializer(); try { while (cursor.hasNext()) { Document document = cursor.next(); Entity entiity = serializer.documentToEntity(document); ret.add(entiity); } } finally { cursor.close(); } } catch (ParseException e) { throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } return ret; } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#delete(java.lang.String, * java.lang.String) */ public void delete( String id) throws DaoException { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); collection.deleteOne(new Document("_id", id)); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#addProperty(java.lang. * String, java.lang.String, ngsi_ld.model.Property, java.lang.String) */ public void addProperty(String entityId, Property property, String propertyId) throws DaoException { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); try { Bson filter = new Document("_id", entityId); Bson newValue; newValue = new Document("properties." + propertyId, Document.parse(property.toJsonObject().toString())); Bson updateOperationDocument = new Document("$set", newValue); collection.updateOne(filter, updateOperationDocument); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#updateProperty(java.lang * .String, java.lang.String, ngsi_ld.model.Property, java.lang.String) */ public void updateProperty(String entityId, Property property, String propertyId) throws DaoException { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); try { Bson filter = new Document("_id", entityId); Bson newValue = new Document("properties." + propertyId, Document.parse(property.toJsonObject().toString())); Bson updateOperationDocument = new Document("$set", newValue); collection.updateOne(filter, updateOperationDocument, new UpdateOptions().upsert(false)); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#removeProperty(java.lang * .String, java.lang.String, java.lang.String) */ public void removeProperty(String entityId, String propertyName) throws DaoException { /* * Entity entity = findById(collectionName, entityId); * * entity.removeProperty(propertyName); update(collectionName, entity); */ MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Bson filter = new Document("_id", entityId); Bson removedProp = new Document("properties." + propertyName, ""); Bson updateOperationDocument = new Document("$unset", removedProp); collection.updateOne(filter, updateOperationDocument); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#addRelationaship(java. * lang.String, java.lang.String, java.lang.String, * ngsi_ld.model.Relationaship) */ public void addRelationaship( String entityId, String relationashipName, Relationaship relationaship) throws DaoException { Entity entity = findById(entityId); entity.addRelationaship(relationashipName, relationaship); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#updateRelationaship(java * .lang.String, java.lang.String, java.lang.String, * ngsi_ld.model.Relationaship) */ public void updateRelationaship(String entityId, String relationashipName, Relationaship relationaship) throws DaoException { Entity entity = findById(entityId); entity.removeRelationaship(relationashipName); entity.addRelationaship(relationashipName, relationaship); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#removeRelationaship(java * .lang.String, java.lang.String, java.lang.String) */ public void removeRelationaship(String entityId, String relationashipId) throws DaoException { Entity entity = findById(entityId); entity.removeRelationaship(relationashipId); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#addContext(java.lang. * String, java.lang.String, java.lang.String) */ public void addContext( String entityId, String context) throws DaoException { Entity entity = findById(entityId); entity.addContext(context); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#removeContext(java.lang. * String, java.lang.String, java.lang.String) */ public void removeContext(String entityId, String context) throws DaoException { Entity entity = findById( entityId); entity.removeContext(context); update( entity); } public Property findProperty( String entityId, String propertyName) throws DaoException { Entity entity = findById(entityId); if (entity != null) { return entity.getProperty(propertyName); } else { return null; } } public Relationaship findRelationaship( String entityId, String relationashipName) throws DaoException { Entity entity = findById(entityId); if (entity != null) { return entity.getRelationaship(relationashipName); } else { return null; } } public List<Entity> findByDocumentQuery(JSONObject query, int limit, int offset) throws DaoException { List<Entity> entities = new ArrayList<Entity>(); try { Document queryDoc = Document.parse(query.toString()); MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); FindIterable<Document> documents = collection.find(queryDoc).limit(limit).skip(offset); for (Document doc : documents) { Entity entity = new EntitySerializer().documentToEntity(doc); entities.add(entity); } } catch (Exception e) { throw new DaoException(e.getMessage()); } return entities; } public List<Entity> findByQuery(String query, int limit, int offset) throws DaoException { List<Entity> entities = new ArrayList<Entity>(); try { query = query.replace("p*", "properties"); query = query.replace("r*", "relationaships"); String[] queries = query.split(";"); Document queryDoc = new Document(); for (String q : queries) { String[] queryTerms = q.split("\\$", 3); String field = queryTerms[0]; String operator = queryTerms[1]; String value = queryTerms[2]; if (DataTypeUtil.isBoolean(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, Boolean.parseBoolean(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, Boolean.parseBoolean(value)); } } else if (DataTypeUtil.isDate(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, DateFormatUtil.parse(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, DateFormatUtil.parse(value)); } } else if (DataTypeUtil.isDouble(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, Double.parseDouble(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, Double.parseDouble(value)); } } else if (DataTypeUtil.isInteger(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, Integer.parseInt(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, Integer.parseInt(value)); } } else { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, value)); } else { ((Document) queryDoc.get(field)).append("$" + operator, value); } } } MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); FindIterable<Document> documents = collection.find(queryDoc).limit(limit).skip(offset); for (Document doc : documents) { Entity entity = new EntitySerializer().documentToEntity(doc); entities.add(entity); } } catch (Exception e) { throw new DaoException(e.getMessage()); } return entities; } }
UTF-8
Java
16,140
java
NgsiLdDao.java
Java
[]
null
[]
package br.imd.ngsi_ld.dao; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.mongodb.BasicDBObject; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOptions; import com.mongodb.client.model.Updates; import br.imd.ngsi_ld.exception.DaoException; import br.imd.ngsi_ld.exception.EntitySerializerException; import br.imd.ngsi_ld.exception.ObjectNullException; import br.imd.ngsi_ld.model.Entity; import br.imd.ngsi_ld.model.Property; import br.imd.ngsi_ld.model.PropertyType; import br.imd.ngsi_ld.model.Relationaship; import br.imd.ngsi_ld.util.DataTypeUtil; import br.imd.ngsi_ld.util.DateFormatUtil; import br.imd.ngsi_ld.util.EntitySerializer; import static com.mongodb.client.model.Filters.*; import static com.mongodb.client.model.Updates.*; public class NgsiLdDao implements NgsiLdDaoInterface { private static final String collectionName = "ngsi_ld"; public NgsiLdDao() { } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#save(java.lang.String, * ngsi_ld.model.Entity) */ public void save(Entity entity) throws DaoException { try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document document = Document.parse(entity.toJson()); document.put("createdAt", new Date()); document.remove("modifiedAt"); document.put("_id", entity.getId()); // document.remove("id"); collection.insertOne(document); } catch (JsonProcessingException e) { throw new DaoException(e.getMessage()); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#update(java.lang.String, * ngsi_ld.model.Entity) */ public void update(Entity entity) throws DaoException { try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document document = Document.parse(entity.toJson()); document.put("createdAt", findById(entity.getId()).getCreatedAt()); document.remove("modifiedAt"); document.put("modifiedAt", new Date()); collection.replaceOne(new Document("_id", entity.getId()), document, new UpdateOptions().upsert(true)); } catch (JsonProcessingException e) { throw new DaoException(e.getMessage()); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#findById(java.lang. * String, java.lang.String) */ public Entity findById(String id) throws DaoException { try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document document = collection.find(Filters.eq("_id", id)).first(); if (document != null) { Entity entity = new EntitySerializer().documentToEntity(document); return entity; } else { return null; } } catch (ParseException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } } public List<Entity> findByPropertyFilter(String field, String operator, String value, int limit, int offset) throws DaoException { List<Entity> ret = new ArrayList<Entity>(); try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document queryDoc = new Document(); if (DataTypeUtil.isBoolean(value)) { queryDoc.append("properties." + field, new Document("$" + operator, Boolean.parseBoolean(value))); } else if (DataTypeUtil.isDate(value)) { queryDoc.append("properties." + field, new Document("$" + operator, DateFormatUtil.parse(value))); } else if (DataTypeUtil.isInteger(value)) { queryDoc.append("properties." + field, new Document("$" + operator, Integer.parseInt(value))); } else if (DataTypeUtil.isDouble(value)) { queryDoc.append("properties." + field, new Document("$" + operator, Double.parseDouble(value))); } else { queryDoc.append("properties." + field, new Document("$" + operator, value)); } FindIterable<Document> entities = collection.find(queryDoc).skip(offset).limit(limit); MongoCursor<Document> cursor = entities.iterator(); EntitySerializer serializer = new EntitySerializer(); try { while (cursor.hasNext()) { ret.add(serializer.documentToEntity(cursor.next())); } } finally { cursor.close(); } } catch (ParseException e) { throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } return ret; } public List<Entity> findByRelationashipByFilter( String field, String operator, String value, int limit, int offset) throws DaoException { List<Entity> ret = new ArrayList<Entity>(); try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Document queryDoc = new Document(); if (DataTypeUtil.isBoolean(value)) { queryDoc.append("relationaships." + field, new Document("$" + operator, Boolean.parseBoolean(value))); } else if (DataTypeUtil.isDate(value)) { queryDoc.append("relationaships." + field, new Document("$" + operator, DateFormatUtil.parse(value))); } else if (DataTypeUtil.isDouble(value)) { queryDoc.append("relationaships." + field, new Document("$" + operator, Double.parseDouble(value))); } else if (DataTypeUtil.isInteger(value)) { queryDoc.append(field, new Document("$" + operator, Integer.parseInt(value))); } else { queryDoc.append("relationaships." + field, new Document("$" + operator, value)); } FindIterable<Document> entities = collection.find(queryDoc).skip(offset).limit(limit); MongoCursor<Document> cursor = entities.iterator(); EntitySerializer serializer = new EntitySerializer(); try { while (cursor.hasNext()) { ret.add(serializer.documentToEntity(cursor.next())); } } finally { cursor.close(); } } catch (ParseException e) { throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } return ret; } public List<Entity> findAll(int limit, int offset) throws DaoException { List<Entity> ret = new ArrayList<Entity>(); try { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); FindIterable<Document> entities = collection.find().limit(limit).skip(offset); MongoCursor<Document> cursor = entities.iterator(); EntitySerializer serializer = new EntitySerializer(); try { while (cursor.hasNext()) { Document document = cursor.next(); Entity entiity = serializer.documentToEntity(document); ret.add(entiity); } } finally { cursor.close(); } } catch (ParseException e) { throw new DaoException(e.getMessage()); } catch (EntitySerializerException e) { throw new DaoException(e.getMessage()); } catch (ObjectNullException e) { e.printStackTrace(); throw new DaoException(e.getMessage()); } return ret; } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#delete(java.lang.String, * java.lang.String) */ public void delete( String id) throws DaoException { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); collection.deleteOne(new Document("_id", id)); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#addProperty(java.lang. * String, java.lang.String, ngsi_ld.model.Property, java.lang.String) */ public void addProperty(String entityId, Property property, String propertyId) throws DaoException { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); try { Bson filter = new Document("_id", entityId); Bson newValue; newValue = new Document("properties." + propertyId, Document.parse(property.toJsonObject().toString())); Bson updateOperationDocument = new Document("$set", newValue); collection.updateOne(filter, updateOperationDocument); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#updateProperty(java.lang * .String, java.lang.String, ngsi_ld.model.Property, java.lang.String) */ public void updateProperty(String entityId, Property property, String propertyId) throws DaoException { MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); try { Bson filter = new Document("_id", entityId); Bson newValue = new Document("properties." + propertyId, Document.parse(property.toJsonObject().toString())); Bson updateOperationDocument = new Document("$set", newValue); collection.updateOne(filter, updateOperationDocument, new UpdateOptions().upsert(false)); } catch (JSONException e) { throw new DaoException(e.getMessage()); } } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#removeProperty(java.lang * .String, java.lang.String, java.lang.String) */ public void removeProperty(String entityId, String propertyName) throws DaoException { /* * Entity entity = findById(collectionName, entityId); * * entity.removeProperty(propertyName); update(collectionName, entity); */ MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); Bson filter = new Document("_id", entityId); Bson removedProp = new Document("properties." + propertyName, ""); Bson updateOperationDocument = new Document("$unset", removedProp); collection.updateOne(filter, updateOperationDocument); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#addRelationaship(java. * lang.String, java.lang.String, java.lang.String, * ngsi_ld.model.Relationaship) */ public void addRelationaship( String entityId, String relationashipName, Relationaship relationaship) throws DaoException { Entity entity = findById(entityId); entity.addRelationaship(relationashipName, relationaship); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#updateRelationaship(java * .lang.String, java.lang.String, java.lang.String, * ngsi_ld.model.Relationaship) */ public void updateRelationaship(String entityId, String relationashipName, Relationaship relationaship) throws DaoException { Entity entity = findById(entityId); entity.removeRelationaship(relationashipName); entity.addRelationaship(relationashipName, relationaship); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#removeRelationaship(java * .lang.String, java.lang.String, java.lang.String) */ public void removeRelationaship(String entityId, String relationashipId) throws DaoException { Entity entity = findById(entityId); entity.removeRelationaship(relationashipId); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#addContext(java.lang. * String, java.lang.String, java.lang.String) */ public void addContext( String entityId, String context) throws DaoException { Entity entity = findById(entityId); entity.addContext(context); update(entity); } /* * (non-Javadoc) * * @see * br.imd.sgeol.datasource.mongo.NgsiLdDaoInterface#removeContext(java.lang. * String, java.lang.String, java.lang.String) */ public void removeContext(String entityId, String context) throws DaoException { Entity entity = findById( entityId); entity.removeContext(context); update( entity); } public Property findProperty( String entityId, String propertyName) throws DaoException { Entity entity = findById(entityId); if (entity != null) { return entity.getProperty(propertyName); } else { return null; } } public Relationaship findRelationaship( String entityId, String relationashipName) throws DaoException { Entity entity = findById(entityId); if (entity != null) { return entity.getRelationaship(relationashipName); } else { return null; } } public List<Entity> findByDocumentQuery(JSONObject query, int limit, int offset) throws DaoException { List<Entity> entities = new ArrayList<Entity>(); try { Document queryDoc = Document.parse(query.toString()); MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); FindIterable<Document> documents = collection.find(queryDoc).limit(limit).skip(offset); for (Document doc : documents) { Entity entity = new EntitySerializer().documentToEntity(doc); entities.add(entity); } } catch (Exception e) { throw new DaoException(e.getMessage()); } return entities; } public List<Entity> findByQuery(String query, int limit, int offset) throws DaoException { List<Entity> entities = new ArrayList<Entity>(); try { query = query.replace("p*", "properties"); query = query.replace("r*", "relationaships"); String[] queries = query.split(";"); Document queryDoc = new Document(); for (String q : queries) { String[] queryTerms = q.split("\\$", 3); String field = queryTerms[0]; String operator = queryTerms[1]; String value = queryTerms[2]; if (DataTypeUtil.isBoolean(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, Boolean.parseBoolean(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, Boolean.parseBoolean(value)); } } else if (DataTypeUtil.isDate(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, DateFormatUtil.parse(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, DateFormatUtil.parse(value)); } } else if (DataTypeUtil.isDouble(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, Double.parseDouble(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, Double.parseDouble(value)); } } else if (DataTypeUtil.isInteger(value)) { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, Integer.parseInt(value))); } else { ((Document) queryDoc.get(field)).append("$" + operator, Integer.parseInt(value)); } } else { if (queryDoc.get(field) == null) { queryDoc.append(field, new Document("$" + operator, value)); } else { ((Document) queryDoc.get(field)).append("$" + operator, value); } } } MongoCollection<Document> collection = MongoConnection.getInstance().getCollection(collectionName); FindIterable<Document> documents = collection.find(queryDoc).limit(limit).skip(offset); for (Document doc : documents) { Entity entity = new EntitySerializer().documentToEntity(doc); entities.add(entity); } } catch (Exception e) { throw new DaoException(e.getMessage()); } return entities; } }
16,140
0.707311
0.707063
565
27.566372
29.69809
107
false
false
0
0
0
0
0
0
2.237168
false
false
2
b47cd008641e0449c34623439b317dc7e95ed6d7
29,377,576,332,610
9e924d12840ef51e75503da3d3b585fc26aa8659
/study_code/src/before/Solution03Number.java
7b3562c2abfa79459de75927236b7c09dc19bcc1
[]
no_license
ShinDohee/Study_algorithm
https://github.com/ShinDohee/Study_algorithm
219767b259a71ff9e2f90934dbf82b17d8494ac0
fe034c7eb6cea33b68b44156bc8ee76a310218f8
refs/heads/master
2021-09-09T13:17:07.590000
2021-09-01T07:21:03
2021-09-01T07:21:03
156,315,026
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package before; import java.util.Scanner; public class Solution03Number { static int Answer; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int test_case = 0; test_case < T; test_case++) { Answer = 0; // 몇번째를 구할건지 int N = sc.nextInt(); int x = 0; if (N % 2 == 1) { x = 4; } else { x = 7; } for (int i = (N - 1) / 2; i > -1; i--) { Answer += x * Math.pow(10, i); } System.out.println("Case #" + (test_case + 1)); System.out.println(Answer); } } }
UTF-8
Java
777
java
Solution03Number.java
Java
[]
null
[]
package before; import java.util.Scanner; public class Solution03Number { static int Answer; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int test_case = 0; test_case < T; test_case++) { Answer = 0; // 몇번째를 구할건지 int N = sc.nextInt(); int x = 0; if (N % 2 == 1) { x = 4; } else { x = 7; } for (int i = (N - 1) / 2; i > -1; i--) { Answer += x * Math.pow(10, i); } System.out.println("Case #" + (test_case + 1)); System.out.println(Answer); } } }
777
0.400788
0.381078
29
24.241379
17.460606
61
false
false
0
0
0
0
0
0
0.62069
false
false
2
fbd8efc3cbf6b2edb43389b2dcde7b82b9f1c823
23,819,888,639,604
85cae10ac5cf1a3dfe3bfa1871b613ef7ca7fc7c
/app/src/main/java/com/moviee/moviee/models/Scores.java
24a82b38774f733ba120902a2952f49f3f30f3e3
[ "Apache-2.0" ]
permissive
Marplex/solid-garbanzo
https://github.com/Marplex/solid-garbanzo
7105a49e19292b5a6e0c149835428156607e5508
049cdaf5d2f4ede83d7769157d7406a8e3ec0959
refs/heads/master
2019-08-08T06:38:02.938000
2016-09-12T12:54:17
2016-09-12T12:54:17
64,468,360
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.moviee.moviee.models; /** * Created by Thomas on 07/08/2016. */ public class Scores { public String imdb, meta; public Scores(String imdb, String meta) { this.imdb = imdb; this.meta = meta; } }
UTF-8
Java
241
java
Scores.java
Java
[ { "context": "ckage com.moviee.moviee.models;\n\n/**\n * Created by Thomas on 07/08/2016.\n */\npublic class Scores {\n\n pub", "end": 59, "score": 0.9285635948181152, "start": 53, "tag": "NAME", "value": "Thomas" } ]
null
[]
package com.moviee.moviee.models; /** * Created by Thomas on 07/08/2016. */ public class Scores { public String imdb, meta; public Scores(String imdb, String meta) { this.imdb = imdb; this.meta = meta; } }
241
0.605809
0.572614
16
14.0625
15.311224
45
false
false
0
0
0
0
0
0
0.375
false
false
2
8e59b3532e7f6756b45d01791e2112b689c63c5c
25,340,307,053,616
1873b7338fa2759b2a457850a11c8ee26bc535cb
/changgou-service-api/changgou-service-content-api/src/main/java/changgou/content/api/ContentCategoryFeign.java
f4863ce2f04b220cc0c4f5a82e0711845d13b788
[]
no_license
ab8846254/changgou_parent
https://github.com/ab8846254/changgou_parent
96fe9d44261fd724cb051d8246228419b45c2605
a2437c3a6b4fbbd384a6caf288719b868dd56a5a
refs/heads/master
2022-06-28T00:37:50.771000
2020-01-14T06:19:47
2020-01-14T06:19:47
231,924,813
1
0
null
false
2022-06-17T02:47:23
2020-01-05T13:53:56
2020-01-14T06:20:21
2022-06-17T02:47:23
19,495
1
0
1
JavaScript
false
false
package changgou.content.api; import changgou.content.pojo.ContentCategory; import entity.Result; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; /**** * @Author:传智播客 * @Description: * @Date 2019/6/14 0:18 *****/ @RequestMapping("/contentCategory") public interface ContentCategoryFeign { /*** * 根据ID查询ContentCategory数据 * @param id * @return */ @GetMapping("/{id}") public Result<ContentCategory> findById(@PathVariable("id") Long id); /*** * 查询ContentCategory全部数据 * @return */ @GetMapping public Result<List<ContentCategory>> findAll(); }
UTF-8
Java
803
java
ContentCategoryFeign.java
Java
[ { "context": "apping;\n\nimport java.util.List;\n\n/****\n * @Author:传智播客\n * @Description:\n * @Date 2019/6/14 0:18\n *****/\n", "end": 329, "score": 0.9297749400138855, "start": 325, "tag": "USERNAME", "value": "传智播客" } ]
null
[]
package changgou.content.api; import changgou.content.pojo.ContentCategory; import entity.Result; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; /**** * @Author:传智播客 * @Description: * @Date 2019/6/14 0:18 *****/ @RequestMapping("/contentCategory") public interface ContentCategoryFeign { /*** * 根据ID查询ContentCategory数据 * @param id * @return */ @GetMapping("/{id}") public Result<ContentCategory> findById(@PathVariable("id") Long id); /*** * 查询ContentCategory全部数据 * @return */ @GetMapping public Result<List<ContentCategory>> findAll(); }
803
0.696498
0.683528
35
21.028572
20.264658
73
false
false
0
0
0
0
0
0
0.257143
false
false
2
4c4f398b7c74719ee5982e82eae8c6640ae0af34
25,615,184,959,481
5bc9d8f92f38967cc9ecc03000c0606dbbb38f74
/sca4j/modules/tags/sca4j-modules-parent-pom-0.1.0/runtime/maven/sca4j-maven-host/src/main/java/org/sca4j/maven/MavenArchiveStore.java
cf00de93817f4314ce396e5bc4b7ab7a79d3a1d0
[]
no_license
codehaus/service-conduit
https://github.com/codehaus/service-conduit
795332fad474e12463db22c5e57ddd7cd6e2956e
4687d4cfc16f7a863ced69ce9ca81c6db3adb6d2
refs/heads/master
2023-07-20T00:35:11.240000
2011-08-24T22:13:28
2011-08-24T22:13:28
36,342,601
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * SCA4J * Copyright (c) 2008-2012 Service Symphony Limited * * This proprietary software may be used only in connection with the SCA4J license * (the ?License?), a copy of which is included in the software or may be obtained * at: http://www.servicesymphony.com/licenses/license.html. * * Software distributed under the License is distributed on an as is basis, without * warranties or conditions of any kind. See the License for the specific language * governing permissions and limitations of use of the software. This software is * distributed in conjunction with other software licensed under different terms. * See the separate licenses for those programs included in the distribution for the * permitted and restricted uses of such software. * */ package org.sca4j.maven; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.List; import org.osoa.sca.annotations.Destroy; import org.osoa.sca.annotations.EagerInit; import org.osoa.sca.annotations.Init; import org.osoa.sca.annotations.Property; import org.sca4j.spi.services.archive.ArchiveStore; import org.sca4j.spi.services.archive.ArchiveStoreException; /** * An archive store that delegates to a set of local and remote Maven repositories. * * @version $Rev: 2986 $ $Date: 2008-03-02 18:36:52 +0000 (Sun, 02 Mar 2008) $ */ @EagerInit public class MavenArchiveStore implements ArchiveStore { private static final String DEFAULT_REPO = "http://repo1.maven.org/maven2/"; private String remoteRepositories = DEFAULT_REPO; private MavenHelper helper; @Property(required = false) public void setRemoteRepositories(String remoteRepositories) { this.remoteRepositories = remoteRepositories; } @Init public void init() { helper = new MavenHelper(remoteRepositories, true); helper.start(); } @Destroy public void destroy() { helper.stop(); } public URL store(URI uri, InputStream stream) throws ArchiveStoreException { return find(uri); } public URL store(URI contributionUri, URL sourceURL) throws ArchiveStoreException { return find(contributionUri); } public URL find(URI uri) throws ArchiveStoreException { // assume uri is in the form 'group id:artifact id: version' String[] parsed = uri.toString().split(":"); Artifact artifact = new Artifact(); artifact.setGroup(parsed[0]); artifact.setName(parsed[1]); artifact.setVersion(parsed[2]); artifact.setType("jar"); try { if (!helper.resolveTransitively(artifact)) { return null; } } catch (SCA4JDependencyException e) { String id = uri.toString(); throw new ArchiveStoreException("Error finding archive: " + id, id, e); } return artifact.getUrl(); } public void remove(URI uri) { throw new UnsupportedOperationException(); } public List<URI> list() { throw new UnsupportedOperationException(); } }
UTF-8
Java
3,084
java
MavenArchiveStore.java
Java
[]
null
[]
/* * SCA4J * Copyright (c) 2008-2012 Service Symphony Limited * * This proprietary software may be used only in connection with the SCA4J license * (the ?License?), a copy of which is included in the software or may be obtained * at: http://www.servicesymphony.com/licenses/license.html. * * Software distributed under the License is distributed on an as is basis, without * warranties or conditions of any kind. See the License for the specific language * governing permissions and limitations of use of the software. This software is * distributed in conjunction with other software licensed under different terms. * See the separate licenses for those programs included in the distribution for the * permitted and restricted uses of such software. * */ package org.sca4j.maven; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.List; import org.osoa.sca.annotations.Destroy; import org.osoa.sca.annotations.EagerInit; import org.osoa.sca.annotations.Init; import org.osoa.sca.annotations.Property; import org.sca4j.spi.services.archive.ArchiveStore; import org.sca4j.spi.services.archive.ArchiveStoreException; /** * An archive store that delegates to a set of local and remote Maven repositories. * * @version $Rev: 2986 $ $Date: 2008-03-02 18:36:52 +0000 (Sun, 02 Mar 2008) $ */ @EagerInit public class MavenArchiveStore implements ArchiveStore { private static final String DEFAULT_REPO = "http://repo1.maven.org/maven2/"; private String remoteRepositories = DEFAULT_REPO; private MavenHelper helper; @Property(required = false) public void setRemoteRepositories(String remoteRepositories) { this.remoteRepositories = remoteRepositories; } @Init public void init() { helper = new MavenHelper(remoteRepositories, true); helper.start(); } @Destroy public void destroy() { helper.stop(); } public URL store(URI uri, InputStream stream) throws ArchiveStoreException { return find(uri); } public URL store(URI contributionUri, URL sourceURL) throws ArchiveStoreException { return find(contributionUri); } public URL find(URI uri) throws ArchiveStoreException { // assume uri is in the form 'group id:artifact id: version' String[] parsed = uri.toString().split(":"); Artifact artifact = new Artifact(); artifact.setGroup(parsed[0]); artifact.setName(parsed[1]); artifact.setVersion(parsed[2]); artifact.setType("jar"); try { if (!helper.resolveTransitively(artifact)) { return null; } } catch (SCA4JDependencyException e) { String id = uri.toString(); throw new ArchiveStoreException("Error finding archive: " + id, id, e); } return artifact.getUrl(); } public void remove(URI uri) { throw new UnsupportedOperationException(); } public List<URI> list() { throw new UnsupportedOperationException(); } }
3,084
0.689689
0.674449
95
31.463158
28.249941
87
false
false
0
0
0
0
0
0
0.421053
false
false
2
df634229ed35a88fd662fc2f629a8053d6ecba96
29,746,943,501,019
82a1d5f03400db8d0d073d2a19f0866eaad7d9a2
/cep/src/main/java/upm/pfc/cep/Processer.java
f5bc1022ab750a7fff3f56bc343c2ae552b6d68b
[]
no_license
erobert-c/PFC
https://github.com/erobert-c/PFC
5145604db5a58b26ecaf08205b8ef288924451dd
a534d9d93e9501e58ecbc25dc59a0b3f3bbd2ebd
refs/heads/master
2020-02-07T04:12:32.924000
2013-06-24T08:56:18
2013-06-24T08:56:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package upm.pfc.cep; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import upm.pfc.cep.esper.EsperProcessing; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; /** * Main class for the CEP part of the application. Creates the thread {@link upm.pfc.cep.esper.EsperProcessing EsperProcessing} that will grab the tweets sent to RabbitMQ and processed them before sending them to the client. To know which processing should be done, the program listen to a RabbitMQ fanout called <em>user_hashtag</em> where the clients will publish their hashtags. * @author Eric ROBERT <eric.robert@insa-lyon.fr> */ public class Processer { /** * Log4j Logger */ private static final Logger LOGGER = Logger.getLogger(Processer.class.getClass()); /** * Exchange name for user hashtag */ private static final String USER_HASHTAG_FANOUT = "user_hashtag"; /** * The list of existing programs */ private static Map<String, Integer> programs = new HashMap<String, Integer>(); /** * RabbitMQ connection factory */ private static ConnectionFactory factory; /** * RabbitMQ connection */ private static Connection connection; /** * RabbitMQ channel */ private static Channel channel; /** * RabbitMQ consumer */ private static QueueingConsumer consumer; /** * Esper processor object * @uml.property name="esperProcessor" * @uml.associationEnd */ private static EsperProcessing esperProcessor; /** * Launches this application. If arguments are provided, they won't be used anyway. * * @param args Arguments used */ public static void main( String[] args ) { try{ configureRabbitMQ(); } catch (IOException brokerError){ LOGGER.fatal("Error while configuring RabbitMQ", brokerError); System.exit(-1); } try{ esperProcessor = new EsperProcessing(); } catch (IOException esperError){ LOGGER.fatal("Error while creating Esper processor", esperError); System.exit(-1); } Thread processing = new Thread(esperProcessor); processing.start(); String hashtag; LOGGER.debug("Waiting for new hashtags"); while (true){ try{ QueueingConsumer.Delivery delivery = consumer.nextDelivery(); hashtag = new String(delivery.getBody()); LOGGER.debug("New hashtag received: " + hashtag); if ("[ABORT ALL]".equals(hashtag)) break; if (hashtag.matches(".*ABORT.*")) abortListening(hashtag); else if (!programs.containsKey(hashtag)){ esperProcessor.addStatement(hashtag); programs.put(hashtag, 1); LOGGER.debug("Number of clients for " + hashtag + ": " + programs.get(hashtag)); } else{ programs.put(hashtag, programs.get(hashtag) + 1); LOGGER.debug("Number of clients for " + hashtag + ": " + programs.get(hashtag)); } } catch (InterruptedException error){ LOGGER.fatal("RabbitMQ interrupted error", error); break; } } // If there is an error with RabbitMQ we stop all the Esper processing for (Map.Entry<String, Integer> client : programs.entrySet()){ esperProcessor.removeStatement(client.getKey()); } try{ channel.close(); connection.close(); } catch (IOException closingError){ LOGGER.error("Error while closing RabbitMQ connection", closingError); System.exit(-1); } return; } /** * Configures RabbitMQ Connection for subscribing to the user published hashtags. * * @throws IOException */ private static void configureRabbitMQ() throws IOException{ factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(USER_HASHTAG_FANOUT, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, USER_HASHTAG_FANOUT, ""); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); LOGGER.debug("RabbitMQ connection created"); } /** * Checks if an unsubscribe message is correct and corresponds to one of the existing * subscription. If so, stop the esper processing for this hashtag. * @param cmd */ private static void abortListening(String cmd){ String statement = cmd.substring("[ABORT ".length()); if (']' == statement.charAt(statement.length() - 1)) statement = statement.substring(0, statement.length() - 1); if (programs.containsKey(statement)){ programs.put(statement, programs.get(statement) - 1); int numberClient = programs.get(statement); LOGGER.debug("Number of client for " + statement + ": " + numberClient); if (numberClient == 0){ programs.remove(statement); esperProcessor.removeStatement(statement); } } } }
UTF-8
Java
5,271
java
Processer.java
Java
[ { "context": " clients will publish their hashtags. \n * @author Eric ROBERT <eric.robert@insa-lyon.fr>\n */\npublic class Proce", "end": 756, "score": 0.9998490810394287, "start": 745, "tag": "NAME", "value": "Eric ROBERT" }, { "context": "publish their hashtags. \n * @author Eric ROBERT <eric.robert@insa-lyon.fr>\n */\npublic class Processer \n{\n\t/**\n\t * Log4j Log", "end": 782, "score": 0.9999256134033203, "start": 758, "tag": "EMAIL", "value": "eric.robert@insa-lyon.fr" } ]
null
[]
package upm.pfc.cep; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import upm.pfc.cep.esper.EsperProcessing; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; /** * Main class for the CEP part of the application. Creates the thread {@link upm.pfc.cep.esper.EsperProcessing EsperProcessing} that will grab the tweets sent to RabbitMQ and processed them before sending them to the client. To know which processing should be done, the program listen to a RabbitMQ fanout called <em>user_hashtag</em> where the clients will publish their hashtags. * @author <NAME> <<EMAIL>> */ public class Processer { /** * Log4j Logger */ private static final Logger LOGGER = Logger.getLogger(Processer.class.getClass()); /** * Exchange name for user hashtag */ private static final String USER_HASHTAG_FANOUT = "user_hashtag"; /** * The list of existing programs */ private static Map<String, Integer> programs = new HashMap<String, Integer>(); /** * RabbitMQ connection factory */ private static ConnectionFactory factory; /** * RabbitMQ connection */ private static Connection connection; /** * RabbitMQ channel */ private static Channel channel; /** * RabbitMQ consumer */ private static QueueingConsumer consumer; /** * Esper processor object * @uml.property name="esperProcessor" * @uml.associationEnd */ private static EsperProcessing esperProcessor; /** * Launches this application. If arguments are provided, they won't be used anyway. * * @param args Arguments used */ public static void main( String[] args ) { try{ configureRabbitMQ(); } catch (IOException brokerError){ LOGGER.fatal("Error while configuring RabbitMQ", brokerError); System.exit(-1); } try{ esperProcessor = new EsperProcessing(); } catch (IOException esperError){ LOGGER.fatal("Error while creating Esper processor", esperError); System.exit(-1); } Thread processing = new Thread(esperProcessor); processing.start(); String hashtag; LOGGER.debug("Waiting for new hashtags"); while (true){ try{ QueueingConsumer.Delivery delivery = consumer.nextDelivery(); hashtag = new String(delivery.getBody()); LOGGER.debug("New hashtag received: " + hashtag); if ("[ABORT ALL]".equals(hashtag)) break; if (hashtag.matches(".*ABORT.*")) abortListening(hashtag); else if (!programs.containsKey(hashtag)){ esperProcessor.addStatement(hashtag); programs.put(hashtag, 1); LOGGER.debug("Number of clients for " + hashtag + ": " + programs.get(hashtag)); } else{ programs.put(hashtag, programs.get(hashtag) + 1); LOGGER.debug("Number of clients for " + hashtag + ": " + programs.get(hashtag)); } } catch (InterruptedException error){ LOGGER.fatal("RabbitMQ interrupted error", error); break; } } // If there is an error with RabbitMQ we stop all the Esper processing for (Map.Entry<String, Integer> client : programs.entrySet()){ esperProcessor.removeStatement(client.getKey()); } try{ channel.close(); connection.close(); } catch (IOException closingError){ LOGGER.error("Error while closing RabbitMQ connection", closingError); System.exit(-1); } return; } /** * Configures RabbitMQ Connection for subscribing to the user published hashtags. * * @throws IOException */ private static void configureRabbitMQ() throws IOException{ factory = new ConnectionFactory(); factory.setHost("localhost"); connection = factory.newConnection(); channel = connection.createChannel(); channel.exchangeDeclare(USER_HASHTAG_FANOUT, "fanout"); String queueName = channel.queueDeclare().getQueue(); channel.queueBind(queueName, USER_HASHTAG_FANOUT, ""); consumer = new QueueingConsumer(channel); channel.basicConsume(queueName, true, consumer); LOGGER.debug("RabbitMQ connection created"); } /** * Checks if an unsubscribe message is correct and corresponds to one of the existing * subscription. If so, stop the esper processing for this hashtag. * @param cmd */ private static void abortListening(String cmd){ String statement = cmd.substring("[ABORT ".length()); if (']' == statement.charAt(statement.length() - 1)) statement = statement.substring(0, statement.length() - 1); if (programs.containsKey(statement)){ programs.put(statement, programs.get(statement) - 1); int numberClient = programs.get(statement); LOGGER.debug("Number of client for " + statement + ": " + numberClient); if (numberClient == 0){ programs.remove(statement); esperProcessor.removeStatement(statement); } } } }
5,249
0.651489
0.649213
174
29.293104
36.678478
386
false
false
0
0
0
0
0
0
1.58046
false
false
2
b83cb6271810202065a88d6dc0f4f5cf4f9f1e69
14,843,406,987,907
933bd826f9243a9a161d8119e133e9bd28d40c5c
/Proyecto_Java/EmpleoDigital/src/main/java/controllers/ListarFormacion.java
8737f60eb188f6cd7feed7f3cbe983002f3b5f5c
[]
no_license
nojiro15/Java-Toletvm
https://github.com/nojiro15/Java-Toletvm
cf41b969218e0c351ee04f8ab9d3e256a8e7a9fe
5cd3c03cb186b99b34364b01f79f87541204b8af
refs/heads/master
2021-01-23T00:25:30.304000
2017-06-17T21:38:26
2017-06-17T21:38:26
92,811,974
0
5
null
false
2017-06-17T21:38:26
2017-05-30T08:19:10
2017-05-30T11:23:47
2017-06-17T21:38:26
12,487
0
4
0
Java
null
null
package controllers; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import dao.DAOFormacion; import modelos.Formacion; import utils.Calendario; @Controller public class ListarFormacion { @Autowired DAOFormacion daof; @Autowired ApplicationContext ctx; /** * Este método enviará a la vista los tres diferentes listados de formaciones. * Una lista será la completa, otra la del listado de finalizados, y otro la de en curso. * @param sesion * @return */ @RequestMapping(value = {"VCIndex"}) public ModelAndView listado(HttpSession sesion){ ModelAndView mv = new ModelAndView("VListados"); //Fecha actual Date fechaD = new Date(); int fecha = (int)fechaD.getTime(); List<Formacion> listaCompleta = daof.listar(); List<Formacion> listaFinalizados = new ArrayList<Formacion>(); List<Formacion> listaEnCurso = new ArrayList<Formacion>(); //Recorremos todas las fechas mirando si están o no finalizados Calendario objetoCal = new Calendario(ctx); for(Formacion formacion:listaCompleta){ if (fechaD.compareTo(objetoCal.getFechaFin(formacion)) > 0){ System.out.println(formacion); listaFinalizados.add(formacion); }else{ listaEnCurso.add(formacion); } } //Enviamos a la vista todas las listas para mostrarlas en su correspondiente sesion mv.addObject("listaCompleta", listaCompleta); mv.addObject("listaFinalizados", listaFinalizados); mv.addObject("listaEnCurso", listaEnCurso); return mv; } }
ISO-8859-2
Java
1,937
java
ListarFormacion.java
Java
[]
null
[]
package controllers; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import dao.DAOFormacion; import modelos.Formacion; import utils.Calendario; @Controller public class ListarFormacion { @Autowired DAOFormacion daof; @Autowired ApplicationContext ctx; /** * Este método enviará a la vista los tres diferentes listados de formaciones. * Una lista será la completa, otra la del listado de finalizados, y otro la de en curso. * @param sesion * @return */ @RequestMapping(value = {"VCIndex"}) public ModelAndView listado(HttpSession sesion){ ModelAndView mv = new ModelAndView("VListados"); //Fecha actual Date fechaD = new Date(); int fecha = (int)fechaD.getTime(); List<Formacion> listaCompleta = daof.listar(); List<Formacion> listaFinalizados = new ArrayList<Formacion>(); List<Formacion> listaEnCurso = new ArrayList<Formacion>(); //Recorremos todas las fechas mirando si están o no finalizados Calendario objetoCal = new Calendario(ctx); for(Formacion formacion:listaCompleta){ if (fechaD.compareTo(objetoCal.getFechaFin(formacion)) > 0){ System.out.println(formacion); listaFinalizados.add(formacion); }else{ listaEnCurso.add(formacion); } } //Enviamos a la vista todas las listas para mostrarlas en su correspondiente sesion mv.addObject("listaCompleta", listaCompleta); mv.addObject("listaFinalizados", listaFinalizados); mv.addObject("listaEnCurso", listaEnCurso); return mv; } }
1,937
0.720124
0.719607
68
26.42647
24.294344
90
false
false
0
0
0
0
0
0
2.014706
false
false
2
c4cc8a49470e3b81f54d70b215dc0612e7437cf0
11,295,764,001,750
ead42582173e22dc958d9ae74cfce6e819be39cb
/src/cleonproject.deliverables.architecture.model.architecture/src/cleon.testingmethods.hermes.metamodel/src-gen/cleon/testingmethods/hermes/metamodel/spec/_01_concept/test_goals/javamodel/ITestGoals.java
756fab40a41de6087ce29f135d2f97d610f1d4ef
[]
no_license
marcozwyssig/cleon
https://github.com/marcozwyssig/cleon
6c66c6f55625f07a22c7e59b3f4989fa93aad324
1318b835dd584f11b51de41ad0ac10a3584bbb47
refs/heads/master
2023-08-05T15:14:30.350000
2023-07-28T13:45:42
2023-07-28T13:45:42
17,729,102
0
4
null
false
2016-03-10T15:57:31
2014-03-13T23:09:40
2016-01-14T06:11:05
2016-03-10T15:56:39
93,886
0
2
0
Java
null
null
package cleon.testingmethods.hermes.metamodel.spec._01_concept.test_goals.javamodel; import ch.actifsource.util.collection.IMultiMapOrdered; public interface ITestGoals extends cleon.testingmethods.hermes.metamodel.spec._01_concept.javamodel.IAbstractTestingChapter { public static final ch.actifsource.core.INode TYPE_ID = new ch.actifsource.core.Resource("6b104a80-d406-11e5-8556-8f55ceb91287"); // relations public java.util.List<? extends cleon.testingmethods.hermes.metamodel.spec._01_concept.test_goals.javamodel.ITestGoal> selectTestGoals(); } /* Actifsource ID=[3ca9f967-db37-11de-82b8-17be2e034a3b,6b104a80-d406-11e5-8556-8f55ceb91287,UQyyAm3cntqLW6Xh/HRTwxrni9I=] */
UTF-8
Java
711
java
ITestGoals.java
Java
[]
null
[]
package cleon.testingmethods.hermes.metamodel.spec._01_concept.test_goals.javamodel; import ch.actifsource.util.collection.IMultiMapOrdered; public interface ITestGoals extends cleon.testingmethods.hermes.metamodel.spec._01_concept.javamodel.IAbstractTestingChapter { public static final ch.actifsource.core.INode TYPE_ID = new ch.actifsource.core.Resource("6b104a80-d406-11e5-8556-8f55ceb91287"); // relations public java.util.List<? extends cleon.testingmethods.hermes.metamodel.spec._01_concept.test_goals.javamodel.ITestGoal> selectTestGoals(); } /* Actifsource ID=[3ca9f967-db37-11de-82b8-17be2e034a3b,6b104a80-d406-11e5-8556-8f55ceb91287,UQyyAm3cntqLW6Xh/HRTwxrni9I=] */
711
0.791842
0.684951
15
45.400002
56.187542
139
false
false
0
0
0
0
0
0
0.4
false
false
2
219c91b9031a2a5c3fd0d05c8575b27222bd0421
33,560,874,460,948
36fd54c4b201ab3c04ed9c2ed55b3eed892bd6a5
/common/src/test/java/com/ericsson/bss/cassandra/ecaudit/common/chronicle/TestWriteReadVersionCurrent.java
1c26364e6d2270737afea06e1fcde805d9de3063
[ "Apache-2.0", "MIT" ]
permissive
Ericsson/ecaudit
https://github.com/Ericsson/ecaudit
d7bda842bd08a35d1b1cf5ee60708c238b386f8b
c0c4c3b018db5a210b64a778587686dc042351a2
refs/heads/release/c3.11
2023-08-07T00:49:10.853000
2023-05-16T08:26:38
2023-05-16T08:26:38
145,960,323
50
43
Apache-2.0
false
2023-07-24T08:21:34
2018-08-24T07:49:45
2023-05-19T04:20:03
2023-07-06T23:51:35
1,859
38
34
23
Java
false
false
/* * Copyright 2019 Telefonaktiebolaget LM Ericsson * * 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.ericsson.bss.cassandra.ecaudit.common.chronicle; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.ericsson.bss.cassandra.ecaudit.common.record.AuditRecord; import com.ericsson.bss.cassandra.ecaudit.common.record.SimpleAuditOperation; import com.ericsson.bss.cassandra.ecaudit.common.record.SimpleAuditRecord; import com.ericsson.bss.cassandra.ecaudit.common.record.Status; import com.ericsson.bss.cassandra.ecaudit.common.record.StoredAuditRecord; import net.openhft.chronicle.core.io.IORuntimeException; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.queue.ChronicleQueueBuilder; import net.openhft.chronicle.queue.ExcerptAppender; import net.openhft.chronicle.queue.ExcerptTailer; import net.openhft.chronicle.wire.WriteMarshallable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class TestWriteReadVersionCurrent { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private ChronicleQueue chronicleQueue; @Before public void before() { chronicleQueue = ChronicleQueueBuilder.single(temporaryFolder.getRoot()).blockSize(1024).build(); } @After public void after() { chronicleQueue.close(); } @Test public void writeReadSubject() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().withSubject("bob-the-subject").build(); FieldSelector fieldsWithSubject = FieldSelector.DEFAULT_FIELDS.withField(FieldSelector.Field.SUBJECT); writeAuditRecordToChronicle(expectedAuditRecord, fieldsWithSubject); StoredAuditRecord actualAuditRecord = readAuditRecordFromChronicle(); assertThatRecordsMatch(actualAuditRecord, expectedAuditRecord); } @Test public void writeReadBatch() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().withBatchId(UUID.randomUUID()).build(); writeAuditRecordToChronicle(expectedAuditRecord); StoredAuditRecord actualAuditRecord = readAuditRecordFromChronicle(); assertThatRecordsMatch(actualAuditRecord, expectedAuditRecord); } @Test public void writeReadSingle() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().withStatus(Status.FAILED).build(); writeAuditRecordToChronicle(expectedAuditRecord); StoredAuditRecord actualAuditRecord = readAuditRecordFromChronicle(); assertThatRecordsMatch(actualAuditRecord, expectedAuditRecord); } @Test public void tryReuseOnRead() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().build(); writeAuditRecordToChronicle(expectedAuditRecord); writeAuditRecordToChronicle(expectedAuditRecord); AuditRecordReadMarshallable readMarshallable = new AuditRecordReadMarshallable(); ExcerptTailer tailer = chronicleQueue.createTailer(); tailer.readDocument(readMarshallable); assertThatExceptionOfType(IORuntimeException.class) .isThrownBy(() -> tailer.readDocument(readMarshallable)) .withMessage("Tried to read from wire with used marshallable"); } private SimpleAuditRecord.Builder likeGenericRecord() throws UnknownHostException { return SimpleAuditRecord .builder() .withClientAddress(new InetSocketAddress(InetAddress.getByName("0.1.2.3"), 876)) .withCoordinatorAddress(InetAddress.getByName("4.5.6.7")) .withStatus(Status.ATTEMPT) .withOperation(new SimpleAuditOperation("SELECT SOMETHING")) .withUser("bob") .withTimestamp(System.currentTimeMillis()); } private void writeAuditRecordToChronicle(AuditRecord auditRecord) { writeAuditRecordToChronicle(auditRecord, FieldSelector.DEFAULT_FIELDS); } private void writeAuditRecordToChronicle(AuditRecord auditRecord, FieldSelector fields) { WriteMarshallable writeMarshallable = new AuditRecordWriteMarshallable(auditRecord, fields); ExcerptAppender appender = chronicleQueue.acquireAppender(); appender.writeDocument(writeMarshallable); } private StoredAuditRecord readAuditRecordFromChronicle() { AuditRecordReadMarshallable readMarshallable = new AuditRecordReadMarshallable(); ExcerptTailer tailer = chronicleQueue.createTailer(); tailer.readDocument(readMarshallable); return readMarshallable.getAuditRecord(); } private void assertThatRecordsMatch(StoredAuditRecord actualAuditRecord, AuditRecord expectedAuditRecord) { assertThat(actualAuditRecord.getBatchId()).isEqualTo(expectedAuditRecord.getBatchId()); assertThat(actualAuditRecord.getClientAddress()).contains(expectedAuditRecord.getClientAddress().getAddress()); assertThat(actualAuditRecord.getClientPort()).contains(expectedAuditRecord.getClientAddress().getPort()); assertThat(actualAuditRecord.getCoordinatorAddress()).contains(expectedAuditRecord.getCoordinatorAddress()); assertThat(actualAuditRecord.getStatus()).contains(expectedAuditRecord.getStatus()); assertThat(actualAuditRecord.getOperation()).contains(expectedAuditRecord.getOperation().getOperationString()); assertThat(actualAuditRecord.getNakedOperation()).isEmpty(); assertThat(actualAuditRecord.getUser()).contains(expectedAuditRecord.getUser()); assertThat(actualAuditRecord.getTimestamp()).contains(expectedAuditRecord.getTimestamp()); assertThat(actualAuditRecord.getSubject()).isEqualTo(expectedAuditRecord.getSubject()); } }
UTF-8
Java
6,550
java
TestWriteReadVersionCurrent.java
Java
[ { "context": "/*\n * Copyright 2019 Telefonaktiebolaget LM Ericsson\n *\n * Licensed under the Apache License, Version ", "end": 52, "score": 0.9897570610046387, "start": 44, "tag": "NAME", "value": "Ericsson" }, { "context": "Operation(\"SELECT SOMETHING\"))\n .withUser(\"bob\")\n .withTimestamp(System.currentTimeMillis", "end": 4536, "score": 0.9988644123077393, "start": 4533, "tag": "USERNAME", "value": "bob" } ]
null
[]
/* * Copyright 2019 Telefonaktiebolaget LM Ericsson * * 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.ericsson.bss.cassandra.ecaudit.common.chronicle; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.ericsson.bss.cassandra.ecaudit.common.record.AuditRecord; import com.ericsson.bss.cassandra.ecaudit.common.record.SimpleAuditOperation; import com.ericsson.bss.cassandra.ecaudit.common.record.SimpleAuditRecord; import com.ericsson.bss.cassandra.ecaudit.common.record.Status; import com.ericsson.bss.cassandra.ecaudit.common.record.StoredAuditRecord; import net.openhft.chronicle.core.io.IORuntimeException; import net.openhft.chronicle.queue.ChronicleQueue; import net.openhft.chronicle.queue.ChronicleQueueBuilder; import net.openhft.chronicle.queue.ExcerptAppender; import net.openhft.chronicle.queue.ExcerptTailer; import net.openhft.chronicle.wire.WriteMarshallable; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class TestWriteReadVersionCurrent { @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private ChronicleQueue chronicleQueue; @Before public void before() { chronicleQueue = ChronicleQueueBuilder.single(temporaryFolder.getRoot()).blockSize(1024).build(); } @After public void after() { chronicleQueue.close(); } @Test public void writeReadSubject() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().withSubject("bob-the-subject").build(); FieldSelector fieldsWithSubject = FieldSelector.DEFAULT_FIELDS.withField(FieldSelector.Field.SUBJECT); writeAuditRecordToChronicle(expectedAuditRecord, fieldsWithSubject); StoredAuditRecord actualAuditRecord = readAuditRecordFromChronicle(); assertThatRecordsMatch(actualAuditRecord, expectedAuditRecord); } @Test public void writeReadBatch() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().withBatchId(UUID.randomUUID()).build(); writeAuditRecordToChronicle(expectedAuditRecord); StoredAuditRecord actualAuditRecord = readAuditRecordFromChronicle(); assertThatRecordsMatch(actualAuditRecord, expectedAuditRecord); } @Test public void writeReadSingle() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().withStatus(Status.FAILED).build(); writeAuditRecordToChronicle(expectedAuditRecord); StoredAuditRecord actualAuditRecord = readAuditRecordFromChronicle(); assertThatRecordsMatch(actualAuditRecord, expectedAuditRecord); } @Test public void tryReuseOnRead() throws Exception { AuditRecord expectedAuditRecord = likeGenericRecord().build(); writeAuditRecordToChronicle(expectedAuditRecord); writeAuditRecordToChronicle(expectedAuditRecord); AuditRecordReadMarshallable readMarshallable = new AuditRecordReadMarshallable(); ExcerptTailer tailer = chronicleQueue.createTailer(); tailer.readDocument(readMarshallable); assertThatExceptionOfType(IORuntimeException.class) .isThrownBy(() -> tailer.readDocument(readMarshallable)) .withMessage("Tried to read from wire with used marshallable"); } private SimpleAuditRecord.Builder likeGenericRecord() throws UnknownHostException { return SimpleAuditRecord .builder() .withClientAddress(new InetSocketAddress(InetAddress.getByName("0.1.2.3"), 876)) .withCoordinatorAddress(InetAddress.getByName("4.5.6.7")) .withStatus(Status.ATTEMPT) .withOperation(new SimpleAuditOperation("SELECT SOMETHING")) .withUser("bob") .withTimestamp(System.currentTimeMillis()); } private void writeAuditRecordToChronicle(AuditRecord auditRecord) { writeAuditRecordToChronicle(auditRecord, FieldSelector.DEFAULT_FIELDS); } private void writeAuditRecordToChronicle(AuditRecord auditRecord, FieldSelector fields) { WriteMarshallable writeMarshallable = new AuditRecordWriteMarshallable(auditRecord, fields); ExcerptAppender appender = chronicleQueue.acquireAppender(); appender.writeDocument(writeMarshallable); } private StoredAuditRecord readAuditRecordFromChronicle() { AuditRecordReadMarshallable readMarshallable = new AuditRecordReadMarshallable(); ExcerptTailer tailer = chronicleQueue.createTailer(); tailer.readDocument(readMarshallable); return readMarshallable.getAuditRecord(); } private void assertThatRecordsMatch(StoredAuditRecord actualAuditRecord, AuditRecord expectedAuditRecord) { assertThat(actualAuditRecord.getBatchId()).isEqualTo(expectedAuditRecord.getBatchId()); assertThat(actualAuditRecord.getClientAddress()).contains(expectedAuditRecord.getClientAddress().getAddress()); assertThat(actualAuditRecord.getClientPort()).contains(expectedAuditRecord.getClientAddress().getPort()); assertThat(actualAuditRecord.getCoordinatorAddress()).contains(expectedAuditRecord.getCoordinatorAddress()); assertThat(actualAuditRecord.getStatus()).contains(expectedAuditRecord.getStatus()); assertThat(actualAuditRecord.getOperation()).contains(expectedAuditRecord.getOperation().getOperationString()); assertThat(actualAuditRecord.getNakedOperation()).isEmpty(); assertThat(actualAuditRecord.getUser()).contains(expectedAuditRecord.getUser()); assertThat(actualAuditRecord.getTimestamp()).contains(expectedAuditRecord.getTimestamp()); assertThat(actualAuditRecord.getSubject()).isEqualTo(expectedAuditRecord.getSubject()); } }
6,550
0.76229
0.758779
167
38.221558
35.661652
119
false
false
0
0
0
0
0
0
0.479042
false
false
2
88dce05d07077d3a20b8335fb7189ecb386dc50f
7,103,875,924,453
6da3803eb24f980f2b987cb5a75155d51ceb831e
/revisions_2018/examenJanvier2017/question1/PubSubImpl2.java
0b76ea425bb358844fa30038197e758dcd59c073
[]
no_license
Atalaia/NFP121
https://github.com/Atalaia/NFP121
622fc3ec754c008bd12aba752c8e0d90e824e49d
ebaae29ec9dc986c818631d16f58fc5d31a10b43
refs/heads/master
2020-06-26T19:24:10.116000
2020-02-23T17:00:29
2020-02-23T17:00:29
199,725,507
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package examenJanvier2017.question1; import java.util.*; import java.io.Serializable; /** * Write a description of class PubSubImpl2 here. * * @author (your name) * @version (a version number or a date) */ public class PubSubImpl2 implements PubSubI { private String name; private Map<String, SubscriberI> subscribers; public PubSubImpl2(){ this.subscribers = new HashMap<String, SubscriberI>(); } public PubSubImpl2(String name){ this(); this.name = name; } public String getName(){return name;} /** Publication d'un message à  certains souscripteurs. * @param names les noms des souscripteurs * @param message le message à  transmettre * @return le nombre de souscripteurs ayant reçu le message */ public int publish(String[] names, Message message){ int subs = 0; for(String name : names){ if(publish(name,message)); subs++; } return subs; } /** Publication d'un message à un souscripteur. * @param name le nom du souscripteur * @param message le message à  transmettre * @return true si l'envoi est réussi, false autrement */ public boolean publish(String name,Message message){ boolean res = false; SubscriberI sub = subscribers.get(name); if(sub != null){ try{ sub.onMessage(message); res = true; }catch (Exception e){} } return res; } /** Souscription. * @param subscriber le souscripteur * @return false si ce souscripteur a déjà souscrit avec le même nom */ public boolean subscribe(SubscriberI subscriber){ if(subscribers.get(subscriber.getName()) != null) return false; subscribers.put(subscriber.getName(),subscriber); subscriber.addPubSub(this); return true; } /** Obtention d'un itérateur. * @return un itérateur sur les souscripteurs enregistrés */ public Iterator<SubscriberI> iterator(){ return subscribers.values().iterator(); } }
UTF-8
Java
2,013
java
PubSubImpl2.java
Java
[]
null
[]
package examenJanvier2017.question1; import java.util.*; import java.io.Serializable; /** * Write a description of class PubSubImpl2 here. * * @author (your name) * @version (a version number or a date) */ public class PubSubImpl2 implements PubSubI { private String name; private Map<String, SubscriberI> subscribers; public PubSubImpl2(){ this.subscribers = new HashMap<String, SubscriberI>(); } public PubSubImpl2(String name){ this(); this.name = name; } public String getName(){return name;} /** Publication d'un message à  certains souscripteurs. * @param names les noms des souscripteurs * @param message le message à  transmettre * @return le nombre de souscripteurs ayant reçu le message */ public int publish(String[] names, Message message){ int subs = 0; for(String name : names){ if(publish(name,message)); subs++; } return subs; } /** Publication d'un message à un souscripteur. * @param name le nom du souscripteur * @param message le message à  transmettre * @return true si l'envoi est réussi, false autrement */ public boolean publish(String name,Message message){ boolean res = false; SubscriberI sub = subscribers.get(name); if(sub != null){ try{ sub.onMessage(message); res = true; }catch (Exception e){} } return res; } /** Souscription. * @param subscriber le souscripteur * @return false si ce souscripteur a déjà souscrit avec le même nom */ public boolean subscribe(SubscriberI subscriber){ if(subscribers.get(subscriber.getName()) != null) return false; subscribers.put(subscriber.getName(),subscriber); subscriber.addPubSub(this); return true; } /** Obtention d'un itérateur. * @return un itérateur sur les souscripteurs enregistrés */ public Iterator<SubscriberI> iterator(){ return subscribers.values().iterator(); } }
2,013
0.659319
0.654309
76
25.263159
20.124853
70
false
false
0
0
0
0
0
0
0.394737
false
false
2
45b36d816273d332232152f450fe64efdd63a39b
850,403,558,466
41ca93e30b0dc0fb491ec229d96ababfdcb3005b
/Human.java
d23611d0c24e3a51602cd1975c2525cc7f368296
[]
no_license
Kryptikz/Civility
https://github.com/Kryptikz/Civility
d42a53d5bbebb8250dba4b6b33569477c7229d0c
9449d8a72ba97ab2f490fe3fdef9b3cf7534de67
refs/heads/master
2020-04-07T03:14:21.075000
2019-05-07T23:45:30
2019-05-07T23:45:30
158,008,212
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import javafx.geometry.*; import java.awt.*; public class Human implements AI,Runnable { double x; double y; int width=30; int height=30; Display d; Color color = new Color(255,226,140); String name; House home; public Human(int x_loc, int y_loc, Display dis, House h) { x=x_loc; y=y_loc; d=dis; String[] names = new String[]{"Bob","Brian","Tristan","Ethan","Steve","Bill","Charles","Oliver","Harry","Jack","George","Noah","Charlie","Jacob","Alfie","Freddie","Oscar","Leo","Logan","Wes", "Roger","Nicholas","Rich","Korey","Renaldo","Donte","Rodolfo","Gerald","Rigoberto","Jamar","Doyle","Thad","Edgardo","Trey","Sylvester","Abel","Markus","Bryan","Odell","Oswaldo","Albert","Hai","Robby","Parker","Kermit","Darin","Willy","Juan","Jamie","Junior","Faustino","Harvey","Gayle","Eric","Otha","Sam","Roscoe","Stacey","Gerardo","Karl","Titus","Jerrod","Minh","Young","Danial","Emery","Felipe","Gustavo","Elisha","Malcolm"}; int namenum = (int)(Math.random()*names.length); name=names[namenum]; home=h; } public void update() { } public void run() { while(true) { try { Thread.sleep((int)((Math.random()*2000)+500)); //Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } ArrayList<Building> builds = d.getBuildings(); //ArrayList<Resource> resource = d.getResources(); ArrayList<Resource> resource = new ArrayList<Resource>(); int dir = (int)(Math.random()*4); double center_x=d.getCenterX(); double center_y=d.getCenterY(); int movx=0; int movy=0; int magnitude = 150; int maxhomedist = 500; if (dir==0) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x-magnitude,y,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x-magnitude,y,width,height))) { check = true; } } if (!check&&homeDistance(x-magnitude,y)<maxhomedist) { movx=-magnitude; } } else if (dir==1) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x+magnitude,y,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x+magnitude,y,width,height))) { check = true; } } if (!check&&homeDistance(x+magnitude,y)<maxhomedist) { movx=magnitude; } } else if (dir==2) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x,y-magnitude,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x,y-magnitude,width,height))) { check = true; } } if (!check&&homeDistance(x,y-magnitude)<maxhomedist) { movy=-magnitude; } } else if (dir==3) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x,y+magnitude,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x,y+magnitude,width,height))) { check = true; } } if (!check&&homeDistance(x,y+magnitude)<maxhomedist) { movy=magnitude; } } for(int i=0;i<100;i++) { try { Thread.sleep(6); } catch (Exception e) { e.printStackTrace(); } x+=(double)(movx)/100; y+=(double)(movy)/100; } } } public double getX() { return x; } public double getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public BoundingBox getBoundingBox() { return new BoundingBox(x,y,width,height); } public Color getColor() { return color; } public String getType() { return "human"; } public String getName() { return name; } private double homeDistance(double x2, double y2) { return Math.sqrt((x2-home.getX())*(x2-home.getX())+(y2-home.getY())*(y2-home.getY())); } public static String getRandomName() { String[] names = new String[]{"Bob","Brian","Tristan","Ethan","Steve","Bill","Charles","Oliver","Harry","Jack","George","Noah","Charlie","Jacob","Alfie","Freddie","Oscar","Leo","Logan","Wes", "Roger","Nicholas","Rich","Korey","Renaldo","Donte","Rodolfo","Gerald","Rigoberto","Jamar","Doyle","Thad","Edgardo","Trey","Sylvester","Abel","Markus","Bryan","Odell","Oswaldo","Albert","Hai","Robby","Parker","Kermit","Darin","Willy","Juan","Jamie","Junior","Faustino","Harvey","Gayle","Eric","Otha","Sam","Roscoe","Stacey","Gerardo","Karl","Titus","Jerrod","Minh","Young","Danial","Emery","Felipe","Gustavo","Elisha","Malcolm"}; int namenum = (int)(Math.random()*names.length); String tname=names[namenum]; return tname; } }
UTF-8
Java
6,181
java
Human.java
Java
[ { "context": " d=dis;\n String[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charle", "end": 418, "score": 0.9998142123222351, "start": 415, "tag": "NAME", "value": "Bob" }, { "context": "dis;\n String[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliv", "end": 426, "score": 0.9997701644897461, "start": 421, "tag": "NAME", "value": "Brian" }, { "context": " String[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry", "end": 436, "score": 0.9997212290763855, "start": 429, "tag": "NAME", "value": "Tristan" }, { "context": "g[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\"", "end": 444, "score": 0.9997820854187012, "start": 439, "tag": "NAME", "value": "Ethan" }, { "context": "s = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George", "end": 452, "score": 0.9997786283493042, "start": 447, "tag": "NAME", "value": "Steve" }, { "context": "String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah", "end": 459, "score": 0.9997475743293762, "start": 455, "tag": "NAME", "value": "Bill" }, { "context": "]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie", "end": 469, "score": 0.9997760057449341, "start": 462, "tag": "NAME", "value": "Charles" }, { "context": "rian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\"", "end": 478, "score": 0.9997955560684204, "start": 472, "tag": "NAME", "value": "Oliver" }, { "context": "istan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\"", "end": 486, "score": 0.9997808933258057, "start": 481, "tag": "NAME", "value": "Harry" }, { "context": "Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Fredd", "end": 493, "score": 0.9997790455818176, "start": 489, "tag": "NAME", "value": "Jack" }, { "context": "\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Osca", "end": 502, "score": 0.9997565746307373, "start": 496, "tag": "NAME", "value": "George" }, { "context": "Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo", "end": 509, "score": 0.999764621257782, "start": 505, "tag": "NAME", "value": "Noah" }, { "context": "Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",", "end": 519, "score": 0.9997818470001221, "start": 512, "tag": "NAME", "value": "Charlie" }, { "context": "Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"", "end": 527, "score": 0.9997643232345581, "start": 522, "tag": "NAME", "value": "Jacob" }, { "context": "\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"", "end": 535, "score": 0.9997956156730652, "start": 530, "tag": "NAME", "value": "Alfie" }, { "context": "\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",", "end": 545, "score": 0.9997987747192383, "start": 538, "tag": "NAME", "value": "Freddie" }, { "context": "orge\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"", "end": 553, "score": 0.999796986579895, "start": 548, "tag": "NAME", "value": "Oscar" }, { "context": "oah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\"", "end": 559, "score": 0.9997718334197998, "start": 556, "tag": "NAME", "value": "Leo" }, { "context": "Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renald", "end": 567, "score": 0.9997711181640625, "start": 562, "tag": "NAME", "value": "Logan" }, { "context": ",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Do", "end": 573, "score": 0.9997705817222595, "start": 570, "tag": "NAME", "value": "Wes" }, { "context": "\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rod", "end": 582, "score": 0.9997727870941162, "start": 577, "tag": "NAME", "value": "Roger" }, { "context": "\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gera", "end": 593, "score": 0.9997712969779968, "start": 585, "tag": "NAME", "value": "Nicholas" }, { "context": ",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Ri", "end": 600, "score": 0.9997020363807678, "start": 596, "tag": "NAME", "value": "Rich" }, { "context": "\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\"", "end": 608, "score": 0.9997479319572449, "start": 603, "tag": "NAME", "value": "Korey" }, { "context": "\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"", "end": 618, "score": 0.9997982382774353, "start": 611, "tag": "NAME", "value": "Renaldo" }, { "context": "es\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"", "end": 626, "score": 0.9997389316558838, "start": 621, "tag": "NAME", "value": "Donte" }, { "context": "ger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edg", "end": 636, "score": 0.9997710585594177, "start": 629, "tag": "NAME", "value": "Rodolfo" }, { "context": "olas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Tr", "end": 645, "score": 0.9997972846031189, "start": 639, "tag": "NAME", "value": "Gerald" }, { "context": "ch\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvest", "end": 657, "score": 0.9997828006744385, "start": 648, "tag": "NAME", "value": "Rigoberto" }, { "context": "\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abe", "end": 665, "score": 0.999755859375, "start": 660, "tag": "NAME", "value": "Jamar" }, { "context": "\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Mark", "end": 673, "score": 0.9997535943984985, "start": 668, "tag": "NAME", "value": "Doyle" }, { "context": "\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Br", "end": 680, "score": 0.9997513294219971, "start": 676, "tag": "NAME", "value": "Thad" }, { "context": "lfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odel", "end": 690, "score": 0.999774158000946, "start": 683, "tag": "NAME", "value": "Edgardo" }, { "context": "ld\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Osw", "end": 697, "score": 0.9997226595878601, "start": 693, "tag": "NAME", "value": "Trey" }, { "context": "goberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Alber", "end": 709, "score": 0.9998032450675964, "start": 700, "tag": "NAME", "value": "Sylvester" }, { "context": "mar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai", "end": 716, "score": 0.9997705221176147, "start": 712, "tag": "NAME", "value": "Abel" }, { "context": "oyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\"", "end": 725, "score": 0.9997897148132324, "start": 719, "tag": "NAME", "value": "Markus" }, { "context": "ad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker", "end": 733, "score": 0.999790608882904, "start": 728, "tag": "NAME", "value": "Bryan" }, { "context": "ardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermi", "end": 741, "score": 0.9998074173927307, "start": 736, "tag": "NAME", "value": "Odell" }, { "context": "rey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\"", "end": 751, "score": 0.999826192855835, "start": 744, "tag": "NAME", "value": "Oswaldo" }, { "context": "ester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",", "end": 760, "score": 0.9997774362564087, "start": 754, "tag": "NAME", "value": "Albert" }, { "context": "bel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\"", "end": 766, "score": 0.9997916221618652, "start": 763, "tag": "NAME", "value": "Hai" }, { "context": "Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\"", "end": 774, "score": 0.9997791051864624, "start": 769, "tag": "NAME", "value": "Robby" }, { "context": "\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\"", "end": 783, "score": 0.9997481107711792, "start": 777, "tag": "NAME", "value": "Parker" }, { "context": "Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustin", "end": 792, "score": 0.9997802972793579, "start": 786, "tag": "NAME", "value": "Kermit" }, { "context": "swaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harv", "end": 800, "score": 0.9997601509094238, "start": 795, "tag": "NAME", "value": "Darin" }, { "context": "\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gay", "end": 808, "score": 0.9997705221176147, "start": 803, "tag": "NAME", "value": "Willy" }, { "context": ",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Er", "end": 815, "score": 0.9997251629829407, "start": 811, "tag": "NAME", "value": "Juan" }, { "context": "\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Oth", "end": 823, "score": 0.9997513890266418, "start": 818, "tag": "NAME", "value": "Jamie" }, { "context": "\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",", "end": 832, "score": 0.9996521472930908, "start": 826, "tag": "NAME", "value": "Junior" }, { "context": "\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"S", "end": 843, "score": 0.9997990131378174, "start": 835, "tag": "NAME", "value": "Faustino" }, { "context": "arin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"G", "end": 852, "score": 0.9997690916061401, "start": 846, "tag": "NAME", "value": "Harvey" }, { "context": "lly\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",", "end": 860, "score": 0.9997883439064026, "start": 855, "tag": "NAME", "value": "Gayle" }, { "context": "an\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",", "end": 867, "score": 0.9997768402099609, "start": 863, "tag": "NAME", "value": "Eric" }, { "context": "mie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\"", "end": 874, "score": 0.9997975826263428, "start": 870, "tag": "NAME", "value": "Otha" }, { "context": "unior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerr", "end": 880, "score": 0.9997713565826416, "start": 877, "tag": "NAME", "value": "Sam" }, { "context": ",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh", "end": 889, "score": 0.9997167587280273, "start": 883, "tag": "NAME", "value": "Roscoe" }, { "context": "o\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\"", "end": 898, "score": 0.9997815489768982, "start": 892, "tag": "NAME", "value": "Stacey" }, { "context": "y\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",", "end": 908, "score": 0.9997670650482178, "start": 901, "tag": "NAME", "value": "Gerardo" }, { "context": ",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\"", "end": 915, "score": 0.9998088479042053, "start": 911, "tag": "NAME", "value": "Karl" }, { "context": ",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe", "end": 923, "score": 0.9997649192810059, "start": 918, "tag": "NAME", "value": "Titus" }, { "context": "\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustav", "end": 932, "score": 0.9997837543487549, "start": 926, "tag": "NAME", "value": "Jerrod" }, { "context": "scoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Eli", "end": 939, "score": 0.9997923374176025, "start": 935, "tag": "NAME", "value": "Minh" }, { "context": "Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Ma", "end": 947, "score": 0.9997768402099609, "start": 942, "tag": "NAME", "value": "Young" }, { "context": "\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n", "end": 956, "score": 0.9997908473014832, "start": 950, "tag": "NAME", "value": "Danial" }, { "context": ",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n ", "end": 964, "score": 0.9997852444648743, "start": 959, "tag": "NAME", "value": "Emery" }, { "context": "\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namen", "end": 973, "score": 0.9998005032539368, "start": 967, "tag": "NAME", "value": "Felipe" }, { "context": "Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namenum = (int)", "end": 983, "score": 0.9998063445091248, "start": 976, "tag": "NAME", "value": "Gustavo" }, { "context": "inh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namenum = (int)(Math.ran", "end": 992, "score": 0.9998171925544739, "start": 986, "tag": "NAME", "value": "Elisha" }, { "context": "ng\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namenum = (int)(Math.random()*name", "end": 1002, "score": 0.9997588992118835, "start": 995, "tag": "NAME", "value": "Malcolm" }, { "context": "omName() {\n String[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charle", "end": 5470, "score": 0.9998394846916199, "start": 5467, "tag": "NAME", "value": "Bob" }, { "context": "() {\n String[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliv", "end": 5478, "score": 0.9997857809066772, "start": 5473, "tag": "NAME", "value": "Brian" }, { "context": " String[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry", "end": 5488, "score": 0.999772310256958, "start": 5481, "tag": "NAME", "value": "Tristan" }, { "context": "g[] names = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\"", "end": 5496, "score": 0.9997938871383667, "start": 5491, "tag": "NAME", "value": "Ethan" }, { "context": "s = new String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George", "end": 5504, "score": 0.9997628331184387, "start": 5499, "tag": "NAME", "value": "Steve" }, { "context": "String[]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah", "end": 5511, "score": 0.9997580647468567, "start": 5507, "tag": "NAME", "value": "Bill" }, { "context": "]{\"Bob\",\"Brian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie", "end": 5521, "score": 0.9997646808624268, "start": 5514, "tag": "NAME", "value": "Charles" }, { "context": "rian\",\"Tristan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\"", "end": 5530, "score": 0.999795138835907, "start": 5524, "tag": "NAME", "value": "Oliver" }, { "context": "istan\",\"Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\"", "end": 5538, "score": 0.9997717142105103, "start": 5533, "tag": "NAME", "value": "Harry" }, { "context": "Ethan\",\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Fredd", "end": 5545, "score": 0.9997842311859131, "start": 5541, "tag": "NAME", "value": "Jack" }, { "context": "\"Steve\",\"Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Osca", "end": 5554, "score": 0.99979168176651, "start": 5548, "tag": "NAME", "value": "George" }, { "context": "Bill\",\"Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo", "end": 5561, "score": 0.9998224973678589, "start": 5557, "tag": "NAME", "value": "Noah" }, { "context": "Charles\",\"Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",", "end": 5571, "score": 0.9998039603233337, "start": 5564, "tag": "NAME", "value": "Charlie" }, { "context": "Oliver\",\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"", "end": 5579, "score": 0.9997818470001221, "start": 5574, "tag": "NAME", "value": "Jacob" }, { "context": "\"Harry\",\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"", "end": 5587, "score": 0.9998223185539246, "start": 5582, "tag": "NAME", "value": "Alfie" }, { "context": "\"Jack\",\"George\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",", "end": 5597, "score": 0.999821662902832, "start": 5590, "tag": "NAME", "value": "Freddie" }, { "context": "orge\",\"Noah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"", "end": 5605, "score": 0.9998250007629395, "start": 5600, "tag": "NAME", "value": "Oscar" }, { "context": "oah\",\"Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\"", "end": 5611, "score": 0.9997913837432861, "start": 5608, "tag": "NAME", "value": "Leo" }, { "context": "Charlie\",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renald", "end": 5619, "score": 0.9997777342796326, "start": 5614, "tag": "NAME", "value": "Logan" }, { "context": ",\"Jacob\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Do", "end": 5625, "score": 0.9998102188110352, "start": 5622, "tag": "NAME", "value": "Wes" }, { "context": "\",\"Alfie\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rod", "end": 5634, "score": 0.9998424649238586, "start": 5629, "tag": "NAME", "value": "Roger" }, { "context": "\",\"Freddie\",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gera", "end": 5645, "score": 0.9998000264167786, "start": 5637, "tag": "NAME", "value": "Nicholas" }, { "context": ",\"Oscar\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Ri", "end": 5652, "score": 0.999790608882904, "start": 5648, "tag": "NAME", "value": "Rich" }, { "context": "\",\"Leo\",\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\"", "end": 5660, "score": 0.9997820854187012, "start": 5655, "tag": "NAME", "value": "Korey" }, { "context": "\"Logan\",\"Wes\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"", "end": 5670, "score": 0.9998064041137695, "start": 5663, "tag": "NAME", "value": "Renaldo" }, { "context": "es\", \"Roger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"", "end": 5678, "score": 0.999782919883728, "start": 5673, "tag": "NAME", "value": "Donte" }, { "context": "ger\",\"Nicholas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edg", "end": 5688, "score": 0.9998309016227722, "start": 5681, "tag": "NAME", "value": "Rodolfo" }, { "context": "olas\",\"Rich\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Tr", "end": 5697, "score": 0.9998266696929932, "start": 5691, "tag": "NAME", "value": "Gerald" }, { "context": "ch\",\"Korey\",\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvest", "end": 5709, "score": 0.9998326301574707, "start": 5700, "tag": "NAME", "value": "Rigoberto" }, { "context": "\"Renaldo\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abe", "end": 5717, "score": 0.9998255968093872, "start": 5712, "tag": "NAME", "value": "Jamar" }, { "context": "\",\"Donte\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Mark", "end": 5725, "score": 0.9998129606246948, "start": 5720, "tag": "NAME", "value": "Doyle" }, { "context": "\",\"Rodolfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Br", "end": 5732, "score": 0.9998021125793457, "start": 5728, "tag": "NAME", "value": "Thad" }, { "context": "lfo\",\"Gerald\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odel", "end": 5742, "score": 0.9997928738594055, "start": 5735, "tag": "NAME", "value": "Edgardo" }, { "context": "ld\",\"Rigoberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Osw", "end": 5749, "score": 0.9996968507766724, "start": 5745, "tag": "NAME", "value": "Trey" }, { "context": "goberto\",\"Jamar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Alber", "end": 5761, "score": 0.9998273849487305, "start": 5752, "tag": "NAME", "value": "Sylvester" }, { "context": "mar\",\"Doyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai", "end": 5768, "score": 0.9998239278793335, "start": 5764, "tag": "NAME", "value": "Abel" }, { "context": "oyle\",\"Thad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\"", "end": 5777, "score": 0.9998173117637634, "start": 5771, "tag": "NAME", "value": "Markus" }, { "context": "ad\",\"Edgardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker", "end": 5785, "score": 0.9998275637626648, "start": 5780, "tag": "NAME", "value": "Bryan" }, { "context": "ardo\",\"Trey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermi", "end": 5793, "score": 0.9998276829719543, "start": 5788, "tag": "NAME", "value": "Odell" }, { "context": "rey\",\"Sylvester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\"", "end": 5803, "score": 0.9998393058776855, "start": 5796, "tag": "NAME", "value": "Oswaldo" }, { "context": "ester\",\"Abel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",", "end": 5812, "score": 0.9998053312301636, "start": 5806, "tag": "NAME", "value": "Albert" }, { "context": "bel\",\"Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\"", "end": 5818, "score": 0.9997621774673462, "start": 5815, "tag": "NAME", "value": "Hai" }, { "context": "Markus\",\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\"", "end": 5826, "score": 0.999799370765686, "start": 5821, "tag": "NAME", "value": "Robby" }, { "context": "\"Bryan\",\"Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\"", "end": 5835, "score": 0.9997134804725647, "start": 5829, "tag": "NAME", "value": "Parker" }, { "context": "Odell\",\"Oswaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustin", "end": 5844, "score": 0.9998029470443726, "start": 5838, "tag": "NAME", "value": "Kermit" }, { "context": "swaldo\",\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harv", "end": 5852, "score": 0.9997954368591309, "start": 5847, "tag": "NAME", "value": "Darin" }, { "context": "\"Albert\",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gay", "end": 5860, "score": 0.9998143911361694, "start": 5855, "tag": "NAME", "value": "Willy" }, { "context": ",\"Hai\",\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Er", "end": 5867, "score": 0.9997222423553467, "start": 5863, "tag": "NAME", "value": "Juan" }, { "context": "\"Robby\",\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Oth", "end": 5875, "score": 0.999778687953949, "start": 5870, "tag": "NAME", "value": "Jamie" }, { "context": "\"Parker\",\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",", "end": 5884, "score": 0.9995739459991455, "start": 5878, "tag": "NAME", "value": "Junior" }, { "context": "\"Kermit\",\"Darin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"S", "end": 5895, "score": 0.9997951984405518, "start": 5887, "tag": "NAME", "value": "Faustino" }, { "context": "arin\",\"Willy\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"G", "end": 5904, "score": 0.9997842907905579, "start": 5898, "tag": "NAME", "value": "Harvey" }, { "context": "lly\",\"Juan\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",", "end": 5912, "score": 0.9997850060462952, "start": 5907, "tag": "NAME", "value": "Gayle" }, { "context": "an\",\"Jamie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",", "end": 5919, "score": 0.9997783303260803, "start": 5915, "tag": "NAME", "value": "Eric" }, { "context": "mie\",\"Junior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\"", "end": 5926, "score": 0.9997686147689819, "start": 5922, "tag": "NAME", "value": "Otha" }, { "context": "unior\",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerr", "end": 5932, "score": 0.9998027682304382, "start": 5929, "tag": "NAME", "value": "Sam" }, { "context": ",\"Faustino\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh", "end": 5941, "score": 0.9998078346252441, "start": 5935, "tag": "NAME", "value": "Roscoe" }, { "context": "o\",\"Harvey\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\"", "end": 5950, "score": 0.9995865821838379, "start": 5944, "tag": "NAME", "value": "Stacey" }, { "context": "y\",\"Gayle\",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",", "end": 5960, "score": 0.983923077583313, "start": 5953, "tag": "NAME", "value": "Gerardo" }, { "context": ",\"Eric\",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\"", "end": 5967, "score": 0.999755322933197, "start": 5963, "tag": "NAME", "value": "Karl" }, { "context": ",\"Otha\",\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe", "end": 5975, "score": 0.9996625781059265, "start": 5970, "tag": "NAME", "value": "Titus" }, { "context": "\"Sam\",\"Roscoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustav", "end": 5984, "score": 0.9997394680976868, "start": 5978, "tag": "NAME", "value": "Jerrod" }, { "context": "scoe\",\"Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Eli", "end": 5991, "score": 0.9997476935386658, "start": 5987, "tag": "NAME", "value": "Minh" }, { "context": "Stacey\",\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Ma", "end": 5999, "score": 0.9997684955596924, "start": 5994, "tag": "NAME", "value": "Young" }, { "context": "\"Gerardo\",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n", "end": 6008, "score": 0.9997591376304626, "start": 6002, "tag": "NAME", "value": "Danial" }, { "context": ",\"Karl\",\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n ", "end": 6016, "score": 0.9997575879096985, "start": 6011, "tag": "NAME", "value": "Emery" }, { "context": "\"Titus\",\"Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namen", "end": 6025, "score": 0.9997674822807312, "start": 6019, "tag": "NAME", "value": "Felipe" }, { "context": "Jerrod\",\"Minh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namenum = (int)", "end": 6035, "score": 0.9997587203979492, "start": 6028, "tag": "NAME", "value": "Gustavo" }, { "context": "inh\",\"Young\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namenum = (int)(Math.ran", "end": 6044, "score": 0.999748706817627, "start": 6038, "tag": "NAME", "value": "Elisha" }, { "context": "ng\",\"Danial\",\"Emery\",\"Felipe\",\"Gustavo\",\"Elisha\",\"Malcolm\"};\n int namenum = (int)(Math.random()*name", "end": 6054, "score": 0.9995782971382141, "start": 6047, "tag": "NAME", "value": "Malcolm" } ]
null
[]
import java.util.*; import javafx.geometry.*; import java.awt.*; public class Human implements AI,Runnable { double x; double y; int width=30; int height=30; Display d; Color color = new Color(255,226,140); String name; House home; public Human(int x_loc, int y_loc, Display dis, House h) { x=x_loc; y=y_loc; d=dis; String[] names = new String[]{"Bob","Brian","Tristan","Ethan","Steve","Bill","Charles","Oliver","Harry","Jack","George","Noah","Charlie","Jacob","Alfie","Freddie","Oscar","Leo","Logan","Wes", "Roger","Nicholas","Rich","Korey","Renaldo","Donte","Rodolfo","Gerald","Rigoberto","Jamar","Doyle","Thad","Edgardo","Trey","Sylvester","Abel","Markus","Bryan","Odell","Oswaldo","Albert","Hai","Robby","Parker","Kermit","Darin","Willy","Juan","Jamie","Junior","Faustino","Harvey","Gayle","Eric","Otha","Sam","Roscoe","Stacey","Gerardo","Karl","Titus","Jerrod","Minh","Young","Danial","Emery","Felipe","Gustavo","Elisha","Malcolm"}; int namenum = (int)(Math.random()*names.length); name=names[namenum]; home=h; } public void update() { } public void run() { while(true) { try { Thread.sleep((int)((Math.random()*2000)+500)); //Thread.sleep(10); } catch (Exception e) { e.printStackTrace(); } ArrayList<Building> builds = d.getBuildings(); //ArrayList<Resource> resource = d.getResources(); ArrayList<Resource> resource = new ArrayList<Resource>(); int dir = (int)(Math.random()*4); double center_x=d.getCenterX(); double center_y=d.getCenterY(); int movx=0; int movy=0; int magnitude = 150; int maxhomedist = 500; if (dir==0) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x-magnitude,y,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x-magnitude,y,width,height))) { check = true; } } if (!check&&homeDistance(x-magnitude,y)<maxhomedist) { movx=-magnitude; } } else if (dir==1) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x+magnitude,y,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x+magnitude,y,width,height))) { check = true; } } if (!check&&homeDistance(x+magnitude,y)<maxhomedist) { movx=magnitude; } } else if (dir==2) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x,y-magnitude,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x,y-magnitude,width,height))) { check = true; } } if (!check&&homeDistance(x,y-magnitude)<maxhomedist) { movy=-magnitude; } } else if (dir==3) { boolean check = false; for (Building b : builds) { if (b.getBoundingBox().intersects(new BoundingBox(x,y+magnitude,width,height))) { check = true; } } for (Resource r : resource) { if (r.getBoundingBox().intersects(new BoundingBox(x,y+magnitude,width,height))) { check = true; } } if (!check&&homeDistance(x,y+magnitude)<maxhomedist) { movy=magnitude; } } for(int i=0;i<100;i++) { try { Thread.sleep(6); } catch (Exception e) { e.printStackTrace(); } x+=(double)(movx)/100; y+=(double)(movy)/100; } } } public double getX() { return x; } public double getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public BoundingBox getBoundingBox() { return new BoundingBox(x,y,width,height); } public Color getColor() { return color; } public String getType() { return "human"; } public String getName() { return name; } private double homeDistance(double x2, double y2) { return Math.sqrt((x2-home.getX())*(x2-home.getX())+(y2-home.getY())*(y2-home.getY())); } public static String getRandomName() { String[] names = new String[]{"Bob","Brian","Tristan","Ethan","Steve","Bill","Charles","Oliver","Harry","Jack","George","Noah","Charlie","Jacob","Alfie","Freddie","Oscar","Leo","Logan","Wes", "Roger","Nicholas","Rich","Korey","Renaldo","Donte","Rodolfo","Gerald","Rigoberto","Jamar","Doyle","Thad","Edgardo","Trey","Sylvester","Abel","Markus","Bryan","Odell","Oswaldo","Albert","Hai","Robby","Parker","Kermit","Darin","Willy","Juan","Jamie","Junior","Faustino","Harvey","Gayle","Eric","Otha","Sam","Roscoe","Stacey","Gerardo","Karl","Titus","Jerrod","Minh","Young","Danial","Emery","Felipe","Gustavo","Elisha","Malcolm"}; int namenum = (int)(Math.random()*names.length); String tname=names[namenum]; return tname; } }
6,181
0.488109
0.479696
147
41.05442
72.81472
629
false
false
0
0
0
0
0
0
1.646258
false
false
2
dfe724dab76468692c27d7a686984eb8a82f141e
4,492,535,828,324
68471568bc7be584733b82f43463a4b0f8dd5af4
/jobotsim26/JobotSim26/src/javaBot/JrTacho/BraitenbergBehavior.java
6daa3f12bd5fe5eedc23bc22196aa9ae6e3bfeb0
[]
no_license
carriercomm/robots
https://github.com/carriercomm/robots
e2f23b05305e8a3197accababed6a115de9b7d64
8a7e362bf2d52e1a79bbdddfc5ec475c71e91766
refs/heads/master
2020-12-11T04:19:16.618000
2011-03-18T11:15:03
2011-03-18T11:15:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created on Aug 13, 2004 * FleeBehavior (dip=5) moves in the opposite direction * of an obstacle detected by a sensor * The behavior base class sits on the behavior base class * @author James Caska */ package javaBot.JrTacho; import com.muvium.apt.PeriodicTimer; /** * Created on 20-02-2006 * Copyright: (c) 2006 * Company: Dancing Bear Software * * @version $Revision$ * last changed 20-02-2006 * * TODO CLASS: DOCUMENT ME! */ public class BraitenbergBehavior extends Behavior { private int dip = 0; /** * Creates a new BraitenbergJrBehavior object. * * @param initJoBot TODO PARAM: DOCUMENT ME! * @param initServiceTick TODO PARAM: DOCUMENT ME! * @param servicePeriod TODO PARAM: DOCUMENT ME! * @param dipValue TODO PARAM: DOCUMENT ME! */ public BraitenbergBehavior(JobotBaseController initJoBot, PeriodicTimer initServiceTick, int servicePeriod, int dipValue) { super(initJoBot, initServiceTick, servicePeriod); dip = dipValue; } /** * TODO METHOD: DOCUMENT ME! * * @param value TODO PARAM: param description * * @return $returnType$ TODO RETURN: return description */ private int scale(int value) { if (value > 100) { return 100; } else { return value; } } /** * TODO METHOD: DOCUMENT ME! */ public void doBehavior() { int s0 = 0; int s1 = 0; int vx = 0; int vy = 0; s0 = getJoBot().getSensor(0); s1 = getJoBot().getSensor(1); if (dip == 0) { vx = s0; vy = s1; } if (dip == 1) { vx = s1; vy = s0; } if (dip == 2) { vx = -s0; vy = -s1; } if (dip == 3) { vx = -s1; vy = -s0; } getJoBot().setStatusLeds(false, vx == 0, vy == 0); getJoBot().drive(vx, vy); } }
UTF-8
Java
1,823
java
BraitenbergBehavior.java
Java
[ { "context": " class sits on the behavior base class\r\n * @author James Caska\r\n */\r\npackage javaBot.JrTacho;\r\n\r\nimport com.muvi", "end": 211, "score": 0.9998346567153931, "start": 200, "tag": "NAME", "value": "James Caska" } ]
null
[]
/* * Created on Aug 13, 2004 * FleeBehavior (dip=5) moves in the opposite direction * of an obstacle detected by a sensor * The behavior base class sits on the behavior base class * @author <NAME> */ package javaBot.JrTacho; import com.muvium.apt.PeriodicTimer; /** * Created on 20-02-2006 * Copyright: (c) 2006 * Company: Dancing Bear Software * * @version $Revision$ * last changed 20-02-2006 * * TODO CLASS: DOCUMENT ME! */ public class BraitenbergBehavior extends Behavior { private int dip = 0; /** * Creates a new BraitenbergJrBehavior object. * * @param initJoBot TODO PARAM: DOCUMENT ME! * @param initServiceTick TODO PARAM: DOCUMENT ME! * @param servicePeriod TODO PARAM: DOCUMENT ME! * @param dipValue TODO PARAM: DOCUMENT ME! */ public BraitenbergBehavior(JobotBaseController initJoBot, PeriodicTimer initServiceTick, int servicePeriod, int dipValue) { super(initJoBot, initServiceTick, servicePeriod); dip = dipValue; } /** * TODO METHOD: DOCUMENT ME! * * @param value TODO PARAM: param description * * @return $returnType$ TODO RETURN: return description */ private int scale(int value) { if (value > 100) { return 100; } else { return value; } } /** * TODO METHOD: DOCUMENT ME! */ public void doBehavior() { int s0 = 0; int s1 = 0; int vx = 0; int vy = 0; s0 = getJoBot().getSensor(0); s1 = getJoBot().getSensor(1); if (dip == 0) { vx = s0; vy = s1; } if (dip == 1) { vx = s1; vy = s0; } if (dip == 2) { vx = -s0; vy = -s1; } if (dip == 3) { vx = -s1; vy = -s0; } getJoBot().setStatusLeds(false, vx == 0, vy == 0); getJoBot().drive(vx, vy); } }
1,818
0.590784
0.558969
100
16.23
17.934801
89
false
false
0
0
0
0
0
0
1.51
false
false
2
9aba4a7dfc97d293ea8a2c2591cd6a42b7cea298
5,772,436,083,655
c7dc8f03385c970cfec3da708f95402b60cf7ed8
/harec-web/src/main/java/pe/com/bbva/harec/service/ProvinciaService.java
3677f58090ec3968c07e67dcb0d127bcf802fd36
[]
no_license
balderasalberto/sarx3
https://github.com/balderasalberto/sarx3
021d5ba65d1c5f08e97e1ea6c22361d3cefd45b1
75c3074034136106bcfd320e11143f500aebcbce
refs/heads/master
2021-01-10T14:04:07.931000
2014-09-11T15:50:42
2014-09-11T15:50:42
36,672,608
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pe.com.bbva.harec.service; import java.util.List; import pe.com.bbva.harec.model.Provincia; import pe.com.bbva.harec.model.Valor; public interface ProvinciaService extends BaseService<Provincia, Long> { public List<Provincia> listarTodos(); public void registrarProvincia(Provincia provincia); public void registrarProvincia(List<Provincia> listaProvincia, Valor estado); public void inactivarRegistros(List<Provincia> listaProvincia, Valor estado); }
UTF-8
Java
491
java
ProvinciaService.java
Java
[]
null
[]
package pe.com.bbva.harec.service; import java.util.List; import pe.com.bbva.harec.model.Provincia; import pe.com.bbva.harec.model.Valor; public interface ProvinciaService extends BaseService<Provincia, Long> { public List<Provincia> listarTodos(); public void registrarProvincia(Provincia provincia); public void registrarProvincia(List<Provincia> listaProvincia, Valor estado); public void inactivarRegistros(List<Provincia> listaProvincia, Valor estado); }
491
0.773931
0.773931
17
26.882353
28.711306
78
false
false
0
0
0
0
0
0
1.058824
false
false
2
ca9748580bdbddafe966ed00631f9ab93ac9da99
26,671,746,931,905
d18d1d80af84224076dcbf958ea348a44f84529d
/WrittenExamination/src/Alibaba_20200323/problem1_1.java
07f9a6ed1cad3db6471475508897dafb0107107e
[]
no_license
Finallap/JavaStudy2019
https://github.com/Finallap/JavaStudy2019
dd2420825b2da63d5208e8cfb6ebf6e875c42f7a
67c74bcd1cb05af01c8aa5ad38dd6954b85a8b4b
refs/heads/master
2022-12-23T06:40:37.897000
2020-09-09T06:26:59
2020-09-09T06:26:59
207,821,931
1
0
null
false
2022-12-16T15:42:13
2019-09-11T13:40:08
2020-10-23T08:28:30
2022-12-16T15:42:10
6,060
1
0
17
Java
false
false
package Alibaba_20200323; import java.util.Scanner; /** * @description: problem1 * @date: 2020/3/23 18:52 * @author: Finallap * @version: 1.0 */ public class problem1_1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int num = in.nextInt(); System.out.println(func1(num)); } } final static int M = 1000000007; private static long fastPow2(int n) { if (n == 0) return 1; if (n == 1) return 2; long ans = 1; long base = 2; while (n != 0) { if ((n & 1) == 1) ans = ((ans % M) * (base % M)) % M; base = ((base % M) * (base % M)) % M; n >>= 1; } return ans % M; } //n*2^(n-1) % 1000000007 private static int func1(int n) { return (int) (((n % M) * (fastPow2(n - 1) % M)) % M); } }
UTF-8
Java
940
java
problem1_1.java
Java
[ { "context": "on: problem1\n * @date: 2020/3/23 18:52\n * @author: Finallap\n * @version: 1.0\n */\npublic class problem1_1 {\n ", "end": 130, "score": 0.9995205402374268, "start": 122, "tag": "NAME", "value": "Finallap" } ]
null
[]
package Alibaba_20200323; import java.util.Scanner; /** * @description: problem1 * @date: 2020/3/23 18:52 * @author: Finallap * @version: 1.0 */ public class problem1_1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int num = in.nextInt(); System.out.println(func1(num)); } } final static int M = 1000000007; private static long fastPow2(int n) { if (n == 0) return 1; if (n == 1) return 2; long ans = 1; long base = 2; while (n != 0) { if ((n & 1) == 1) ans = ((ans % M) * (base % M)) % M; base = ((base % M) * (base % M)) % M; n >>= 1; } return ans % M; } //n*2^(n-1) % 1000000007 private static int func1(int n) { return (int) (((n % M) * (fastPow2(n - 1) % M)) % M); } }
940
0.468085
0.403191
40
22.5
16.300306
61
false
false
0
0
0
0
0
0
0.375
false
false
2
1ff5a126a7b48a93574ebb0f514503ad632ba230
21,715,354,682,642
57af9211d1c3cb23cd0b399b570168c044f1e3f0
/src/test/java/stepDefs/DocumentationPageStepDefs.java
098efdc388c198a8e64aa20cfcccdb86029c605c
[]
no_license
jeevans2404/Here
https://github.com/jeevans2404/Here
4122b2a981c0b9029016365be25d13abf52cd6a5
d628b51b9ba43090e2e89f5d7de7c04774f85806
refs/heads/master
2021-04-13T18:16:36.444000
2020-03-22T15:39:25
2020-03-22T15:39:25
249,178,399
0
0
null
false
2020-10-13T20:33:32
2020-03-22T12:27:38
2020-03-22T15:40:05
2020-10-13T20:33:31
22
0
0
1
Java
false
false
package stepDefs; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.Iterator; import java.util.List; import java.util.Set; public class DocumentationPageStepDefs { public WebDriver driver; public static final Logger LOGGER = LogManager.getLogger(DocumentationPageStepDefs.class); @Given("^launch url for Here website \"([^\"]*)\"$") public void launchUrlForHereWebsite(String url) throws Throwable { System.setProperty("webdriver.gecko.driver","C:\\drive\\installation\\drivers\\geckodriver.exe"); driver = new FirefoxDriver(); if (System.getProperty("os.name").contains("Windows")){ driver.get(url.toString().replaceAll("/", "\\\\")); } } @Then("^Navigate to Documentation page$") public void navigateToDocumentationPage() throws Throwable{ LOGGER.info("Step Defs: Navigating to Doc page"); navigateToDocumentPage(); } @And("^verify active Documentation link in Documentaion page$") public void verifyActiveDocumentationLinkInDocumentaionPage() throws Throwable{ LOGGER.info("separate out the Documention links and verify"); List<WebElement> docLinks = driver.findElements(By.xpath("//span[@class='cta__content'][contains(text(),'Documentation')]")); System.out.println(docLinks.size()); String title=null; String parentWindow = driver.getWindowHandle(); String currentUrl = driver.getCurrentUrl(); for(int i=0; i<docLinks.size(); i++){ docLinks.get(i).click(); Thread.sleep(4000); Set<String> allWindowHandles = driver.getWindowHandles(); Iterator<String> itr = allWindowHandles.iterator(); for(String handle : allWindowHandles) { System.out.println("Window handle - > " + handle); driver.switchTo().window(handle); Thread.sleep(4000); title = driver.getTitle(); System.out.println("Page is active and title is: "+title); break; } driver.switchTo().window(parentWindow); } driver.get(currentUrl); } @Then("^close the browser$") public void closeTheBrowser() throws Throwable{ LOGGER.info("Closing all the browser "); Thread.sleep(3000); driver.quit(); } public void navigateToDocumentPage() throws Throwable{ LOGGER.info("Navigating to Document Page"); Thread.sleep(3000); driver.findElement(By.xpath("//li[@class='menu-list-item menu-list-item--primary has-flyout binded']" + "//a[@class='menu-link menu-link--primary']//span[@class='link-content'][contains(text(),'Documentation')]")).click(); Thread.sleep(5000); } }
UTF-8
Java
3,101
java
DocumentationPageStepDefs.java
Java
[]
null
[]
package stepDefs; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.Iterator; import java.util.List; import java.util.Set; public class DocumentationPageStepDefs { public WebDriver driver; public static final Logger LOGGER = LogManager.getLogger(DocumentationPageStepDefs.class); @Given("^launch url for Here website \"([^\"]*)\"$") public void launchUrlForHereWebsite(String url) throws Throwable { System.setProperty("webdriver.gecko.driver","C:\\drive\\installation\\drivers\\geckodriver.exe"); driver = new FirefoxDriver(); if (System.getProperty("os.name").contains("Windows")){ driver.get(url.toString().replaceAll("/", "\\\\")); } } @Then("^Navigate to Documentation page$") public void navigateToDocumentationPage() throws Throwable{ LOGGER.info("Step Defs: Navigating to Doc page"); navigateToDocumentPage(); } @And("^verify active Documentation link in Documentaion page$") public void verifyActiveDocumentationLinkInDocumentaionPage() throws Throwable{ LOGGER.info("separate out the Documention links and verify"); List<WebElement> docLinks = driver.findElements(By.xpath("//span[@class='cta__content'][contains(text(),'Documentation')]")); System.out.println(docLinks.size()); String title=null; String parentWindow = driver.getWindowHandle(); String currentUrl = driver.getCurrentUrl(); for(int i=0; i<docLinks.size(); i++){ docLinks.get(i).click(); Thread.sleep(4000); Set<String> allWindowHandles = driver.getWindowHandles(); Iterator<String> itr = allWindowHandles.iterator(); for(String handle : allWindowHandles) { System.out.println("Window handle - > " + handle); driver.switchTo().window(handle); Thread.sleep(4000); title = driver.getTitle(); System.out.println("Page is active and title is: "+title); break; } driver.switchTo().window(parentWindow); } driver.get(currentUrl); } @Then("^close the browser$") public void closeTheBrowser() throws Throwable{ LOGGER.info("Closing all the browser "); Thread.sleep(3000); driver.quit(); } public void navigateToDocumentPage() throws Throwable{ LOGGER.info("Navigating to Document Page"); Thread.sleep(3000); driver.findElement(By.xpath("//li[@class='menu-list-item menu-list-item--primary has-flyout binded']" + "//a[@class='menu-link menu-link--primary']//span[@class='link-content'][contains(text(),'Documentation')]")).click(); Thread.sleep(5000); } }
3,101
0.644308
0.636891
93
32.344086
30.813869
134
false
false
0
0
0
0
0
0
0.548387
false
false
2
2c21277855073caa5b35054ec4e42b1030043843
4,458,176,110,418
4a627944b713338ca778834b911a03145bf48a43
/src/main/java/com/cpu/sistema_horario_java/app/carga/CargaAcademicaModelAssembler.java
8dc3d7e8f93b40bb6d8ad9b419acd332adf53709
[]
no_license
mbastidasluis/horarios
https://github.com/mbastidasluis/horarios
91d2b6bf942ea9d7f7db0c53416d683579473de7
58c9649e5e660b4352d8d444085c98e0cb453d31
refs/heads/master
2021-07-19T07:09:34.287000
2020-03-09T18:03:19
2020-03-09T18:03:19
245,479,148
0
0
null
false
2021-03-31T21:50:26
2020-03-06T17:25:42
2020-03-09T18:03:22
2021-03-31T21:50:25
130
0
0
1
Java
false
false
package com.cpu.sistema_horario_java.app.carga; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; import com.cpu.sistema_horario_java.app.controller.api.v1.CargaAcademicaController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.stereotype.Component; @Component public class CargaAcademicaModelAssembler implements RepresentationModelAssembler<CargaAcademicaDTO, EntityModel<CargaAcademicaDTO>> { @Override public EntityModel<CargaAcademicaDTO> toModel(CargaAcademicaDTO dto) { return new EntityModel<>(dto, linkTo(methodOn(CargaAcademicaController.class).buscar(dto.getId())).withSelfRel(), linkTo(methodOn(CargaAcademicaController.class).listar()).withRel("cargas_academicas")); } }
UTF-8
Java
952
java
CargaAcademicaModelAssembler.java
Java
[]
null
[]
package com.cpu.sistema_horario_java.app.carga; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; import com.cpu.sistema_horario_java.app.controller.api.v1.CargaAcademicaController; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.server.RepresentationModelAssembler; import org.springframework.stereotype.Component; @Component public class CargaAcademicaModelAssembler implements RepresentationModelAssembler<CargaAcademicaDTO, EntityModel<CargaAcademicaDTO>> { @Override public EntityModel<CargaAcademicaDTO> toModel(CargaAcademicaDTO dto) { return new EntityModel<>(dto, linkTo(methodOn(CargaAcademicaController.class).buscar(dto.getId())).withSelfRel(), linkTo(methodOn(CargaAcademicaController.class).listar()).withRel("cargas_academicas")); } }
952
0.802521
0.801471
22
42.31818
41.259033
134
false
false
0
0
0
0
0
0
0.5
false
false
2
16ce484ee23111493aee42357fd0a1e82e0095b1
32,203,664,822,762
e8779f04765463c4520e52e31976a163e186511c
/src/edu/ufl/LevelWin.java
ba91ab870bbcadb343b468376b998a45ffb0c597
[]
no_license
jbirlingmair/Super-Gator-World
https://github.com/jbirlingmair/Super-Gator-World
128260af62b8b279e137f58ca095e39a4a4957f3
1d9214b7ff59354dff08e4c671f8535a6e64d8d8
refs/heads/master
2020-12-07T05:25:35.095000
2016-06-16T01:18:35
2016-06-16T01:18:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ufl; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; public class LevelWin extends Activity { protected boolean _active = true; protected int _showTime = 5000; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.levelwin); // Creates and loads SoundManager SoundManager.getInstance(); SoundManager.initSounds(this.getApplicationContext()); SoundManager.loadSounds(); SoundManager.loadMedia(); SoundManager.playMedia(1); Thread winThread = new Thread() { @Override public void run() { try { int waited = 0; while(_active && (waited < _showTime)) { sleep(100); if(_active) { waited += 100; } } } catch(InterruptedException e) { // do nothing } finally { SoundManager.pauseMedia(); SoundManager.resetMedia(); finish(); // interrupt(); } } }; winThread.start(); } @Override protected void onPause(){ super.onPause(); finish(); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { _active = false; } return true; } }
UTF-8
Java
1,807
java
LevelWin.java
Java
[]
null
[]
package edu.ufl; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; public class LevelWin extends Activity { protected boolean _active = true; protected int _showTime = 5000; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.levelwin); // Creates and loads SoundManager SoundManager.getInstance(); SoundManager.initSounds(this.getApplicationContext()); SoundManager.loadSounds(); SoundManager.loadMedia(); SoundManager.playMedia(1); Thread winThread = new Thread() { @Override public void run() { try { int waited = 0; while(_active && (waited < _showTime)) { sleep(100); if(_active) { waited += 100; } } } catch(InterruptedException e) { // do nothing } finally { SoundManager.pauseMedia(); SoundManager.resetMedia(); finish(); // interrupt(); } } }; winThread.start(); } @Override protected void onPause(){ super.onPause(); finish(); } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { _active = false; } return true; } }
1,807
0.472053
0.465412
66
26.348484
16.291374
62
false
false
0
0
0
0
0
0
0.454545
false
false
2
7a22772edb7095f9d7212c8b311d39dbf00dd659
16,243,566,358,931
6d35b49abadef2370e9689cf474956a3bc0a0e01
/app/src/main/java/com/pruebabci/MainActivity.java
004f9bddbb65ac63a975ee1dc817c314d44fe3ef
[]
no_license
cholemon/bci
https://github.com/cholemon/bci
6c8fbc171950949e1957150e63c5e3d669120ce2
b6ee1552aa095cc49f83cfe2a2ca7ae44dfeaa9d
refs/heads/master
2020-06-16T01:17:07.976000
2019-09-16T02:01:16
2019-09-16T02:01:16
195,442,113
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pruebabci; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import com.google.android.material.textfield.TextInputLayout; import androidx.appcompat.app.AppCompatActivity; import controller.ControlMainActivity; import android.os.StrictMode; public class MainActivity extends AppCompatActivity { private ControlMainActivity control; public TextInputLayout layout_busqueda; public EditText txt_busqueda; public Button btn_buscar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); init_components(); init_events(); } private void init_components(){ layout_busqueda = findViewById(R.id.layout_busqueda); txt_busqueda = findViewById(R.id.txt_busqueda); btn_buscar = findViewById(R.id.btn_buscar); } private void init_events(){ control = new ControlMainActivity(this); btn_buscar.setOnClickListener(control); } }
UTF-8
Java
1,224
java
MainActivity.java
Java
[]
null
[]
package com.pruebabci; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import com.google.android.material.textfield.TextInputLayout; import androidx.appcompat.app.AppCompatActivity; import controller.ControlMainActivity; import android.os.StrictMode; public class MainActivity extends AppCompatActivity { private ControlMainActivity control; public TextInputLayout layout_busqueda; public EditText txt_busqueda; public Button btn_buscar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); init_components(); init_events(); } private void init_components(){ layout_busqueda = findViewById(R.id.layout_busqueda); txt_busqueda = findViewById(R.id.txt_busqueda); btn_buscar = findViewById(R.id.btn_buscar); } private void init_events(){ control = new ControlMainActivity(this); btn_buscar.setOnClickListener(control); } }
1,224
0.720588
0.720588
42
28.142857
23.560026
99
false
false
0
0
0
0
0
0
0.547619
false
false
2
9f4932ac1dfb52d42fccdb2702ffc09c377424b3
29,755,533,485,432
5b370ace963d4aa6824a91023a7ed3636e5c503b
/server-demo/src/main/java/show/tmh/rpc/demo/EchoServiceImpl.java
2651048113e1452e982a61817e254c1bbedbaaec
[]
no_license
yuh666/tmh-rpc
https://github.com/yuh666/tmh-rpc
2229549deb15a3ea202709e6c140cf37da14638f
170fe8f0ca5db8fe71be009a60e567ecfcb09a37
refs/heads/master
2022-12-27T04:17:17.114000
2020-06-19T05:36:00
2020-06-19T05:36:00
272,137,930
0
0
null
false
2020-10-13T22:47:10
2020-06-14T05:16:13
2020-06-19T05:38:39
2020-10-13T22:47:09
58
0
0
2
Java
false
false
package show.tmh.rpc.demo; import show.tmh.rpc.client.annotation.RpcMember; /** * @author zy-user */ public class EchoServiceImpl implements EchoService { @Override public String echo(String words) { return words; } }
UTF-8
Java
243
java
EchoServiceImpl.java
Java
[ { "context": "h.rpc.client.annotation.RpcMember;\n\n/**\n * @author zy-user\n */\npublic class EchoServiceImpl implements EchoS", "end": 100, "score": 0.999576210975647, "start": 93, "tag": "USERNAME", "value": "zy-user" } ]
null
[]
package show.tmh.rpc.demo; import show.tmh.rpc.client.annotation.RpcMember; /** * @author zy-user */ public class EchoServiceImpl implements EchoService { @Override public String echo(String words) { return words; } }
243
0.687243
0.687243
14
16.357143
17.858999
53
false
false
0
0
0
0
0
0
0.214286
false
false
2
a8f2d98599cce38975901e89a74142211655013c
33,234,456,981,762
8f16fb90e641bf20450633fb3cd0d5d2a04079cb
/Themaopdracht5/src/com/appspot/Accent/controller/CompetentieOverzichtServlet.java
1b4a6306f027d7a95c7411278fa5e73fadec0dab
[]
no_license
colin-ch/ThemaOpdracht5
https://github.com/colin-ch/ThemaOpdracht5
c20423098b6c692da17ad29541e5eb6dd6c74304
f52dfecd70a8a8d6f7b50eb332723d24446316b3
refs/heads/master
2021-01-20T08:48:51.983000
2014-03-13T11:53:48
2014-03-13T11:53:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.appspot.Accent.controller; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.appspot.Accent.model.Competentie; import com.appspot.Accent.model.Stelling; import com.appspot.Accent.model.service.CompetentieOfyDAOImpl; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; public class CompetentieOverzichtServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Objectify ofy; private static final Logger log = Logger.getLogger(BeoordelingAanmakenServlet.class.getName()); RequestDispatcher rd = null; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ofy = ObjectifyService.begin(); ArrayList<Competentie> competenties = new ArrayList<Competentie>(); CompetentieOfyDAOImpl cod = new CompetentieOfyDAOImpl(); competenties = (ArrayList<Competentie>) cod.getAllCompetenties(); loop: for (Competentie c : competenties) { String id = ""+c.getEigenId(); if (req.getParameter("competentie").equals(id)) { String msgs = c.getTitel(); req.setAttribute("msgs", msgs); rd = req.getRequestDispatcher("StellingOverzicht.jsp"); break loop; }else{ String msgs = "geen competenties gevonden"; req.setAttribute("msgs", msgs); rd = req.getRequestDispatcher("StellingOverzicht.jsp"); } } rd.forward(req, resp); } }
UTF-8
Java
1,683
java
CompetentieOverzichtServlet.java
Java
[]
null
[]
package com.appspot.Accent.controller; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.appspot.Accent.model.Competentie; import com.appspot.Accent.model.Stelling; import com.appspot.Accent.model.service.CompetentieOfyDAOImpl; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyService; public class CompetentieOverzichtServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Objectify ofy; private static final Logger log = Logger.getLogger(BeoordelingAanmakenServlet.class.getName()); RequestDispatcher rd = null; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ofy = ObjectifyService.begin(); ArrayList<Competentie> competenties = new ArrayList<Competentie>(); CompetentieOfyDAOImpl cod = new CompetentieOfyDAOImpl(); competenties = (ArrayList<Competentie>) cod.getAllCompetenties(); loop: for (Competentie c : competenties) { String id = ""+c.getEigenId(); if (req.getParameter("competentie").equals(id)) { String msgs = c.getTitel(); req.setAttribute("msgs", msgs); rd = req.getRequestDispatcher("StellingOverzicht.jsp"); break loop; }else{ String msgs = "geen competenties gevonden"; req.setAttribute("msgs", msgs); rd = req.getRequestDispatcher("StellingOverzicht.jsp"); } } rd.forward(req, resp); } }
1,683
0.769459
0.768865
54
30.166666
23.972013
96
false
false
0
0
0
0
0
0
2.037037
false
false
2
2146ba51977da1ae4e0884c3f9c793fdca086162
18,683,107,776,806
884f9ff56c30977826058c70ba19206ea9cc7b32
/src/main/java/com/nationwide/sre/Encryptor.java
44feb3aa7312327863acaae84f1ba3516bd4f242
[]
no_license
mrfawy/Encryption-java
https://github.com/mrfawy/Encryption-java
5108b7692485c7b6a4a6130e38d0283ecb6a97b0
b54ff9359800d8679fbe98a0ead2f09b77d7abb2
refs/heads/master
2016-09-06T07:14:39.718000
2015-03-18T20:29:05
2015-03-18T20:29:05
32,482,115
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nationwide.sre; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; import org.apache.commons.codec.binary.Base64; public class Encryptor { /** * Encrypt plainText using AES symmetric key algorithm and encode the result into Base64 * AES Specs :ECB mode and PKCS5Padding schema * @param plainText message text * @param secretKey * @return */ public static String encryptBase64(String plainText, SecretKey secretKey) { try { byte[] encryptedBytes = Encryptor.encrypt(plainText, secretKey); String encryptedText = Base64.encodeBase64String(encryptedBytes); return encryptedText; } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] encrypt(String plainText, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] plainTextByte = plainText.getBytes(); byte[] encryptedByte = cipher.doFinal(plainTextByte); byte[] IVByte=cipher.getIV(); //result has first 16 bytes as IV + cipherMsg byte[] result=combineBytes(IVByte,encryptedByte); return result; } private static byte[] combineBytes(byte[] a,byte[] b){ byte[] combined = new byte[a.length + b.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < a.length ? a[i] : b[i - a.length]; } return combined; } }
UTF-8
Java
1,440
java
Encryptor.java
Java
[]
null
[]
package com.nationwide.sre; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; import org.apache.commons.codec.binary.Base64; public class Encryptor { /** * Encrypt plainText using AES symmetric key algorithm and encode the result into Base64 * AES Specs :ECB mode and PKCS5Padding schema * @param plainText message text * @param secretKey * @return */ public static String encryptBase64(String plainText, SecretKey secretKey) { try { byte[] encryptedBytes = Encryptor.encrypt(plainText, secretKey); String encryptedText = Base64.encodeBase64String(encryptedBytes); return encryptedText; } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] encrypt(String plainText, SecretKey secretKey) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] plainTextByte = plainText.getBytes(); byte[] encryptedByte = cipher.doFinal(plainTextByte); byte[] IVByte=cipher.getIV(); //result has first 16 bytes as IV + cipherMsg byte[] result=combineBytes(IVByte,encryptedByte); return result; } private static byte[] combineBytes(byte[] a,byte[] b){ byte[] combined = new byte[a.length + b.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < a.length ? a[i] : b[i - a.length]; } return combined; } }
1,440
0.707639
0.697222
54
25.666666
24.587711
89
false
false
0
0
0
0
0
0
1.888889
false
false
2
7ea9c7d9703c97c37cf22f220b7947fbb73fbbfe
25,812,753,499,271
45b16f78db3cdc43980bc6701944e976eda16b2e
/FXzadanie1/src/kryptologia/Decode.java
2e0aa03c147124d8d78b11b772469eae374f3d64
[]
no_license
914840/JavaEE
https://github.com/914840/JavaEE
23f16c620dfc7151bbbeb948035195d770e5b768
45511ddbb777108e5c37d4a851dbb52b813f9578
refs/heads/master
2020-04-15T05:12:53.494000
2019-01-25T13:43:52
2019-01-25T13:43:52
164,413,042
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kryptologia; import java.util.regex.Pattern; import sun.net.www.content.text.plain; public class Decode { private String decodeText, plainText; public Decode() { } private void setPlainText(String str) { this.plainText = str; } private void setDecodeText(String str) { this.decodeText = str; } public String getPlainText() { return this.plainText; } public void plainText(String str) { this.setDecodeText(str); // plain String letter = ""; String arg = ""; String text = ""; String num = ""; int j = 0; for (int i = 0, count = 1 ; i < decodeText.length(); i++) { // TODO porównać znami za pomocą wyrażeń regularnych // 1. czy string pasuje do wzoru [a-Z_0-9][0-9][0-9 lub ,] - jeśli przecinek to trzeba wypisać znak i zacząć ilczyć od nowa. letter = decodeText.charAt(i) + ""; if( count == 1) { arg = letter; text += arg; count++; } else if (count > 1) { if( letter.matches("[0-9]")) { // w tym miejscu obsługa braku przecinka na koncu wiersza. num += letter; count++; if (i+1 == decodeText.length()) { j = Integer.parseInt(num); for (int a = 1; a < j; a++) { text += arg; } } } else if( letter.matches("\\D[^,]")) { arg = letter; text += arg; num = ""; count++; // błędny kod } else if( letter.matches(",")) { if(num.matches("")) { text += letter; count++; arg = letter; } else { j = Integer.parseInt(num); for (int a = 1; a < j; a++) { text += arg; } num = ""; arg = ""; count = 1; } } } } setPlainText(text); } }
WINDOWS-1250
Java
1,913
java
Decode.java
Java
[]
null
[]
package kryptologia; import java.util.regex.Pattern; import sun.net.www.content.text.plain; public class Decode { private String decodeText, plainText; public Decode() { } private void setPlainText(String str) { this.plainText = str; } private void setDecodeText(String str) { this.decodeText = str; } public String getPlainText() { return this.plainText; } public void plainText(String str) { this.setDecodeText(str); // plain String letter = ""; String arg = ""; String text = ""; String num = ""; int j = 0; for (int i = 0, count = 1 ; i < decodeText.length(); i++) { // TODO porównać znami za pomocą wyrażeń regularnych // 1. czy string pasuje do wzoru [a-Z_0-9][0-9][0-9 lub ,] - jeśli przecinek to trzeba wypisać znak i zacząć ilczyć od nowa. letter = decodeText.charAt(i) + ""; if( count == 1) { arg = letter; text += arg; count++; } else if (count > 1) { if( letter.matches("[0-9]")) { // w tym miejscu obsługa braku przecinka na koncu wiersza. num += letter; count++; if (i+1 == decodeText.length()) { j = Integer.parseInt(num); for (int a = 1; a < j; a++) { text += arg; } } } else if( letter.matches("\\D[^,]")) { arg = letter; text += arg; num = ""; count++; // błędny kod } else if( letter.matches(",")) { if(num.matches("")) { text += letter; count++; arg = letter; } else { j = Integer.parseInt(num); for (int a = 1; a < j; a++) { text += arg; } num = ""; arg = ""; count = 1; } } } } setPlainText(text); } }
1,913
0.479474
0.47
91
19.879122
18.864372
130
false
false
0
0
0
0
0
0
3.736264
false
false
2
c39bc5767e14d1826b946942c729b90ed65c9056
28,595,892,306,772
ba8dbe2fc0ac1c7e1658020d306b55b056724cf6
/mdw-services/src/com/centurylink/mdw/services/user/UserServicesImpl.java
a338e64768fae638cba9304599ff6c371d62ba80
[ "Apache-2.0" ]
permissive
magrawa/MDW
https://github.com/magrawa/MDW
f04d90be6858a1503d33be6397cbd4dc3f30de75
1628973c9d19b00e2c4e5ef147278bb94caa812c
refs/heads/master
2021-01-23T04:19:25.642000
2017-03-24T18:05:10
2017-03-24T18:05:10
86,170,562
1
0
null
true
2017-03-25T16:13:48
2017-03-25T16:13:48
2017-03-23T22:04:15
2017-03-24T18:05:14
271,530
0
0
0
null
null
null
/* * Copyright (C) 2017 CenturyLink, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.centurylink.mdw.services.user; import java.util.HashMap; import java.util.List; import com.centurylink.mdw.cache.CachingException; import com.centurylink.mdw.dataaccess.DataAccess; import com.centurylink.mdw.dataaccess.DataAccessException; import com.centurylink.mdw.dataaccess.DatabaseAccess; import com.centurylink.mdw.model.user.RoleList; import com.centurylink.mdw.model.user.UserAction; import com.centurylink.mdw.model.user.Workgroup; import com.centurylink.mdw.model.user.UserList; import com.centurylink.mdw.model.user.Role; import com.centurylink.mdw.model.user.User; import com.centurylink.mdw.model.user.WorkgroupList; import com.centurylink.mdw.service.data.task.UserGroupCache; import com.centurylink.mdw.service.data.user.UserDataAccess; import com.centurylink.mdw.services.UserServices; public class UserServicesImpl implements UserServices { private UserDataAccess getUserDAO() { DatabaseAccess db = new DatabaseAccess(null); return new UserDataAccess(db); } public WorkgroupList getWorkgroups() throws DataAccessException { List<Workgroup> groups = UserGroupCache.getWorkgroups(); WorkgroupList groupList = new WorkgroupList(groups); groupList.setRetrieveDate(DatabaseAccess.getDbDate()); return groupList; } public RoleList getRoles() throws DataAccessException { List<Role> roles = UserGroupCache.getRoles(); RoleList roleList = new RoleList(roles); roleList.setRetrieveDate(DatabaseAccess.getDbDate()); return roleList; } public UserList getUsers() throws DataAccessException { List<User> users = UserGroupCache.getUsers(); UserList userList = new UserList(users); userList.setRetrieveDate(DatabaseAccess.getDbDate()); return userList; } public UserList getUsers(int start, int pageSize) throws DataAccessException { List<User> users = UserGroupCache.getUsers(start, pageSize); UserList userList = new UserList(users); userList.setRetrieveDate(DatabaseAccess.getDbDate()); userList.setTotal(UserGroupCache.getTotalUsers()); return userList; } public UserList findUsers(String prefix) throws DataAccessException { List<User> users = UserGroupCache.findUsers(prefix); return new UserList(users); } public UserList findWorkgroupUsers(String[] workgroups, String prefix) throws DataAccessException { try { List<User> users = UserGroupCache.findUsers(workgroups, prefix); return new UserList(users); } catch (CachingException ex) { throw new DataAccessException(ex.getMessage(), ex); } } /** * Does not include non-public attributes. * Includes empty values for all public attributes. */ public User getUser(String cuid) throws DataAccessException { try { User user = UserGroupCache.getUser(cuid); if (user == null) throw new CachingException(""); // add empty attributes if (user.getAttributes() == null) user.setAttributes(new HashMap<String,String>()); for (String name : UserGroupCache.getUserAttributeNames()) { if (!user.getAttributes().containsKey(name)) user.setAttribute(name, null); // substitute friendly attribute names if (user.getAttributes().containsKey(User.OLD_EMAIL_ADDRESS)) { String oldEmail = user.getAttributes().remove(User.OLD_EMAIL_ADDRESS); if (user.getAttribute(User.EMAIL_ADDRESS) == null) user.setAttribute(User.EMAIL_ADDRESS, oldEmail); } if (user.getAttributes().containsKey(User.OLD_PHONE_NUMBER)) { String oldPhone = user.getAttributes().remove(User.OLD_PHONE_NUMBER); if (user.getAttribute(User.PHONE_NUMBER) == null) user.setAttribute(User.PHONE_NUMBER, oldPhone); } } return user; } catch (CachingException ex) { throw new DataAccessException("Cannot find user: " + cuid, ex); } } public Workgroup getWorkgroup(String groupName) throws DataAccessException { try { return UserGroupCache.getWorkgroup(groupName); } catch (CachingException ex) { throw new DataAccessException("Cannot find workgroup: " + groupName, ex); } } public Role getRole(String roleName) throws DataAccessException { try { return UserGroupCache.getRole(roleName); } catch (CachingException ex) { throw new DataAccessException("Cannot find role: " + roleName, ex); } } public void auditLog(UserAction userAction) throws DataAccessException { DataAccess.getUserDataAccess(new DatabaseAccess(null)).auditLogUserAction(userAction);; } public void createWorkgroup(Workgroup workgroup) throws DataAccessException { workgroup.setId(getUserDAO().saveGroup(workgroup)); UserGroupCache.set(workgroup); } public void updateWorkgroup(Workgroup workgroup) throws DataAccessException { getUserDAO().saveGroup(workgroup); UserGroupCache.set(workgroup); } public void deleteWorkgroup(String name) throws DataAccessException { UserDataAccess dao = getUserDAO(); Workgroup group = dao.getGroup(name); if (group == null) throw new DataAccessException("Workgroup: " + name + " does not exist"); dao.deleteGroup(group.getId()); UserGroupCache.remove(group); } public void createUser(User user) throws DataAccessException { user.setId(getUserDAO().saveUser(user)); getUserDAO().updateUserAttributes(user.getId(), user.getAttributes()); UserGroupCache.set(user); } public void updateUser(User user) throws DataAccessException { user.setId(getUserDAO().saveUser(user)); getUserDAO().updateUserAttributes(user.getId(), user.getAttributes()); UserGroupCache.set(user); } public void deleteUser(String cuid) throws DataAccessException { UserDataAccess dao = getUserDAO(); User user = dao.getUser(cuid); if (cuid == null) throw new DataAccessException("User: " + cuid + " does not exist"); dao.deleteUser(user.getId()); UserGroupCache.remove(user); } public void addUserToWorkgroup(String cuid, String group) throws DataAccessException { try { getUserDAO().addUserToGroup(cuid, group); UserGroupCache.clear(); } catch (Exception ex) { throw new DataAccessException(ex.getMessage(), ex); } } public void removeUserFromWorkgroup(String cuid, String group) throws DataAccessException { getUserDAO().removeUserFromGroup(cuid, group); UserGroupCache.clear(); } public void addUserToRole(String cuid, String role) throws DataAccessException { getUserDAO().addUserToRole(cuid, role); UserGroupCache.clear(); } public void removeUserFromRole(String cuid, String role) throws DataAccessException { getUserDAO().removeUserFromRole(cuid, role); UserGroupCache.clear(); } public void createRole(Role role) throws DataAccessException { role.setId(getUserDAO().saveRole(role)); UserGroupCache.set(role); } public void updateRole(Role role) throws DataAccessException { getUserDAO().saveRole(role); UserGroupCache.set(role); } public void deleteRole(String name) throws DataAccessException { UserDataAccess dao = getUserDAO(); Role role = dao.getRole(name); if (role == null) throw new DataAccessException("Role: " + name + " does not exist"); dao.deleteRole(role.getId()); UserGroupCache.remove(role); } }
UTF-8
Java
8,699
java
UserServicesImpl.java
Java
[]
null
[]
/* * Copyright (C) 2017 CenturyLink, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.centurylink.mdw.services.user; import java.util.HashMap; import java.util.List; import com.centurylink.mdw.cache.CachingException; import com.centurylink.mdw.dataaccess.DataAccess; import com.centurylink.mdw.dataaccess.DataAccessException; import com.centurylink.mdw.dataaccess.DatabaseAccess; import com.centurylink.mdw.model.user.RoleList; import com.centurylink.mdw.model.user.UserAction; import com.centurylink.mdw.model.user.Workgroup; import com.centurylink.mdw.model.user.UserList; import com.centurylink.mdw.model.user.Role; import com.centurylink.mdw.model.user.User; import com.centurylink.mdw.model.user.WorkgroupList; import com.centurylink.mdw.service.data.task.UserGroupCache; import com.centurylink.mdw.service.data.user.UserDataAccess; import com.centurylink.mdw.services.UserServices; public class UserServicesImpl implements UserServices { private UserDataAccess getUserDAO() { DatabaseAccess db = new DatabaseAccess(null); return new UserDataAccess(db); } public WorkgroupList getWorkgroups() throws DataAccessException { List<Workgroup> groups = UserGroupCache.getWorkgroups(); WorkgroupList groupList = new WorkgroupList(groups); groupList.setRetrieveDate(DatabaseAccess.getDbDate()); return groupList; } public RoleList getRoles() throws DataAccessException { List<Role> roles = UserGroupCache.getRoles(); RoleList roleList = new RoleList(roles); roleList.setRetrieveDate(DatabaseAccess.getDbDate()); return roleList; } public UserList getUsers() throws DataAccessException { List<User> users = UserGroupCache.getUsers(); UserList userList = new UserList(users); userList.setRetrieveDate(DatabaseAccess.getDbDate()); return userList; } public UserList getUsers(int start, int pageSize) throws DataAccessException { List<User> users = UserGroupCache.getUsers(start, pageSize); UserList userList = new UserList(users); userList.setRetrieveDate(DatabaseAccess.getDbDate()); userList.setTotal(UserGroupCache.getTotalUsers()); return userList; } public UserList findUsers(String prefix) throws DataAccessException { List<User> users = UserGroupCache.findUsers(prefix); return new UserList(users); } public UserList findWorkgroupUsers(String[] workgroups, String prefix) throws DataAccessException { try { List<User> users = UserGroupCache.findUsers(workgroups, prefix); return new UserList(users); } catch (CachingException ex) { throw new DataAccessException(ex.getMessage(), ex); } } /** * Does not include non-public attributes. * Includes empty values for all public attributes. */ public User getUser(String cuid) throws DataAccessException { try { User user = UserGroupCache.getUser(cuid); if (user == null) throw new CachingException(""); // add empty attributes if (user.getAttributes() == null) user.setAttributes(new HashMap<String,String>()); for (String name : UserGroupCache.getUserAttributeNames()) { if (!user.getAttributes().containsKey(name)) user.setAttribute(name, null); // substitute friendly attribute names if (user.getAttributes().containsKey(User.OLD_EMAIL_ADDRESS)) { String oldEmail = user.getAttributes().remove(User.OLD_EMAIL_ADDRESS); if (user.getAttribute(User.EMAIL_ADDRESS) == null) user.setAttribute(User.EMAIL_ADDRESS, oldEmail); } if (user.getAttributes().containsKey(User.OLD_PHONE_NUMBER)) { String oldPhone = user.getAttributes().remove(User.OLD_PHONE_NUMBER); if (user.getAttribute(User.PHONE_NUMBER) == null) user.setAttribute(User.PHONE_NUMBER, oldPhone); } } return user; } catch (CachingException ex) { throw new DataAccessException("Cannot find user: " + cuid, ex); } } public Workgroup getWorkgroup(String groupName) throws DataAccessException { try { return UserGroupCache.getWorkgroup(groupName); } catch (CachingException ex) { throw new DataAccessException("Cannot find workgroup: " + groupName, ex); } } public Role getRole(String roleName) throws DataAccessException { try { return UserGroupCache.getRole(roleName); } catch (CachingException ex) { throw new DataAccessException("Cannot find role: " + roleName, ex); } } public void auditLog(UserAction userAction) throws DataAccessException { DataAccess.getUserDataAccess(new DatabaseAccess(null)).auditLogUserAction(userAction);; } public void createWorkgroup(Workgroup workgroup) throws DataAccessException { workgroup.setId(getUserDAO().saveGroup(workgroup)); UserGroupCache.set(workgroup); } public void updateWorkgroup(Workgroup workgroup) throws DataAccessException { getUserDAO().saveGroup(workgroup); UserGroupCache.set(workgroup); } public void deleteWorkgroup(String name) throws DataAccessException { UserDataAccess dao = getUserDAO(); Workgroup group = dao.getGroup(name); if (group == null) throw new DataAccessException("Workgroup: " + name + " does not exist"); dao.deleteGroup(group.getId()); UserGroupCache.remove(group); } public void createUser(User user) throws DataAccessException { user.setId(getUserDAO().saveUser(user)); getUserDAO().updateUserAttributes(user.getId(), user.getAttributes()); UserGroupCache.set(user); } public void updateUser(User user) throws DataAccessException { user.setId(getUserDAO().saveUser(user)); getUserDAO().updateUserAttributes(user.getId(), user.getAttributes()); UserGroupCache.set(user); } public void deleteUser(String cuid) throws DataAccessException { UserDataAccess dao = getUserDAO(); User user = dao.getUser(cuid); if (cuid == null) throw new DataAccessException("User: " + cuid + " does not exist"); dao.deleteUser(user.getId()); UserGroupCache.remove(user); } public void addUserToWorkgroup(String cuid, String group) throws DataAccessException { try { getUserDAO().addUserToGroup(cuid, group); UserGroupCache.clear(); } catch (Exception ex) { throw new DataAccessException(ex.getMessage(), ex); } } public void removeUserFromWorkgroup(String cuid, String group) throws DataAccessException { getUserDAO().removeUserFromGroup(cuid, group); UserGroupCache.clear(); } public void addUserToRole(String cuid, String role) throws DataAccessException { getUserDAO().addUserToRole(cuid, role); UserGroupCache.clear(); } public void removeUserFromRole(String cuid, String role) throws DataAccessException { getUserDAO().removeUserFromRole(cuid, role); UserGroupCache.clear(); } public void createRole(Role role) throws DataAccessException { role.setId(getUserDAO().saveRole(role)); UserGroupCache.set(role); } public void updateRole(Role role) throws DataAccessException { getUserDAO().saveRole(role); UserGroupCache.set(role); } public void deleteRole(String name) throws DataAccessException { UserDataAccess dao = getUserDAO(); Role role = dao.getRole(name); if (role == null) throw new DataAccessException("Role: " + name + " does not exist"); dao.deleteRole(role.getId()); UserGroupCache.remove(role); } }
8,699
0.663869
0.66295
225
37.595554
28.036024
103
false
false
0
0
0
0
0
0
0.551111
false
false
2
227d1125cc7430e95ff2fdfef95ec2a417adc150
13,907,104,147,898
fb6e876fcb0ba76ce8786d94a9e188039b0175c2
/O-to-M & M-to-O(Bydirectional)update/src/com/insert/Wifi.java
aadd3ac6bf3915731b6dc56ae9d57b6ea5d7a5ba
[]
no_license
Abhishek83492/Hibernate_XML
https://github.com/Abhishek83492/Hibernate_XML
470bfca19180de45bcc013a9ad34c6c5d3f7204d
e3956b441d5a5b77e6feaf62bd21862ab5c83c40
refs/heads/master
2020-09-26T17:48:17.413000
2019-12-06T10:45:19
2019-12-06T10:45:19
226,305,899
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.insert; public class Wifi { private Integer wifiid; private String wifiname; private Hotspot hotspotid; public Integer getWifiid() { return wifiid; } public void setWifiid(Integer wifiid) { this.wifiid = wifiid; } public String getWifiname() { return wifiname; } public void setWifiname(String wifiname) { this.wifiname = wifiname; } public Hotspot getHotspotid() { return hotspotid; } public void setHotspotid(Hotspot hotspotid) { this.hotspotid = hotspotid; } }
UTF-8
Java
542
java
Wifi.java
Java
[]
null
[]
package com.insert; public class Wifi { private Integer wifiid; private String wifiname; private Hotspot hotspotid; public Integer getWifiid() { return wifiid; } public void setWifiid(Integer wifiid) { this.wifiid = wifiid; } public String getWifiname() { return wifiname; } public void setWifiname(String wifiname) { this.wifiname = wifiname; } public Hotspot getHotspotid() { return hotspotid; } public void setHotspotid(Hotspot hotspotid) { this.hotspotid = hotspotid; } }
542
0.680812
0.680812
30
16.066668
14.456678
46
false
false
0
0
0
0
0
0
1.333333
false
false
2
f2be92ba7213103d37229a53a5158a5871702b23
16,166,256,929,604
1c62563ea506f7baba295c8f401ad590268b16bd
/services/dao-jpa/src/main/java/com/entrego/services/dao/jpa/model/JPABaseRate.java
2ed2c96a9ec2a23438a322486955970f4f4bd324
[]
no_license
mikhail-kulish/entrego-server
https://github.com/mikhail-kulish/entrego-server
b318f932ea5933709c3d23370de4d8b16bbc7081
58c45ee301582507b060a3ed3415d11312954565
refs/heads/master
2020-03-04T15:55:20.441000
2017-06-02T13:26:36
2017-06-02T13:26:36
93,167,800
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.entrego.services.dao.jpa.model; import com.entrego.core.model.delivery.Money; import com.entrego.core.model.rate.BaseRate; import java.io.Serializable; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embeddable; /** * * @author finger */ @Embeddable public class JPABaseRate implements BaseRate, Serializable { private JPAMoney start; private Long meters; private Long minutes; public JPABaseRate(BaseRate baseRate) { this.start = new JPAMoney(baseRate.start()); this.meters = baseRate.meters(); this.minutes = baseRate.minutes(); } protected JPABaseRate() { } @Override public Money start() { return start; } @Override public Long meters() { return meters; } @Override public Long minutes() { return minutes; } @AttributeOverrides({ @AttributeOverride( name = "amount", column = @Column(name = "startAmount") ), @AttributeOverride( name = "currency", column = @Column(name = "startCurrency") ) }) protected JPAMoney getStart() { return start; } protected void setStart(JPAMoney start) { this.start = start; } protected Long getMeters() { return meters; } protected void setMeters(Long meters) { this.meters = meters; } protected Long getMinutes() { return minutes; } public void setMinutes(Long minutes) { this.minutes = minutes; } }
UTF-8
Java
1,723
java
JPABaseRate.java
Java
[ { "context": "t javax.persistence.Embeddable;\n\n/**\n *\n * @author finger\n */\n@Embeddable\npublic class JPABaseRate implemen", "end": 349, "score": 0.9950287938117981, "start": 343, "tag": "USERNAME", "value": "finger" } ]
null
[]
package com.entrego.services.dao.jpa.model; import com.entrego.core.model.delivery.Money; import com.entrego.core.model.rate.BaseRate; import java.io.Serializable; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embeddable; /** * * @author finger */ @Embeddable public class JPABaseRate implements BaseRate, Serializable { private JPAMoney start; private Long meters; private Long minutes; public JPABaseRate(BaseRate baseRate) { this.start = new JPAMoney(baseRate.start()); this.meters = baseRate.meters(); this.minutes = baseRate.minutes(); } protected JPABaseRate() { } @Override public Money start() { return start; } @Override public Long meters() { return meters; } @Override public Long minutes() { return minutes; } @AttributeOverrides({ @AttributeOverride( name = "amount", column = @Column(name = "startAmount") ), @AttributeOverride( name = "currency", column = @Column(name = "startCurrency") ) }) protected JPAMoney getStart() { return start; } protected void setStart(JPAMoney start) { this.start = start; } protected Long getMeters() { return meters; } protected void setMeters(Long meters) { this.meters = meters; } protected Long getMinutes() { return minutes; } public void setMinutes(Long minutes) { this.minutes = minutes; } }
1,723
0.597214
0.597214
81
20.271605
17.306969
60
false
false
0
0
0
0
0
0
0.333333
false
false
2
edad98c8e8e983fee7fd2f0912ebccd87ca88651
31,963,146,645,268
a54dafa35593ad89b3930c0a477889940cc06efa
/source/esdk_uc_native_professional_java/src/main/java/com/huawei/esdk/uc/professional/local/callback/CallCallback.java
6f82096b10407817e50b843803c3519f3e455bc9
[ "Apache-2.0" ]
permissive
winggynOnly/esdk_uc_native_java
https://github.com/winggynOnly/esdk_uc_native_java
b20b7e29c47d9887cf89d57377463869487d6259
9bd8203582e31938a3af478a97b111332bbb4c44
refs/heads/master
2020-05-20T22:26:34.231000
2015-10-17T15:10:59
2015-10-17T15:10:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huawei.esdk.uc.professional.local.callback; public interface CallCallback extends UCProfessionalCallback{ void notifyCTDStatus(String initiator,String callId,Integer status ); }
UTF-8
Java
194
java
CallCallback.java
Java
[]
null
[]
package com.huawei.esdk.uc.professional.local.callback; public interface CallCallback extends UCProfessionalCallback{ void notifyCTDStatus(String initiator,String callId,Integer status ); }
194
0.835052
0.835052
6
31.333334
30.976694
70
false
false
0
0
0
0
0
0
1
false
false
2
73ab3c18c932530a387a163acf38a92c18112d88
20,847,771,289,684
533d671dc699454e5ae36e2943dc3dbbcc81b791
/frameworks/bof-framework/framework/src/se/abalon/bof/AbstractQueryBuilder.java
dbd8db6ccf57307f1a5b529f193d25d40b8ce360
[]
no_license
tstjerndal/steveham_git
https://github.com/tstjerndal/steveham_git
1647206badef42458459c0eb4072cedafaa40874
094308ce12cf64ab1d8f434fcdbf24289c47b6e2
refs/heads/master
2016-08-07T18:38:38.255000
2013-12-10T11:46:43
2013-12-10T11:46:43
37,447,267
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package se.abalon.bof; import java.sql.Types; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.log4j.Category; import se.abalon.bof.type.AbalonPrimaryKey; import se.abalon.bof.type.GregorianDate; import se.abalon.bof.type.Timespan; import se.abalon.bof.util.Converter; import se.abalon.bof.util.MacroHandler; import se.abalon.util.MayflowerRuntimeException; import se.abalon.util.StringUtil; /** * Helper to create SQL SELECT statements from a BofQuery object as well as * other native system queries according to a MS SQL database (SQL server 2000). * * @author Fredrik Hed [f.hed@abalon.se] */ @SuppressWarnings("unchecked") public abstract class AbstractQueryBuilder implements QueryBuilder { private static Category log = Category.getInstance(AbstractQueryBuilder.class); private static final String quoteChar = "\""; /** * Optimization: map with globaly constant values which can optimize the * join part of the query */ private Map<String, String> globalConstants = new HashMap<String, String>(); /** * Helper that adds a ORDER BY for all primary key fields in the query. * * @param query * The query object to add the order by statements for * @param modelAlias * the bod to add the primary key to the order by for * @throws ModelException * if the modelAlias found in the query dont exist. This shall * newer happend. */ private void addOrderByForPrimaryKey(BofQuery query, String modelAlias) throws ModelException { String bodName = query.getModels().get(modelAlias); String pkFieldName = ModelDefinition.getInstance(bodName).getPrimaryKeyFieldName(); for(String toBodAlias : query.getRelations(modelAlias).keySet()) { addOrderByForPrimaryKey(query, toBodAlias); } /* * Check if a sort order already exists for this field. If that is the * case we do not set it again since we don't know if it is supposed to * be ascending or descending */ if (!query.hasOrderBy(modelAlias, pkFieldName)) { query.addOrderBy(modelAlias, pkFieldName); // throws ModelException } } public abstract int getDBType(); public String getFetchSql(BofQuery query, String rootAlias) throws ModelException { return getFetchSql(query, rootAlias, null); } public String getFetchDuplicateSql(BofQuery query, String rootAlias, DuplicateFieldMap fieldMap) throws ModelException { return getFetchSql(query, rootAlias, fieldMap); } public String getFetchSql(BofQuery query, String rootAlias, DuplicateFieldMap fieldMap) throws ModelException { Set<String> itemSet = new HashSet<String>(); // contains "...ID as ...ID", // "count("...ID") as ...ID" Set<String> fromSet = new HashSet<String>(); List<String> orderSet = new ArrayList<String>(); /* * Add an order by statement for all primary keys for all bods to assure * that all rows for a bo will be fetched in sequence. */ addOrderByForPrimaryKey(query, rootAlias); fetchItem(query, rootAlias, fromSet, itemSet, false); List<Join> joinList = new ArrayList<Join>(); List<Join> outerJoinList = new ArrayList<Join>(); List<String> groupByList = new ArrayList<String>(); /* * fetch joins according to parent to the root model */ String rootModelName = (String) query.getModels().get(rootAlias); fetchParent(query, rootModelName, rootAlias, fromSet, joinList, outerJoinList, Join.INNER, null); /* * This will use the global constant... */ fetchJoin(query, rootAlias, fromSet, joinList, outerJoinList, null); /* * Optimization: map with globaly constant values which can optimize the * join part of the query */ String where = fetchWhere(query, false, "", true); /* * there are only GROUP BY values if we have an aggregation... */ if (query.hasBodAggregation(rootAlias) && query.getAggregations().keySet().contains(rootAlias)) { fetchGroupBy(query, rootAlias, groupByList); } else { fetchOrder(query, rootAlias, orderSet); } String str = ""; if (fieldMap == null || fieldMap.getAliasModelMap().size() < 1) { // queries with maxnbrhits and conditions str = getFetchSql(false, query, rootAlias, fromSet, itemSet, orderSet, joinList, outerJoinList, groupByList, where); } else { // requests for duplicate queries, ie fields are supplied in call str = getFetchDuplicateSql(query, rootAlias, fromSet, itemSet, orderSet, joinList, outerJoinList, groupByList, where, fieldMap); } return str; } public abstract String getFetchSql(boolean idQuery, BofQuery query, String rootAlias, Set<String> fromSet, Set<String> itemSet, List<String> orderSet, List<Join> joinList, List<Join> outerJoinList, List<String> groupByList, String where) throws ModelException; public abstract String getFetchDuplicateSql(BofQuery query, String rootAlias, Set<String> fromSet, Set<String> itemSet, List<String> orderSet, List<Join> joinList, List<Join> outerJoinList, List<String> groupByList, String where, DuplicateFieldMap fieldMap) throws ModelException; /** * Returns a distinct sql statement for retrieving ids for a given query. * * @param query * @param rootAlias */ public String getFetchIdSql(BofQuery query, String rootAlias) throws ModelException { return getIdSql(query, rootAlias, null); } /** * Returns a distinc sql statement for inserting ids for a given query. * * @param query * @param rootAlias * @param metadata * if metadata is given an INSERT INTO statement is returned */ public String getInsertIdSql(BofQuery query, String rootAlias, AbalonPrimaryKey metadata) throws ModelException { return getIdSql(query, rootAlias, metadata); } /** * Returns a distinc sql statement for retrieving or inserting ids for a * given query. * * @param query * @param rootAlias * @param metadata * if metadata is given an INSERT INTO statement is returned */ String getIdSql(BofQuery query, String rootAlias, AbalonPrimaryKey metadata) throws ModelException { Set<String> itemSet = new HashSet<String>(); // contains "...ID as ...ID", // "count("...ID") as ...ID" Set<String> fromSet = new HashSet<String>(); List<String> orderSet = new ArrayList<String>(); // alias.FIELD_NAME String modelField = query.getFetchOnlyPk(); fetchIdItem(query, rootAlias, modelField, fromSet, itemSet); List<Join> joinList = new ArrayList<Join>(); List<Join> outerJoinList = new ArrayList<Join>(); List<String> groupByList = new ArrayList<String>(); /* * fetch joins according to parent to the root model */ String rootModelName = (String) query.getModels().get(rootAlias); fetchParent(query, rootModelName, rootAlias, fromSet, joinList, outerJoinList, Join.INNER, null); /* * This will use the global constant... */ fetchJoin(query, rootAlias, fromSet, joinList, outerJoinList, null); /* * Optimization: map with globaly constant values which can optimize the * join part of the query */ String where = fetchWhere(query, false, "", true); /* * Instead of rootAlias we fetch the alias specified by getFetchOnlyPK */ String sql = getFetchSql(true, query, rootAlias, fromSet, itemSet, orderSet, joinList, outerJoinList, groupByList, where); /* * build "not null" condition */ String notNullCondition = fetchIdIsNotNullCondition(query, rootAlias, modelField); /* * If we have aggregations (we have stripped all fields except the one * defined by the 'fetchOnlyPrimaryKey') do a count query (ex. * ptestbc.id AS p_ID) */ String[] modelFieldArr = modelField.split("\\."); if (metadata == null && query.getAggregations().containsKey(modelFieldArr[0])) { String str[] = sql.split("\\s+"); // the first enty defined the field to count String countField = str[0]; List<String> elems = Arrays.asList(str); elems = elems.subList(1, elems.size()); sql = StringUtil.join(elems, " "); if (sql.indexOf(" WHERE ") > 0) { return "SELECT count(DISTINCT " + countField + ") " + sql + " AND " + notNullCondition; } return "SELECT count(DISTINCT " + countField + ") " + sql + " WHERE " + notNullCondition; } /* * If no metadata ID is specified, just return a simple SELECT statement */ else if (metadata == null) { if (sql.indexOf(" WHERE ") > 0) { return "SELECT DISTINCT " + sql + " AND " + notNullCondition; } return "SELECT DISTINCT " + sql + " WHERE " + notNullCondition; } /* * Otherwise, generate an INSERT statement that inserts the rows * selected into the mf_datasetrow table, with the metadata PON as a * constant expression. */ if (sql.indexOf(" WHERE ") > 0) { return decorateForInsert(sql + " AND " + notNullCondition, metadata); } return decorateForInsert(sql + " WHERE " + notNullCondition, metadata); } public static String decorateForInsert(String sql, AbalonPrimaryKey metadata) { // INSERT INTO mf_datasetrow (metadata, objref) return "SELECT DISTINCT " + metadata + " as md, " + sql; } private String getJoinsSql(List<Join> outerJoinList, Set<String> fromSet) { StringBuffer join = new StringBuffer(); return getSelectSql(outerJoinList, join, fromSet, new HashSet<String>()).toString(); } protected String getColumnsIDSql(boolean idQuery, Set<String> itemSet) { // special treatment for id queries - the one and only id filed is // always named "id" String columns = ""; List<String> idSet = new ArrayList<String>(); for (Object object : itemSet) { String itemString = (String) object; String[] aliasArr = itemString.split(" AS "); idSet.add(aliasArr[1]); } if (itemSet.size() == 1 && idQuery) { columns = " the_id "; } else { columns = StringUtil.join(idSet, ", "); } return columns; } protected String getSelectAndJoinSql(boolean idQuery, List<Join> outerJoinList, Set<String> fromSet, Set<String> itemSet) { String columns = ""; StringBuffer join = new StringBuffer(); join = getSelectSql(outerJoinList, join, fromSet, new HashSet<String>()); // special treatment for id queries - the one and only id filed is // always named "id" if (itemSet.size() == 1 && idQuery) { String[] str = itemSet.iterator().next().toString().split("\\s+"); columns = str[0] + " AS the_id "; } else { columns = StringUtil.join(itemSet, ", "); } columns += " FROM "; columns += StringUtil.join(fromSet, ", "); if (fromSet.size() == 1 && join.length() == 0) { columns += " WITH (NOLOCK) "; } else if (fromSet.isEmpty() || join.length() == 0) { columns += join.toString(); } else { columns += ", " + join.toString(); } return columns; } protected String getJoinSql(boolean idQuery, List<Join> outerJoinList, Set<String> fromSet, Set<String> itemSet) { String columns = ""; StringBuffer join = new StringBuffer(); join = getSelectSql(outerJoinList, join, fromSet, new HashSet<String>()); // special tratement for id queries - the one and only id filed is // allways named "id" if (itemSet.size() == 1 && idQuery) { String[] str = itemSet.iterator().next().toString().split("\\s+"); columns = str[0] + " AS the_id "; } else { columns = StringUtil.join(itemSet, ", "); } columns += " FROM "; columns += StringUtil.join(fromSet, ", "); boolean aggregated = false; if(!outerJoinList.isEmpty()) { for (Join joinListItem : (List<Join>)outerJoinList) { if(joinListItem.type==Join.AGGREGATION) { aggregated=true; break; } } } if (fromSet.size() == 1 && join.length() == 0) { columns += " WITH (NOLOCK) "; } else if (fromSet.size() == 1 && aggregated) { columns += join.toString(); } else if (fromSet.isEmpty() || join.length() == 0) { columns += join.toString(); } else { columns += ", " + join.toString(); } return columns; } private StringBuffer getSelectSql(List<Join> joinList, StringBuffer sb, Set<String> fromSet, Set<String> joined) { for(Join oj : joinList) { if (sb.length() == 0 || (!joined.contains(oj.on) && oj.type==Join.AGGREGATION)) { /* * Bugfix. Some queries results in inner joins on the same table * on the same columns. */ if(oj.type==Join.AGGREGATION) { sb.append(oj.getJoinSql()); sb.append("(SELECT "); sb.append(oj.relationField); sb.append(", "); Iterator<String> aggregationItor = oj.aggregations.keySet().iterator(); while(aggregationItor.hasNext()) { String aggregateBodField = aggregationItor.next(); String aggregateField = null; String aggregation = null; Object tmpAggregation = oj.aggregations.get(aggregateBodField); if(tmpAggregation instanceof Map<?,?>) { for(String key : ((Map<String, String>)tmpAggregation).keySet()) { aggregateField = key; aggregation = ((Map<String, String>)tmpAggregation).get(key); } } if(!aggregateField.equals("id") && !aggregateField.equals("isa_instance") && !oj.aggregations.containsKey("ID") && !oj.aggregations.containsKey("ISA_INSTANCE")) { sb.append(aggregation); sb.append("("); sb.append(aggregateField); sb.append(") AS id, "); } sb.append(aggregation); sb.append("("); sb.append(aggregateField); sb.append(") AS "); sb.append(aggregateField); if(aggregationItor.hasNext()) { sb.append(", "); } } sb.append(" from "); //sb.append(oj.table); String fromStr = getJoinsSql(oj.parentAggregationJoins, fromSet); if(fromStr.length()==0) { fromStr = oj.table; } sb.append(fromStr); if(oj.conditionStr!=null && !oj.conditionStr.equals("")) { sb.append(" where "); sb.append(oj.conditionStr); } sb.append(" group by "); sb.append(oj.relationField); sb.append(") "); sb.append(oj.aggTo); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.table + " " + oj.to); } else if (!oj.from.equals(oj.to)) { sb.append(oj.from); sb.append(" WITH (NOLOCK) "); sb.append(oj.getJoinSql()); sb.append(oj.to); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.from); fromSet.remove(oj.to); } } else if (joined.contains(oj.from)) { sb.append(oj.getJoinSql()); sb.append(oj.to); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.to); } else if (joined.contains(oj.to)) { sb.append(oj.getJoinSql()); sb.append(oj.from); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.from); } else { sb.append(", "); sb.append(oj.from); sb.append(" WITH (NOLOCK) "); sb.append(oj.getJoinSql()); sb.append(oj.to); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.from); fromSet.remove(oj.to); } joined.add(oj.from); joined.add(oj.to); } return sb; } /** * Follows all relations defined in query. For each relation found, * fetchParent is called. * * @param query * @param internalModelName * @param fromSet * @param joinList * @param outerJoinList * @param forceInnerJoin * @throws ModelException */ private void fetchJoin(BofQuery query, String internalModelName, Set<String> fromSet, List<Join> joinList, List<Join> outerJoinList, String token) throws ModelException { ModelDefinition fromBod; ModelDefinition toBod; ModelRelation bodRelation; String fromModel; String toTable; String toField; String fromTable; String fromField; String toInternalModelName; int cardinality; // TODO: handle null token if (token == null) token = ""; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException Condition tmpC = query.clearConditions(); List<Condition> tmpCondList = getConditionsList(tmpC); List<Condition> queryCondList = new ArrayList<Condition>(tmpCondList); /* * build inner and outer joins for all relations */ for(String relationName : query.getRelationsFromMe(internalModelName)) { toInternalModelName = query.getRelationsToMe().get(internalModelName + "." + relationName); String toModel = query.getModels().get(toInternalModelName); toBod = ModelDefinition.getInstance(toModel); bodRelation = fromBod.getModelRelation(relationName); cardinality = bodRelation.getCardinality(); if (cardinality == ModelRelation.CARDINALITY_0M) { fromTable = fromBod.getStorageTable(bodRelation.getField()); // throws // ModelException fromField = fromBod.getStorageColumn(bodRelation.getField()); // throws // ModelException toTable = toBod.getStorageTable(bodRelation.getForeignField()); // throws // ModelException toField = toBod.getStorageColumn(bodRelation.getForeignField()); // throws // ModelException } else { fromTable = fromBod.getStorageTable(bodRelation.getForeignField()); // throws // ModelException fromField = fromBod.getStorageColumn(bodRelation.getForeignField()); // throws // ModelException toTable = toBod.getStorageTable(bodRelation.getField()); // throws // ModelException toField = toBod.getStorageColumn(bodRelation.getField()); // throws // ModelException } /* * optimization, if both query.getModelDefinitions() has * queryFields, there must be bo's in both query. * getModelDefinitions() and there is no need to do a OUTER JOIN */ Join oj = null; Map<String, Object> aggregationMap = null; int joinType; if ((query.hasCondition(internalModelName) && (query.hasCondition(toInternalModelName) && !query.hasBodAggregation(toInternalModelName)) || cardinality == ModelRelation.CARDINALITY_11)) { joinType = Join.INNER; } else if(query.hasBodAggregation(toInternalModelName)) { joinType = Join.AGGREGATION; Map<String, String> strAggregationMap = query.getAggregations().get(toInternalModelName); aggregationMap = new HashMap<String, Object>(strAggregationMap); } else { // outer join here to fetch all bos where relation dont have // bos... joinType = Join.OUTER; } oj = new Join(joinType); oj.from = fromTable + " " + BofPersistenceManager.getIdentifier(internalModelName, fromTable) + token; boolean useAggTo = false; if(joinType==Join.AGGREGATION) { List<Join> parentJoins = new ArrayList<Join>(); if(!toBod.getStorageTable(toBod.getPrimaryKeyFieldName()).equals(toTable)) { oj.aggTo = BofPersistenceManager.getIdentifier(toInternalModelName, toBod.getStorageTable(toBod.getPrimaryKeyFieldName())) + token; useAggTo = true; } else { oj.aggTo = BofPersistenceManager.getIdentifier(toInternalModelName, toTable) + token; } oj.to = BofPersistenceManager.getIdentifier(toInternalModelName, toTable) + token; oj.table = toTable; // Insert conditions into aggregation join. Just the conditions that is supposed to be here. List<Condition> innerCondList = new ArrayList<Condition>(); moveInnerConditions(toInternalModelName, aggregationMap, tmpCondList, queryCondList, innerCondList); Map<String, Object> tmpAggregationMap = new HashMap<String, Object>(aggregationMap); for(String aggKey : tmpAggregationMap.keySet()) { if(tmpAggregationMap.get(aggKey) instanceof String) { String aggValue = aggregationMap.get(aggKey).toString(); String resolvedAggKey = toBod.getStorageColumn(aggKey); Map<String, String> resolvedMap = new HashMap<String, String>(); resolvedMap.put(resolvedAggKey, aggValue); aggregationMap.remove(aggKey); aggregationMap.put(aggKey, resolvedMap); } } fetchParent(query, toModel, toInternalModelName, fromSet, parentJoins, outerJoinList, Join.INNER, token); oj.parentAggregationJoins = parentJoins; Condition innerCond = createConditionFromList(innerCondList); oj.conditionStr = fetchWhere(query, innerCond, false, "", false); } else { oj.to = toTable + " " + BofPersistenceManager.getIdentifier(toInternalModelName, toTable) + token; } if(useAggTo) { oj.on = getId(internalModelName, fromTable, fromField, token) + " = " + getId(toInternalModelName, toBod.getStorageTable(toBod.getPrimaryKeyFieldName()), toField, token); } else { oj.on = getId(internalModelName, fromTable, fromField, token) + " = " + getId(toInternalModelName, toTable, toField, token); } oj.relationField = toField; oj.aggregations = aggregationMap; outerJoinList.add(oj); if(joinType!=Join.AGGREGATION) { fetchParent(query, toModel, toInternalModelName, fromSet, joinList, outerJoinList, joinType, token); } if (query.getModels().containsKey(toInternalModelName)) { fetchJoin(query, toInternalModelName, fromSet, joinList, outerJoinList, token); // recursion } } for(Condition cond : queryCondList) { query.addCondition(cond); } } /** * Get a list of Conditions from a {@link Condition}. {@link ComplexCondition} with OR operator * will be returned as ComplexConditions. All other will be returned as a {@link ConstantCondition}. * * @param condition * @return */ private java.util.List<Condition> getConditionsList(Condition condition){ java.util.List<Condition> conditions = new ArrayList<Condition>(); java.util.List<Condition> tmpConditions = new ArrayList<Condition>(); if(condition instanceof ComplexCondition){ ComplexCondition comp = (ComplexCondition)condition; if(comp.getOperation()==Condition.OR) { conditions.add(comp); } else { Condition c1 = comp.getCondition1(); Condition c2 = comp.getCondition2(); if(c1 != null) tmpConditions.add(c1); if(c2 != null) tmpConditions.add(c2); } for(Condition cond : tmpConditions) { if(cond instanceof ComplexCondition) { conditions.addAll(getConditionsList(cond)); } else { conditions.add(cond); } } } else if(condition instanceof ConstantCondition){ conditions.add(condition); } return conditions; } /** * Creates a single {@link ComplexCondition} from a list of Conditions. If the list * contains only one object it will be returned by itself (can be a {@link ConstantCondition}) * * @param condList * @return */ private Condition createConditionFromList(java.util.List<Condition> condList) { if(condList.size()==0) { return null; } if(condList.size()==1) { return condList.iterator().next(); } Condition c1 = condList.remove(0); Condition c2 = condList.remove(0); ComplexCondition comp = new ComplexCondition(c1, c2, Condition.AND); for(Condition cond : condList) { comp = new ComplexCondition(comp, cond, Condition.AND); } return comp; } /** * Move conditions for aggregations from query to the Join condition list * * It adds IS NOT NULL and IS NULL conditions depending on the original * conditions. * * @param toInternalModelName * @param aggregationMap * @param tmpCondList * @param queryCondList * @param innerCondList */ private void moveInnerConditions(String toInternalModelName, Map<String, Object> aggregationMap, List<Condition> tmpCondList, List<Condition> queryCondList, List<Condition> innerCondList) { for (Condition cond : tmpCondList) { if(cond instanceof ComplexCondition) { Condition c1 = ((ComplexCondition)cond).getCondition1(); Condition c2 = ((ComplexCondition)cond).getCondition2(); if(((ComplexCondition)cond).getOperation()==Condition.OR) { if(((ConstantCondition)c1).getBodAlias().equals(toInternalModelName) && ((ConstantCondition)c2).getBodAlias().equals(toInternalModelName)) { if(!aggregationMap.containsKey(((ConstantCondition)c1).getField()) && !aggregationMap.containsKey(((ConstantCondition)c2).getField())) { if(queryCondList.remove(cond)) { if(((ConstantCondition)c1).getOperation()!=Condition.IS_NULL || ((ConstantCondition)c2).getOperation()!=Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NOT_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } innerCondList.add(cond); } else if(((ConstantCondition)c1).getOperation()==Condition.IS_NULL || ((ConstantCondition)c2).getOperation()==Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } } } } } } } else { if(((ConstantCondition)cond).getBodAlias().equals(toInternalModelName)) { if(!aggregationMap.containsKey(((ConstantCondition)cond).getField())) { if(queryCondList.remove(cond)) { if(((ConstantCondition)cond).getOperation()!=Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NOT_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } innerCondList.add(cond); } else if(((ConstantCondition)cond).getOperation()==Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } } } } else { System.out.println(cond); } } } } } private String getId(String modelAlias, String table, String field, String innerToken) { if (innerToken == null) innerToken = ""; String key = BofPersistenceManager.getIdentifier(modelAlias, table) + innerToken + "." + field; if (globalConstants.containsKey(key)) { return globalConstants.get(key); } return key; } /** * Adds table entries to fromSet (format: [table name] [table alias]) and * join entries to the joinList (format: [table alias 1].[column name 1] = * [table alias 2].[column name 2]) * * All parent joins are INNER JOINS. * * @param internalModelName * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param joinList * the join set to be populated * @param forceOuterJoin * forces join sql parts to be outer joins * @throws ModelException * if the model does not match the ModelDefinition */ protected void fetchParent(BofQuery query, String modelName, String modelAlias, Set<String> fromSet, List<Join> joinList, List<Join> outerJoinList, int joinType, String innerToken) throws ModelException { ModelDefinition fromBod; String fromTable; String fromField; String toTable; String toField; // handle null values of inner token if (innerToken == null) innerToken = ""; fromBod = ModelDefinition.getInstance(modelName); // throws // ModelException ModelDefinition pBod = null; if (fromBod.getParentName() != null && fromBod.getParentName().length() > 0) { try { pBod = ModelDefinition.getInstance(fromBod.getParentName()); // throws // ModelException } catch (ModelException e) { // no defined model name } } if (pBod != null) { fromTable = fromBod.getStorage(); fromField = fromBod.getPrimaryKeyStorageColumn(); toTable = pBod.getStorage(); toField = pBod.getPrimaryKeyStorageColumn(); Join oj = null; /* * parent model with no storage - No join needed. */ if (fromTable.equals("") || toTable.equals("")) { // No join needed. } /* * parent model with storage in same table - No join needed. */ else if (fromTable.equals(toTable) && fromField.equals(toField)) { // No join needed. } else { oj = new Join(joinType); } if (oj != null) { oj.from = fromTable + " " + BofPersistenceManager.getIdentifier(modelAlias, fromTable) + innerToken; oj.to = toTable + " " + BofPersistenceManager.getIdentifier(modelAlias, toTable) + innerToken; oj.on = getId(modelAlias, fromTable, fromField, innerToken) + " = " + getId(modelAlias, toTable, toField, innerToken); if (joinType == Join.INNER) { joinList.add(oj); } else { outerJoinList.add(oj); } } /* * call fetchParent for the parent */ if (fromBod.getParentName() != null && !fromBod.getParentName().equals("")) { fetchParent(query, fromBod.getParentName(), modelAlias, fromSet, joinList, outerJoinList, joinType, innerToken); } /* * fetch relations for parent */ fetchJoin(query, modelAlias, fromSet, joinList, outerJoinList, innerToken); } } /** * Adds table entries to fromSet (format: [table name] [table alias]) and * item entries to the itemSet (format: [table alias].[column name] AS * [model alias]_[column alias]) * * @param internalModelName * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param itemSet * the item set to be populated * @throws ModelException * if the model does not match the ModelDefinition */ private void fetchItem(BofQuery query, String internalModelName, Set<String> fromSet, Set<String> itemSet, boolean inner) throws ModelException { String fromField; String fromTable; String fromModel; ModelDefinition fromBod; List<String> itemNames; Map<String, String> myAggregations; Boolean hasAggregations = false; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException // TODO: move this to the checkRelations method... if (!query.getFields().containsKey(internalModelName)) { itemNames = new ArrayList<String>(); itemNames.add("ID"); // allways add businessObject query.getFields().put(internalModelName, itemNames); log.warn("fetchItem (" + internalModelName + ") no items to add ... PATCH added ID!!!"); } if(!query.getAggregations().isEmpty() && query.getAggregations().containsKey(internalModelName)){ hasAggregations = true; } // if we have aggregations fetch them, otherwise make a dummy Map... if (query.getAggregations().containsKey(internalModelName)) { myAggregations = query.getAggregations().get(internalModelName); } else { myAggregations = new HashMap<String, String>(); } if (query.getFields().containsKey(internalModelName)) { for(String itemName : query.getFields().get(internalModelName)) { fromField = fromBod.getStorageColumn(itemName); fromTable = fromBod.getStorageTable(itemName); if(!fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()).equals(fromTable) && hasAggregations) { //fromTable = fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()); } // If the storage column is "" this indicates that it is a // virtual field that has no storage... if (fromField.equals("")) { continue; } String mangledName = ""; if (inner) { mangledName = BofPersistenceManager.getIdentifier(internalModelName, fromTable + "_inner"); } else { mangledName = BofPersistenceManager.getIdentifier(internalModelName, fromTable); } String mangledAlias = ""; if (inner) { mangledAlias = BofPersistenceManager.getIdentifier(internalModelName + "_inner", itemName); } else { mangledAlias = BofPersistenceManager.getIdentifier(internalModelName, itemName); } // aggregation item... // "count(personPERSON.NAMN) AS person_NAME" if (myAggregations.keySet().contains(itemName) || (!myAggregations.isEmpty() && !myAggregations.keySet().contains(itemName) && itemName.equals("ID"))) { String aggregationType = myAggregations.get(itemName); if(aggregationType==null && itemName.equals("ID") && internalModelName.equals(query.getRootAlias())) { String aggFromField = ""; for (Object key : myAggregations.keySet()) { aggregationType = myAggregations.get(key); aggFromField = fromBod.getStorageColumn(key.toString()); } itemSet.add(aggregationType + "(" + mangledName + "." + aggFromField + ")" + " AS " + mangledAlias); } else { if(internalModelName.equals(query.getRootAlias())) { itemSet.add(aggregationType + "(" + mangledName + "." + fromField + ")" + " AS " + mangledAlias); } else { itemSet.add(mangledName + "." + fromField + " AS " + internalModelName+"_" + itemName); if(itemName.equals("ID")) { itemSet.add(mangledName + "." + fromField + " AS " + internalModelName+"_" + aggregationType); } } } } // normal item... // "personPERSON.NAMN AS person_NAME" else { if(!hasAggregations){ String iName = mangledName + "." + fromField + " AS " + mangledAlias; itemSet.add(iName); } else { itemSet.add("COUNT(" + mangledName + "." + fromField + ")" + " AS " + mangledAlias); } } fromSet.add(fromTable + " " + mangledName); } } for(String toInternalRelationName : query.getRelations(internalModelName).keySet()) { fetchItem(query, toInternalRelationName, fromSet, itemSet, inner); // recursion } } private String fetchIdIsNotNullCondition(BofQuery query, String modelAlias, String fieldName) throws ModelException { String[] str = fieldName.split("\\."); String model = query.getModels().get(str[0]); ModelDefinition md = ModelDefinition.getInstance(model); // throws String column = md.getStorageColumn(str[1]); String table = md.getStorageTable(str[1]); return BofPersistenceManager.getIdentifier(str[0], table) + "." + column + " is not null"; } /** * * @param query * @param modelAlias * @param fieldName * alias.FIELD_NAME * @param fromSet * @param itemSet * @throws ModelException */ private void fetchIdItem(BofQuery query, String modelAlias, String fieldName, Set<String> fromSet, Set<String> itemSet) throws ModelException { String fromField; String fromTable; String fromModel; ModelDefinition fromBod; List<String> itemNames; fromModel = (String) query.getModels().get(modelAlias); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException String[] str = fieldName.split("\\."); if (!query.getFields().containsKey(str[0]) && modelAlias.equals(str[0])) { itemNames = new ArrayList<String>(); itemNames.add(str[1]); // always add businessObject query.getFields().put(str[0], itemNames); } // TODO: move this to the checkRelations method... /* * if (!query.getFields().containsKey(modelAlias)) { itemNames = new * ArrayList(); itemNames.add("ID"); // allways add businessObject * query.getFields().put(modelAlias, itemNames); log.warn("fetchItem (" + * modelAlias + ") no items to add ... PATCH added ID!!!"); } */ // if we have aggregations fetch them, otherwise make a dummy Map... /* * if (query.getAggregations().containsKey(modelAlias)) { myAggregations = * (Map) query.getAggregations().get( modelAlias); } else { * myAggregations = new HashMap(); } */ if (query.getFields().containsKey(modelAlias)) { for(String itemName : query.getFields().get(modelAlias)) { fromField = fromBod.getStorageColumn(itemName); fromTable = fromBod.getStorageTable(itemName); if(!fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()).equals(fromTable) && query.hasAggregation(modelAlias)) { fromTable = fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()); } // If the storage column is "" this indicates that it is a // virtual field that has no storage... if (fromField.equals("")) { continue; } // aggregation item... // "count(personPERSON.NAMN) AS person_NAME" /* * if (myAggregations.keySet().contains(itemName)) { String * aggregationType = (String) myAggregations .get(itemName); * itemSet.add(aggregationType + "(" + * BofPersistenceManager.getIdentifier( modelAlias, fromTable) + * "." + fromField + ")" + " AS " + modelAlias + "_" + * itemName); } */// normal item... // "personPERSON.NAMN AS person_NAME" // else { if (modelAlias.equals(str[0]) && itemName.equals(str[1])) { itemSet.add(BofPersistenceManager.getIdentifier(modelAlias, fromTable) + "." + fromField + " AS " + modelAlias + "_" + itemName); } fromSet.add(fromTable + " " + BofPersistenceManager.getIdentifier(modelAlias, fromTable)); } } for(String toInternalRelationName : query.getRelations(modelAlias).keySet()) { fetchIdItem(query, toInternalRelationName, fieldName, fromSet, itemSet); // recursion } } /* * private void fetchIdItem(BofQuery query, String modelAlias, String * fieldName, Set fromSet, Set itemSet) throws ModelException { String * itemName; String fromField; String fromTable; String fromModel; * ModelDefinition fromBod; Iterator itemIterator; * * fromModel = (String) query.getModels().get(modelAlias); fromBod = * ModelDefinition.getInstance(fromModel); // throws // ModelException * * if (query.getFields().containsKey(modelAlias)) { itemIterator = ((List) * query.getFields().get(modelAlias)) .iterator(); * * while (itemIterator.hasNext()) { itemName = (String) itemIterator.next(); * fromField = fromBod.getStorageColumn(itemName); fromTable = * fromBod.getStorageTable(itemName); * * if (itemName.equals(fieldName)) { // If the storage column is "" this * indicates that it is a // virtual field that has no storage... if * (fromField.equals("")) { continue; } // normal item... // * "personPERSON.NAMN AS person_NAME" * itemSet.add(BofPersistenceManager.getIdentifier(modelAlias, fromTable) + * "." + fromField + " AS " + modelAlias + "_" + itemName); * fromSet.add(fromTable + " " + * BofPersistenceManager.getIdentifier(modelAlias, fromTable)); } } } } */ /** * Joins all elements in the collection after the convertToSql are applyed * to all conditions-values. * * @param sqlType * the type to convert the elements to * @param c * the Colleciton of conditions-values to join * @param fieldType * TODO */ private String join(int sqlType, Collection<Object> c, BofQuery query, String fieldType) throws ModelException { StringBuffer sb = new StringBuffer(); for(Object o : c) { if (sb.length() > 0) { sb.append(","); } sb.append(convertToSql(sqlType, o, query, fieldType)); } return sb.toString(); } /** * Original fetchOrder for safety. Never used anymore * * @param query * @param internalModelName * @param orderSet * @throws ModelException */ @Deprecated @SuppressWarnings("unused") private void fetchOrder_org(BofQuery query, String internalModelName, List<String> orderSet) throws ModelException { String itemName; Integer sortOrder; String fromField; String fromModel; ModelDefinition fromBod; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // BodException String ascendingStr = "ASC"; String descendingStr = "DESC"; if (query.getOrderBy().containsKey(internalModelName)) { List<List<Object>> orderList = query.getOrderBy().get(internalModelName); /* * This is a list with lists in it (fieldName/sortorder pairs) */ String sortStr; for(List<Object> orderPair : orderList) { // itemName = (String) itemIterator.next(); itemName = (String) orderPair.get(0); sortOrder = (Integer) orderPair.get(1); if (sortOrder.intValue() == Condition.ASCENDING) { sortStr = ascendingStr; } else { sortStr = descendingStr; } /* * If the storage column is "" this indicates that it is a * virtual field that has no storage... */ fromField = fromBod.getStorageColumn(itemName); if (fromField.equals("")) { continue; } /* * Fields that are not part of the fetch-set might still be used * to sort. To make sure that the fields are accessed correctly * we reference all these field like: <tablealias>.<columnname> */ String columnName = fromBod.getField(itemName).getStorageColumn(); String tableName = fromBod.getField(itemName).getStorageTable(); String tableAlias = BofPersistenceManager.getIdentifier(internalModelName, tableName); orderSet.add(tableAlias + "." + columnName + " " + sortStr); // originally: // orderSet.add(internalModelName + "_" + itemName + " " + // sortStr); } } for(String toInternalRelationName : query.getRelations(internalModelName).keySet()) { fetchOrder(query, toInternalRelationName, orderSet); // recursion } } /** * Builds the orderBys for the query according the orderOfOrderBys listing. * * @param query * @param internalModelName * @param orderSet * @param inner * @throws ModelException */ private void fetchOrder(BofQuery query, String xxxinternalModelName, List<String> orderSet) throws ModelException { String itemName; Integer sortOrder; String fromField; String fromModel; ModelDefinition fromBod; // for each entry in the orderOfOrderBy add an entry in the orderSet // list List<String> orderOfOrders = query.getOrderOfOrders(); for (String alias : orderOfOrders) { fromModel = (String) query.getModels().get(alias); fromBod = ModelDefinition.getInstance(fromModel); // throws String ascendingStr = "ASC"; String descendingStr = "DESC"; if (query.getOrderBy().containsKey(alias) && !query.getAggregations().keySet().contains(alias)) { List<List<Object>> orderList = query.getOrderBy().get(alias); /* * This is a list with lists in it (fieldName/sortorder pairs) */ String sortStr; for(List<Object> orderPair : orderList) { // itemName = (String) itemIterator.next(); itemName = (String) orderPair.get(0); // TODO: think again.. -we dont want to order by id values // when maxNbrHits is set, but do we really want to do this // here? if (itemName != null && itemName.equals("ID") && query.getMaxNbrHits() != 0) continue; sortOrder = (Integer) orderPair.get(1); if (sortOrder.intValue() == Condition.ASCENDING) { sortStr = ascendingStr; } else { sortStr = descendingStr; } /* * If the storage column is "" this indicates that it is a * virtual field that has no storage... */ fromField = fromBod.getStorageColumn(itemName); if (fromField.equals("")) { continue; } /* * Fields that are not part of the fetch-set might still be * used to sort. To make sure that the fields are accessed * correctly we reference all these field like: * <tablealias>.<columnname> */ String columnName = fromBod.getField(itemName).getStorageColumn(); String tableName = fromBod.getField(itemName).getStorageTable(); String tableAlias = BofPersistenceManager.getIdentifier(alias, tableName); orderSet.add(tableAlias + "." + columnName + " " + sortStr); } } } } /** * Adds group by entries to the groupBySet (format: [table alias].[column * name]) * * @param internalModelName * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param joinList * the join set to be populated * @throws ModelException * if the model does not match the ModelDefinition */ private void fetchGroupBy(BofQuery query, String internalModelName, List<String> groupByList) throws ModelException { String fromField; String fromTable; String fromModel; ModelDefinition fromBod; Map<String, String> myAggregations; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException // if we have aggregations fetch them, otherwise make a dummy Map... if (query.getAggregations().containsKey(internalModelName)) { myAggregations = query.getAggregations().get(internalModelName); } else { myAggregations = new HashMap<String, String>(); } /* * Add all userdefined group by from query */ if (query.getGroupBy().containsKey(internalModelName)) { List<String> groupByFields = query.getGroupBy().get(internalModelName); for(String field : groupByFields) { fromField = fromBod.getStorageColumn(field); fromTable = fromBod.getStorageTable(field); if (fromField.equals("")) { continue; } String groupBySql = BofPersistenceManager.getIdentifier(internalModelName, fromTable) + "." + fromField; if (!groupByList.contains(groupBySql)) { groupByList.add(groupBySql); } } } /* * recursivly add all used defined fields */ for(String toInternalRelationName : query.getRelations(internalModelName).keySet()) { fetchGroupBy(query, toInternalRelationName, groupByList); // recursion } /* * Add all field not added so fare and are not aggregated fields */ if (query.getFields().containsKey(internalModelName)) { // add all items not declared as aggregation... for(String itemName : query.getFields().get(internalModelName)) { if (myAggregations.keySet().contains(itemName) || itemName.equals("ID")) { continue; } fromField = fromBod.getStorageColumn(itemName); fromTable = fromBod.getStorageTable(itemName); if (fromField.equals("")) { continue; } String groupBySql = BofPersistenceManager.getIdentifier(internalModelName, fromTable) + "." + fromField; if (!groupByList.contains(groupBySql)) { groupByList.add(groupBySql); } // groupByList.add(BofPersistenceManager.getIdentifier(internalModelName, // fromTable) + "." + fromField); } } } /** * Sorts a List with outerJoin Objects in chains. Where the elements in the * lists related like: * * <p> * <code>outerJoin1.to = outerJoin7.from<code><br> * <code>outerJoin7.to = outerJoin3.from<code><br> * ... */ protected static List<Join> sort(List<Join> list) { if (list.isEmpty()) { return list; } /* * remove multiple instances... */ List<Join> toSort = new ArrayList<Join>(); for(Join oj : list) { if (!toSort.contains(oj)) { toSort.add(oj); } } /* * sort */ List<Join> newlySorted = new ArrayList<Join>(); LinkedList<Join> sorted = new LinkedList<Join>(); sorted.add(toSort.remove(0)); // add first element do { boolean found = false; toSort.removeAll(newlySorted); sorted.addAll(newlySorted); newlySorted.clear(); Iterator<Join> leftItor = toSort.iterator(); while (leftItor.hasNext() && !found) { Join left = leftItor.next(); Iterator<Join> sortedItor = sorted.iterator(); while (sortedItor.hasNext() && !found) { Join aSorted = sortedItor.next(); if (aSorted.to.equals(left.from)) { newlySorted.add(left); found = true; } else if (aSorted.from.equals(left.from)) { newlySorted.add(left); found = true; } else if (aSorted.to.equals(left.to)) { newlySorted.add(left); found = true; } else if (aSorted.from.equals(left.to)) { newlySorted.add(left); found = true; } } } } while (!newlySorted.isEmpty()); /* * all we could not sort... just add them... */ sorted.addAll(toSort); return sorted; } protected class Join { protected static final int OUTER = 1; protected static final int INNER = 2; protected static final int AGGREGATION = 3; int type = OUTER; public String from; public String to; public String aggTo; public String on; public String table; public String relationField; public Map<String, Object> aggregations; public List<Join> parentAggregationJoins; public String conditionStr; public Join() { type = OUTER; } public Join(int type) { this.type = type; } /** * converting Columns and Tables to lower case * */ public void toLower() { } public String getJoinSql() { if (type == INNER) { return (" LEFT JOIN "); } return (" LEFT OUTER JOIN "); } /* * public String toString() { return from + " -> " + to + " (" + on + * ")"; } */ public boolean equals(Object o) { Join oj; if (o == null) { return false; } try { oj = (Join) o; } catch (ClassCastException e) { return false; } if (!oj.from.equals(from)) { return false; } if (!oj.to.equals(to)) { return false; } if (!oj.on.equals(on)) { return false; } return true; } public int hashCode() { return from.hashCode() + 13 * to.hashCode() + 13 * 13 * on.hashCode(); } } /** * * @param modelAlias * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param joinList * the join set to be populated * @throws BodException * if the model does not match the BusinessObjectDefinition */ private String fetchWhere(BofQuery query, boolean inner, String suffix, boolean useAlias) throws ModelException { Condition cond = query.getCondition(); if (cond == null) { return ""; } return getSql(cond, query, globalConstants, useAlias); } private String fetchWhere(BofQuery query, Condition cond, boolean inner, String suffix, boolean useAlias) throws ModelException { if (cond == null) { return ""; } return getSql(cond, query, globalConstants, useAlias); } /** * Recursivly walks down the Condition tree and generates the WHERE clause * for the SQL. Recursion for every ComplexCondition node found. * * @param condition * the condition to generate SQL for * @param q * the Query where the Bod, relations and fields are declared * @param constant * a Map of column identifiers [table alias].[column] keys * pointing to the equivalent constant for the column. This can * be used to optimize the query * @throws BodException * if unexpected data are found in Query or if an unsupported * implementation of Condition is found */ private String getSql(Condition condition, BofQuery q, Map<String, String> constant, boolean useAlias) throws ModelException { if (condition instanceof ComplexCondition) { ComplexCondition c = (ComplexCondition) condition; StringBuffer sb = new StringBuffer(); Map<String, String> myConstants = new HashMap<String, String>(); sb.append("("); sb.append(getSql(c.getCondition1(), q, myConstants, useAlias)); sb.append(" ").append(getOperation(c.getOperation())).append(" "); sb.append(getSql(c.getCondition2(), q, myConstants, useAlias)); sb.append(")"); if (c.getOperation() == Condition.AND) { constant.putAll(myConstants); } return sb.toString(); } else if (condition instanceof ConstantCondition) { return getConstantConditionSql((ConstantCondition) condition, q, constant, useAlias); } throw new MayflowerRuntimeException(ResourceKeys.UNKNOWN_CONDITION, new Object[] { condition }); } private String getOperation(int op) throws ModelException { if (op == Condition.AND) { return "AND"; } if (op == Condition.OR) { return "OR"; } throw new ModelException(ResourceKeys.UNKNOWN_OPERATION, new Object[] { "" + op }); } /** * Generates SQL for a end node (leaf) in a ComplexCondition. * * <p> * This implementation uses OracleSpecific handling for String to Date * transformations. * * @todo move locale and oracle formating string to resource... * @param c * the condition to generate SQL for * @param q * the Query where the Bod, relations and fields are declared * @throws BodException * if unexpected data are found in Query */ private String getConstantConditionSql(ConstantCondition c, BofQuery q, Map<String, String> constant, boolean useAlias) throws ModelException { String fromModel; ModelDefinition fromBod; String fromTable; String aliasTable; String column; fromModel = (String) q.getModels().get(c.getBodAlias()); fromBod = ModelDefinition.getInstance(fromModel); // throws // BodException fromTable = fromBod.getStorageTable(c.getField()); // throws // BodException aliasTable = fromTable; column = fromBod.getStorageColumn(c.getField()); // throws // BodException // Check for aggregated values and correct the aliasTable if(!fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()).equals(fromTable) && (q.hasAggregation(c.getBodAlias())&&q.hasAggregation(c.getBodAlias(), c.getField()))) { aliasTable = fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()); } StringBuffer sb = new StringBuffer(); /* * allways use the format <modelAlias><tableName>.<columnName> or some * other secret unit como for <modelAlias> and <tableName> */ String key = ""; if(useAlias) key = BofPersistenceManager.getIdentifier(c.getBodAlias(), aliasTable) + "." + column; else key = column; sb.append(key); String newValue = null; String fieldType = fromBod.getField(c.getField()).getFieldType(); int sqlType = Converter.itemJdbcIntMap(fieldType, getDBType()); switch (c.getOperation()) { case Condition.EXACT: /* * !!! REMOVE THIS !!!! An exact query on the String '*' is a valid * Query */ /* * if (c.getCondition().getClass().equals(String.class) && * ((String)c.getCondition()).equals("*")) { sb.append(" IS NOT * NULL"); log.warn("A single '*' is found in "); } else { */ sb.append("=" + convertToSql(sqlType, c.getCondition(), q, fieldType)); /* * optimization - this constant might be used to optimize the * query... */ if (constant.containsKey(key)) { constant.remove(key); } else { constant.put(key, convertToSql(sqlType, c.getCondition(), q, fieldType)); } // } break; case Condition.NOT_EXACT: sb.append("!=" + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.LIKE: newValue = (c.getCondition().toString()).replace('*', '%'); newValue = newValue.replace('?', '_'); sb.append(" LIKE " + convertToSql(Types.VARCHAR, newValue, q, fieldType)); break; case Condition.STARTS_WITH: newValue = c.getCondition().toString() + "%"; sb.append(" LIKE " + convertToSql(Types.VARCHAR, newValue, q, fieldType)); break; case Condition.INCLUDES: newValue = "%" + c.getCondition().toString() + "%"; sb.append(" LIKE " + convertToSql(Types.VARCHAR, newValue, q, fieldType)); break; case Condition.IN: case Condition.NOT_IN: if (c.getOperation() == Condition.NOT_IN) { sb.append(" NOT "); } sb.append(" IN ("); if (c.getCondition() instanceof BofQuery) { sb.append(((BofQuery) c.getCondition()).getSql()); } else { sb.append(join(sqlType, (Collection<Object>) c.getCondition(), q, fieldType)); } sb.append(")"); break; case Condition.IS_NULL: sb.append(" IS NULL"); break; case Condition.IS_NOT_NULL: sb.append(" IS NOT NULL"); break; case Condition.GREATER_THAN: sb.append(" > " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.LESSER_THAN: sb.append(" < " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.GREATER_OR_EQUAL: sb.append(" >= " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.LESSER_OR_EQUAL: sb.append(" <= " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.BETWEEN: String fieldModel = sb.toString(); sb.append(" >= " + convertToSql(sqlType, c.getCondition(), q, fieldType) + " and " + fieldModel + " < " + convertToSql(sqlType, c.getCondition2(), q, fieldType)); break; case Condition.NOT_LIKE: String newValue2 = (c.getCondition().toString()).replace('*', '%'); newValue2 = newValue2.replace('?', '_'); sb.append(" NOT LIKE " + convertToSql(sqlType, newValue2, q, fieldType)); break; } return sb.toString(); } protected String convertToSql(int sqlType, Object value, BofQuery query, String fieldType) throws ModelException { if (value == null) { throw new ModelException(ResourceKeys.INVALID_NULL); } switch (sqlType) { case Types.DOUBLE: case Types.NUMERIC: return value.toString(); case Types.DECIMAL: if (value.getClass().equals(Timespan.class)) { return ((Timespan) value).getSeconds().toString(); } return value.toString(); case Types.INTEGER: /* * gregorian date conversions... * * Value could be an */ if (value.getClass().equals(Date.class)) { Date dateValue = (Date) value; GregorianDate d = new GregorianDate(dateValue); return "" + d.intValue(); } else if (value.getClass().equals(GregorianDate.class)) { GregorianDate dateValue = (GregorianDate) value; return "" + dateValue.intValue(); } else if (value.getClass().equals(Timespan.class)) { return ((Timespan) value).getSeconds().toString(); } else if (value.getClass().equals(String.class)) { if (fieldType.equals("PONREF") || fieldType.equals("PON") || fieldType.equals("CreateUserDesc") || fieldType.equals("ModifyUserDesc")) { try { return MacroHandler.parseUserMacro(value.toString()); } catch (ParseException pe) { ; } } else { try { Date dateValue = MacroHandler.parseDateMacro(value.toString()); GregorianDate d = new GregorianDate(dateValue); return "" + d.intValue(); } catch (ParseException pe) { ; } } } return value.toString(); case Types.SMALLINT: return value.toString(); case Types.DATE: throw new ModelException(ResourceKeys.UNSUPPORTED_CONVERSION, new Object[] { value.getClass().getName(), "Types.DATE" }); case Types.TIMESTAMP: /* * If the jdbc class is a TIMESTAMP we must call a Oracle function * in order to be able to do comparison. This is for the benefit of * being able to do comparisons on the time and not just the data * value. */ if (value.getClass().equals(Date.class)) { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date dateValue = (Date) value; dateValue = ModelBuilder.modifyForTimeZone(dateValue, (BofPersistenceManager) query.getPersistenceManager(), ModelBuilder.MODEL_TO_STORAGE); String strValue = sdf.format(dateValue); return "convert(DateTime,'" + strValue + "' , 121)"; } /* * Same as above but we have to convert the String to a Date (before * we convert it back to a properly formatted string. */ if (value.getClass().equals(String.class)) { DateFormat sdf = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, new Locale("sv")); DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT, new Locale("sv")); String stringValue = (String) value; Date dateValue; /* * Try to parse the String using different formats in the * following order: 1. Date and Time format 2. Date format TODO: * make this Locale-aware */ try { dateValue = sdf.parse(stringValue); } catch (ParseException e) { try { dateValue = shortDf.parse(stringValue); } catch (ParseException ee) { try { // As a last resort, check to see if one of the // macros have been used dateValue = MacroHandler.parseDateMacro(stringValue); } catch (ParseException eee) { throw new ModelException(ResourceKeys.DATE_CONVERSION_ERROR, new Object[] { stringValue }); } } } dateValue = ModelBuilder.modifyForTimeZone(dateValue, (BofPersistenceManager) query.getPersistenceManager(), ModelBuilder.MODEL_TO_STORAGE); String strValue = sdf.format(dateValue); return "convert(DateTime,'" + strValue + "' , 120)"; } throw new ModelException(ResourceKeys.DATE_CONVERSION_ERROR); case Types.CLOB: case Types.VARCHAR: // used by javaType Boolean stored as VARCHAR2(1) if (value instanceof Boolean) { Boolean bool = (Boolean) value; if (bool.booleanValue()) { return "'1'"; } return "'0'"; } else if (value instanceof Long) { Long lng = (Long) value; return "" + lng.longValue(); } else if (value instanceof String) { String str = (String) value; if (str.indexOf("'") > -1) { str = str.replaceAll("'", "''"); return "'" + str.toString() + "'"; } } return "'" + value.toString() + "'"; case Types.VARBINARY: throw new ModelException(ResourceKeys.UNSUPPORTED_CONVERSION, new Object[] { value.getClass().getName(), "Types.VARBINARY" }); default: throw new ModelException(ResourceKeys.UNKNOWN_SQL_TYPE, new Object[] { "" + sqlType }); } } /** * Returns the database specific character for quoting names. Different * databases have different ways of quoting column names, for example. * * @return String quote character for this database. */ public String getDBQuoteChar() { return quoteChar; } public abstract String getNativeSql(int query) throws ModelException; }
UTF-8
Java
63,747
java
AbstractQueryBuilder.java
Java
[ { "context": "S SQL database (SQL server 2000).\r\n * \r\n * @author Fredrik Hed [f.hed@abalon.se]\r\n */\r\n@SuppressWarnings(\"unchec", "end": 987, "score": 0.9998821020126343, "start": 976, "tag": "NAME", "value": "Fredrik Hed" }, { "context": " (SQL server 2000).\r\n * \r\n * @author Fredrik Hed [f.hed@abalon.se]\r\n */\r\n@SuppressWarnings(\"unchecked\")\r\npublic abs", "end": 1004, "score": 0.9999325275421143, "start": 989, "tag": "EMAIL", "value": "f.hed@abalon.se" } ]
null
[]
package se.abalon.bof; import java.sql.Types; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.log4j.Category; import se.abalon.bof.type.AbalonPrimaryKey; import se.abalon.bof.type.GregorianDate; import se.abalon.bof.type.Timespan; import se.abalon.bof.util.Converter; import se.abalon.bof.util.MacroHandler; import se.abalon.util.MayflowerRuntimeException; import se.abalon.util.StringUtil; /** * Helper to create SQL SELECT statements from a BofQuery object as well as * other native system queries according to a MS SQL database (SQL server 2000). * * @author <NAME> [<EMAIL>] */ @SuppressWarnings("unchecked") public abstract class AbstractQueryBuilder implements QueryBuilder { private static Category log = Category.getInstance(AbstractQueryBuilder.class); private static final String quoteChar = "\""; /** * Optimization: map with globaly constant values which can optimize the * join part of the query */ private Map<String, String> globalConstants = new HashMap<String, String>(); /** * Helper that adds a ORDER BY for all primary key fields in the query. * * @param query * The query object to add the order by statements for * @param modelAlias * the bod to add the primary key to the order by for * @throws ModelException * if the modelAlias found in the query dont exist. This shall * newer happend. */ private void addOrderByForPrimaryKey(BofQuery query, String modelAlias) throws ModelException { String bodName = query.getModels().get(modelAlias); String pkFieldName = ModelDefinition.getInstance(bodName).getPrimaryKeyFieldName(); for(String toBodAlias : query.getRelations(modelAlias).keySet()) { addOrderByForPrimaryKey(query, toBodAlias); } /* * Check if a sort order already exists for this field. If that is the * case we do not set it again since we don't know if it is supposed to * be ascending or descending */ if (!query.hasOrderBy(modelAlias, pkFieldName)) { query.addOrderBy(modelAlias, pkFieldName); // throws ModelException } } public abstract int getDBType(); public String getFetchSql(BofQuery query, String rootAlias) throws ModelException { return getFetchSql(query, rootAlias, null); } public String getFetchDuplicateSql(BofQuery query, String rootAlias, DuplicateFieldMap fieldMap) throws ModelException { return getFetchSql(query, rootAlias, fieldMap); } public String getFetchSql(BofQuery query, String rootAlias, DuplicateFieldMap fieldMap) throws ModelException { Set<String> itemSet = new HashSet<String>(); // contains "...ID as ...ID", // "count("...ID") as ...ID" Set<String> fromSet = new HashSet<String>(); List<String> orderSet = new ArrayList<String>(); /* * Add an order by statement for all primary keys for all bods to assure * that all rows for a bo will be fetched in sequence. */ addOrderByForPrimaryKey(query, rootAlias); fetchItem(query, rootAlias, fromSet, itemSet, false); List<Join> joinList = new ArrayList<Join>(); List<Join> outerJoinList = new ArrayList<Join>(); List<String> groupByList = new ArrayList<String>(); /* * fetch joins according to parent to the root model */ String rootModelName = (String) query.getModels().get(rootAlias); fetchParent(query, rootModelName, rootAlias, fromSet, joinList, outerJoinList, Join.INNER, null); /* * This will use the global constant... */ fetchJoin(query, rootAlias, fromSet, joinList, outerJoinList, null); /* * Optimization: map with globaly constant values which can optimize the * join part of the query */ String where = fetchWhere(query, false, "", true); /* * there are only GROUP BY values if we have an aggregation... */ if (query.hasBodAggregation(rootAlias) && query.getAggregations().keySet().contains(rootAlias)) { fetchGroupBy(query, rootAlias, groupByList); } else { fetchOrder(query, rootAlias, orderSet); } String str = ""; if (fieldMap == null || fieldMap.getAliasModelMap().size() < 1) { // queries with maxnbrhits and conditions str = getFetchSql(false, query, rootAlias, fromSet, itemSet, orderSet, joinList, outerJoinList, groupByList, where); } else { // requests for duplicate queries, ie fields are supplied in call str = getFetchDuplicateSql(query, rootAlias, fromSet, itemSet, orderSet, joinList, outerJoinList, groupByList, where, fieldMap); } return str; } public abstract String getFetchSql(boolean idQuery, BofQuery query, String rootAlias, Set<String> fromSet, Set<String> itemSet, List<String> orderSet, List<Join> joinList, List<Join> outerJoinList, List<String> groupByList, String where) throws ModelException; public abstract String getFetchDuplicateSql(BofQuery query, String rootAlias, Set<String> fromSet, Set<String> itemSet, List<String> orderSet, List<Join> joinList, List<Join> outerJoinList, List<String> groupByList, String where, DuplicateFieldMap fieldMap) throws ModelException; /** * Returns a distinct sql statement for retrieving ids for a given query. * * @param query * @param rootAlias */ public String getFetchIdSql(BofQuery query, String rootAlias) throws ModelException { return getIdSql(query, rootAlias, null); } /** * Returns a distinc sql statement for inserting ids for a given query. * * @param query * @param rootAlias * @param metadata * if metadata is given an INSERT INTO statement is returned */ public String getInsertIdSql(BofQuery query, String rootAlias, AbalonPrimaryKey metadata) throws ModelException { return getIdSql(query, rootAlias, metadata); } /** * Returns a distinc sql statement for retrieving or inserting ids for a * given query. * * @param query * @param rootAlias * @param metadata * if metadata is given an INSERT INTO statement is returned */ String getIdSql(BofQuery query, String rootAlias, AbalonPrimaryKey metadata) throws ModelException { Set<String> itemSet = new HashSet<String>(); // contains "...ID as ...ID", // "count("...ID") as ...ID" Set<String> fromSet = new HashSet<String>(); List<String> orderSet = new ArrayList<String>(); // alias.FIELD_NAME String modelField = query.getFetchOnlyPk(); fetchIdItem(query, rootAlias, modelField, fromSet, itemSet); List<Join> joinList = new ArrayList<Join>(); List<Join> outerJoinList = new ArrayList<Join>(); List<String> groupByList = new ArrayList<String>(); /* * fetch joins according to parent to the root model */ String rootModelName = (String) query.getModels().get(rootAlias); fetchParent(query, rootModelName, rootAlias, fromSet, joinList, outerJoinList, Join.INNER, null); /* * This will use the global constant... */ fetchJoin(query, rootAlias, fromSet, joinList, outerJoinList, null); /* * Optimization: map with globaly constant values which can optimize the * join part of the query */ String where = fetchWhere(query, false, "", true); /* * Instead of rootAlias we fetch the alias specified by getFetchOnlyPK */ String sql = getFetchSql(true, query, rootAlias, fromSet, itemSet, orderSet, joinList, outerJoinList, groupByList, where); /* * build "not null" condition */ String notNullCondition = fetchIdIsNotNullCondition(query, rootAlias, modelField); /* * If we have aggregations (we have stripped all fields except the one * defined by the 'fetchOnlyPrimaryKey') do a count query (ex. * ptestbc.id AS p_ID) */ String[] modelFieldArr = modelField.split("\\."); if (metadata == null && query.getAggregations().containsKey(modelFieldArr[0])) { String str[] = sql.split("\\s+"); // the first enty defined the field to count String countField = str[0]; List<String> elems = Arrays.asList(str); elems = elems.subList(1, elems.size()); sql = StringUtil.join(elems, " "); if (sql.indexOf(" WHERE ") > 0) { return "SELECT count(DISTINCT " + countField + ") " + sql + " AND " + notNullCondition; } return "SELECT count(DISTINCT " + countField + ") " + sql + " WHERE " + notNullCondition; } /* * If no metadata ID is specified, just return a simple SELECT statement */ else if (metadata == null) { if (sql.indexOf(" WHERE ") > 0) { return "SELECT DISTINCT " + sql + " AND " + notNullCondition; } return "SELECT DISTINCT " + sql + " WHERE " + notNullCondition; } /* * Otherwise, generate an INSERT statement that inserts the rows * selected into the mf_datasetrow table, with the metadata PON as a * constant expression. */ if (sql.indexOf(" WHERE ") > 0) { return decorateForInsert(sql + " AND " + notNullCondition, metadata); } return decorateForInsert(sql + " WHERE " + notNullCondition, metadata); } public static String decorateForInsert(String sql, AbalonPrimaryKey metadata) { // INSERT INTO mf_datasetrow (metadata, objref) return "SELECT DISTINCT " + metadata + " as md, " + sql; } private String getJoinsSql(List<Join> outerJoinList, Set<String> fromSet) { StringBuffer join = new StringBuffer(); return getSelectSql(outerJoinList, join, fromSet, new HashSet<String>()).toString(); } protected String getColumnsIDSql(boolean idQuery, Set<String> itemSet) { // special treatment for id queries - the one and only id filed is // always named "id" String columns = ""; List<String> idSet = new ArrayList<String>(); for (Object object : itemSet) { String itemString = (String) object; String[] aliasArr = itemString.split(" AS "); idSet.add(aliasArr[1]); } if (itemSet.size() == 1 && idQuery) { columns = " the_id "; } else { columns = StringUtil.join(idSet, ", "); } return columns; } protected String getSelectAndJoinSql(boolean idQuery, List<Join> outerJoinList, Set<String> fromSet, Set<String> itemSet) { String columns = ""; StringBuffer join = new StringBuffer(); join = getSelectSql(outerJoinList, join, fromSet, new HashSet<String>()); // special treatment for id queries - the one and only id filed is // always named "id" if (itemSet.size() == 1 && idQuery) { String[] str = itemSet.iterator().next().toString().split("\\s+"); columns = str[0] + " AS the_id "; } else { columns = StringUtil.join(itemSet, ", "); } columns += " FROM "; columns += StringUtil.join(fromSet, ", "); if (fromSet.size() == 1 && join.length() == 0) { columns += " WITH (NOLOCK) "; } else if (fromSet.isEmpty() || join.length() == 0) { columns += join.toString(); } else { columns += ", " + join.toString(); } return columns; } protected String getJoinSql(boolean idQuery, List<Join> outerJoinList, Set<String> fromSet, Set<String> itemSet) { String columns = ""; StringBuffer join = new StringBuffer(); join = getSelectSql(outerJoinList, join, fromSet, new HashSet<String>()); // special tratement for id queries - the one and only id filed is // allways named "id" if (itemSet.size() == 1 && idQuery) { String[] str = itemSet.iterator().next().toString().split("\\s+"); columns = str[0] + " AS the_id "; } else { columns = StringUtil.join(itemSet, ", "); } columns += " FROM "; columns += StringUtil.join(fromSet, ", "); boolean aggregated = false; if(!outerJoinList.isEmpty()) { for (Join joinListItem : (List<Join>)outerJoinList) { if(joinListItem.type==Join.AGGREGATION) { aggregated=true; break; } } } if (fromSet.size() == 1 && join.length() == 0) { columns += " WITH (NOLOCK) "; } else if (fromSet.size() == 1 && aggregated) { columns += join.toString(); } else if (fromSet.isEmpty() || join.length() == 0) { columns += join.toString(); } else { columns += ", " + join.toString(); } return columns; } private StringBuffer getSelectSql(List<Join> joinList, StringBuffer sb, Set<String> fromSet, Set<String> joined) { for(Join oj : joinList) { if (sb.length() == 0 || (!joined.contains(oj.on) && oj.type==Join.AGGREGATION)) { /* * Bugfix. Some queries results in inner joins on the same table * on the same columns. */ if(oj.type==Join.AGGREGATION) { sb.append(oj.getJoinSql()); sb.append("(SELECT "); sb.append(oj.relationField); sb.append(", "); Iterator<String> aggregationItor = oj.aggregations.keySet().iterator(); while(aggregationItor.hasNext()) { String aggregateBodField = aggregationItor.next(); String aggregateField = null; String aggregation = null; Object tmpAggregation = oj.aggregations.get(aggregateBodField); if(tmpAggregation instanceof Map<?,?>) { for(String key : ((Map<String, String>)tmpAggregation).keySet()) { aggregateField = key; aggregation = ((Map<String, String>)tmpAggregation).get(key); } } if(!aggregateField.equals("id") && !aggregateField.equals("isa_instance") && !oj.aggregations.containsKey("ID") && !oj.aggregations.containsKey("ISA_INSTANCE")) { sb.append(aggregation); sb.append("("); sb.append(aggregateField); sb.append(") AS id, "); } sb.append(aggregation); sb.append("("); sb.append(aggregateField); sb.append(") AS "); sb.append(aggregateField); if(aggregationItor.hasNext()) { sb.append(", "); } } sb.append(" from "); //sb.append(oj.table); String fromStr = getJoinsSql(oj.parentAggregationJoins, fromSet); if(fromStr.length()==0) { fromStr = oj.table; } sb.append(fromStr); if(oj.conditionStr!=null && !oj.conditionStr.equals("")) { sb.append(" where "); sb.append(oj.conditionStr); } sb.append(" group by "); sb.append(oj.relationField); sb.append(") "); sb.append(oj.aggTo); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.table + " " + oj.to); } else if (!oj.from.equals(oj.to)) { sb.append(oj.from); sb.append(" WITH (NOLOCK) "); sb.append(oj.getJoinSql()); sb.append(oj.to); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.from); fromSet.remove(oj.to); } } else if (joined.contains(oj.from)) { sb.append(oj.getJoinSql()); sb.append(oj.to); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.to); } else if (joined.contains(oj.to)) { sb.append(oj.getJoinSql()); sb.append(oj.from); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.from); } else { sb.append(", "); sb.append(oj.from); sb.append(" WITH (NOLOCK) "); sb.append(oj.getJoinSql()); sb.append(oj.to); sb.append(" WITH (NOLOCK) "); sb.append(" ON "); sb.append(oj.on); fromSet.remove(oj.from); fromSet.remove(oj.to); } joined.add(oj.from); joined.add(oj.to); } return sb; } /** * Follows all relations defined in query. For each relation found, * fetchParent is called. * * @param query * @param internalModelName * @param fromSet * @param joinList * @param outerJoinList * @param forceInnerJoin * @throws ModelException */ private void fetchJoin(BofQuery query, String internalModelName, Set<String> fromSet, List<Join> joinList, List<Join> outerJoinList, String token) throws ModelException { ModelDefinition fromBod; ModelDefinition toBod; ModelRelation bodRelation; String fromModel; String toTable; String toField; String fromTable; String fromField; String toInternalModelName; int cardinality; // TODO: handle null token if (token == null) token = ""; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException Condition tmpC = query.clearConditions(); List<Condition> tmpCondList = getConditionsList(tmpC); List<Condition> queryCondList = new ArrayList<Condition>(tmpCondList); /* * build inner and outer joins for all relations */ for(String relationName : query.getRelationsFromMe(internalModelName)) { toInternalModelName = query.getRelationsToMe().get(internalModelName + "." + relationName); String toModel = query.getModels().get(toInternalModelName); toBod = ModelDefinition.getInstance(toModel); bodRelation = fromBod.getModelRelation(relationName); cardinality = bodRelation.getCardinality(); if (cardinality == ModelRelation.CARDINALITY_0M) { fromTable = fromBod.getStorageTable(bodRelation.getField()); // throws // ModelException fromField = fromBod.getStorageColumn(bodRelation.getField()); // throws // ModelException toTable = toBod.getStorageTable(bodRelation.getForeignField()); // throws // ModelException toField = toBod.getStorageColumn(bodRelation.getForeignField()); // throws // ModelException } else { fromTable = fromBod.getStorageTable(bodRelation.getForeignField()); // throws // ModelException fromField = fromBod.getStorageColumn(bodRelation.getForeignField()); // throws // ModelException toTable = toBod.getStorageTable(bodRelation.getField()); // throws // ModelException toField = toBod.getStorageColumn(bodRelation.getField()); // throws // ModelException } /* * optimization, if both query.getModelDefinitions() has * queryFields, there must be bo's in both query. * getModelDefinitions() and there is no need to do a OUTER JOIN */ Join oj = null; Map<String, Object> aggregationMap = null; int joinType; if ((query.hasCondition(internalModelName) && (query.hasCondition(toInternalModelName) && !query.hasBodAggregation(toInternalModelName)) || cardinality == ModelRelation.CARDINALITY_11)) { joinType = Join.INNER; } else if(query.hasBodAggregation(toInternalModelName)) { joinType = Join.AGGREGATION; Map<String, String> strAggregationMap = query.getAggregations().get(toInternalModelName); aggregationMap = new HashMap<String, Object>(strAggregationMap); } else { // outer join here to fetch all bos where relation dont have // bos... joinType = Join.OUTER; } oj = new Join(joinType); oj.from = fromTable + " " + BofPersistenceManager.getIdentifier(internalModelName, fromTable) + token; boolean useAggTo = false; if(joinType==Join.AGGREGATION) { List<Join> parentJoins = new ArrayList<Join>(); if(!toBod.getStorageTable(toBod.getPrimaryKeyFieldName()).equals(toTable)) { oj.aggTo = BofPersistenceManager.getIdentifier(toInternalModelName, toBod.getStorageTable(toBod.getPrimaryKeyFieldName())) + token; useAggTo = true; } else { oj.aggTo = BofPersistenceManager.getIdentifier(toInternalModelName, toTable) + token; } oj.to = BofPersistenceManager.getIdentifier(toInternalModelName, toTable) + token; oj.table = toTable; // Insert conditions into aggregation join. Just the conditions that is supposed to be here. List<Condition> innerCondList = new ArrayList<Condition>(); moveInnerConditions(toInternalModelName, aggregationMap, tmpCondList, queryCondList, innerCondList); Map<String, Object> tmpAggregationMap = new HashMap<String, Object>(aggregationMap); for(String aggKey : tmpAggregationMap.keySet()) { if(tmpAggregationMap.get(aggKey) instanceof String) { String aggValue = aggregationMap.get(aggKey).toString(); String resolvedAggKey = toBod.getStorageColumn(aggKey); Map<String, String> resolvedMap = new HashMap<String, String>(); resolvedMap.put(resolvedAggKey, aggValue); aggregationMap.remove(aggKey); aggregationMap.put(aggKey, resolvedMap); } } fetchParent(query, toModel, toInternalModelName, fromSet, parentJoins, outerJoinList, Join.INNER, token); oj.parentAggregationJoins = parentJoins; Condition innerCond = createConditionFromList(innerCondList); oj.conditionStr = fetchWhere(query, innerCond, false, "", false); } else { oj.to = toTable + " " + BofPersistenceManager.getIdentifier(toInternalModelName, toTable) + token; } if(useAggTo) { oj.on = getId(internalModelName, fromTable, fromField, token) + " = " + getId(toInternalModelName, toBod.getStorageTable(toBod.getPrimaryKeyFieldName()), toField, token); } else { oj.on = getId(internalModelName, fromTable, fromField, token) + " = " + getId(toInternalModelName, toTable, toField, token); } oj.relationField = toField; oj.aggregations = aggregationMap; outerJoinList.add(oj); if(joinType!=Join.AGGREGATION) { fetchParent(query, toModel, toInternalModelName, fromSet, joinList, outerJoinList, joinType, token); } if (query.getModels().containsKey(toInternalModelName)) { fetchJoin(query, toInternalModelName, fromSet, joinList, outerJoinList, token); // recursion } } for(Condition cond : queryCondList) { query.addCondition(cond); } } /** * Get a list of Conditions from a {@link Condition}. {@link ComplexCondition} with OR operator * will be returned as ComplexConditions. All other will be returned as a {@link ConstantCondition}. * * @param condition * @return */ private java.util.List<Condition> getConditionsList(Condition condition){ java.util.List<Condition> conditions = new ArrayList<Condition>(); java.util.List<Condition> tmpConditions = new ArrayList<Condition>(); if(condition instanceof ComplexCondition){ ComplexCondition comp = (ComplexCondition)condition; if(comp.getOperation()==Condition.OR) { conditions.add(comp); } else { Condition c1 = comp.getCondition1(); Condition c2 = comp.getCondition2(); if(c1 != null) tmpConditions.add(c1); if(c2 != null) tmpConditions.add(c2); } for(Condition cond : tmpConditions) { if(cond instanceof ComplexCondition) { conditions.addAll(getConditionsList(cond)); } else { conditions.add(cond); } } } else if(condition instanceof ConstantCondition){ conditions.add(condition); } return conditions; } /** * Creates a single {@link ComplexCondition} from a list of Conditions. If the list * contains only one object it will be returned by itself (can be a {@link ConstantCondition}) * * @param condList * @return */ private Condition createConditionFromList(java.util.List<Condition> condList) { if(condList.size()==0) { return null; } if(condList.size()==1) { return condList.iterator().next(); } Condition c1 = condList.remove(0); Condition c2 = condList.remove(0); ComplexCondition comp = new ComplexCondition(c1, c2, Condition.AND); for(Condition cond : condList) { comp = new ComplexCondition(comp, cond, Condition.AND); } return comp; } /** * Move conditions for aggregations from query to the Join condition list * * It adds IS NOT NULL and IS NULL conditions depending on the original * conditions. * * @param toInternalModelName * @param aggregationMap * @param tmpCondList * @param queryCondList * @param innerCondList */ private void moveInnerConditions(String toInternalModelName, Map<String, Object> aggregationMap, List<Condition> tmpCondList, List<Condition> queryCondList, List<Condition> innerCondList) { for (Condition cond : tmpCondList) { if(cond instanceof ComplexCondition) { Condition c1 = ((ComplexCondition)cond).getCondition1(); Condition c2 = ((ComplexCondition)cond).getCondition2(); if(((ComplexCondition)cond).getOperation()==Condition.OR) { if(((ConstantCondition)c1).getBodAlias().equals(toInternalModelName) && ((ConstantCondition)c2).getBodAlias().equals(toInternalModelName)) { if(!aggregationMap.containsKey(((ConstantCondition)c1).getField()) && !aggregationMap.containsKey(((ConstantCondition)c2).getField())) { if(queryCondList.remove(cond)) { if(((ConstantCondition)c1).getOperation()!=Condition.IS_NULL || ((ConstantCondition)c2).getOperation()!=Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NOT_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } innerCondList.add(cond); } else if(((ConstantCondition)c1).getOperation()==Condition.IS_NULL || ((ConstantCondition)c2).getOperation()==Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } } } } } } } else { if(((ConstantCondition)cond).getBodAlias().equals(toInternalModelName)) { if(!aggregationMap.containsKey(((ConstantCondition)cond).getField())) { if(queryCondList.remove(cond)) { if(((ConstantCondition)cond).getOperation()!=Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NOT_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } innerCondList.add(cond); } else if(((ConstantCondition)cond).getOperation()==Condition.IS_NULL) { ConstantCondition notNullCond = new ConstantCondition(toInternalModelName, "ID", Condition.IS_NULL); if(queryCondList.isEmpty() || !queryCondList.contains(notNullCond)) { queryCondList.add(notNullCond); } } } } else { System.out.println(cond); } } } } } private String getId(String modelAlias, String table, String field, String innerToken) { if (innerToken == null) innerToken = ""; String key = BofPersistenceManager.getIdentifier(modelAlias, table) + innerToken + "." + field; if (globalConstants.containsKey(key)) { return globalConstants.get(key); } return key; } /** * Adds table entries to fromSet (format: [table name] [table alias]) and * join entries to the joinList (format: [table alias 1].[column name 1] = * [table alias 2].[column name 2]) * * All parent joins are INNER JOINS. * * @param internalModelName * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param joinList * the join set to be populated * @param forceOuterJoin * forces join sql parts to be outer joins * @throws ModelException * if the model does not match the ModelDefinition */ protected void fetchParent(BofQuery query, String modelName, String modelAlias, Set<String> fromSet, List<Join> joinList, List<Join> outerJoinList, int joinType, String innerToken) throws ModelException { ModelDefinition fromBod; String fromTable; String fromField; String toTable; String toField; // handle null values of inner token if (innerToken == null) innerToken = ""; fromBod = ModelDefinition.getInstance(modelName); // throws // ModelException ModelDefinition pBod = null; if (fromBod.getParentName() != null && fromBod.getParentName().length() > 0) { try { pBod = ModelDefinition.getInstance(fromBod.getParentName()); // throws // ModelException } catch (ModelException e) { // no defined model name } } if (pBod != null) { fromTable = fromBod.getStorage(); fromField = fromBod.getPrimaryKeyStorageColumn(); toTable = pBod.getStorage(); toField = pBod.getPrimaryKeyStorageColumn(); Join oj = null; /* * parent model with no storage - No join needed. */ if (fromTable.equals("") || toTable.equals("")) { // No join needed. } /* * parent model with storage in same table - No join needed. */ else if (fromTable.equals(toTable) && fromField.equals(toField)) { // No join needed. } else { oj = new Join(joinType); } if (oj != null) { oj.from = fromTable + " " + BofPersistenceManager.getIdentifier(modelAlias, fromTable) + innerToken; oj.to = toTable + " " + BofPersistenceManager.getIdentifier(modelAlias, toTable) + innerToken; oj.on = getId(modelAlias, fromTable, fromField, innerToken) + " = " + getId(modelAlias, toTable, toField, innerToken); if (joinType == Join.INNER) { joinList.add(oj); } else { outerJoinList.add(oj); } } /* * call fetchParent for the parent */ if (fromBod.getParentName() != null && !fromBod.getParentName().equals("")) { fetchParent(query, fromBod.getParentName(), modelAlias, fromSet, joinList, outerJoinList, joinType, innerToken); } /* * fetch relations for parent */ fetchJoin(query, modelAlias, fromSet, joinList, outerJoinList, innerToken); } } /** * Adds table entries to fromSet (format: [table name] [table alias]) and * item entries to the itemSet (format: [table alias].[column name] AS * [model alias]_[column alias]) * * @param internalModelName * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param itemSet * the item set to be populated * @throws ModelException * if the model does not match the ModelDefinition */ private void fetchItem(BofQuery query, String internalModelName, Set<String> fromSet, Set<String> itemSet, boolean inner) throws ModelException { String fromField; String fromTable; String fromModel; ModelDefinition fromBod; List<String> itemNames; Map<String, String> myAggregations; Boolean hasAggregations = false; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException // TODO: move this to the checkRelations method... if (!query.getFields().containsKey(internalModelName)) { itemNames = new ArrayList<String>(); itemNames.add("ID"); // allways add businessObject query.getFields().put(internalModelName, itemNames); log.warn("fetchItem (" + internalModelName + ") no items to add ... PATCH added ID!!!"); } if(!query.getAggregations().isEmpty() && query.getAggregations().containsKey(internalModelName)){ hasAggregations = true; } // if we have aggregations fetch them, otherwise make a dummy Map... if (query.getAggregations().containsKey(internalModelName)) { myAggregations = query.getAggregations().get(internalModelName); } else { myAggregations = new HashMap<String, String>(); } if (query.getFields().containsKey(internalModelName)) { for(String itemName : query.getFields().get(internalModelName)) { fromField = fromBod.getStorageColumn(itemName); fromTable = fromBod.getStorageTable(itemName); if(!fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()).equals(fromTable) && hasAggregations) { //fromTable = fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()); } // If the storage column is "" this indicates that it is a // virtual field that has no storage... if (fromField.equals("")) { continue; } String mangledName = ""; if (inner) { mangledName = BofPersistenceManager.getIdentifier(internalModelName, fromTable + "_inner"); } else { mangledName = BofPersistenceManager.getIdentifier(internalModelName, fromTable); } String mangledAlias = ""; if (inner) { mangledAlias = BofPersistenceManager.getIdentifier(internalModelName + "_inner", itemName); } else { mangledAlias = BofPersistenceManager.getIdentifier(internalModelName, itemName); } // aggregation item... // "count(personPERSON.NAMN) AS person_NAME" if (myAggregations.keySet().contains(itemName) || (!myAggregations.isEmpty() && !myAggregations.keySet().contains(itemName) && itemName.equals("ID"))) { String aggregationType = myAggregations.get(itemName); if(aggregationType==null && itemName.equals("ID") && internalModelName.equals(query.getRootAlias())) { String aggFromField = ""; for (Object key : myAggregations.keySet()) { aggregationType = myAggregations.get(key); aggFromField = fromBod.getStorageColumn(key.toString()); } itemSet.add(aggregationType + "(" + mangledName + "." + aggFromField + ")" + " AS " + mangledAlias); } else { if(internalModelName.equals(query.getRootAlias())) { itemSet.add(aggregationType + "(" + mangledName + "." + fromField + ")" + " AS " + mangledAlias); } else { itemSet.add(mangledName + "." + fromField + " AS " + internalModelName+"_" + itemName); if(itemName.equals("ID")) { itemSet.add(mangledName + "." + fromField + " AS " + internalModelName+"_" + aggregationType); } } } } // normal item... // "personPERSON.NAMN AS person_NAME" else { if(!hasAggregations){ String iName = mangledName + "." + fromField + " AS " + mangledAlias; itemSet.add(iName); } else { itemSet.add("COUNT(" + mangledName + "." + fromField + ")" + " AS " + mangledAlias); } } fromSet.add(fromTable + " " + mangledName); } } for(String toInternalRelationName : query.getRelations(internalModelName).keySet()) { fetchItem(query, toInternalRelationName, fromSet, itemSet, inner); // recursion } } private String fetchIdIsNotNullCondition(BofQuery query, String modelAlias, String fieldName) throws ModelException { String[] str = fieldName.split("\\."); String model = query.getModels().get(str[0]); ModelDefinition md = ModelDefinition.getInstance(model); // throws String column = md.getStorageColumn(str[1]); String table = md.getStorageTable(str[1]); return BofPersistenceManager.getIdentifier(str[0], table) + "." + column + " is not null"; } /** * * @param query * @param modelAlias * @param fieldName * alias.FIELD_NAME * @param fromSet * @param itemSet * @throws ModelException */ private void fetchIdItem(BofQuery query, String modelAlias, String fieldName, Set<String> fromSet, Set<String> itemSet) throws ModelException { String fromField; String fromTable; String fromModel; ModelDefinition fromBod; List<String> itemNames; fromModel = (String) query.getModels().get(modelAlias); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException String[] str = fieldName.split("\\."); if (!query.getFields().containsKey(str[0]) && modelAlias.equals(str[0])) { itemNames = new ArrayList<String>(); itemNames.add(str[1]); // always add businessObject query.getFields().put(str[0], itemNames); } // TODO: move this to the checkRelations method... /* * if (!query.getFields().containsKey(modelAlias)) { itemNames = new * ArrayList(); itemNames.add("ID"); // allways add businessObject * query.getFields().put(modelAlias, itemNames); log.warn("fetchItem (" + * modelAlias + ") no items to add ... PATCH added ID!!!"); } */ // if we have aggregations fetch them, otherwise make a dummy Map... /* * if (query.getAggregations().containsKey(modelAlias)) { myAggregations = * (Map) query.getAggregations().get( modelAlias); } else { * myAggregations = new HashMap(); } */ if (query.getFields().containsKey(modelAlias)) { for(String itemName : query.getFields().get(modelAlias)) { fromField = fromBod.getStorageColumn(itemName); fromTable = fromBod.getStorageTable(itemName); if(!fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()).equals(fromTable) && query.hasAggregation(modelAlias)) { fromTable = fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()); } // If the storage column is "" this indicates that it is a // virtual field that has no storage... if (fromField.equals("")) { continue; } // aggregation item... // "count(personPERSON.NAMN) AS person_NAME" /* * if (myAggregations.keySet().contains(itemName)) { String * aggregationType = (String) myAggregations .get(itemName); * itemSet.add(aggregationType + "(" + * BofPersistenceManager.getIdentifier( modelAlias, fromTable) + * "." + fromField + ")" + " AS " + modelAlias + "_" + * itemName); } */// normal item... // "personPERSON.NAMN AS person_NAME" // else { if (modelAlias.equals(str[0]) && itemName.equals(str[1])) { itemSet.add(BofPersistenceManager.getIdentifier(modelAlias, fromTable) + "." + fromField + " AS " + modelAlias + "_" + itemName); } fromSet.add(fromTable + " " + BofPersistenceManager.getIdentifier(modelAlias, fromTable)); } } for(String toInternalRelationName : query.getRelations(modelAlias).keySet()) { fetchIdItem(query, toInternalRelationName, fieldName, fromSet, itemSet); // recursion } } /* * private void fetchIdItem(BofQuery query, String modelAlias, String * fieldName, Set fromSet, Set itemSet) throws ModelException { String * itemName; String fromField; String fromTable; String fromModel; * ModelDefinition fromBod; Iterator itemIterator; * * fromModel = (String) query.getModels().get(modelAlias); fromBod = * ModelDefinition.getInstance(fromModel); // throws // ModelException * * if (query.getFields().containsKey(modelAlias)) { itemIterator = ((List) * query.getFields().get(modelAlias)) .iterator(); * * while (itemIterator.hasNext()) { itemName = (String) itemIterator.next(); * fromField = fromBod.getStorageColumn(itemName); fromTable = * fromBod.getStorageTable(itemName); * * if (itemName.equals(fieldName)) { // If the storage column is "" this * indicates that it is a // virtual field that has no storage... if * (fromField.equals("")) { continue; } // normal item... // * "personPERSON.NAMN AS person_NAME" * itemSet.add(BofPersistenceManager.getIdentifier(modelAlias, fromTable) + * "." + fromField + " AS " + modelAlias + "_" + itemName); * fromSet.add(fromTable + " " + * BofPersistenceManager.getIdentifier(modelAlias, fromTable)); } } } } */ /** * Joins all elements in the collection after the convertToSql are applyed * to all conditions-values. * * @param sqlType * the type to convert the elements to * @param c * the Colleciton of conditions-values to join * @param fieldType * TODO */ private String join(int sqlType, Collection<Object> c, BofQuery query, String fieldType) throws ModelException { StringBuffer sb = new StringBuffer(); for(Object o : c) { if (sb.length() > 0) { sb.append(","); } sb.append(convertToSql(sqlType, o, query, fieldType)); } return sb.toString(); } /** * Original fetchOrder for safety. Never used anymore * * @param query * @param internalModelName * @param orderSet * @throws ModelException */ @Deprecated @SuppressWarnings("unused") private void fetchOrder_org(BofQuery query, String internalModelName, List<String> orderSet) throws ModelException { String itemName; Integer sortOrder; String fromField; String fromModel; ModelDefinition fromBod; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // BodException String ascendingStr = "ASC"; String descendingStr = "DESC"; if (query.getOrderBy().containsKey(internalModelName)) { List<List<Object>> orderList = query.getOrderBy().get(internalModelName); /* * This is a list with lists in it (fieldName/sortorder pairs) */ String sortStr; for(List<Object> orderPair : orderList) { // itemName = (String) itemIterator.next(); itemName = (String) orderPair.get(0); sortOrder = (Integer) orderPair.get(1); if (sortOrder.intValue() == Condition.ASCENDING) { sortStr = ascendingStr; } else { sortStr = descendingStr; } /* * If the storage column is "" this indicates that it is a * virtual field that has no storage... */ fromField = fromBod.getStorageColumn(itemName); if (fromField.equals("")) { continue; } /* * Fields that are not part of the fetch-set might still be used * to sort. To make sure that the fields are accessed correctly * we reference all these field like: <tablealias>.<columnname> */ String columnName = fromBod.getField(itemName).getStorageColumn(); String tableName = fromBod.getField(itemName).getStorageTable(); String tableAlias = BofPersistenceManager.getIdentifier(internalModelName, tableName); orderSet.add(tableAlias + "." + columnName + " " + sortStr); // originally: // orderSet.add(internalModelName + "_" + itemName + " " + // sortStr); } } for(String toInternalRelationName : query.getRelations(internalModelName).keySet()) { fetchOrder(query, toInternalRelationName, orderSet); // recursion } } /** * Builds the orderBys for the query according the orderOfOrderBys listing. * * @param query * @param internalModelName * @param orderSet * @param inner * @throws ModelException */ private void fetchOrder(BofQuery query, String xxxinternalModelName, List<String> orderSet) throws ModelException { String itemName; Integer sortOrder; String fromField; String fromModel; ModelDefinition fromBod; // for each entry in the orderOfOrderBy add an entry in the orderSet // list List<String> orderOfOrders = query.getOrderOfOrders(); for (String alias : orderOfOrders) { fromModel = (String) query.getModels().get(alias); fromBod = ModelDefinition.getInstance(fromModel); // throws String ascendingStr = "ASC"; String descendingStr = "DESC"; if (query.getOrderBy().containsKey(alias) && !query.getAggregations().keySet().contains(alias)) { List<List<Object>> orderList = query.getOrderBy().get(alias); /* * This is a list with lists in it (fieldName/sortorder pairs) */ String sortStr; for(List<Object> orderPair : orderList) { // itemName = (String) itemIterator.next(); itemName = (String) orderPair.get(0); // TODO: think again.. -we dont want to order by id values // when maxNbrHits is set, but do we really want to do this // here? if (itemName != null && itemName.equals("ID") && query.getMaxNbrHits() != 0) continue; sortOrder = (Integer) orderPair.get(1); if (sortOrder.intValue() == Condition.ASCENDING) { sortStr = ascendingStr; } else { sortStr = descendingStr; } /* * If the storage column is "" this indicates that it is a * virtual field that has no storage... */ fromField = fromBod.getStorageColumn(itemName); if (fromField.equals("")) { continue; } /* * Fields that are not part of the fetch-set might still be * used to sort. To make sure that the fields are accessed * correctly we reference all these field like: * <tablealias>.<columnname> */ String columnName = fromBod.getField(itemName).getStorageColumn(); String tableName = fromBod.getField(itemName).getStorageTable(); String tableAlias = BofPersistenceManager.getIdentifier(alias, tableName); orderSet.add(tableAlias + "." + columnName + " " + sortStr); } } } } /** * Adds group by entries to the groupBySet (format: [table alias].[column * name]) * * @param internalModelName * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param joinList * the join set to be populated * @throws ModelException * if the model does not match the ModelDefinition */ private void fetchGroupBy(BofQuery query, String internalModelName, List<String> groupByList) throws ModelException { String fromField; String fromTable; String fromModel; ModelDefinition fromBod; Map<String, String> myAggregations; fromModel = (String) query.getModels().get(internalModelName); fromBod = ModelDefinition.getInstance(fromModel); // throws // ModelException // if we have aggregations fetch them, otherwise make a dummy Map... if (query.getAggregations().containsKey(internalModelName)) { myAggregations = query.getAggregations().get(internalModelName); } else { myAggregations = new HashMap<String, String>(); } /* * Add all userdefined group by from query */ if (query.getGroupBy().containsKey(internalModelName)) { List<String> groupByFields = query.getGroupBy().get(internalModelName); for(String field : groupByFields) { fromField = fromBod.getStorageColumn(field); fromTable = fromBod.getStorageTable(field); if (fromField.equals("")) { continue; } String groupBySql = BofPersistenceManager.getIdentifier(internalModelName, fromTable) + "." + fromField; if (!groupByList.contains(groupBySql)) { groupByList.add(groupBySql); } } } /* * recursivly add all used defined fields */ for(String toInternalRelationName : query.getRelations(internalModelName).keySet()) { fetchGroupBy(query, toInternalRelationName, groupByList); // recursion } /* * Add all field not added so fare and are not aggregated fields */ if (query.getFields().containsKey(internalModelName)) { // add all items not declared as aggregation... for(String itemName : query.getFields().get(internalModelName)) { if (myAggregations.keySet().contains(itemName) || itemName.equals("ID")) { continue; } fromField = fromBod.getStorageColumn(itemName); fromTable = fromBod.getStorageTable(itemName); if (fromField.equals("")) { continue; } String groupBySql = BofPersistenceManager.getIdentifier(internalModelName, fromTable) + "." + fromField; if (!groupByList.contains(groupBySql)) { groupByList.add(groupBySql); } // groupByList.add(BofPersistenceManager.getIdentifier(internalModelName, // fromTable) + "." + fromField); } } } /** * Sorts a List with outerJoin Objects in chains. Where the elements in the * lists related like: * * <p> * <code>outerJoin1.to = outerJoin7.from<code><br> * <code>outerJoin7.to = outerJoin3.from<code><br> * ... */ protected static List<Join> sort(List<Join> list) { if (list.isEmpty()) { return list; } /* * remove multiple instances... */ List<Join> toSort = new ArrayList<Join>(); for(Join oj : list) { if (!toSort.contains(oj)) { toSort.add(oj); } } /* * sort */ List<Join> newlySorted = new ArrayList<Join>(); LinkedList<Join> sorted = new LinkedList<Join>(); sorted.add(toSort.remove(0)); // add first element do { boolean found = false; toSort.removeAll(newlySorted); sorted.addAll(newlySorted); newlySorted.clear(); Iterator<Join> leftItor = toSort.iterator(); while (leftItor.hasNext() && !found) { Join left = leftItor.next(); Iterator<Join> sortedItor = sorted.iterator(); while (sortedItor.hasNext() && !found) { Join aSorted = sortedItor.next(); if (aSorted.to.equals(left.from)) { newlySorted.add(left); found = true; } else if (aSorted.from.equals(left.from)) { newlySorted.add(left); found = true; } else if (aSorted.to.equals(left.to)) { newlySorted.add(left); found = true; } else if (aSorted.from.equals(left.to)) { newlySorted.add(left); found = true; } } } } while (!newlySorted.isEmpty()); /* * all we could not sort... just add them... */ sorted.addAll(toSort); return sorted; } protected class Join { protected static final int OUTER = 1; protected static final int INNER = 2; protected static final int AGGREGATION = 3; int type = OUTER; public String from; public String to; public String aggTo; public String on; public String table; public String relationField; public Map<String, Object> aggregations; public List<Join> parentAggregationJoins; public String conditionStr; public Join() { type = OUTER; } public Join(int type) { this.type = type; } /** * converting Columns and Tables to lower case * */ public void toLower() { } public String getJoinSql() { if (type == INNER) { return (" LEFT JOIN "); } return (" LEFT OUTER JOIN "); } /* * public String toString() { return from + " -> " + to + " (" + on + * ")"; } */ public boolean equals(Object o) { Join oj; if (o == null) { return false; } try { oj = (Join) o; } catch (ClassCastException e) { return false; } if (!oj.from.equals(from)) { return false; } if (!oj.to.equals(to)) { return false; } if (!oj.on.equals(on)) { return false; } return true; } public int hashCode() { return from.hashCode() + 13 * to.hashCode() + 13 * 13 * on.hashCode(); } } /** * * @param modelAlias * the name of the root model to express as sql * @param fromSet * the form set to be populated * @param joinList * the join set to be populated * @throws BodException * if the model does not match the BusinessObjectDefinition */ private String fetchWhere(BofQuery query, boolean inner, String suffix, boolean useAlias) throws ModelException { Condition cond = query.getCondition(); if (cond == null) { return ""; } return getSql(cond, query, globalConstants, useAlias); } private String fetchWhere(BofQuery query, Condition cond, boolean inner, String suffix, boolean useAlias) throws ModelException { if (cond == null) { return ""; } return getSql(cond, query, globalConstants, useAlias); } /** * Recursivly walks down the Condition tree and generates the WHERE clause * for the SQL. Recursion for every ComplexCondition node found. * * @param condition * the condition to generate SQL for * @param q * the Query where the Bod, relations and fields are declared * @param constant * a Map of column identifiers [table alias].[column] keys * pointing to the equivalent constant for the column. This can * be used to optimize the query * @throws BodException * if unexpected data are found in Query or if an unsupported * implementation of Condition is found */ private String getSql(Condition condition, BofQuery q, Map<String, String> constant, boolean useAlias) throws ModelException { if (condition instanceof ComplexCondition) { ComplexCondition c = (ComplexCondition) condition; StringBuffer sb = new StringBuffer(); Map<String, String> myConstants = new HashMap<String, String>(); sb.append("("); sb.append(getSql(c.getCondition1(), q, myConstants, useAlias)); sb.append(" ").append(getOperation(c.getOperation())).append(" "); sb.append(getSql(c.getCondition2(), q, myConstants, useAlias)); sb.append(")"); if (c.getOperation() == Condition.AND) { constant.putAll(myConstants); } return sb.toString(); } else if (condition instanceof ConstantCondition) { return getConstantConditionSql((ConstantCondition) condition, q, constant, useAlias); } throw new MayflowerRuntimeException(ResourceKeys.UNKNOWN_CONDITION, new Object[] { condition }); } private String getOperation(int op) throws ModelException { if (op == Condition.AND) { return "AND"; } if (op == Condition.OR) { return "OR"; } throw new ModelException(ResourceKeys.UNKNOWN_OPERATION, new Object[] { "" + op }); } /** * Generates SQL for a end node (leaf) in a ComplexCondition. * * <p> * This implementation uses OracleSpecific handling for String to Date * transformations. * * @todo move locale and oracle formating string to resource... * @param c * the condition to generate SQL for * @param q * the Query where the Bod, relations and fields are declared * @throws BodException * if unexpected data are found in Query */ private String getConstantConditionSql(ConstantCondition c, BofQuery q, Map<String, String> constant, boolean useAlias) throws ModelException { String fromModel; ModelDefinition fromBod; String fromTable; String aliasTable; String column; fromModel = (String) q.getModels().get(c.getBodAlias()); fromBod = ModelDefinition.getInstance(fromModel); // throws // BodException fromTable = fromBod.getStorageTable(c.getField()); // throws // BodException aliasTable = fromTable; column = fromBod.getStorageColumn(c.getField()); // throws // BodException // Check for aggregated values and correct the aliasTable if(!fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()).equals(fromTable) && (q.hasAggregation(c.getBodAlias())&&q.hasAggregation(c.getBodAlias(), c.getField()))) { aliasTable = fromBod.getStorageTable(fromBod.getPrimaryKeyFieldName()); } StringBuffer sb = new StringBuffer(); /* * allways use the format <modelAlias><tableName>.<columnName> or some * other secret unit como for <modelAlias> and <tableName> */ String key = ""; if(useAlias) key = BofPersistenceManager.getIdentifier(c.getBodAlias(), aliasTable) + "." + column; else key = column; sb.append(key); String newValue = null; String fieldType = fromBod.getField(c.getField()).getFieldType(); int sqlType = Converter.itemJdbcIntMap(fieldType, getDBType()); switch (c.getOperation()) { case Condition.EXACT: /* * !!! REMOVE THIS !!!! An exact query on the String '*' is a valid * Query */ /* * if (c.getCondition().getClass().equals(String.class) && * ((String)c.getCondition()).equals("*")) { sb.append(" IS NOT * NULL"); log.warn("A single '*' is found in "); } else { */ sb.append("=" + convertToSql(sqlType, c.getCondition(), q, fieldType)); /* * optimization - this constant might be used to optimize the * query... */ if (constant.containsKey(key)) { constant.remove(key); } else { constant.put(key, convertToSql(sqlType, c.getCondition(), q, fieldType)); } // } break; case Condition.NOT_EXACT: sb.append("!=" + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.LIKE: newValue = (c.getCondition().toString()).replace('*', '%'); newValue = newValue.replace('?', '_'); sb.append(" LIKE " + convertToSql(Types.VARCHAR, newValue, q, fieldType)); break; case Condition.STARTS_WITH: newValue = c.getCondition().toString() + "%"; sb.append(" LIKE " + convertToSql(Types.VARCHAR, newValue, q, fieldType)); break; case Condition.INCLUDES: newValue = "%" + c.getCondition().toString() + "%"; sb.append(" LIKE " + convertToSql(Types.VARCHAR, newValue, q, fieldType)); break; case Condition.IN: case Condition.NOT_IN: if (c.getOperation() == Condition.NOT_IN) { sb.append(" NOT "); } sb.append(" IN ("); if (c.getCondition() instanceof BofQuery) { sb.append(((BofQuery) c.getCondition()).getSql()); } else { sb.append(join(sqlType, (Collection<Object>) c.getCondition(), q, fieldType)); } sb.append(")"); break; case Condition.IS_NULL: sb.append(" IS NULL"); break; case Condition.IS_NOT_NULL: sb.append(" IS NOT NULL"); break; case Condition.GREATER_THAN: sb.append(" > " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.LESSER_THAN: sb.append(" < " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.GREATER_OR_EQUAL: sb.append(" >= " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.LESSER_OR_EQUAL: sb.append(" <= " + convertToSql(sqlType, c.getCondition(), q, fieldType)); break; case Condition.BETWEEN: String fieldModel = sb.toString(); sb.append(" >= " + convertToSql(sqlType, c.getCondition(), q, fieldType) + " and " + fieldModel + " < " + convertToSql(sqlType, c.getCondition2(), q, fieldType)); break; case Condition.NOT_LIKE: String newValue2 = (c.getCondition().toString()).replace('*', '%'); newValue2 = newValue2.replace('?', '_'); sb.append(" NOT LIKE " + convertToSql(sqlType, newValue2, q, fieldType)); break; } return sb.toString(); } protected String convertToSql(int sqlType, Object value, BofQuery query, String fieldType) throws ModelException { if (value == null) { throw new ModelException(ResourceKeys.INVALID_NULL); } switch (sqlType) { case Types.DOUBLE: case Types.NUMERIC: return value.toString(); case Types.DECIMAL: if (value.getClass().equals(Timespan.class)) { return ((Timespan) value).getSeconds().toString(); } return value.toString(); case Types.INTEGER: /* * gregorian date conversions... * * Value could be an */ if (value.getClass().equals(Date.class)) { Date dateValue = (Date) value; GregorianDate d = new GregorianDate(dateValue); return "" + d.intValue(); } else if (value.getClass().equals(GregorianDate.class)) { GregorianDate dateValue = (GregorianDate) value; return "" + dateValue.intValue(); } else if (value.getClass().equals(Timespan.class)) { return ((Timespan) value).getSeconds().toString(); } else if (value.getClass().equals(String.class)) { if (fieldType.equals("PONREF") || fieldType.equals("PON") || fieldType.equals("CreateUserDesc") || fieldType.equals("ModifyUserDesc")) { try { return MacroHandler.parseUserMacro(value.toString()); } catch (ParseException pe) { ; } } else { try { Date dateValue = MacroHandler.parseDateMacro(value.toString()); GregorianDate d = new GregorianDate(dateValue); return "" + d.intValue(); } catch (ParseException pe) { ; } } } return value.toString(); case Types.SMALLINT: return value.toString(); case Types.DATE: throw new ModelException(ResourceKeys.UNSUPPORTED_CONVERSION, new Object[] { value.getClass().getName(), "Types.DATE" }); case Types.TIMESTAMP: /* * If the jdbc class is a TIMESTAMP we must call a Oracle function * in order to be able to do comparison. This is for the benefit of * being able to do comparisons on the time and not just the data * value. */ if (value.getClass().equals(Date.class)) { DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date dateValue = (Date) value; dateValue = ModelBuilder.modifyForTimeZone(dateValue, (BofPersistenceManager) query.getPersistenceManager(), ModelBuilder.MODEL_TO_STORAGE); String strValue = sdf.format(dateValue); return "convert(DateTime,'" + strValue + "' , 121)"; } /* * Same as above but we have to convert the String to a Date (before * we convert it back to a properly formatted string. */ if (value.getClass().equals(String.class)) { DateFormat sdf = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, new Locale("sv")); DateFormat shortDf = DateFormat.getDateInstance(DateFormat.SHORT, new Locale("sv")); String stringValue = (String) value; Date dateValue; /* * Try to parse the String using different formats in the * following order: 1. Date and Time format 2. Date format TODO: * make this Locale-aware */ try { dateValue = sdf.parse(stringValue); } catch (ParseException e) { try { dateValue = shortDf.parse(stringValue); } catch (ParseException ee) { try { // As a last resort, check to see if one of the // macros have been used dateValue = MacroHandler.parseDateMacro(stringValue); } catch (ParseException eee) { throw new ModelException(ResourceKeys.DATE_CONVERSION_ERROR, new Object[] { stringValue }); } } } dateValue = ModelBuilder.modifyForTimeZone(dateValue, (BofPersistenceManager) query.getPersistenceManager(), ModelBuilder.MODEL_TO_STORAGE); String strValue = sdf.format(dateValue); return "convert(DateTime,'" + strValue + "' , 120)"; } throw new ModelException(ResourceKeys.DATE_CONVERSION_ERROR); case Types.CLOB: case Types.VARCHAR: // used by javaType Boolean stored as VARCHAR2(1) if (value instanceof Boolean) { Boolean bool = (Boolean) value; if (bool.booleanValue()) { return "'1'"; } return "'0'"; } else if (value instanceof Long) { Long lng = (Long) value; return "" + lng.longValue(); } else if (value instanceof String) { String str = (String) value; if (str.indexOf("'") > -1) { str = str.replaceAll("'", "''"); return "'" + str.toString() + "'"; } } return "'" + value.toString() + "'"; case Types.VARBINARY: throw new ModelException(ResourceKeys.UNSUPPORTED_CONVERSION, new Object[] { value.getClass().getName(), "Types.VARBINARY" }); default: throw new ModelException(ResourceKeys.UNKNOWN_SQL_TYPE, new Object[] { "" + sqlType }); } } /** * Returns the database specific character for quoting names. Different * databases have different ways of quoting column names, for example. * * @return String quote character for this database. */ public String getDBQuoteChar() { return quoteChar; } public abstract String getNativeSql(int query) throws ModelException; }
63,734
0.653035
0.651262
1,847
32.513805
32.607037
281
false
false
0
0
0
0
0
0
3.120195
false
false
2
480fc596d0981c59a15eacc7a68efc188604dd8f
21,225,728,392,604
b905fbc16a3e4c1765ce4b4eb270d017e6b4b5d2
/HRMS/HRMS-Services/src/main/java/com/csipl/hrms/service/adaptor/TdsTransactionAdaptor.java
1d3e553d448bfa40d6d1f477c40d81f61c734e43
[]
no_license
ravindra2017bangalore/FabHR
https://github.com/ravindra2017bangalore/FabHR
76ed00741be81b6219b565bb38c4c4a68a364dc1
c77e5d4c99d5e9bdb042efea5e30fa25e7e0561e
refs/heads/master
2021-07-03T22:56:55.877000
2019-03-11T15:13:02
2019-03-11T15:13:02
175,022,830
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.csipl.hrms.service.adaptor; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.csipl.hrms.common.util.DateUtils; import com.csipl.hrms.dto.payroll.TdsTransactionDTO; import com.csipl.hrms.model.employee.Employee; import com.csipl.hrms.model.payroll.TdsGroup; import com.csipl.hrms.model.payroll.TdsSection; import com.csipl.hrms.model.payroll.TdsTransaction; public class TdsTransactionAdaptor{ private static final Logger logger = LoggerFactory.getLogger(TdsTransactionAdaptor.class); public List<TdsTransactionDTO> databaseModelToObjectArray(List<Object[]> objectTdsTransactionList) { List<TdsTransactionDTO> tdsTransactionDtoList = new ArrayList<>(); for (Object[] tdsInvestmentSummaryObj : objectTdsTransactionList) { TdsTransactionDTO tdsTransactionDto = new TdsTransactionDTO(); DateUtils dateUtils = new DateUtils(); Long tdsGroupId = tdsInvestmentSummaryObj[0] != null ? Long.parseLong(tdsInvestmentSummaryObj[0].toString()) : null; Long tdsSectionId = tdsInvestmentSummaryObj[1] != null ? Long.parseLong(tdsInvestmentSummaryObj[1].toString()) : null; String tdsSectionName = tdsInvestmentSummaryObj[2] != null ? (String) tdsInvestmentSummaryObj[2] : null; String tdsDescription = tdsInvestmentSummaryObj[3] != null ? (String) tdsInvestmentSummaryObj[3] : null; String tdsGroupName = tdsInvestmentSummaryObj[4] != null ? (String) tdsInvestmentSummaryObj[4] : null; BigDecimal investmentAmount = tdsInvestmentSummaryObj[5] != null ? (new BigDecimal(tdsInvestmentSummaryObj[5].toString())) : null; Long tdsTransactionId = tdsInvestmentSummaryObj[6] != null ? Long.parseLong(tdsInvestmentSummaryObj[6].toString()) : null; String approveStatus = tdsInvestmentSummaryObj[7] != null ? (String) tdsInvestmentSummaryObj[7] : null; Long userId = tdsInvestmentSummaryObj[8] != null ? Long.parseLong(tdsInvestmentSummaryObj[8].toString()) : null; Date dateCreated = tdsInvestmentSummaryObj[9] != null ? (Date) tdsInvestmentSummaryObj[9] : null; BigDecimal maxLimit = tdsInvestmentSummaryObj[10] != null ? (new BigDecimal(tdsInvestmentSummaryObj[10].toString())) : null; Long employeeId = tdsInvestmentSummaryObj[11] != null ? Long.parseLong(tdsInvestmentSummaryObj[11].toString()) : null; String status = tdsInvestmentSummaryObj[12] != null ? (String) tdsInvestmentSummaryObj[12] : null; String financialYear = tdsInvestmentSummaryObj[13] != null ? (String) tdsInvestmentSummaryObj[13] : null; String city = tdsInvestmentSummaryObj[14] != null ? (String) tdsInvestmentSummaryObj[14] : null; tdsTransactionDto.setTdsGroupId(tdsGroupId); tdsTransactionDto.setTdsSectionId(tdsSectionId); tdsTransactionDto.setTdsSectionName(tdsSectionName); tdsTransactionDto.setTdsGroupName(tdsGroupName); tdsTransactionDto.setInvestmentAmount(investmentAmount); tdsTransactionDto.setTdsDescription(tdsSectionName + " - " + tdsDescription); tdsTransactionDto.setTdsTransactionId(tdsTransactionId); tdsTransactionDto.setApproveStatus(approveStatus); tdsTransactionDto.setUserId(userId); if (dateCreated != null) tdsTransactionDto.setDateCreated(dateUtils.getDateStringWirhYYYYMMDD(dateCreated)); tdsTransactionDto.setMaxLimit(maxLimit); tdsTransactionDto.setEmployeeId(employeeId); tdsTransactionDto.setStatus(status); tdsTransactionDto.setFinancialYear(financialYear); tdsTransactionDto.setCity(city); tdsTransactionDtoList.add(tdsTransactionDto); /* * for (TdsTransactionDTO tdsTransactionDto1:tdsTransactionDtoList) { * tdsTransactionDto1.setSrno(srno); } */ } return tdsTransactionDtoList; } public List<TdsTransaction> uiDtoToTdsTransactionModelList(List<TdsTransactionDTO> tdsTransactionDtoList, Long employeeId) { List<TdsTransaction> tdsTransactionList = new ArrayList<>(); for (TdsTransactionDTO tdsTransactionDto : tdsTransactionDtoList) { tdsTransactionList.add(uiDtoToDatabaseModel(tdsTransactionDto, employeeId)); } return tdsTransactionList; } public TdsTransaction uiDtoToDatabaseModel(TdsTransactionDTO tdsTransactionDto, Long employeeId) { TdsTransaction tdsTransaction = new TdsTransaction(); TdsGroup tdsGroup = new TdsGroup(); TdsSection tdsSection = new TdsSection(); Employee employee = new Employee(); DateUtils dateUtils = new DateUtils(); tdsGroup.setTdsGroupId(tdsTransactionDto.getTdsGroupId()); tdsSection.setTdsSectionId(tdsTransactionDto.getTdsSectionId()); tdsTransaction.setTdsSection(tdsSection); tdsTransaction.setStatus(tdsTransactionDto.getStatus()); tdsTransaction.setTdsGroup(tdsGroup); tdsTransaction.setTdsTransactionId(tdsTransactionDto.getTdsTransactionId()); tdsTransaction.setInvestmentAmount(tdsTransactionDto.getInvestmentAmount()); tdsTransaction.setApproveStatus(tdsTransactionDto.getApproveStatus()); tdsTransaction.setProof(tdsTransactionDto.getProof()); tdsTransaction.setNoOfDocuments(tdsTransactionDto.getNoOfDocuments()); tdsTransaction.setMaxLimit(tdsTransactionDto.getMaxLimit()); tdsTransaction.setFileLocation(tdsTransactionDto.getFileLocation()); tdsTransaction.setCity(tdsTransactionDto.getCity()); tdsTransaction.setApprovedAmount(tdsTransactionDto.getApprovedAmount()); employee.setEmployeeId(employeeId); tdsTransaction.setEmployee(employee); tdsTransaction.setUserId(tdsTransactionDto.getUserId()); tdsTransaction.setUserIdUpdate(tdsTransactionDto.getUserIdUpdate()); tdsTransaction.setDateUpdate(new Date()); if (tdsTransactionDto.getDateCreated() != null) tdsTransaction.setDateCreated(dateUtils.getDateWirhYYYYMMDD(tdsTransactionDto.getDateCreated())); else tdsTransaction.setDateCreated(new Date()); return tdsTransaction; } public List<TdsTransactionDTO> databaseModelToTdsInvestmentArray(List<Object[]> objectInvestmentSummaryList) { List<TdsTransactionDTO> tdsInvestmentSummaryList = new ArrayList<>(); for (Object[] tdsInvestmentSummaryObj : objectInvestmentSummaryList) { DateUtils dateUtils = new DateUtils(); TdsTransactionDTO tdsTransactionDto = new TdsTransactionDTO(); Long tdsGroupId = tdsInvestmentSummaryObj[0] != null ? Long.parseLong(tdsInvestmentSummaryObj[0].toString()) : null; Long tdsSectionId = tdsInvestmentSummaryObj[1] != null ? Long.parseLong(tdsInvestmentSummaryObj[1].toString()) : null; String tdsSectionName = tdsInvestmentSummaryObj[2] != null ? (String) tdsInvestmentSummaryObj[2] : null; String tdsDescription = tdsInvestmentSummaryObj[3] != null ? (String) tdsInvestmentSummaryObj[3] : null; BigDecimal maxLimit = tdsInvestmentSummaryObj[4] != null ? (new BigDecimal(tdsInvestmentSummaryObj[4].toString())) : null; String financialYear = tdsInvestmentSummaryObj[5] != null ? (String) tdsInvestmentSummaryObj[5] : null; BigDecimal investmentAmount = tdsInvestmentSummaryObj[6] != null ? (new BigDecimal(tdsInvestmentSummaryObj[6].toString())) : null; Date dateCreated = tdsInvestmentSummaryObj[7] != null ? (Date) (tdsInvestmentSummaryObj[7]) : null; String status = tdsInvestmentSummaryObj[8] != null ? (String) tdsInvestmentSummaryObj[8] : null; BigDecimal approvedAmount = tdsInvestmentSummaryObj[9] != null ? (new BigDecimal(tdsInvestmentSummaryObj[9].toString())) : null; tdsTransactionDto.setTdsGroupId(tdsGroupId); tdsTransactionDto.setTdsSectionId(tdsSectionId); tdsTransactionDto.setTdsSectionName(tdsSectionName); tdsTransactionDto.setInvestmentAmount(investmentAmount); tdsTransactionDto.setTdsDescription(tdsDescription); tdsTransactionDto.setDateCreated(dateUtils.getDateStringWirhYYYYMMDD(dateCreated)); tdsTransactionDto.setStatus(status); tdsTransactionDto.setFinancialYear(financialYear); tdsTransactionDto.setApprovedAmount(approvedAmount); tdsTransactionDto.setMaxLimit(maxLimit); tdsInvestmentSummaryList.add(tdsTransactionDto); } return tdsInvestmentSummaryList; } }
UTF-8
Java
8,263
java
TdsTransactionAdaptor.java
Java
[]
null
[]
package com.csipl.hrms.service.adaptor; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.csipl.hrms.common.util.DateUtils; import com.csipl.hrms.dto.payroll.TdsTransactionDTO; import com.csipl.hrms.model.employee.Employee; import com.csipl.hrms.model.payroll.TdsGroup; import com.csipl.hrms.model.payroll.TdsSection; import com.csipl.hrms.model.payroll.TdsTransaction; public class TdsTransactionAdaptor{ private static final Logger logger = LoggerFactory.getLogger(TdsTransactionAdaptor.class); public List<TdsTransactionDTO> databaseModelToObjectArray(List<Object[]> objectTdsTransactionList) { List<TdsTransactionDTO> tdsTransactionDtoList = new ArrayList<>(); for (Object[] tdsInvestmentSummaryObj : objectTdsTransactionList) { TdsTransactionDTO tdsTransactionDto = new TdsTransactionDTO(); DateUtils dateUtils = new DateUtils(); Long tdsGroupId = tdsInvestmentSummaryObj[0] != null ? Long.parseLong(tdsInvestmentSummaryObj[0].toString()) : null; Long tdsSectionId = tdsInvestmentSummaryObj[1] != null ? Long.parseLong(tdsInvestmentSummaryObj[1].toString()) : null; String tdsSectionName = tdsInvestmentSummaryObj[2] != null ? (String) tdsInvestmentSummaryObj[2] : null; String tdsDescription = tdsInvestmentSummaryObj[3] != null ? (String) tdsInvestmentSummaryObj[3] : null; String tdsGroupName = tdsInvestmentSummaryObj[4] != null ? (String) tdsInvestmentSummaryObj[4] : null; BigDecimal investmentAmount = tdsInvestmentSummaryObj[5] != null ? (new BigDecimal(tdsInvestmentSummaryObj[5].toString())) : null; Long tdsTransactionId = tdsInvestmentSummaryObj[6] != null ? Long.parseLong(tdsInvestmentSummaryObj[6].toString()) : null; String approveStatus = tdsInvestmentSummaryObj[7] != null ? (String) tdsInvestmentSummaryObj[7] : null; Long userId = tdsInvestmentSummaryObj[8] != null ? Long.parseLong(tdsInvestmentSummaryObj[8].toString()) : null; Date dateCreated = tdsInvestmentSummaryObj[9] != null ? (Date) tdsInvestmentSummaryObj[9] : null; BigDecimal maxLimit = tdsInvestmentSummaryObj[10] != null ? (new BigDecimal(tdsInvestmentSummaryObj[10].toString())) : null; Long employeeId = tdsInvestmentSummaryObj[11] != null ? Long.parseLong(tdsInvestmentSummaryObj[11].toString()) : null; String status = tdsInvestmentSummaryObj[12] != null ? (String) tdsInvestmentSummaryObj[12] : null; String financialYear = tdsInvestmentSummaryObj[13] != null ? (String) tdsInvestmentSummaryObj[13] : null; String city = tdsInvestmentSummaryObj[14] != null ? (String) tdsInvestmentSummaryObj[14] : null; tdsTransactionDto.setTdsGroupId(tdsGroupId); tdsTransactionDto.setTdsSectionId(tdsSectionId); tdsTransactionDto.setTdsSectionName(tdsSectionName); tdsTransactionDto.setTdsGroupName(tdsGroupName); tdsTransactionDto.setInvestmentAmount(investmentAmount); tdsTransactionDto.setTdsDescription(tdsSectionName + " - " + tdsDescription); tdsTransactionDto.setTdsTransactionId(tdsTransactionId); tdsTransactionDto.setApproveStatus(approveStatus); tdsTransactionDto.setUserId(userId); if (dateCreated != null) tdsTransactionDto.setDateCreated(dateUtils.getDateStringWirhYYYYMMDD(dateCreated)); tdsTransactionDto.setMaxLimit(maxLimit); tdsTransactionDto.setEmployeeId(employeeId); tdsTransactionDto.setStatus(status); tdsTransactionDto.setFinancialYear(financialYear); tdsTransactionDto.setCity(city); tdsTransactionDtoList.add(tdsTransactionDto); /* * for (TdsTransactionDTO tdsTransactionDto1:tdsTransactionDtoList) { * tdsTransactionDto1.setSrno(srno); } */ } return tdsTransactionDtoList; } public List<TdsTransaction> uiDtoToTdsTransactionModelList(List<TdsTransactionDTO> tdsTransactionDtoList, Long employeeId) { List<TdsTransaction> tdsTransactionList = new ArrayList<>(); for (TdsTransactionDTO tdsTransactionDto : tdsTransactionDtoList) { tdsTransactionList.add(uiDtoToDatabaseModel(tdsTransactionDto, employeeId)); } return tdsTransactionList; } public TdsTransaction uiDtoToDatabaseModel(TdsTransactionDTO tdsTransactionDto, Long employeeId) { TdsTransaction tdsTransaction = new TdsTransaction(); TdsGroup tdsGroup = new TdsGroup(); TdsSection tdsSection = new TdsSection(); Employee employee = new Employee(); DateUtils dateUtils = new DateUtils(); tdsGroup.setTdsGroupId(tdsTransactionDto.getTdsGroupId()); tdsSection.setTdsSectionId(tdsTransactionDto.getTdsSectionId()); tdsTransaction.setTdsSection(tdsSection); tdsTransaction.setStatus(tdsTransactionDto.getStatus()); tdsTransaction.setTdsGroup(tdsGroup); tdsTransaction.setTdsTransactionId(tdsTransactionDto.getTdsTransactionId()); tdsTransaction.setInvestmentAmount(tdsTransactionDto.getInvestmentAmount()); tdsTransaction.setApproveStatus(tdsTransactionDto.getApproveStatus()); tdsTransaction.setProof(tdsTransactionDto.getProof()); tdsTransaction.setNoOfDocuments(tdsTransactionDto.getNoOfDocuments()); tdsTransaction.setMaxLimit(tdsTransactionDto.getMaxLimit()); tdsTransaction.setFileLocation(tdsTransactionDto.getFileLocation()); tdsTransaction.setCity(tdsTransactionDto.getCity()); tdsTransaction.setApprovedAmount(tdsTransactionDto.getApprovedAmount()); employee.setEmployeeId(employeeId); tdsTransaction.setEmployee(employee); tdsTransaction.setUserId(tdsTransactionDto.getUserId()); tdsTransaction.setUserIdUpdate(tdsTransactionDto.getUserIdUpdate()); tdsTransaction.setDateUpdate(new Date()); if (tdsTransactionDto.getDateCreated() != null) tdsTransaction.setDateCreated(dateUtils.getDateWirhYYYYMMDD(tdsTransactionDto.getDateCreated())); else tdsTransaction.setDateCreated(new Date()); return tdsTransaction; } public List<TdsTransactionDTO> databaseModelToTdsInvestmentArray(List<Object[]> objectInvestmentSummaryList) { List<TdsTransactionDTO> tdsInvestmentSummaryList = new ArrayList<>(); for (Object[] tdsInvestmentSummaryObj : objectInvestmentSummaryList) { DateUtils dateUtils = new DateUtils(); TdsTransactionDTO tdsTransactionDto = new TdsTransactionDTO(); Long tdsGroupId = tdsInvestmentSummaryObj[0] != null ? Long.parseLong(tdsInvestmentSummaryObj[0].toString()) : null; Long tdsSectionId = tdsInvestmentSummaryObj[1] != null ? Long.parseLong(tdsInvestmentSummaryObj[1].toString()) : null; String tdsSectionName = tdsInvestmentSummaryObj[2] != null ? (String) tdsInvestmentSummaryObj[2] : null; String tdsDescription = tdsInvestmentSummaryObj[3] != null ? (String) tdsInvestmentSummaryObj[3] : null; BigDecimal maxLimit = tdsInvestmentSummaryObj[4] != null ? (new BigDecimal(tdsInvestmentSummaryObj[4].toString())) : null; String financialYear = tdsInvestmentSummaryObj[5] != null ? (String) tdsInvestmentSummaryObj[5] : null; BigDecimal investmentAmount = tdsInvestmentSummaryObj[6] != null ? (new BigDecimal(tdsInvestmentSummaryObj[6].toString())) : null; Date dateCreated = tdsInvestmentSummaryObj[7] != null ? (Date) (tdsInvestmentSummaryObj[7]) : null; String status = tdsInvestmentSummaryObj[8] != null ? (String) tdsInvestmentSummaryObj[8] : null; BigDecimal approvedAmount = tdsInvestmentSummaryObj[9] != null ? (new BigDecimal(tdsInvestmentSummaryObj[9].toString())) : null; tdsTransactionDto.setTdsGroupId(tdsGroupId); tdsTransactionDto.setTdsSectionId(tdsSectionId); tdsTransactionDto.setTdsSectionName(tdsSectionName); tdsTransactionDto.setInvestmentAmount(investmentAmount); tdsTransactionDto.setTdsDescription(tdsDescription); tdsTransactionDto.setDateCreated(dateUtils.getDateStringWirhYYYYMMDD(dateCreated)); tdsTransactionDto.setStatus(status); tdsTransactionDto.setFinancialYear(financialYear); tdsTransactionDto.setApprovedAmount(approvedAmount); tdsTransactionDto.setMaxLimit(maxLimit); tdsInvestmentSummaryList.add(tdsTransactionDto); } return tdsInvestmentSummaryList; } }
8,263
0.771027
0.763282
162
49.006172
31.704557
111
false
false
0
0
0
0
0
0
3.061728
false
false
2
b859bb67c7b90a5100f78b8d6922d084f4371bcb
28,595,892,273,560
67969ddd421ef9461591b293ebeb9a5792262fa3
/springbootbios-master/springbootbios/src/main/java/bios/springframework/spring5webapp/bootstrap/DevBootstrap.java
d7a9894b449fe6ff037784dac135eb633af68e2a
[]
no_license
Majnkeyzer/springbootbios
https://github.com/Majnkeyzer/springbootbios
6ac507e64b70e2a9d5c4f7bab6b4da759d723993
44c6107073436ec28706fa42b65796798c831ac7
refs/heads/master
2020-04-02T07:27:49.488000
2018-10-23T21:20:22
2018-10-23T21:20:22
154,197,419
0
0
null
false
2018-10-23T21:20:23
2018-10-22T18:45:42
2018-10-22T19:08:19
2018-10-23T21:20:22
49
0
0
0
Java
false
null
package bios.springframework.spring5webapp.bootstrap; import bios.springframework.spring5webapp.model.Zaal; import bios.springframework.spring5webapp.model.Film; import bios.springframework.spring5webapp.repositories.ZaalRepository; import bios.springframework.spring5webapp.repositories.FilmRepository; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class DevBootstrap implements ApplicationListener<ContextRefreshedEvent> { private ZaalRepository zaalRepository; private FilmRepository filmRepository; public DevBootstrap(ZaalRepository zaalRepository, FilmRepository filmRepository) { this.zaalRepository = zaalRepository; this.filmRepository = filmRepository; } @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { initData(); } private void initData(){ //Zaal 1 Zaal zaal = new Zaal("Zaal 1"); Film ddd = new Film("James Bond"); zaal.getFilms().add(ddd); ddd.getZalen().add(zaal); zaalRepository.save(zaal); filmRepository.save(ddd); //Zaal 2 Zaal zaal2 = new Zaal("Zaal 2"); Film noEJB = new Film("De Smurfen"); zaal2.getFilms().add(noEJB); noEJB.getZalen().add(zaal2); zaalRepository.save(zaal2); filmRepository.save(noEJB); } }
UTF-8
Java
1,552
java
DevBootstrap.java
Java
[ { "context": "new Zaal(\"Zaal 1\");\r\n Film ddd = new Film(\"James Bond\");\r\n zaal.getFilms().add(ddd);\r\n dd", "end": 1130, "score": 0.999799907207489, "start": 1120, "tag": "NAME", "value": "James Bond" }, { "context": "w Zaal(\"Zaal 2\");\r\n Film noEJB = new Film(\"De Smurfen\");\r\n zaal2.getFilms().add(noEJB);\r\n ", "end": 1383, "score": 0.9998251795768738, "start": 1373, "tag": "NAME", "value": "De Smurfen" } ]
null
[]
package bios.springframework.spring5webapp.bootstrap; import bios.springframework.spring5webapp.model.Zaal; import bios.springframework.spring5webapp.model.Film; import bios.springframework.spring5webapp.repositories.ZaalRepository; import bios.springframework.spring5webapp.repositories.FilmRepository; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class DevBootstrap implements ApplicationListener<ContextRefreshedEvent> { private ZaalRepository zaalRepository; private FilmRepository filmRepository; public DevBootstrap(ZaalRepository zaalRepository, FilmRepository filmRepository) { this.zaalRepository = zaalRepository; this.filmRepository = filmRepository; } @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { initData(); } private void initData(){ //Zaal 1 Zaal zaal = new Zaal("Zaal 1"); Film ddd = new Film("<NAME>"); zaal.getFilms().add(ddd); ddd.getZalen().add(zaal); zaalRepository.save(zaal); filmRepository.save(ddd); //Zaal 2 Zaal zaal2 = new Zaal("Zaal 2"); Film noEJB = new Film("<NAME>"); zaal2.getFilms().add(noEJB); noEJB.getZalen().add(zaal2); zaalRepository.save(zaal2); filmRepository.save(noEJB); } }
1,544
0.696521
0.688144
53
27.283018
25.561895
87
false
false
0
0
0
0
0
0
0.490566
false
false
2
e163244c51bbd64294c89f790890dd267cbcef01
3,100,966,405,982
3f56ebcc8b8fa30fa78276420cd075dbdf90b69a
/src/main/java/cm/controller/StudentTeamController.java
17bbc713b36b892e6cd77bb6de1bd94bd1c03c24
[]
no_license
Jasminexyy/version-after
https://github.com/Jasminexyy/version-after
b8251256c40a55610ca9b81f7604ff0cf62ba6e1
802d9cf4fbf98e95f75b607e86bfed9a9e269379
refs/heads/master
2020-04-15T02:30:15.778000
2019-01-06T08:23:17
2019-01-06T08:23:17
164,316,881
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cm.controller; import cm.service.CourseService; import cm.service.KlassService; import cm.service.StudentService; import cm.service.TeamService; import cm.vo.CourseDetailVO; import cm.vo.TeamVO; import cm.vo.UserVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.parameters.P; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping("/cm/student/course/team") public class StudentTeamController { @Autowired private TeamService teamService; @Autowired private CourseService courseService; @Autowired private KlassService klassService; @Autowired private StudentService studentService; UserVO student; CourseDetailVO courseDetailVO; //////student team list @RequestMapping(value="/teamList",method= RequestMethod.GET) public String studentTeam(Long klassId,String account,Model model){ System.out.println("teamList"); System.out.println(klassId); System.out.println(account); courseDetailVO=courseService.getCourseByKlassId(klassId); student= studentService.getUserVOByAccount(account); model.addAttribute("myTeam",teamService.getMyTeam(courseDetailVO.getId(),student.getId())); model.addAttribute("teamList",teamService.listTeamByCourseId(courseDetailVO.getId())); model.addAttribute("studentsNotInTeam",studentService.getStudentNotInTeam(courseDetailVO.getId(),student.getId())); return "student_teams"; } //////student my team @RequestMapping(value = "/myteam",method = RequestMethod.GET) public String studentMyTeam(Model model,Long id){ TeamVO tmp=teamService.getVOByTeamId(id); model.addAttribute("myTeam",tmp); System.out.println("student id:"+student.getId()); System.out.println("course id:"+courseDetailVO.getId()); model.addAttribute("studentList",studentService.getStudentNotInTeam(courseDetailVO.getId(),student.getId())); if(student.getId().equals(tmp.getLeader().getId())) return "student_myteam_leader"; else return "studnet_myteam_member"; } ///////student my team quit @RequestMapping(value="/myteam/quit/{teamId}",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamQuit(@PathVariable Long teamId){ teamService.quitTeam(teamId,student.getId()); return new ResponseEntity(HttpStatus.OK); } ///////student create team @RequestMapping(value = "/create",method = RequestMethod.GET) public String studentTeamCreate(Model model){ model.addAttribute("studentList",studentService.getStudentNotInTeam(courseDetailVO.getId(),student.getId())); model.addAttribute("klassId",klassService.getKlassByStudentIdCourseId(student.getId(),courseDetailVO.getId())); return "student_team_create"; } ///////student create team @RequestMapping(value="/create",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamCreate(String teamName, List<String> studentNum,Long klassId){ teamService.createTeam(teamName,klassId,studentNum); return new ResponseEntity(HttpStatus.OK); } //////student delete member-leader @RequestMapping(value = "/delete/{studentNum}",method=RequestMethod.DELETE) @ResponseBody public ResponseEntity studentTeamDeleteMember(@PathVariable String studentNum){ Long teamId=teamService.getMyTeam(courseDetailVO.getId(),student.getId()).getTeamId(); teamService.deleteMember(student.getId(),teamId,studentNum); return new ResponseEntity(HttpStatus.OK); } /////student add member leader @RequestMapping(value = "/add",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamAdd(Long teamId,List<String> studentNum){ teamService.addMember(student.getId(),teamId,studentNum); return new ResponseEntity(HttpStatus.OK); } /** * 遣散小组 * @param teamId * @param studentNum * @return */ //////student disband team leader @RequestMapping(value = "/disband",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamDisband(Long teamId,List<String> studentNum){ teamService.teamDisband(teamId,studentNum); return new ResponseEntity(HttpStatus.OK); } //搜索成员 @RequestMapping(value = "/search",method = RequestMethod.GET) @ResponseBody public UserVO studentSearch(String studentAccount){ return teamService.searchStudent(studentAccount); } }
UTF-8
Java
5,049
java
StudentTeamController.java
Java
[]
null
[]
package cm.controller; import cm.service.CourseService; import cm.service.KlassService; import cm.service.StudentService; import cm.service.TeamService; import cm.vo.CourseDetailVO; import cm.vo.TeamVO; import cm.vo.UserVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.parameters.P; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping("/cm/student/course/team") public class StudentTeamController { @Autowired private TeamService teamService; @Autowired private CourseService courseService; @Autowired private KlassService klassService; @Autowired private StudentService studentService; UserVO student; CourseDetailVO courseDetailVO; //////student team list @RequestMapping(value="/teamList",method= RequestMethod.GET) public String studentTeam(Long klassId,String account,Model model){ System.out.println("teamList"); System.out.println(klassId); System.out.println(account); courseDetailVO=courseService.getCourseByKlassId(klassId); student= studentService.getUserVOByAccount(account); model.addAttribute("myTeam",teamService.getMyTeam(courseDetailVO.getId(),student.getId())); model.addAttribute("teamList",teamService.listTeamByCourseId(courseDetailVO.getId())); model.addAttribute("studentsNotInTeam",studentService.getStudentNotInTeam(courseDetailVO.getId(),student.getId())); return "student_teams"; } //////student my team @RequestMapping(value = "/myteam",method = RequestMethod.GET) public String studentMyTeam(Model model,Long id){ TeamVO tmp=teamService.getVOByTeamId(id); model.addAttribute("myTeam",tmp); System.out.println("student id:"+student.getId()); System.out.println("course id:"+courseDetailVO.getId()); model.addAttribute("studentList",studentService.getStudentNotInTeam(courseDetailVO.getId(),student.getId())); if(student.getId().equals(tmp.getLeader().getId())) return "student_myteam_leader"; else return "studnet_myteam_member"; } ///////student my team quit @RequestMapping(value="/myteam/quit/{teamId}",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamQuit(@PathVariable Long teamId){ teamService.quitTeam(teamId,student.getId()); return new ResponseEntity(HttpStatus.OK); } ///////student create team @RequestMapping(value = "/create",method = RequestMethod.GET) public String studentTeamCreate(Model model){ model.addAttribute("studentList",studentService.getStudentNotInTeam(courseDetailVO.getId(),student.getId())); model.addAttribute("klassId",klassService.getKlassByStudentIdCourseId(student.getId(),courseDetailVO.getId())); return "student_team_create"; } ///////student create team @RequestMapping(value="/create",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamCreate(String teamName, List<String> studentNum,Long klassId){ teamService.createTeam(teamName,klassId,studentNum); return new ResponseEntity(HttpStatus.OK); } //////student delete member-leader @RequestMapping(value = "/delete/{studentNum}",method=RequestMethod.DELETE) @ResponseBody public ResponseEntity studentTeamDeleteMember(@PathVariable String studentNum){ Long teamId=teamService.getMyTeam(courseDetailVO.getId(),student.getId()).getTeamId(); teamService.deleteMember(student.getId(),teamId,studentNum); return new ResponseEntity(HttpStatus.OK); } /////student add member leader @RequestMapping(value = "/add",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamAdd(Long teamId,List<String> studentNum){ teamService.addMember(student.getId(),teamId,studentNum); return new ResponseEntity(HttpStatus.OK); } /** * 遣散小组 * @param teamId * @param studentNum * @return */ //////student disband team leader @RequestMapping(value = "/disband",method = RequestMethod.POST) @ResponseBody public ResponseEntity studentTeamDisband(Long teamId,List<String> studentNum){ teamService.teamDisband(teamId,studentNum); return new ResponseEntity(HttpStatus.OK); } //搜索成员 @RequestMapping(value = "/search",method = RequestMethod.GET) @ResponseBody public UserVO studentSearch(String studentAccount){ return teamService.searchStudent(studentAccount); } }
5,049
0.727995
0.727995
130
37.715385
29.558348
123
false
false
0
0
0
0
0
0
0.715385
false
false
2
43a3086460f53a81df9b52917730039bd1cffc53
26,671,746,938,858
bc0a9d1ae2897051d696fb817e8e6dfb77cb3f49
/ServletTutorial/src/com/amit/webapplication/servlet/ProdLogout.java
2782c103012777bb776fae15d8a8b25b71e4cec6
[]
no_license
amit---kumar/webapplication
https://github.com/amit---kumar/webapplication
857aed80af0309c0416201142556e17dee848004
b4a1f57de6a847975a9be9a35925838a37d0fc1f
refs/heads/master
2021-01-21T07:03:58.594000
2017-03-03T12:18:43
2017-03-03T12:18:43
83,309,517
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amit.webapplication.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProdLogout extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); Cookie ck=new Cookie("name",""); ck.setMaxAge(0); res.addCookie(ck); out.print("you are successfully logged out!"); out.print("<br>"); req.getRequestDispatcher("/prodindex.html").include(req,res); } }
UTF-8
Java
783
java
ProdLogout.java
Java
[]
null
[]
package com.amit.webapplication.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ProdLogout extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); Cookie ck=new Cookie("name",""); ck.setMaxAge(0); res.addCookie(ck); out.print("you are successfully logged out!"); out.print("<br>"); req.getRequestDispatcher("/prodindex.html").include(req,res); } }
783
0.739464
0.738186
26
29.115385
24.526794
105
false
false
0
0
0
0
0
0
1.230769
false
false
2
1661949f513f63121b92367b9c9f59996671f5a0
18,090,402,299,209
60a99e5de69dab840144865cb5cdce94d49761da
/netty-base/src/main/java/com/study/netty/protoclotcp/MyClientHandler.java
2f6a919d1213a4dc7d5c55d3ef3adf5525841446
[]
no_license
ldj0816/netty-study
https://github.com/ldj0816/netty-study
54fcc9925c3bc550ad1f930bdd7087318147d7b8
18ebc3843c49e7f64b75217be73dc59daf558802
refs/heads/master
2023-03-25T04:53:48.596000
2021-03-12T02:41:22
2021-03-12T02:41:22
341,123,904
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.study.netty.protoclotcp; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.CharsetUtil; /** * @author: 吕东杰 * @description: //TODO * @create: 2021-03-11 18:07 **/ public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> { private int count = 0; @Override protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception { int len = msg.getLen(); byte[] content = msg.getCcontent(); System.out.println("客户端接收到数据如下:"); System.out.println("长度:"+ len); System.out.println("内容:"+ new String(content,CharsetUtil.UTF_8)); System.out.println("客户接收到数量="+ (++this.count)); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { //使用客户端发送十条数据 hello server for (int i = 0; i < 5; i++) { String message = "今天天气冷,吃火锅"; byte[] content = message.getBytes(CharsetUtil.UTF_8); int length = message.getBytes(CharsetUtil.UTF_8).length; MessageProtocol messageProtocol = new MessageProtocol(); messageProtocol.setCcontent(content); messageProtocol.setLen(length); ctx.writeAndFlush(messageProtocol); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
UTF-8
Java
1,606
java
MyClientHandler.java
Java
[ { "context": "mport io.netty.util.CharsetUtil;\n\n/**\n * @author: 吕东杰\n * @description: //TODO\n * @create: 2021-03-11 18", "end": 192, "score": 0.9998067617416382, "start": 189, "tag": "NAME", "value": "吕东杰" } ]
null
[]
package com.study.netty.protoclotcp; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.CharsetUtil; /** * @author: 吕东杰 * @description: //TODO * @create: 2021-03-11 18:07 **/ public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> { private int count = 0; @Override protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception { int len = msg.getLen(); byte[] content = msg.getCcontent(); System.out.println("客户端接收到数据如下:"); System.out.println("长度:"+ len); System.out.println("内容:"+ new String(content,CharsetUtil.UTF_8)); System.out.println("客户接收到数量="+ (++this.count)); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { //使用客户端发送十条数据 hello server for (int i = 0; i < 5; i++) { String message = "今天天气冷,吃火锅"; byte[] content = message.getBytes(CharsetUtil.UTF_8); int length = message.getBytes(CharsetUtil.UTF_8).length; MessageProtocol messageProtocol = new MessageProtocol(); messageProtocol.setCcontent(content); messageProtocol.setLen(length); ctx.writeAndFlush(messageProtocol); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
1,606
0.662037
0.649471
44
33.363636
27.037088
98
false
false
0
0
0
0
0
0
0.568182
false
false
2
ce0f767893132afb7206e89fb6b9b9f26b2bcbaa
19,559,281,118,412
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Spotify_source/src/com/spotify/mobile/android/porcelain/json/subitem/PorcelainJsonPlayable.java
58ea9dfadf686a41356c7defe868c4d834d6edee
[]
no_license
cha63506/CompSecurity
https://github.com/cha63506/CompSecurity
5c69743f660b9899146ed3cf21eceabe3d5f4280
eee7e74f4088b9c02dd711c061fc04fb1e4e2654
refs/heads/master
2018-03-23T04:15:18.480000
2015-12-19T01:29:58
2015-12-19T01:29:58
null
0
0
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.spotify.mobile.android.porcelain.json.subitem; import android.os.Parcel; import android.os.Parcelable; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableMap; import com.spotify.mobile.android.cosmos.player.v2.PlayerTrack; import cty; import cur; import drz; import dsa; import gen; // Referenced classes of package com.spotify.mobile.android.porcelain.json.subitem: // PorcelainJsonLoggableEntity public class PorcelainJsonPlayable extends PorcelainJsonLoggableEntity implements Parcelable, drz { public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() { public final Object createFromParcel(Parcel parcel) { return new PorcelainJsonPlayable(parcel.readString(), parcel.readString(), (PorcelainJsonEntityInfo)parcel.readParcelable(com/spotify/mobile/android/porcelain/json/subitem/PorcelainJsonPlayable$PorcelainJsonEntityInfo.getClassLoader()), parcel.readString(), gen.e(parcel)); } public final volatile Object[] newArray(int i) { return new PorcelainJsonPlayable[i]; } }; private static final String KEY_CONTEXT = "context"; private static final String KEY_ENTITY_INFO = "playerTrack"; private static final String KEY_GROUP = "group"; private static final String KEY_URI = "uri"; private final String mContext; private final PorcelainJsonEntityInfo mEntityInfo; private final String mGroup; private final String mUri; public PorcelainJsonPlayable(String s, String s1, PorcelainJsonEntityInfo porcelainjsonentityinfo, String s2, JsonNode jsonnode) { super(s1, jsonnode); mGroup = s2; mContext = s; mEntityInfo = porcelainjsonentityinfo; mUri = s1; } public int describeContents() { return 0; } public boolean equals(Object obj) { if (this != obj) { if (obj == null || getClass() != obj.getClass()) { return false; } obj = (PorcelainJsonPlayable)obj; if (!cty.a(mContext, ((PorcelainJsonPlayable) (obj)).mContext) || !cty.a(mUri, ((PorcelainJsonPlayable) (obj)).mUri) || !cty.a(mEntityInfo, ((PorcelainJsonPlayable) (obj)).mEntityInfo) || !cty.a(mGroup, ((PorcelainJsonPlayable) (obj)).mGroup)) { return false; } } return true; } public final String getContext() { return mContext; } public final PorcelainJsonEntityInfo getEntityInfo() { return mEntityInfo; } public volatile dsa getEntityInfo() { return getEntityInfo(); } public final String getGroup() { return mGroup; } public final String getUri() { return mUri; } public int hashCode() { int l = 0; int i; int j; int k; if (mContext != null) { i = mContext.hashCode(); } else { i = 0; } if (mUri != null) { j = mUri.hashCode(); } else { j = 0; } if (mEntityInfo != null) { k = mEntityInfo.hashCode(); } else { k = 0; } if (mGroup != null) { l = mGroup.hashCode(); } return (k + (j + i * 31) * 31) * 31 + l; } public final boolean isPlayable() { return mUri != null && mEntityInfo != null; } public PlayerTrack toPlayerTrack() { if (isPlayable()) { PorcelainJsonEntityInfo porcelainjsonentityinfo = getEntityInfo(); String s = getUri(); cur cur1 = ImmutableMap.i(); cur1.a("media.type", "audio").a("artist_name", porcelainjsonentityinfo.getArtistName()).a("album_title", porcelainjsonentityinfo.getAlbumName()).a("title", porcelainjsonentityinfo.getTrackName()); if (porcelainjsonentityinfo.getAlbumImageUri() != null) { cur1.a("image_url", porcelainjsonentityinfo.getAlbumImageUri()); } return PlayerTrack.create(s, porcelainjsonentityinfo.getAlbumUri(), porcelainjsonentityinfo.getArtistUri(), cur1.a()); } else { throw new AssertionError("Playable cannot be played!"); } } public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mContext); parcel.writeString(mUri); parcel.writeParcelable(mEntityInfo, i); parcel.writeString(mGroup); writeExtraDataToParcel(parcel); } private class PorcelainJsonEntityInfo implements Parcelable, JacksonModel, dsa { public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() { public final Object createFromParcel(Parcel parcel) { return new PorcelainJsonEntityInfo(parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString()); } public final volatile Object[] newArray(int i) { return new PorcelainJsonEntityInfo[i]; } }; private static final String KEY_ALBUM_IMAGE = "albumImageUri"; private static final String KEY_ALBUM_NAME = "albumName"; private static final String KEY_ALBUM_URI = "albumUri"; private static final String KEY_ARTIST_NAME = "artistName"; private static final String KEY_ARTIST_URI = "artistUri"; private static final String KEY_TRACK_NAME = "trackName"; private final String mAlbumImageUri; private final String mAlbumName; private final String mAlbumUri; private final String mArtistName; private final String mArtistUri; private final String mTrackName; public int describeContents() { return 0; } public boolean equals(Object obj) { if (this != obj) { if (obj == null || getClass() != obj.getClass()) { return false; } obj = (PorcelainJsonEntityInfo)obj; if (!cty.a(mAlbumUri, ((PorcelainJsonEntityInfo) (obj)).mAlbumUri) || !cty.a(mAlbumName, ((PorcelainJsonEntityInfo) (obj)).mAlbumName) || !cty.a(mArtistUri, ((PorcelainJsonEntityInfo) (obj)).mArtistUri) || !cty.a(mArtistName, ((PorcelainJsonEntityInfo) (obj)).mArtistName) || !cty.a(mTrackName, ((PorcelainJsonEntityInfo) (obj)).mTrackName) || !cty.a(mAlbumImageUri, ((PorcelainJsonEntityInfo) (obj)).mAlbumImageUri)) { return false; } } return true; } public String getAlbumImageUri() { return mAlbumImageUri; } public String getAlbumName() { return mAlbumName; } public String getAlbumUri() { return mAlbumUri; } public String getArtistName() { return mArtistName; } public String getArtistUri() { return mArtistUri; } public String getTrackName() { return mTrackName; } public int hashCode() { int j = mAlbumUri.hashCode(); int k = mAlbumName.hashCode(); int l = mArtistUri.hashCode(); int i1 = mArtistName.hashCode(); int j1 = mTrackName.hashCode(); int i; if (mAlbumImageUri != null) { i = mAlbumImageUri.hashCode(); } else { i = 0; } return i + ((((j * 31 + k) * 31 + l) * 31 + i1) * 31 + j1) * 31; } public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mAlbumUri); parcel.writeString(mAlbumName); parcel.writeString(mArtistUri); parcel.writeString(mArtistName); parcel.writeString(mTrackName); parcel.writeString(mAlbumImageUri); } public PorcelainJsonEntityInfo(String s, String s1, String s2, String s3, String s4, String s5) { mAlbumUri = (String)ctz.a(s); mAlbumName = (String)ctz.a(s1); mArtistUri = (String)ctz.a(s2); mArtistName = (String)ctz.a(s3); mTrackName = (String)ctz.a(s4); mAlbumImageUri = s5; } } }
UTF-8
Java
8,924
java
PorcelainJsonPlayable.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.9995695352554321, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" }, { "context": "vate static final String KEY_ARTIST_NAME = \"artistName\";\n private static final String KEY_ARTIST_", "end": 5813, "score": 0.5071060657501221, "start": 5809, "tag": "KEY", "value": "Name" } ]
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.spotify.mobile.android.porcelain.json.subitem; import android.os.Parcel; import android.os.Parcelable; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableMap; import com.spotify.mobile.android.cosmos.player.v2.PlayerTrack; import cty; import cur; import drz; import dsa; import gen; // Referenced classes of package com.spotify.mobile.android.porcelain.json.subitem: // PorcelainJsonLoggableEntity public class PorcelainJsonPlayable extends PorcelainJsonLoggableEntity implements Parcelable, drz { public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() { public final Object createFromParcel(Parcel parcel) { return new PorcelainJsonPlayable(parcel.readString(), parcel.readString(), (PorcelainJsonEntityInfo)parcel.readParcelable(com/spotify/mobile/android/porcelain/json/subitem/PorcelainJsonPlayable$PorcelainJsonEntityInfo.getClassLoader()), parcel.readString(), gen.e(parcel)); } public final volatile Object[] newArray(int i) { return new PorcelainJsonPlayable[i]; } }; private static final String KEY_CONTEXT = "context"; private static final String KEY_ENTITY_INFO = "playerTrack"; private static final String KEY_GROUP = "group"; private static final String KEY_URI = "uri"; private final String mContext; private final PorcelainJsonEntityInfo mEntityInfo; private final String mGroup; private final String mUri; public PorcelainJsonPlayable(String s, String s1, PorcelainJsonEntityInfo porcelainjsonentityinfo, String s2, JsonNode jsonnode) { super(s1, jsonnode); mGroup = s2; mContext = s; mEntityInfo = porcelainjsonentityinfo; mUri = s1; } public int describeContents() { return 0; } public boolean equals(Object obj) { if (this != obj) { if (obj == null || getClass() != obj.getClass()) { return false; } obj = (PorcelainJsonPlayable)obj; if (!cty.a(mContext, ((PorcelainJsonPlayable) (obj)).mContext) || !cty.a(mUri, ((PorcelainJsonPlayable) (obj)).mUri) || !cty.a(mEntityInfo, ((PorcelainJsonPlayable) (obj)).mEntityInfo) || !cty.a(mGroup, ((PorcelainJsonPlayable) (obj)).mGroup)) { return false; } } return true; } public final String getContext() { return mContext; } public final PorcelainJsonEntityInfo getEntityInfo() { return mEntityInfo; } public volatile dsa getEntityInfo() { return getEntityInfo(); } public final String getGroup() { return mGroup; } public final String getUri() { return mUri; } public int hashCode() { int l = 0; int i; int j; int k; if (mContext != null) { i = mContext.hashCode(); } else { i = 0; } if (mUri != null) { j = mUri.hashCode(); } else { j = 0; } if (mEntityInfo != null) { k = mEntityInfo.hashCode(); } else { k = 0; } if (mGroup != null) { l = mGroup.hashCode(); } return (k + (j + i * 31) * 31) * 31 + l; } public final boolean isPlayable() { return mUri != null && mEntityInfo != null; } public PlayerTrack toPlayerTrack() { if (isPlayable()) { PorcelainJsonEntityInfo porcelainjsonentityinfo = getEntityInfo(); String s = getUri(); cur cur1 = ImmutableMap.i(); cur1.a("media.type", "audio").a("artist_name", porcelainjsonentityinfo.getArtistName()).a("album_title", porcelainjsonentityinfo.getAlbumName()).a("title", porcelainjsonentityinfo.getTrackName()); if (porcelainjsonentityinfo.getAlbumImageUri() != null) { cur1.a("image_url", porcelainjsonentityinfo.getAlbumImageUri()); } return PlayerTrack.create(s, porcelainjsonentityinfo.getAlbumUri(), porcelainjsonentityinfo.getArtistUri(), cur1.a()); } else { throw new AssertionError("Playable cannot be played!"); } } public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mContext); parcel.writeString(mUri); parcel.writeParcelable(mEntityInfo, i); parcel.writeString(mGroup); writeExtraDataToParcel(parcel); } private class PorcelainJsonEntityInfo implements Parcelable, JacksonModel, dsa { public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() { public final Object createFromParcel(Parcel parcel) { return new PorcelainJsonEntityInfo(parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString()); } public final volatile Object[] newArray(int i) { return new PorcelainJsonEntityInfo[i]; } }; private static final String KEY_ALBUM_IMAGE = "albumImageUri"; private static final String KEY_ALBUM_NAME = "albumName"; private static final String KEY_ALBUM_URI = "albumUri"; private static final String KEY_ARTIST_NAME = "artistName"; private static final String KEY_ARTIST_URI = "artistUri"; private static final String KEY_TRACK_NAME = "trackName"; private final String mAlbumImageUri; private final String mAlbumName; private final String mAlbumUri; private final String mArtistName; private final String mArtistUri; private final String mTrackName; public int describeContents() { return 0; } public boolean equals(Object obj) { if (this != obj) { if (obj == null || getClass() != obj.getClass()) { return false; } obj = (PorcelainJsonEntityInfo)obj; if (!cty.a(mAlbumUri, ((PorcelainJsonEntityInfo) (obj)).mAlbumUri) || !cty.a(mAlbumName, ((PorcelainJsonEntityInfo) (obj)).mAlbumName) || !cty.a(mArtistUri, ((PorcelainJsonEntityInfo) (obj)).mArtistUri) || !cty.a(mArtistName, ((PorcelainJsonEntityInfo) (obj)).mArtistName) || !cty.a(mTrackName, ((PorcelainJsonEntityInfo) (obj)).mTrackName) || !cty.a(mAlbumImageUri, ((PorcelainJsonEntityInfo) (obj)).mAlbumImageUri)) { return false; } } return true; } public String getAlbumImageUri() { return mAlbumImageUri; } public String getAlbumName() { return mAlbumName; } public String getAlbumUri() { return mAlbumUri; } public String getArtistName() { return mArtistName; } public String getArtistUri() { return mArtistUri; } public String getTrackName() { return mTrackName; } public int hashCode() { int j = mAlbumUri.hashCode(); int k = mAlbumName.hashCode(); int l = mArtistUri.hashCode(); int i1 = mArtistName.hashCode(); int j1 = mTrackName.hashCode(); int i; if (mAlbumImageUri != null) { i = mAlbumImageUri.hashCode(); } else { i = 0; } return i + ((((j * 31 + k) * 31 + l) * 31 + i1) * 31 + j1) * 31; } public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mAlbumUri); parcel.writeString(mAlbumName); parcel.writeString(mArtistUri); parcel.writeString(mArtistName); parcel.writeString(mTrackName); parcel.writeString(mAlbumImageUri); } public PorcelainJsonEntityInfo(String s, String s1, String s2, String s3, String s4, String s5) { mAlbumUri = (String)ctz.a(s); mAlbumName = (String)ctz.a(s1); mArtistUri = (String)ctz.a(s2); mArtistName = (String)ctz.a(s3); mTrackName = (String)ctz.a(s4); mAlbumImageUri = s5; } } }
8,914
0.575863
0.569812
293
29.457338
41.144409
433
false
false
0
0
0
0
71
0.007956
0.587031
false
false
2
896dba13d34f42f211ff2da48d7f69e9de803427
19,559,281,117,140
165850aea55ec60cec055ed8ca0de05603207d97
/strings/ReverseWordsInString.java
e212cdc6160e5372c2a389ade5099259f63a48eb
[]
no_license
thepiyushmital/Data-Structures
https://github.com/thepiyushmital/Data-Structures
949faa868d295f82ad5dd1312e3dc58ab26ceabf
1e98bf7b42e8dc1b0dfa36ad5e6dd3dab3337462
refs/heads/main
2023-04-25T22:53:05.077000
2021-05-24T03:31:10
2021-05-24T03:31:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; class ReverseWordsInString{ public static String reverseWordsNaive(String str){ String strArray[] = str.split(" "); if(strArray.length == 0) return str; StringBuilder sb = new StringBuilder(); for(int i = strArray.length - 1; i > 0; i--){ sb.append(strArray[i]).append(" "); } sb.append(strArray[0]); return sb.toString(); } public static String reverWordsEfficient(String str){ char[] charArr = str.toCharArray(); int start = 0; for(int end = 0; end < charArr.length; end++){ if(charArr[end] == ' '){ reverse(charArr, start, end); start = end + 1; } } reverse(charArr, start, charArr.length - 1); reverse(charArr, 0, charArr.length - 1); // One can also use new String(charArr) return String.valueOf(charArr); } public static void main(String args[]){ String str = "I love coding"; str = reverseWords(String str); return; } }
UTF-8
Java
928
java
ReverseWordsInString.java
Java
[]
null
[]
import java.util.*; class ReverseWordsInString{ public static String reverseWordsNaive(String str){ String strArray[] = str.split(" "); if(strArray.length == 0) return str; StringBuilder sb = new StringBuilder(); for(int i = strArray.length - 1; i > 0; i--){ sb.append(strArray[i]).append(" "); } sb.append(strArray[0]); return sb.toString(); } public static String reverWordsEfficient(String str){ char[] charArr = str.toCharArray(); int start = 0; for(int end = 0; end < charArr.length; end++){ if(charArr[end] == ' '){ reverse(charArr, start, end); start = end + 1; } } reverse(charArr, start, charArr.length - 1); reverse(charArr, 0, charArr.length - 1); // One can also use new String(charArr) return String.valueOf(charArr); } public static void main(String args[]){ String str = "I love coding"; str = reverseWords(String str); return; } }
928
0.637931
0.627155
43
20.60465
18.279661
54
false
false
0
0
0
0
0
0
2.27907
false
false
2
e7250fe281b202f4e76f6989c37d85ad3570385c
16,638,703,308,992
3f1726753a3a0b31f6c92d8a4513309817bbb750
/src/main/java/com/athenatics/ruleengine/service/dto/Expression.java
d057aca59d50e78294e4bc634ca91da69355e428
[ "MIT" ]
permissive
athenatics/GIOM-POC
https://github.com/athenatics/GIOM-POC
b6b044225d287b03dc1493de62a062141435eb64
e7ef5b5ad17b16e5d0f4cb64d803514fa5ae08df
refs/heads/master
2018-11-18T09:45:36.139000
2017-06-26T15:45:16
2017-06-26T15:45:16
94,418,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.athenatics.ruleengine.service.dto; import java.io.Serializable; /** * Expression interface. * * @author Praveen.Puskar * @Created May 22, 2016, 12:05:24 AM */ public interface Expression extends Serializable { /** * Gets the property value. * * @return the property value */ public String getPropertyValue(); /** * Gets the operator. * * @return the operator */ public Operator getOperator(); }
UTF-8
Java
473
java
Expression.java
Java
[ { "context": "zable;\n\n/**\n * Expression interface.\n *\n * @author Praveen.Puskar\n * @Created May 22, 2016, 12:05:24 AM\n */\npublic ", "end": 135, "score": 0.9998732209205627, "start": 121, "tag": "NAME", "value": "Praveen.Puskar" } ]
null
[]
package com.athenatics.ruleengine.service.dto; import java.io.Serializable; /** * Expression interface. * * @author Praveen.Puskar * @Created May 22, 2016, 12:05:24 AM */ public interface Expression extends Serializable { /** * Gets the property value. * * @return the property value */ public String getPropertyValue(); /** * Gets the operator. * * @return the operator */ public Operator getOperator(); }
473
0.627907
0.602537
27
16.518518
15.896355
50
false
false
0
0
0
0
0
0
0.222222
false
false
2
7735cd376d81d99c32d5a8fed3512e7b8277b494
10,754,598,163,874
c912dfd3d58de95ae2a5e06ee9e536474d0b4dd5
/myshowbooking/src/main/java/com/myshowbooking/main/movie/controller/EventController.java
563a8148b801b4e7ac95a49ecdc7c6f9472cb88f
[]
no_license
Aayog/Java_projects
https://github.com/Aayog/Java_projects
4c8f5867d4cdc78701c0f7c48747b7900d2a008f
ebc880053749baa329d3d2ec453f9164ca32db89
refs/heads/master
2020-09-05T08:04:48.435000
2020-03-06T05:54:28
2020-03-06T05:54:28
220,034,756
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myshowbooking.main.movie.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.myshowbooking.main.movie.model.EventModel; import com.myshowbooking.main.movie.service.EvenCrudeService; @Controller public class EventController { @Autowired EvenCrudeService eventCrudService; @RequestMapping("/") public String getEventDisplay(Model model) { return "index"; } @RequestMapping("/insertevent") public String geteventinsert(@ModelAttribute EventModel eventmovie) { eventCrudService.insertNewEvent(eventmovie); return "index"; } @RequestMapping("/updateevent") public String geteventupdate(@ModelAttribute EventModel eventmovie) { eventCrudService.updatebookingStatus(eventmovie); return "index"; } }
UTF-8
Java
986
java
EventController.java
Java
[]
null
[]
package com.myshowbooking.main.movie.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.myshowbooking.main.movie.model.EventModel; import com.myshowbooking.main.movie.service.EvenCrudeService; @Controller public class EventController { @Autowired EvenCrudeService eventCrudService; @RequestMapping("/") public String getEventDisplay(Model model) { return "index"; } @RequestMapping("/insertevent") public String geteventinsert(@ModelAttribute EventModel eventmovie) { eventCrudService.insertNewEvent(eventmovie); return "index"; } @RequestMapping("/updateevent") public String geteventupdate(@ModelAttribute EventModel eventmovie) { eventCrudService.updatebookingStatus(eventmovie); return "index"; } }
986
0.809331
0.809331
37
25.648649
24.541433
71
false
false
0
0
0
0
0
0
1
false
false
2
37564f4d68d8d0b88dac058c89157f20975d9404
34,471,407,554,328
f73cba92ee671b496d6dd92f0941387c55f4cf44
/src/main/java/com/loan/pojo/DataCustomerLoan.java
9a6eaba9a3c93300eceea8108ae9b5a59dd5c8fb
[]
no_license
Pastelhorizon/CLRA-LoanManagementMicroservice
https://github.com/Pastelhorizon/CLRA-LoanManagementMicroservice
537c536a65122bf56d8fdbcfbe9d5501aab63f76
943a5152bc41329c6ea7b44302691a9b26a5ae01
refs/heads/master
2023-06-01T22:09:11.445000
2021-06-20T17:25:06
2021-06-20T17:25:06
377,193,215
0
1
null
false
2021-06-21T03:42:26
2021-06-15T14:33:13
2021-06-20T17:25:15
2021-06-20T17:25:13
59
0
1
1
Java
false
false
package com.loan.pojo; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @ToString public class DataCustomerLoan { private int loanProductId; private double loanPrincipal; private double tenure; private double interest; private double emi; }
UTF-8
Java
337
java
DataCustomerLoan.java
Java
[]
null
[]
package com.loan.pojo; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @ToString public class DataCustomerLoan { private int loanProductId; private double loanPrincipal; private double tenure; private double interest; private double emi; }
337
0.807122
0.807122
19
16.736841
10.871702
32
false
false
0
0
0
0
0
0
0.842105
false
false
7
509974beba6c681409249f2c90357dbe98f62b6a
30,897,994,775,941
0a5bb71fea67b66a8639f7c6bc7aa68f71cd8214
/ecrm-s/src/main/java/com/maven/dao/impl/BettingQwpDaoImpl.java
373057018799fb9c7926a9132df39d3062b434c6
[]
no_license
daxingyou/bw
https://github.com/daxingyou/bw
4e4e100c1428153ccc54d5ded2119840c839841d
b7a3021fe13969510fbcf35b82982617c090e57d
refs/heads/master
2022-01-07T22:30:09.117000
2019-01-14T09:19:06
2019-01-14T09:19:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.maven.dao.impl; import java.util.Map; import org.springframework.stereotype.Repository; import com.maven.base.dao.impl.BaseDaoImpl; import com.maven.dao.BettingQwpDao; import com.maven.entity.BettingQwp; @Repository public class BettingQwpDaoImpl extends BaseDaoImpl<BettingQwp> implements BettingQwpDao { /** * 获取游戏记录总数之金额统计 * @param object * @return */ public Map<String, Object> takeRecordCountMoney(Map<String, Object> object) throws Exception { return getSqlSession().selectOne("BettingQwp.takeRecordCountMoney", object); } }
UTF-8
Java
585
java
BettingQwpDaoImpl.java
Java
[]
null
[]
package com.maven.dao.impl; import java.util.Map; import org.springframework.stereotype.Repository; import com.maven.base.dao.impl.BaseDaoImpl; import com.maven.dao.BettingQwpDao; import com.maven.entity.BettingQwp; @Repository public class BettingQwpDaoImpl extends BaseDaoImpl<BettingQwp> implements BettingQwpDao { /** * 获取游戏记录总数之金额统计 * @param object * @return */ public Map<String, Object> takeRecordCountMoney(Map<String, Object> object) throws Exception { return getSqlSession().selectOne("BettingQwp.takeRecordCountMoney", object); } }
585
0.785331
0.785331
21
25.666666
29.214043
95
false
false
0
0
0
0
0
0
0.904762
false
false
7
b23444bb0d6f94b0122577432057eb673fe0cc3d
15,659,450,815,381
14154c28abc2ed8b897b8da7e988c921d1d512c3
/product-crawler/src/main/java/com/mode/entity/CheckProductStatus.java
3ad70c87ea3cdf191008afd78fda2bd2e44c1b85
[]
no_license
yuerugou54/javaWeb
https://github.com/yuerugou54/javaWeb
2c519598dd29944d6f453410a6f65eb483b4ced3
a7554879bda61341512976d697b388c92497ca4a
refs/heads/master
2021-05-06T05:50:02.634000
2018-06-26T06:22:21
2018-06-26T06:22:21
115,171,211
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mode.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.Table; /* * @author maxiaodong on 2018/05/07 * @version 0.0.1 */ @Entity @Table(name = "check_product_status", indexes = { @Index(columnList = "productUrl"), @Index(columnList = "id") }) public class CheckProductStatus { @Id @Column(columnDefinition = "bigint(13)") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(length = 100) private String spu; @Column(length = 100) private String sku; @Column(length = 500) private String productUrl; @Column(length = 200) private String status; @Column(length = 2000) private String lackInfo; // 产品编号,有可能需要,非自增 @Column(columnDefinition = "bigint(13)") private Long productId; // 上传时间 @Column(length = 50) private String uploadtime; // 上传用户 @Column(length = 20) private String username; public Long getId() { return id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getLackInfo() { return lackInfo; } public void setLackInfo(String lackInfo) { this.lackInfo = lackInfo; } public String getSpu() { return spu; } public void setSpu(String spu) { this.spu = spu; } public String getProductUrl() { return productUrl; } public void setProductUrl(String productUrl) { this.productUrl = productUrl; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUploadtime() { return uploadtime; } public void setUploadtime(String uploadtime) { this.uploadtime = uploadtime; } }
UTF-8
Java
2,408
java
CheckProductStatus.java
Java
[ { "context": "ex;\nimport javax.persistence.Table;\n\n/*\n * @author maxiaodong on 2018/05/07\n * @version 0.0.1\n */\n\n@Entity\n@Tab", "end": 292, "score": 0.9996418356895447, "start": 282, "tag": "USERNAME", "value": "maxiaodong" } ]
null
[]
package com.mode.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.Table; /* * @author maxiaodong on 2018/05/07 * @version 0.0.1 */ @Entity @Table(name = "check_product_status", indexes = { @Index(columnList = "productUrl"), @Index(columnList = "id") }) public class CheckProductStatus { @Id @Column(columnDefinition = "bigint(13)") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(length = 100) private String spu; @Column(length = 100) private String sku; @Column(length = 500) private String productUrl; @Column(length = 200) private String status; @Column(length = 2000) private String lackInfo; // 产品编号,有可能需要,非自增 @Column(columnDefinition = "bigint(13)") private Long productId; // 上传时间 @Column(length = 50) private String uploadtime; // 上传用户 @Column(length = 20) private String username; public Long getId() { return id; } public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getLackInfo() { return lackInfo; } public void setLackInfo(String lackInfo) { this.lackInfo = lackInfo; } public String getSpu() { return spu; } public void setSpu(String spu) { this.spu = spu; } public String getProductUrl() { return productUrl; } public void setProductUrl(String productUrl) { this.productUrl = productUrl; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSku() { return sku; } public void setSku(String sku) { this.sku = sku; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUploadtime() { return uploadtime; } public void setUploadtime(String uploadtime) { this.uploadtime = uploadtime; } }
2,408
0.62775
0.612944
120
18.700001
16.578903
84
false
false
0
0
0
0
0
0
0.3
false
false
7
44b7a90cd36e606b8917c1f14773ae2e4c95c375
5,712,306,537,997
6cf4b8ff17e5f26abde823bc6d19a5bb5ea3763a
/src/main/java/ua/org/training/workshop/dao/RequestDao.java
c0e067a59bd47a478e9c9a1a496e3ba534c5500d
[]
no_license
kissik/workshop
https://github.com/kissik/workshop
9086ce5336164637a86f0c223410e9dbc6d2d5d6
e8c94642833d65daf7e6bb88fddfd46b839f1bbf
refs/heads/master
2022-06-25T19:26:26.352000
2020-02-17T11:17:25
2020-02-17T11:17:25
238,503,071
0
2
null
false
2022-06-21T02:44:52
2020-02-05T17:01:52
2020-02-17T11:17:42
2022-06-21T02:44:49
9,156
0
1
2
Java
false
false
package ua.org.training.workshop.dao; import ua.org.training.workshop.domain.Request; import ua.org.training.workshop.utility.Page; public interface RequestDao extends GenericDao<Request> { Page<Request> getPageByAuthor( Page<Request> page, Long authorId); Page<Request> getPageByLanguageAndAuthor( Page<Request> page, String language, Long authorId); Page<Request> getPageByLanguageAndStatus( Page<Request> page, String language, Long statusId); }
UTF-8
Java
561
java
RequestDao.java
Java
[]
null
[]
package ua.org.training.workshop.dao; import ua.org.training.workshop.domain.Request; import ua.org.training.workshop.utility.Page; public interface RequestDao extends GenericDao<Request> { Page<Request> getPageByAuthor( Page<Request> page, Long authorId); Page<Request> getPageByLanguageAndAuthor( Page<Request> page, String language, Long authorId); Page<Request> getPageByLanguageAndStatus( Page<Request> page, String language, Long statusId); }
561
0.654189
0.654189
20
27.049999
17.411131
57
false
false
0
0
0
0
0
0
0.55
false
false
7
8f3dfc0eabd5cf01030ab50cdfbd3b196ab832d0
32,916,629,426,494
ab1af9783ebdc9b1e5e2bf3f0aed0cf2503e4231
/src/ProjectManagement/Forum/ThreadObserver.java
1d332442dd03b2a04d5e00d544e16db803d4d758
[]
no_license
Cyberuben/avans-ts
https://github.com/Cyberuben/avans-ts
91ea39538df6ddb5424ad02af5c8443a353e9f36
c95a64f4e67f410aecfbb4b0c06b7ecd8d5b247c
refs/heads/master
2021-04-26T22:26:08.266000
2018-03-07T22:17:38
2018-03-07T22:17:38
124,091,414
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ProjectManagement.Forum; public interface ThreadObserver { public void onPost(Thread thread, Post post); }
UTF-8
Java
120
java
ThreadObserver.java
Java
[]
null
[]
package ProjectManagement.Forum; public interface ThreadObserver { public void onPost(Thread thread, Post post); }
120
0.783333
0.783333
5
23
19.339079
49
false
false
0
0
0
0
0
0
0.6
false
false
7
bcf6262c807071babdb625dc02c56b665553f2e6
18,373,870,111,617
35418a2539871cec17c320fe64951a8b1bfa7874
/decorator/src/main/java/com/darakay/patterns/message/AnonymousMessage.java
dd8f97be940c322091b1d9f9ab86ceb1e8283f42
[]
no_license
daria-kay/design-patterns
https://github.com/daria-kay/design-patterns
9e59c9a20cad8fe2660817b191989058e42e0bc6
b4227e497d40f2208f567729eb06cdf207cb4a5b
refs/heads/master
2021-06-27T12:03:58.123000
2019-12-08T17:22:38
2019-12-08T17:22:38
215,328,809
0
0
null
false
2021-03-31T21:46:07
2019-10-15T15:09:08
2019-12-08T17:22:50
2021-03-31T21:46:06
131
0
0
2
Java
false
false
package com.darakay.patterns.message; public class AnonymousMessage extends MessageDecorator { public AnonymousMessage(IMessage message) { super(message); } public String getRecipientName() { return message.getRecipientName(); } public String getAuthorName() { return "SECRET"; } public String getText() { return message.getText(); } }
UTF-8
Java
404
java
AnonymousMessage.java
Java
[]
null
[]
package com.darakay.patterns.message; public class AnonymousMessage extends MessageDecorator { public AnonymousMessage(IMessage message) { super(message); } public String getRecipientName() { return message.getRecipientName(); } public String getAuthorName() { return "SECRET"; } public String getText() { return message.getText(); } }
404
0.653465
0.653465
20
19.200001
18.527277
56
false
false
0
0
0
0
0
0
0.25
false
false
7
42b98957e151619408b5f4baac9b1077ec11d344
30,142,080,534,280
69a4f2d51ebeea36c4d8192e25cfb5f3f77bef5e
/methods/Method_15646.java
e304aa30c929169ba69260e408c568abd9703e1a
[]
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
@Override public Optional<Double> asDouble(){ return Optional.empty(); }
UTF-8
Java
75
java
Method_15646.java
Java
[]
null
[]
@Override public Optional<Double> asDouble(){ return Optional.empty(); }
75
0.733333
0.733333
3
24
18.018509
45
false
false
0
0
0
0
0
0
0.333333
false
false
7
c9fe8b23f0ea1484b544c86edc6c8bbd87f19991
29,248,727,331,570
9d9c0d9aba0c3102787a0215621b24dbe7f64b59
/jeecms-front/src/main/java/com/jeecms/common/FrontDispatcherConfig.java
e7bbd76c71c96955087fe29c01508ad4fcb75548
[]
no_license
hd19901110/jeecms1.4.1test
https://github.com/hd19901110/jeecms1.4.1test
b354019c57a06384524d53aa667614c1f4e5a743
4e3e0cb31513e53004aa20c108f79741203becb0
refs/heads/master
2022-12-08T06:10:06.868000
2020-08-31T09:59:19
2020-08-31T09:59:19
285,445,431
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jeecms.common; import com.jeecms.front.config.FrontConfig; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.MultipartConfigElement; /** * 注册前端Dispatcher * * @author: tom * @date: 2019年1月5日 下午2:06:38 * @Copyright: 江西金磊科技发展有限公司 All rights reserved.Notice * 仅限于授权后使用,禁止非授权传阅以及私自用于商业目的。 */ @Component public class FrontDispatcherConfig { /** * 前端 DispatcherServlet bean * @Title: frontDispatcherServlet * @return: DispatcherServlet */ @Bean(name = "frontDispatcherServlet") public DispatcherServlet frontDispatcherServlet() { AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext(); /*** 使用FrontConfig作为配置类 */ servletAppContext.register(FrontConfig.class); DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext); return dispatcherServlet; } /** * 注册 前端 DispatcherServlet * @Title: dispatcherServletRegistration * @param multipartConfigProvider MultipartConfigElement * @return: ServletRegistrationBean ServletRegistrationBean */ @Bean(name = "frontDispatcherServletRegistration") public ServletRegistrationBean<DispatcherServlet> dispatcherServletRegistration( ObjectProvider<MultipartConfigElement> multipartConfigProvider,DispatcherServlet frontDispatcherServlet) { ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean<DispatcherServlet>(frontDispatcherServlet); // 必须指定启动优先级,否则无法生效 registration.setLoadOnStartup(1); registration.setName("frontDispatcherServlet"); // 注册上传配置对象,否则后台不能处理上传 /*MultipartConfigElement multipartConfig = multipartConfigProvider.getIfAvailable(); if (multipartConfig != null) { registration.setMultipartConfig(multipartConfig); }*/ return registration; } }
UTF-8
Java
2,388
java
FrontDispatcherConfig.java
Java
[ { "context": "ement;\r\n\r\n/**\r\n * 注册前端Dispatcher\r\n * \r\n * @author: tom\r\n * @date: 2019年1月5日 下午2:06:38\r\n * @Copyright: 江西", "end": 546, "score": 0.9903590083122253, "start": 543, "tag": "USERNAME", "value": "tom" }, { "context": "tom\r\n * @date: 2019年1月5日 下午2:06:38\r\n * @Copyright: 江西金磊科技发展有限公司 All rights reserved.Notice\r\n * ", "end": 598, "score": 0.8346362113952637, "start": 594, "tag": "NAME", "value": "江西金磊" } ]
null
[]
package com.jeecms.common; import com.jeecms.front.config.FrontConfig; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import javax.servlet.MultipartConfigElement; /** * 注册前端Dispatcher * * @author: tom * @date: 2019年1月5日 下午2:06:38 * @Copyright: 江西金磊科技发展有限公司 All rights reserved.Notice * 仅限于授权后使用,禁止非授权传阅以及私自用于商业目的。 */ @Component public class FrontDispatcherConfig { /** * 前端 DispatcherServlet bean * @Title: frontDispatcherServlet * @return: DispatcherServlet */ @Bean(name = "frontDispatcherServlet") public DispatcherServlet frontDispatcherServlet() { AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext(); /*** 使用FrontConfig作为配置类 */ servletAppContext.register(FrontConfig.class); DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext); return dispatcherServlet; } /** * 注册 前端 DispatcherServlet * @Title: dispatcherServletRegistration * @param multipartConfigProvider MultipartConfigElement * @return: ServletRegistrationBean ServletRegistrationBean */ @Bean(name = "frontDispatcherServletRegistration") public ServletRegistrationBean<DispatcherServlet> dispatcherServletRegistration( ObjectProvider<MultipartConfigElement> multipartConfigProvider,DispatcherServlet frontDispatcherServlet) { ServletRegistrationBean<DispatcherServlet> registration = new ServletRegistrationBean<DispatcherServlet>(frontDispatcherServlet); // 必须指定启动优先级,否则无法生效 registration.setLoadOnStartup(1); registration.setName("frontDispatcherServlet"); // 注册上传配置对象,否则后台不能处理上传 /*MultipartConfigElement multipartConfig = multipartConfigProvider.getIfAvailable(); if (multipartConfig != null) { registration.setMultipartConfig(multipartConfig); }*/ return registration; } }
2,388
0.785519
0.780055
60
34.599998
28.169842
109
false
false
0
0
0
0
0
0
1.25
false
false
7
de2a2ff2c69ffac6e994751214dd1f95e4755608
3,341,484,561,636
35e46a270d1de548763c161c0dac554282a33d9d
/CSIS-DevR3/csis.dao/src/main/java/bo/gob/sin/sre/fac/dao/IArchivosDao.java
01d179e000d7ad5cc3bc6cbe407cc960e62f7389
[]
no_license
cruz-victor/ServiciosSOAPyRESTJavaSpringBoot
https://github.com/cruz-victor/ServiciosSOAPyRESTJavaSpringBoot
e817e16c8518b3135a26d7ad7f6b0deb8066fe42
f04a2b40b118d2d34269c4f954537025b67b3784
refs/heads/master
2023-01-07T11:09:30.758000
2020-11-15T14:01:08
2020-11-15T14:01:08
312,744,182
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bo.gob.sin.sre.fac.dao; import bo.gob.sin.sre.fac.model.SreArchivos; import bo.gob.sin.str.ccs.dao.GenericDao; //IASC public interface IArchivosDao extends GenericDao<SreArchivos>{ }
UTF-8
Java
196
java
IArchivosDao.java
Java
[]
null
[]
package bo.gob.sin.sre.fac.dao; import bo.gob.sin.sre.fac.model.SreArchivos; import bo.gob.sin.str.ccs.dao.GenericDao; //IASC public interface IArchivosDao extends GenericDao<SreArchivos>{ }
196
0.77551
0.77551
11
16.818182
22.04878
62
false
false
0
0
0
0
0
0
0.272727
false
false
7
3bc0e5a20359a2f56fd7e31fe6d281621a7e864c
12,043,088,343,885
4814b51c6afe60939effda6be09649d736055e57
/src/Services/servicesTeam.java
3a44533973acd0bc96aedae766caabcf85dab069
[]
no_license
elyes10/Game-Division
https://github.com/elyes10/Game-Division
a9986b303704f08a82625af8553522f4ed502c0f
181a9aaefaface69efea7fd02f61cef5ab137e51
refs/heads/main
2023-04-23T06:53:10.078000
2021-03-31T01:09:48
2021-03-31T01:09:48
342,914,028
0
1
null
false
2021-03-30T13:17:32
2021-02-27T17:18:50
2021-03-27T20:38:00
2021-03-30T13:15:55
51,336
0
1
1
Java
false
false
/* * 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 Services; import entities.connecttoDb; import entities.Teams; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author iyadh */ public class servicesTeam { Connection c = connecttoDb.getInstance().getCnx(); public void addteam(Teams t ) throws SQLException{ Statement st; try { st = c.createStatement(); String rec = " INSERT INTO `teams`(`team_id`, `team_name`, `team_logo`, `Team_Website`, `user1_id`, `user2_id`, `user3_id`, `user4_id`, `user5_id`) " + " VALUES ('"+t.getTeam_id()+"','"+t.getTeam_name()+"','"+t.getTeam_logo()+"','"+t.getTeam_Website()+"','"+t.getUser1_id()+"','"+t.getUser2_id()+"','"+t.getUser3_id()+"','"+t.getUser4_id()+"','"+t.getUser5_id()+"')"; st.executeUpdate(rec); System.err.println("add successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void addteam1(Teams t ) throws SQLException{ Statement st; try { st = c.createStatement(); String rec = " INSERT INTO `teams`(`team_name`, `team_logo`, `Team_Website`, `user1_id`, `user2_id`, `user3_id`, `user4_id`, `user5_id`) " + " VALUES ('"+t.getTeam_name()+"','"+t.getTeam_logo()+"','"+t.getTeam_Website()+"','"+t.getUser1_id()+"','"+t.getUser2_id()+"','"+t.getUser3_id()+"','"+t.getUser4_id()+"','"+t.getUser5_id()+"')"; st.executeUpdate(rec); System.err.println("add successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void showTeams() { PreparedStatement pt; try { pt = c.prepareStatement("select * from teams"); ResultSet rs = pt.executeQuery(); while (rs.next()) { System.out.println("Team [ team_id : " + rs.getInt(1) + ", team_name " + rs.getString(2) + ", team_logo " + rs.getString(3) +", team_website " +rs.getString(4)+" menber1_id "+rs.getInt(5)+" menber2_id "+rs.getInt(6)+" member3_id "+ rs.getInt(7)+" member4_id "+rs.getInt(7)+" member5_id "+ rs.getInt(8)); } } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void updateTeams(int id, Teams t) { try { PreparedStatement pt = c.prepareStatement("UPDATE `teams` SET `team_name`=?,`team_logo`=?,`Team_Website`=?,`user1_id`=?,`user2_id`=?,`user3_id`=?,`user4_id`=?,`user5_id`=? WHERE team_id=?"); pt.setString(1, t.getTeam_name()); pt.setString(2, t.getTeam_logo()); pt.setString(3,t.getTeam_Website()); pt.setInt(4, t.getUser1_id()); pt.setInt(5, t.getUser2_id()); pt.setInt(6, t.getUser3_id()); pt.setInt(7, t.getUser4_id()); pt.setInt(8, t.getUser5_id()); pt.setInt(9, id); pt.executeUpdate(); System.err.println("update successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void deleteTeams(Teams t) { PreparedStatement pt; try { pt = c.prepareStatement("delete from teams where team_id=? "); pt.setInt(1, t.getTeam_id()); pt.executeUpdate(); System.out.println("delete successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public List<Teams> getAll(){ List<Teams> us = new ArrayList<>(); PreparedStatement p; try { p = c.prepareStatement("select * from teams"); ResultSet rs = p.executeQuery(); while (rs.next()){ //Teams u = new Teams(rs.getString(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getInt(5),rs.getInt(6),rs.getInt(7),rs.getInt(8)); Teams u = new Teams(rs.getInt(1),rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5),rs.getInt(6),rs.getInt(7),rs.getInt(8),rs.getInt(9)); us.add(u); System.out.println("success"); } } catch (SQLException ex) { Logger.getLogger(servicesUser.class.getName()).log(Level.SEVERE, null, ex); } return us; } }
UTF-8
Java
5,132
java
servicesTeam.java
Java
[ { "context": "t java.util.logging.Logger;\r\n\r\n/**\r\n *\r\n * @author iyadh\r\n */\r\npublic class servicesTeam {\r\n \r\n Connec", "end": 564, "score": 0.9842711091041565, "start": 559, "tag": "USERNAME", "value": "iyadh" } ]
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 Services; import entities.connecttoDb; import entities.Teams; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author iyadh */ public class servicesTeam { Connection c = connecttoDb.getInstance().getCnx(); public void addteam(Teams t ) throws SQLException{ Statement st; try { st = c.createStatement(); String rec = " INSERT INTO `teams`(`team_id`, `team_name`, `team_logo`, `Team_Website`, `user1_id`, `user2_id`, `user3_id`, `user4_id`, `user5_id`) " + " VALUES ('"+t.getTeam_id()+"','"+t.getTeam_name()+"','"+t.getTeam_logo()+"','"+t.getTeam_Website()+"','"+t.getUser1_id()+"','"+t.getUser2_id()+"','"+t.getUser3_id()+"','"+t.getUser4_id()+"','"+t.getUser5_id()+"')"; st.executeUpdate(rec); System.err.println("add successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void addteam1(Teams t ) throws SQLException{ Statement st; try { st = c.createStatement(); String rec = " INSERT INTO `teams`(`team_name`, `team_logo`, `Team_Website`, `user1_id`, `user2_id`, `user3_id`, `user4_id`, `user5_id`) " + " VALUES ('"+t.getTeam_name()+"','"+t.getTeam_logo()+"','"+t.getTeam_Website()+"','"+t.getUser1_id()+"','"+t.getUser2_id()+"','"+t.getUser3_id()+"','"+t.getUser4_id()+"','"+t.getUser5_id()+"')"; st.executeUpdate(rec); System.err.println("add successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void showTeams() { PreparedStatement pt; try { pt = c.prepareStatement("select * from teams"); ResultSet rs = pt.executeQuery(); while (rs.next()) { System.out.println("Team [ team_id : " + rs.getInt(1) + ", team_name " + rs.getString(2) + ", team_logo " + rs.getString(3) +", team_website " +rs.getString(4)+" menber1_id "+rs.getInt(5)+" menber2_id "+rs.getInt(6)+" member3_id "+ rs.getInt(7)+" member4_id "+rs.getInt(7)+" member5_id "+ rs.getInt(8)); } } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void updateTeams(int id, Teams t) { try { PreparedStatement pt = c.prepareStatement("UPDATE `teams` SET `team_name`=?,`team_logo`=?,`Team_Website`=?,`user1_id`=?,`user2_id`=?,`user3_id`=?,`user4_id`=?,`user5_id`=? WHERE team_id=?"); pt.setString(1, t.getTeam_name()); pt.setString(2, t.getTeam_logo()); pt.setString(3,t.getTeam_Website()); pt.setInt(4, t.getUser1_id()); pt.setInt(5, t.getUser2_id()); pt.setInt(6, t.getUser3_id()); pt.setInt(7, t.getUser4_id()); pt.setInt(8, t.getUser5_id()); pt.setInt(9, id); pt.executeUpdate(); System.err.println("update successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public void deleteTeams(Teams t) { PreparedStatement pt; try { pt = c.prepareStatement("delete from teams where team_id=? "); pt.setInt(1, t.getTeam_id()); pt.executeUpdate(); System.out.println("delete successful"); } catch (SQLException ex) { Logger.getLogger(servicesTeam.class.getName()).log(Level.SEVERE, null, ex); } } public List<Teams> getAll(){ List<Teams> us = new ArrayList<>(); PreparedStatement p; try { p = c.prepareStatement("select * from teams"); ResultSet rs = p.executeQuery(); while (rs.next()){ //Teams u = new Teams(rs.getString(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getInt(5),rs.getInt(6),rs.getInt(7),rs.getInt(8)); Teams u = new Teams(rs.getInt(1),rs.getString(2), rs.getString(3), rs.getString(4), rs.getInt(5),rs.getInt(6),rs.getInt(7),rs.getInt(8),rs.getInt(9)); us.add(u); System.out.println("success"); } } catch (SQLException ex) { Logger.getLogger(servicesUser.class.getName()).log(Level.SEVERE, null, ex); } return us; } }
5,132
0.545791
0.531761
132
36.863636
49.178982
328
false
false
0
0
0
0
0
0
1.060606
false
false
7
3303afe858c135460fd3fe05f41ca0d601de4a91
5,815,385,739,068
7549a170d5721f1cbed570880708c77d29e6c2d8
/AppiumTest_-_MobileObjectsSample__1_.java
612f2c448c06a4b13b237835d4bfeffd312d48d9
[]
no_license
hari-canada/JavaCourseSamples
https://github.com/hari-canada/JavaCourseSamples
ea91a19e79119720487191954a278c95207dffc2
f5b4de237304e62435c0dd89b1a3cbc7029a7369
refs/heads/master
2021-09-05T19:19:20.959000
2018-01-30T14:04:42
2018-01-30T14:04:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.html5.*; import org.openqa.selenium.logging.*; import org.openqa.selenium.remote.*; import com.perfectomobile.selenium.util.EclipseConnector; import io.appium.java_client.*; import io.appium.java_client.android.*; import io.appium.java_client.ios.*; public class AppiumTest { public static void main(String[] args) throws MalformedURLException, IOException { System.out.println("Run started"); String cloudUser = "myUser"; String cloudPw = "myPassword"; String resultString; // String browserName = "mobileOS"; DesiredCapabilities capabilities = new DesiredCapabilities("", "", Platform.ANY); String host = "myCloud.perfectomobile.com"; capabilities.setCapability("user", cloudUser); capabilities.setCapability("password", cloudPw); //TODO: Change your device ID capabilities.setCapability("automationName", "Appium"); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("platformVersion", "5.*"); capabilities.setCapability("autoLaunch", true); capabilities.setCapability("fullReset", true); capabilities.setCapability("app", "PUBLIC:Samples/TestApp.apk"); capabilities.setCapability("appPackage", "com.example.testapp"); // Call this method if you want the script to share the devices with the Perfecto Lab plugin. setExecutionIdCapability(capabilities, host); // Add a persona to your script (see https://community.perfectomobile.com/posts/1048047-available-personas) //capabilities.setCapability(WindTunnelUtils.WIND_TUNNEL_PERSONA_CAPABILITY, WindTunnelUtils.GEORGIA); // Name your script // capabilities.setCapability("scriptName", "AppiumTest"); AndroidDriver driver = new AndroidDriver(new URL("https://" + host + "/nexperience/perfectomobile/wd/hub"), capabilities); // IOSDriver driver = new IOSDriver(new URL("https://" + host + "/nexperience/perfectomobile/wd/hub"), capabilities); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); try { // write your code here /* PART 1: * Login to demo application - set user and password and click Login using objects */ //Set the username WebElement nameElement = driver.findElementByXPath("//*[@resource-id='com.example.testapp:id/etName']"); nameElement.sendKeys("John"); //Set the password WebElement passwordElement = driver.findElement(By.xpath("//*[@resource-id='com.example.testapp:id/etPass']")); passwordElement.sendKeys("Perfecto1"); //Click on the Login button WebElement loginElement = driver.findElementByXPath("//*[@text='Login']"); loginElement.click(); //Text checkpoint on "Welcome back John" Map<String, Object> params = new HashMap<>(); params.put("content", "Welcome back John"); params.put("timeout", "20"); resultString = (String) driver.executeScript("mobile:checkpoint:text", params); if (!resultString.equalsIgnoreCase("true")) { System.out.println("Did not login successfully - 'Welcome back John' text not found"); throw new NoSuchFieldException(); } /* PART 2: * Navigate within application */ //Click on Continue button WebElement continueElement = driver.findElementByXPath("//android.widget.Button [@text='Continue']"); continueElement.click(); //Cick on First Screen button WebElement firstScreenElement = driver.findElementByXPath("//android.widget.Button[starts-with(@text,'First')]"); firstScreenElement.click(); //Radio button example for Android devices List<WebElement> radioButtons = driver.findElementsByXPath("//*[@checkable='true']"); for (WebElement radioButton:radioButtons){ radioButton.click(); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Retrieve the URL of the Wind Tunnel Report, can be saved to your execution summary and used to download the report at a later point String reportURL = (String)(driver.getCapabilities().getCapability(WindTunnelUtils.WIND_TUNNEL_REPORT_URL_CAPABILITY)); driver.close(); // In case you want to download the report or the report attachments, do it here. // PerfectoLabUtils.downloadReport(driver, "pdf", "C:\\test\\report"); // PerfectoLabUtils.downloadAttachment(driver, "video", "C:\\test\\report\\video", "flv"); // PerfectoLabUtils.downloadAttachment(driver, "image", "C:\\test\\report\\images", "jpg"); } catch (Exception e) { e.printStackTrace(); } driver.quit(); } System.out.println("Run ended"); } // Recommended: // Remove the comment and use this method if you want the script to share the devices with the recording plugin.\ // Requires import com.perfectomobile.selenium.util.EclipseConnector; private static void setExecutionIdCapability(DesiredCapabilities capabilities) throws IOException { EclipseConnector connector = new EclipseConnector(); String executionId = connector.getExecutionId(); capabilities.setCapability(EclipseConnector.ECLIPSE_EXECUTION_ID, executionId); } }
UTF-8
Java
6,251
java
AppiumTest_-_MobileObjectsSample__1_.java
Java
[ { "context": "rintln(\"Run started\");\r\n\t\t\r\n\t\tString cloudUser = \"myUser\";\r\n\t\tString cloudPw = \"myPassword\";\r\n\t\tString res", "end": 1109, "score": 0.9994157552719116, "start": 1103, "tag": "USERNAME", "value": "myUser" }, { "context": "String cloudUser = \"myUser\";\r\n\t\tString cloudPw = \"myPassword\";\r\n\t\tString resultString;\r\n\t\t\r\n//\t\tString browser", "end": 1143, "score": 0.999383807182312, "start": 1133, "tag": "PASSWORD", "value": "myPassword" }, { "context": ".testapp:id/etName']\");\r\n\t\t\tnameElement.sendKeys(\"John\");\r\n\t\t\t\r\n\t\t\t//Set the password\t\t\t\r\n\t\t\tWebElement ", "end": 3057, "score": 0.999672532081604, "start": 3053, "tag": "NAME", "value": "John" }, { "context": "app:id/etPass']\"));\r\n\t\t\tpasswordElement.sendKeys(\"Perfecto1\");\r\n\t\t\t\r\n\t\t\t//Click on the Login button\t\t\t\r\n\t\t\tWe", "end": 3247, "score": 0.9993872046470642, "start": 3238, "tag": "PASSWORD", "value": "Perfecto1" }, { "context": "k();\r\n\r\n\t\t\t\r\n\t\t\t//Text checkpoint on \"Welcome back John\" \r\n \tMap<String, Object> param", "end": 3455, "score": 0.9813216328620911, "start": 3451, "tag": "NAME", "value": "John" }, { "context": "();\r\n \tparams.put(\"content\", \"Welcome back John\");\r\n \tparams.put(\"timeout\", \"20\");\r\n ", "end": 3577, "score": 0.9963294863700867, "start": 3573, "tag": "NAME", "value": "John" }, { "context": "rintln(\"Did not login successfully - 'Welcome back John' text not found\");\r\n \t\tthrow new NoSuchFi", "end": 3848, "score": 0.9621469378471375, "start": 3844, "tag": "NAME", "value": "John" } ]
null
[]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.openqa.selenium.*; import org.openqa.selenium.html5.*; import org.openqa.selenium.logging.*; import org.openqa.selenium.remote.*; import com.perfectomobile.selenium.util.EclipseConnector; import io.appium.java_client.*; import io.appium.java_client.android.*; import io.appium.java_client.ios.*; public class AppiumTest { public static void main(String[] args) throws MalformedURLException, IOException { System.out.println("Run started"); String cloudUser = "myUser"; String cloudPw = "<PASSWORD>"; String resultString; // String browserName = "mobileOS"; DesiredCapabilities capabilities = new DesiredCapabilities("", "", Platform.ANY); String host = "myCloud.perfectomobile.com"; capabilities.setCapability("user", cloudUser); capabilities.setCapability("password", cloudPw); //TODO: Change your device ID capabilities.setCapability("automationName", "Appium"); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("platformVersion", "5.*"); capabilities.setCapability("autoLaunch", true); capabilities.setCapability("fullReset", true); capabilities.setCapability("app", "PUBLIC:Samples/TestApp.apk"); capabilities.setCapability("appPackage", "com.example.testapp"); // Call this method if you want the script to share the devices with the Perfecto Lab plugin. setExecutionIdCapability(capabilities, host); // Add a persona to your script (see https://community.perfectomobile.com/posts/1048047-available-personas) //capabilities.setCapability(WindTunnelUtils.WIND_TUNNEL_PERSONA_CAPABILITY, WindTunnelUtils.GEORGIA); // Name your script // capabilities.setCapability("scriptName", "AppiumTest"); AndroidDriver driver = new AndroidDriver(new URL("https://" + host + "/nexperience/perfectomobile/wd/hub"), capabilities); // IOSDriver driver = new IOSDriver(new URL("https://" + host + "/nexperience/perfectomobile/wd/hub"), capabilities); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); try { // write your code here /* PART 1: * Login to demo application - set user and password and click Login using objects */ //Set the username WebElement nameElement = driver.findElementByXPath("//*[@resource-id='com.example.testapp:id/etName']"); nameElement.sendKeys("John"); //Set the password WebElement passwordElement = driver.findElement(By.xpath("//*[@resource-id='com.example.testapp:id/etPass']")); passwordElement.sendKeys("<PASSWORD>"); //Click on the Login button WebElement loginElement = driver.findElementByXPath("//*[@text='Login']"); loginElement.click(); //Text checkpoint on "Welcome back John" Map<String, Object> params = new HashMap<>(); params.put("content", "Welcome back John"); params.put("timeout", "20"); resultString = (String) driver.executeScript("mobile:checkpoint:text", params); if (!resultString.equalsIgnoreCase("true")) { System.out.println("Did not login successfully - 'Welcome back John' text not found"); throw new NoSuchFieldException(); } /* PART 2: * Navigate within application */ //Click on Continue button WebElement continueElement = driver.findElementByXPath("//android.widget.Button [@text='Continue']"); continueElement.click(); //Cick on First Screen button WebElement firstScreenElement = driver.findElementByXPath("//android.widget.Button[starts-with(@text,'First')]"); firstScreenElement.click(); //Radio button example for Android devices List<WebElement> radioButtons = driver.findElementsByXPath("//*[@checkable='true']"); for (WebElement radioButton:radioButtons){ radioButton.click(); } } catch (Exception e) { e.printStackTrace(); } finally { try { // Retrieve the URL of the Wind Tunnel Report, can be saved to your execution summary and used to download the report at a later point String reportURL = (String)(driver.getCapabilities().getCapability(WindTunnelUtils.WIND_TUNNEL_REPORT_URL_CAPABILITY)); driver.close(); // In case you want to download the report or the report attachments, do it here. // PerfectoLabUtils.downloadReport(driver, "pdf", "C:\\test\\report"); // PerfectoLabUtils.downloadAttachment(driver, "video", "C:\\test\\report\\video", "flv"); // PerfectoLabUtils.downloadAttachment(driver, "image", "C:\\test\\report\\images", "jpg"); } catch (Exception e) { e.printStackTrace(); } driver.quit(); } System.out.println("Run ended"); } // Recommended: // Remove the comment and use this method if you want the script to share the devices with the recording plugin.\ // Requires import com.perfectomobile.selenium.util.EclipseConnector; private static void setExecutionIdCapability(DesiredCapabilities capabilities) throws IOException { EclipseConnector connector = new EclipseConnector(); String executionId = connector.getExecutionId(); capabilities.setCapability(EclipseConnector.ECLIPSE_EXECUTION_ID, executionId); } }
6,252
0.663254
0.660694
155
38.341934
35.273941
150
false
false
0
0
0
0
0
0
1.651613
false
false
7
0d50d31f0c1e69520c4d6a0b8ae0831ed86b356b
6,760,278,576,212
b6b5e1d4325893b7fcddd14c9a2c1588eb0e0666
/src/com/amanda/sample/Application.java
e5f38f6d7224ff83170bd344ea76874cdbcde56a
[]
no_license
Pabodini/java-sa
https://github.com/Pabodini/java-sa
a1c264a57f4e6d1c026389e20ca2b89c1fa878c6
c28c0570bc21a23a1ddae785f2d3c246220282c1
refs/heads/master
2021-02-06T16:32:55.407000
2020-02-29T10:17:09
2020-02-29T10:17:09
243,931,785
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.amanda.sample; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Application { public static void main(String[] args) { /* List<String> students =new ArrayList<>(); students.add("Yanadhi"); students.add("Nuwan"); students.add("Dileepa"); students.add("Pari"); students.add("Thari"); System.out.println(students); List<String> filterdata=students.stream() .filter(s -> s.length()>5) .collect(Collectors.toList()); System.out.println(filterdata); */ List<Sensor> sensors = new ArrayList<>(); Sensor sensor1 =new Sensor("Bed room",28); sensors.add(sensor1); Sensor sensor2 =new Sensor("Living Room",35); sensors.add(sensor2); Sensor sensor3 =new Sensor("Kitchen",52); sensors.add(sensor3); Sensor sensor4 =new Sensor("Corridor",29); sensors.add(sensor4); Sensor sensor5 =new Sensor("Front Door",32); sensors.add(sensor5); List<Sensor> hotsensors= sensors.stream() .filter(sensor -> sensor.getValue()>32) .collect(Collectors.toList()); System.out.println(hotsensors); } }
UTF-8
Java
1,336
java
Application.java
Java
[ { "context": "tudents =new ArrayList<>();\n students.add(\"Yanadhi\");\n students.add(\"Nuwan\");\n student", "end": 269, "score": 0.999698281288147, "start": 262, "tag": "NAME", "value": "Yanadhi" }, { "context": " students.add(\"Yanadhi\");\n students.add(\"Nuwan\");\n students.add(\"Dileepa\");\n stude", "end": 300, "score": 0.9996768236160278, "start": 295, "tag": "NAME", "value": "Nuwan" }, { "context": " students.add(\"Nuwan\");\n students.add(\"Dileepa\");\n students.add(\"Pari\");\n students", "end": 333, "score": 0.9997004270553589, "start": 326, "tag": "NAME", "value": "Dileepa" }, { "context": " students.add(\"Dileepa\");\n students.add(\"Pari\");\n students.add(\"Thari\");\n System.", "end": 363, "score": 0.9996459484100342, "start": 359, "tag": "NAME", "value": "Pari" }, { "context": " students.add(\"Pari\");\n students.add(\"Thari\");\n System.out.println(students);\n\n ", "end": 394, "score": 0.9996259212493896, "start": 389, "tag": "NAME", "value": "Thari" } ]
null
[]
package com.amanda.sample; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Application { public static void main(String[] args) { /* List<String> students =new ArrayList<>(); students.add("Yanadhi"); students.add("Nuwan"); students.add("Dileepa"); students.add("Pari"); students.add("Thari"); System.out.println(students); List<String> filterdata=students.stream() .filter(s -> s.length()>5) .collect(Collectors.toList()); System.out.println(filterdata); */ List<Sensor> sensors = new ArrayList<>(); Sensor sensor1 =new Sensor("Bed room",28); sensors.add(sensor1); Sensor sensor2 =new Sensor("Living Room",35); sensors.add(sensor2); Sensor sensor3 =new Sensor("Kitchen",52); sensors.add(sensor3); Sensor sensor4 =new Sensor("Corridor",29); sensors.add(sensor4); Sensor sensor5 =new Sensor("Front Door",32); sensors.add(sensor5); List<Sensor> hotsensors= sensors.stream() .filter(sensor -> sensor.getValue()>32) .collect(Collectors.toList()); System.out.println(hotsensors); } }
1,336
0.572605
0.555389
56
22.803572
20.117884
55
false
false
0
0
0
0
0
0
0.553571
false
false
7
89d75112ca9e0f140176b0ca711be49e0f16fc6d
6,451,040,948,449
8aa6f279062b77c8848b84d35986b6f947733a64
/src/bl/tool/TeamHighSortTool.java
acc61993e7da7d2d632f08044cd7e85eefa406a2
[]
no_license
laimingjin/NBAInfo
https://github.com/laimingjin/NBAInfo
3ab66155ce67bbc4657aa7e0c727332ee4dd7efd
e966663b78465e5e61df70a6f547d43f9146d1fa
refs/heads/master
2021-04-29T01:37:55.977000
2016-12-31T17:04:27
2016-12-31T17:04:27
77,748,612
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bl.tool; import java.util.Comparator; import vo.TeamHighVO; import enumerate.TypeOfSort; import enumerate.TypeOfSort4TeamsHigh; /** *@author:小春 *@date:2015年6月5日下午9:07:08 *@version */ public class TeamHighSortTool implements Comparator<TeamHighVO>{ TypeOfSort typeOfSort; TypeOfSort4TeamsHigh typeOfSort4TeamHigh; public TeamHighSortTool(TypeOfSort typeOfSort, TypeOfSort4TeamsHigh typeOfSort4PlayerHigh){ this.typeOfSort=typeOfSort; this.typeOfSort4TeamHigh=typeOfSort4PlayerHigh; } public int compare(TeamHighVO o1, TeamHighVO o2) { double num_first = o1.getNum(typeOfSort4TeamHigh); double num_second = o2.getNum(typeOfSort4TeamHigh); switch (typeOfSort) { case ASCENDING_ORDER_TOTAL:// 升序总数据 case ASCENDING_ORDER_AVERAGE: if (num_first > num_second) { return 1; } else if (num_first < num_second) { return -1; } return 0; case DESCENDING_ORDER_TOTAL:// 降序总数据 case DESCENDING_ORDER_AVERAGE: if (num_first < num_second) { return 1; } else if (num_first > num_second) { return -1; } return 0; default: return 0; } } }
UTF-8
Java
1,191
java
TeamHighSortTool.java
Java
[ { "context": "enumerate.TypeOfSort4TeamsHigh;\r\n\r\n/**\r\n *@author:小春\r\n *@date:2015年6月5日下午9:07:08\r\n *@version\r\n */\r\n\r\np", "end": 164, "score": 0.7684231400489807, "start": 162, "tag": "USERNAME", "value": "小春" } ]
null
[]
package bl.tool; import java.util.Comparator; import vo.TeamHighVO; import enumerate.TypeOfSort; import enumerate.TypeOfSort4TeamsHigh; /** *@author:小春 *@date:2015年6月5日下午9:07:08 *@version */ public class TeamHighSortTool implements Comparator<TeamHighVO>{ TypeOfSort typeOfSort; TypeOfSort4TeamsHigh typeOfSort4TeamHigh; public TeamHighSortTool(TypeOfSort typeOfSort, TypeOfSort4TeamsHigh typeOfSort4PlayerHigh){ this.typeOfSort=typeOfSort; this.typeOfSort4TeamHigh=typeOfSort4PlayerHigh; } public int compare(TeamHighVO o1, TeamHighVO o2) { double num_first = o1.getNum(typeOfSort4TeamHigh); double num_second = o2.getNum(typeOfSort4TeamHigh); switch (typeOfSort) { case ASCENDING_ORDER_TOTAL:// 升序总数据 case ASCENDING_ORDER_AVERAGE: if (num_first > num_second) { return 1; } else if (num_first < num_second) { return -1; } return 0; case DESCENDING_ORDER_TOTAL:// 降序总数据 case DESCENDING_ORDER_AVERAGE: if (num_first < num_second) { return 1; } else if (num_first > num_second) { return -1; } return 0; default: return 0; } } }
1,191
0.694901
0.668107
48
22.104166
17.728554
64
false
false
0
0
0
0
0
0
1.958333
false
false
7
ef785f30c9df1f881378bdc24337f8dadb3821c3
18,829,136,659,291
f69d8ff96b1c53e13ac0acff87570c1d2bd0b316
/web/src/main/java/sensecloud/web/bean/AbRole.java
7b0bcf26d666148ebeed1a8de3eb45b9fc2319e7
[]
no_license
PerfectZQ/sensecloud-analysis
https://github.com/PerfectZQ/sensecloud-analysis
2578ecef9777d23fd7728182702acf51004ffe38
bdb323abc65bea1851a1a1702ed2394503ed22dc
refs/heads/master
2023-07-07T17:58:56.503000
2021-02-02T07:25:08
2021-02-02T07:25:08
394,546,296
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package sensecloud.web.bean; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.KeySequence; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * <p> * * </p> * * @author ZhangQiang * @since 2020-10-13 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("ab_role") @KeySequence("ab_role_id_seq") @ApiModel(value="AbRole对象", description="") public class AbRole implements Serializable { private static final long serialVersionUID = 1L; @TableId(type = IdType.INPUT) private Integer id; private String name; }
UTF-8
Java
836
java
AbRole.java
Java
[ { "context": "erializable;\n\n/**\n * <p>\n * \n * </p>\n *\n * @author ZhangQiang\n * @since 2020-10-13\n */\n@Data\n@EqualsAndHashCode", "end": 452, "score": 0.9997958540916443, "start": 442, "tag": "NAME", "value": "ZhangQiang" } ]
null
[]
package sensecloud.web.bean; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.KeySequence; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; /** * <p> * * </p> * * @author ZhangQiang * @since 2020-10-13 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("ab_role") @KeySequence("ab_role_id_seq") @ApiModel(value="AbRole对象", description="") public class AbRole implements Serializable { private static final long serialVersionUID = 1L; @TableId(type = IdType.INPUT) private Integer id; private String name; }
836
0.759615
0.748798
37
21.486486
18.55397
55
false
false
0
0
0
0
0
0
0.378378
false
false
7
38a77b7b972e3c574d29642bcd11b8ba5434c845
3,401,614,160,093
1c93f72465de8582e10cedcedfb91c064ad09e54
/shared/src/main/java/com/simplechat/shared/CommonUtils.java
52439fab89548c89a82c32679c2c1a3f625c73ee
[ "MIT" ]
permissive
HristoTodorov/simple-chat
https://github.com/HristoTodorov/simple-chat
87652249ebdb78255ff32d79c83935a2b4d194b6
c0b9bb726189e9edaede66ef0c3dc25c0727af90
refs/heads/master
2020-03-29T03:00:16.443000
2017-06-26T04:30:32
2017-06-26T04:30:32
94,647,716
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.simplechat.shared; /** * Created by lampt on 6/24/2017. */ public class CommonUtils { public static final String USER_HOME_DIR = System.getProperty("user.home"); public static final String LINE_SEPARATOR = System.getProperty("line.separator"); }
UTF-8
Java
269
java
CommonUtils.java
Java
[ { "context": "package com.simplechat.shared;\n\n/**\n * Created by lampt on 6/24/2017.\n */\npublic class CommonUtils {\n ", "end": 55, "score": 0.9996389746665955, "start": 50, "tag": "USERNAME", "value": "lampt" } ]
null
[]
package com.simplechat.shared; /** * Created by lampt on 6/24/2017. */ public class CommonUtils { public static final String USER_HOME_DIR = System.getProperty("user.home"); public static final String LINE_SEPARATOR = System.getProperty("line.separator"); }
269
0.728625
0.702602
9
28.888889
30.981874
85
false
false
0
0
0
0
0
0
0.333333
false
false
7
2919c0741219386deda6852bf22df7aab7f08db6
11,888,469,477,656
c0e3b006d5f99280d3cb45a2d0a3b08c01bbfe1e
/src/main/java/io/github/ratysz/arsarcanum/gui/GuiSpellscribeSlot.java
65e457da1adf0992f151fd1143e262c2fcea6f6f
[]
no_license
Ratysz/ArsArcanum
https://github.com/Ratysz/ArsArcanum
72585ebfa0ef636f918dc933a4f681dfd9a57ae6
28ce7c8fb0f408f57920e3eff9e757882e53cd34
refs/heads/master
2016-05-15T15:08:24.562000
2016-04-05T19:25:43
2016-04-05T19:25:43
52,104,914
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.github.ratysz.arsarcanum.gui; import io.github.ratysz.arsarcanum.handler.LogHandler; import io.github.ratysz.arsarcanum.inventory.SpellscribeSlot; import io.github.ratysz.arsarcanum.spell.WNode; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.HashSet; @SideOnly(Side.CLIENT) public class GuiSpellscribeSlot extends GuiElement { private static final LogHandler LOGGER = new LogHandler(GuiSpellscribeSlot.class); private SpellscribeSlot spellscribeSlot; private GuiWNode rootWNode; private HashSet<GuiWNode> childWNodes; public GuiSpellscribeSlot(SpellscribeSlot spellscribeSlot) { super(spellscribeSlot.getXPos(), spellscribeSlot.getYPos(), spellscribeSlot.getWidth() * 8, spellscribeSlot.getHeight() * 8, 0, 0); this.spellscribeSlot = spellscribeSlot; this.rootWNode = new GuiWNode(0, 0, 0, 0, 0, 0); this.rootWNode .setWNode(this.spellscribeSlot.getSpell().getSpellTree()) .setParent(this); this.childWNodes = new HashSet<>(); } @Override public GuiElement onDraw(int mouseX, int mouseY, float partialTicks) { this.childWNodes = new HashSet<>(); recursiveGatherWNodes(rootWNode); for (GuiWNode guiWNode : childWNodes) { guiWNode.onDraw(mouseX, mouseY, partialTicks); } return super.onDraw(mouseX, mouseY, partialTicks); } private void recursiveGatherWNodes(GuiWNode guiWNode) { for (WNode childWNode : guiWNode.getWNode().getChildren()) { GuiWNode childGuiWNode = new GuiWNode(0, 0, 0, 0, 0, 0); childGuiWNode .setWNode(childWNode) .setParent(guiWNode) .setAbsX(8 * childGuiWNode.getWNode().getXPos() + this.getAbsX()) .setAbsY(8 * childGuiWNode.getWNode().getYPos() + this.getAbsY()) .setZLevel(getZLevel() + 1); childWNodes.add(childGuiWNode); recursiveGatherWNodes(childGuiWNode); } } @Override public GuiElement onHover(int mouseX, int mouseY) { if (isActive() && isParentActive() && isInBounds(mouseX, mouseY) && !isDragged()) { for (GuiWNode guiWNode : childWNodes) { GuiElement hoveredNode = guiWNode.onHover(mouseX, mouseY); if (hoveredNode != null) { return hoveredNode; } } if (onHoverAction != null) { onHoverAction.action(mouseX, mouseY); } return this; } return null; } /* public boolean canAttachWord(int mouseX, int mouseY, GuiWNode guiWord) { final int slotX = (int) (((mouseX - getAbsX()) / 8.0f) - (((mouseX - getAbsX()) / 8.0f) % 1)); final int slotY = (int) (((mouseY - getAbsY()) / 8.0f) - (((mouseY - getAbsY()) / 8.0f) % 1)); return spellscribeSlot.getSpell().canAttachWord(slotX, slotY, guiWord.getWord()) != null; } */ public void attachWord(int mouseX, int mouseY, GuiWord guiWord, GuiWNode parentWNode) { GuiWNode guiWNode = parentWNode; if (guiWNode == null) { LOGGER.debug("attachWord called with null parentWNode."); guiWNode = this.rootWNode; } final int slotX = (int) (((mouseX - getAbsX()) / 8.0f) - (((mouseX - getAbsX()) / 8.0f) % 1)); final int slotY = (int) (((mouseY - getAbsY()) / 8.0f) - (((mouseY - getAbsY()) / 8.0f) % 1)); LOGGER.debug("attachWord called with mouseX = " + mouseX + ", mouseY = " + mouseY + ", word " + guiWord.getWord().getID() + ". slotX = " + slotX + ", slotY = " + slotY); spellscribeSlot.getSpell().compile(); spellscribeSlot.getSpell().attachWord(slotX, slotY, guiWord.isRotated(), guiWord.getWord(), guiWNode.getWNode()); } }
UTF-8
Java
3,552
java
GuiSpellscribeSlot.java
Java
[ { "context": "package io.github.ratysz.arsarcanum.gui;\n\nimport io.github.ratysz.arsarcan", "end": 24, "score": 0.9963449835777283, "start": 18, "tag": "USERNAME", "value": "ratysz" }, { "context": "o.github.ratysz.arsarcanum.gui;\n\nimport io.github.ratysz.arsarcanum.handler.LogHandler;\nimport io.github.r", "end": 65, "score": 0.9970130324363708, "start": 59, "tag": "USERNAME", "value": "ratysz" }, { "context": "z.arsarcanum.handler.LogHandler;\nimport io.github.ratysz.arsarcanum.inventory.SpellscribeSlot;\nimport io.g", "end": 120, "score": 0.9944937229156494, "start": 114, "tag": "USERNAME", "value": "ratysz" }, { "context": "canum.inventory.SpellscribeSlot;\nimport io.github.ratysz.arsarcanum.spell.WNode;\nimport net.minecraftforge", "end": 182, "score": 0.9899576306343079, "start": 176, "tag": "USERNAME", "value": "ratysz" } ]
null
[]
package io.github.ratysz.arsarcanum.gui; import io.github.ratysz.arsarcanum.handler.LogHandler; import io.github.ratysz.arsarcanum.inventory.SpellscribeSlot; import io.github.ratysz.arsarcanum.spell.WNode; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.HashSet; @SideOnly(Side.CLIENT) public class GuiSpellscribeSlot extends GuiElement { private static final LogHandler LOGGER = new LogHandler(GuiSpellscribeSlot.class); private SpellscribeSlot spellscribeSlot; private GuiWNode rootWNode; private HashSet<GuiWNode> childWNodes; public GuiSpellscribeSlot(SpellscribeSlot spellscribeSlot) { super(spellscribeSlot.getXPos(), spellscribeSlot.getYPos(), spellscribeSlot.getWidth() * 8, spellscribeSlot.getHeight() * 8, 0, 0); this.spellscribeSlot = spellscribeSlot; this.rootWNode = new GuiWNode(0, 0, 0, 0, 0, 0); this.rootWNode .setWNode(this.spellscribeSlot.getSpell().getSpellTree()) .setParent(this); this.childWNodes = new HashSet<>(); } @Override public GuiElement onDraw(int mouseX, int mouseY, float partialTicks) { this.childWNodes = new HashSet<>(); recursiveGatherWNodes(rootWNode); for (GuiWNode guiWNode : childWNodes) { guiWNode.onDraw(mouseX, mouseY, partialTicks); } return super.onDraw(mouseX, mouseY, partialTicks); } private void recursiveGatherWNodes(GuiWNode guiWNode) { for (WNode childWNode : guiWNode.getWNode().getChildren()) { GuiWNode childGuiWNode = new GuiWNode(0, 0, 0, 0, 0, 0); childGuiWNode .setWNode(childWNode) .setParent(guiWNode) .setAbsX(8 * childGuiWNode.getWNode().getXPos() + this.getAbsX()) .setAbsY(8 * childGuiWNode.getWNode().getYPos() + this.getAbsY()) .setZLevel(getZLevel() + 1); childWNodes.add(childGuiWNode); recursiveGatherWNodes(childGuiWNode); } } @Override public GuiElement onHover(int mouseX, int mouseY) { if (isActive() && isParentActive() && isInBounds(mouseX, mouseY) && !isDragged()) { for (GuiWNode guiWNode : childWNodes) { GuiElement hoveredNode = guiWNode.onHover(mouseX, mouseY); if (hoveredNode != null) { return hoveredNode; } } if (onHoverAction != null) { onHoverAction.action(mouseX, mouseY); } return this; } return null; } /* public boolean canAttachWord(int mouseX, int mouseY, GuiWNode guiWord) { final int slotX = (int) (((mouseX - getAbsX()) / 8.0f) - (((mouseX - getAbsX()) / 8.0f) % 1)); final int slotY = (int) (((mouseY - getAbsY()) / 8.0f) - (((mouseY - getAbsY()) / 8.0f) % 1)); return spellscribeSlot.getSpell().canAttachWord(slotX, slotY, guiWord.getWord()) != null; } */ public void attachWord(int mouseX, int mouseY, GuiWord guiWord, GuiWNode parentWNode) { GuiWNode guiWNode = parentWNode; if (guiWNode == null) { LOGGER.debug("attachWord called with null parentWNode."); guiWNode = this.rootWNode; } final int slotX = (int) (((mouseX - getAbsX()) / 8.0f) - (((mouseX - getAbsX()) / 8.0f) % 1)); final int slotY = (int) (((mouseY - getAbsY()) / 8.0f) - (((mouseY - getAbsY()) / 8.0f) % 1)); LOGGER.debug("attachWord called with mouseX = " + mouseX + ", mouseY = " + mouseY + ", word " + guiWord.getWord().getID() + ". slotX = " + slotX + ", slotY = " + slotY); spellscribeSlot.getSpell().compile(); spellscribeSlot.getSpell().attachWord(slotX, slotY, guiWord.isRotated(), guiWord.getWord(), guiWNode.getWNode()); } }
3,552
0.679336
0.668356
119
28.84874
26.196619
91
false
false
0
0
0
0
0
0
2.789916
false
false
7
16340e9e43256e454eabc2888eaa2f8aeeb2e014
7,739,531,104,782
f538b56104c45e04f70ef3473a971d4a67e1b089
/java/netxms-eclipse/ImageLibrary/src/org/netxms/ui/eclipse/imagelibrary/widgets/ImageSelector.java
55df0ab8763e2732d9c90df8f54f42c0496238fd
[]
no_license
phongtran0715/SpiderClient
https://github.com/phongtran0715/SpiderClient
85d5d0559c6af0393cd058c25584074d80f8df9a
fdc264a85b7ff52c5dc2b6bb3cc83da62aad2aff
refs/heads/master
2020-03-20T20:07:12.075000
2018-08-10T08:37:10
2018-08-10T08:37:10
137,671,006
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * NetXMS - open source network management system * Copyright (C) 2003-2013 Victor Kirhenshtein * * 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 2 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.netxms.ui.eclipse.imagelibrary.widgets; import java.util.UUID; import org.eclipse.jface.window.Window; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Composite; import org.netxms.base.NXCommon; import org.netxms.client.LibraryImage; import org.netxms.ui.eclipse.imagelibrary.Messages; import org.netxms.ui.eclipse.imagelibrary.dialogs.ImageSelectionDialog; import org.netxms.ui.eclipse.imagelibrary.shared.ImageProvider; import org.netxms.ui.eclipse.imagelibrary.shared.ImageUpdateListener; import org.netxms.ui.eclipse.widgets.AbstractSelector; /** * Image selector */ public class ImageSelector extends AbstractSelector implements ImageUpdateListener { private UUID imageGuid = NXCommon.EMPTY_GUID; /** * @param parent * @param style */ public ImageSelector(Composite parent, int style) { super(parent, style, SHOW_CLEAR_BUTTON); ImageProvider.getInstance().addUpdateListener(this); addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { ImageProvider.getInstance().removeUpdateListener( ImageSelector.this); } }); } /* * (non-Javadoc) * * @see * org.netxms.ui.eclipse.widgets.AbstractSelector#selectionButtonHandler() */ @Override protected void selectionButtonHandler() { ImageSelectionDialog dlg = new ImageSelectionDialog(getShell()); if (dlg.open() == Window.OK) { LibraryImage image = dlg.getLibraryImage(); if (image != null) { setText(image.getName()); setImage(dlg.getImage()); imageGuid = dlg.getGuid(); } else { setText(Messages.get().ImageSelector_Default); setImage(null); imageGuid = NXCommon.EMPTY_GUID; } getParent().layout(); } } /* * (non-Javadoc) * * @see org.netxms.ui.eclipse.widgets.AbstractSelector#clearButtonHandler() */ @Override protected void clearButtonHandler() { setText(Messages.get().ImageSelector_Default); setImage(null); imageGuid = NXCommon.EMPTY_GUID; getParent().layout(); } /* * (non-Javadoc) * * @see * org.netxms.ui.eclipse.widgets.AbstractSelector#getSelectionButtonToolTip * () */ @Override protected String getSelectionButtonToolTip() { return Messages.get().ImageSelector_SelectImage; } /** * @return the imageGuid */ public UUID getImageGuid() { return imageGuid; } /** * Set image GUID * * @param imageGuid * image GUID * @param redoLayout * if set to true, control will update it's layout */ public void setImageGuid(UUID imageGuid, boolean redoLayout) { this.imageGuid = imageGuid; if (imageGuid.equals(NXCommon.EMPTY_GUID)) { setText(Messages.get().ImageSelector_Default); setImage(null); } else { LibraryImage image = ImageProvider.getInstance() .getLibraryImageObject(imageGuid); if (image != null) { setText(image.getName()); setImage(ImageProvider.getInstance().getImage(imageGuid)); } else { setText("<?>" + imageGuid.toString()); //$NON-NLS-1$ setImage(null); } } if (redoLayout) getParent().layout(); } /* * (non-Javadoc) * * @see * org.netxms.ui.eclipse.imagelibrary.shared.ImageUpdateListener#imageUpdated * (java.util.UUID) */ @Override public void imageUpdated(UUID guid) { if (guid.equals(imageGuid)) { getDisplay().asyncExec(new Runnable() { @Override public void run() { setImage(ImageProvider.getInstance().getImage(imageGuid)); getParent().layout(); } }); } } }
UTF-8
Java
4,368
java
ImageSelector.java
Java
[ { "context": "twork management system\n * Copyright (C) 2003-2013 Victor Kirhenshtein\n *\n * This program is free software; you can redi", "end": 100, "score": 0.9998607635498047, "start": 81, "tag": "NAME", "value": "Victor Kirhenshtein" } ]
null
[]
/** * NetXMS - open source network management system * Copyright (C) 2003-2013 <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 2 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.netxms.ui.eclipse.imagelibrary.widgets; import java.util.UUID; import org.eclipse.jface.window.Window; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Composite; import org.netxms.base.NXCommon; import org.netxms.client.LibraryImage; import org.netxms.ui.eclipse.imagelibrary.Messages; import org.netxms.ui.eclipse.imagelibrary.dialogs.ImageSelectionDialog; import org.netxms.ui.eclipse.imagelibrary.shared.ImageProvider; import org.netxms.ui.eclipse.imagelibrary.shared.ImageUpdateListener; import org.netxms.ui.eclipse.widgets.AbstractSelector; /** * Image selector */ public class ImageSelector extends AbstractSelector implements ImageUpdateListener { private UUID imageGuid = NXCommon.EMPTY_GUID; /** * @param parent * @param style */ public ImageSelector(Composite parent, int style) { super(parent, style, SHOW_CLEAR_BUTTON); ImageProvider.getInstance().addUpdateListener(this); addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { ImageProvider.getInstance().removeUpdateListener( ImageSelector.this); } }); } /* * (non-Javadoc) * * @see * org.netxms.ui.eclipse.widgets.AbstractSelector#selectionButtonHandler() */ @Override protected void selectionButtonHandler() { ImageSelectionDialog dlg = new ImageSelectionDialog(getShell()); if (dlg.open() == Window.OK) { LibraryImage image = dlg.getLibraryImage(); if (image != null) { setText(image.getName()); setImage(dlg.getImage()); imageGuid = dlg.getGuid(); } else { setText(Messages.get().ImageSelector_Default); setImage(null); imageGuid = NXCommon.EMPTY_GUID; } getParent().layout(); } } /* * (non-Javadoc) * * @see org.netxms.ui.eclipse.widgets.AbstractSelector#clearButtonHandler() */ @Override protected void clearButtonHandler() { setText(Messages.get().ImageSelector_Default); setImage(null); imageGuid = NXCommon.EMPTY_GUID; getParent().layout(); } /* * (non-Javadoc) * * @see * org.netxms.ui.eclipse.widgets.AbstractSelector#getSelectionButtonToolTip * () */ @Override protected String getSelectionButtonToolTip() { return Messages.get().ImageSelector_SelectImage; } /** * @return the imageGuid */ public UUID getImageGuid() { return imageGuid; } /** * Set image GUID * * @param imageGuid * image GUID * @param redoLayout * if set to true, control will update it's layout */ public void setImageGuid(UUID imageGuid, boolean redoLayout) { this.imageGuid = imageGuid; if (imageGuid.equals(NXCommon.EMPTY_GUID)) { setText(Messages.get().ImageSelector_Default); setImage(null); } else { LibraryImage image = ImageProvider.getInstance() .getLibraryImageObject(imageGuid); if (image != null) { setText(image.getName()); setImage(ImageProvider.getInstance().getImage(imageGuid)); } else { setText("<?>" + imageGuid.toString()); //$NON-NLS-1$ setImage(null); } } if (redoLayout) getParent().layout(); } /* * (non-Javadoc) * * @see * org.netxms.ui.eclipse.imagelibrary.shared.ImageUpdateListener#imageUpdated * (java.util.UUID) */ @Override public void imageUpdated(UUID guid) { if (guid.equals(imageGuid)) { getDisplay().asyncExec(new Runnable() { @Override public void run() { setImage(ImageProvider.getInstance().getImage(imageGuid)); getParent().layout(); } }); } } }
4,355
0.70902
0.704899
162
25.962963
23.183084
78
false
false
0
0
0
0
0
0
1.796296
false
false
7
a27c3ece526d07681619935e1841115d493959a5
12,275,016,582,324
3294934df505acb637cffc478da38341675bab71
/algorithm/src/main/java/com/nano/datastructure/刷题/剑指Offer/Q59滑动窗口的最大值.java
85128feef794420514b5babb10f0beb1b1381747
[ "Apache-2.0" ]
permissive
nanodaemony/JavaNotesCode
https://github.com/nanodaemony/JavaNotesCode
6883ec21ebec764e77c1a8c8ddf1a6237eed8f17
39232ad3f7c0de5aa2aca69521049c0580b312a6
refs/heads/master
2022-06-21T16:11:12.172000
2020-09-13T08:59:22
2020-09-13T08:59:22
245,740,674
0
0
Apache-2.0
false
2022-06-17T02:56:30
2020-03-08T02:43:28
2020-09-13T08:59:55
2022-06-17T02:56:30
558
0
0
4
Java
false
false
package com.nano.datastructure.刷题.剑指Offer; import java.util.ArrayList; import java.util.LinkedList; import java.util.PriorityQueue; /** * @author: nano * @time: 2020/7/4 13:58 */ public class Q59滑动窗口的最大值 { /** * 基于堆实现 */ public int[] maxSlidingWindow(int[] nums, int k) { if(nums == null || nums.length == 0 || k < 1) { return new int[]{}; } ArrayList<Integer> resList = new ArrayList<>(); // 大顶堆 PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1); // 先将K个元素加入堆中 for (int i = 0; i < k; i++) heap.add(nums[i]); // 此时第一个元素就是当前最大值 resList.add(heap.peek()); // 维护一个大小为size的大顶堆 for (int i = 0, j = i + k; j < nums.length; i++, j++) { // 不断取出窗口的左边界并加入右边界 heap.remove(nums[i]); heap.add(nums[j]); // 每次滑动一个都得到一个值 resList.add(heap.peek()); } // 列表转为数组 int[] res = new int[resList.size()]; for (int i = 0; i < res.length; i++) { res[i] = resList.get(i); } return res; } /** * 基于单调队列实现 */ public int[] maxSlidingWindow2(int[] nums, int k) { // Base case if (nums == null || k < 1 || nums.length < k) { return new int[0]; } int index = 0; // 构造一个结果数组 int[] res = new int[nums.length - k + 1]; // 单调队列 LinkedList<Integer> queue = new LinkedList<>(); for (int i = 0; i < nums.length; i++) { // 在队列不为空的情况下,如果队列尾部的元素要比当前的元素小,或等于当前的元素 // 那么为了维持从大到小的原则,必须让尾部元素弹出 while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) { queue.pollLast(); } // 不走while的话,说明正常在队列尾部添加元素 queue.addLast(i); // 如果滑动窗口已经略过了队列中头部的元素,则将头部元素弹出 if (queue.peekFirst() == (i - k)) { queue.pollFirst(); } // 看看窗口有没有形成,只有形成了大小为k的窗口才能收集窗口内的最大值 if (i >= (k - 1)) { res[index++] = nums[queue.peekFirst()]; } } return res; } }
UTF-8
Java
2,255
java
Q59滑动窗口的最大值.java
Java
[ { "context": ";\nimport java.util.PriorityQueue;\n\n/**\n * @author: nano\n * @time: 2020/7/4 13:58\n */\npublic class Q59滑动窗口", "end": 154, "score": 0.9994207620620728, "start": 150, "tag": "USERNAME", "value": "nano" } ]
null
[]
package com.nano.datastructure.刷题.剑指Offer; import java.util.ArrayList; import java.util.LinkedList; import java.util.PriorityQueue; /** * @author: nano * @time: 2020/7/4 13:58 */ public class Q59滑动窗口的最大值 { /** * 基于堆实现 */ public int[] maxSlidingWindow(int[] nums, int k) { if(nums == null || nums.length == 0 || k < 1) { return new int[]{}; } ArrayList<Integer> resList = new ArrayList<>(); // 大顶堆 PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1); // 先将K个元素加入堆中 for (int i = 0; i < k; i++) heap.add(nums[i]); // 此时第一个元素就是当前最大值 resList.add(heap.peek()); // 维护一个大小为size的大顶堆 for (int i = 0, j = i + k; j < nums.length; i++, j++) { // 不断取出窗口的左边界并加入右边界 heap.remove(nums[i]); heap.add(nums[j]); // 每次滑动一个都得到一个值 resList.add(heap.peek()); } // 列表转为数组 int[] res = new int[resList.size()]; for (int i = 0; i < res.length; i++) { res[i] = resList.get(i); } return res; } /** * 基于单调队列实现 */ public int[] maxSlidingWindow2(int[] nums, int k) { // Base case if (nums == null || k < 1 || nums.length < k) { return new int[0]; } int index = 0; // 构造一个结果数组 int[] res = new int[nums.length - k + 1]; // 单调队列 LinkedList<Integer> queue = new LinkedList<>(); for (int i = 0; i < nums.length; i++) { // 在队列不为空的情况下,如果队列尾部的元素要比当前的元素小,或等于当前的元素 // 那么为了维持从大到小的原则,必须让尾部元素弹出 while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]) { queue.pollLast(); } // 不走while的话,说明正常在队列尾部添加元素 queue.addLast(i); // 如果滑动窗口已经略过了队列中头部的元素,则将头部元素弹出 if (queue.peekFirst() == (i - k)) { queue.pollFirst(); } // 看看窗口有没有形成,只有形成了大小为k的窗口才能收集窗口内的最大值 if (i >= (k - 1)) { res[index++] = nums[queue.peekFirst()]; } } return res; } }
2,255
0.584799
0.568917
83
20.240963
17.873444
73
false
false
0
0
0
0
0
0
2.240964
false
false
7
b5e53383021710d10985a31d3fab161cfeda1466
9,835,475,129,871
89be2c3626be5c0ea0f827640e350b1337ad0b28
/app/src/main/java/com/example/administrator/calendartest/MainActivity.java
ff4fb72f2382fbb2c7d4f2a376e0e57e6eeb9792
[]
no_license
Ct7Liang/CalendarTest
https://github.com/Ct7Liang/CalendarTest
dacd8f759ef12b16edb41d4b5cbf5f7fcbe03daf
b6bf11815e76a0ca198f38ca9db7d49c55a0c708
refs/heads/master
2020-05-29T21:40:15.737000
2019-05-30T09:47:03
2019-05-30T09:47:03
189,388,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.administrator.calendartest; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.haibin.calendarview.Calendar; import com.haibin.calendarview.CalendarView; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private CalendarView calendarView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); calendarView = (CalendarView) findViewById(R.id.calendarView); calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() { @Override public void onMonthChange(int year, int month) { Toast.makeText(MainActivity.this, "year="+year+", month="+month , Toast.LENGTH_SHORT).show(); } }); int year = calendarView.getCurYear(); int month = calendarView.getCurMonth(); Map<String, Calendar> map = new HashMap<>(); map.put(getSchemeCalendar(year, month+1, 1, 0xFF40db25, "就").toString(), getSchemeCalendar(year, month+1, 1, 0xFF40db25, "就")); map.put(getSchemeCalendar(year, month, 3, 0xFF40db25, "假").toString(), getSchemeCalendar(year, month, 3, 0xFF40db25, "假")); map.put(getSchemeCalendar(year, month, 6, 0xFFe69138, "事").toString(), getSchemeCalendar(year, month, 6, 0xFFe69138, "事")); map.put(getSchemeCalendar(year, month, 9, 0xFFdf1356, "议").toString(), getSchemeCalendar(year, month, 9, 0xFFdf1356, "议")); map.put(getSchemeCalendar(year, month, 13, 0xFFedc56d, "记").toString(), getSchemeCalendar(year, month, 13, 0xFFedc56d, "记")); map.put(getSchemeCalendar(year, month, 27, 0xFF13acf0, "多").toString(), getSchemeCalendar(year, month, 27, 0xFF13acf0, "多")); map.put(getSchemeCalendar(year, month, 30, 0xFF13acf0, "例").toString(), getSchemeCalendar(year, month, 30, 0xFF13acf0, "例")); //此方法在巨大的数据量上不影响遍历性能,推荐使用 calendarView.setSchemeDate(map); } private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) { Calendar calendar = new Calendar(); calendar.setYear(year); calendar.setMonth(month); calendar.setDay(day); calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色 calendar.setScheme(text); calendar.addScheme(new Calendar.Scheme()); calendar.addScheme(0xFF008800, "假"); calendar.addScheme(0xFF008800, "节"); return calendar; } }
UTF-8
Java
2,874
java
MainActivity.java
Java
[]
null
[]
package com.example.administrator.calendartest; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.haibin.calendarview.Calendar; import com.haibin.calendarview.CalendarView; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private CalendarView calendarView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); calendarView = (CalendarView) findViewById(R.id.calendarView); calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() { @Override public void onMonthChange(int year, int month) { Toast.makeText(MainActivity.this, "year="+year+", month="+month , Toast.LENGTH_SHORT).show(); } }); int year = calendarView.getCurYear(); int month = calendarView.getCurMonth(); Map<String, Calendar> map = new HashMap<>(); map.put(getSchemeCalendar(year, month+1, 1, 0xFF40db25, "就").toString(), getSchemeCalendar(year, month+1, 1, 0xFF40db25, "就")); map.put(getSchemeCalendar(year, month, 3, 0xFF40db25, "假").toString(), getSchemeCalendar(year, month, 3, 0xFF40db25, "假")); map.put(getSchemeCalendar(year, month, 6, 0xFFe69138, "事").toString(), getSchemeCalendar(year, month, 6, 0xFFe69138, "事")); map.put(getSchemeCalendar(year, month, 9, 0xFFdf1356, "议").toString(), getSchemeCalendar(year, month, 9, 0xFFdf1356, "议")); map.put(getSchemeCalendar(year, month, 13, 0xFFedc56d, "记").toString(), getSchemeCalendar(year, month, 13, 0xFFedc56d, "记")); map.put(getSchemeCalendar(year, month, 27, 0xFF13acf0, "多").toString(), getSchemeCalendar(year, month, 27, 0xFF13acf0, "多")); map.put(getSchemeCalendar(year, month, 30, 0xFF13acf0, "例").toString(), getSchemeCalendar(year, month, 30, 0xFF13acf0, "例")); //此方法在巨大的数据量上不影响遍历性能,推荐使用 calendarView.setSchemeDate(map); } private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) { Calendar calendar = new Calendar(); calendar.setYear(year); calendar.setMonth(month); calendar.setDay(day); calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色 calendar.setScheme(text); calendar.addScheme(new Calendar.Scheme()); calendar.addScheme(0xFF008800, "假"); calendar.addScheme(0xFF008800, "节"); return calendar; } }
2,874
0.658581
0.622013
65
41.49231
28.189535
109
false
false
0
0
0
0
0
0
1.707692
false
false
7
1a19f40d7866a9a119f71cb3a8345c814c5efc9c
29,454,885,717,624
ee87e2296c83d2faae545a3442f7545e069ac32c
/JARVIS-Android/mobile/src/main/java/com/bugertindustries/coolbots7/jarvis/NotedbHelper.java
ee8718b6caacbd406f74d873ce0659e81cfdcb08
[]
no_license
Coolbots7/JARVIS
https://github.com/Coolbots7/JARVIS
fc9d4345d4bff6147c7672dbda0c17ce43d0e434
def963f1b90982584618b12b4009c07e90d95d68
refs/heads/master
2019-01-22T10:43:48.575000
2017-09-10T04:36:02
2017-09-10T04:36:02
85,647,724
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bugertindustries.coolbots7.jarvis; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by coolbots7 on 2017-03-26. */ public class NotedbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "notes.db"; public NotedbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(NoteContract.SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(NoteContract.SQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
UTF-8
Java
892
java
NotedbHelper.java
Java
[ { "context": "tabase.sqlite.SQLiteOpenHelper;\n\n/**\n * Created by coolbots7 on 2017-03-26.\n */\n\npublic class NotedbHelper ext", "end": 204, "score": 0.9995066523551941, "start": 195, "tag": "USERNAME", "value": "coolbots7" } ]
null
[]
package com.bugertindustries.coolbots7.jarvis; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by coolbots7 on 2017-03-26. */ public class NotedbHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "notes.db"; public NotedbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { db.execSQL(NoteContract.SQL_CREATE_ENTRIES); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(NoteContract.SQL_DELETE_ENTRIES); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
892
0.730942
0.71861
29
29.758621
28.826059
99
false
false
0
0
0
0
0
0
0.689655
false
false
7
c4246246aee8470d78f1bc02d53fd923f3b700dc
20,340,965,179,693
52e51542223cc25051f9379a701c0b449a6e3515
/spring-boot-v1-pocs/spring-boot-form-login-security-base64-encoder-poc/src/main/java/com/jedivision/controller/IndexController.java
69b8fb823bcabbac74b033eb8a1a74e6f9ce8489
[]
no_license
tech1-io/tech1-temple-java
https://github.com/tech1-io/tech1-temple-java
4ac7d3e390622eba231ea0f8c51b1a5c6486a0c6
b7da4e746a01fc870ae94f43932cb9f57b93ae37
refs/heads/master
2022-12-30T18:30:44.829000
2020-09-08T18:16:32
2020-09-08T18:16:32
66,531,667
22
1
null
false
2020-10-13T06:07:24
2016-08-25T06:33:01
2020-09-08T18:16:38
2020-10-12T22:49:10
5,853
67
5
1
Java
false
false
package com.jedivision.controller; import com.jedivision.entity.User; import com.jedivision.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class IndexController { private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class); private final UserService userService; @Autowired public IndexController(UserService userService) { this.userService = userService; } @RequestMapping(value = "/index", method = RequestMethod.GET) public String index(final ModelMap model) { LOGGER.debug("Index page"); model.addAttribute("usersWithoutCurrent", userService.findUsersExceptCurrentUser()); model.addAttribute("users", userService.findAll()); model.addAttribute("user", User.builder().build()); return Pages.INDEX; } @RequestMapping(value = "/addUser", method = RequestMethod.POST) public String save(@ModelAttribute User user) { userService.save(user); return "redirect:/index"; } }
UTF-8
Java
1,400
java
IndexController.java
Java
[]
null
[]
package com.jedivision.controller; import com.jedivision.entity.User; import com.jedivision.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class IndexController { private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class); private final UserService userService; @Autowired public IndexController(UserService userService) { this.userService = userService; } @RequestMapping(value = "/index", method = RequestMethod.GET) public String index(final ModelMap model) { LOGGER.debug("Index page"); model.addAttribute("usersWithoutCurrent", userService.findUsersExceptCurrentUser()); model.addAttribute("users", userService.findAll()); model.addAttribute("user", User.builder().build()); return Pages.INDEX; } @RequestMapping(value = "/addUser", method = RequestMethod.POST) public String save(@ModelAttribute User user) { userService.save(user); return "redirect:/index"; } }
1,400
0.751429
0.75
40
34
25.8689
92
false
false
0
0
0
0
0
0
0.65
false
false
7
1f01f9f0a7eb135ac548b57a827c82298875b673
4,346,506,932,581
3852e9aa4c2c66dbeec1bba5a54c8908524c8736
/docc_git/src/com/sinotrans/gd/wlp/dcs/query/SearchForecastQueryItem.java
ac33ca5a638742696ab6bccd2b2c12e4af2829d8
[]
no_license
wins6/docc
https://github.com/wins6/docc
19252f14729f2cc27c4cdb4058e41add22bdcd1a
44f2abe6f70909969300f990086b40af9e2633e4
refs/heads/master
2020-03-02T13:04:48.487000
2018-04-19T16:30:04
2018-04-19T16:30:04
91,869,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sinotrans.gd.wlp.dcs.query; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import com.sinotrans.framework.core.query.BaseQueryItem; @Entity public class SearchForecastQueryItem extends BaseQueryItem { private String vesselCode; private String voyageNo; private String portDeparture; private String portArrival; private Date dateDeparture; private Date dateArrival; private Integer publishAvailableE20; private Integer publishAvailableF20; private Integer publishAvailableE40; private Date vesselBerthEtd; private String creator; private Date createTime; private Date closingDate; private String workDemand; private Integer remain20; private Integer remain40; @Column(name = "VESSEL_CODE") public String getVesselCode() { return vesselCode; } public void setVesselCode(String vesselCode) { this.vesselCode = vesselCode; addValidField("vesselCode"); } @Column(name = "VOYAGE_NO") public String getVoyageNo() { return voyageNo; } public void setVoyageNo(String voyageNo) { this.voyageNo = voyageNo; addValidField("voyageNo"); } @Column(name = "PORT_DEPARTURE") public String getPortDeparture() { return portDeparture; } public void setPortDeparture(String portDeparture) { this.portDeparture = portDeparture; addValidField("portDeparture"); } @Column(name = "PORT_ARRIVAL") public String getPortArrival() { return portArrival; } public void setPortArrival(String portArrival) { this.portArrival = portArrival; addValidField("portArrival"); } @Column(name = "DATE_DEPARTURE") public Date getDateDeparture() { return dateDeparture; } public void setDateDeparture(Date dateDeparture) { this.dateDeparture = dateDeparture; addValidField("dateDeparture"); } @Column(name = "DATE_ARRIVAL") public Date getDateArrival() { return dateArrival; } public void setDateArrival(Date dateArrival) { this.dateArrival = dateArrival; addValidField("dateArrival"); } @Column(name = "PUBLISH_AVAILABLE_E20") public Integer getPublishAvailableE20() { return publishAvailableE20; } public void setPublishAvailableE20(Integer publishAvailableE20) { this.publishAvailableE20 = publishAvailableE20; addValidField("publishAvailableE20"); } @Column(name = "PUBLISH_AVAILABLE_F20") public Integer getPublishAvailableF20() { return publishAvailableF20; } public void setPublishAvailableF20(Integer publishAvailableF20) { this.publishAvailableF20 = publishAvailableF20; addValidField("publishAvailableF20"); } @Column(name = "VESSEL_BERTH_ETD") public Date getVesselBerthEtd() { return vesselBerthEtd; } public void setVesselBerthEtd(Date vesselBerthEtd) { this.vesselBerthEtd = vesselBerthEtd; addValidField("vesselBerthEtd"); } @Column(name = "CREATOR") public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; addValidField("creator"); } @Column(name = "CREATE_TIME") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; addValidField("createTime"); } @Column(name = "PUBLISH_AVAILABLE_E40") public Integer getPublishAvailableE40() { return publishAvailableE40; } public void setPublishAvailableE40(Integer publishAvailableE40) { this.publishAvailableE40 = publishAvailableE40; } @Column(name = "CLOSING_DATE") public Date getClosingDate() { return closingDate; } public void setClosingDate(Date closingDate) { this.closingDate = closingDate; } @Column(name = "WORK_DEMAND") public String getWorkDemand() { return workDemand; } public void setWorkDemand(String workDemand) { this.workDemand = workDemand; } @Column(name = "REMAIN20") public Integer getRemain20() { return remain20; } public void setRemain20(Integer remain20) { this.remain20 = remain20; } @Column(name = "REMAIN40") public Integer getRemain40() { return remain40; } public void setRemain40(Integer remain40) { this.remain40 = remain40; } }
UTF-8
Java
4,264
java
SearchForecastQueryItem.java
Java
[]
null
[]
package com.sinotrans.gd.wlp.dcs.query; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import com.sinotrans.framework.core.query.BaseQueryItem; @Entity public class SearchForecastQueryItem extends BaseQueryItem { private String vesselCode; private String voyageNo; private String portDeparture; private String portArrival; private Date dateDeparture; private Date dateArrival; private Integer publishAvailableE20; private Integer publishAvailableF20; private Integer publishAvailableE40; private Date vesselBerthEtd; private String creator; private Date createTime; private Date closingDate; private String workDemand; private Integer remain20; private Integer remain40; @Column(name = "VESSEL_CODE") public String getVesselCode() { return vesselCode; } public void setVesselCode(String vesselCode) { this.vesselCode = vesselCode; addValidField("vesselCode"); } @Column(name = "VOYAGE_NO") public String getVoyageNo() { return voyageNo; } public void setVoyageNo(String voyageNo) { this.voyageNo = voyageNo; addValidField("voyageNo"); } @Column(name = "PORT_DEPARTURE") public String getPortDeparture() { return portDeparture; } public void setPortDeparture(String portDeparture) { this.portDeparture = portDeparture; addValidField("portDeparture"); } @Column(name = "PORT_ARRIVAL") public String getPortArrival() { return portArrival; } public void setPortArrival(String portArrival) { this.portArrival = portArrival; addValidField("portArrival"); } @Column(name = "DATE_DEPARTURE") public Date getDateDeparture() { return dateDeparture; } public void setDateDeparture(Date dateDeparture) { this.dateDeparture = dateDeparture; addValidField("dateDeparture"); } @Column(name = "DATE_ARRIVAL") public Date getDateArrival() { return dateArrival; } public void setDateArrival(Date dateArrival) { this.dateArrival = dateArrival; addValidField("dateArrival"); } @Column(name = "PUBLISH_AVAILABLE_E20") public Integer getPublishAvailableE20() { return publishAvailableE20; } public void setPublishAvailableE20(Integer publishAvailableE20) { this.publishAvailableE20 = publishAvailableE20; addValidField("publishAvailableE20"); } @Column(name = "PUBLISH_AVAILABLE_F20") public Integer getPublishAvailableF20() { return publishAvailableF20; } public void setPublishAvailableF20(Integer publishAvailableF20) { this.publishAvailableF20 = publishAvailableF20; addValidField("publishAvailableF20"); } @Column(name = "VESSEL_BERTH_ETD") public Date getVesselBerthEtd() { return vesselBerthEtd; } public void setVesselBerthEtd(Date vesselBerthEtd) { this.vesselBerthEtd = vesselBerthEtd; addValidField("vesselBerthEtd"); } @Column(name = "CREATOR") public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; addValidField("creator"); } @Column(name = "CREATE_TIME") public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; addValidField("createTime"); } @Column(name = "PUBLISH_AVAILABLE_E40") public Integer getPublishAvailableE40() { return publishAvailableE40; } public void setPublishAvailableE40(Integer publishAvailableE40) { this.publishAvailableE40 = publishAvailableE40; } @Column(name = "CLOSING_DATE") public Date getClosingDate() { return closingDate; } public void setClosingDate(Date closingDate) { this.closingDate = closingDate; } @Column(name = "WORK_DEMAND") public String getWorkDemand() { return workDemand; } public void setWorkDemand(String workDemand) { this.workDemand = workDemand; } @Column(name = "REMAIN20") public Integer getRemain20() { return remain20; } public void setRemain20(Integer remain20) { this.remain20 = remain20; } @Column(name = "REMAIN40") public Integer getRemain40() { return remain40; } public void setRemain40(Integer remain40) { this.remain40 = remain40; } }
4,264
0.721857
0.702158
185
21.048649
17.922138
66
false
false
0
0
0
0
0
0
1.32973
false
false
7
c4a362c8e528f3ed93d6da2ab75e6d9acf38e70a
28,570,122,516,459
269e3f268e49053f2fdc55acdf29881b1ef2f710
/be/feeps/epicpets/inventories/EpicInventories.java
9293a69670d6987fbcccafa03dbd01dac1944b48
[]
no_license
2183c/EpicPets
https://github.com/2183c/EpicPets
ff1f7567543a2721239fa00d23558f8bd3cf8c87
880837e739bd6d44ce41ef5476e9d87a30f0a892
refs/heads/master
2020-03-12T00:25:15.095000
2017-06-23T13:26:13
2017-06-23T13:26:13
130,348,521
1
0
null
true
2018-04-20T10:38:49
2018-04-20T10:38:48
2017-11-29T18:31:19
2017-06-23T13:26:26
106
0
0
0
null
false
null
package be.feeps.epicpets.inventories; import be.feeps.epicpets.EpicPetsPlayer; import be.feeps.epicpets.config.CacheConfig; import be.feeps.epicpets.utils.MessageUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.List; /** * Created by feeps on 18/06/2017. */ public abstract class EpicInventories { private Inventory inv; protected Player player; protected EpicPetsPlayer epicPetsPlayer; protected CacheConfig cache = CacheConfig.getInstance(); public EpicInventories(Player player, String name, int size){ this.player = player; this.epicPetsPlayer = EpicPetsPlayer.instanceOf(this.player); this.inv = Bukkit.createInventory(null, size, name); this.epicPetsPlayer.setEpicInv(this); } public void setItem(ItemStack item, int slot, String name, List<String> lore) { ItemMeta im = item.getItemMeta(); im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_UNBREAKABLE); if (name != null) { im.setDisplayName(MessageUtil.translate(name)); } if (lore != null) { im.setLore(MessageUtil.listTranslate(lore)); } item.setItemMeta(im); this.inv.setItem(slot, item); } public abstract void create(); public abstract void onClick(ItemStack current, int slot); public void openInv(){ this.player.openInventory(this.inv); } public void update(){ this.inv.clear(); this.create(); } public void clear(){ this.inv.clear(); this.inv = null; this.epicPetsPlayer.setEpicInv(null); } public Inventory getInv(){ return this.inv; } }
UTF-8
Java
2,049
java
EpicInventories.java
Java
[ { "context": "emMeta;\n\nimport java.util.List;\n\n/**\n * Created by feeps on 18/06/2017.\n */\npublic abstract class EpicInve", "end": 436, "score": 0.9995408654212952, "start": 431, "tag": "USERNAME", "value": "feeps" } ]
null
[]
package be.feeps.epicpets.inventories; import be.feeps.epicpets.EpicPetsPlayer; import be.feeps.epicpets.config.CacheConfig; import be.feeps.epicpets.utils.MessageUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.List; /** * Created by feeps on 18/06/2017. */ public abstract class EpicInventories { private Inventory inv; protected Player player; protected EpicPetsPlayer epicPetsPlayer; protected CacheConfig cache = CacheConfig.getInstance(); public EpicInventories(Player player, String name, int size){ this.player = player; this.epicPetsPlayer = EpicPetsPlayer.instanceOf(this.player); this.inv = Bukkit.createInventory(null, size, name); this.epicPetsPlayer.setEpicInv(this); } public void setItem(ItemStack item, int slot, String name, List<String> lore) { ItemMeta im = item.getItemMeta(); im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_UNBREAKABLE); if (name != null) { im.setDisplayName(MessageUtil.translate(name)); } if (lore != null) { im.setLore(MessageUtil.listTranslate(lore)); } item.setItemMeta(im); this.inv.setItem(slot, item); } public abstract void create(); public abstract void onClick(ItemStack current, int slot); public void openInv(){ this.player.openInventory(this.inv); } public void update(){ this.inv.clear(); this.create(); } public void clear(){ this.inv.clear(); this.inv = null; this.epicPetsPlayer.setEpicInv(null); } public Inventory getInv(){ return this.inv; } }
2,049
0.654954
0.651049
72
27.458334
20.598637
83
false
false
0
0
0
0
0
0
0.666667
false
false
7
720857a0b2eb231dfb4815e2cd5fa3244015bbc9
23,983,097,420,033
ea2134b37daf9f3d527815db14aa4dbacf36ffa9
/Homework 8-1/src/homework/Client.java
3e04e31884a80cea08c337ab5e3cb2e70ff0337a
[]
no_license
PingchuanMa/COMP0042-Assignments
https://github.com/PingchuanMa/COMP0042-Assignments
df011bd35c9cbbdf2225a6288a8c89a7732aa20c
e6e902910ee2ef99d286659a67d3e232ac0be9cf
refs/heads/master
2021-08-15T22:28:39.531000
2017-11-18T11:35:14
2017-11-18T11:35:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package homework; import java.net.*; import java.io.*; import java.util.*; class Ha { String k = "fuck"; } class Word extends Ha implements Serializable { String s; void getS() { System.out.println(s); } Word() { Scanner scanner = new Scanner(System.in); s = new String(scanner.nextLine()); } } public class Client { DatagramSocket socket; DatagramPacket packet; ByteArrayOutputStream baos; ObjectOutputStream oos; byte[] outBuff; Client() { try { while (true) { Word w = new Word(); socket = new DatagramSocket(); baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(w); outBuff = baos.toByteArray(); packet = new DatagramPacket(outBuff, outBuff.length, InetAddress.getByName("localhost"), 8848); socket.send(packet); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub new Client(); } }
UTF-8
Java
993
java
Client.java
Java
[]
null
[]
package homework; import java.net.*; import java.io.*; import java.util.*; class Ha { String k = "fuck"; } class Word extends Ha implements Serializable { String s; void getS() { System.out.println(s); } Word() { Scanner scanner = new Scanner(System.in); s = new String(scanner.nextLine()); } } public class Client { DatagramSocket socket; DatagramPacket packet; ByteArrayOutputStream baos; ObjectOutputStream oos; byte[] outBuff; Client() { try { while (true) { Word w = new Word(); socket = new DatagramSocket(); baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(w); outBuff = baos.toByteArray(); packet = new DatagramPacket(outBuff, outBuff.length, InetAddress.getByName("localhost"), 8848); socket.send(packet); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub new Client(); } }
993
0.659939
0.655903
56
16.696428
17.567137
99
false
false
0
0
0
0
0
0
1.892857
false
false
7
2680b3366eb59e8b7f91a4331dd4b3f16b6ed7ea
120,259,130,728
ab3660af9cb6c0f19cc57b8108346f671aae9a49
/src/main/java/com/iquma/service/impl/TagServiceImpl.java
cda92d9da9cb5fa2e12baee7b8698d48b15dbf52
[]
no_license
1162492411/iquma
https://github.com/1162492411/iquma
b99810f3f01d169693bef3767bdaa56637ee634c
93fd0c7f22b82106d972b00527642822a584bebc
refs/heads/master
2021-07-10T12:17:40.429000
2017-08-29T02:47:18
2017-08-29T02:47:18
106,838,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iquma.service.impl; import com.iquma.dao.TagMapper; import com.iquma.exception.NoSuchTagException; import com.iquma.pojo.Tag; import com.iquma.service.TagService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by Mo on 2016/12/4. */ @Service public class TagServiceImpl implements TagService { @Autowired private TagMapper tagMapper; @Override public Tag selectByCondition(Tag condition) throws NoSuchTagException { Tag tag = this.tagMapper.selectByCondition(condition); if(null == tag) throw new NoSuchTagException(); return tag; } @Override public List selectsFirstTag() { return this.tagMapper.selectsFirstTag(); } @Override public List selectsChildren(Tag condition) { return this.tagMapper.selectsByCondition(condition); } @Override public List selectAll() { return this.tagMapper.selectAll(); } @Override public List selectsRelevant(Byte id) { return this.tagMapper.selectsRelevant(id); } }
UTF-8
Java
1,143
java
TagServiceImpl.java
Java
[ { "context": "ervice;\n\nimport java.util.List;\n\n/**\n * Created by Mo on 2016/12/4.\n */\n@Service\npublic class TagServic", "end": 331, "score": 0.6582801342010498, "start": 329, "tag": "USERNAME", "value": "Mo" } ]
null
[]
package com.iquma.service.impl; import com.iquma.dao.TagMapper; import com.iquma.exception.NoSuchTagException; import com.iquma.pojo.Tag; import com.iquma.service.TagService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by Mo on 2016/12/4. */ @Service public class TagServiceImpl implements TagService { @Autowired private TagMapper tagMapper; @Override public Tag selectByCondition(Tag condition) throws NoSuchTagException { Tag tag = this.tagMapper.selectByCondition(condition); if(null == tag) throw new NoSuchTagException(); return tag; } @Override public List selectsFirstTag() { return this.tagMapper.selectsFirstTag(); } @Override public List selectsChildren(Tag condition) { return this.tagMapper.selectsByCondition(condition); } @Override public List selectAll() { return this.tagMapper.selectAll(); } @Override public List selectsRelevant(Byte id) { return this.tagMapper.selectsRelevant(id); } }
1,143
0.710411
0.704287
46
23.847826
21.479988
75
false
false
0
0
0
0
0
0
0.347826
false
false
7
82f889fd3632a5f313bd018a77a7f4ab6afae90b
120,259,132,350
48776456f4432312f9ff5020c83e0f2d38d7d821
/app/src/main/java/com/gaga/messagehost/scope/ZZShowScopeActivity.java
35b64246823f5b2b99fe5893ac9b2dc2da87a7e3
[]
no_license
chailyuan/MessageHost
https://github.com/chailyuan/MessageHost
50cee4434e59c3b584710ff632730e688091617c
dc7bb8a2808cd853d5d5122c476acddf42a75627
refs/heads/master
2021-01-01T04:46:15.779000
2017-11-15T08:21:43
2017-11-15T08:21:43
58,859,869
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gaga.messagehost.scope; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.gaga.messagehost.R; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class ZZShowScopeActivity extends Activity { private static final String PREF_SCREEN = "pref_screen"; private static final String PREF_AUTO = "pref_auto"; private static final String DEAL_DATA = "dealdata"; private static final String STATE = "state"; private static final String SINGLE = "single"; private static final String TIMEBASE = "timebase"; private static final String INDEX = "index"; private static final String LEVEL = "level"; protected static final int DEFAULT_TIMEBASE = 2; protected int timebase; public static final int GONEXTPAGE = 1; public static final int GOBACKPAGE = 2; public static final int GOCURRPAGE = 3; private ZZScope zzscope; private ZZXScale zzxscale; public ZZYScale zzyscale; private Toast toast; private SubMenu submenu_tb; private boolean screen; private boolean dealdata;//是否处理读取的数据 //read the file //要打开的文件 /* 要打开的文件 文件长度 当前指向位置 每一页显示的个数 */ private File fileToOpen = null; private RandomAccessFile randomAccessFile = null; protected long fileLength = 0; protected long curOffset = 0;//当前读取的偏移量 public static int numEveryPage=500;//每页显示的数量 public int numRead = 0; //读取的数据放在这里 protected byte[] data; private Handler handler = null; private Runnable runnable= null; private int sleepTime = 5; private boolean inAutoThread = false; private int Sleep_Time[] = {1,2,5,10,20,50}; private static final String strings[] = {"1 s", "2 s", "5 s", "10 s", "20 s", "50 s"}; // On create @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scopemainzz); zzscope = (ZZScope) findViewById(R.id.zzscope); zzxscale = (ZZXScale) findViewById(R.id.zzxscale); zzyscale = (ZZYScale) findViewById(R.id.zzyscale); // Get action bar ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); // Set short title if (actionBar != null) actionBar.setTitle(R.string.short_name); //init data data = new byte[1024]; if (zzscope != null) { zzscope.main = this; } if (zzxscale!=null){ zzxscale.main=this; } // Set timebase index timebase = DEFAULT_TIMEBASE; handler = new Handler(); runnable = new Runnable() { @Override public void run() { handler.postDelayed(this,sleepTime*1000); inAutoThread = true; readDataSetting(GONEXTPAGE); } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem item; // Inflate the menu; this adds items to the action bar if it // is present. getMenuInflater().inflate(R.menu.main, menu); // Timebase item = menu.findItem(R.id.countbase); if (timebase != DEFAULT_TIMEBASE) { if (item.hasSubMenu()) { submenu_tb = item.getSubMenu(); clearLast(submenu_tb, DEFAULT_TIMEBASE); item = submenu_tb.getItem(timebase); setTimebase(timebase,false); if (item != null) item.setChecked(true); } } item = menu.findItem(R.id.automove); item.setIcon(inAutoThread ? R.drawable.ic_action_autofalse : R.drawable.ic_action_autotrue); item = menu.findItem(R.id.action_dealdata); if (dealdata){ item.setChecked(true); }else { item.setChecked(false); } return true; } // Restore state @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Get saved state bundle Bundle bundle = savedInstanceState.getBundle(STATE); inAutoThread = bundle.getBoolean(SINGLE); // Timebase timebase = bundle.getInt(TIMEBASE, DEFAULT_TIMEBASE); setTimebase(timebase, false); // Start zzxscale.postInvalidate(); // Index zzscope.index = bundle.getFloat(INDEX, 0); // Level zzyscale.index = bundle.getFloat(LEVEL, 0); zzyscale.postInvalidate(); } // Save state @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // State bundle Bundle bundle = new Bundle(); // Timebase bundle.putInt(TIMEBASE, timebase); bundle.putBoolean(SINGLE,inAutoThread); // Index bundle.putFloat(INDEX, zzscope.index); // Level bundle.putFloat(LEVEL, zzyscale.index); // Save bundle outState.putBundle(STATE, bundle); } // On options item @Override public boolean onOptionsItemSelected(MenuItem item) { // Get id int id = item.getItemId(); switch (id) { case android.R.id.home: this.finish(); break; //ic_bigger case R.id.bigger: numEveryPage -= 20; if (numEveryPage<20) numEveryPage = 20; zzxscale.postInvalidate(); zzscope.postInvalidate(); break; // Trigger //ic_smaller case R.id.smaller: numEveryPage += 20; if (numEveryPage>500) numEveryPage = 500; readDataSetting(GOCURRPAGE); zzxscale.postInvalidate(); zzscope.postInvalidate(); break; // Single shot case R.id.automove: inAutoThread = !inAutoThread; item.setIcon(inAutoThread ? R.drawable.ic_action_autofalse : R.drawable.ic_action_autotrue); showToast(inAutoThread ? R.string.pref_auto : R.string.pref_menual); if (inAutoThread){ handler.postDelayed(runnable,sleepTime*1000); //禁用其他菜单 }else { handler.removeCallbacks(runnable); //启用其他菜单 } break; // Timebase case R.id.countbase: if (item.hasSubMenu()) submenu_tb = item.getSubMenu(); break; // 0.1 ms case R.id.tb_1s: clearLast(submenu_tb, timebase); timebase = 0; item.setChecked(true); setTimebase(timebase, true); break; // 0.2 ms case R.id.tb_2s: clearLast(submenu_tb, timebase); timebase = 1; item.setChecked(true); setTimebase(timebase, true); break; // 0.5 ms case R.id.tb_5s: clearLast(submenu_tb, timebase); timebase = 2; item.setChecked(true); setTimebase(timebase, true); break; // 1.0 ms case R.id.tb_10s: clearLast(submenu_tb, timebase); timebase = 3; item.setChecked(true); setTimebase(timebase, true); break; // 2.0 ms case R.id.tb_20s: clearLast(submenu_tb, timebase); timebase = 4; item.setChecked(true); setTimebase(timebase, true); break; // 5.0 ms case R.id.tb_50s: clearLast(submenu_tb, timebase); timebase = 5; item.setChecked(true); setTimebase(timebase, true); break; // Clear case R.id.clear: openFile(); break; // Left case R.id.goleft: readDataSetting(GOBACKPAGE); break; // Right case R.id.goright: readDataSetting(GONEXTPAGE); break; // Start case R.id.gotostart: curOffset = 0; readDataSetting(GOCURRPAGE); break; // End case R.id.gotoend: curOffset = fileLength-numEveryPage; readDataSetting(GOCURRPAGE); break; // openfile case R.id.action_getfile: return onOpenFileClick(item); //dealdata case R.id.action_dealdata: dealdata = !dealdata; item.setChecked(dealdata); break; // Settings case R.id.action_settings: return onSettingsClick(item); default: return false; } return true; } // On settings click private boolean onSettingsClick(MenuItem item) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } // On spectrum click private boolean onOpenFileClick(MenuItem item) { Intent intent = new Intent(this, OpenFileActivity.class); startActivity(intent); return true; } // Clear last void clearLast(SubMenu submenu, int timebase) { // Clear last submenu item tickbox if (submenu != null) { MenuItem last = submenu.getItem(timebase); if (last != null) last.setChecked(false); } } // Set timebase void setTimebase(int timebase, boolean show) { sleepTime = Sleep_Time[timebase]; // Show timebase if (show) showTimebase(timebase); } // Show timebase void showTimebase(int timebase) { String text = "Timebase: " + strings[timebase]; showToast(text); } // Show toast. void showToast(int key) { Resources resources = getResources(); String text = resources.getString(key); showToast(text); } void showToast(String text) { // Cancel the last one if (toast != null) toast.cancel(); // Make a new one toast = Toast.makeText(this, text, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } //open file protected boolean openFile(){ if (OpenFileActivity.FILENAME.equals(OpenFileActivity.ROOTFOLDER)) { runOnUiThread(new Runnable() { @Override public void run() { showToast( R.string.error_choosefile); } }); fileToOpen = null; randomAccessFile=null; return false; } fileToOpen = new File(OpenFileActivity.FILENAME); if (!fileToOpen.exists()){ //文件不存在,请重新选择 runOnUiThread(new Runnable() { @Override public void run() { showToast(R.string.error_fileNotExist); } }); fileToOpen= null; randomAccessFile=null; return false; } //判断是否是文件 if (!fileToOpen.isFile()) { runOnUiThread(new Runnable() { @Override public void run() { showToast(R.string.error_filewrong); } }); fileToOpen= null; randomAccessFile=null; return false; } //判断文件是否为空 long fileSize = fileToOpen.length(); if (fileSize<=0){ runOnUiThread(new Runnable() { @Override public void run() { showToast(R.string.error_fileEmpty); } }); fileToOpen= null; randomAccessFile=null; return false; } fileLength = fileSize; curOffset = 0; try { randomAccessFile = new RandomAccessFile(fileToOpen,"r"); } catch (FileNotFoundException e) { e.printStackTrace(); fileToOpen = null; randomAccessFile=null; return false; } readDataSetting(GOCURRPAGE); return true; } protected boolean isFileOpened(){ if (fileToOpen == null|| randomAccessFile == null) return false; else return true; } //read data /* * direction: int 方向,1向前;2向后,其他不动 */ protected void readDataSetting(int direction){ if (direction == GONEXTPAGE ){ curOffset+=numEveryPage; } else if (direction==GOBACKPAGE){ curOffset-=numEveryPage; } if (curOffset<0){ curOffset=0; showToast(R.string.error_firstpage); } if (curOffset>=fileLength-numEveryPage){ showToast(R.string.error_lastpage); curOffset = fileLength-numEveryPage; if (inAutoThread){ inAutoThread = false; handler.removeCallbacks(runnable); } } readData(); } private void readData(){ try { randomAccessFile.seek(curOffset); numRead = randomAccessFile.read(data,0,numEveryPage+1); if (dealdata){ dealTheData(); } zzscope.postInvalidate(); zzxscale.postInvalidate(); } catch (IOException e) { e.printStackTrace(); } } private void dealTheData() { for (int i=0;i<numRead;i++){ //deal data data[i] /= 2; } } // On start @Override protected void onStart() { super.onStart(); } // On Resume @Override protected void onResume() { super.onResume(); // Get preferences getPreferences(); // Open the file if (!isFileOpened()){ if (!openFile()){ Intent intent = new Intent(this, OpenFileActivity.class); startActivity(intent); return; } } readDataSetting(GOCURRPAGE); //自动运行 if (inAutoThread){ handler.postDelayed(runnable,sleepTime*1000); } } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(runnable); // Save preferences savePreferences(); } // On stop @Override protected void onStop() { super.onStop(); } // Get preferences void getPreferences() { // Load preferences PreferenceManager.setDefaultValues(this, R.xml.preferences, false); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // Set preferences screen = preferences.getBoolean(PREF_SCREEN, false); inAutoThread = preferences.getBoolean(PREF_AUTO,false); dealdata = preferences.getBoolean(DEAL_DATA,false); timebase = preferences.getInt(TIMEBASE,2); String string = preferences.getString("pref_inputlength","500"); if (string!=null && !string.equals("")) numEveryPage = Integer.parseInt(string); else numEveryPage = 500; //最大值500 numEveryPage = numEveryPage>500?500:numEveryPage; zzxscale.postInvalidate(); zzscope.postInvalidate(); // Check screen if (screen) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } // Save preferences void savePreferences() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); editor.putString("pref_inputlength", numEveryPage+""); editor.putInt(TIMEBASE,timebase); editor.putBoolean(DEAL_DATA,dealdata); editor.commit(); // TODO } // Show alert void showAlert(int appName, int errorBuffer) { // Create an alert dialog builder AlertDialog.Builder builder = new AlertDialog.Builder(this); // Set the title, message and button builder.setTitle(appName); builder.setMessage(errorBuffer); builder.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Dismiss dialog dialog.dismiss(); } }); // Create the dialog AlertDialog dialog = builder.create(); // Show it dialog.show(); } }
UTF-8
Java
18,521
java
ZZShowScopeActivity.java
Java
[]
null
[]
package com.gaga.messagehost.scope; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import com.gaga.messagehost.R; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class ZZShowScopeActivity extends Activity { private static final String PREF_SCREEN = "pref_screen"; private static final String PREF_AUTO = "pref_auto"; private static final String DEAL_DATA = "dealdata"; private static final String STATE = "state"; private static final String SINGLE = "single"; private static final String TIMEBASE = "timebase"; private static final String INDEX = "index"; private static final String LEVEL = "level"; protected static final int DEFAULT_TIMEBASE = 2; protected int timebase; public static final int GONEXTPAGE = 1; public static final int GOBACKPAGE = 2; public static final int GOCURRPAGE = 3; private ZZScope zzscope; private ZZXScale zzxscale; public ZZYScale zzyscale; private Toast toast; private SubMenu submenu_tb; private boolean screen; private boolean dealdata;//是否处理读取的数据 //read the file //要打开的文件 /* 要打开的文件 文件长度 当前指向位置 每一页显示的个数 */ private File fileToOpen = null; private RandomAccessFile randomAccessFile = null; protected long fileLength = 0; protected long curOffset = 0;//当前读取的偏移量 public static int numEveryPage=500;//每页显示的数量 public int numRead = 0; //读取的数据放在这里 protected byte[] data; private Handler handler = null; private Runnable runnable= null; private int sleepTime = 5; private boolean inAutoThread = false; private int Sleep_Time[] = {1,2,5,10,20,50}; private static final String strings[] = {"1 s", "2 s", "5 s", "10 s", "20 s", "50 s"}; // On create @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scopemainzz); zzscope = (ZZScope) findViewById(R.id.zzscope); zzxscale = (ZZXScale) findViewById(R.id.zzxscale); zzyscale = (ZZYScale) findViewById(R.id.zzyscale); // Get action bar ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); // Set short title if (actionBar != null) actionBar.setTitle(R.string.short_name); //init data data = new byte[1024]; if (zzscope != null) { zzscope.main = this; } if (zzxscale!=null){ zzxscale.main=this; } // Set timebase index timebase = DEFAULT_TIMEBASE; handler = new Handler(); runnable = new Runnable() { @Override public void run() { handler.postDelayed(this,sleepTime*1000); inAutoThread = true; readDataSetting(GONEXTPAGE); } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem item; // Inflate the menu; this adds items to the action bar if it // is present. getMenuInflater().inflate(R.menu.main, menu); // Timebase item = menu.findItem(R.id.countbase); if (timebase != DEFAULT_TIMEBASE) { if (item.hasSubMenu()) { submenu_tb = item.getSubMenu(); clearLast(submenu_tb, DEFAULT_TIMEBASE); item = submenu_tb.getItem(timebase); setTimebase(timebase,false); if (item != null) item.setChecked(true); } } item = menu.findItem(R.id.automove); item.setIcon(inAutoThread ? R.drawable.ic_action_autofalse : R.drawable.ic_action_autotrue); item = menu.findItem(R.id.action_dealdata); if (dealdata){ item.setChecked(true); }else { item.setChecked(false); } return true; } // Restore state @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Get saved state bundle Bundle bundle = savedInstanceState.getBundle(STATE); inAutoThread = bundle.getBoolean(SINGLE); // Timebase timebase = bundle.getInt(TIMEBASE, DEFAULT_TIMEBASE); setTimebase(timebase, false); // Start zzxscale.postInvalidate(); // Index zzscope.index = bundle.getFloat(INDEX, 0); // Level zzyscale.index = bundle.getFloat(LEVEL, 0); zzyscale.postInvalidate(); } // Save state @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // State bundle Bundle bundle = new Bundle(); // Timebase bundle.putInt(TIMEBASE, timebase); bundle.putBoolean(SINGLE,inAutoThread); // Index bundle.putFloat(INDEX, zzscope.index); // Level bundle.putFloat(LEVEL, zzyscale.index); // Save bundle outState.putBundle(STATE, bundle); } // On options item @Override public boolean onOptionsItemSelected(MenuItem item) { // Get id int id = item.getItemId(); switch (id) { case android.R.id.home: this.finish(); break; //ic_bigger case R.id.bigger: numEveryPage -= 20; if (numEveryPage<20) numEveryPage = 20; zzxscale.postInvalidate(); zzscope.postInvalidate(); break; // Trigger //ic_smaller case R.id.smaller: numEveryPage += 20; if (numEveryPage>500) numEveryPage = 500; readDataSetting(GOCURRPAGE); zzxscale.postInvalidate(); zzscope.postInvalidate(); break; // Single shot case R.id.automove: inAutoThread = !inAutoThread; item.setIcon(inAutoThread ? R.drawable.ic_action_autofalse : R.drawable.ic_action_autotrue); showToast(inAutoThread ? R.string.pref_auto : R.string.pref_menual); if (inAutoThread){ handler.postDelayed(runnable,sleepTime*1000); //禁用其他菜单 }else { handler.removeCallbacks(runnable); //启用其他菜单 } break; // Timebase case R.id.countbase: if (item.hasSubMenu()) submenu_tb = item.getSubMenu(); break; // 0.1 ms case R.id.tb_1s: clearLast(submenu_tb, timebase); timebase = 0; item.setChecked(true); setTimebase(timebase, true); break; // 0.2 ms case R.id.tb_2s: clearLast(submenu_tb, timebase); timebase = 1; item.setChecked(true); setTimebase(timebase, true); break; // 0.5 ms case R.id.tb_5s: clearLast(submenu_tb, timebase); timebase = 2; item.setChecked(true); setTimebase(timebase, true); break; // 1.0 ms case R.id.tb_10s: clearLast(submenu_tb, timebase); timebase = 3; item.setChecked(true); setTimebase(timebase, true); break; // 2.0 ms case R.id.tb_20s: clearLast(submenu_tb, timebase); timebase = 4; item.setChecked(true); setTimebase(timebase, true); break; // 5.0 ms case R.id.tb_50s: clearLast(submenu_tb, timebase); timebase = 5; item.setChecked(true); setTimebase(timebase, true); break; // Clear case R.id.clear: openFile(); break; // Left case R.id.goleft: readDataSetting(GOBACKPAGE); break; // Right case R.id.goright: readDataSetting(GONEXTPAGE); break; // Start case R.id.gotostart: curOffset = 0; readDataSetting(GOCURRPAGE); break; // End case R.id.gotoend: curOffset = fileLength-numEveryPage; readDataSetting(GOCURRPAGE); break; // openfile case R.id.action_getfile: return onOpenFileClick(item); //dealdata case R.id.action_dealdata: dealdata = !dealdata; item.setChecked(dealdata); break; // Settings case R.id.action_settings: return onSettingsClick(item); default: return false; } return true; } // On settings click private boolean onSettingsClick(MenuItem item) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; } // On spectrum click private boolean onOpenFileClick(MenuItem item) { Intent intent = new Intent(this, OpenFileActivity.class); startActivity(intent); return true; } // Clear last void clearLast(SubMenu submenu, int timebase) { // Clear last submenu item tickbox if (submenu != null) { MenuItem last = submenu.getItem(timebase); if (last != null) last.setChecked(false); } } // Set timebase void setTimebase(int timebase, boolean show) { sleepTime = Sleep_Time[timebase]; // Show timebase if (show) showTimebase(timebase); } // Show timebase void showTimebase(int timebase) { String text = "Timebase: " + strings[timebase]; showToast(text); } // Show toast. void showToast(int key) { Resources resources = getResources(); String text = resources.getString(key); showToast(text); } void showToast(String text) { // Cancel the last one if (toast != null) toast.cancel(); // Make a new one toast = Toast.makeText(this, text, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } //open file protected boolean openFile(){ if (OpenFileActivity.FILENAME.equals(OpenFileActivity.ROOTFOLDER)) { runOnUiThread(new Runnable() { @Override public void run() { showToast( R.string.error_choosefile); } }); fileToOpen = null; randomAccessFile=null; return false; } fileToOpen = new File(OpenFileActivity.FILENAME); if (!fileToOpen.exists()){ //文件不存在,请重新选择 runOnUiThread(new Runnable() { @Override public void run() { showToast(R.string.error_fileNotExist); } }); fileToOpen= null; randomAccessFile=null; return false; } //判断是否是文件 if (!fileToOpen.isFile()) { runOnUiThread(new Runnable() { @Override public void run() { showToast(R.string.error_filewrong); } }); fileToOpen= null; randomAccessFile=null; return false; } //判断文件是否为空 long fileSize = fileToOpen.length(); if (fileSize<=0){ runOnUiThread(new Runnable() { @Override public void run() { showToast(R.string.error_fileEmpty); } }); fileToOpen= null; randomAccessFile=null; return false; } fileLength = fileSize; curOffset = 0; try { randomAccessFile = new RandomAccessFile(fileToOpen,"r"); } catch (FileNotFoundException e) { e.printStackTrace(); fileToOpen = null; randomAccessFile=null; return false; } readDataSetting(GOCURRPAGE); return true; } protected boolean isFileOpened(){ if (fileToOpen == null|| randomAccessFile == null) return false; else return true; } //read data /* * direction: int 方向,1向前;2向后,其他不动 */ protected void readDataSetting(int direction){ if (direction == GONEXTPAGE ){ curOffset+=numEveryPage; } else if (direction==GOBACKPAGE){ curOffset-=numEveryPage; } if (curOffset<0){ curOffset=0; showToast(R.string.error_firstpage); } if (curOffset>=fileLength-numEveryPage){ showToast(R.string.error_lastpage); curOffset = fileLength-numEveryPage; if (inAutoThread){ inAutoThread = false; handler.removeCallbacks(runnable); } } readData(); } private void readData(){ try { randomAccessFile.seek(curOffset); numRead = randomAccessFile.read(data,0,numEveryPage+1); if (dealdata){ dealTheData(); } zzscope.postInvalidate(); zzxscale.postInvalidate(); } catch (IOException e) { e.printStackTrace(); } } private void dealTheData() { for (int i=0;i<numRead;i++){ //deal data data[i] /= 2; } } // On start @Override protected void onStart() { super.onStart(); } // On Resume @Override protected void onResume() { super.onResume(); // Get preferences getPreferences(); // Open the file if (!isFileOpened()){ if (!openFile()){ Intent intent = new Intent(this, OpenFileActivity.class); startActivity(intent); return; } } readDataSetting(GOCURRPAGE); //自动运行 if (inAutoThread){ handler.postDelayed(runnable,sleepTime*1000); } } @Override protected void onPause() { super.onPause(); handler.removeCallbacks(runnable); // Save preferences savePreferences(); } // On stop @Override protected void onStop() { super.onStop(); } // Get preferences void getPreferences() { // Load preferences PreferenceManager.setDefaultValues(this, R.xml.preferences, false); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); // Set preferences screen = preferences.getBoolean(PREF_SCREEN, false); inAutoThread = preferences.getBoolean(PREF_AUTO,false); dealdata = preferences.getBoolean(DEAL_DATA,false); timebase = preferences.getInt(TIMEBASE,2); String string = preferences.getString("pref_inputlength","500"); if (string!=null && !string.equals("")) numEveryPage = Integer.parseInt(string); else numEveryPage = 500; //最大值500 numEveryPage = numEveryPage>500?500:numEveryPage; zzxscale.postInvalidate(); zzscope.postInvalidate(); // Check screen if (screen) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } // Save preferences void savePreferences() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); editor.putString("pref_inputlength", numEveryPage+""); editor.putInt(TIMEBASE,timebase); editor.putBoolean(DEAL_DATA,dealdata); editor.commit(); // TODO } // Show alert void showAlert(int appName, int errorBuffer) { // Create an alert dialog builder AlertDialog.Builder builder = new AlertDialog.Builder(this); // Set the title, message and button builder.setTitle(appName); builder.setMessage(errorBuffer); builder.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Dismiss dialog dialog.dismiss(); } }); // Create the dialog AlertDialog dialog = builder.create(); // Show it dialog.show(); } }
18,521
0.535529
0.529129
693
25.379509
19.01223
84
false
false
0
0
0
0
0
0
0.507937
false
false
7
3a07f6c03755aabb3527b1a7504a30c00f41faa7
11,579,231,896,562
b8d8ae82b62e54057ac967c43e1edd8d1ba2dfb7
/src/main/java/gr/demokritos/iit/datasetgen/io/MultilingFileReader.java
9260ad302c82acb4a0db1f629622cbafdbcbedde
[]
no_license
npit/ml17-data
https://github.com/npit/ml17-data
74e5a1169665bca66c7db5dd4b0eb7753e3a4ecc
686e6cedba914068173747a08e7f4e2057fe89c6
refs/heads/master
2021-01-09T06:16:18.954000
2017-02-10T12:59:34
2017-02-10T12:59:34
80,941,358
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gr.demokritos.iit.datasetgen.io; import gr.demokritos.iit.datasetgen.io.sentsplit.BasicSentenceSplitter; import gr.demokritos.iit.datasetgen.io.sentsplit.ISentenceSplitter; import gr.demokritos.iit.datasetgen.io.sentsplit.OpenNLPSentenceSplitter; import gr.demokritos.iit.datasetgen.utils.Utils; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import static gr.demokritos.iit.datasetgen.utils.Utils.toFolderPath; /** * Created by nik on 2/3/17. */ /** * Class to read folders with multiling summaries from humans & models, as well * as source articles for Sentence Replacement */ public class MultilingFileReader { String [] inputFolders; String machinesFolder; String replFolder; Set<String> Languages; ISentenceSplitter SentenceSplitter; boolean Verbosity; public TextfileCollection getTextfileCollection() { return TextfileColl; } TextfileCollection TextfileColl; public MultilingFileReader(Properties props) { Verbosity = Utils.csvStringContains(props.getProperty("modifiers"),"verbose"); TextfileColl =new TextfileCollection(); Languages = new HashSet<>(); String content = props.getProperty("input_texts",""); inputFolders = content.split(","); replFolder = props.getProperty("replacement_texts",""); String splitMode = props.getProperty("split_mode",""); if( splitMode.equals("opennlp")) SentenceSplitter = new OpenNLPSentenceSplitter(props.getProperty("sentenceSplitter_model_paths")); else if (splitMode.equals("basic")) SentenceSplitter = new BasicSentenceSplitter(props); else { SentenceSplitter = null; System.err.println("Undefined split_mode : [" + splitMode + "]"); } } // Read data from all assigned paths public void read() { if(SentenceSplitter == null) return ; System.out.println("\nParsing input data..."); for(String inputFolder : inputFolders) readFolder(inputFolder,TextfileColl.INPUT); System.out.println("\nParsing replacement data..."); readFolder(replFolder, TextfileColl.REPL); System.err.flush(); System.out.println("\nDone reading."); } // Read data from a folder. Format expected is // basedir/language1/text1,text2,... void readFolder(final String rootFolder, final String label) { ArrayList<Textfile> textfiles = new ArrayList<>(); if(rootFolder.isEmpty()){ System.err.println("\tEmpty root folder: [" + rootFolder + "]"); return; } // we expect each subfolder to be a language folder File rootFileFolder = new File(rootFolder); if(!rootFileFolder.exists()) { System.err.println("Failed to open folder: [" + rootFolder+"]"); return; } for(final String lang : rootFileFolder.list()) { // parse folder of each language String langFolder = toFolderPath(rootFolder + lang); if(! new File(langFolder).isDirectory()) { System.out.println("\tExpecting language folder - skipping non-directory:" + langFolder); continue; } // add the language to the total if(!Languages.contains(lang)) Languages.add(lang); // parse each file in the language folder File langFolderFile = new File(langFolder); for(final String textfile : langFolderFile.list()) { String textFilePath = langFolder + textfile; try { // get file text String fileContent = Utils.readFileToString(textFilePath); List<String> sentences = SentenceSplitter.splitToSentences(fileContent,lang); if(sentences == null) { System.err.println("\tFailed to read file " + textFilePath); System.err.println("\tAborting language folder read : " + langFolder); System.err.flush(); break; } Textfile tf = new Textfile(fileContent, lang); tf.setSentences(sentences); tf.setFilePath(textFilePath); textfiles.add(tf); TextfileColl.AllLanguages.add(lang); if(Verbosity) System.out.println("\tDid read file: " + textFilePath); } catch (IOException e) { System.err.printf("Error reading file %s\n",textfile); } } } Path p = Paths.get(rootFolder); TextfileColl.addInputTextfileList(textfiles,label); } }
UTF-8
Java
4,941
java
MultilingFileReader.java
Java
[ { "context": "etgen.utils.Utils.toFolderPath;\n\n/**\n * Created by nik on 2/3/17.\n */\n\n/**\n * Class to read folders with", "end": 522, "score": 0.9942951798439026, "start": 519, "tag": "USERNAME", "value": "nik" } ]
null
[]
package gr.demokritos.iit.datasetgen.io; import gr.demokritos.iit.datasetgen.io.sentsplit.BasicSentenceSplitter; import gr.demokritos.iit.datasetgen.io.sentsplit.ISentenceSplitter; import gr.demokritos.iit.datasetgen.io.sentsplit.OpenNLPSentenceSplitter; import gr.demokritos.iit.datasetgen.utils.Utils; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import static gr.demokritos.iit.datasetgen.utils.Utils.toFolderPath; /** * Created by nik on 2/3/17. */ /** * Class to read folders with multiling summaries from humans & models, as well * as source articles for Sentence Replacement */ public class MultilingFileReader { String [] inputFolders; String machinesFolder; String replFolder; Set<String> Languages; ISentenceSplitter SentenceSplitter; boolean Verbosity; public TextfileCollection getTextfileCollection() { return TextfileColl; } TextfileCollection TextfileColl; public MultilingFileReader(Properties props) { Verbosity = Utils.csvStringContains(props.getProperty("modifiers"),"verbose"); TextfileColl =new TextfileCollection(); Languages = new HashSet<>(); String content = props.getProperty("input_texts",""); inputFolders = content.split(","); replFolder = props.getProperty("replacement_texts",""); String splitMode = props.getProperty("split_mode",""); if( splitMode.equals("opennlp")) SentenceSplitter = new OpenNLPSentenceSplitter(props.getProperty("sentenceSplitter_model_paths")); else if (splitMode.equals("basic")) SentenceSplitter = new BasicSentenceSplitter(props); else { SentenceSplitter = null; System.err.println("Undefined split_mode : [" + splitMode + "]"); } } // Read data from all assigned paths public void read() { if(SentenceSplitter == null) return ; System.out.println("\nParsing input data..."); for(String inputFolder : inputFolders) readFolder(inputFolder,TextfileColl.INPUT); System.out.println("\nParsing replacement data..."); readFolder(replFolder, TextfileColl.REPL); System.err.flush(); System.out.println("\nDone reading."); } // Read data from a folder. Format expected is // basedir/language1/text1,text2,... void readFolder(final String rootFolder, final String label) { ArrayList<Textfile> textfiles = new ArrayList<>(); if(rootFolder.isEmpty()){ System.err.println("\tEmpty root folder: [" + rootFolder + "]"); return; } // we expect each subfolder to be a language folder File rootFileFolder = new File(rootFolder); if(!rootFileFolder.exists()) { System.err.println("Failed to open folder: [" + rootFolder+"]"); return; } for(final String lang : rootFileFolder.list()) { // parse folder of each language String langFolder = toFolderPath(rootFolder + lang); if(! new File(langFolder).isDirectory()) { System.out.println("\tExpecting language folder - skipping non-directory:" + langFolder); continue; } // add the language to the total if(!Languages.contains(lang)) Languages.add(lang); // parse each file in the language folder File langFolderFile = new File(langFolder); for(final String textfile : langFolderFile.list()) { String textFilePath = langFolder + textfile; try { // get file text String fileContent = Utils.readFileToString(textFilePath); List<String> sentences = SentenceSplitter.splitToSentences(fileContent,lang); if(sentences == null) { System.err.println("\tFailed to read file " + textFilePath); System.err.println("\tAborting language folder read : " + langFolder); System.err.flush(); break; } Textfile tf = new Textfile(fileContent, lang); tf.setSentences(sentences); tf.setFilePath(textFilePath); textfiles.add(tf); TextfileColl.AllLanguages.add(lang); if(Verbosity) System.out.println("\tDid read file: " + textFilePath); } catch (IOException e) { System.err.printf("Error reading file %s\n",textfile); } } } Path p = Paths.get(rootFolder); TextfileColl.addInputTextfileList(textfiles,label); } }
4,941
0.600081
0.598664
137
35.065693
27.084406
110
false
false
0
0
0
0
0
0
0.576642
false
false
7
9a379c1ce791d5ba3ee358d36a3149485b309287
9,414,568,321,116
60a73226bb7e52ada713d3497fadaed8e092428e
/src/main/java/org/example/ui/registration/RegistrationPanel.java
52dc45f32c1b4b8a3bf6af44a1920d3e1bde5cbf
[]
no_license
AzengaKevin/MangoesLeisureFacility
https://github.com/AzengaKevin/MangoesLeisureFacility
938bec7ab31c48a1c653cbe7abedb56c65fc81a9
bfa5c4bf5433caf95965b4770587798f6a57fc4a
refs/heads/master
2023-02-15T18:46:53.078000
2021-01-15T16:44:47
2021-01-15T16:44:47
328,906,483
0
0
null
false
2021-01-15T16:44:49
2021-01-12T07:29:34
2021-01-13T17:02:13
2021-01-15T16:44:48
42
0
0
0
Java
false
false
package org.example.ui.registration; import org.kordamp.ikonli.fontawesome5.FontAwesomeSolid; import org.kordamp.ikonli.swing.FontIcon; import javax.swing.*; import java.awt.*; public class RegistrationPanel extends JPanel { private final RegistrationButtonListener listener; public enum Item {Categories, Memberships, Members, Staff} private final JButton browseCategoriesButton; private final JButton browseMembershipsButton; private final JButton browseMembersButton; private final JButton browseStaffsButton; public RegistrationPanel(RegistrationButtonListener listener) { this.listener = listener; browseCategoriesButton = new JButton("Browse Categories"); FontIcon categoriesIcon = FontIcon.of(FontAwesomeSolid.LIST_ALT, 48, Color.BLACK); browseCategoriesButton.setIcon(categoriesIcon); browseCategoriesButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseCategoriesButton.setHorizontalTextPosition(SwingConstants.CENTER); browseMembershipsButton = new JButton("Browse Memberships"); FontIcon membershipIcon = FontIcon.of(FontAwesomeSolid.USER_TAG, 48, Color.BLACK); browseMembershipsButton.setIcon(membershipIcon); browseMembershipsButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseMembershipsButton.setHorizontalTextPosition(SwingConstants.CENTER); browseMembersButton = new JButton("Browse Members"); FontIcon membersIcon = FontIcon.of(FontAwesomeSolid.USERS, 48, Color.BLACK); browseMembersButton.setIcon(membersIcon); browseMembersButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseMembersButton.setHorizontalTextPosition(SwingConstants.CENTER); browseStaffsButton = new JButton("Browse Staff"); FontIcon staffIcon = FontIcon.of(FontAwesomeSolid.USERS_COG, 48, Color.BLACK); browseStaffsButton.setIcon(staffIcon); browseStaffsButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseStaffsButton.setHorizontalTextPosition(SwingConstants.CENTER); initComponents(); addComponents(); } private void addComponents() { setLayout(new GridLayout(2, 2, 20, 20)); add(browseCategoriesButton); add(browseMembershipsButton); add(browseMembersButton); add(browseStaffsButton); } private void initComponents() { browseCategoriesButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Categories)); browseMembershipsButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Memberships)); browseMembersButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Members)); browseStaffsButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Staff)); } public interface RegistrationButtonListener { void onRegistrationItemClicked(Item item); } }
UTF-8
Java
2,965
java
RegistrationPanel.java
Java
[]
null
[]
package org.example.ui.registration; import org.kordamp.ikonli.fontawesome5.FontAwesomeSolid; import org.kordamp.ikonli.swing.FontIcon; import javax.swing.*; import java.awt.*; public class RegistrationPanel extends JPanel { private final RegistrationButtonListener listener; public enum Item {Categories, Memberships, Members, Staff} private final JButton browseCategoriesButton; private final JButton browseMembershipsButton; private final JButton browseMembersButton; private final JButton browseStaffsButton; public RegistrationPanel(RegistrationButtonListener listener) { this.listener = listener; browseCategoriesButton = new JButton("Browse Categories"); FontIcon categoriesIcon = FontIcon.of(FontAwesomeSolid.LIST_ALT, 48, Color.BLACK); browseCategoriesButton.setIcon(categoriesIcon); browseCategoriesButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseCategoriesButton.setHorizontalTextPosition(SwingConstants.CENTER); browseMembershipsButton = new JButton("Browse Memberships"); FontIcon membershipIcon = FontIcon.of(FontAwesomeSolid.USER_TAG, 48, Color.BLACK); browseMembershipsButton.setIcon(membershipIcon); browseMembershipsButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseMembershipsButton.setHorizontalTextPosition(SwingConstants.CENTER); browseMembersButton = new JButton("Browse Members"); FontIcon membersIcon = FontIcon.of(FontAwesomeSolid.USERS, 48, Color.BLACK); browseMembersButton.setIcon(membersIcon); browseMembersButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseMembersButton.setHorizontalTextPosition(SwingConstants.CENTER); browseStaffsButton = new JButton("Browse Staff"); FontIcon staffIcon = FontIcon.of(FontAwesomeSolid.USERS_COG, 48, Color.BLACK); browseStaffsButton.setIcon(staffIcon); browseStaffsButton.setVerticalTextPosition(SwingConstants.BOTTOM); browseStaffsButton.setHorizontalTextPosition(SwingConstants.CENTER); initComponents(); addComponents(); } private void addComponents() { setLayout(new GridLayout(2, 2, 20, 20)); add(browseCategoriesButton); add(browseMembershipsButton); add(browseMembersButton); add(browseStaffsButton); } private void initComponents() { browseCategoriesButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Categories)); browseMembershipsButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Memberships)); browseMembersButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Members)); browseStaffsButton.addActionListener(e -> listener.onRegistrationItemClicked(Item.Staff)); } public interface RegistrationButtonListener { void onRegistrationItemClicked(Item item); } }
2,965
0.754469
0.74941
74
39.067566
33.201813
109
false
false
0
0
0
0
0
0
0.77027
false
false
7
19062b96abbc84258726bdfb777247e5c763e328
28,089,086,157,963
918192e6d3fc92ddf1c57457493aef593726e84d
/src/main/java/facades/UserFacade.java
66f5fb22a2b69e1497428c49c261fc875b954de5
[]
no_license
jacmac2812/4.Sem_security_backend
https://github.com/jacmac2812/4.Sem_security_backend
6655b5dc826554a494253eded1c505d68c4412ae
455b615b48803c095a49957d1e0a4fb8e977e263
refs/heads/master
2023-05-08T04:26:01.770000
2021-05-30T18:17:17
2021-05-30T18:17:17
346,009,621
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package facades; import dto.UserDTO; import dto.UsersDTO; import entities.Post; import entities.Role; import entities.User; import errorhandling.MissingInputException; import errorhandling.NotFoundException; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.TypedQuery; import org.mindrot.jbcrypt.BCrypt; import security.errorhandling.AuthenticationException; /** * @author lam@cphbusiness.dk */ public class UserFacade { private static EntityManagerFactory emf; private static UserFacade instance; private UserFacade() { } /** * * @param _emf * @return the instance of this facade. */ public static UserFacade getUserFacade(EntityManagerFactory _emf) { if (instance == null) { emf = _emf; instance = new UserFacade(); } return instance; } public User getVeryfiedUser(String username, String password) throws AuthenticationException { EntityManager em = emf.createEntityManager(); User user; try { user = em.find(User.class, username); if (user == null || !user.verifyPassword(password)) { throw new AuthenticationException("Invalid user name or password"); } } finally { em.close(); } return user; } public UserDTO createUser(String name, String password, String email, String age, String profilePicPath) throws MissingInputException { if (name.length() == 0 || password.length() == 0) { throw new MissingInputException("Name and/or password is missing"); } if (email.length() == 0 || email.contains("@") == false) { throw new MissingInputException("Email missing and/or does not contain @"); } if (Integer.parseInt(age) <= 13) { throw new MissingInputException("Age missing or must be higher then 13"); } EntityManager em = emf.createEntityManager(); try { User u = new User(name, password, email, age, profilePicPath); Role userRole = new Role("user"); u.addRole(userRole); em.getTransaction().begin(); em.persist(u); em.getTransaction().commit(); return new UserDTO(u); } finally { em.close(); } } public UserDTO deleteUser(String name) { EntityManager em = emf.createEntityManager(); try { User user = em.find(User.class, name); em.getTransaction().begin(); List<Post> posts = user.getPosts(); for (Post post : posts) { user.removePost(post); } em.remove(user); em.getTransaction().commit(); UserDTO uDTO = new UserDTO(user); return uDTO; } finally { em.close(); } } public UserDTO editUser(UserDTO u, String[] tokenSplit, String name) throws MissingInputException { EntityManager em = emf.createEntityManager(); if (name.equals(tokenSplit[0])) { try { User user = em.find(User.class, name); if (u.getPassword().length() != 0) { user.setUserPass(BCrypt.hashpw(u.getPassword(), BCrypt.gensalt(5))); } if (u.getEmail().length() != 0 && u.getEmail().contains("@") == true) { user.setEmail(u.getEmail()); } if (Integer.parseInt(u.getAge()) >= 13) { user.setAge(u.getAge()); } if (u.getProfilePicPath().length() != 0 && u.getProfilePicPath().contains(".jpg") == true) { user.setProfilePicPath(u.getProfilePicPath()); } em.getTransaction().begin(); em.persist(user); em.getTransaction().commit(); UserDTO uDTO = new UserDTO(user); return uDTO; } finally { em.close(); } } else { throw new MissingInputException("Not authorized to edit user"); } } public UsersDTO getAllUsers() { EntityManager em = emf.createEntityManager(); try { TypedQuery<User> query = em.createQuery("SELECT u FROM User u", entities.User.class); List<User> users = query.getResultList(); UsersDTO all = new UsersDTO(users); return all; } finally { em.close(); } } public String getPicturePath(String username) throws NotFoundException { EntityManager em = emf.createEntityManager(); User user; String picturePath; try { user = em.find(User.class, username); if (user == null) { throw new NotFoundException("User not found"); } picturePath = user.getProfilePicPath(); } finally { em.close(); } return picturePath; } }
UTF-8
Java
5,176
java
UserFacade.java
Java
[ { "context": "rhandling.AuthenticationException;\n\n/**\n * @author lam@cphbusiness.dk\n */\npublic class UserFacade {\n\n private static", "end": 480, "score": 0.9999293684959412, "start": 462, "tag": "EMAIL", "value": "lam@cphbusiness.dk" } ]
null
[]
package facades; import dto.UserDTO; import dto.UsersDTO; import entities.Post; import entities.Role; import entities.User; import errorhandling.MissingInputException; import errorhandling.NotFoundException; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.TypedQuery; import org.mindrot.jbcrypt.BCrypt; import security.errorhandling.AuthenticationException; /** * @author <EMAIL> */ public class UserFacade { private static EntityManagerFactory emf; private static UserFacade instance; private UserFacade() { } /** * * @param _emf * @return the instance of this facade. */ public static UserFacade getUserFacade(EntityManagerFactory _emf) { if (instance == null) { emf = _emf; instance = new UserFacade(); } return instance; } public User getVeryfiedUser(String username, String password) throws AuthenticationException { EntityManager em = emf.createEntityManager(); User user; try { user = em.find(User.class, username); if (user == null || !user.verifyPassword(password)) { throw new AuthenticationException("Invalid user name or password"); } } finally { em.close(); } return user; } public UserDTO createUser(String name, String password, String email, String age, String profilePicPath) throws MissingInputException { if (name.length() == 0 || password.length() == 0) { throw new MissingInputException("Name and/or password is missing"); } if (email.length() == 0 || email.contains("@") == false) { throw new MissingInputException("Email missing and/or does not contain @"); } if (Integer.parseInt(age) <= 13) { throw new MissingInputException("Age missing or must be higher then 13"); } EntityManager em = emf.createEntityManager(); try { User u = new User(name, password, email, age, profilePicPath); Role userRole = new Role("user"); u.addRole(userRole); em.getTransaction().begin(); em.persist(u); em.getTransaction().commit(); return new UserDTO(u); } finally { em.close(); } } public UserDTO deleteUser(String name) { EntityManager em = emf.createEntityManager(); try { User user = em.find(User.class, name); em.getTransaction().begin(); List<Post> posts = user.getPosts(); for (Post post : posts) { user.removePost(post); } em.remove(user); em.getTransaction().commit(); UserDTO uDTO = new UserDTO(user); return uDTO; } finally { em.close(); } } public UserDTO editUser(UserDTO u, String[] tokenSplit, String name) throws MissingInputException { EntityManager em = emf.createEntityManager(); if (name.equals(tokenSplit[0])) { try { User user = em.find(User.class, name); if (u.getPassword().length() != 0) { user.setUserPass(BCrypt.hashpw(u.getPassword(), BCrypt.gensalt(5))); } if (u.getEmail().length() != 0 && u.getEmail().contains("@") == true) { user.setEmail(u.getEmail()); } if (Integer.parseInt(u.getAge()) >= 13) { user.setAge(u.getAge()); } if (u.getProfilePicPath().length() != 0 && u.getProfilePicPath().contains(".jpg") == true) { user.setProfilePicPath(u.getProfilePicPath()); } em.getTransaction().begin(); em.persist(user); em.getTransaction().commit(); UserDTO uDTO = new UserDTO(user); return uDTO; } finally { em.close(); } } else { throw new MissingInputException("Not authorized to edit user"); } } public UsersDTO getAllUsers() { EntityManager em = emf.createEntityManager(); try { TypedQuery<User> query = em.createQuery("SELECT u FROM User u", entities.User.class); List<User> users = query.getResultList(); UsersDTO all = new UsersDTO(users); return all; } finally { em.close(); } } public String getPicturePath(String username) throws NotFoundException { EntityManager em = emf.createEntityManager(); User user; String picturePath; try { user = em.find(User.class, username); if (user == null) { throw new NotFoundException("User not found"); } picturePath = user.getProfilePicPath(); } finally { em.close(); } return picturePath; } }
5,165
0.55255
0.549845
177
28.242937
26.594948
139
false
false
0
0
0
0
0
0
0.548023
false
false
7
153b7b8ff68fd51fface7286dfacc009b6f2a3ad
24,266,565,288,175
c519b8be275d97b147ec5b29bde2be993cad07f0
/src/main/java/fashion/services/PayMethodService.java
22b015111400fa5ad680fba021d9dff6cd7ec465
[]
no_license
zavlagas/FashionProject
https://github.com/zavlagas/FashionProject
8f22d96e606eab1077ee86dc9cf465d046b6133c
8dd450fbf4b35ffbe2ef9faf2bbb49076ad5e952
refs/heads/master
2023-02-18T03:55:40.179000
2021-01-20T13:34:40
2021-01-20T13:34:40
313,345,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fashion.services; import com.stripe.exception.StripeException; import fashion.entity.PaymentRequest; public interface PayMethodService { public String charge(PaymentRequest request) throws StripeException; }
UTF-8
Java
224
java
PayMethodService.java
Java
[]
null
[]
package fashion.services; import com.stripe.exception.StripeException; import fashion.entity.PaymentRequest; public interface PayMethodService { public String charge(PaymentRequest request) throws StripeException; }
224
0.825893
0.825893
10
21.4
24.000834
72
false
false
0
0
0
0
0
0
0.4
false
false
7
6b29d4ac68b4a206904029b1d4177d1a2f3f7c80
7,584,912,248,504
678fdd95c8b21a086cc7b305814cdc024b9c4ce4
/src/main/java/GUI/Screens/SplashScreen/SplashScreenController.java
dd91ed8667b61c81a89bb9a317845ebadc090251
[]
no_license
MostafaTwfiq/To-Do-List
https://github.com/MostafaTwfiq/To-Do-List
673a60550a2289d8d704a59de80d0357b2f9c8e2
22197b1b3816811b2889b7c10e63048baf8aa79a
refs/heads/master
2023-01-01T21:55:48.288000
2020-10-16T13:19:51
2020-10-16T13:19:51
293,337,694
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package GUI.Screens.SplashScreen; import GUI.IControllers; import GUI.Screens.LoginScreen.LoginScreenController; import GUI.Style.ScreensPaths; import Main.Main; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.util.Duration; import java.net.URL; import java.util.ResourceBundle; public class SplashScreenController implements IControllers { @FXML private AnchorPane parentLayout; @FXML private ImageView appLogo; private Timeline resizingTimeLine; private Timeline reverseResizingTimeLine; private Timeline fadingTimeLine; public SplashScreenController() {} private void setupAppLogo() { try { appLogo.setImage(new Image("/TodoAppIcon.png")); } catch (Exception e) { System.out.println("Something went wrong while loading app logo in opening screen."); } } public void setupAnimationTimers() { double originalHeight = appLogo.getFitHeight(); double originalWidth = appLogo.getFitWidth(); appLogo.setFitHeight(0); appLogo.setFitWidth(0); KeyValue resizingHeightKV = new KeyValue(appLogo.fitHeightProperty(), originalHeight * 1.5); KeyValue resizingWidthKV = new KeyValue(appLogo.fitWidthProperty(), originalWidth * 1.5); KeyValue rotationKV = new KeyValue(appLogo.rotateProperty(), 360); KeyValue reverseResizingHeightKV = new KeyValue(appLogo.fitHeightProperty(), originalHeight); KeyValue reverseResizingWidthKV = new KeyValue(appLogo.fitWidthProperty(), originalWidth); resizingTimeLine = new Timeline( new KeyFrame( Duration.millis(700), resizingHeightKV, resizingWidthKV, rotationKV, new KeyValue(appLogo.layoutXProperty(), parentLayout.getPrefWidth() / 2.0 - (originalWidth * 1.5) / 2.0), new KeyValue(appLogo.layoutYProperty(), parentLayout.getPrefHeight() / 2.0 - (originalHeight * 1.5) / 2.0) ) ); reverseResizingTimeLine = new Timeline( new KeyFrame( Duration.millis(300), reverseResizingHeightKV, reverseResizingWidthKV, new KeyValue(appLogo.layoutXProperty(), parentLayout.getPrefWidth() / 2.0 - originalWidth / 2.0), new KeyValue(appLogo.layoutYProperty(), parentLayout.getPrefHeight() / 2.0 - originalHeight / 2.0) ) ); fadingTimeLine = new Timeline( new KeyFrame( Duration.millis(700), new KeyValue(appLogo.opacityProperty(), 0) ) ); fadingTimeLine.setOnFinished(e -> { try { LoginScreenController loginScreenController = new LoginScreenController(); Parent loginScreenParent = null; ScreensPaths paths = new ScreensPaths(); FXMLLoader loader = new FXMLLoader(getClass().getResource(paths.getLoginScreenFxml())); loader.setController(loginScreenController); loginScreenParent = loader.load(); loginScreenParent.getStylesheets().add(paths.getLoginScreenCssSheet()); Main.screenManager.changeScreen(loginScreenController); } catch (Exception exception) { exception.printStackTrace(); } }); reverseResizingTimeLine.setOnFinished(e -> { fadingTimeLine.play(); }); resizingTimeLine.setOnFinished(e -> { reverseResizingTimeLine.play(); }); } public void startSplashScreen() { resizingTimeLine.play(); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { setupAppLogo(); setupAnimationTimers(); } @Override public void updateStyle() { } @Override public Parent getParent() { return parentLayout; } }
UTF-8
Java
4,303
java
SplashScreenController.java
Java
[]
null
[]
package GUI.Screens.SplashScreen; import GUI.IControllers; import GUI.Screens.LoginScreen.LoginScreenController; import GUI.Style.ScreensPaths; import Main.Main; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.util.Duration; import java.net.URL; import java.util.ResourceBundle; public class SplashScreenController implements IControllers { @FXML private AnchorPane parentLayout; @FXML private ImageView appLogo; private Timeline resizingTimeLine; private Timeline reverseResizingTimeLine; private Timeline fadingTimeLine; public SplashScreenController() {} private void setupAppLogo() { try { appLogo.setImage(new Image("/TodoAppIcon.png")); } catch (Exception e) { System.out.println("Something went wrong while loading app logo in opening screen."); } } public void setupAnimationTimers() { double originalHeight = appLogo.getFitHeight(); double originalWidth = appLogo.getFitWidth(); appLogo.setFitHeight(0); appLogo.setFitWidth(0); KeyValue resizingHeightKV = new KeyValue(appLogo.fitHeightProperty(), originalHeight * 1.5); KeyValue resizingWidthKV = new KeyValue(appLogo.fitWidthProperty(), originalWidth * 1.5); KeyValue rotationKV = new KeyValue(appLogo.rotateProperty(), 360); KeyValue reverseResizingHeightKV = new KeyValue(appLogo.fitHeightProperty(), originalHeight); KeyValue reverseResizingWidthKV = new KeyValue(appLogo.fitWidthProperty(), originalWidth); resizingTimeLine = new Timeline( new KeyFrame( Duration.millis(700), resizingHeightKV, resizingWidthKV, rotationKV, new KeyValue(appLogo.layoutXProperty(), parentLayout.getPrefWidth() / 2.0 - (originalWidth * 1.5) / 2.0), new KeyValue(appLogo.layoutYProperty(), parentLayout.getPrefHeight() / 2.0 - (originalHeight * 1.5) / 2.0) ) ); reverseResizingTimeLine = new Timeline( new KeyFrame( Duration.millis(300), reverseResizingHeightKV, reverseResizingWidthKV, new KeyValue(appLogo.layoutXProperty(), parentLayout.getPrefWidth() / 2.0 - originalWidth / 2.0), new KeyValue(appLogo.layoutYProperty(), parentLayout.getPrefHeight() / 2.0 - originalHeight / 2.0) ) ); fadingTimeLine = new Timeline( new KeyFrame( Duration.millis(700), new KeyValue(appLogo.opacityProperty(), 0) ) ); fadingTimeLine.setOnFinished(e -> { try { LoginScreenController loginScreenController = new LoginScreenController(); Parent loginScreenParent = null; ScreensPaths paths = new ScreensPaths(); FXMLLoader loader = new FXMLLoader(getClass().getResource(paths.getLoginScreenFxml())); loader.setController(loginScreenController); loginScreenParent = loader.load(); loginScreenParent.getStylesheets().add(paths.getLoginScreenCssSheet()); Main.screenManager.changeScreen(loginScreenController); } catch (Exception exception) { exception.printStackTrace(); } }); reverseResizingTimeLine.setOnFinished(e -> { fadingTimeLine.play(); }); resizingTimeLine.setOnFinished(e -> { reverseResizingTimeLine.play(); }); } public void startSplashScreen() { resizingTimeLine.play(); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { setupAppLogo(); setupAnimationTimers(); } @Override public void updateStyle() { } @Override public Parent getParent() { return parentLayout; } }
4,303
0.63142
0.622356
133
31.353384
31.205406
130
false
false
0
0
0
0
0
0
0.56391
false
false
7
54e3e0e6997c697dd68979ec74116ec1d64284c8
14,645,838,490,319
836805e4cb43cb50046869aaa87e715655e64bc3
/src/main/java/com/kowpad/dao/persistance/GenericDAOImpl.java
157ba02029e54f30c8c17fd04c1a90e9cbc287ce
[]
no_license
deepcabinwala/kowpad
https://github.com/deepcabinwala/kowpad
91425b340d04839bdba696866de66f69c40a64e6
f57d09831b87d599c6cf6a6d614bf8b799ab06a1
refs/heads/master
2017-12-31T16:53:43.072000
2016-03-13T03:27:15
2016-03-13T03:27:15
29,572,819
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kowpad.dao.persistance; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.math.NumberUtils; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.transform.Transformers; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import org.springframework.transaction.annotation.Transactional; import com.kowpad.util.Parameter; public abstract class GenericDAOImpl<T, ID extends Serializable> extends HibernateDaoSupport { protected Class<T> persistentClass; private SessionFactory sessionFactory; @SuppressWarnings("unchecked") public GenericDAOImpl() { this.persistentClass = (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } /** * * @param colName * @param strId * @param clazz * @return */ public List getListByValue(Class clazz, String colName, Object value, Order order) { return getListByCriterian(clazz, Restrictions.eq(colName, value), order); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<Object[]> findByCriteriaList(DetachedCriteria criteria) { return (List<Object[]>) getHibernateTemplate().findByCriteria(criteria); } //this method will accept the limit and offset value to show the results @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<Object[]> findByCriteriaListPagination(DetachedCriteria criteria,int firstResult, int maxResults) { return (List<Object[]>) getHibernateTemplate().findByCriteria(criteria,firstResult,maxResults); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<String> findByCriteriasList(DetachedCriteria criteria) { return (List<String>) getHibernateTemplate().findByCriteria(criteria); } /** * Gets database session from {@link SessionFactory} * * @return */ @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<T> findByCriteria(DetachedCriteria criteria) { return (List<T>) getHibernateTemplate().findByCriteria(criteria); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<T> findByCriteriaListObjectPagination(DetachedCriteria criteria,int firstResult, int maxResults) { return (List<T>) getHibernateTemplate().findByCriteria(criteria); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<ID> findByCriterias(DetachedCriteria criteria) { return (List<ID>) getHibernateTemplate().findByCriteria(criteria); } protected final T getByCriteria(DetachedCriteria criteria) { List<T> list = findByCriteria(criteria); T t = list.size() > 0 ? list.get(0) : null; return t; } //This method will return an object data type protected final Object getObjectByCriteria(DetachedCriteria criteria) { Session session = this.getSessionFactory().openSession(); Criteria crit = criteria.getExecutableCriteria(session); Object obj= crit.uniqueResult(); session.close(); return obj; } public Class<T> getPersistentClass() { return persistentClass; } @SuppressWarnings("unused") protected List getListFromObj(Object obj){ List v = new ArrayList(); v.add(obj); return v; } public boolean add(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.save(object); } tr.commit(); return true; } catch (Exception e) { e.printStackTrace(); tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Closes current database session. */ public void closeCurrentSession() { Transaction tr = null; try { Session sess = sessionFactory.getCurrentSession(); if (sess.isOpen()) { tr = sess.getTransaction(); sess.flush(); tr.commit(); sess.close(); } } catch (HibernateException e) { if (tr != null) { tr.rollback(); } } } /** * Updates list of objects in database. * * @param obj * @return */ public boolean update(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.update(object); } tr.commit(); return true; } catch (Exception e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Save or updates (if already exists) list of objects in database. * * @param obj * @return */ public boolean saveOrUpdate(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.saveOrUpdate(object); } tr.commit(); return true; } catch (Exception e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Executes HQL query. * * @param query * @return */ public int executeHQLQuery(String query) { Session session = null; int result = -1; Transaction tx = null; try { session = getSessionFactory().openSession(); tx = session.beginTransaction(); Query hqlQuery = session.createQuery(query); result = hqlQuery.executeUpdate(); tx.commit(); } catch (HibernateException e) { tx.rollback(); } finally { if (session != null) session.close(); } return result; } /** * * @param query * @return */ public List getRowCountSQLQuery(String query) { Session session = null; List count = null; // Transaction tx = null; try { session = getSessionFactory().openSession(); count = session.createSQLQuery(query).list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return count; } /** * Execute SQL query. * * @param query * the query * @return the list */ public List<Object[]> runSQLQuery(String query) { Session session = null; List<Object[]> result = null; try { session = getSessionFactory().openSession(); result = session.createSQLQuery(query).list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Execute SQL query. * * @param query * the query * @return the list */ public List executeSQLQuery(String query) { Session session = null; List result = null; try { session = getSessionFactory().openSession(); result = session.createSQLQuery(query).list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Execute sql update. * * @param query * the query * @return the int */ public int executeSQLUpdate(String query) { Session session = null; int result = -1; try { session = getSessionFactory().openSession(); result = session.createSQLQuery(query).executeUpdate(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Get data by executing HQL query. * * @param query * @return */ @SuppressWarnings("unchecked") public List getByHQLQuery(String query, Integer limit, Integer offset) { Session session = null; List result = null; try { session = getSessionFactory().openSession(); Query hqlQuery = session.createQuery(query); if (limit != null) hqlQuery.setMaxResults(limit); if (offset != null) hqlQuery.setFirstResult(offset); result = hqlQuery.list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Deletes list of object from database. * * @param obj * @return */ public boolean delete(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.delete(object); } tr.commit(); return true; } catch (HibernateException e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } // This method is created manually because delete a list there will two sessions public boolean deleteList(List<Object> objs) { Session session=null; Transaction tr=null; try { if(getSessionFactory().getCurrentSession().isOpen()){ session= getSessionFactory().getCurrentSession(); tr = session.getTransaction(); } else{ session = getSessionFactory().openSession(); tr = session.beginTransaction(); } for (Object object : objs) { session.delete(object); } tr.commit(); return true; } catch (HibernateException e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Get list of objects of specific class. * * @param clazz * @return */ @SuppressWarnings("unchecked") public List getList(Class clazz) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); users = crt.list(); } finally { session.close(); } return users; } /** * Get list of objects of specific class with condition list. * * @param clazz * @param criterion * @param order * optional * @return */ @SuppressWarnings("unchecked") public List getListByCriterianList(Class clazz, List<Criterion> criterions, Order order) { return getListByCriterianList(clazz, criterions, order, null); } /** * Get list of objects[contains only those attributes that are defined in * projection list] of specific class with condition list. * * @param clazz * @param criterion * @param order * optional * @return */ @SuppressWarnings("unchecked") public List getListByCriterianList(Class clazz, List<Criterion> criterions, Order order, ProjectionList projectionList) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); if (criterions != null) { for (Criterion criterion : criterions) crt.add(criterion); } if (order != null) crt.addOrder(order); if (projectionList != null) crt.setProjection(projectionList); users = crt.list(); } finally { session.close(); } return users; } /** * Gets the row count of class by filter. * * @param clazz * the clazz * @param colName * the col name * @param colVal * the col val * @return */ public Long getRowCount(Class<?> clazz, String colName, Object colVal) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(clazz); ProjectionList projList = Projections.projectionList(); projList.add(Projections.rowCount()); crit.setProjection(projList); if (colName != null) { if (colVal instanceof String) crit.add(Restrictions.eq(colName, (String) colVal)); else if (colVal instanceof Long) crit.add(Restrictions.eq(colName, (Long) colVal)); } Long count = NumberUtils.toLong(crit.list().get(0) + "", 0); return count; } /** * Gets the row count. * * @param clazz * the clazz * @param lstCriterian * the lst criterian * @return the row count */ public Long getRowCount(Class<?> clazz, List<Criterion> lstCriterian) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(clazz); ProjectionList projList = Projections.projectionList(); projList.add(Projections.rowCount()); crit.setProjection(projList); if (lstCriterian != null) { for (Criterion criterion : lstCriterian) crit.add(criterion); } // Integer count = (Integer) crit.list().get(0); Long count = (Long) crit.list().get(0); return count; } //This method gives the count of records in table. public Long getRowCount(Class<?> clazz) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(clazz); crit.setProjection(Projections.rowCount()); Long count = (Long) crit.uniqueResult(); session.close(); return count; } @SuppressWarnings("unchecked") protected List<T> findByCriteria(Criterion... criterion) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(getPersistentClass()); for (Criterion c : criterion) { crit.add(c); } return crit.list(); } /** * Get object list by criteria. * * @param clazz * @param criterion * @param order * optional * @return */ @Transactional @SuppressWarnings("unchecked") public List getListByCriterian(Class<?> clazz, Criterion criterion, Order order) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); crt.add(criterion); if (order != null) crt.addOrder(order); users = crt.list(); } finally { try { session.close(); } catch (Exception e) { } } return users; } /** * Get filtered list of objects. Filtering parameters can be: -- is less * than -- is equal to -- is greater than -- in -- not equal to -- order asc * -- order desc -- pagination * * @param clazz * @param lstParam * @return */ @SuppressWarnings("unchecked") public List getFilterList(Class clazz, List<Parameter> lstParam) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); if (lstParam != null) { for (Parameter param : lstParam) { int key = param.getComparator(); switch (key) { case Parameter.LESS: crt.add(Restrictions.le(param.getName(), param.getValue())); break; case Parameter.EQUAL: crt.add(Restrictions.eq(param.getName(), param.getValue())); break; case Parameter.GREATER: crt.add(Restrictions.ge(param.getName(), param.getValue())); break; case Parameter.IN: crt.add(Restrictions.in(param.getName(), (Object[]) param.getValue())); break; case Parameter.NOT_EQUAL: crt.add(Restrictions.ne(param.getName(), param.getValue())); break; case Parameter.LIMIT: crt.setMaxResults((Integer) param.getValue()); break; case Parameter.ORDER_ASC: crt.addOrder(Order.asc((String) param.getValue())); break; case Parameter.ORDER_DESK: crt.addOrder(Order.desc((String) param.getValue())); break; default: System.err.println("No comparator found......"); break; } } } users = crt.list(); } finally { session.close(); } return users; } /** * Get filtered list by id. * * @param clazz * @param colName * @param id * @return */ @SuppressWarnings("unchecked") public List getFilterListById(Class clazz, String colName, Long id) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); crt.add(Restrictions.eq(colName, id)); users = crt.list(); } finally { session.close(); } return users; } /** * Gets list of objects by projection. * * @param clazz * the clazz * @param lstCriterian * -list of criteria - <b>can be null</b> * @param lstProperty * - list of property string to be fetched - <b>can be null</b> * @param returnObject * -if true returns specifies class object list, otherwise row * object list * @return List of class object if returnObject is true else row object list */ @SuppressWarnings("unchecked") public List getByProjection(Class clazz, List<Criterion> lstCriterian, List<String> lstProperty, boolean returnObject) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); if (lstCriterian != null) { for (Criterion c : lstCriterian) crt.add(c); } if (lstProperty != null) { ProjectionList projList = Projections.projectionList(); for (String proj : lstProperty) projList.add(Projections.property(proj), proj); crt.setProjection(projList); } if (returnObject) crt.setResultTransformer(Transformers.aliasToBean(clazz)); users = crt.list(); } finally { session.close(); } return users; } }
UTF-8
Java
17,422
java
GenericDAOImpl.java
Java
[]
null
[]
package com.kowpad.dao.persistance; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.math.NumberUtils; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hibernate.transform.Transformers; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import org.springframework.transaction.annotation.Transactional; import com.kowpad.util.Parameter; public abstract class GenericDAOImpl<T, ID extends Serializable> extends HibernateDaoSupport { protected Class<T> persistentClass; private SessionFactory sessionFactory; @SuppressWarnings("unchecked") public GenericDAOImpl() { this.persistentClass = (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } /** * * @param colName * @param strId * @param clazz * @return */ public List getListByValue(Class clazz, String colName, Object value, Order order) { return getListByCriterian(clazz, Restrictions.eq(colName, value), order); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<Object[]> findByCriteriaList(DetachedCriteria criteria) { return (List<Object[]>) getHibernateTemplate().findByCriteria(criteria); } //this method will accept the limit and offset value to show the results @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<Object[]> findByCriteriaListPagination(DetachedCriteria criteria,int firstResult, int maxResults) { return (List<Object[]>) getHibernateTemplate().findByCriteria(criteria,firstResult,maxResults); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<String> findByCriteriasList(DetachedCriteria criteria) { return (List<String>) getHibernateTemplate().findByCriteria(criteria); } /** * Gets database session from {@link SessionFactory} * * @return */ @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<T> findByCriteria(DetachedCriteria criteria) { return (List<T>) getHibernateTemplate().findByCriteria(criteria); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<T> findByCriteriaListObjectPagination(DetachedCriteria criteria,int firstResult, int maxResults) { return (List<T>) getHibernateTemplate().findByCriteria(criteria); } @Transactional(readOnly = true) @SuppressWarnings({ "unchecked" }) protected final List<ID> findByCriterias(DetachedCriteria criteria) { return (List<ID>) getHibernateTemplate().findByCriteria(criteria); } protected final T getByCriteria(DetachedCriteria criteria) { List<T> list = findByCriteria(criteria); T t = list.size() > 0 ? list.get(0) : null; return t; } //This method will return an object data type protected final Object getObjectByCriteria(DetachedCriteria criteria) { Session session = this.getSessionFactory().openSession(); Criteria crit = criteria.getExecutableCriteria(session); Object obj= crit.uniqueResult(); session.close(); return obj; } public Class<T> getPersistentClass() { return persistentClass; } @SuppressWarnings("unused") protected List getListFromObj(Object obj){ List v = new ArrayList(); v.add(obj); return v; } public boolean add(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.save(object); } tr.commit(); return true; } catch (Exception e) { e.printStackTrace(); tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Closes current database session. */ public void closeCurrentSession() { Transaction tr = null; try { Session sess = sessionFactory.getCurrentSession(); if (sess.isOpen()) { tr = sess.getTransaction(); sess.flush(); tr.commit(); sess.close(); } } catch (HibernateException e) { if (tr != null) { tr.rollback(); } } } /** * Updates list of objects in database. * * @param obj * @return */ public boolean update(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.update(object); } tr.commit(); return true; } catch (Exception e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Save or updates (if already exists) list of objects in database. * * @param obj * @return */ public boolean saveOrUpdate(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.saveOrUpdate(object); } tr.commit(); return true; } catch (Exception e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Executes HQL query. * * @param query * @return */ public int executeHQLQuery(String query) { Session session = null; int result = -1; Transaction tx = null; try { session = getSessionFactory().openSession(); tx = session.beginTransaction(); Query hqlQuery = session.createQuery(query); result = hqlQuery.executeUpdate(); tx.commit(); } catch (HibernateException e) { tx.rollback(); } finally { if (session != null) session.close(); } return result; } /** * * @param query * @return */ public List getRowCountSQLQuery(String query) { Session session = null; List count = null; // Transaction tx = null; try { session = getSessionFactory().openSession(); count = session.createSQLQuery(query).list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return count; } /** * Execute SQL query. * * @param query * the query * @return the list */ public List<Object[]> runSQLQuery(String query) { Session session = null; List<Object[]> result = null; try { session = getSessionFactory().openSession(); result = session.createSQLQuery(query).list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Execute SQL query. * * @param query * the query * @return the list */ public List executeSQLQuery(String query) { Session session = null; List result = null; try { session = getSessionFactory().openSession(); result = session.createSQLQuery(query).list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Execute sql update. * * @param query * the query * @return the int */ public int executeSQLUpdate(String query) { Session session = null; int result = -1; try { session = getSessionFactory().openSession(); result = session.createSQLQuery(query).executeUpdate(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Get data by executing HQL query. * * @param query * @return */ @SuppressWarnings("unchecked") public List getByHQLQuery(String query, Integer limit, Integer offset) { Session session = null; List result = null; try { session = getSessionFactory().openSession(); Query hqlQuery = session.createQuery(query); if (limit != null) hqlQuery.setMaxResults(limit); if (offset != null) hqlQuery.setFirstResult(offset); result = hqlQuery.list(); } catch (HibernateException e) { } finally { if (session != null) session.close(); } return result; } /** * Deletes list of object from database. * * @param obj * @return */ public boolean delete(List<Object> objs) { Session session = null; Transaction tr = null; try { session = getSessionFactory().openSession(); tr = session.beginTransaction(); for (Object object : objs) { session.delete(object); } tr.commit(); return true; } catch (HibernateException e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } // This method is created manually because delete a list there will two sessions public boolean deleteList(List<Object> objs) { Session session=null; Transaction tr=null; try { if(getSessionFactory().getCurrentSession().isOpen()){ session= getSessionFactory().getCurrentSession(); tr = session.getTransaction(); } else{ session = getSessionFactory().openSession(); tr = session.beginTransaction(); } for (Object object : objs) { session.delete(object); } tr.commit(); return true; } catch (HibernateException e) { tr.rollback(); } finally { if (session != null) session.close(); } return false; } /** * Get list of objects of specific class. * * @param clazz * @return */ @SuppressWarnings("unchecked") public List getList(Class clazz) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); users = crt.list(); } finally { session.close(); } return users; } /** * Get list of objects of specific class with condition list. * * @param clazz * @param criterion * @param order * optional * @return */ @SuppressWarnings("unchecked") public List getListByCriterianList(Class clazz, List<Criterion> criterions, Order order) { return getListByCriterianList(clazz, criterions, order, null); } /** * Get list of objects[contains only those attributes that are defined in * projection list] of specific class with condition list. * * @param clazz * @param criterion * @param order * optional * @return */ @SuppressWarnings("unchecked") public List getListByCriterianList(Class clazz, List<Criterion> criterions, Order order, ProjectionList projectionList) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); if (criterions != null) { for (Criterion criterion : criterions) crt.add(criterion); } if (order != null) crt.addOrder(order); if (projectionList != null) crt.setProjection(projectionList); users = crt.list(); } finally { session.close(); } return users; } /** * Gets the row count of class by filter. * * @param clazz * the clazz * @param colName * the col name * @param colVal * the col val * @return */ public Long getRowCount(Class<?> clazz, String colName, Object colVal) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(clazz); ProjectionList projList = Projections.projectionList(); projList.add(Projections.rowCount()); crit.setProjection(projList); if (colName != null) { if (colVal instanceof String) crit.add(Restrictions.eq(colName, (String) colVal)); else if (colVal instanceof Long) crit.add(Restrictions.eq(colName, (Long) colVal)); } Long count = NumberUtils.toLong(crit.list().get(0) + "", 0); return count; } /** * Gets the row count. * * @param clazz * the clazz * @param lstCriterian * the lst criterian * @return the row count */ public Long getRowCount(Class<?> clazz, List<Criterion> lstCriterian) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(clazz); ProjectionList projList = Projections.projectionList(); projList.add(Projections.rowCount()); crit.setProjection(projList); if (lstCriterian != null) { for (Criterion criterion : lstCriterian) crit.add(criterion); } // Integer count = (Integer) crit.list().get(0); Long count = (Long) crit.list().get(0); return count; } //This method gives the count of records in table. public Long getRowCount(Class<?> clazz) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(clazz); crit.setProjection(Projections.rowCount()); Long count = (Long) crit.uniqueResult(); session.close(); return count; } @SuppressWarnings("unchecked") protected List<T> findByCriteria(Criterion... criterion) { Session session = this.getSessionFactory().openSession(); Criteria crit = session.createCriteria(getPersistentClass()); for (Criterion c : criterion) { crit.add(c); } return crit.list(); } /** * Get object list by criteria. * * @param clazz * @param criterion * @param order * optional * @return */ @Transactional @SuppressWarnings("unchecked") public List getListByCriterian(Class<?> clazz, Criterion criterion, Order order) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); crt.add(criterion); if (order != null) crt.addOrder(order); users = crt.list(); } finally { try { session.close(); } catch (Exception e) { } } return users; } /** * Get filtered list of objects. Filtering parameters can be: -- is less * than -- is equal to -- is greater than -- in -- not equal to -- order asc * -- order desc -- pagination * * @param clazz * @param lstParam * @return */ @SuppressWarnings("unchecked") public List getFilterList(Class clazz, List<Parameter> lstParam) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); if (lstParam != null) { for (Parameter param : lstParam) { int key = param.getComparator(); switch (key) { case Parameter.LESS: crt.add(Restrictions.le(param.getName(), param.getValue())); break; case Parameter.EQUAL: crt.add(Restrictions.eq(param.getName(), param.getValue())); break; case Parameter.GREATER: crt.add(Restrictions.ge(param.getName(), param.getValue())); break; case Parameter.IN: crt.add(Restrictions.in(param.getName(), (Object[]) param.getValue())); break; case Parameter.NOT_EQUAL: crt.add(Restrictions.ne(param.getName(), param.getValue())); break; case Parameter.LIMIT: crt.setMaxResults((Integer) param.getValue()); break; case Parameter.ORDER_ASC: crt.addOrder(Order.asc((String) param.getValue())); break; case Parameter.ORDER_DESK: crt.addOrder(Order.desc((String) param.getValue())); break; default: System.err.println("No comparator found......"); break; } } } users = crt.list(); } finally { session.close(); } return users; } /** * Get filtered list by id. * * @param clazz * @param colName * @param id * @return */ @SuppressWarnings("unchecked") public List getFilterListById(Class clazz, String colName, Long id) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); crt.add(Restrictions.eq(colName, id)); users = crt.list(); } finally { session.close(); } return users; } /** * Gets list of objects by projection. * * @param clazz * the clazz * @param lstCriterian * -list of criteria - <b>can be null</b> * @param lstProperty * - list of property string to be fetched - <b>can be null</b> * @param returnObject * -if true returns specifies class object list, otherwise row * object list * @return List of class object if returnObject is true else row object list */ @SuppressWarnings("unchecked") public List getByProjection(Class clazz, List<Criterion> lstCriterian, List<String> lstProperty, boolean returnObject) { Session session = null; List users = null; try { session = this.getSessionFactory().openSession(); Criteria crt = session.createCriteria(clazz); if (lstCriterian != null) { for (Criterion c : lstCriterian) crt.add(c); } if (lstProperty != null) { ProjectionList projList = Projections.projectionList(); for (String proj : lstProperty) projList.add(Projections.property(proj), proj); crt.setProjection(projList); } if (returnObject) crt.setResultTransformer(Transformers.aliasToBean(clazz)); users = crt.list(); } finally { session.close(); } return users; } }
17,422
0.666112
0.66548
697
23.995695
20.227365
122
false
false
0
0
0
0
0
0
2.397418
false
false
7
f1ac45f70bc68be6d44572d8e0a1d8aee9882b0d
30,992,484,013,967
8d93ef65546a517097a3f5751a8f0aa57ad52371
/app/src/main/java/com/mobile/diemo/soshoba/fragment/SwipeHome.java
5046ab9c236902f42edabaf2bd67680896180e55
[]
no_license
DevDiemo/Diemo-Soshoba
https://github.com/DevDiemo/Diemo-Soshoba
b068ffae27b733008d24d3d331616ea54fe7ccd6
634f4794adc34a7cb0de73a8ddafb443c8d65f4f
refs/heads/master
2018-12-11T12:50:37.888000
2018-11-12T16:13:58
2018-11-12T16:13:58
145,886,767
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mobile.diemo.soshoba.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mobile.diemo.soshoba.R; import com.mobile.diemo.soshoba.adapter.SwipeHomeAdapter; /** * Created by Diemo on 25/8/2017. */ public class SwipeHome extends Fragment { private ViewPager mViewPager; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.swipe_home, container, false); initialize(v); //setListeners(); setAdapter(); return v; } private void initialize(View v){ mViewPager = (ViewPager) v.findViewById(R.id.pager); } private void setAdapter(){ FragmentManager fragmentManager = getChildFragmentManager(); mViewPager.setAdapter(new SwipeHomeAdapter(fragmentManager)); } }
UTF-8
Java
1,159
java
SwipeHome.java
Java
[ { "context": "shoba.adapter.SwipeHomeAdapter;\n\n/**\n * Created by Diemo on 25/8/2017.\n */\n\npublic class SwipeHome extends", "end": 454, "score": 0.9996467232704163, "start": 449, "tag": "USERNAME", "value": "Diemo" } ]
null
[]
package com.mobile.diemo.soshoba.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mobile.diemo.soshoba.R; import com.mobile.diemo.soshoba.adapter.SwipeHomeAdapter; /** * Created by Diemo on 25/8/2017. */ public class SwipeHome extends Fragment { private ViewPager mViewPager; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.swipe_home, container, false); initialize(v); //setListeners(); setAdapter(); return v; } private void initialize(View v){ mViewPager = (ViewPager) v.findViewById(R.id.pager); } private void setAdapter(){ FragmentManager fragmentManager = getChildFragmentManager(); mViewPager.setAdapter(new SwipeHomeAdapter(fragmentManager)); } }
1,159
0.729077
0.720449
43
25.953489
26.199551
123
false
false
0
0
0
0
0
0
0.55814
false
false
7
fa5bcb32b806eeb63091650e427f886d5140f2ab
16,286,516,012,949
8426f61eb265f348755eec4f8275ec16a39707f0
/app/src/main/java/sd/code/morsalpos/common/GlobalConstants.java
77da560fb82b155c78eb337e3549897e9974615a
[]
no_license
NoamKhlaf/MorsalPOS
https://github.com/NoamKhlaf/MorsalPOS
ba8eca32fb702e31e92432b067adf2da6e9515a7
6ea9cf19d4919e8e474cfef517b17d9a9aab3a30
refs/heads/master
2020-03-22T19:49:54.454000
2018-06-26T09:21:46
2018-06-26T09:21:46
140,553,778
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sd.code.morsalpos.common; import com.vanstone.trans.api.struct.EmvAppList; import com.vanstone.trans.api.struct.EmvCapk; import com.vanstone.trans.api.struct.EmvParam; public class GlobalConstants { public static int isPinPad=1; //������� public static String CurAppDir = ""; public static PosCom PosCom = new PosCom(); public static byte[] BitMap = new byte[17]; public static int g_EmvFullOrSim; //����EMV�������̻��Ǽ������� 0:�������� 1: �������� public static int g_SwipedFlag; //���������Ƿ��⵽ˢ������IC�� 0:û�� 1:ˢ�� 2:��IC�� public static EmvParam stEmvParam = new EmvParam(); public static EmvCapk gltCurCapk = new EmvCapk(); // ��ǰ������CAPKԪ�� public static EmvAppList gltCurApp = new EmvAppList(); // ��ǰ������APP���� }
UTF-8
Java
956
java
GlobalConstants.java
Java
[]
null
[]
package sd.code.morsalpos.common; import com.vanstone.trans.api.struct.EmvAppList; import com.vanstone.trans.api.struct.EmvCapk; import com.vanstone.trans.api.struct.EmvParam; public class GlobalConstants { public static int isPinPad=1; //������� public static String CurAppDir = ""; public static PosCom PosCom = new PosCom(); public static byte[] BitMap = new byte[17]; public static int g_EmvFullOrSim; //����EMV�������̻��Ǽ������� 0:�������� 1: �������� public static int g_SwipedFlag; //���������Ƿ��⵽ˢ������IC�� 0:û�� 1:ˢ�� 2:��IC�� public static EmvParam stEmvParam = new EmvParam(); public static EmvCapk gltCurCapk = new EmvCapk(); // ��ǰ������CAPKԪ�� public static EmvAppList gltCurApp = new EmvAppList(); // ��ǰ������APP���� }
956
0.646518
0.636005
21
35.238094
28.324488
86
false
false
0
0
0
0
0
0
1.047619
false
false
7
a94521851d2505ec6d07d97c5b450c2f89525ff9
23,356,032,206,442
335a4999d94e028e5bfdaf4b00b7600e83d5d22e
/src/main/java/cn/tblack/work/reporter/gen/controller/GenDbController.java
90cdd6b23014e1dc684a09fdb206844333e166ca
[]
no_license
BinSSSSS/work-reporter
https://github.com/BinSSSSS/work-reporter
aaa973166c3cdf4594262f4d992aec6987d46c3b
5a4c297d46e1f64b2f9fbd2e8385ea4ee7a78f91
refs/heads/master
2022-07-03T10:03:53.114000
2019-12-19T06:34:10
2019-12-19T06:34:10
228,167,160
0
0
null
false
2022-06-29T17:50:55
2019-12-15T10:37:11
2019-12-19T06:34:24
2022-06-29T17:50:55
25,367
0
0
5
JavaScript
false
false
package cn.tblack.work.reporter.gen.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import cn.tblack.work.reporter.annotation.NeedAnyRole; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Controller @RequestMapping("/gen-db") @Api(tags = "生成数据源视图控制器") @NeedAnyRole public class GenDbController { @ApiOperation(value = "生成数据源页面") @GetMapping(value = "/index.html") public String index() { return "/gen/genDb"; } }
UTF-8
Java
627
java
GenDbController.java
Java
[]
null
[]
package cn.tblack.work.reporter.gen.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import cn.tblack.work.reporter.annotation.NeedAnyRole; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Controller @RequestMapping("/gen-db") @Api(tags = "生成数据源视图控制器") @NeedAnyRole public class GenDbController { @ApiOperation(value = "生成数据源页面") @GetMapping(value = "/index.html") public String index() { return "/gen/genDb"; } }
627
0.785835
0.785835
24
23.708334
20.509102
62
false
false
0
0
0
0
0
0
0.625
false
false
7
7672e6cdf68c4a34eee392b8c3833cb16c6a08fb
27,917,287,453,361
10a796d3d2b71dd1bc946c24665271e52136262d
/Java Stream API/src/sterams/Main.java
b70b1b7b4ac40ed8b6581a97e035a385195d22e4
[]
no_license
Rasim13/projects
https://github.com/Rasim13/projects
7d4c3af4a634356603c5924924bd208c40cb062d
8cdb7a68f7e62f526d009a4d906241faf7c64026
refs/heads/master
2023-08-27T04:35:19.181000
2021-11-11T19:21:06
2021-11-11T19:21:06
417,558,315
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sterams; import comparing.User; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; public class Main { public static void main(String[] args) { List<User> users = new ArrayList<>(); User user0 = new User(100L, "User1", "User1", 44); User user1 = new User(22L, "User2", "User2", 30); User user2 = new User(3L, "User3", "User3", 25); User user3 = new User(1L, "User4", "User4", 48); User user4 = new User(40L, "User5", "User5", 10); User user5 = new User(33L, "User6", "User6", 15); User user6 = new User(44L, "User7", "User7", 35); User user7 = new User(8L, "User8", "User8", 44); User user8 = new User(9L, "User9", "User9", 21); User user9 = new User(7L, "User10", "User10", 40); users.add(user0); users.add(user1); users.add(user2); users.add(user3); users.add(user4); users.add(user5); users.add(user6); users.add(user7); users.add(user8); users.add(user9); // распечатать id пользователей, у которых возраст больше 30 лет в отсортированном по возрасту порядке //поток пользователей Stream<User> userStream = users.stream(); Predicate<User> ageMoreThan30 = user -> user.getAge() > 30; //получить пользователей, у которых возраст больше 30 лет Stream<User> filteredUsers = userStream.filter(ageMoreThan30); Comparator<User> usersComparator = Comparator.comparingInt(User::getAge); // отсортировать пользователей по возрасту Stream<User> sortedUsers = filteredUsers.sorted(usersComparator); Function<User, Long> getIdFunction = user -> user.getId(); // получить id пользователей Stream<Long> ids = sortedUsers.map(getIdFunction); // распечатать id пользователей Consumer<Long> printId = id -> System.out.println(id); ids.forEach(printId); } }
UTF-8
Java
2,355
java
Main.java
Java
[]
null
[]
package sterams; import comparing.User; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; public class Main { public static void main(String[] args) { List<User> users = new ArrayList<>(); User user0 = new User(100L, "User1", "User1", 44); User user1 = new User(22L, "User2", "User2", 30); User user2 = new User(3L, "User3", "User3", 25); User user3 = new User(1L, "User4", "User4", 48); User user4 = new User(40L, "User5", "User5", 10); User user5 = new User(33L, "User6", "User6", 15); User user6 = new User(44L, "User7", "User7", 35); User user7 = new User(8L, "User8", "User8", 44); User user8 = new User(9L, "User9", "User9", 21); User user9 = new User(7L, "User10", "User10", 40); users.add(user0); users.add(user1); users.add(user2); users.add(user3); users.add(user4); users.add(user5); users.add(user6); users.add(user7); users.add(user8); users.add(user9); // распечатать id пользователей, у которых возраст больше 30 лет в отсортированном по возрасту порядке //поток пользователей Stream<User> userStream = users.stream(); Predicate<User> ageMoreThan30 = user -> user.getAge() > 30; //получить пользователей, у которых возраст больше 30 лет Stream<User> filteredUsers = userStream.filter(ageMoreThan30); Comparator<User> usersComparator = Comparator.comparingInt(User::getAge); // отсортировать пользователей по возрасту Stream<User> sortedUsers = filteredUsers.sorted(usersComparator); Function<User, Long> getIdFunction = user -> user.getId(); // получить id пользователей Stream<Long> ids = sortedUsers.map(getIdFunction); // распечатать id пользователей Consumer<Long> printId = id -> System.out.println(id); ids.forEach(printId); } }
2,355
0.6277
0.586385
62
33.354839
25.368317
110
false
false
0
0
0
0
0
0
1.16129
false
false
7
c6ae3c218b1e56b5686b6d3a4903124a8d923bb5
13,846,974,605,319
0a4a19cc2caf2477ab061b31efb386fe38f5dc68
/dubbo-api/src/main/java/com/llf/dubbo/service/HelloDubboService.java
67acd941f260a1c16beee4d90b82a00f598800ec
[]
no_license
phycholee/dubbo-demo
https://github.com/phycholee/dubbo-demo
6dc2b8cb8fff279264899862c260fc029f35475a
2ec3d35ea3ce74e0d7c231cff08fd8ac127e4a64
refs/heads/master
2022-06-22T00:34:06.398000
2020-03-26T08:58:49
2020-03-26T08:58:49
184,221,201
1
1
null
false
2022-06-17T02:06:54
2019-04-30T08:18:25
2020-03-26T08:58:52
2022-06-17T02:06:54
17
1
1
3
Java
false
false
package com.llf.dubbo.service; import com.llf.dubbo.dto.HelloDto; /** * @author: Oliver.li * @Description: * @date: 2019/1/17 15:08 */ public interface HelloDubboService { HelloDto getHello(Long id); }
UTF-8
Java
214
java
HelloDubboService.java
Java
[ { "context": "mport com.llf.dubbo.dto.HelloDto;\n\n/**\n * @author: Oliver.li\n * @Description:\n * @date: 2019/1/17 15:08\n */\npu", "end": 93, "score": 0.9997624158859253, "start": 84, "tag": "NAME", "value": "Oliver.li" } ]
null
[]
package com.llf.dubbo.service; import com.llf.dubbo.dto.HelloDto; /** * @author: Oliver.li * @Description: * @date: 2019/1/17 15:08 */ public interface HelloDubboService { HelloDto getHello(Long id); }
214
0.686916
0.635514
14
14.285714
14.134196
36
false
false
0
0
0
0
0
0
0.214286
false
false
7
b55ae57e60d0713d14a470a86aebcf79eae17076
3,951,369,949,730
81fe6bf5282d7a60fda43863815e62113e6d4ea8
/algoritmo12/src/test/java/br/ufg/inf/es/construcao/algoritmo12/Algoritmo12Test.java
dd29bb07c67c3c023dd5b4009e321acc2aad3bbb
[]
no_license
erickriger/CS2015-Algoritmos
https://github.com/erickriger/CS2015-Algoritmos
22a3c02136c8c7848cb8bf8ca31b0e80cfb7cdf7
895e520f830267d3a39701687f770dccb556ad37
refs/heads/master
2021-01-10T12:37:16.685000
2015-11-13T01:09:19
2015-11-13T01:09:19
45,276,011
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.ufg.inf.es.construcao.algoritmo12; import org.junit.Test; import static org.junit.Assert.*; public class Algoritmo12Test { @Test(expected = IllegalArgumentException.class) public void testAMenorQueB() { int a = 10; int b = 12; Algoritmo12.mdc(a, b); } @Test(expected = IllegalArgumentException.class) public void testBMenorOuIgualAZero() { int a = 10; int b = 0; Algoritmo12.mdc(a, b); } @Test public void testMdcNumerosIguais() { int a = 10; int b = 10; int expResult = 10; int result = Algoritmo12.mdc(a, b); assertEquals(expResult, result); } @Test public void testMdcNumerosDiferentes() { int a = 15; int b = 10; int expResult = 5; int result = Algoritmo12.mdc(a, b); assertEquals(expResult, result); } }
UTF-8
Java
907
java
Algoritmo12Test.java
Java
[]
null
[]
package br.ufg.inf.es.construcao.algoritmo12; import org.junit.Test; import static org.junit.Assert.*; public class Algoritmo12Test { @Test(expected = IllegalArgumentException.class) public void testAMenorQueB() { int a = 10; int b = 12; Algoritmo12.mdc(a, b); } @Test(expected = IllegalArgumentException.class) public void testBMenorOuIgualAZero() { int a = 10; int b = 0; Algoritmo12.mdc(a, b); } @Test public void testMdcNumerosIguais() { int a = 10; int b = 10; int expResult = 10; int result = Algoritmo12.mdc(a, b); assertEquals(expResult, result); } @Test public void testMdcNumerosDiferentes() { int a = 15; int b = 10; int expResult = 5; int result = Algoritmo12.mdc(a, b); assertEquals(expResult, result); } }
907
0.582139
0.549063
40
21.674999
16.433788
52
false
false
0
0
0
0
0
0
0.625
false
false
7
32e6f918d19d7544d172e20b01e7ae3e9c3918e0
32,203,664,837,412
f19c028ce3c38326e0348799cb67e0c6db659cd0
/src/main/java/com/hitachivantara/hcp/management/model/builder/ModifyNfsProtocolBuilder.java
2f567e55adbf02128269db2d6afe0e0cbc9965ab
[ "Apache-2.0" ]
permissive
pineconehouse/hitachivantara-java-sdk-hcp
https://github.com/pineconehouse/hitachivantara-java-sdk-hcp
d3bb65472217fe3ec8fadcb5b1e655369d8d04c7
b7081fe9a8ee8e5082b8b0f544cd8d9e5ec5ea3c
refs/heads/main
2023-03-26T21:13:38.112000
2021-03-24T09:53:25
2021-03-24T09:53:25
349,978,062
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (C) 2019 Rison Han * * 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.hitachivantara.hcp.management.model.builder; import com.hitachivantara.hcp.management.model.NfsProtocolSettings; public class ModifyNfsProtocolBuilder extends ModifyProtocolBuilder<ModifyNfsProtocolBuilder, NfsProtocolSettings> { public ModifyNfsProtocolBuilder() { super(new NfsProtocolSettings()); } public ModifyNfsProtocolBuilder withEnabled(boolean enabled) { settings.setEnabled(enabled); return this; } public ModifyNfsProtocolBuilder withGid(int gid) { settings.setGid(gid); return this; } public ModifyNfsProtocolBuilder withUid(int uid) { settings.setUid(uid); return this; } }
UTF-8
Java
1,814
java
ModifyNfsProtocolBuilder.java
Java
[ { "context": " \n * Copyright (C) 2019 Rison Han \n * ", "end": 111, "score": 0.9998078346252441, "start": 102, "tag": "NAME", "value": "Rison Han" } ]
null
[]
/* * Copyright (C) 2019 <NAME> * * 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.hitachivantara.hcp.management.model.builder; import com.hitachivantara.hcp.management.model.NfsProtocolSettings; public class ModifyNfsProtocolBuilder extends ModifyProtocolBuilder<ModifyNfsProtocolBuilder, NfsProtocolSettings> { public ModifyNfsProtocolBuilder() { super(new NfsProtocolSettings()); } public ModifyNfsProtocolBuilder withEnabled(boolean enabled) { settings.setEnabled(enabled); return this; } public ModifyNfsProtocolBuilder withGid(int gid) { settings.setGid(gid); return this; } public ModifyNfsProtocolBuilder withUid(int uid) { settings.setUid(uid); return this; } }
1,811
0.518192
0.513782
41
43.243904
34.956264
116
false
false
0
0
0
0
0
0
0.902439
false
false
7
64c4d292380bd0933f08abd5bb70624abe38109d
17,721,035,112,651
320dc3d877f36c97a78278f8f60a17f10859f6f6
/tiny-rpc/tiny-rpc-core/src/main/java/com/github/byference/tinyrpc/core/spring/TinyRpcBeanDefinitionScanner.java
90b6210093175712f3e60ce823a3c7efde1d8d59
[ "Apache-2.0" ]
permissive
byference/tiny-frameworks
https://github.com/byference/tiny-frameworks
a3631e0aac9281889c4ce5fad013fa8116948c19
1146cd7fbac620efb820bb19c1167e3f64c51b42
refs/heads/master
2023-06-26T08:42:48.091000
2022-08-22T13:52:39
2022-08-22T13:52:39
175,833,950
5
2
Apache-2.0
false
2023-06-14T22:30:42
2019-03-15T14:19:29
2022-08-22T13:54:44
2023-06-14T22:30:42
232
4
2
4
Java
false
false
package com.github.byference.tinyrpc.core.spring; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import java.util.Arrays; import java.util.Set; /** * TinyRpcBeanDefinitionScanner * * @author byference * @since 2019-12-28 */ @Slf4j public class TinyRpcBeanDefinitionScanner extends ClassPathBeanDefinitionScanner { public TinyRpcBeanDefinitionScanner(BeanDefinitionRegistry registry) { super(registry); } @Override protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages); if (beanDefinitions.isEmpty()) { log.warn("No target mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration."); } else { processBeanDefinitions(beanDefinitions); } return beanDefinitions; } private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) { beanDefinitions.forEach(holder -> { GenericBeanDefinition beanDefinition = (GenericBeanDefinition) holder.getBeanDefinition(); beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName()); beanDefinition.setBeanClass(TinyRpcFactoryBean.class); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); log.info("==> {} process finished", beanDefinition.getBeanClassName()); }); } /** * copy form {@code org.mybatis.spring.mapper.ClassPathMapperScanner#registerFilters} */ public void registerFilters() { // default include filter that accepts all classes addIncludeFilter((metadataReader, metadataReaderFactory) -> true); // exclude package-info.java addExcludeFilter((metadataReader, metadataReaderFactory) -> { String className = metadataReader.getClassMetadata().getClassName(); return className.endsWith("package-info"); }); } /** * {@inheritDoc} */ @Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent(); } }
UTF-8
Java
2,722
java
TinyRpcBeanDefinitionScanner.java
Java
[ { "context": "package com.github.byference.tinyrpc.core.spring;\n\nimport lombok.extern.slf4j.", "end": 28, "score": 0.9982757568359375, "start": 19, "tag": "USERNAME", "value": "byference" }, { "context": "\n/**\n * TinyRpcBeanDefinitionScanner\n *\n * @author byference\n * @since 2019-12-28\n */\n@Slf4j\npublic class Tiny", "end": 636, "score": 0.9994433522224426, "start": 627, "tag": "USERNAME", "value": "byference" } ]
null
[]
package com.github.byference.tinyrpc.core.spring; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.context.annotation.ClassPathBeanDefinitionScanner; import java.util.Arrays; import java.util.Set; /** * TinyRpcBeanDefinitionScanner * * @author byference * @since 2019-12-28 */ @Slf4j public class TinyRpcBeanDefinitionScanner extends ClassPathBeanDefinitionScanner { public TinyRpcBeanDefinitionScanner(BeanDefinitionRegistry registry) { super(registry); } @Override protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages); if (beanDefinitions.isEmpty()) { log.warn("No target mapper was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration."); } else { processBeanDefinitions(beanDefinitions); } return beanDefinitions; } private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) { beanDefinitions.forEach(holder -> { GenericBeanDefinition beanDefinition = (GenericBeanDefinition) holder.getBeanDefinition(); beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanDefinition.getBeanClassName()); beanDefinition.setBeanClass(TinyRpcFactoryBean.class); beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE); log.info("==> {} process finished", beanDefinition.getBeanClassName()); }); } /** * copy form {@code org.mybatis.spring.mapper.ClassPathMapperScanner#registerFilters} */ public void registerFilters() { // default include filter that accepts all classes addIncludeFilter((metadataReader, metadataReaderFactory) -> true); // exclude package-info.java addExcludeFilter((metadataReader, metadataReaderFactory) -> { String className = metadataReader.getClassMetadata().getClassName(); return className.endsWith("package-info"); }); } /** * {@inheritDoc} */ @Override protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) { return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent(); } }
2,722
0.729611
0.725569
72
36.805557
35.981724
136
false
false
0
0
0
0
0
0
0.402778
false
false
7
7ee687fbb511c210e6527020b0d9fefbd01f918a
26,929,445,014,243
5863a9ea2053b24a03d3e8410890a4c13d8af582
/src/main/java/com/ijavac/springboot/annotation/Authorization.java
d7cd31aa2f6f31467eeea8449592ec569e6aebba
[]
no_license
fishool/JavaStudy
https://github.com/fishool/JavaStudy
775041994a8ae118ce6ddb67d0fa34802f4fb77e
3490e182df169d2008cf0e7b820f5d532d0f199f
refs/heads/master
2021-01-16T05:28:41.625000
2021-01-15T03:31:06
2021-01-15T03:31:06
242,988,594
1
0
null
false
2020-10-13T19:51:30
2020-02-25T11:57:16
2020-10-13T09:28:32
2020-10-13T19:51:29
189,814
1
0
3
Java
false
false
package com.ijavac.springboot.annotation; import java.lang.annotation.*; /** * @ClassName : Authorization * @Description : 注解定义 * @Author : ijavac * @Date: 2020-07-01 15:36 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Authorization { String value() default ""; String[] role() default {""}; }
UTF-8
Java
371
java
Authorization.java
Java
[ { "context": " Authorization\n * @Description : 注解定义\n * @Author : ijavac\n * @Date: 2020-07-01 15:36\n */\n\n@Target({ElementT", "end": 151, "score": 0.9996762871742249, "start": 145, "tag": "USERNAME", "value": "ijavac" } ]
null
[]
package com.ijavac.springboot.annotation; import java.lang.annotation.*; /** * @ClassName : Authorization * @Description : 注解定义 * @Author : ijavac * @Date: 2020-07-01 15:36 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Authorization { String value() default ""; String[] role() default {""}; }
371
0.694215
0.661157
18
19.166666
14.170588
41
false
false
0
0
0
0
0
0
0.222222
false
false
7
5880a35544675a4c6b874d80dcbaeaadbf96b5fe
29,789,893,232,565
5f507a3a2df9da77d6cc8ba37fde230bc0148b6e
/src/main/java/com/qisen/mts/common/dao/base/EmpDao.java
ee3838e9ce910b0ada54b1197500d2981784750b
[]
no_license
Victoryxsl/mts-spa
https://github.com/Victoryxsl/mts-spa
2a4a7218aba8bc7293d225d30d9d3e5da9770675
0a7a55eef880dee5044280a2ce10c89e6bd6ebb1
refs/heads/master
2020-04-03T12:14:47.006000
2018-12-19T16:53:46
2018-12-19T16:53:46
155,245,936
1
0
null
true
2018-10-29T16:36:53
2018-10-29T16:36:53
2018-10-18T15:06:05
2018-10-18T15:06:03
534
0
0
0
null
false
null
package com.qisen.mts.common.dao.base; import java.util.List; import org.apache.ibatis.annotations.Param; import com.alibaba.fastjson.JSONObject; import com.qisen.mts.common.model.entity.base.Emp; import com.qisen.mts.common.model.request.BaseRequest; import com.qisen.mts.common.model.request.PageRequest; public interface EmpDao { /** * 查询门店员工(metaData用) * * @param sid * @return */ public List<Emp> list4MetaData(Integer sid); /** * 查询可预约的员工(美一客用) * * @param sid * @return */ public List<Emp> listBoookingEmp(Integer sid); /** * 查询门店员工 * * @param eid * @param body.sids 门店ID数组 * @return */ public List<Emp> list4Shop(@Param("eid") Integer eid, @Param("body") JSONObject body); public Integer create(Emp baseEmp) throws Exception;// 新增 public Integer delete(@Param("id") Integer id,@Param("eid") Integer eid) throws Exception;// 根据id删除 public Integer update(Emp baseEmp) throws Exception;// 更新字段 public Integer count(PageRequest<JSONObject> req);// 查询总个数 public List<Emp> list(PageRequest<JSONObject> req);// 查询结果集 public Emp find(Integer id);// 根据id查询单个对象 public Integer check(Emp baseEmp);// 查询个数 public Integer updatestatus(BaseRequest<JSONObject> req) throws Exception;// 更新字段 }
UTF-8
Java
1,396
java
EmpDao.java
Java
[]
null
[]
package com.qisen.mts.common.dao.base; import java.util.List; import org.apache.ibatis.annotations.Param; import com.alibaba.fastjson.JSONObject; import com.qisen.mts.common.model.entity.base.Emp; import com.qisen.mts.common.model.request.BaseRequest; import com.qisen.mts.common.model.request.PageRequest; public interface EmpDao { /** * 查询门店员工(metaData用) * * @param sid * @return */ public List<Emp> list4MetaData(Integer sid); /** * 查询可预约的员工(美一客用) * * @param sid * @return */ public List<Emp> listBoookingEmp(Integer sid); /** * 查询门店员工 * * @param eid * @param body.sids 门店ID数组 * @return */ public List<Emp> list4Shop(@Param("eid") Integer eid, @Param("body") JSONObject body); public Integer create(Emp baseEmp) throws Exception;// 新增 public Integer delete(@Param("id") Integer id,@Param("eid") Integer eid) throws Exception;// 根据id删除 public Integer update(Emp baseEmp) throws Exception;// 更新字段 public Integer count(PageRequest<JSONObject> req);// 查询总个数 public List<Emp> list(PageRequest<JSONObject> req);// 查询结果集 public Emp find(Integer id);// 根据id查询单个对象 public Integer check(Emp baseEmp);// 查询个数 public Integer updatestatus(BaseRequest<JSONObject> req) throws Exception;// 更新字段 }
1,396
0.713831
0.712242
56
21.464285
25.791723
100
false
false
0
0
0
0
0
0
1.017857
false
false
7
2c704ed668f2f369990b48a7d38a2f6f935004d8
10,995,116,330,277
2fea544bdf6d95bfa0561c2124700b85a61cb178
/dolaing-admin/src/main/java/com/dolaing/modular/api/OrderApi.java
54a7ff75c452f46a6d46ec4370baacff838c2c1b
[]
no_license
zx913726265/dolaing
https://github.com/zx913726265/dolaing
44c0a7ffb8023389ebfb064298144a7a3077da98
f5be5fef3b0cab0783485939316b99a53150462c
refs/heads/master
2021-09-22T01:44:23.295000
2018-09-05T04:19:30
2018-09-05T04:19:30
141,554,062
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dolaing.modular.api; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.mapper.Wrapper; import com.baomidou.mybatisplus.plugins.Page; import com.dolaing.core.base.tips.ErrorTip; import com.dolaing.core.common.annotion.AuthAccess; import com.dolaing.core.common.constant.Const; import com.dolaing.core.common.constant.GlobalData; import com.dolaing.core.support.HttpKit; import com.dolaing.core.util.TokenUtil; import com.dolaing.core.util.ToolUtil; import com.dolaing.modular.api.base.BaseApi; import com.dolaing.modular.mall.model.MallGoods; import com.dolaing.modular.mall.model.OrderGoods; import com.dolaing.modular.mall.model.OrderInfo; import com.dolaing.modular.mall.service.IOrderInfoService; import com.dolaing.modular.mall.vo.OrderInfoVo; import com.dolaing.modular.redis.service.RedisTokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; import java.util.Date; /** * Author: zx * Date: Created in 2018/08/3 11:44 * Copyright: Copyright (c) 2018 * Description: 订单 */ @RestController @RequestMapping("/dolaing") public class OrderApi extends BaseApi { @Autowired private IOrderInfoService orderInfoService; @Autowired private RedisTokenService redisTokenService; /** * 生成订单 */ @AuthAccess @PostMapping("/order/generateOrder") public Object publish(@RequestBody OrderInfoVo orderInfoVo) { String token = TokenUtil.getToken(HttpKit.getRequest()); String account = redisTokenService.getTokenModel(token).getAccount(); if (ToolUtil.isOneEmpty(orderInfoVo.getGoodsId(), orderInfoVo.getMobile(), orderInfoVo.getConsignee(), orderInfoVo.getAddress())) { return new ErrorTip(500, "订单生成异常,请稍候重试"); } Integer goodsId = orderInfoVo.getGoodsId(); MallGoods mallGoods = new MallGoods().selectById(goodsId); String orderSn = getOrderSn(); BigDecimal goodsAmount = orderInfoVo.getBuyerOrderAmount(); OrderInfo orderInfo = new OrderInfo(); orderInfo.setOrderSn(orderSn); orderInfo.setConsignee(orderInfoVo.getConsignee()); orderInfo.setMobile(orderInfoVo.getMobile()); orderInfo.setCountry(Const.CHINA_ID); orderInfo.setProvince(orderInfoVo.getProvince()); orderInfo.setCity(orderInfoVo.getCity()); orderInfo.setDistrict(orderInfoVo.getDistrict()); orderInfo.setAddress(orderInfoVo.getAddress()); orderInfo.setRemarks(orderInfoVo.getRemarks()); orderInfo.setGoodsAmount(goodsAmount); orderInfo.setBuyerOrderAmount(goodsAmount); orderInfo.setOrderStatus(1); orderInfo.setShippingStatus(0); orderInfo.setPayStatus(0);//付款状态:未付款 orderInfo.setPaymentId(0);//支付方式:证联支付 orderInfo.setSellerReceiveStatus(0);//收款状态:未收款 orderInfo.setFarmerReceiveStatus(0);//收款状态:未收款 orderInfo.setSellerMoneyReceived(BigDecimal.ZERO); //卖家应收金额 = 商品总额 * 10% orderInfo.setSellerReceivableAmount(goodsAmount.multiply(Const.SELLERRECEIVABLEAMOUNT_RATE)); orderInfo.setBuyerMoneyPaid(BigDecimal.ZERO); orderInfo.setFarmerMoneyReceived(BigDecimal.ZERO); //农户应收金额 = 商品总额 * 80% orderInfo.setFarmerReceivableAmount(goodsAmount.multiply(Const.FARMERRECEIVABLEAMOUNT_RATE)); orderInfo.setShopId(mallGoods.getShopId()); orderInfo.setUserId(account); orderInfo.setCreateBy(account); orderInfo.setCreateTime(new Date()); orderInfo.setShopId(orderInfoVo.getShopId()); orderInfoService.saveOrderInfo(orderInfo); Integer orderId = orderInfo.getId(); OrderGoods orderGoods = new OrderGoods(); orderGoods.setOrderId(orderId); orderGoods.setGoodsSn(mallGoods.getGoodsSn()); orderGoods.setGoodsName(mallGoods.getGoodsName()); orderGoods.setGoodsPrice(mallGoods.getShopPrice()); orderGoods.setGoodsId(goodsId); orderGoods.setGoodsNumber(orderInfoVo.getGoodsNum()); orderGoods.insert(); /*******下单 新的库存=库存-订单商品数量******/ mallGoods.setGoodsNumber(mallGoods.getGoodsNumber() - orderInfoVo.getGoodsNum()); mallGoods.updateById(); return render(orderId); } /** * 订单详情:确认状态下没有付款 */ @AuthAccess @PostMapping("/order/detail") public Object detail(@RequestParam String orderId) { OrderInfo orderInfo = new OrderInfo().selectById(orderId); String token = TokenUtil.getToken(HttpKit.getRequest()); String account = redisTokenService.getTokenModel(token).getAccount(); if (orderInfo != null) { if (!account.equals(orderInfo.getUserId())) { return new ErrorTip(500, "您没有权限查看该订单"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 1) { return new ErrorTip(500, "该订单已完成支付"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 0) { Integer province = orderInfo.getProvince(); Integer city = orderInfo.getCity(); Integer district = orderInfo.getDistrict(); if (province != null && city != null && district != null) { orderInfo.setAddress(GlobalData.AREAS.get(province).getChName() + GlobalData.AREAS.get(city).getChName() + GlobalData.AREAS.get(district).getChName() + orderInfo.getAddress()); } return render(orderInfo); } else { return new ErrorTip(500, "订单状态异常"); } } return new ErrorTip(500, "订单不存在"); } /** * 订单详情:确认状态下已付款 */ @AuthAccess @PostMapping("/order/detailPaied") public Object detailPaied(@RequestParam String orderId) { OrderInfo orderInfo = new OrderInfo().selectById(orderId); String token = TokenUtil.getToken(HttpKit.getRequest()); String account = redisTokenService.getTokenModel(token).getAccount(); if (orderInfo != null) { if (!account.equals(orderInfo.getUserId())) { return new ErrorTip(500, "您没有权限查看该订单"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 0) { return new ErrorTip(500, "该订单待付款"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 1) { Integer province = orderInfo.getProvince(); Integer city = orderInfo.getCity(); Integer district = orderInfo.getDistrict(); if (province != null && city != null && district != null) { orderInfo.setAddress(GlobalData.AREAS.get(province).getChName() + GlobalData.AREAS.get(city).getChName() + GlobalData.AREAS.get(district).getChName() + orderInfo.getAddress()); } return render(orderInfo); } else { return new ErrorTip(500, "订单状态异常"); } } return new ErrorTip(500, "订单不存在"); } /** * 生成订单号 * * @return orderSn */ public String getOrderSn() { String orderSn; String maxOrderSn; OrderInfo orderInfo; Wrapper<OrderInfo> wrapper = new EntityWrapper<>(); wrapper.orderBy("order_sn", false); Page<OrderInfo> page = new Page<>(1, 1); Page<OrderInfo> orders = orderInfoService.selectPage(page, wrapper); if (orders != null && orders.getRecords() != null && orders.getRecords().size() > 0) { orderInfo = orders.getRecords().get(0); maxOrderSn = orderInfo.getOrderSn().substring(3, orderInfo.getOrderSn().length()); Integer temp = Integer.valueOf(maxOrderSn); orderSn = "DLY" + String.format("%08d", temp + 1); } else { orderSn = "DLY00000001"; } System.out.println("orderSn=" + orderSn); return orderSn; } }
UTF-8
Java
8,406
java
OrderApi.java
Java
[ { "context": "BigDecimal;\nimport java.util.Date;\n\n/**\n * Author: zx\n * Date: Created in 2018/08/3 11:44\n * Copyright:", "end": 1041, "score": 0.9802230000495911, "start": 1039, "tag": "USERNAME", "value": "zx" } ]
null
[]
package com.dolaing.modular.api; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.mapper.Wrapper; import com.baomidou.mybatisplus.plugins.Page; import com.dolaing.core.base.tips.ErrorTip; import com.dolaing.core.common.annotion.AuthAccess; import com.dolaing.core.common.constant.Const; import com.dolaing.core.common.constant.GlobalData; import com.dolaing.core.support.HttpKit; import com.dolaing.core.util.TokenUtil; import com.dolaing.core.util.ToolUtil; import com.dolaing.modular.api.base.BaseApi; import com.dolaing.modular.mall.model.MallGoods; import com.dolaing.modular.mall.model.OrderGoods; import com.dolaing.modular.mall.model.OrderInfo; import com.dolaing.modular.mall.service.IOrderInfoService; import com.dolaing.modular.mall.vo.OrderInfoVo; import com.dolaing.modular.redis.service.RedisTokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; import java.util.Date; /** * Author: zx * Date: Created in 2018/08/3 11:44 * Copyright: Copyright (c) 2018 * Description: 订单 */ @RestController @RequestMapping("/dolaing") public class OrderApi extends BaseApi { @Autowired private IOrderInfoService orderInfoService; @Autowired private RedisTokenService redisTokenService; /** * 生成订单 */ @AuthAccess @PostMapping("/order/generateOrder") public Object publish(@RequestBody OrderInfoVo orderInfoVo) { String token = TokenUtil.getToken(HttpKit.getRequest()); String account = redisTokenService.getTokenModel(token).getAccount(); if (ToolUtil.isOneEmpty(orderInfoVo.getGoodsId(), orderInfoVo.getMobile(), orderInfoVo.getConsignee(), orderInfoVo.getAddress())) { return new ErrorTip(500, "订单生成异常,请稍候重试"); } Integer goodsId = orderInfoVo.getGoodsId(); MallGoods mallGoods = new MallGoods().selectById(goodsId); String orderSn = getOrderSn(); BigDecimal goodsAmount = orderInfoVo.getBuyerOrderAmount(); OrderInfo orderInfo = new OrderInfo(); orderInfo.setOrderSn(orderSn); orderInfo.setConsignee(orderInfoVo.getConsignee()); orderInfo.setMobile(orderInfoVo.getMobile()); orderInfo.setCountry(Const.CHINA_ID); orderInfo.setProvince(orderInfoVo.getProvince()); orderInfo.setCity(orderInfoVo.getCity()); orderInfo.setDistrict(orderInfoVo.getDistrict()); orderInfo.setAddress(orderInfoVo.getAddress()); orderInfo.setRemarks(orderInfoVo.getRemarks()); orderInfo.setGoodsAmount(goodsAmount); orderInfo.setBuyerOrderAmount(goodsAmount); orderInfo.setOrderStatus(1); orderInfo.setShippingStatus(0); orderInfo.setPayStatus(0);//付款状态:未付款 orderInfo.setPaymentId(0);//支付方式:证联支付 orderInfo.setSellerReceiveStatus(0);//收款状态:未收款 orderInfo.setFarmerReceiveStatus(0);//收款状态:未收款 orderInfo.setSellerMoneyReceived(BigDecimal.ZERO); //卖家应收金额 = 商品总额 * 10% orderInfo.setSellerReceivableAmount(goodsAmount.multiply(Const.SELLERRECEIVABLEAMOUNT_RATE)); orderInfo.setBuyerMoneyPaid(BigDecimal.ZERO); orderInfo.setFarmerMoneyReceived(BigDecimal.ZERO); //农户应收金额 = 商品总额 * 80% orderInfo.setFarmerReceivableAmount(goodsAmount.multiply(Const.FARMERRECEIVABLEAMOUNT_RATE)); orderInfo.setShopId(mallGoods.getShopId()); orderInfo.setUserId(account); orderInfo.setCreateBy(account); orderInfo.setCreateTime(new Date()); orderInfo.setShopId(orderInfoVo.getShopId()); orderInfoService.saveOrderInfo(orderInfo); Integer orderId = orderInfo.getId(); OrderGoods orderGoods = new OrderGoods(); orderGoods.setOrderId(orderId); orderGoods.setGoodsSn(mallGoods.getGoodsSn()); orderGoods.setGoodsName(mallGoods.getGoodsName()); orderGoods.setGoodsPrice(mallGoods.getShopPrice()); orderGoods.setGoodsId(goodsId); orderGoods.setGoodsNumber(orderInfoVo.getGoodsNum()); orderGoods.insert(); /*******下单 新的库存=库存-订单商品数量******/ mallGoods.setGoodsNumber(mallGoods.getGoodsNumber() - orderInfoVo.getGoodsNum()); mallGoods.updateById(); return render(orderId); } /** * 订单详情:确认状态下没有付款 */ @AuthAccess @PostMapping("/order/detail") public Object detail(@RequestParam String orderId) { OrderInfo orderInfo = new OrderInfo().selectById(orderId); String token = TokenUtil.getToken(HttpKit.getRequest()); String account = redisTokenService.getTokenModel(token).getAccount(); if (orderInfo != null) { if (!account.equals(orderInfo.getUserId())) { return new ErrorTip(500, "您没有权限查看该订单"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 1) { return new ErrorTip(500, "该订单已完成支付"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 0) { Integer province = orderInfo.getProvince(); Integer city = orderInfo.getCity(); Integer district = orderInfo.getDistrict(); if (province != null && city != null && district != null) { orderInfo.setAddress(GlobalData.AREAS.get(province).getChName() + GlobalData.AREAS.get(city).getChName() + GlobalData.AREAS.get(district).getChName() + orderInfo.getAddress()); } return render(orderInfo); } else { return new ErrorTip(500, "订单状态异常"); } } return new ErrorTip(500, "订单不存在"); } /** * 订单详情:确认状态下已付款 */ @AuthAccess @PostMapping("/order/detailPaied") public Object detailPaied(@RequestParam String orderId) { OrderInfo orderInfo = new OrderInfo().selectById(orderId); String token = TokenUtil.getToken(HttpKit.getRequest()); String account = redisTokenService.getTokenModel(token).getAccount(); if (orderInfo != null) { if (!account.equals(orderInfo.getUserId())) { return new ErrorTip(500, "您没有权限查看该订单"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 0) { return new ErrorTip(500, "该订单待付款"); } if (orderInfo.getOrderStatus() == 1 && orderInfo.getPayStatus() == 1) { Integer province = orderInfo.getProvince(); Integer city = orderInfo.getCity(); Integer district = orderInfo.getDistrict(); if (province != null && city != null && district != null) { orderInfo.setAddress(GlobalData.AREAS.get(province).getChName() + GlobalData.AREAS.get(city).getChName() + GlobalData.AREAS.get(district).getChName() + orderInfo.getAddress()); } return render(orderInfo); } else { return new ErrorTip(500, "订单状态异常"); } } return new ErrorTip(500, "订单不存在"); } /** * 生成订单号 * * @return orderSn */ public String getOrderSn() { String orderSn; String maxOrderSn; OrderInfo orderInfo; Wrapper<OrderInfo> wrapper = new EntityWrapper<>(); wrapper.orderBy("order_sn", false); Page<OrderInfo> page = new Page<>(1, 1); Page<OrderInfo> orders = orderInfoService.selectPage(page, wrapper); if (orders != null && orders.getRecords() != null && orders.getRecords().size() > 0) { orderInfo = orders.getRecords().get(0); maxOrderSn = orderInfo.getOrderSn().substring(3, orderInfo.getOrderSn().length()); Integer temp = Integer.valueOf(maxOrderSn); orderSn = "DLY" + String.format("%08d", temp + 1); } else { orderSn = "DLY00000001"; } System.out.println("orderSn=" + orderSn); return orderSn; } }
8,406
0.650037
0.640606
192
40.96875
29.423967
196
false
false
0
0
0
0
0
0
0.661458
false
false
7
34be115f80dd62d697d1f33684e48ef955726cd2
5,239,860,163,777
d130a5d11726eb06162ba26257bc9f7cb7c2888f
/app/src/main/java/com/android/agendacontactos/Database/SQL.java
1a8d5b2ba7717decd3537d8d40a3a9c004b826f4
[]
no_license
bverset/alc
https://github.com/bverset/alc
db49eba3c5368e303618a881d446bd65c8dd6b3e
b96f560b8c92d52354d60828b74d96505cc297d6
refs/heads/master
2021-01-16T22:02:37.336000
2016-10-19T09:12:04
2016-10-19T09:12:04
45,150,567
0
0
null
true
2015-10-29T00:41:01
2015-10-29T00:41:00
2015-10-27T01:50:43
2015-10-29T00:33:39
0
0
0
0
null
null
null
package com.android.agendacontactos.Database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import com.android.agendacontactos.model.Contact; import java.util.ArrayList; /** * Created by James on 29/10/15. */ public class SQL extends SQLiteOpenHelper { private final static String DATABASE_NAME = "nombrebd"; private final static int DATABASE_VERSION = 1; public SQL(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_CONTACT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } private String TABLE_CONTACT = "contact"; // nombre tabla private String CONTACT_ID = "_id"; private String CONTACT_NAME = "_name"; private String CONTACT_EMAIL = "_email"; private String CONTACT_CEL = "_cel"; private String CONTACT_PHONE = "_phone"; private String CONTACT_PICTURE = "_picture"; private String CONTACT_GROUP = "_group"; private String CREATE_TABLE_CONTACT = "CREATE TABLE " + TABLE_CONTACT + " (" + CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + CONTACT_NAME + " VARCHAR(30), " + CONTACT_EMAIL + " VARCHAR(30), " + CONTACT_CEL + " VARCHAR(30), " + CONTACT_PHONE + " VARCHAR(30), " + CONTACT_PICTURE + " VARCHAR(30), " + CONTACT_GROUP + " VARCHAR(30));"; private String DROP_TABLE_CONTACT = "DROP TABLE IF EXISTS '" + TABLE_CONTACT + "'"; private final String[] COLUMNS = {CONTACT_ID, CONTACT_NAME, CONTACT_EMAIL, CONTACT_CEL, CONTACT_PHONE, CONTACT_PICTURE, CONTACT_GROUP}; private ContentValues createContent(Contact contact){ ContentValues values = new ContentValues(); values.put(CONTACT_NAME, contact.getName()); values.put(CONTACT_EMAIL, contact.getEmail()); values.put(CONTACT_CEL, contact.getCel()); values.put(CONTACT_PHONE, contact.getPhone()); values.put(CONTACT_PICTURE, contact.getPicture()); values.put(CONTACT_GROUP, contact.getGroup()); return values; } public long insertContact(Contact contact){ long rowId = -1; SQLiteDatabase db = getWritableDatabase(); try { rowId = db.insert(TABLE_CONTACT, null, createContent(contact)); db.close(); }catch (SQLiteException e){ db.close(); } return rowId; } public boolean updateContact(Contact contact){ long rowId = -1; SQLiteDatabase db = getWritableDatabase(); try { rowId = db.update( TABLE_CONTACT, createContent(contact), CONTACT_ID + "=" + contact.getId(), null ); }catch (SQLiteException e){} db.close(); return rowId > 0; } public boolean deleteContact(long contactId){ long rowId = -1; SQLiteDatabase db = getWritableDatabase(); try { rowId = db.delete( TABLE_CONTACT, CONTACT_ID + "=" + contactId, null ); }catch (SQLiteException e){} db.close(); return rowId > 0; } public Contact getContact(long contactId){ SQLiteDatabase db = getReadableDatabase(); Cursor cursor = null; Contact contact = null; try { cursor = db.query(TABLE_CONTACT, COLUMNS, CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null, null, null, null ); if(cursor != null && cursor.getCount() > 0){ cursor.moveToFirst(); contact = new Contact(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6)); cursor.close(); } }catch (SQLiteException e){ if(cursor != null){ cursor.close(); } } db.close(); return contact; } //obligatorio public ArrayList<Contact> getAll(){ ArrayList<Contact> al = new ArrayList<>(); SQLiteDatabase db = getWritableDatabase(); Cursor cursor = null; Contact contact = null; try { cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACT, null); if(cursor != null && cursor.getCount() > 0){ cursor.moveToFirst(); do { contact = new Contact(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6)); al.add(contact); } while (cursor.moveToNext()); cursor.close(); } }catch (SQLiteException e){} if(cursor != null){ cursor.close(); } db.close(); return al; } //opcional public long checkContact(String nombre){ //true si es existe long rowId = -1; SQLiteDatabase db = getWritableDatabase(); Cursor cursor = null; try { cursor = db.query(TABLE_CONTACT, COLUMNS, CONTACT_NAME + "=?", new String[]{nombre}, null, null, null, null ); //cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACT + " where "+ CONTACT_NAME + " = " + nombre, null); if(cursor != null && cursor.getCount() > 0){ cursor.moveToFirst(); rowId = cursor.getLong(0); cursor.close(); } }catch (SQLiteException e){} db.close(); return rowId; } }
UTF-8
Java
6,456
java
SQL.java
Java
[ { "context": "t;\n\nimport java.util.ArrayList;\n\n/**\n * Created by James on 29/10/15.\n */\npublic class SQL extends SQLiteO", "end": 397, "score": 0.8684741854667664, "start": 392, "tag": "NAME", "value": "James" } ]
null
[]
package com.android.agendacontactos.Database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import com.android.agendacontactos.model.Contact; import java.util.ArrayList; /** * Created by James on 29/10/15. */ public class SQL extends SQLiteOpenHelper { private final static String DATABASE_NAME = "nombrebd"; private final static int DATABASE_VERSION = 1; public SQL(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_CONTACT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } private String TABLE_CONTACT = "contact"; // nombre tabla private String CONTACT_ID = "_id"; private String CONTACT_NAME = "_name"; private String CONTACT_EMAIL = "_email"; private String CONTACT_CEL = "_cel"; private String CONTACT_PHONE = "_phone"; private String CONTACT_PICTURE = "_picture"; private String CONTACT_GROUP = "_group"; private String CREATE_TABLE_CONTACT = "CREATE TABLE " + TABLE_CONTACT + " (" + CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + CONTACT_NAME + " VARCHAR(30), " + CONTACT_EMAIL + " VARCHAR(30), " + CONTACT_CEL + " VARCHAR(30), " + CONTACT_PHONE + " VARCHAR(30), " + CONTACT_PICTURE + " VARCHAR(30), " + CONTACT_GROUP + " VARCHAR(30));"; private String DROP_TABLE_CONTACT = "DROP TABLE IF EXISTS '" + TABLE_CONTACT + "'"; private final String[] COLUMNS = {CONTACT_ID, CONTACT_NAME, CONTACT_EMAIL, CONTACT_CEL, CONTACT_PHONE, CONTACT_PICTURE, CONTACT_GROUP}; private ContentValues createContent(Contact contact){ ContentValues values = new ContentValues(); values.put(CONTACT_NAME, contact.getName()); values.put(CONTACT_EMAIL, contact.getEmail()); values.put(CONTACT_CEL, contact.getCel()); values.put(CONTACT_PHONE, contact.getPhone()); values.put(CONTACT_PICTURE, contact.getPicture()); values.put(CONTACT_GROUP, contact.getGroup()); return values; } public long insertContact(Contact contact){ long rowId = -1; SQLiteDatabase db = getWritableDatabase(); try { rowId = db.insert(TABLE_CONTACT, null, createContent(contact)); db.close(); }catch (SQLiteException e){ db.close(); } return rowId; } public boolean updateContact(Contact contact){ long rowId = -1; SQLiteDatabase db = getWritableDatabase(); try { rowId = db.update( TABLE_CONTACT, createContent(contact), CONTACT_ID + "=" + contact.getId(), null ); }catch (SQLiteException e){} db.close(); return rowId > 0; } public boolean deleteContact(long contactId){ long rowId = -1; SQLiteDatabase db = getWritableDatabase(); try { rowId = db.delete( TABLE_CONTACT, CONTACT_ID + "=" + contactId, null ); }catch (SQLiteException e){} db.close(); return rowId > 0; } public Contact getContact(long contactId){ SQLiteDatabase db = getReadableDatabase(); Cursor cursor = null; Contact contact = null; try { cursor = db.query(TABLE_CONTACT, COLUMNS, CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null, null, null, null ); if(cursor != null && cursor.getCount() > 0){ cursor.moveToFirst(); contact = new Contact(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6)); cursor.close(); } }catch (SQLiteException e){ if(cursor != null){ cursor.close(); } } db.close(); return contact; } //obligatorio public ArrayList<Contact> getAll(){ ArrayList<Contact> al = new ArrayList<>(); SQLiteDatabase db = getWritableDatabase(); Cursor cursor = null; Contact contact = null; try { cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACT, null); if(cursor != null && cursor.getCount() > 0){ cursor.moveToFirst(); do { contact = new Contact(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6)); al.add(contact); } while (cursor.moveToNext()); cursor.close(); } }catch (SQLiteException e){} if(cursor != null){ cursor.close(); } db.close(); return al; } //opcional public long checkContact(String nombre){ //true si es existe long rowId = -1; SQLiteDatabase db = getWritableDatabase(); Cursor cursor = null; try { cursor = db.query(TABLE_CONTACT, COLUMNS, CONTACT_NAME + "=?", new String[]{nombre}, null, null, null, null ); //cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACT + " where "+ CONTACT_NAME + " = " + nombre, null); if(cursor != null && cursor.getCount() > 0){ cursor.moveToFirst(); rowId = cursor.getLong(0); cursor.close(); } }catch (SQLiteException e){} db.close(); return rowId; } }
6,456
0.529895
0.523234
228
27.320175
22.77422
118
false
false
0
0
0
0
0
0
0.614035
false
false
7
8917d642ca124fcf1062baeeb0ad5f5638047506
25,005,299,647,483
a850de9fb115ce201b53e535de9cea099d49b3f9
/core/src/com/vhelium/lotig/scene/gamescene/spells/darkpriest/SpellShadowCurse.java
63cc1a1c8250e82cca17067770f35cdaab03f028
[]
no_license
Vhelium/lotig
https://github.com/Vhelium/lotig
7e491e900d49013ba7d4291e796f1f8ded31b140
ec705be2893956580c53c368eac3a2ebb941a221
refs/heads/master
2021-01-05T23:20:20.071000
2014-10-24T22:28:17
2014-10-24T22:28:17
241,164,835
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vhelium.lotig.scene.gamescene.spells.darkpriest; import com.vhelium.lotig.scene.connection.DataPacket; import com.vhelium.lotig.scene.connection.MessageType; import com.vhelium.lotig.scene.gamescene.SoundFile; import com.vhelium.lotig.scene.gamescene.server.EntityServerMixin; import com.vhelium.lotig.scene.gamescene.server.Realm; import com.vhelium.lotig.scene.gamescene.spells.Spell; public class SpellShadowCurse extends Spell { public static String name = "Shadow Curse"; public static String effectAsset = "Shadow Curse"; public static float cooldownBase = 20000f; public static float cooldownPerLevel = 500f; public static float manaCostBase = 180; public static float manaCostPerLevel = 10; public static int aoeRadiusBase = 150; public static int aoeRadiusPerLevel = 7; public static int durationBase = 10000; public static int durationPerLevel = 200; public static float damageBase = 360; public static float damagePerLevel = 75; public SpellShadowCurse() { instantCast = true; } //>>>>>>>>>>>>>>>> CLIENT vvv >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> @Override public String getName() { return name; } @Override public String getDescription() { return "You curse the nearest enemy with a dark curse dealing absolute damage over time.\n\nDamage: " + getDamage(getLevel()) + " over " + (getDuration(getLevel()) / 1000) + " seconds\nRadius: " + getAoeRadius(getLevel()); } @Override public float getManaCost() { return getManaCostStatic(getLevel()); } @Override public float getCooldown() { return cooldownBase + cooldownPerLevel * (getLevel() - 1); } @Override public DataPacket generateRequest(float x, float y, float rotation, float dirX, float dirY) { DataPacket dp = new DataPacket(); dp.setInt(MessageType.MSG_SPELL_REQUEST); dp.setString(name); dp.setInt(getLevel()); dp.setFloat(x); dp.setFloat(y); return dp; } //>>>>>>>>>>>>>>>> SERVER vvv >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> public static void activate(int shooterId, int spellLevel, DataPacket dp, Realm realm) { if(realm.getPlayer(shooterId) == null) return; int level = spellLevel; float x = dp.getFloat(); float y = dp.getFloat(); realm.playEffect(x, y, getAoeRadius(level) * 2, getAoeRadius(level) * 2, effectAsset, 0); EntityServerMixin entity = realm.getNearestHostileEntity(x, y, getAoeRadius(spellLevel), realm.getPlayer(shooterId).getTeamNr()); if(entity != null) { realm.playSound(shooterId, SoundFile.spell_cursed); realm.requestCondition(entity.Nr, name, "Cursed", getDamage(spellLevel), getDuration(spellLevel), false, effectAsset, System.currentTimeMillis()); } else realm.playSound(shooterId, SoundFile.spell_failed); } public static float getManaCostStatic(int level) { return manaCostBase + manaCostPerLevel * (level - 1); } public static int getAoeRadius(int level) { return aoeRadiusBase + aoeRadiusPerLevel * (level - 1); } public static int getDuration(int level) { return durationBase + durationPerLevel * (level - 1); } public static int getDamage(int level) { return (int) (damageBase + damagePerLevel * (level - 1)); } }
UTF-8
Java
3,240
java
SpellShadowCurse.java
Java
[]
null
[]
package com.vhelium.lotig.scene.gamescene.spells.darkpriest; import com.vhelium.lotig.scene.connection.DataPacket; import com.vhelium.lotig.scene.connection.MessageType; import com.vhelium.lotig.scene.gamescene.SoundFile; import com.vhelium.lotig.scene.gamescene.server.EntityServerMixin; import com.vhelium.lotig.scene.gamescene.server.Realm; import com.vhelium.lotig.scene.gamescene.spells.Spell; public class SpellShadowCurse extends Spell { public static String name = "Shadow Curse"; public static String effectAsset = "Shadow Curse"; public static float cooldownBase = 20000f; public static float cooldownPerLevel = 500f; public static float manaCostBase = 180; public static float manaCostPerLevel = 10; public static int aoeRadiusBase = 150; public static int aoeRadiusPerLevel = 7; public static int durationBase = 10000; public static int durationPerLevel = 200; public static float damageBase = 360; public static float damagePerLevel = 75; public SpellShadowCurse() { instantCast = true; } //>>>>>>>>>>>>>>>> CLIENT vvv >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> @Override public String getName() { return name; } @Override public String getDescription() { return "You curse the nearest enemy with a dark curse dealing absolute damage over time.\n\nDamage: " + getDamage(getLevel()) + " over " + (getDuration(getLevel()) / 1000) + " seconds\nRadius: " + getAoeRadius(getLevel()); } @Override public float getManaCost() { return getManaCostStatic(getLevel()); } @Override public float getCooldown() { return cooldownBase + cooldownPerLevel * (getLevel() - 1); } @Override public DataPacket generateRequest(float x, float y, float rotation, float dirX, float dirY) { DataPacket dp = new DataPacket(); dp.setInt(MessageType.MSG_SPELL_REQUEST); dp.setString(name); dp.setInt(getLevel()); dp.setFloat(x); dp.setFloat(y); return dp; } //>>>>>>>>>>>>>>>> SERVER vvv >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> public static void activate(int shooterId, int spellLevel, DataPacket dp, Realm realm) { if(realm.getPlayer(shooterId) == null) return; int level = spellLevel; float x = dp.getFloat(); float y = dp.getFloat(); realm.playEffect(x, y, getAoeRadius(level) * 2, getAoeRadius(level) * 2, effectAsset, 0); EntityServerMixin entity = realm.getNearestHostileEntity(x, y, getAoeRadius(spellLevel), realm.getPlayer(shooterId).getTeamNr()); if(entity != null) { realm.playSound(shooterId, SoundFile.spell_cursed); realm.requestCondition(entity.Nr, name, "Cursed", getDamage(spellLevel), getDuration(spellLevel), false, effectAsset, System.currentTimeMillis()); } else realm.playSound(shooterId, SoundFile.spell_failed); } public static float getManaCostStatic(int level) { return manaCostBase + manaCostPerLevel * (level - 1); } public static int getAoeRadius(int level) { return aoeRadiusBase + aoeRadiusPerLevel * (level - 1); } public static int getDuration(int level) { return durationBase + durationPerLevel * (level - 1); } public static int getDamage(int level) { return (int) (damageBase + damagePerLevel * (level - 1)); } }
3,240
0.695988
0.683025
116
26.931034
34.383419
224
false
false
0
0
0
0
0
0
1.810345
false
false
7
83e196da5eaa6b91e21fb5e0871099e7c3c0c508
14,482,629,724,916
5b873632d262b3cb50677164c4c5dbf2c41e9f44
/Chess Game/src/Chess/LoadGameMenu.java
9f845a4673653e93b22b1cdce8d27eea36290acc
[]
no_license
vkoutha/Chess
https://github.com/vkoutha/Chess
41a3adf55588f1da4023720dcb4f472133f9bafe
08b61d5f5a2aa771f34ec20b985b5db200111ce9
refs/heads/master
2021-10-09T18:28:28.552000
2019-01-02T04:34:18
2019-01-02T04:34:18
156,449,588
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Chess; import java.awt.Color; import java.awt.Font; import java.awt.Image; import java.io.File; import java.util.ArrayList; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoadGameMenu { JFrame frame; File[] gameFiles; ArrayList<String> gameFileNames; public LoadGameMenu() { Game.frame.setVisible(false); gameFiles = GameData.gameFiles; gameFileNames = new ArrayList<String>(); for (File file : gameFiles) { gameFileNames.add(file.getName().replace(".txt", "")); } frame = new JFrame("Load Game"); frame.setIconImage(GameData.frameIcon); frame.getContentPane().setBackground(Color.ORANGE); frame.setSize(500, 400); frame.setVisible(true); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel lblLoadGame = new JLabel("Load Game"); lblLoadGame.setFont(new Font("Snap ITC", Font.BOLD, 40)); lblLoadGame.setBounds(124, 34, 289, 34); frame.getContentPane().add(lblLoadGame); JList list = new JList(gameFileNames.toArray()); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setBounds(378, 310, -261, -147); list.setBackground(Color.YELLOW); JScrollPane listScroll = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); listScroll.add(list); listScroll.setBounds(152, 150, 190, 190); listScroll.setViewportView(list); listScroll.setForeground(Color.LIGHT_GRAY); listScroll.setBackground(Color.LIGHT_GRAY); frame.getContentPane().add(listScroll); JButton btnLoad = new JButton(); btnLoad.setFont(new Font("Snap ITC", Font.BOLD, 20)); btnLoad.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("load.png")).getImage().getScaledInstance(80, 50, Image.SCALE_DEFAULT))); removeBackground(btnLoad); btnLoad.setBounds(184, 82, 155, 55); btnLoad.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(list.getSelectedValue() == null) { JOptionPane.showMessageDialog(null, "Please select a game to load!", "Error!", JOptionPane.ERROR_MESSAGE); return; } for(File file : gameFiles) { if((list.getSelectedValue() + ".txt").equals(file.getName())) { Game.frame.setVisible(true); Game.gameState = GameData.gameState.IN_GAME; Game.loadGameFile(file); frame.dispose(); } } } }); frame.getContentPane().add(btnLoad); JButton backButton = new JButton(); backButton.setBounds(0, -5, 100, 100); backButton.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("backArrow.png")).getImage().getScaledInstance(60, 50, Image.SCALE_DEFAULT))); removeBackground(backButton); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub Game.frame.setVisible(true); frame.dispose(); } }); frame.add(backButton); } public void deleteGame() { } public void removeBackground(JButton button) { button.setContentAreaFilled(false); button.setFocusPainted(false); button.setBorderPainted(false); } }
UTF-8
Java
3,724
java
LoadGameMenu.java
Java
[]
null
[]
package Chess; import java.awt.Color; import java.awt.Font; import java.awt.Image; import java.io.File; import java.util.ArrayList; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoadGameMenu { JFrame frame; File[] gameFiles; ArrayList<String> gameFileNames; public LoadGameMenu() { Game.frame.setVisible(false); gameFiles = GameData.gameFiles; gameFileNames = new ArrayList<String>(); for (File file : gameFiles) { gameFileNames.add(file.getName().replace(".txt", "")); } frame = new JFrame("Load Game"); frame.setIconImage(GameData.frameIcon); frame.getContentPane().setBackground(Color.ORANGE); frame.setSize(500, 400); frame.setVisible(true); frame.getContentPane().setLayout(null); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel lblLoadGame = new JLabel("Load Game"); lblLoadGame.setFont(new Font("Snap ITC", Font.BOLD, 40)); lblLoadGame.setBounds(124, 34, 289, 34); frame.getContentPane().add(lblLoadGame); JList list = new JList(gameFileNames.toArray()); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setBounds(378, 310, -261, -147); list.setBackground(Color.YELLOW); JScrollPane listScroll = new JScrollPane(list, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); listScroll.add(list); listScroll.setBounds(152, 150, 190, 190); listScroll.setViewportView(list); listScroll.setForeground(Color.LIGHT_GRAY); listScroll.setBackground(Color.LIGHT_GRAY); frame.getContentPane().add(listScroll); JButton btnLoad = new JButton(); btnLoad.setFont(new Font("Snap ITC", Font.BOLD, 20)); btnLoad.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("load.png")).getImage().getScaledInstance(80, 50, Image.SCALE_DEFAULT))); removeBackground(btnLoad); btnLoad.setBounds(184, 82, 155, 55); btnLoad.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(list.getSelectedValue() == null) { JOptionPane.showMessageDialog(null, "Please select a game to load!", "Error!", JOptionPane.ERROR_MESSAGE); return; } for(File file : gameFiles) { if((list.getSelectedValue() + ".txt").equals(file.getName())) { Game.frame.setVisible(true); Game.gameState = GameData.gameState.IN_GAME; Game.loadGameFile(file); frame.dispose(); } } } }); frame.getContentPane().add(btnLoad); JButton backButton = new JButton(); backButton.setBounds(0, -5, 100, 100); backButton.setIcon(new ImageIcon(new ImageIcon(this.getClass().getResource("backArrow.png")).getImage().getScaledInstance(60, 50, Image.SCALE_DEFAULT))); removeBackground(backButton); backButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub Game.frame.setVisible(true); frame.dispose(); } }); frame.add(backButton); } public void deleteGame() { } public void removeBackground(JButton button) { button.setContentAreaFilled(false); button.setFocusPainted(false); button.setBorderPainted(false); } }
3,724
0.694683
0.675886
127
27.322834
26.877054
155
false
false
0
0
0
0
0
0
2.818898
false
false
7
0fa9c34e207bc99b27fdfc02c1e25daa529e9701
19,559,281,114,884
91b4d4799bb4cd9dda2d74001143f7821b22eb73
/hbase-hadoop-compat/src/main/java/org/apache/hadoop/metrics2/lib/MutableRangeHistogram.java
a4d316fa9f4693ee27259a298b4b00483ca91a76
[ "CC-BY-3.0", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-protobuf", "MIT" ]
permissive
apache/hbase
https://github.com/apache/hbase
dce46e0c368a0aacee2ca414edfdbd6159059800
121c8e17ecea66267fe77bab078f79d14a74a832
refs/heads/master
2023-09-04T10:46:40.146000
2023-08-31T13:33:45
2023-08-31T13:33:45
20,089,857
5,493
3,991
Apache-2.0
false
2023-09-14T14:55:43
2014-05-23T07:00:07
2023-09-14T07:16:55
2023-09-14T08:07:28
479,849
4,963
3,247
189
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.metrics2.lib; import org.apache.hadoop.hbase.metrics.Interns; import org.apache.hadoop.hbase.metrics.Snapshot; import org.apache.hadoop.metrics2.MetricHistogram; import org.apache.hadoop.metrics2.MetricsInfo; import org.apache.hadoop.metrics2.MetricsRecordBuilder; import org.apache.yetus.audience.InterfaceAudience; /** * Extended histogram implementation with metric range counters. */ @InterfaceAudience.Private public abstract class MutableRangeHistogram extends MutableHistogram implements MetricHistogram { public MutableRangeHistogram(MetricsInfo info) { this(info.name(), info.description()); } public MutableRangeHistogram(String name, String description) { super(name, description); } /** * Returns the type of range histogram size or time */ public abstract String getRangeType(); /** * Returns the ranges to be counted */ public abstract long[] getRanges(); @Override public synchronized void snapshot(MetricsRecordBuilder metricsRecordBuilder, boolean all) { // Get a reference to the old histogram. Snapshot snapshot = histogram.snapshot(); if (snapshot != null) { updateSnapshotMetrics(name, desc, histogram, snapshot, metricsRecordBuilder); updateSnapshotRangeMetrics(metricsRecordBuilder, snapshot); } } public void updateSnapshotRangeMetrics(MetricsRecordBuilder metricsRecordBuilder, Snapshot snapshot) { long priorRange = 0; long cumNum = 0; final long[] ranges = getRanges(); final String rangeType = getRangeType(); for (int i = 0; i < ranges.length; i++) { long val = snapshot.getCountAtOrBelow(ranges[i]); if (val - cumNum > 0) { metricsRecordBuilder.addCounter( Interns.info(name + "_" + rangeType + "_" + priorRange + "-" + ranges[i], desc), val - cumNum); } priorRange = ranges[i]; cumNum = val; } long val = snapshot.getCount(); if (val - cumNum > 0) { metricsRecordBuilder.addCounter( Interns.info(name + "_" + rangeType + "_" + priorRange + "-inf", desc), val - cumNum); } } @Override public long getCount() { return histogram.getCount(); } }
UTF-8
Java
3,013
java
MutableRangeHistogram.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.metrics2.lib; import org.apache.hadoop.hbase.metrics.Interns; import org.apache.hadoop.hbase.metrics.Snapshot; import org.apache.hadoop.metrics2.MetricHistogram; import org.apache.hadoop.metrics2.MetricsInfo; import org.apache.hadoop.metrics2.MetricsRecordBuilder; import org.apache.yetus.audience.InterfaceAudience; /** * Extended histogram implementation with metric range counters. */ @InterfaceAudience.Private public abstract class MutableRangeHistogram extends MutableHistogram implements MetricHistogram { public MutableRangeHistogram(MetricsInfo info) { this(info.name(), info.description()); } public MutableRangeHistogram(String name, String description) { super(name, description); } /** * Returns the type of range histogram size or time */ public abstract String getRangeType(); /** * Returns the ranges to be counted */ public abstract long[] getRanges(); @Override public synchronized void snapshot(MetricsRecordBuilder metricsRecordBuilder, boolean all) { // Get a reference to the old histogram. Snapshot snapshot = histogram.snapshot(); if (snapshot != null) { updateSnapshotMetrics(name, desc, histogram, snapshot, metricsRecordBuilder); updateSnapshotRangeMetrics(metricsRecordBuilder, snapshot); } } public void updateSnapshotRangeMetrics(MetricsRecordBuilder metricsRecordBuilder, Snapshot snapshot) { long priorRange = 0; long cumNum = 0; final long[] ranges = getRanges(); final String rangeType = getRangeType(); for (int i = 0; i < ranges.length; i++) { long val = snapshot.getCountAtOrBelow(ranges[i]); if (val - cumNum > 0) { metricsRecordBuilder.addCounter( Interns.info(name + "_" + rangeType + "_" + priorRange + "-" + ranges[i], desc), val - cumNum); } priorRange = ranges[i]; cumNum = val; } long val = snapshot.getCount(); if (val - cumNum > 0) { metricsRecordBuilder.addCounter( Interns.info(name + "_" + rangeType + "_" + priorRange + "-inf", desc), val - cumNum); } } @Override public long getCount() { return histogram.getCount(); } }
3,013
0.710256
0.705941
89
32.853931
27.484234
97
false
false
0
0
0
0
0
0
0.516854
false
false
7
93230922e96317806e080682be38ba67b881e201
3,272,765,140,676
69f8ad9eb3fc6b267475abe0c12a9b6edc4895b5
/src/test/java/com/softarex/datacollector/model/service/MailServiceTest.java
bf7149b5108f52966d78c3c9bd84840b9af6ae77
[]
no_license
Vorobeyyyyyy/QuestionnairePortal
https://github.com/Vorobeyyyyyy/QuestionnairePortal
de4a187f15066b4769f3c7b5641128bbaad4dc7d
7e70c447c3f7f08250c2e8036ebe12513ef8dfe7
refs/heads/master
2023-04-23T12:32:51.835000
2021-05-21T16:31:05
2021-05-21T16:31:05
365,209,254
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.softarex.datacollector.model.service; import com.softarex.datacollector.model.entity.user.User; import com.softarex.datacollector.model.property.MailProperty; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @ExtendWith(MockitoExtension.class) class MailServiceTest { private final static String FROM = "noreply@test.com"; @Mock JavaMailSender javaMailSender; @Mock MailProperty mailProperty; private MailService mailService = new MailService(javaMailSender, mailProperty); @Test void sendMessage() { User user = new User(); String email = "test@mail.com"; String subject = "Lorem ipsum"; String text = "dolor sit amet"; user.setEmail(email); SimpleMailMessage expectedMailMessage = new SimpleMailMessage(); expectedMailMessage.setFrom(FROM); expectedMailMessage.setText(text); expectedMailMessage.setSubject(subject); expectedMailMessage.setTo(email); mailService.sendMessage(user, subject, text); Mockito.verify(javaMailSender, Mockito.times(1)).send(expectedMailMessage); } }
UTF-8
Java
1,419
java
MailServiceTest.java
Java
[ { "context": "iceTest {\n private final static String FROM = \"noreply@test.com\";\n @Mock\n JavaMailSender javaMailSender;\n ", "end": 628, "score": 0.9997448325157166, "start": 612, "tag": "EMAIL", "value": "noreply@test.com" }, { "context": " User user = new User();\n String email = \"test@mail.com\";\n String subject = \"Lorem ipsum\";\n ", "end": 908, "score": 0.9999110102653503, "start": 895, "tag": "EMAIL", "value": "test@mail.com" } ]
null
[]
package com.softarex.datacollector.model.service; import com.softarex.datacollector.model.entity.user.User; import com.softarex.datacollector.model.property.MailProperty; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; @ExtendWith(MockitoExtension.class) class MailServiceTest { private final static String FROM = "<EMAIL>"; @Mock JavaMailSender javaMailSender; @Mock MailProperty mailProperty; private MailService mailService = new MailService(javaMailSender, mailProperty); @Test void sendMessage() { User user = new User(); String email = "<EMAIL>"; String subject = "Lorem ipsum"; String text = "dolor sit amet"; user.setEmail(email); SimpleMailMessage expectedMailMessage = new SimpleMailMessage(); expectedMailMessage.setFrom(FROM); expectedMailMessage.setText(text); expectedMailMessage.setSubject(subject); expectedMailMessage.setTo(email); mailService.sendMessage(user, subject, text); Mockito.verify(javaMailSender, Mockito.times(1)).send(expectedMailMessage); } }
1,404
0.743481
0.742777
42
32.809525
23.30669
84
false
false
0
0
0
0
0
0
0.738095
false
false
7
ca87246b8fe8de79cf9f8e10cd498e9a26aea2b2
987,842,543,231
b7e2cd4f8e1e63bc1fa9ff6e674494191ca0a3e4
/M2/DeveloppementWeb/Spring/Ex05-JPA/CustomerCategory/CorrectionsCustomerCategory/CorrectionCustomerCategory-V2.1/src/test/java/edu/uha/miage/core/repository/CategoryRepositoryTest.java
0810e0339df8954e0a0c909282b337f5504b98c4
[]
no_license
gerobum/Enseignements
https://github.com/gerobum/Enseignements
079f2c32de1115f629240509bff2927fc5d52f5d
d0e421d32b084fd2c5b5c58231c5bfaed57740c0
refs/heads/master
2023-07-24T04:17:37.619000
2023-07-10T18:06:24
2023-07-10T18:06:24
56,856,667
0
0
null
false
2023-07-10T18:08:15
2016-04-22T13:17:55
2021-10-03T21:26:54
2023-07-10T18:06:32
52,823
0
0
0
Java
false
false
/* * 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 edu.uha.miage.core.repository; import edu.uha.miage.core.entity.Category; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * * @author yvan */ // #### V1.2 @RunWith(SpringJUnit4ClassRunner.class) Indique que la classe utilise JUnit pour les tests unitaires // #### V1.2 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html @RunWith(SpringJUnit4ClassRunner.class)// #### V1.2 Equivalent à @RunWith(SpringRunner.class) // #### V1.2 @DataJpaTest doit être employé dans le cas de test Jpa, notamment // #### V1.2 pour que l'injection de dépendance se passe bien. // #### V1.2 https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTest.html @DataJpaTest public class CategoryRepositoryTest { // #### V1.2 Du logging peut être utile private static final Logger LOGGER = LoggerFactory.getLogger(CategoryRepositoryTest.class); // #### V1.2 Du logging peut être utile // #### V1.2 Injection de dépendance @Autowired CategoryRepository categoryRepository; public CategoryRepositoryTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } // #### V1.2 Des exemples sont enregistrés avant chaque test. @Before public void setUp() { saveCategory("A"); saveCategory("B"); saveCategory("Z"); } private void saveCategory(String name) { if (categoryRepository.findByName(name) == null) { Category category = new Category(name); categoryRepository.save(category); } } @After public void tearDown() { } // #### V1.2 Test pour voir si le findByName se passe bien. @Test public void testFindByName() { LOGGER.info("Test findByName"); System.out.println("Test findByName"); assertNotNull(categoryRepository.findByName("A")); assertNull(categoryRepository.findByName("W")); saveCategory("W"); assertNotNull(categoryRepository.findByName("W")); } // #### V1.2 Et ainsi de suite. Voir un cours sur les tests unitaires. @Test public void testCount() { LOGGER.info("Test Count"); System.out.println("Test Count"); assertEquals(3, categoryRepository.count()); saveCategory("W"); assertEquals(4, categoryRepository.count()); } // #### V1.2 Ce ne sont que des exemples. @Test public void testDelete() { LOGGER.info("Test Count"); System.out.println("Test Count"); Category a = categoryRepository.findByName("A"); long n = categoryRepository.count(); categoryRepository.delete(a); assertEquals(n-1, categoryRepository.count()); categoryRepository.deleteAll(); assertEquals(0, categoryRepository.count()); } }
UTF-8
Java
3,581
java
CategoryRepositoryTest.java
Java
[ { "context": "junit4.SpringJUnit4ClassRunner;\n\n/**\n *\n * @author yvan\n */\n\n// #### V1.2 @RunWith(SpringJUnit4ClassRunn", "end": 753, "score": 0.9693447947502136, "start": 749, "tag": "USERNAME", "value": "yvan" } ]
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 edu.uha.miage.core.repository; import edu.uha.miage.core.entity.Category; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * * @author yvan */ // #### V1.2 @RunWith(SpringJUnit4ClassRunner.class) Indique que la classe utilise JUnit pour les tests unitaires // #### V1.2 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.html @RunWith(SpringJUnit4ClassRunner.class)// #### V1.2 Equivalent à @RunWith(SpringRunner.class) // #### V1.2 @DataJpaTest doit être employé dans le cas de test Jpa, notamment // #### V1.2 pour que l'injection de dépendance se passe bien. // #### V1.2 https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/orm/jpa/DataJpaTest.html @DataJpaTest public class CategoryRepositoryTest { // #### V1.2 Du logging peut être utile private static final Logger LOGGER = LoggerFactory.getLogger(CategoryRepositoryTest.class); // #### V1.2 Du logging peut être utile // #### V1.2 Injection de dépendance @Autowired CategoryRepository categoryRepository; public CategoryRepositoryTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } // #### V1.2 Des exemples sont enregistrés avant chaque test. @Before public void setUp() { saveCategory("A"); saveCategory("B"); saveCategory("Z"); } private void saveCategory(String name) { if (categoryRepository.findByName(name) == null) { Category category = new Category(name); categoryRepository.save(category); } } @After public void tearDown() { } // #### V1.2 Test pour voir si le findByName se passe bien. @Test public void testFindByName() { LOGGER.info("Test findByName"); System.out.println("Test findByName"); assertNotNull(categoryRepository.findByName("A")); assertNull(categoryRepository.findByName("W")); saveCategory("W"); assertNotNull(categoryRepository.findByName("W")); } // #### V1.2 Et ainsi de suite. Voir un cours sur les tests unitaires. @Test public void testCount() { LOGGER.info("Test Count"); System.out.println("Test Count"); assertEquals(3, categoryRepository.count()); saveCategory("W"); assertEquals(4, categoryRepository.count()); } // #### V1.2 Ce ne sont que des exemples. @Test public void testDelete() { LOGGER.info("Test Count"); System.out.println("Test Count"); Category a = categoryRepository.findByName("A"); long n = categoryRepository.count(); categoryRepository.delete(a); assertEquals(n-1, categoryRepository.count()); categoryRepository.deleteAll(); assertEquals(0, categoryRepository.count()); } }
3,581
0.680381
0.669745
110
31.481817
29.044395
146
false
false
0
0
0
0
85
0.042541
0.436364
false
false
7
dc561aa8baa13d18ded10f69f488f0ca37885d9e
12,652,973,695,015
913664133e3d46b794366c3b3b538e48f8ac7d24
/src/apresentacao/LocalidadeBean.java
efac33c420f51692a7c1824d8f3ac3435e664417
[]
no_license
isolino/bestplace
https://github.com/isolino/bestplace
43242e43e4305780b3932406dd6be888a6436247
10e27d9c92e93c7ab97f57dc1498f011fa0f1a79
refs/heads/master
2017-12-22T10:12:58.414000
2015-03-08T16:43:45
2015-03-08T16:43:45
31,658,904
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package apresentacao; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ManagedBean(name = "localidadeBean") @ViewScoped public class LocalidadeBean { }
UTF-8
Java
181
java
LocalidadeBean.java
Java
[]
null
[]
package apresentacao; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ManagedBean(name = "localidadeBean") @ViewScoped public class LocalidadeBean { }
181
0.79558
0.79558
11
15.454545
15.570156
37
false
false
0
0
0
0
0
0
0.272727
false
false
7
bfd3101395761680a6db8b3a1388897c85cecfcf
893,353,221,419
d052d49e0476c7e59c01bf3f2940cd53b614ccab
/Tasks/Task 21/src/Channels.java
c174d07af9b307ad105e59df47505f580bb8429a
[]
no_license
GalimovMarat/GALIMOV_JAVA
https://github.com/GalimovMarat/GALIMOV_JAVA
da8c7b9ea9e889176c8237f48e373cbf144bf8cb
d28fc3f36ffe5a3cf10c7fbbbac35b2019b69758
refs/heads/master
2020-04-11T15:37:05.960000
2019-04-19T13:16:52
2019-04-19T13:16:52
161,897,590
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Random; public class Channels { public String name; private Show [] shows; public String showsArray[] = {"Гуппи и пузырики", "С добрым утром малыши","Поезд динозавров","Ми-ми-мишки","Три кота", "Politics News", "Science news","sports news","culture News","Weather","Love Triangle", "Doctor Adventures", "Necklace","Sugar And Spice","Slice Of Heaven"}; final static int MAX_SHOWS_NUM = 5; public Channels(String name) { Random random = new Random(); this.name = name; this.shows = new Show [MAX_SHOWS_NUM]; for (int i = 0; i < MAX_SHOWS_NUM; i++){ shows[i] = new Show(showsArray[random.nextInt(showsArray.length)]); } } public void showChannel (){ Random random = new Random(); System.out.print("You are watching "); shows[random.nextInt(MAX_SHOWS_NUM)].printName(); System.out.println(" on " + name); } }
UTF-8
Java
999
java
Channels.java
Java
[]
null
[]
import java.util.Random; public class Channels { public String name; private Show [] shows; public String showsArray[] = {"Гуппи и пузырики", "С добрым утром малыши","Поезд динозавров","Ми-ми-мишки","Три кота", "Politics News", "Science news","sports news","culture News","Weather","Love Triangle", "Doctor Adventures", "Necklace","Sugar And Spice","Slice Of Heaven"}; final static int MAX_SHOWS_NUM = 5; public Channels(String name) { Random random = new Random(); this.name = name; this.shows = new Show [MAX_SHOWS_NUM]; for (int i = 0; i < MAX_SHOWS_NUM; i++){ shows[i] = new Show(showsArray[random.nextInt(showsArray.length)]); } } public void showChannel (){ Random random = new Random(); System.out.print("You are watching "); shows[random.nextInt(MAX_SHOWS_NUM)].printName(); System.out.println(" on " + name); } }
999
0.621795
0.619658
26
35
30.944118
118
false
false
0
0
0
0
0
0
1.115385
false
false
7
93de3dba5a0c031afe7fc0c3098838744edec77b
14,207,751,865,415
d45d5b3b13a5ab7fc6d5b8572438814a94982c2d
/IdeaProjects/FileCopyingTask/src/CopyFilesDirectlyTask.java
0629ad2ea4c05ba0b208b76917d9d685462b637a
[]
no_license
Jane2001/CopyFile
https://github.com/Jane2001/CopyFile
8255e9aee8daac9baad4bcd070cd8b0a0bbd06aa
8f7f6aa61dd9ca8ffa7c0e5946a23380e2d3884b
refs/heads/master
2020-09-21T21:02:35.685000
2019-11-29T22:58:00
2019-11-29T22:58:00
223,750,684
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.*; public class CopyFilesDirectlyTask extends AbstractCopyFilesTask { @Override protected void copyFiles(File source, File dest) throws IOException { try(final InputStream sourceStream = new FileInputStream(source); final OutputStream destStream = new FileOutputStream(dest)){ final long totalSize = source.length(); long readCount = 0; while(sourceStream.available()>0){ int readByte = sourceStream.read(); destStream.write(readByte); readCount++; System.out.println("Progress: " + readCount + "/" + totalSize); } } } }
UTF-8
Java
691
java
CopyFilesDirectlyTask.java
Java
[]
null
[]
import java.io.*; public class CopyFilesDirectlyTask extends AbstractCopyFilesTask { @Override protected void copyFiles(File source, File dest) throws IOException { try(final InputStream sourceStream = new FileInputStream(source); final OutputStream destStream = new FileOutputStream(dest)){ final long totalSize = source.length(); long readCount = 0; while(sourceStream.available()>0){ int readByte = sourceStream.read(); destStream.write(readByte); readCount++; System.out.println("Progress: " + readCount + "/" + totalSize); } } } }
691
0.599132
0.596237
19
35.315788
27.518515
79
false
false
0
0
0
0
0
0
0.473684
false
false
7
603f802d832574d1f5ddd13805f4d69dcbf2edcf
17,179,883,759
d55a4d56638db99af60eed5501061a5ebb7231b3
/src/sample/Controller.java
9e1c68082b96926eb884fbb2263ed3108ac593b8
[]
no_license
Pabloms06/JavaFxConcurrencia
https://github.com/Pabloms06/JavaFxConcurrencia
222e25c931a36fc20ef8308a3a44144e4004819c
de25e8bda1139ee855c5f05251bad531498287f9
refs/heads/master
2023-01-24T03:12:55.425000
2020-11-24T19:08:47
2020-11-24T19:08:47
315,728,377
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample; import javafx.fxml.FXML; import javafx.scene.control.Button; public class Controller { public javafx.scene.control.Label label; public javafx.scene.control.TextField texto; public Button boton; @FXML private void BotonPulsado(){ label.setText(""); String palabra = texto.getText(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } label.setText(palabra.toUpperCase()); } }
UTF-8
Java
527
java
Controller.java
Java
[]
null
[]
package sample; import javafx.fxml.FXML; import javafx.scene.control.Button; public class Controller { public javafx.scene.control.Label label; public javafx.scene.control.TextField texto; public Button boton; @FXML private void BotonPulsado(){ label.setText(""); String palabra = texto.getText(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } label.setText(palabra.toUpperCase()); } }
527
0.620493
0.612903
26
19.26923
16.784969
48
false
false
0
0
0
0
0
0
0.423077
false
false
7