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
cdd33ae245fdea5d3f7f19179101b9032948a839
1,322,849,959,565
8fc097646c4a51dab35ae4427a3f99db2645d80f
/src/main/java/com/knoable/application/modules/system/model/VersionUpgrade.java
2027ac140f8a480588c3d7d1e4c5dd72fd30b458
[ "Apache-2.0" ]
permissive
leechuanrong/api-ch01
https://github.com/leechuanrong/api-ch01
0e2150e1404dba0cd9ba37aa0faddbdb3b7dac30
500704649e0a8dfe278837b00a1006eebbd6f121
refs/heads/master
2020-03-22T21:35:52.919000
2018-07-13T05:24:25
2018-07-13T05:24:25
140,699,322
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.knoable.application.modules.system.model; import java.io.Serializable; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonIgnore; /** * 版本升级Model * @author * */ public class VersionUpgrade implements Serializable { /** * */ private static final long serialVersionUID = 1L; @JSONField(serialize = false) @JsonIgnore private Long id; // private int code; // 版本号 private String description; // 版本简单介绍 private String downloadUrl; // 下载地址 private int lowestCode; // 最低版本号 private String deviceName; // 设备名称 private String note; // 更新内容 private String deviceType; // 设备类型 1 安卓 private Date updateTime; // 更新时间 private int resetLogin; // 是否重新登录 0 不需要 1需要 private String version; // 最新版本号 public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public int getLowestCode() { return lowestCode; } public void setLowestCode(int lowestCode) { this.lowestCode = lowestCode; } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public int getResetLogin() { return resetLogin; } public void setResetLogin(int resetLogin) { this.resetLogin = resetLogin; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
UTF-8
Java
2,295
java
VersionUpgrade.java
Java
[]
null
[]
package com.knoable.application.modules.system.model; import java.io.Serializable; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; import com.fasterxml.jackson.annotation.JsonIgnore; /** * 版本升级Model * @author * */ public class VersionUpgrade implements Serializable { /** * */ private static final long serialVersionUID = 1L; @JSONField(serialize = false) @JsonIgnore private Long id; // private int code; // 版本号 private String description; // 版本简单介绍 private String downloadUrl; // 下载地址 private int lowestCode; // 最低版本号 private String deviceName; // 设备名称 private String note; // 更新内容 private String deviceType; // 设备类型 1 安卓 private Date updateTime; // 更新时间 private int resetLogin; // 是否重新登录 0 不需要 1需要 private String version; // 最新版本号 public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public int getLowestCode() { return lowestCode; } public void setLowestCode(int lowestCode) { this.lowestCode = lowestCode; } public String getDeviceName() { return deviceName; } public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getDeviceType() { return deviceType; } public void setDeviceType(String deviceType) { this.deviceType = deviceType; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public int getResetLogin() { return resetLogin; } public void setResetLogin(int resetLogin) { this.resetLogin = resetLogin; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
2,295
0.7224
0.720568
102
20.40196
16.39719
53
false
false
0
0
0
0
0
0
1.431373
false
false
12
65d5b8cd8633e706b7f75c1f6f763d506804f860
22,342,419,895,593
73308ecf567af9e5f4ef8d5ff10f5e9a71e81709
/jaso72859/src/main/java/com/example/jaso72859/LoginController.java
941fb9dea80295680dd194f44ab279dc807e26c4
[]
no_license
yukihane/stackoverflow-qa
https://github.com/yukihane/stackoverflow-qa
bfaf371e3c61919492e2084ed4c65f33323d7231
ba5e6a0d51f5ecfa80bb149456adea49de1bf6fb
refs/heads/main
2023-08-03T06:54:32.086000
2023-07-26T20:02:07
2023-07-26T20:02:07
194,699,870
3
3
null
false
2023-03-02T23:37:45
2019-07-01T15:34:08
2022-12-14T23:02:29
2023-03-02T23:37:45
8,277
3
2
79
Java
false
false
package com.example.jaso72859; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class LoginController { @GetMapping("/loginForm") public String getLogin() { return "loginForm"; } }
UTF-8
Java
282
java
LoginController.java
Java
[ { "context": "package com.example.jaso72859;\n\nimport org.springframework.stereotype.Contro", "end": 26, "score": 0.5948041081428528, "start": 23, "tag": "USERNAME", "value": "o72" } ]
null
[]
package com.example.jaso72859; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class LoginController { @GetMapping("/loginForm") public String getLogin() { return "loginForm"; } }
282
0.748227
0.730496
13
20.76923
18.758194
58
false
false
0
0
0
0
0
0
0.307692
false
false
12
a164191de9447b236d457cbf6dcefa6a08249037
22,342,419,896,698
7c01e6e66c5ae292ed000e4a851acac2f08cc033
/src/main/java/br/com/sysprice/business/WatsonConversationService.java
e2862b4bd8536178b2f6043dfea3cad09b8e636b
[]
no_license
Giovanni-Bruno/disk-wat
https://github.com/Giovanni-Bruno/disk-wat
7e75014a49e18080fab4d665d2d2028ed9f9191c
8ee21a9acd55a8745338845134cfca095f2c9009
refs/heads/master
2016-08-26T08:06:04.881000
2016-08-11T20:09:44
2016-08-11T20:09:44
65,207,059
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.sysprice.business; import com.ibm.watson.developer_cloud.conversation.v1.ConversationService; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; /** * * @author gluigi */ public class WatsonConversationService { private ConversationService service; public WatsonConversationService(){ init(); } private void init(){ service = new ConversationService(ConversationService.VERSION_DATE_2016_07_11); service.setUsernameAndPassword("a5d0e01a-f720-4d34-80ee-c78e26cd914d", "QP3MSzI6DgID"); } public MessageResponse sendMessage(MessageRequest message){ MessageResponse responseWatson = service.message("552b60bb-d57b-4d85-9ea0-797bb661eba6", message).execute(); return responseWatson; } }
UTF-8
Java
1,098
java
WatsonConversationService.java
Java
[ { "context": "n.v1.model.MessageResponse;\r\n\r\n/**\r\n *\r\n * @author gluigi\r\n */\r\npublic class WatsonConversationService {\r\n ", "end": 486, "score": 0.879138708114624, "start": 480, "tag": "USERNAME", "value": "gluigi" }, { "context": "_07_11);\r\n service.setUsernameAndPassword(\"a5d0e01a-f720-4d34-80ee-c78e26cd914d\", \"QP3MSzI6DgID\");\r\n }\r\n \r\n public Messa", "end": 839, "score": 0.9993634223937988, "start": 803, "tag": "PASSWORD", "value": "a5d0e01a-f720-4d34-80ee-c78e26cd914d" } ]
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 br.com.sysprice.business; import com.ibm.watson.developer_cloud.conversation.v1.ConversationService; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; /** * * @author gluigi */ public class WatsonConversationService { private ConversationService service; public WatsonConversationService(){ init(); } private void init(){ service = new ConversationService(ConversationService.VERSION_DATE_2016_07_11); service.setUsernameAndPassword("<PASSWORD>", "QP3MSzI6DgID"); } public MessageResponse sendMessage(MessageRequest message){ MessageResponse responseWatson = service.message("552b60bb-d57b-4d85-9ea0-797bb661eba6", message).execute(); return responseWatson; } }
1,072
0.723133
0.676685
31
33.419353
33.710125
116
false
false
0
0
0
0
0
0
0.483871
false
false
12
6713de39872032e684776f1938702eb0eee1ee85
22,342,419,895,615
778c33d422fee51fca99b50dc01bab5ae7f68645
/Customer.java
09e95eb5e80e5e7ce3aaa5e0733bd4f658bf510f
[]
no_license
sashahavia/Bank_Simulation
https://github.com/sashahavia/Bank_Simulation
0df0ed6b963c8e9c22f14a0da3171be0add0fe4d
243742f55c4f79710811e79a3f94c3917ed28677
refs/heads/master
2021-01-02T22:59:23.279000
2017-08-05T15:47:30
2017-08-05T15:47:30
99,432,082
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** Assignment 3 -- Aliaksandra Havia */ public abstract class Customer { private String name; private String address; private int age; private String telephoneNumber; private int customerNumber; // Constructor public Customer(String name, String address, int age, String telephoneNumber, int customerNumber) { this.name = name; this.address = address; this.telephoneNumber = telephoneNumber; this.customerNumber = customerNumber; this.age = age; } // Modifier methods public void setName (String name) { this.name = name; } public void setAddress (String address) { this.address = address; } public void setAge (int age) { this.age = age; } public void setTelephoneNumber (String telephoneNumber) { this.telephoneNumber = telephoneNumber; } public void setCustomerNumber (int customerNumber) { this.customerNumber = customerNumber; } // Accessor methods public String getName () { return name; } public String getAddress () { return address; } public int getAge () { return age; } public String getTelephoneNumber () { return telephoneNumber; } public int getNumber () { return customerNumber; } @Override public String toString() { return(name + " | " + address + " | " + telephoneNumber + " | " + age + " | " + customerNumber); } public abstract double getSavingsInterest (); public abstract double getCheckingInterest (); public abstract double getCheckCharge (); public abstract double getOverdraftPenalty (); }
UTF-8
Java
1,502
java
Customer.java
Java
[ { "context": "/** Assignment 3 -- Aliaksandra Havia */\n\npublic abstract class Customer {\n\tprivate Str", "end": 37, "score": 0.9998940825462341, "start": 20, "tag": "NAME", "value": "Aliaksandra Havia" } ]
null
[]
/** Assignment 3 -- <NAME> */ public abstract class Customer { private String name; private String address; private int age; private String telephoneNumber; private int customerNumber; // Constructor public Customer(String name, String address, int age, String telephoneNumber, int customerNumber) { this.name = name; this.address = address; this.telephoneNumber = telephoneNumber; this.customerNumber = customerNumber; this.age = age; } // Modifier methods public void setName (String name) { this.name = name; } public void setAddress (String address) { this.address = address; } public void setAge (int age) { this.age = age; } public void setTelephoneNumber (String telephoneNumber) { this.telephoneNumber = telephoneNumber; } public void setCustomerNumber (int customerNumber) { this.customerNumber = customerNumber; } // Accessor methods public String getName () { return name; } public String getAddress () { return address; } public int getAge () { return age; } public String getTelephoneNumber () { return telephoneNumber; } public int getNumber () { return customerNumber; } @Override public String toString() { return(name + " | " + address + " | " + telephoneNumber + " | " + age + " | " + customerNumber); } public abstract double getSavingsInterest (); public abstract double getCheckingInterest (); public abstract double getCheckCharge (); public abstract double getOverdraftPenalty (); }
1,491
0.711718
0.711052
71
20.169014
21.221161
100
false
false
0
0
0
0
0
0
1.450704
false
false
12
0daaeff914834ebf06d18e255e8726dda14d4df2
10,264,971,856,965
44e9e794fc8737b9cedc3634af9dbda079ea37e5
/CompanyStructure/src/Employee.java
c531ad364833dc5bb8b1daadc21ce00d4f1fd68a
[]
no_license
shinnew99/OOP
https://github.com/shinnew99/OOP
1b95a4170f071c4012b28e91fce1e0b0692ffb69
952441470819efc1b66626519d18a1bd1ac8d1fa
refs/heads/master
2022-06-13T09:39:35.299000
2020-05-08T08:23:27
2020-05-08T08:23:27
256,450,800
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public abstract class Employee { String name; double baseSalary; public static int employeeIDCnt = 1; int employeeId; Employee manager; public Employee(String name, double baseSalary){ //일종의 멤버변수에 파라미터값을 저장해주는 행위라고 보면됌 this.name = name; this.baseSalary = baseSalary; this.employeeId = employeeIDCnt; employeeIDCnt++; } public double getBaseSalary(){ double currentSalary = this.baseSalary; return currentSalary; } public String getName(){ String currentName = this.name; return currentName; } public int getEmployeeID(){ return this.employeeId; } public Employee getManager(){ return this.manager; } public boolean equals(Employee other){ //어떤 employeeId가 새로들어온(입력된) emloyeeId랑 같은지 비교 if(this.employeeId == other.employeeId){ return true; } else { return false; } } public String toString(){ String combination = this.employeeId + " " + this.name; return combination; } public String employeeStatus(){ //줄 바꾸는 건 "\n" String status = this.toString() + " " + this.baseSalary + " " + manager; return status; } /* public static void main(String[] args) { Employee employee = new Employee("Martin Grarrix", 5000.0); Employee employee2 = new Employee("DJ Snake", 5500.0 ); Employee employee3 = new Employee("DJ Khalid", 5300.0 ); System.out.println(employee); System.out.println(employee.employeeId); System.out.println(employee2.employeeId); System.out.println(employee3.employeeId); Employee employee4 = new Employee("abcd", 5300.0 ); System.out.println(employee4.employeeId); System.out.println(employee3.toString()); System.out.println(employee3.employeeStatus()); }*/ }
UTF-8
Java
2,116
java
Employee.java
Java
[ { "context": "rgs) {\r\n Employee employee = new Employee(\"Martin Grarrix\", 5000.0);\r\n Employee employee2 = new Empl", "end": 1445, "score": 0.9998911023139954, "start": 1431, "tag": "NAME", "value": "Martin Grarrix" }, { "context": "0.0);\r\n Employee employee2 = new Employee(\"DJ Snake\", 5500.0 );\r\n Employee employee3 = new Emp", "end": 1509, "score": 0.9998432993888855, "start": 1501, "tag": "NAME", "value": "DJ Snake" }, { "context": ".0 );\r\n Employee employee3 = new Employee(\"DJ Khalid\", 5300.0 );\r\n\r\n System.out.println(employe", "end": 1575, "score": 0.9998845458030701, "start": 1566, "tag": "NAME", "value": "DJ Khalid" } ]
null
[]
public abstract class Employee { String name; double baseSalary; public static int employeeIDCnt = 1; int employeeId; Employee manager; public Employee(String name, double baseSalary){ //일종의 멤버변수에 파라미터값을 저장해주는 행위라고 보면됌 this.name = name; this.baseSalary = baseSalary; this.employeeId = employeeIDCnt; employeeIDCnt++; } public double getBaseSalary(){ double currentSalary = this.baseSalary; return currentSalary; } public String getName(){ String currentName = this.name; return currentName; } public int getEmployeeID(){ return this.employeeId; } public Employee getManager(){ return this.manager; } public boolean equals(Employee other){ //어떤 employeeId가 새로들어온(입력된) emloyeeId랑 같은지 비교 if(this.employeeId == other.employeeId){ return true; } else { return false; } } public String toString(){ String combination = this.employeeId + " " + this.name; return combination; } public String employeeStatus(){ //줄 바꾸는 건 "\n" String status = this.toString() + " " + this.baseSalary + " " + manager; return status; } /* public static void main(String[] args) { Employee employee = new Employee("<NAME>", 5000.0); Employee employee2 = new Employee("<NAME>", 5500.0 ); Employee employee3 = new Employee("<NAME>", 5300.0 ); System.out.println(employee); System.out.println(employee.employeeId); System.out.println(employee2.employeeId); System.out.println(employee3.employeeId); Employee employee4 = new Employee("abcd", 5300.0 ); System.out.println(employee4.employeeId); System.out.println(employee3.toString()); System.out.println(employee3.employeeStatus()); }*/ }
2,103
0.589109
0.574752
73
25.671232
21.228731
80
false
false
0
0
0
0
0
0
0.506849
false
false
12
cc222cd07ca87844cd69b8b6a124db8c94d9501e
3,899,830,316,502
7fe4387cf53bc4c02ddfe4a7023f2d092e0d43b0
/gameserver/java/ru/l2gw/gameserver/clientpackets/RequestBBSwrite.java
37e379301cea095e24ef5ef3f4bd89233a296784
[]
no_license
d1slike/jserver
https://github.com/d1slike/jserver
65a6f47edc1fc8e86d28daaa210574c1226ded52
e3a2dc01bba3a6e8db013db545f5b3573c8b6379
refs/heads/master
2016-03-29T12:17:15.855000
2015-08-16T19:25:02
2015-08-16T19:25:02
35,298,906
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.l2gw.gameserver.clientpackets; import ru.l2gw.gameserver.Config; import ru.l2gw.gameserver.instancemanager.CommunityBoard.CommunityBoardManager; import ru.l2gw.gameserver.instancemanager.CommunityBoard.ICommunityBoardHandler; import ru.l2gw.gameserver.model.Player; import ru.l2gw.gameserver.serverpackets.SystemMessage; /** * Format SSSSSS */ public class RequestBBSwrite extends L2GameClientPacket { private String _url; private String _arg1; private String _arg2; private String _arg3; private String _arg4; private String _arg5; @Override public void readImpl() { _url = readS(); _arg1 = readS(); _arg2 = readS(); _arg3 = readS(); _arg4 = readS(); _arg5 = readS(); } @Override public void runImpl() { Player player = getClient().getPlayer(); if(player == null) return; ICommunityBoardHandler handler = CommunityBoardManager.getInstance().getCommunityHandler(_url); if(handler != null) { if(!Config.COMMUNITYBOARD_ENABLED) player.sendPacket(new SystemMessage(SystemMessage.THE_COMMUNITY_SERVER_IS_CURRENTLY_OFFLINE)); else handler.onWriteCommand(player, _url, _arg1, _arg2, _arg3, _arg4, _arg5); } } }
UTF-8
Java
1,185
java
RequestBBSwrite.java
Java
[]
null
[]
package ru.l2gw.gameserver.clientpackets; import ru.l2gw.gameserver.Config; import ru.l2gw.gameserver.instancemanager.CommunityBoard.CommunityBoardManager; import ru.l2gw.gameserver.instancemanager.CommunityBoard.ICommunityBoardHandler; import ru.l2gw.gameserver.model.Player; import ru.l2gw.gameserver.serverpackets.SystemMessage; /** * Format SSSSSS */ public class RequestBBSwrite extends L2GameClientPacket { private String _url; private String _arg1; private String _arg2; private String _arg3; private String _arg4; private String _arg5; @Override public void readImpl() { _url = readS(); _arg1 = readS(); _arg2 = readS(); _arg3 = readS(); _arg4 = readS(); _arg5 = readS(); } @Override public void runImpl() { Player player = getClient().getPlayer(); if(player == null) return; ICommunityBoardHandler handler = CommunityBoardManager.getInstance().getCommunityHandler(_url); if(handler != null) { if(!Config.COMMUNITYBOARD_ENABLED) player.sendPacket(new SystemMessage(SystemMessage.THE_COMMUNITY_SERVER_IS_CURRENTLY_OFFLINE)); else handler.onWriteCommand(player, _url, _arg1, _arg2, _arg3, _arg4, _arg5); } } }
1,185
0.730802
0.712236
48
23.708334
25.499149
98
false
false
0
0
0
0
0
0
1.75
false
false
12
901cb4f54846bb00762c19888df8d7cf6b87c548
3,899,830,315,341
86019c52d483dcd4cc45d5242168f14a307f351b
/src/main/java/com/ihomefnt/sky/common/cache/RedisCacheUtil.java
ea55ef4231eb1bbb4c78f1882e88d4b56280442b
[]
no_license
huayunlei/my-zuul
https://github.com/huayunlei/my-zuul
4a2741fd12c9b619050c3704e572a79ab887ee9d
b4732a0ce52ca08ff1da509496fc2e1d26eaf074
refs/heads/master
2023-01-03T08:54:36.925000
2020-10-21T14:46:31
2020-10-21T14:46:31
306,045,352
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ihomefnt.sky.common.cache; /** * @Description: * @Author hua * @Date 2020/1/15 3:46 下午 */ public class RedisCacheUtil { /**生成缓存key(拼冒号) * @param namespace * @param keys * @return */ public static String generateCacheKey(String namespace, Object... keys) { StringBuilder out = new StringBuilder(); out.append(namespace); if (keys != null && keys.length > 0) { out.append(":"); for (int i = 0; i < keys.length; i++) { out.append(keys[i]); if (i != keys.length - 1) { out.append(":"); } } } return out.toString(); } /**生成不拼冒号的缓存key * @param namespace * @param keys * @return */ public static String generateNoColonCacheKey(String namespace, Object... keys) { StringBuilder out = new StringBuilder(); out.append(namespace); if (keys != null && keys.length > 0) { out.append(":"); for (int i = 0; i < keys.length; i++) { out.append(keys[i]); } } return out.toString(); } }
UTF-8
Java
1,227
java
RedisCacheUtil.java
Java
[ { "context": "sky.common.cache;\n\n/**\n * @Description:\n * @Author hua\n * @Date 2020/1/15 3:46 下午\n */\npublic class Redis", "end": 75, "score": 0.9870485663414001, "start": 72, "tag": "USERNAME", "value": "hua" } ]
null
[]
package com.ihomefnt.sky.common.cache; /** * @Description: * @Author hua * @Date 2020/1/15 3:46 下午 */ public class RedisCacheUtil { /**生成缓存key(拼冒号) * @param namespace * @param keys * @return */ public static String generateCacheKey(String namespace, Object... keys) { StringBuilder out = new StringBuilder(); out.append(namespace); if (keys != null && keys.length > 0) { out.append(":"); for (int i = 0; i < keys.length; i++) { out.append(keys[i]); if (i != keys.length - 1) { out.append(":"); } } } return out.toString(); } /**生成不拼冒号的缓存key * @param namespace * @param keys * @return */ public static String generateNoColonCacheKey(String namespace, Object... keys) { StringBuilder out = new StringBuilder(); out.append(namespace); if (keys != null && keys.length > 0) { out.append(":"); for (int i = 0; i < keys.length; i++) { out.append(keys[i]); } } return out.toString(); } }
1,227
0.491154
0.478517
46
24.804348
19.121601
84
true
false
0
0
0
0
0
0
0.391304
false
false
12
7bc3a463058c880ca705e31bf3299d96c254de73
16,406,775,087,513
37ae90aa265ddb6671ba74da4b18eafb351a1921
/espproj1/src/lesson32dz/MainIterator.java
9bccff77fa8548cf427ef80cf8050563d0b9f4b0
[]
no_license
perepelkaS/iteasyum
https://github.com/perepelkaS/iteasyum
7e9ba3a71592f16c37a005747b777c946c9104ce
7638ac3d3a0d96cfe28a006d0881cff8c24ca658
refs/heads/master
2022-11-06T17:01:56.703000
2020-06-26T18:59:24
2020-06-26T18:59:24
271,264,276
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lesson32dz; public class MainIterator { public static void main(String[] args) { ArrayIterator<Integer> iter = new ArrayIterator<>(new Integer[][]{{1, 2}, {1, 3}, {2,5}}); while (iter.hasNext()) { Integer element = iter.next(); System.out.println(element); } } }
UTF-8
Java
329
java
MainIterator.java
Java
[]
null
[]
package lesson32dz; public class MainIterator { public static void main(String[] args) { ArrayIterator<Integer> iter = new ArrayIterator<>(new Integer[][]{{1, 2}, {1, 3}, {2,5}}); while (iter.hasNext()) { Integer element = iter.next(); System.out.println(element); } } }
329
0.568389
0.544073
12
26.416666
27.004501
98
false
false
0
0
0
0
0
0
0.75
false
false
12
252e0d21b6703011af7f5c0891e8f0e97db2a3f4
5,214,090,319,773
fc4902678c2599da2e49c2d678a10beb8dd50041
/五一讲课/code/Test1/src/cn/hbc/dao/impl/StudentDaoImpl.java
149df029ebec06a6d23d8b20378bd51e95fd956a
[]
no_license
handsomecui/MyPage
https://github.com/handsomecui/MyPage
49577e113caf5fb6193c98f3406ea167cbd33fd2
dd3e15653b1da477feccf11289c2a84cfb1361ac
refs/heads/master
2021-01-20T06:36:32.989000
2017-05-01T06:20:13
2017-05-01T06:20:13
89,901,650
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.hbc.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import cn.hbc.dao.StudentDao; import cn.hbc.entity.Student; import cn.hbc.util.JdbcUtils; public class StudentDaoImpl implements StudentDao { @Override public void add(Student e) { Connection conn = JdbcUtils.getConn(); String sql = "insert into student(name,age,sex) values(?,?,?)"; try { PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, e.getName()); statement.setInt(2, e.getAge()); statement.setString(3, e.getSex()); statement.execute(); statement.close(); conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @Override public void delete(Student e) { Connection conn = JdbcUtils.getConn(); String sql = "delete from student where id=1"; try { PreparedStatement statement = conn.prepareStatement(sql); statement.execute(); statement.close(); conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @Override public void update(Student e) { Connection conn = JdbcUtils.getConn(); String sql = "update student set name=?,age=?,sex=? where id=?"; try { PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, e.getName()); statement.setInt(2, e.getAge()); statement.setString(3, e.getSex()); statement.setInt(4, 1); statement.execute(); statement.close(); conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @Override public List<Student> query() { QueryRunner qr = new QueryRunner(); Connection conn = JdbcUtils.getConn(); List<Student> list; try { String sql = "select * from student"; list = qr.query(conn, sql, new BeanListHandler<Student>( Student.class)); conn.close(); return list; } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Student> query(int l, int r) { QueryRunner qr = new QueryRunner(); Connection conn = JdbcUtils.getConn(); List<Student> list; try { String sql = "select * from student limit ?,?"; list = qr.query(conn, sql, new BeanListHandler<Student>( Student.class), l, r); conn.close(); return list; } catch (Exception e) { throw new RuntimeException(e); } } @Override public int getCount() { QueryRunner qr = new QueryRunner(); Connection conn = JdbcUtils.getConn(); try { String sql = "select count(*) from student"; Long count = qr.query(conn, sql, new ScalarHandler<Long>()); conn.close(); return count.intValue(); } catch (Exception e) { throw new RuntimeException(e); } } }
UTF-8
Java
2,980
java
StudentDaoImpl.java
Java
[]
null
[]
package cn.hbc.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import cn.hbc.dao.StudentDao; import cn.hbc.entity.Student; import cn.hbc.util.JdbcUtils; public class StudentDaoImpl implements StudentDao { @Override public void add(Student e) { Connection conn = JdbcUtils.getConn(); String sql = "insert into student(name,age,sex) values(?,?,?)"; try { PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, e.getName()); statement.setInt(2, e.getAge()); statement.setString(3, e.getSex()); statement.execute(); statement.close(); conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @Override public void delete(Student e) { Connection conn = JdbcUtils.getConn(); String sql = "delete from student where id=1"; try { PreparedStatement statement = conn.prepareStatement(sql); statement.execute(); statement.close(); conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @Override public void update(Student e) { Connection conn = JdbcUtils.getConn(); String sql = "update student set name=?,age=?,sex=? where id=?"; try { PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1, e.getName()); statement.setInt(2, e.getAge()); statement.setString(3, e.getSex()); statement.setInt(4, 1); statement.execute(); statement.close(); conn.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } @Override public List<Student> query() { QueryRunner qr = new QueryRunner(); Connection conn = JdbcUtils.getConn(); List<Student> list; try { String sql = "select * from student"; list = qr.query(conn, sql, new BeanListHandler<Student>( Student.class)); conn.close(); return list; } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Student> query(int l, int r) { QueryRunner qr = new QueryRunner(); Connection conn = JdbcUtils.getConn(); List<Student> list; try { String sql = "select * from student limit ?,?"; list = qr.query(conn, sql, new BeanListHandler<Student>( Student.class), l, r); conn.close(); return list; } catch (Exception e) { throw new RuntimeException(e); } } @Override public int getCount() { QueryRunner qr = new QueryRunner(); Connection conn = JdbcUtils.getConn(); try { String sql = "select count(*) from student"; Long count = qr.query(conn, sql, new ScalarHandler<Long>()); conn.close(); return count.intValue(); } catch (Exception e) { throw new RuntimeException(e); } } }
2,980
0.683893
0.678859
118
24.254238
18.05415
66
false
false
0
0
0
0
0
0
2.559322
false
false
12
7653afb6183159906b8c84de2040faaffab1cbfe
24,678,882,107,672
83b592d3451db486d3625913c6706c1565639627
/src/me/darthteddy1/gta/crates/CrateListener.java
57a9c95be5bb162361109fb6aad0b51223312d5c
[]
no_license
FlamePost/GTAMC
https://github.com/FlamePost/GTAMC
6648ac8da4d07c657a14f6c263e34faff3654c82
e355faa71bf1563090849b8d407aa77b2a10cb78
refs/heads/master
2020-06-10T05:31:24.145000
2019-07-02T00:40:12
2019-07-02T00:40:12
193,597,411
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.darthteddy1.gta.crates; import me.darthteddy1.gta.utils.MessageUtils; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerInteractEvent; public class CrateListener implements Listener { @EventHandler public void onInt(PlayerInteractEvent e) { Player p = e.getPlayer(); if(e.getAction() != Action.RIGHT_CLICK_BLOCK) return; if(e.getClickedBlock().getType() == Material.CHEST && CrateHelper.crates.get(e.getClickedBlock().getLocation()) != null) { if(CrateHelper.crates.get(e.getClickedBlock().getLocation()).equalsIgnoreCase("ammo")) { e.setCancelled(true); if (p.getItemInHand() != null && p.getItemInHand().isSimilar(CrateHelper.getAmmoKey())) { if (p.getItemInHand().getAmount() > 1) { p.sendMessage(MessageUtils.PREFIX_BAD + "You cannot open crates with multiple keys in hand."); } else { p.setItemInHand(CrateHelper.getAmmoWin()); p.updateInventory(); p.sendMessage(MessageUtils.PREFIX_GOOD + "You have opened an ammo crate!"); } } else { p.sendMessage(MessageUtils.PREFIX_BAD + "You must be holding a key to open an Ammo crate."); } } } } @EventHandler public void onBreak(BlockBreakEvent e) { if(e.getBlock().getType() == Material.CHEST && CrateHelper.crates.get(e.getBlock().getLocation()) != null) { e.setCancelled(true); e.getPlayer().sendMessage(MessageUtils.PREFIX_BAD + "You cannot destroy crates"); } } }
UTF-8
Java
1,935
java
CrateListener.java
Java
[]
null
[]
package me.darthteddy1.gta.crates; import me.darthteddy1.gta.utils.MessageUtils; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerInteractEvent; public class CrateListener implements Listener { @EventHandler public void onInt(PlayerInteractEvent e) { Player p = e.getPlayer(); if(e.getAction() != Action.RIGHT_CLICK_BLOCK) return; if(e.getClickedBlock().getType() == Material.CHEST && CrateHelper.crates.get(e.getClickedBlock().getLocation()) != null) { if(CrateHelper.crates.get(e.getClickedBlock().getLocation()).equalsIgnoreCase("ammo")) { e.setCancelled(true); if (p.getItemInHand() != null && p.getItemInHand().isSimilar(CrateHelper.getAmmoKey())) { if (p.getItemInHand().getAmount() > 1) { p.sendMessage(MessageUtils.PREFIX_BAD + "You cannot open crates with multiple keys in hand."); } else { p.setItemInHand(CrateHelper.getAmmoWin()); p.updateInventory(); p.sendMessage(MessageUtils.PREFIX_GOOD + "You have opened an ammo crate!"); } } else { p.sendMessage(MessageUtils.PREFIX_BAD + "You must be holding a key to open an Ammo crate."); } } } } @EventHandler public void onBreak(BlockBreakEvent e) { if(e.getBlock().getType() == Material.CHEST && CrateHelper.crates.get(e.getBlock().getLocation()) != null) { e.setCancelled(true); e.getPlayer().sendMessage(MessageUtils.PREFIX_BAD + "You cannot destroy crates"); } } }
1,935
0.602584
0.601034
46
40.065216
36.381077
130
false
false
0
0
0
0
0
0
0.413043
false
false
12
97f3faf21c95bebb0bad746a8057821d9067132e
618,475,331,360
3dcd37402d326469a9565be2939d4cfd16ae5ac2
/app/src/main/java/com/vsn/omino/activites/ChatActivity.java
4035ab141e35d8471a2ea59d14b926cf7f1ea5db
[]
no_license
murtazavirku/Omino
https://github.com/murtazavirku/Omino
fa6c90c45680112ad60e6311489fbfcc97c56572
74615e8e9000d109d2c500fd0fd3a85bd6d605cb
refs/heads/master
2023-06-12T08:32:10.981000
2021-07-01T07:41:54
2021-07-01T07:41:54
381,950,038
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.vsn.omino.activites; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.wear.widget.CircledImageView; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import com.vsn.omino.Adapters.MessagesAdapter; import com.vsn.omino.R; import com.vsn.omino.models.MessageModel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; public class ChatActivity extends AppCompatActivity { private BottomSheetBehavior mBehavior; private BottomSheetDialog mBottomSheetDialog; LinearLayout selectIMG,selectMP4,selectMP3; MessagesAdapter messagesAdapter; List<MessageModel> messagelList; String FUserID; LinearLayout lyt_back; com.mikhaellopez.circularimageview.CircularImageView image; TextView username,IsOnline; EditText text_content; ImageView attachment; FloatingActionButton btn_send; public static final String MY_PREFS_NAME = "MyPrefsFile"; SharedPreferences prefs; RecyclerView recyclerView; private View bottom_sheet; private static final int REQUEST_PERMISSIONS = 100; private static final String PERMISSIONS_REQUIRED[] = new String[]{ android.Manifest.permission.READ_PHONE_STATE }; SendChatFilesActivity sendChatFilesActivity; Uri imageUri,videoUri,audioUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityCompat.requestPermissions(ChatActivity.this, PERMISSIONS_REQUIRED, REQUEST_PERMISSIONS); setContentView(R.layout.activity_chat); View findViewById = findViewById(R.id.bottom_sheet); bottom_sheet = findViewById; mBehavior = BottomSheetBehavior.from(findViewById); View inflate = getLayoutInflater().inflate(R.layout.sheet_menu, null); mBottomSheetDialog = new BottomSheetDialog(ChatActivity.this); mBottomSheetDialog.setContentView(inflate); selectIMG = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectIMG); selectMP3 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP3); selectMP4 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP4); seenAllMessages(); prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); FUserID = getIntent().getStringExtra("frontuserid"); messagelList = new ArrayList<>(); messagesAdapter = new MessagesAdapter(ChatActivity.this,messagelList); lyt_back = (LinearLayout)findViewById(R.id.lyt_back); image = (com.mikhaellopez.circularimageview.CircularImageView)findViewById(R.id.image); username = (TextView)findViewById(R.id.username); IsOnline = (TextView)findViewById(R.id.onlinestatus); text_content = (EditText)findViewById(R.id.text_content); attachment = (ImageView)findViewById(R.id.attachment); btn_send = (FloatingActionButton)findViewById(R.id.btn_send); recyclerView = (RecyclerView)findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(ChatActivity.this)); getAllMessages(); getFrontUsrDetails(); btn_send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(text_content.getText().toString().isEmpty()){ Toast.makeText(ChatActivity.this, "Can't send empty message", Toast.LENGTH_SHORT).show(); } else{ SendMessage(); } } }); attachment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBottomSheetDialog(); } }); lyt_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } private void SendMessage() { Date currentTime = Calendar.getInstance().getTime(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault()); String currentDateandTime = sdf.format(currentTime); DatabaseReference reference = FirebaseDatabase.getInstance().getReference("ChatMessages"); String MessageID = reference.push().getKey(); HashMap<String , String> messageMap = new HashMap<>(); messageMap.put("Sender",prefs.getString("userID",null)); messageMap.put("Reciver",FUserID); messageMap.put("MsgType","text"); messageMap.put("Content",text_content.getText().toString()); messageMap.put("DateTime",currentDateandTime); messageMap.put("isSeen","false"); messageMap.put("MsgID",MessageID); reference.child(MessageID).setValue(messageMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ DatabaseReference reference2 = FirebaseDatabase.getInstance().getReference("ChatLists").child(prefs.getString("userID",null)); HashMap<String , String> Map = new HashMap<>(); Map.put("FrontUserID",FUserID); Map.put("LastMessage",text_content.getText().toString()); reference2.child(FUserID).setValue(Map); DatabaseReference reference3 = FirebaseDatabase.getInstance().getReference("ChatLists").child(FUserID); HashMap<String , String> Mapp = new HashMap<>(); Mapp.put("FrontUserID",prefs.getString("userID",null)); Mapp.put("LastMessage",text_content.getText().toString()); reference3.child(prefs.getString("userID",null)).setValue(Mapp); } } }); } private void getAllMessages(){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference("ChatMessages"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { messagelList.clear(); for(DataSnapshot snapshot1 : snapshot.getChildren()){ String sender = snapshot1.child("Sender").getValue().toString(); String receiver = snapshot1.child("Reciver").getValue().toString(); String type = snapshot1.child("MsgType").getValue().toString(); String content = snapshot1.child("Content").getValue().toString(); String time = snapshot1.child("DateTime").getValue().toString(); String seen = snapshot1.child("isSeen").getValue().toString(); String msgid = snapshot1.child("MsgID").getValue().toString(); if((sender.equals(prefs.getString("userID",null)) && receiver.equals(FUserID)) || (sender.equals(FUserID) && receiver.equals(prefs.getString("userID",null))) ){ messagelList.add(new MessageModel(sender,receiver,type,content,time,seen,msgid)); } } messagesAdapter = new MessagesAdapter(ChatActivity.this,messagelList); recyclerView.setAdapter(messagesAdapter); recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount()-1); } @Override public void onCancelled(@NonNull DatabaseError error) { Toast.makeText(ChatActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void showBottomSheetDialog() { if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) { mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } View inflate = getLayoutInflater().inflate(R.layout.sheet_menu, null); mBottomSheetDialog = new BottomSheetDialog(this); mBottomSheetDialog.setContentView(inflate); selectIMG = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectIMG); selectMP3 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP3); selectMP4 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP4); if (Build.VERSION.SDK_INT >= 21) { mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } mBottomSheetDialog.show(); this.mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialogInterface) { mBottomSheetDialog = null; } }); selectMP4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Video"), 3); } }); selectIMG.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image"), 1); } }); selectMP3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("audio/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Music"), 2); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==1 && resultCode == RESULT_OK && data != null && data.getData() != null){ imageUri = data.getData(); Intent intent = new Intent(ChatActivity.this,SendChatFilesActivity.class); intent.putExtra("type","image"); intent.putExtra("data",data.getData().toString()); intent.putExtra("frontUser",FUserID); startActivity(intent); } if(requestCode==2 && resultCode == RESULT_OK && data != null && data.getData() != null){ audioUri = data.getData(); Intent intent = new Intent(ChatActivity.this,SendChatFilesActivity.class); intent.putExtra("type","audio"); intent.putExtra("data",data.getData().toString()); intent.putExtra("frontUser",FUserID); startActivity(intent); } if(requestCode==3 && resultCode == RESULT_OK && data != null && data.getData() != null){ videoUri = data.getData(); Intent intent = new Intent(ChatActivity.this,SendChatFilesActivity.class); intent.putExtra("type","video"); intent.putExtra("data",data.getData().toString()); intent.putExtra("frontUser",FUserID); startActivity(intent); } } private void getFrontUsrDetails(){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference("UserAccountSettings").child(FUserID); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String usern = snapshot.child("username").getValue().toString(); String proPic = snapshot.child("profile_photo").getValue().toString(); username.setText(usern); Picasso.get().load(proPic).into(image); } @Override public void onCancelled(@NonNull DatabaseError error) { Toast.makeText(ChatActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void seenAllMessages() { DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("ChatMessages"); databaseRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot msg : snapshot.getChildren()) { if(msg.child("Reciver").getValue().toString().equals(prefs.getString("userID",null)) && msg.child("Sender").getValue().toString().equals(FUserID)){ if(msg.child("isSeen").equals("false")){ DatabaseReference databaseRefr = FirebaseDatabase.getInstance().getReference("ChatMessages").child(msg.getKey().toString()); databaseRefr.child("isSeen").setValue("true"); } } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }
UTF-8
Java
14,848
java
ChatActivity.java
Java
[]
null
[]
package com.vsn.omino.activites; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.wear.widget.CircledImageView; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.squareup.picasso.Picasso; import com.vsn.omino.Adapters.MessagesAdapter; import com.vsn.omino.R; import com.vsn.omino.models.MessageModel; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; public class ChatActivity extends AppCompatActivity { private BottomSheetBehavior mBehavior; private BottomSheetDialog mBottomSheetDialog; LinearLayout selectIMG,selectMP4,selectMP3; MessagesAdapter messagesAdapter; List<MessageModel> messagelList; String FUserID; LinearLayout lyt_back; com.mikhaellopez.circularimageview.CircularImageView image; TextView username,IsOnline; EditText text_content; ImageView attachment; FloatingActionButton btn_send; public static final String MY_PREFS_NAME = "MyPrefsFile"; SharedPreferences prefs; RecyclerView recyclerView; private View bottom_sheet; private static final int REQUEST_PERMISSIONS = 100; private static final String PERMISSIONS_REQUIRED[] = new String[]{ android.Manifest.permission.READ_PHONE_STATE }; SendChatFilesActivity sendChatFilesActivity; Uri imageUri,videoUri,audioUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityCompat.requestPermissions(ChatActivity.this, PERMISSIONS_REQUIRED, REQUEST_PERMISSIONS); setContentView(R.layout.activity_chat); View findViewById = findViewById(R.id.bottom_sheet); bottom_sheet = findViewById; mBehavior = BottomSheetBehavior.from(findViewById); View inflate = getLayoutInflater().inflate(R.layout.sheet_menu, null); mBottomSheetDialog = new BottomSheetDialog(ChatActivity.this); mBottomSheetDialog.setContentView(inflate); selectIMG = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectIMG); selectMP3 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP3); selectMP4 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP4); seenAllMessages(); prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); FUserID = getIntent().getStringExtra("frontuserid"); messagelList = new ArrayList<>(); messagesAdapter = new MessagesAdapter(ChatActivity.this,messagelList); lyt_back = (LinearLayout)findViewById(R.id.lyt_back); image = (com.mikhaellopez.circularimageview.CircularImageView)findViewById(R.id.image); username = (TextView)findViewById(R.id.username); IsOnline = (TextView)findViewById(R.id.onlinestatus); text_content = (EditText)findViewById(R.id.text_content); attachment = (ImageView)findViewById(R.id.attachment); btn_send = (FloatingActionButton)findViewById(R.id.btn_send); recyclerView = (RecyclerView)findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(ChatActivity.this)); getAllMessages(); getFrontUsrDetails(); btn_send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(text_content.getText().toString().isEmpty()){ Toast.makeText(ChatActivity.this, "Can't send empty message", Toast.LENGTH_SHORT).show(); } else{ SendMessage(); } } }); attachment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showBottomSheetDialog(); } }); lyt_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } private void SendMessage() { Date currentTime = Calendar.getInstance().getTime(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault()); String currentDateandTime = sdf.format(currentTime); DatabaseReference reference = FirebaseDatabase.getInstance().getReference("ChatMessages"); String MessageID = reference.push().getKey(); HashMap<String , String> messageMap = new HashMap<>(); messageMap.put("Sender",prefs.getString("userID",null)); messageMap.put("Reciver",FUserID); messageMap.put("MsgType","text"); messageMap.put("Content",text_content.getText().toString()); messageMap.put("DateTime",currentDateandTime); messageMap.put("isSeen","false"); messageMap.put("MsgID",MessageID); reference.child(MessageID).setValue(messageMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ DatabaseReference reference2 = FirebaseDatabase.getInstance().getReference("ChatLists").child(prefs.getString("userID",null)); HashMap<String , String> Map = new HashMap<>(); Map.put("FrontUserID",FUserID); Map.put("LastMessage",text_content.getText().toString()); reference2.child(FUserID).setValue(Map); DatabaseReference reference3 = FirebaseDatabase.getInstance().getReference("ChatLists").child(FUserID); HashMap<String , String> Mapp = new HashMap<>(); Mapp.put("FrontUserID",prefs.getString("userID",null)); Mapp.put("LastMessage",text_content.getText().toString()); reference3.child(prefs.getString("userID",null)).setValue(Mapp); } } }); } private void getAllMessages(){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference("ChatMessages"); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { messagelList.clear(); for(DataSnapshot snapshot1 : snapshot.getChildren()){ String sender = snapshot1.child("Sender").getValue().toString(); String receiver = snapshot1.child("Reciver").getValue().toString(); String type = snapshot1.child("MsgType").getValue().toString(); String content = snapshot1.child("Content").getValue().toString(); String time = snapshot1.child("DateTime").getValue().toString(); String seen = snapshot1.child("isSeen").getValue().toString(); String msgid = snapshot1.child("MsgID").getValue().toString(); if((sender.equals(prefs.getString("userID",null)) && receiver.equals(FUserID)) || (sender.equals(FUserID) && receiver.equals(prefs.getString("userID",null))) ){ messagelList.add(new MessageModel(sender,receiver,type,content,time,seen,msgid)); } } messagesAdapter = new MessagesAdapter(ChatActivity.this,messagelList); recyclerView.setAdapter(messagesAdapter); recyclerView.smoothScrollToPosition(recyclerView.getAdapter().getItemCount()-1); } @Override public void onCancelled(@NonNull DatabaseError error) { Toast.makeText(ChatActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void showBottomSheetDialog() { if (mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) { mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } View inflate = getLayoutInflater().inflate(R.layout.sheet_menu, null); mBottomSheetDialog = new BottomSheetDialog(this); mBottomSheetDialog.setContentView(inflate); selectIMG = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectIMG); selectMP3 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP3); selectMP4 = (LinearLayout) mBottomSheetDialog.findViewById(R.id.selectMP4); if (Build.VERSION.SDK_INT >= 21) { mBottomSheetDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); } mBottomSheetDialog.show(); this.mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { public void onDismiss(DialogInterface dialogInterface) { mBottomSheetDialog = null; } }); selectMP4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Video"), 3); } }); selectIMG.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image"), 1); } }); selectMP3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("audio/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Music"), 2); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==1 && resultCode == RESULT_OK && data != null && data.getData() != null){ imageUri = data.getData(); Intent intent = new Intent(ChatActivity.this,SendChatFilesActivity.class); intent.putExtra("type","image"); intent.putExtra("data",data.getData().toString()); intent.putExtra("frontUser",FUserID); startActivity(intent); } if(requestCode==2 && resultCode == RESULT_OK && data != null && data.getData() != null){ audioUri = data.getData(); Intent intent = new Intent(ChatActivity.this,SendChatFilesActivity.class); intent.putExtra("type","audio"); intent.putExtra("data",data.getData().toString()); intent.putExtra("frontUser",FUserID); startActivity(intent); } if(requestCode==3 && resultCode == RESULT_OK && data != null && data.getData() != null){ videoUri = data.getData(); Intent intent = new Intent(ChatActivity.this,SendChatFilesActivity.class); intent.putExtra("type","video"); intent.putExtra("data",data.getData().toString()); intent.putExtra("frontUser",FUserID); startActivity(intent); } } private void getFrontUsrDetails(){ DatabaseReference reference = FirebaseDatabase.getInstance().getReference("UserAccountSettings").child(FUserID); reference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String usern = snapshot.child("username").getValue().toString(); String proPic = snapshot.child("profile_photo").getValue().toString(); username.setText(usern); Picasso.get().load(proPic).into(image); } @Override public void onCancelled(@NonNull DatabaseError error) { Toast.makeText(ChatActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void seenAllMessages() { DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("ChatMessages"); databaseRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot msg : snapshot.getChildren()) { if(msg.child("Reciver").getValue().toString().equals(prefs.getString("userID",null)) && msg.child("Sender").getValue().toString().equals(FUserID)){ if(msg.child("isSeen").equals("false")){ DatabaseReference databaseRefr = FirebaseDatabase.getInstance().getReference("ChatMessages").child(msg.getKey().toString()); databaseRefr.child("isSeen").setValue("true"); } } } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } }
14,848
0.639749
0.637325
342
42.418129
32.039413
180
false
false
0
0
0
0
0
0
0.77193
false
false
12
9a509f07ffb07555bd2e7144d7dca938d263116f
4,595,615,034,956
0e4a7d38a8ec2fc11db9f95aebd270406db2f1d8
/lotr/common/entity/npc/LOTREntityDolGuldurOrcTrader.java
87d9ac24d693c235e51083b607072ee704725a3b
[]
no_license
KyberJeffHason/FA-help
https://github.com/KyberJeffHason/FA-help
fe07812a24b3295e8ca21ab2cbe948dd54e650fe
0f0775a429fa1751fe699d8a7072f92e83dca101
refs/heads/main
2022-07-29T20:25:24.836000
2021-04-28T19:53:52
2021-04-28T19:53:52
356,083,269
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lotr.common.entity.npc; import lotr.common.*; import net.minecraft.entity.IEntityLivingData; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class LOTREntityDolGuldurOrcTrader extends LOTREntityDolGuldurOrc implements LOTRTradeable.Smith { public LOTREntityDolGuldurOrcTrader(World world) { super(world); this.addTargetTasks(false); } @Override public LOTRTradeEntries getBuyPool() { return LOTRTradeEntries.DOL_GULDUR_TRADER_BUY; } @Override public LOTRTradeEntries getSellPool() { return LOTRTradeEntries.DOL_GULDUR_TRADER_SELL; } @Override public IEntityLivingData onSpawnWithEgg(IEntityLivingData data) { data = super.onSpawnWithEgg(data); this.npcItemsInv.setMeleeWeapon(new ItemStack(LOTRMod.daggerDolGuldurPoisoned)); this.npcItemsInv.setIdleItem(this.npcItemsInv.getMeleeWeapon()); return data; } @Override public float getAlignmentBonus() { return 2.0f; } @Override public boolean canTradeWith(EntityPlayer entityplayer) { return LOTRLevelData.getData(entityplayer).getAlignment(this.getFaction()) >= 100.0f && this.isFriendly(entityplayer); } @Override public void onPlayerTrade(EntityPlayer entityplayer, LOTRTradeEntries.TradeType type, ItemStack itemstack) { LOTRLevelData.getData(entityplayer).addAchievement(LOTRAchievement.tradeDolGuldurTrader); } @Override public boolean shouldTraderRespawn() { return true; } @Override public String getSpeechBank(EntityPlayer entityplayer) { if(this.isFriendly(entityplayer)) { if(this.canTradeWith(entityplayer)) { return "dolGuldur/trader/friendly"; } return "dolGuldur/trader/neutral"; } return "dolGuldur/orc/hostile"; } }
UTF-8
Java
1,953
java
LOTREntityDolGuldurOrcTrader.java
Java
[]
null
[]
package lotr.common.entity.npc; import lotr.common.*; import net.minecraft.entity.IEntityLivingData; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class LOTREntityDolGuldurOrcTrader extends LOTREntityDolGuldurOrc implements LOTRTradeable.Smith { public LOTREntityDolGuldurOrcTrader(World world) { super(world); this.addTargetTasks(false); } @Override public LOTRTradeEntries getBuyPool() { return LOTRTradeEntries.DOL_GULDUR_TRADER_BUY; } @Override public LOTRTradeEntries getSellPool() { return LOTRTradeEntries.DOL_GULDUR_TRADER_SELL; } @Override public IEntityLivingData onSpawnWithEgg(IEntityLivingData data) { data = super.onSpawnWithEgg(data); this.npcItemsInv.setMeleeWeapon(new ItemStack(LOTRMod.daggerDolGuldurPoisoned)); this.npcItemsInv.setIdleItem(this.npcItemsInv.getMeleeWeapon()); return data; } @Override public float getAlignmentBonus() { return 2.0f; } @Override public boolean canTradeWith(EntityPlayer entityplayer) { return LOTRLevelData.getData(entityplayer).getAlignment(this.getFaction()) >= 100.0f && this.isFriendly(entityplayer); } @Override public void onPlayerTrade(EntityPlayer entityplayer, LOTRTradeEntries.TradeType type, ItemStack itemstack) { LOTRLevelData.getData(entityplayer).addAchievement(LOTRAchievement.tradeDolGuldurTrader); } @Override public boolean shouldTraderRespawn() { return true; } @Override public String getSpeechBank(EntityPlayer entityplayer) { if(this.isFriendly(entityplayer)) { if(this.canTradeWith(entityplayer)) { return "dolGuldur/trader/friendly"; } return "dolGuldur/trader/neutral"; } return "dolGuldur/orc/hostile"; } }
1,953
0.704045
0.700973
63
30
30.30899
126
false
false
0
0
0
0
0
0
0.365079
false
false
12
aa8fe05d803f9f103f3d6d8b334f88ac1e7cfcde
26,645,977,151,910
e4f9d85b1046eb4f322a8e6c9112662637e1e32b
/src/main/java/EchoProtocol.java
22422cc304c1d0fdf6e126b64e56d2220b40a18d
[]
no_license
nHiRanZ/threading-training
https://github.com/nHiRanZ/threading-training
5cd2eda8ce2977a729d1eb91c432d57246c9010b
f25d8a908d061a13c52182bddf3d25bcbbd6c7ff
refs/heads/master
2021-02-27T06:18:18.834000
2020-03-07T07:26:17
2020-03-07T07:26:17
245,587,171
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import domain.Inventory; import domain.Product; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class EchoProtocol { public String processInput(String input) { return input.toUpperCase(); } public static List<Inventory> processInventory(String request) { return Arrays.stream(request.split("\n")). map(s -> s.split(",")) .map(o -> new Inventory(o[0], o[1])) .collect(Collectors.toList()); } public static List<Product> processProducts(String request) { return Arrays.stream(request.split("\n")). map(s -> s.split(",")) .map(o -> new Product(o[0], o[1], o[2])) .collect(Collectors.toList()); } }
UTF-8
Java
786
java
EchoProtocol.java
Java
[]
null
[]
import domain.Inventory; import domain.Product; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class EchoProtocol { public String processInput(String input) { return input.toUpperCase(); } public static List<Inventory> processInventory(String request) { return Arrays.stream(request.split("\n")). map(s -> s.split(",")) .map(o -> new Inventory(o[0], o[1])) .collect(Collectors.toList()); } public static List<Product> processProducts(String request) { return Arrays.stream(request.split("\n")). map(s -> s.split(",")) .map(o -> new Product(o[0], o[1], o[2])) .collect(Collectors.toList()); } }
786
0.586514
0.580153
26
29.23077
21.559055
68
false
false
0
0
0
0
0
0
0.5
false
false
12
bcb1acc977d11edef3668e6a8a07560c254491a9
28,054,726,425,150
8e691ee00f4b5e4390053e38660574c55e54da0f
/app/src/main/java/gcm/android/hmkcode/com/food/ShoppingLists.java
72ad0d6c03112ef8177ac15f0f06262b64f30c45
[]
no_license
mitchcork93/NomNom
https://github.com/mitchcork93/NomNom
ca60e538b7160883f01837b30ddd8360d1b6c1c7
8954b13817ba80629a77bf31be50ae25f1151dd5
refs/heads/master
2021-01-10T06:43:12.971000
2016-04-11T11:37:44
2016-04-11T11:37:44
53,694,646
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gcm.android.hmkcode.com.food; import android.app.ListActivity; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; public class ShoppingLists extends ListActivity { public ArrayList<HashMap<String, String>> lists; public ArrayList<List> allLists; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shopping_lists); setLists(); generateListMap(); generateListView(); ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { // getting values from selected ListItem String ids = ((TextView) view.findViewById(R.id.id)).getText().toString(); String listName = ((TextView) view.findViewById(R.id.name)).getText().toString(); Intent in = new Intent(getApplicationContext(), SelectedList.class); in.putExtra("id", ids); in.putExtra("name",listName); startActivity(in); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_shopping_lists, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void setLists(){ DBhelper db = new DBhelper(this); allLists = db.getAllLists(); if(allLists.size()==0) { Toast.makeText(this, "No Lists Created",Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } } public void generateListMap(){ lists = new ArrayList<HashMap<String, String>>(); for(int i=0; i<allLists.size(); i++) { HashMap<String, String> listMap = new HashMap<String, String>(); listMap.put("name",allLists.get(i).getName()); listMap.put("date","Date Created: " + allLists.get(i).getDate()); listMap.put("id","List ID: " + allLists.get(i).getId()); // listMap.put("readyInMinutes", ready); // adding contact to contact list lists.add(listMap); } } public void generateListView(){ ListAdapter adapter = new SimpleAdapter( ShoppingLists.this, lists, R.layout.list_shopping, new String[] { "name", "date", "id"}, new int[] { R.id.name, R.id.date,R.id.id}); setListAdapter(adapter); } }
UTF-8
Java
3,584
java
ShoppingLists.java
Java
[]
null
[]
package gcm.android.hmkcode.com.food; import android.app.ListActivity; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; public class ShoppingLists extends ListActivity { public ArrayList<HashMap<String, String>> lists; public ArrayList<List> allLists; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shopping_lists); setLists(); generateListMap(); generateListView(); ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view,int position, long id) { // getting values from selected ListItem String ids = ((TextView) view.findViewById(R.id.id)).getText().toString(); String listName = ((TextView) view.findViewById(R.id.name)).getText().toString(); Intent in = new Intent(getApplicationContext(), SelectedList.class); in.putExtra("id", ids); in.putExtra("name",listName); startActivity(in); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_shopping_lists, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void setLists(){ DBhelper db = new DBhelper(this); allLists = db.getAllLists(); if(allLists.size()==0) { Toast.makeText(this, "No Lists Created",Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } } public void generateListMap(){ lists = new ArrayList<HashMap<String, String>>(); for(int i=0; i<allLists.size(); i++) { HashMap<String, String> listMap = new HashMap<String, String>(); listMap.put("name",allLists.get(i).getName()); listMap.put("date","Date Created: " + allLists.get(i).getDate()); listMap.put("id","List ID: " + allLists.get(i).getId()); // listMap.put("readyInMinutes", ready); // adding contact to contact list lists.add(listMap); } } public void generateListView(){ ListAdapter adapter = new SimpleAdapter( ShoppingLists.this, lists, R.layout.list_shopping, new String[] { "name", "date", "id"}, new int[] { R.id.name, R.id.date,R.id.id}); setListAdapter(adapter); } }
3,584
0.627232
0.626395
104
33.46154
25.8925
100
false
false
0
0
0
0
0
0
0.769231
false
false
12
2179fae52c4c73c56e5a1e27587894e51f1f3bfa
10,831,907,554,178
357340c58c225a4e5720408760262d122ac1b88c
/src/chapter19enum/Competitor.java
4660f8997dafae3d3e753e59b5c1fa0903210b98
[]
no_license
gleeman1987/ThinkingInJava
https://github.com/gleeman1987/ThinkingInJava
f0221cd2e71ddfa61ac52f12879e4563d3a165b3
79d21a7aa814c79bd1da24e59c7fed322b94ba3c
refs/heads/master
2020-12-02T21:22:00.109000
2017-12-22T07:23:21
2017-12-22T07:23:21
96,301,428
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter19enum; /** * Authur:zhengjun * E-mail:zhengjun1987@outlook.com * Date:2017/12/3 * Project:ThinkingInJava */ public interface Competitor<T extends Competitor<T>> { Outcome compete(T competitor); }
UTF-8
Java
222
java
Competitor.java
Java
[ { "context": "package chapter19enum;\n\n/**\n * Authur:zhengjun\n * E-mail:zhengjun1987@outlook.com\n * Date:2017/1", "end": 46, "score": 0.9995193481445312, "start": 38, "tag": "USERNAME", "value": "zhengjun" }, { "context": " chapter19enum;\n\n/**\n * Authur:zhengjun\n * E-mail:zhengjun1987@outlook.com\n * Date:2017/12/3\n * Project:ThinkingInJava\n */\np", "end": 81, "score": 0.9999275207519531, "start": 57, "tag": "EMAIL", "value": "zhengjun1987@outlook.com" } ]
null
[]
package chapter19enum; /** * Authur:zhengjun * E-mail:<EMAIL> * Date:2017/12/3 * Project:ThinkingInJava */ public interface Competitor<T extends Competitor<T>> { Outcome compete(T competitor); }
205
0.72973
0.671171
11
19.181818
16.29734
54
false
false
0
0
0
0
0
0
0.181818
false
false
12
d26ff0fbf4c512c2e671b79fa9c63818d4fdd8d2
9,792,525,462,692
3846b312553bc3e3deb65ccb7fb227d94aa6e40f
/src/main/java/by/spetr/web/model/entity/Message.java
af8738818cad0640adcae4e5a3ce9d4f91f774ad
[]
no_license
alexridvansky/Java-EPAM-HTP16-FinalWeb
https://github.com/alexridvansky/Java-EPAM-HTP16-FinalWeb
2ef9bbc047acffa8f3f06e76c5e4aa5288e9ebc0
d4f2bf37358d88b51e91604b1c9bae8e5035f259
refs/heads/main
2023-07-17T11:13:34.759000
2021-08-27T05:13:24
2021-08-27T05:13:24
379,576,344
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.spetr.web.model.entity; import java.io.Serializable; import java.time.LocalDateTime; public class Message extends AbstractEntity implements Serializable { private long messageId; private String topic; private String message; private long senderId; private long receiverId; private LocalDateTime dateSent; private LocalDateTime dateRead; }
UTF-8
Java
381
java
Message.java
Java
[]
null
[]
package by.spetr.web.model.entity; import java.io.Serializable; import java.time.LocalDateTime; public class Message extends AbstractEntity implements Serializable { private long messageId; private String topic; private String message; private long senderId; private long receiverId; private LocalDateTime dateSent; private LocalDateTime dateRead; }
381
0.771654
0.771654
15
24.4
17.749367
69
false
false
0
0
0
0
0
0
0.666667
false
false
12
2b6bfe491f319b48283ce9373f571a21a061a896
12,953,621,431,289
ae518daccaffbc41a9c7b5f8866c661786657b6f
/src/main/java/com/liuhao/cms/dao/CollectDao.java
55f132a24c68781283c97bc41f5c05ced852a310
[]
no_license
luojianwu666/liuhao-cms
https://github.com/luojianwu666/liuhao-cms
22ddfb5dacd6a96695b95a4bea578b5b789e350b
d0a94cf894577946dca13a3c21a36bf4260b623d
refs/heads/master
2022-11-05T09:58:35.577000
2020-02-20T00:21:08
2020-02-20T00:21:08
241,761,166
0
0
null
false
2022-11-16T08:56:24
2020-02-20T00:53:36
2020-02-20T00:54:15
2022-11-16T08:56:21
1,417
0
0
14
JavaScript
false
false
package com.liuhao.cms.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.liuhao.cms.pojo.Collect; public interface CollectDao { List<Collect> selectByUserId(@Param("collect")Collect collect); int deleteById(Integer id); int insert(@Param("collect")Collect collect); }
UTF-8
Java
314
java
CollectDao.java
Java
[]
null
[]
package com.liuhao.cms.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.liuhao.cms.pojo.Collect; public interface CollectDao { List<Collect> selectByUserId(@Param("collect")Collect collect); int deleteById(Integer id); int insert(@Param("collect")Collect collect); }
314
0.761146
0.761146
18
16.444445
20.081009
64
false
false
0
0
0
0
0
0
0.611111
false
false
12
a432f84a206d1a91b555b1a648b24b780bbf2d25
12,953,621,433,491
f3f63b9b1fbd41d9feaf5ebade11bd8df1b4cc46
/src/main/java/pl/currency/exchange/clients/model/Table.java
9fd5ae9ed970ba8a327fa2129bff7c661f108a3f
[]
no_license
astroamator/wymiany
https://github.com/astroamator/wymiany
59510b2cd4dcabf39a25432c863dd28867c007cc
4b8dfd2118d1a0fdd9e04607cb4d2c31ca9b2347
refs/heads/master
2023-06-20T20:26:00.006000
2021-07-31T08:40:34
2021-07-31T08:40:34
391,277,535
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pl.currency.exchange.clients.model; import java.util.List; import lombok.Data; /** * * @author rober */ @Data public class Table { private String table; private String currency; private String code; private List<Rate> rates; }
UTF-8
Java
462
java
Table.java
Java
[ { "context": ".List;\r\nimport lombok.Data;\r\n\r\n/**\r\n *\r\n * @author rober\r\n */\r\n@Data\r\npublic class Table {\r\n private Stri", "end": 309, "score": 0.8655372262001038, "start": 304, "tag": "USERNAME", "value": "rober" } ]
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 pl.currency.exchange.clients.model; import java.util.List; import lombok.Data; /** * * @author rober */ @Data public class Table { private String table; private String currency; private String code; private List<Rate> rates; }
462
0.681818
0.681818
21
20
20.526405
79
false
false
0
0
0
0
0
0
0.47619
false
false
12
d64f72e1f84236b285d0a3db9297de4810a52cef
17,463,337,087,391
bf60cf555b2e8594c9bd8e1cbbf9b0ca27535a46
/Method Overloading/src/method_4.java
c8dc0f5f58d7bdaa766e1dbd4def364fe0831a23
[]
no_license
haritha281/JAVA
https://github.com/haritha281/JAVA
222e4dd54a582e22d2d90b5c479aef5f30593cfc
f5826c4a240a4160f4281fb58dd68d7626cb35c6
refs/heads/master
2023-04-14T06:28:39.472000
2021-05-01T15:05:41
2021-05-01T15:05:41
363,394,220
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//4. Write two methods with the same name and same number of parameters of different //type and call from main method public class method_4 { void m1(int a, String name){ System.out.println("Method 1, a="+a+" name="+name); } void m1(String name, int a){ System.out.println("Method 1, name="+name+" a="+a); } public static void main(String[] args) { method_4 obj=new method_4(); obj.m1(5, "haritha"); obj.m1("rathnam",20); } }
UTF-8
Java
488
java
method_4.java
Java
[ { "context": " method_4 obj=new method_4(); \n obj.m1(5, \"haritha\");\n obj.m1(\"rathnam\",20);\n } \n}\n\n", "end": 443, "score": 0.9996461272239685, "start": 436, "tag": "NAME", "value": "haritha" }, { "context": "4(); \n obj.m1(5, \"haritha\");\n obj.m1(\"rathnam\",20);\n } \n}\n\n", "end": 469, "score": 0.9996518492698669, "start": 462, "tag": "NAME", "value": "rathnam" } ]
null
[]
//4. Write two methods with the same name and same number of parameters of different //type and call from main method public class method_4 { void m1(int a, String name){ System.out.println("Method 1, a="+a+" name="+name); } void m1(String name, int a){ System.out.println("Method 1, name="+name+" a="+a); } public static void main(String[] args) { method_4 obj=new method_4(); obj.m1(5, "haritha"); obj.m1("rathnam",20); } }
488
0.60041
0.57377
15
31.466667
22.144575
84
false
false
0
0
0
0
0
0
0.733333
false
false
12
9fc49422d991a6d40ccc7e073d74e4352279328f
30,820,685,342,942
e8f15a8e0ca2301d011015516818fd945c800bf9
/crmweb/src/com/yuchengtech/bcrm/custmanager/service/CustomerManagerInfoService.java
5a448b75da74f9014fa689abdc828fbc940e62da
[]
no_license
Clown-kakaxi/huayi
https://github.com/Clown-kakaxi/huayi
258b23d069c060ee5ff5f0f7ee1ef2f5b5079199
9778692c8376ca0d7661289dc0897510776accc8
refs/heads/master
2020-04-02T13:03:42.420000
2018-10-26T09:34:31
2018-10-26T09:34:31
154,465,269
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yuchengtech.bcrm.custmanager.service; import org.springframework.stereotype.Service; import com.yuchengtech.bcrm.custmanager.model.OcrmFCmCustMgrInfo; import com.yuchengtech.bcrm.custmanager.model.OcrmFCmCustMgrInfoReview; import com.yuchengtech.bob.common.CommonService; import com.yuchengtech.bob.common.JPABaseDAO; /** * 客户经理信息处理 * @author geyu * 2014-7-7 */ @Service public class CustomerManagerInfoService extends CommonService{ @SuppressWarnings("unchecked") public CustomerManagerInfoService(){ JPABaseDAO<OcrmFCmCustMgrInfo, Long> baseDao = new JPABaseDAO<OcrmFCmCustMgrInfo, Long>(OcrmFCmCustMgrInfo.class); super.setBaseDAO(baseDao); } /** * 保存修改后需审核的客户经理信息 */ public void saveReview(OcrmFCmCustMgrInfoReview cmCustMgrInfoReview){ super.save(cmCustMgrInfoReview); } }
UTF-8
Java
866
java
CustomerManagerInfoService.java
Java
[ { "context": "ob.common.JPABaseDAO;\n\n\n/**\n * 客户经理信息处理\n * @author geyu\n * 2014-7-7\n */\n@Service\npublic class CustomerMan", "end": 366, "score": 0.9995099902153015, "start": 362, "tag": "USERNAME", "value": "geyu" } ]
null
[]
package com.yuchengtech.bcrm.custmanager.service; import org.springframework.stereotype.Service; import com.yuchengtech.bcrm.custmanager.model.OcrmFCmCustMgrInfo; import com.yuchengtech.bcrm.custmanager.model.OcrmFCmCustMgrInfoReview; import com.yuchengtech.bob.common.CommonService; import com.yuchengtech.bob.common.JPABaseDAO; /** * 客户经理信息处理 * @author geyu * 2014-7-7 */ @Service public class CustomerManagerInfoService extends CommonService{ @SuppressWarnings("unchecked") public CustomerManagerInfoService(){ JPABaseDAO<OcrmFCmCustMgrInfo, Long> baseDao = new JPABaseDAO<OcrmFCmCustMgrInfo, Long>(OcrmFCmCustMgrInfo.class); super.setBaseDAO(baseDao); } /** * 保存修改后需审核的客户经理信息 */ public void saveReview(OcrmFCmCustMgrInfoReview cmCustMgrInfoReview){ super.save(cmCustMgrInfoReview); } }
866
0.80122
0.793902
33
23.878788
28.578184
117
false
false
0
0
0
0
0
0
0.818182
false
false
12
fe24076377027049ece883ac5f0c4bc8802799d4
27,307,402,077,450
335b5d01be8174a56fb994147bc6444dde427ae6
/src/main/java/com/salestaxes/tax/ImportTaxCalculationStrategy.java
201e238797f6f3040de9d7a94ab0521aa16f9388
[]
no_license
fabiomrch/sales-taxes-design-patterns
https://github.com/fabiomrch/sales-taxes-design-patterns
a05b3ceeaceb7e3785edc8d0680c459c75f79c60
4d6a7dff58f66022340ef1b41ad391c8d9a5fee7
refs/heads/master
2021-07-20T11:15:59.285000
2019-11-07T22:37:48
2019-11-07T22:37:48
220,339,687
0
0
null
false
2020-10-13T17:17:42
2019-11-07T22:22:22
2019-11-07T22:38:45
2020-10-13T17:17:41
91
0
0
1
Java
false
false
package com.salestaxes.tax; import java.math.BigDecimal; import java.util.ResourceBundle; import com.salestaxes.model.Product; import com.salestaxes.properties.PropertiesResources; import com.salestaxes.utils.PriceRounder; /** * Specific tax calculation algorithm: it considers the import tax rate * @author fab * */ public class ImportTaxCalculationStrategy implements TaxCalculationStrategy { public BigDecimal calculateTax(Product product) { final double importTaxRate = Double.parseDouble(ResourceBundle.getBundle(PropertiesResources.SETTINGS).getString("tax.import.rate")); BigDecimal taxAmount = product.getPrice().multiply(new BigDecimal(product.getTaxRate())); if(product.isImported()) taxAmount = taxAmount.add(product.getPrice().multiply(new BigDecimal(importTaxRate))); return PriceRounder.roundUp(taxAmount); } }
UTF-8
Java
853
java
ImportTaxCalculationStrategy.java
Java
[ { "context": "rithm: it considers the import tax rate\n * @author fab\n *\n */\npublic class ImportTaxCalculationStrategy ", "end": 316, "score": 0.9725508689880371, "start": 313, "tag": "USERNAME", "value": "fab" } ]
null
[]
package com.salestaxes.tax; import java.math.BigDecimal; import java.util.ResourceBundle; import com.salestaxes.model.Product; import com.salestaxes.properties.PropertiesResources; import com.salestaxes.utils.PriceRounder; /** * Specific tax calculation algorithm: it considers the import tax rate * @author fab * */ public class ImportTaxCalculationStrategy implements TaxCalculationStrategy { public BigDecimal calculateTax(Product product) { final double importTaxRate = Double.parseDouble(ResourceBundle.getBundle(PropertiesResources.SETTINGS).getString("tax.import.rate")); BigDecimal taxAmount = product.getPrice().multiply(new BigDecimal(product.getTaxRate())); if(product.isImported()) taxAmount = taxAmount.add(product.getPrice().multiply(new BigDecimal(importTaxRate))); return PriceRounder.roundUp(taxAmount); } }
853
0.794842
0.794842
27
30.592592
35.244396
135
false
false
0
0
0
0
0
0
1
false
false
12
7589dd6b3d722c66828e684901d2ee6522ef24b7
26,396,869,008,244
99f399cbd3a370c1cd43590d082503abc1394dc3
/p2pdinner-clients/p2pdinner-android-client/app/src/main/java/com/p2pdinner/restclient/PlacesServiceManager.java
c7090c690cfa7504048a1f582fbc5eff910cac04
[]
no_license
rajanip2pdinner/p2pdinner
https://github.com/rajanip2pdinner/p2pdinner
67092074ca0b35dd0e723830ff650df0375be0ac
e0ca2a0cd8253fe9e1b7c322e0cc75d95ad3113e
refs/heads/master
2021-03-27T10:11:34.415000
2017-10-16T02:48:41
2017-10-16T02:48:41
61,455,032
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.p2pdinner.restclient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.p2pdinner.common.Constants; import com.p2pdinner.deserializers.DinnerMenuItemDeserializer; import com.p2pdinner.entities.DinnerMenuItem; import com.p2pdinner.entities.DinnerSearchResults; import com.p2pdinner.entities.SearchCriteria; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.json.JSONObject; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.GsonHttpMessageConverter; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import java.util.ArrayList; import java.util.List; import java.util.Locale; import rx.Observable; import rx.Subscriber; /** * Created by rajaniy on 10/7/15. */ public class PlacesServiceManager { private static String TAG = PlacesServiceManager.class.getName(); private RestTemplate restTemplate = null; public PlacesServiceManager(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public Observable<DinnerSearchResults> searchDinnerByLocation(final SearchCriteria searchCriteria, final Locale locale) { return Observable.create(new Observable.OnSubscribe<DinnerSearchResults>() { @Override public void call(Subscriber<? super DinnerSearchResults> subscriber) { Log.d(TAG, "Requesting dinner for address ==> " + searchCriteria.getAddress()); StringBuffer searchQry = new StringBuffer(""); DateTime actualStartTime = DateTime.now(); DateTime actualEndTime = DateTime.now(); actualEndTime = actualStartTime.withTime(23, 59, 59, 0); if (searchCriteria.getStartTime().isAfter(actualStartTime)) { actualStartTime = searchCriteria.getStartTime(); actualEndTime = actualStartTime.withTime(23, 59, 59, 0); } searchQry.append("after_close_time::").append(DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss").withZoneUTC().print(actualStartTime)); searchQry.append("|before_close_time::").append(DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss").withZoneUTC().print(actualEndTime)); searchQry.append("|guests::").append(searchCriteria.getGuests()); searchQry.append("|max_price::").append(searchCriteria.getMaxPrice()); searchQry.append("|min_price::").append(searchCriteria.getMinPrice()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(Constants.P2PDINNER_BASE_URI) .path("/places/nearbysearch") .queryParam("address", searchCriteria.getAddress()) .queryParam("q", searchQry.toString()) .queryParam("locale", locale.toString()) .build(); try { String response = restTemplate.getForObject(uriComponents.toUri(), String.class); Gson gson = new GsonBuilder().registerTypeAdapter(DinnerMenuItem.class, new DinnerMenuItemDeserializer()).create(); DinnerSearchResults results = gson.fromJson(response, DinnerSearchResults.class); subscriber.onNext(results); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }); } }
UTF-8
Java
4,394
java
PlacesServiceManager.java
Java
[ { "context": "servable;\nimport rx.Subscriber;\n\n/**\n * Created by rajaniy on 10/7/15.\n */\npublic class PlacesServiceManager", "end": 1658, "score": 0.9996366500854492, "start": 1651, "tag": "USERNAME", "value": "rajaniy" } ]
null
[]
package com.p2pdinner.restclient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.p2pdinner.common.Constants; import com.p2pdinner.deserializers.DinnerMenuItemDeserializer; import com.p2pdinner.entities.DinnerMenuItem; import com.p2pdinner.entities.DinnerSearchResults; import com.p2pdinner.entities.SearchCriteria; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.json.JSONObject; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.GsonHttpMessageConverter; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import java.util.ArrayList; import java.util.List; import java.util.Locale; import rx.Observable; import rx.Subscriber; /** * Created by rajaniy on 10/7/15. */ public class PlacesServiceManager { private static String TAG = PlacesServiceManager.class.getName(); private RestTemplate restTemplate = null; public PlacesServiceManager(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public Observable<DinnerSearchResults> searchDinnerByLocation(final SearchCriteria searchCriteria, final Locale locale) { return Observable.create(new Observable.OnSubscribe<DinnerSearchResults>() { @Override public void call(Subscriber<? super DinnerSearchResults> subscriber) { Log.d(TAG, "Requesting dinner for address ==> " + searchCriteria.getAddress()); StringBuffer searchQry = new StringBuffer(""); DateTime actualStartTime = DateTime.now(); DateTime actualEndTime = DateTime.now(); actualEndTime = actualStartTime.withTime(23, 59, 59, 0); if (searchCriteria.getStartTime().isAfter(actualStartTime)) { actualStartTime = searchCriteria.getStartTime(); actualEndTime = actualStartTime.withTime(23, 59, 59, 0); } searchQry.append("after_close_time::").append(DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss").withZoneUTC().print(actualStartTime)); searchQry.append("|before_close_time::").append(DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss").withZoneUTC().print(actualEndTime)); searchQry.append("|guests::").append(searchCriteria.getGuests()); searchQry.append("|max_price::").append(searchCriteria.getMaxPrice()); searchQry.append("|min_price::").append(searchCriteria.getMinPrice()); UriComponents uriComponents = UriComponentsBuilder.fromUriString(Constants.P2PDINNER_BASE_URI) .path("/places/nearbysearch") .queryParam("address", searchCriteria.getAddress()) .queryParam("q", searchQry.toString()) .queryParam("locale", locale.toString()) .build(); try { String response = restTemplate.getForObject(uriComponents.toUri(), String.class); Gson gson = new GsonBuilder().registerTypeAdapter(DinnerMenuItem.class, new DinnerMenuItemDeserializer()).create(); DinnerSearchResults results = gson.fromJson(response, DinnerSearchResults.class); subscriber.onNext(results); subscriber.onCompleted(); } catch (Exception e) { subscriber.onError(e); } } }); } }
4,394
0.699363
0.693446
95
45.252632
32.852451
149
false
false
0
0
0
0
0
0
0.852632
false
false
12
6dfdf206ef0d847aa75b2c435eb81b9356e5be22
30,434,138,285,697
b5aedd54e2013e11895c6c4c8ad3eed9018c5d24
/src/java/clases/Indexacion.java
a2ccd17496bfce12622c5c39f000f25a21d8b481
[]
no_license
gastongarcia1996/MotorDeBusquedaTPI
https://github.com/gastongarcia1996/MotorDeBusquedaTPI
b5e092f73bfddc87f89faee2c64e066db999f6f7
aab68334ef4d9a47add44f52576905631eae0f88
refs/heads/master
2020-03-11T01:13:03.836000
2018-05-29T11:14:41
2018-05-29T11:14:41
129,684,771
0
0
null
false
2018-05-27T15:46:23
2018-04-16T04:29:40
2018-05-27T14:22:16
2018-05-27T15:46:22
194,520
0
0
0
JavaScript
false
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 clases; import Database.DBDocumento; import Database.DBManager; import Database.DBTermino; import Database.DBTerminoXDocumento; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import javax.swing.JOptionPane; /** * * @author dlcusr */ public class Indexacion implements Serializable { private Hashtable<String, Termino> ht = new Hashtable<>(); private LinkedList<Documento> al = new LinkedList<>(); private LinkedList<Termino> ll = new LinkedList<>(); private LinkedList<String> nuevos = null; private int cantidad = 0; private File[] lista = null; DBManager db = null; public Indexacion() { } public Indexacion(File[] lista) { this.lista = lista; } /** * Arma el vocabulario del motor; */ public void armar_vocabulario() { Termino t1 = null; String aux = ""; String clave = ""; int countMax = 0; int countMaxAux = 0; FileReader fr = null; BufferedReader br = null; Enumeration enumeration = null; Hashtable<String, Termino> hashAux = new Hashtable<>(); StringTokenizer st = null; try { //db = Datos.getSingleDB(); String s = ""; //File archivo = new File("/home/dlcusr/NetBeansProjects/MotorDeBusquedaTPI/DocumentosTPI"); if (lista == null) { File archivo = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\DocumentosTPI"); lista = archivo.listFiles(); } //ciclo for que recorre la lista de documentos for (int i = 0; i < lista.length; i++) { al.add(new Documento(i, lista[i].getName())); if (validarDocumento(db, lista[i])) { fr = new FileReader(lista[i]); br = new BufferedReader(fr); hashAux = new Hashtable<>(); } else { continue; } // if(!DBDocumento.existeDocumento(db, lista[i].getName())) // { // DBDocumento.insertarDocumento(db, lista[i].getName()); // } //DBDocumento.insertarDocumento(db, lista[i].getName()); //ciclo que toma cada linea del documento while ((s = br.readLine()) != null) { st = new StringTokenizer(s, " ~¼±|\"°!#$%&/()=?¡^¶[]¿-\\/_*³.,«»;:<>+æ’"); //ciclo que recorre las palabras y las agrega a una tabla hash //evitando que no se repitan while (st.hasMoreTokens()) { aux = st.nextToken().toLowerCase(); //aux = aux.replace("'", "''"); //si el termino no esta en la hashtable if (!ht.containsKey(aux)) { t1 = new Termino(aux); hashAux.put(aux, t1); //aux = aux.replace("'", "''"); /* if(!DBTermino.existeTermino(db, aux)) { DBTermino.insertarTermino(db, aux); } */ //aux = aux.replace("''", "'"); ht.put(aux, t1); } else if (!hashAux.containsKey(aux)) { hashAux.put(aux, ht.get(aux)); } } } br.close(); enumeration = hashAux.keys(); while (enumeration.hasMoreElements()) { clave = (String) enumeration.nextElement(); hashAux.get(clave).setCant_doc_aparece(hashAux.get(clave).getCant_doc_aparece() + 1); } hashAux = null; } //db.disconnect(); //guardar_hashtable(); } catch (Exception ex) { System.out.println("Error al leer el archivo " + ex.getMessage()); } System.out.println("Terminó el vocabulario"); for (int i = 0; i < nuevos.size(); i++) { System.out.println("Nuevos doc nº: "+ i +" "+nuevos.get(i)); } } /* private void setear_cant_docs() throws IOException { String palabra = ""; FileReader fr = null; BufferedReader br = null; Hashtable<String, Termino> hashAux = new Hashtable<>(); for(int i = 0; i < lista.length; i++) { fr = new FileReader(lista[i]); br = new BufferedReader(br); while((palabra = br.readLine()) != null) { st = new StringTokenizer(palabra, " ~¼±|\"°!#$%&/()=?¡^¶[]¿-\\/_*³.,«»;:<>+æ’"); while(st.hasMoreTokens()) { if(hashAux) } } } } */ //public void armar_posteo(int desde, int hasta) throws Exception public void armar_posteo() throws Exception { String palabra = ""; int cont = 0; int id_doc = 0; Termino aux = null; Hashtable<String, Termino> hashAux = new Hashtable<>(); FileReader fr = null; BufferedReader br = null; db = Datos.getSingleDB(); ArrayList<String> arrayListAux = DBTermino.selectTerminos(db); Hashtable<String, Termino> aux2 = new Hashtable<>(); StringTokenizer st = null; //ArrayList<String> docs = DBDocumento.getDocsList(); for (String doc : nuevos)//Sacar el 10 { id_doc = DBDocumento.selectDocumentoId(db, doc); /* if (!(docs.contains(lista[i].getName()))) { //JOptionPane.showMessageDialog(null, "Entro al Posteo por: "+lista[i].getName()); if(validarDocumento(db, lista[i])) { fr = new FileReader(lista[i]); br = new BufferedReader(fr); } else continue; */ fr = new FileReader(new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\DocumentosTPI\\" + doc)); br = new BufferedReader(fr); while ((palabra = br.readLine()) != null) { st = new StringTokenizer(palabra, " ~¼±|\"°!#$%&/()=?¡^¶[]¿-\\/_*³.,«»;:<>+æ’"); while (st.hasMoreTokens()) { palabra = st.nextToken().toLowerCase(); if (ht.containsKey(palabra)) { aux = ht.get(palabra); aux.setFrec_aparicion(aux.getFrec_aparicion() + 1); // if (!hashAux.containsKey(palabra)) // { // palabra = palabra.replace("'", "''"); // hashAux.put(palabra, aux); // } if (!arrayListAux.contains(palabra)) { DBTermino.insertarTermino(db, palabra); } if (!aux2.containsKey(palabra)) aux2.put(palabra, aux); } } } //Recorrido de la hashAux insertarABasePosteo(aux2, id_doc); hashAux = new Hashtable<>(); } nuevos = null; db.disconnect(); } /** * Metodo que valida que sea txt y si esta o no en la base de datos * * @param db DBManager * @param f El archivo a validar * @return true sale todo bien, false en caso contrario */ private boolean validarDocumento(DBManager db, File f) { if (es_txt(f)) { if (!DBDocumento.existeDocumento(db, f.getName())) { DBDocumento.insertarDocumento(db, f.getName()); this.nuevos.add(f.getName()); } } else { return false; } return true; } private void insertarABasePosteo(Hashtable<String, Termino> ht, int id_doc) { Enumeration e = ht.keys(); String clave; while (e.hasMoreElements()) { clave = (String) e.nextElement(); DBTerminoXDocumento.insertarTerminoXDocumento(db, clave, id_doc, ht.get(clave).getFrec_aparicion()); clave = clave.replace("''", "'"); this.ht.get(clave).setFrec_aparicion(0); } } public File[] getLista() { return lista; } public void obtenerDocumentos() { try { db = Datos.getSingleDB(); File archivo = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\DocumentosTPI"); File[] lista = archivo.listFiles(); //ciclo for que recorre la lista de documentos for (int i = 0; i < lista.length; i++) { //sl.add(new Documento(i, lista[i].getName())); DBDocumento.insertarDocumento(db, lista[i].getName()); } db.disconnect(); } catch (Exception e) { System.out.println(e.getMessage()); } } public LinkedList<Documento> getDocumentosList() { return al; } public void setDocumentosList(LinkedList<Documento> al) { this.al = al; } public int cantDocs() { return lista.length; } public Hashtable<String, Termino> getHt() { return ht; } public void setHt(Hashtable<String, Termino> ht) { this.ht = ht; } /** * Metodo que recibe un archivo y valida que sea de texto * * @param f: el archivo a validar * @return true si es un archivo txt y false en caso contrario */ private boolean es_txt(File f) { return f.getName().endsWith(".txt") || f.getName().endsWith(".TXT"); } public void setLista(File[] lista) { this.lista = lista; } public Hashtable<String, Termino> crearHash() { Hashtable<String, Termino> tablaTerminos = new Hashtable<>(); try { db = Datos.getSingleDB(); int cantTerminos = DBTermino.countTerminos(db); ArrayList<String> terminos = DBTermino.selectTerminos(db); for (int i = 0; i < cantTerminos; i++) { String word = terminos.get(i); int frecMax = DBTerminoXDocumento.frecuenciaMaxTermino(db, word); int cantApar = DBTerminoXDocumento.contarDocConTermino(db, word); Termino term = new Termino(word, cantApar, frecMax); tablaTerminos.put(word, term); } } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); } return tablaTerminos; } public void guardar_hashtable() throws IOException { File f = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\Hashtable"); FileOutputStream fos = new FileOutputStream(f); ObjectOutputStream oos = new ObjectOutputStream(fos); //oos.writeObject(crearHash()); oos.writeObject(al); oos.writeObject(ht); oos.close(); } public void leer_hashtable() throws IOException, ClassNotFoundException { File f = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\Hashtable"); FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis); al = (LinkedList) ois.readObject(); ht = (Hashtable) ois.readObject(); ois.close(); } public boolean existe_hashtable(String archivo) { File f = new File(archivo); return (f.exists() && f.isFile()); } }
UTF-8
Java
13,143
java
Indexacion.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author dlcusr\n */\npublic class Indexacion implements Serializab", "end": 822, "score": 0.9996300339698792, "start": 816, "tag": "USERNAME", "value": "dlcusr" }, { "context": " File archivo = new File(\"C:\\\\Users\\\\Nico\\\\Documents\\\\Facu\\\\4º\\\\DLC\\\\TP\\\\MotorDeBusquedaTPI", "end": 2046, "score": 0.9946272373199463, "start": 2042, "tag": "NAME", "value": "Nico" }, { "context": " fr = new FileReader(new File(\"C:\\\\Users\\\\Nico\\\\Documents\\\\Facu\\\\4º\\\\DLC\\\\TP\\\\MotorDeBusquedaTPI", "end": 7173, "score": 0.9940729141235352, "start": 7169, "tag": "NAME", "value": "Nico" }, { "context": ";\n File archivo = new File(\"C:\\\\Users\\\\Nico\\\\Documents\\\\Facu\\\\4º\\\\DLC\\\\TP\\\\MotorDeBusquedaTPI", "end": 9894, "score": 0.9944571256637573, "start": 9890, "tag": "NAME", "value": "Nico" }, { "context": "ption\n {\n File f = new File(\"C:\\\\Users\\\\Nico\\\\Documents\\\\Facu\\\\4º\\\\DLC\\\\TP\\\\MotorDeBusquedaTPI", "end": 12225, "score": 0.9962213039398193, "start": 12221, "tag": "NAME", "value": "Nico" }, { "context": "ption\n {\n File f = new File(\"C:\\\\Users\\\\Nico\\\\Documents\\\\Facu\\\\4º\\\\DLC\\\\TP\\\\MotorDeBusquedaTPI", "end": 12659, "score": 0.9969909191131592, "start": 12655, "tag": "NAME", "value": "Nico" } ]
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 clases; import Database.DBDocumento; import Database.DBManager; import Database.DBTermino; import Database.DBTerminoXDocumento; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import javax.swing.JOptionPane; /** * * @author dlcusr */ public class Indexacion implements Serializable { private Hashtable<String, Termino> ht = new Hashtable<>(); private LinkedList<Documento> al = new LinkedList<>(); private LinkedList<Termino> ll = new LinkedList<>(); private LinkedList<String> nuevos = null; private int cantidad = 0; private File[] lista = null; DBManager db = null; public Indexacion() { } public Indexacion(File[] lista) { this.lista = lista; } /** * Arma el vocabulario del motor; */ public void armar_vocabulario() { Termino t1 = null; String aux = ""; String clave = ""; int countMax = 0; int countMaxAux = 0; FileReader fr = null; BufferedReader br = null; Enumeration enumeration = null; Hashtable<String, Termino> hashAux = new Hashtable<>(); StringTokenizer st = null; try { //db = Datos.getSingleDB(); String s = ""; //File archivo = new File("/home/dlcusr/NetBeansProjects/MotorDeBusquedaTPI/DocumentosTPI"); if (lista == null) { File archivo = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\DocumentosTPI"); lista = archivo.listFiles(); } //ciclo for que recorre la lista de documentos for (int i = 0; i < lista.length; i++) { al.add(new Documento(i, lista[i].getName())); if (validarDocumento(db, lista[i])) { fr = new FileReader(lista[i]); br = new BufferedReader(fr); hashAux = new Hashtable<>(); } else { continue; } // if(!DBDocumento.existeDocumento(db, lista[i].getName())) // { // DBDocumento.insertarDocumento(db, lista[i].getName()); // } //DBDocumento.insertarDocumento(db, lista[i].getName()); //ciclo que toma cada linea del documento while ((s = br.readLine()) != null) { st = new StringTokenizer(s, " ~¼±|\"°!#$%&/()=?¡^¶[]¿-\\/_*³.,«»;:<>+æ’"); //ciclo que recorre las palabras y las agrega a una tabla hash //evitando que no se repitan while (st.hasMoreTokens()) { aux = st.nextToken().toLowerCase(); //aux = aux.replace("'", "''"); //si el termino no esta en la hashtable if (!ht.containsKey(aux)) { t1 = new Termino(aux); hashAux.put(aux, t1); //aux = aux.replace("'", "''"); /* if(!DBTermino.existeTermino(db, aux)) { DBTermino.insertarTermino(db, aux); } */ //aux = aux.replace("''", "'"); ht.put(aux, t1); } else if (!hashAux.containsKey(aux)) { hashAux.put(aux, ht.get(aux)); } } } br.close(); enumeration = hashAux.keys(); while (enumeration.hasMoreElements()) { clave = (String) enumeration.nextElement(); hashAux.get(clave).setCant_doc_aparece(hashAux.get(clave).getCant_doc_aparece() + 1); } hashAux = null; } //db.disconnect(); //guardar_hashtable(); } catch (Exception ex) { System.out.println("Error al leer el archivo " + ex.getMessage()); } System.out.println("Terminó el vocabulario"); for (int i = 0; i < nuevos.size(); i++) { System.out.println("Nuevos doc nº: "+ i +" "+nuevos.get(i)); } } /* private void setear_cant_docs() throws IOException { String palabra = ""; FileReader fr = null; BufferedReader br = null; Hashtable<String, Termino> hashAux = new Hashtable<>(); for(int i = 0; i < lista.length; i++) { fr = new FileReader(lista[i]); br = new BufferedReader(br); while((palabra = br.readLine()) != null) { st = new StringTokenizer(palabra, " ~¼±|\"°!#$%&/()=?¡^¶[]¿-\\/_*³.,«»;:<>+æ’"); while(st.hasMoreTokens()) { if(hashAux) } } } } */ //public void armar_posteo(int desde, int hasta) throws Exception public void armar_posteo() throws Exception { String palabra = ""; int cont = 0; int id_doc = 0; Termino aux = null; Hashtable<String, Termino> hashAux = new Hashtable<>(); FileReader fr = null; BufferedReader br = null; db = Datos.getSingleDB(); ArrayList<String> arrayListAux = DBTermino.selectTerminos(db); Hashtable<String, Termino> aux2 = new Hashtable<>(); StringTokenizer st = null; //ArrayList<String> docs = DBDocumento.getDocsList(); for (String doc : nuevos)//Sacar el 10 { id_doc = DBDocumento.selectDocumentoId(db, doc); /* if (!(docs.contains(lista[i].getName()))) { //JOptionPane.showMessageDialog(null, "Entro al Posteo por: "+lista[i].getName()); if(validarDocumento(db, lista[i])) { fr = new FileReader(lista[i]); br = new BufferedReader(fr); } else continue; */ fr = new FileReader(new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\DocumentosTPI\\" + doc)); br = new BufferedReader(fr); while ((palabra = br.readLine()) != null) { st = new StringTokenizer(palabra, " ~¼±|\"°!#$%&/()=?¡^¶[]¿-\\/_*³.,«»;:<>+æ’"); while (st.hasMoreTokens()) { palabra = st.nextToken().toLowerCase(); if (ht.containsKey(palabra)) { aux = ht.get(palabra); aux.setFrec_aparicion(aux.getFrec_aparicion() + 1); // if (!hashAux.containsKey(palabra)) // { // palabra = palabra.replace("'", "''"); // hashAux.put(palabra, aux); // } if (!arrayListAux.contains(palabra)) { DBTermino.insertarTermino(db, palabra); } if (!aux2.containsKey(palabra)) aux2.put(palabra, aux); } } } //Recorrido de la hashAux insertarABasePosteo(aux2, id_doc); hashAux = new Hashtable<>(); } nuevos = null; db.disconnect(); } /** * Metodo que valida que sea txt y si esta o no en la base de datos * * @param db DBManager * @param f El archivo a validar * @return true sale todo bien, false en caso contrario */ private boolean validarDocumento(DBManager db, File f) { if (es_txt(f)) { if (!DBDocumento.existeDocumento(db, f.getName())) { DBDocumento.insertarDocumento(db, f.getName()); this.nuevos.add(f.getName()); } } else { return false; } return true; } private void insertarABasePosteo(Hashtable<String, Termino> ht, int id_doc) { Enumeration e = ht.keys(); String clave; while (e.hasMoreElements()) { clave = (String) e.nextElement(); DBTerminoXDocumento.insertarTerminoXDocumento(db, clave, id_doc, ht.get(clave).getFrec_aparicion()); clave = clave.replace("''", "'"); this.ht.get(clave).setFrec_aparicion(0); } } public File[] getLista() { return lista; } public void obtenerDocumentos() { try { db = Datos.getSingleDB(); File archivo = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\DocumentosTPI"); File[] lista = archivo.listFiles(); //ciclo for que recorre la lista de documentos for (int i = 0; i < lista.length; i++) { //sl.add(new Documento(i, lista[i].getName())); DBDocumento.insertarDocumento(db, lista[i].getName()); } db.disconnect(); } catch (Exception e) { System.out.println(e.getMessage()); } } public LinkedList<Documento> getDocumentosList() { return al; } public void setDocumentosList(LinkedList<Documento> al) { this.al = al; } public int cantDocs() { return lista.length; } public Hashtable<String, Termino> getHt() { return ht; } public void setHt(Hashtable<String, Termino> ht) { this.ht = ht; } /** * Metodo que recibe un archivo y valida que sea de texto * * @param f: el archivo a validar * @return true si es un archivo txt y false en caso contrario */ private boolean es_txt(File f) { return f.getName().endsWith(".txt") || f.getName().endsWith(".TXT"); } public void setLista(File[] lista) { this.lista = lista; } public Hashtable<String, Termino> crearHash() { Hashtable<String, Termino> tablaTerminos = new Hashtable<>(); try { db = Datos.getSingleDB(); int cantTerminos = DBTermino.countTerminos(db); ArrayList<String> terminos = DBTermino.selectTerminos(db); for (int i = 0; i < cantTerminos; i++) { String word = terminos.get(i); int frecMax = DBTerminoXDocumento.frecuenciaMaxTermino(db, word); int cantApar = DBTerminoXDocumento.contarDocConTermino(db, word); Termino term = new Termino(word, cantApar, frecMax); tablaTerminos.put(word, term); } } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); } return tablaTerminos; } public void guardar_hashtable() throws IOException { File f = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\Hashtable"); FileOutputStream fos = new FileOutputStream(f); ObjectOutputStream oos = new ObjectOutputStream(fos); //oos.writeObject(crearHash()); oos.writeObject(al); oos.writeObject(ht); oos.close(); } public void leer_hashtable() throws IOException, ClassNotFoundException { File f = new File("C:\\Users\\Nico\\Documents\\Facu\\4º\\DLC\\TP\\MotorDeBusquedaTPI\\Hashtable"); FileInputStream fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis); al = (LinkedList) ois.readObject(); ht = (Hashtable) ois.readObject(); ois.close(); } public boolean existe_hashtable(String archivo) { File f = new File(archivo); return (f.exists() && f.isFile()); } }
13,143
0.490763
0.488168
420
30.188095
25.977652
134
false
false
0
0
0
0
0
0
0.564286
false
false
12
e4b30034f5bb1291a59d39ef30631d40c1206e0b
31,318,901,592,031
e49349acd95f155e4335e5c0171d3f9ce6d63626
/src/main/java/de/ossi/wolfsbau/db/data/Device.java
25a5ee3f5585d53769516eab61a4a9e572638ea9
[]
no_license
CommentSectionScientist/ModbusTCP
https://github.com/CommentSectionScientist/ModbusTCP
a1064499194cded01784f81d1db0eae839a4fcfa
0111cb9d3d19e4ef2afbe852ec96bd3045b9e89e
refs/heads/master
2022-10-26T08:24:11.826000
2022-10-09T13:09:51
2022-10-09T13:09:51
130,501,411
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.ossi.wolfsbau.db.data; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; import de.ossi.wolfsbau.db.data.persister.LocalDateTimePersister; @DatabaseTable(tableName = "device") public class Device { @DatabaseField(generatedId = true) private long id; @ForeignCollectionField(eager = true) private Collection<Measurement> measurements; @DatabaseField private String name; @DatabaseField private Integer nominalPower; @DatabaseField private String type; @DatabaseField private String serial; @DatabaseField private Integer busAddress; @DatabaseField private String netBiosName; @DatabaseField private String ipAddress; @DatabaseField(persisterClass = LocalDateTimePersister.class, canBeNull = false) private LocalDateTime requestTime; public Device() { // all persisted classes must define a no-arg constructor // with at least package visibility } public void addAll(Collection<Measurement> measurements) { measurements.forEach(this::add); } public void add(Measurement measurement) { if (this.measurements == null) { this.measurements = new ArrayList<>(); } measurement.setDevice(this); this.measurements.add(measurement); } public long getId() { return id; } public void setId(long id) { this.id = id; } public LocalDateTime getRequestTime() { return requestTime; } public void setRequestTime(LocalDateTime requestTime) { this.requestTime = requestTime; } public Collection<Measurement> getMeasurements() { return measurements; } public void setMeasurements(Collection<Measurement> measurements) { this.measurements = measurements; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getNominalPower() { return nominalPower; } public void setNominalPower(Integer nominalPower) { this.nominalPower = nominalPower; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public Integer getBusAddress() { return busAddress; } public void setBusAddress(Integer busAddress) { this.busAddress = busAddress; } public String getNetBiosName() { return netBiosName; } public void setNetBiosName(String netBiosName) { this.netBiosName = netBiosName; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } }
UTF-8
Java
2,727
java
Device.java
Java
[]
null
[]
package de.ossi.wolfsbau.db.data; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.ForeignCollectionField; import com.j256.ormlite.table.DatabaseTable; import de.ossi.wolfsbau.db.data.persister.LocalDateTimePersister; @DatabaseTable(tableName = "device") public class Device { @DatabaseField(generatedId = true) private long id; @ForeignCollectionField(eager = true) private Collection<Measurement> measurements; @DatabaseField private String name; @DatabaseField private Integer nominalPower; @DatabaseField private String type; @DatabaseField private String serial; @DatabaseField private Integer busAddress; @DatabaseField private String netBiosName; @DatabaseField private String ipAddress; @DatabaseField(persisterClass = LocalDateTimePersister.class, canBeNull = false) private LocalDateTime requestTime; public Device() { // all persisted classes must define a no-arg constructor // with at least package visibility } public void addAll(Collection<Measurement> measurements) { measurements.forEach(this::add); } public void add(Measurement measurement) { if (this.measurements == null) { this.measurements = new ArrayList<>(); } measurement.setDevice(this); this.measurements.add(measurement); } public long getId() { return id; } public void setId(long id) { this.id = id; } public LocalDateTime getRequestTime() { return requestTime; } public void setRequestTime(LocalDateTime requestTime) { this.requestTime = requestTime; } public Collection<Measurement> getMeasurements() { return measurements; } public void setMeasurements(Collection<Measurement> measurements) { this.measurements = measurements; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getNominalPower() { return nominalPower; } public void setNominalPower(Integer nominalPower) { this.nominalPower = nominalPower; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSerial() { return serial; } public void setSerial(String serial) { this.serial = serial; } public Integer getBusAddress() { return busAddress; } public void setBusAddress(Integer busAddress) { this.busAddress = busAddress; } public String getNetBiosName() { return netBiosName; } public void setNetBiosName(String netBiosName) { this.netBiosName = netBiosName; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } }
2,727
0.750642
0.747341
135
19.200001
18.618509
81
false
false
0
0
0
0
0
0
1.22963
false
false
12
511ff5f1f513887715e214d8e12aafe4acf282f9
7,499,012,906,286
030134c9af94607f30ab3526f4cc09e844b2ee97
/threed-service/src/main/java/com/hz/business/service/IFileService.java
bd3a5885e6dc8b2cf3d1820ab72cf6a38ad3398d
[]
no_license
hz656765117/threed-service
https://github.com/hz656765117/threed-service
52dac783a9715c2731d66945fe6ab38976eabcc5
44e8276de5ce46e800558e068a97aad36ca61a2a
refs/heads/master
2021-03-22T01:37:05.628000
2017-09-23T16:33:27
2017-09-23T16:33:27
100,085,082
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hz.business.service; import com.hz.base.util.JsonResult; public interface IFileService { /** * 下载文件 * @param username * @param path * @return */ public JsonResult downloadFile(String username, String path); public JsonResult downloadFileById(String username, String id,String type); }
UTF-8
Java
336
java
IFileService.java
Java
[]
null
[]
package com.hz.business.service; import com.hz.base.util.JsonResult; public interface IFileService { /** * 下载文件 * @param username * @param path * @return */ public JsonResult downloadFile(String username, String path); public JsonResult downloadFileById(String username, String id,String type); }
336
0.704268
0.704268
22
13.909091
20.654978
76
false
false
0
0
0
0
0
0
1
false
false
12
852511aa3fda1e2257f16a4265774f4507efc175
17,746,804,870,232
e2dbfa9f5ffceaad85158ca70f97da7069a314c1
/src/javaOverview/ArrayMissingNumber.java
7b99f279ee7226a9343e1b6a905ab7476add95b2
[]
no_license
sagrawal2418/JavaPractice
https://github.com/sagrawal2418/JavaPractice
b6a7ca4326b673cebc104feeb7a59e57a49a7ba1
e292cdb8ed693b87944778000beea2357b92147f
refs/heads/master
2021-02-07T03:47:35.490000
2020-03-28T12:57:17
2020-03-28T12:57:17
243,979,852
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javaOverview; import java.util.Scanner; import java.util.Arrays; /* 10 20 15,14,16,17,20,11,13,14 10 12 18 19 */ public class ArrayMissingNumber { public static void main(String args[]) { int[] numbers ={15,14,16,17,20,11,13,14}; int[] missing = new int[10]; int ind=0; for(int i =10; i<=20; i++){ boolean missing1 = true; for(int j:numbers){ if(i ==j){ missing1=false; } } if(missing1){ missing[ind++] = i; } } System.out.println(Arrays.toString(missing)); } }
UTF-8
Java
570
java
ArrayMissingNumber.java
Java
[]
null
[]
package javaOverview; import java.util.Scanner; import java.util.Arrays; /* 10 20 15,14,16,17,20,11,13,14 10 12 18 19 */ public class ArrayMissingNumber { public static void main(String args[]) { int[] numbers ={15,14,16,17,20,11,13,14}; int[] missing = new int[10]; int ind=0; for(int i =10; i<=20; i++){ boolean missing1 = true; for(int j:numbers){ if(i ==j){ missing1=false; } } if(missing1){ missing[ind++] = i; } } System.out.println(Arrays.toString(missing)); } }
570
0.559649
0.464912
51
10.176471
12.775138
47
false
false
48
0.124561
0
0
0
0
2.098039
false
false
12
9ca9608c912e3c0608898159f9a8692126f681ce
17,308,718,210,717
86ba7486e1d13e6c38bf4268a3a0d6a0104101d2
/app/src/main/java/Service/ApiService.java
79436debdd30266b84da1230193d1c677df4f414
[]
no_license
AddisY/cad-risk-predictor-andrioid-app
https://github.com/AddisY/cad-risk-predictor-andrioid-app
c08086d8c94928f99fde44b4dcb42ec4fec11140
a7c5a35a67e85faf64ad345b26178929c00d0003
refs/heads/master
2020-07-21T20:00:24.300000
2018-11-17T10:30:40
2018-11-17T10:30:40
206,961,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Service; import java.util.Map; import models.AnalysisResult; import models.Data; import models.Doctor; import models.OrdinaryUser; import models.User; import retrofit2.Call; import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * Created by Gurme L on 3/21/2018. */ public interface ApiService { @POST("api/signup/doctor") Call<Void> signupDoctor(@Body Doctor doctor); @POST("api/signup/user") Call<Void> signupOrdinaryUser(@Body OrdinaryUser user); @POST("api/analyze-data") Call<AnalysisResult> analyzeData(@Body Data data); @FormUrlEncoded @POST("api/api-token-auth/") Call<Object> login(@FieldMap Map<String, String> data); }
UTF-8
Java
789
java
ApiService.java
Java
[ { "context": "ed;\nimport retrofit2.http.POST;\n\n/**\n * Created by Gurme L on 3/21/2018.\n */\npublic interface ApiService {\n\n", "end": 363, "score": 0.9898807406425476, "start": 356, "tag": "NAME", "value": "Gurme L" } ]
null
[]
package Service; import java.util.Map; import models.AnalysisResult; import models.Data; import models.Doctor; import models.OrdinaryUser; import models.User; import retrofit2.Call; import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * Created by <NAME> on 3/21/2018. */ public interface ApiService { @POST("api/signup/doctor") Call<Void> signupDoctor(@Body Doctor doctor); @POST("api/signup/user") Call<Void> signupOrdinaryUser(@Body OrdinaryUser user); @POST("api/analyze-data") Call<AnalysisResult> analyzeData(@Body Data data); @FormUrlEncoded @POST("api/api-token-auth/") Call<Object> login(@FieldMap Map<String, String> data); }
788
0.735108
0.718631
37
20.324324
17.528439
59
false
false
0
0
0
0
0
0
0.486486
false
false
12
9b566b86e2fa508f74099f0fe9f80277aeb7df30
15,779,709,867,793
2a5d00efd19f113ba88571d9075333c7b75ae9a7
/app/src/main/java/com/simonrichards/bakingapplication/network/RetrofitInstance.java
8724a87855345024a3ba49437f7b9fa5f8deaeff
[]
no_license
Simon-Richards/BakingApp
https://github.com/Simon-Richards/BakingApp
2b4edc25b4691cb4383854bf9cf779eae5ecdc49
17b88a8350a3ed61d811369569bed9e9404a5600
refs/heads/master
2018-07-25T04:35:06.490000
2018-07-03T06:44:04
2018-07-03T06:44:04
135,810,627
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.simonrichards.bakingapplication.network; import retrofit2.Retrofit; import retrofit2.converter.scalars.ScalarsConverterFactory; public class RetrofitInstance { private static final String BASE_URL = "https://d17h27t6h515a5.cloudfront.net/"; public static Retrofit getRetrofitInstance() { Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(ScalarsConverterFactory.create()); //.addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build(); return retrofit; } }
UTF-8
Java
627
java
RetrofitInstance.java
Java
[]
null
[]
package com.simonrichards.bakingapplication.network; import retrofit2.Retrofit; import retrofit2.converter.scalars.ScalarsConverterFactory; public class RetrofitInstance { private static final String BASE_URL = "https://d17h27t6h515a5.cloudfront.net/"; public static Retrofit getRetrofitInstance() { Retrofit.Builder builder = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(ScalarsConverterFactory.create()); //.addConverterFactory(GsonConverterFactory.create()); Retrofit retrofit = builder.build(); return retrofit; } }
627
0.704944
0.6874
19
32
27.915285
84
false
false
0
0
0
0
0
0
0.421053
false
false
12
4955efb7fd9d40ab19249a9a12a97973e10ee174
20,014,547,614,192
4f0249d669d767055b3a7282a1f4791ceec3c956
/src/test/java/smartshare/administrationservice/controller/APIRequestControllerTest.java
29b2f0a1c73fd3c5d53d8d120839f511d7468e86
[]
no_license
vvshantha999/administrationservice
https://github.com/vvshantha999/administrationservice
29fbe24cc9460dfcae3574816894d6bff69b463b
8986b4e6b4c6126af0f3916f95868e800d097a30
refs/heads/master
2022-10-28T22:50:33.499000
2020-02-18T22:20:18
2020-02-18T22:20:18
272,041,402
0
0
null
true
2020-06-13T16:03:31
2020-06-13T16:03:30
2020-05-10T22:10:00
2020-05-10T22:09:57
228
0
0
0
null
false
false
package smartshare.administrationservice.controller; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import smartshare.administrationservice.dto.AccessingUserInfoForApi; import smartshare.administrationservice.dto.BucketMetadata; import smartshare.administrationservice.dto.BucketObjectMetadata; import smartshare.administrationservice.dto.ObjectMetadata; import smartshare.administrationservice.models.BucketAccess; import smartshare.administrationservice.models.ObjectAccess; import smartshare.administrationservice.service.APIRequestService; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc class APIRequestControllerTest { @MockBean private APIRequestService apiRequestService; @Autowired private MockMvc mockMvc; @Test @DisplayName("GET objects/accessInfo") void fetchMetaDataForObjectsInGivenBucketForSpecificUser() throws Exception { // set up the mock service List<BucketObjectMetadata> usersMetadataForPermittedBucketObjects = new ArrayList<>(); BucketObjectMetadata bucketObjectMetadata = new BucketObjectMetadata(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setOwnerName( "Owner" ); ObjectAccess objectAccess = new ObjectAccess( false, true, false ); AccessingUserInfoForApi accessingUserInfo = new AccessingUserInfoForApi( "sethuram", objectAccess ); objectMetadata.setAccessingUserInfo( accessingUserInfo ); bucketObjectMetadata.setObjectName( "Sample1.txt" ); bucketObjectMetadata.setObjectMetadata( objectMetadata ); usersMetadataForPermittedBucketObjects.add( bucketObjectMetadata ); // when( apiRequestService.fetchMetaDataForObjectsInGivenBucketForSpecificUser( "file.server.1", "sethuram" ) ) // .thenReturn( usersMetadataForPermittedBucketObjects ); // execute the get request mockMvc.perform( get( "/objects/accessInfo" ) .param( "bucketName", "file.server.1" ) .param( "userName", "sethuram" ) ) .andExpect( status().isOk() ) .andExpect( content().contentType( MediaType.APPLICATION_JSON ) ) .andExpect( jsonPath( "$[0].objectName" ).value( "Sample1.txt" ) ) .andExpect( jsonPath( "$[0].objectMetadata.ownerName" ).value( "Owner" ) ); } @Test @DisplayName("GET buckets/accessInfo") void fetchMetaDataForBucketsInS3() throws Exception { // set up the mock service BucketMetadata bucketMetadata = new BucketMetadata( "file.server.1", "sethuram" ); BucketAccess bucketAccess = new BucketAccess( true, false ); bucketMetadata.setAccess( bucketAccess ); when( apiRequestService.fetchMetaDataForBucketsInS3( "sethuram" ) ) .thenReturn( Collections.singletonList( bucketMetadata ) ); // execute the get request mockMvc.perform( get( "/buckets/accessInfo" ) .param( "userName", "sethuram" ) ) .andExpect( status().isOk() ) .andExpect( jsonPath( "$[0].userName" ).value( "sethuram" ) ) .andExpect( jsonPath( "$[0].read" ).value( true ) ) .andExpect( jsonPath( "$[0].write" ).value( false ) ); } }
UTF-8
Java
4,124
java
APIRequestControllerTest.java
Java
[ { "context": "accessingUserInfo = new AccessingUserInfoForApi( \"sethuram\", objectAccess );\n objectMetadata.setAcces", "end": 2195, "score": 0.9994418621063232, "start": 2187, "tag": "USERNAME", "value": "sethuram" }, { "context": ".server.1\" )\n .param( \"userName\", \"sethuram\" )\n )\n .andExpect( status()", "end": 2868, "score": 0.9996527433395386, "start": 2860, "tag": "USERNAME", "value": "sethuram" }, { "context": "ccessInfo\" )\n .param( \"userName\", \"sethuram\" )\n )\n .andExpect( status()", "end": 3839, "score": 0.9996809959411621, "start": 3831, "tag": "USERNAME", "value": "sethuram" }, { "context": " .andExpect( jsonPath( \"$[0].userName\" ).value( \"sethuram\" ) )\n .andExpect( jsonPath( \"$[0].", "end": 3971, "score": 0.9997215270996094, "start": 3963, "tag": "USERNAME", "value": "sethuram" } ]
null
[]
package smartshare.administrationservice.controller; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import smartshare.administrationservice.dto.AccessingUserInfoForApi; import smartshare.administrationservice.dto.BucketMetadata; import smartshare.administrationservice.dto.BucketObjectMetadata; import smartshare.administrationservice.dto.ObjectMetadata; import smartshare.administrationservice.models.BucketAccess; import smartshare.administrationservice.models.ObjectAccess; import smartshare.administrationservice.service.APIRequestService; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @ExtendWith(SpringExtension.class) @SpringBootTest @AutoConfigureMockMvc class APIRequestControllerTest { @MockBean private APIRequestService apiRequestService; @Autowired private MockMvc mockMvc; @Test @DisplayName("GET objects/accessInfo") void fetchMetaDataForObjectsInGivenBucketForSpecificUser() throws Exception { // set up the mock service List<BucketObjectMetadata> usersMetadataForPermittedBucketObjects = new ArrayList<>(); BucketObjectMetadata bucketObjectMetadata = new BucketObjectMetadata(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setOwnerName( "Owner" ); ObjectAccess objectAccess = new ObjectAccess( false, true, false ); AccessingUserInfoForApi accessingUserInfo = new AccessingUserInfoForApi( "sethuram", objectAccess ); objectMetadata.setAccessingUserInfo( accessingUserInfo ); bucketObjectMetadata.setObjectName( "Sample1.txt" ); bucketObjectMetadata.setObjectMetadata( objectMetadata ); usersMetadataForPermittedBucketObjects.add( bucketObjectMetadata ); // when( apiRequestService.fetchMetaDataForObjectsInGivenBucketForSpecificUser( "file.server.1", "sethuram" ) ) // .thenReturn( usersMetadataForPermittedBucketObjects ); // execute the get request mockMvc.perform( get( "/objects/accessInfo" ) .param( "bucketName", "file.server.1" ) .param( "userName", "sethuram" ) ) .andExpect( status().isOk() ) .andExpect( content().contentType( MediaType.APPLICATION_JSON ) ) .andExpect( jsonPath( "$[0].objectName" ).value( "Sample1.txt" ) ) .andExpect( jsonPath( "$[0].objectMetadata.ownerName" ).value( "Owner" ) ); } @Test @DisplayName("GET buckets/accessInfo") void fetchMetaDataForBucketsInS3() throws Exception { // set up the mock service BucketMetadata bucketMetadata = new BucketMetadata( "file.server.1", "sethuram" ); BucketAccess bucketAccess = new BucketAccess( true, false ); bucketMetadata.setAccess( bucketAccess ); when( apiRequestService.fetchMetaDataForBucketsInS3( "sethuram" ) ) .thenReturn( Collections.singletonList( bucketMetadata ) ); // execute the get request mockMvc.perform( get( "/buckets/accessInfo" ) .param( "userName", "sethuram" ) ) .andExpect( status().isOk() ) .andExpect( jsonPath( "$[0].userName" ).value( "sethuram" ) ) .andExpect( jsonPath( "$[0].read" ).value( true ) ) .andExpect( jsonPath( "$[0].write" ).value( false ) ); } }
4,124
0.724054
0.721144
96
41.96875
30.895473
118
false
false
0
0
0
0
0
0
0.541667
false
false
12
85aee6de7c5bbffceb861b12f2b9d16318105233
15,247,133,920,137
b8f804e3fd6e34381ab6c5b125eb3418754c0913
/oaDao/src/main/java/com/oa/dao/DutyDao.java
424cba1a8ff446f150bbf964801aa7b8e03a8a0f
[]
no_license
QTFY-wsy/OA
https://github.com/QTFY-wsy/OA
6863505edd4eb91292c9e287be40621995546ad6
a1491c644c929e0b7bc5891f70b02cd782818599
refs/heads/master
2022-05-04T04:35:33.725000
2019-11-09T19:11:40
2019-11-09T19:11:40
220,685,243
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oa.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.oa.mapper.DutyMapper; import com.oa.pojo.Attendance; import com.oa.pojo.DateParam; import com.oa.pojo.Duty; import com.oa.pojo.DutyName; import com.oa.pojo.Param; import com.oa.pojo.User; import com.oa.pojo.UserDutyInfo; import com.oa.pojo.vo.UserDuty; import com.oa.pojo.vo.UserUpdateAttend; @Component public class DutyDao { @Autowired private SqlSessionFactory sessionFactory; //获取所有班次信息 public List<Duty> getDuty(){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectDuty(); } //按Id查询班次信息 public Duty getDutyById(Param param) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectDutyById(param); } //添加班次信息 public int addDuty(Duty duty) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).insertDuty(duty); } //删除班次信息 public int deleteDuty(Param param) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).deleteDuty(param); } //更新班次信息 public int updateDuty(Duty duty) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).updateDuty(duty); } //查询用户班次信息 public UserDuty getUserDuty(Param param) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserDuty(param); } //添加考勤记录 public int addAttend(Attendance attendance) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).insertAttend(attendance); } //查询某一时间段用户考勤记录 public List<Attendance> getUserAttend(DateParam dateParam){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserAttend(dateParam); } //查询用户所有考勤记录 public List<Attendance> getUserAttends(Param param){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserAttends(param); } //更新考勤记录 public int updateUserAttend(UserUpdateAttend uua) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).updateAttend(uua); } //查询所有排班信息 public List<UserDutyInfo> getUserDutyInfo(){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserDutyInfo(); } //给用户排班 public int addUserDuty(UserDutyInfo udi) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).insertUserDuty(udi); } //删除用户排班信息 public int deleteUserDuty(Integer userId) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).deleteUserDuty(userId); } //更新用户排班 public int updateUserDuty(UserDutyInfo udi) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).updateUserDuty(udi); } //班次名称查重 public DutyName isDutyNameExit(DutyName dutyName) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectDutyName(dutyName); } //按班次id查找用户排班信息 public UserDutyInfo getUserDutyByType(Integer dutyType) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserDutyById(dutyType); } public SqlSessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SqlSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
UTF-8
Java
4,069
java
DutyDao.java
Java
[]
null
[]
package com.oa.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.oa.mapper.DutyMapper; import com.oa.pojo.Attendance; import com.oa.pojo.DateParam; import com.oa.pojo.Duty; import com.oa.pojo.DutyName; import com.oa.pojo.Param; import com.oa.pojo.User; import com.oa.pojo.UserDutyInfo; import com.oa.pojo.vo.UserDuty; import com.oa.pojo.vo.UserUpdateAttend; @Component public class DutyDao { @Autowired private SqlSessionFactory sessionFactory; //获取所有班次信息 public List<Duty> getDuty(){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectDuty(); } //按Id查询班次信息 public Duty getDutyById(Param param) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectDutyById(param); } //添加班次信息 public int addDuty(Duty duty) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).insertDuty(duty); } //删除班次信息 public int deleteDuty(Param param) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).deleteDuty(param); } //更新班次信息 public int updateDuty(Duty duty) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).updateDuty(duty); } //查询用户班次信息 public UserDuty getUserDuty(Param param) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserDuty(param); } //添加考勤记录 public int addAttend(Attendance attendance) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).insertAttend(attendance); } //查询某一时间段用户考勤记录 public List<Attendance> getUserAttend(DateParam dateParam){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserAttend(dateParam); } //查询用户所有考勤记录 public List<Attendance> getUserAttends(Param param){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserAttends(param); } //更新考勤记录 public int updateUserAttend(UserUpdateAttend uua) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).updateAttend(uua); } //查询所有排班信息 public List<UserDutyInfo> getUserDutyInfo(){ SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserDutyInfo(); } //给用户排班 public int addUserDuty(UserDutyInfo udi) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).insertUserDuty(udi); } //删除用户排班信息 public int deleteUserDuty(Integer userId) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).deleteUserDuty(userId); } //更新用户排班 public int updateUserDuty(UserDutyInfo udi) { SqlSession sqlSession=sessionFactory.openSession(true); return sqlSession.getMapper(DutyMapper.class).updateUserDuty(udi); } //班次名称查重 public DutyName isDutyNameExit(DutyName dutyName) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectDutyName(dutyName); } //按班次id查找用户排班信息 public UserDutyInfo getUserDutyByType(Integer dutyType) { SqlSession sqlSession=sessionFactory.openSession(); return sqlSession.getMapper(DutyMapper.class).selectUserDutyById(dutyType); } public SqlSessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SqlSessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
4,069
0.803082
0.803082
112
33.1875
24.837879
77
false
false
0
0
0
0
0
0
1.553571
false
false
12
478a3b1cfbba6dbbdacb2bdc46085c6fd1b148c6
2,602,750,182,914
e377065efd7cb9d3bf9dcda3c9fb78ff25368f75
/O/O/EX2objetoavião.java
774eace4ae286bb421d50e2692064776ba7e116c
[]
no_license
narumiincode/JAVA-Programacao-orientada-a-objetos
https://github.com/narumiincode/JAVA-Programacao-orientada-a-objetos
bb874c0d47dbbb542d33e1b41a3aa695d7b2183c
612d1daabf544e902bd450594cc49fb5a956da3e
refs/heads/master
2023-07-24T00:39:26.939000
2021-09-08T23:31:50
2021-09-08T23:31:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package P.O.O; public class EX2objetoavião { public static void main(String[] args) { // TODO Auto-generated method stub EX2classeavião dados= new EX2classeavião ("KC-390","\nEmbraer","\n2015","\nmilitar", "\nBrasil"); System.out.println(dados.getHangar()); } }
ISO-8859-1
Java
279
java
EX2objetoavião.java
Java
[]
null
[]
package P.O.O; public class EX2objetoavião { public static void main(String[] args) { // TODO Auto-generated method stub EX2classeavião dados= new EX2classeavião ("KC-390","\nEmbraer","\n2015","\nmilitar", "\nBrasil"); System.out.println(dados.getHangar()); } }
279
0.692029
0.655797
12
22
28.307831
99
false
false
0
0
0
0
0
0
1.416667
false
false
12
07ebbfccfd88ffd736fba21385d5acc2e545e0d5
1,408,749,283,609
79b8ffa80c21e2865cc8b3bb92fa89105edb6896
/app/src/main/java/com/app/cellstudio/holidayplanner/presentation/component/DisableSwipeViewPager.java
6feaabf65089b856ec92e7bde72309e2bab31123
[]
no_license
Celliusx3/HolidayPlanner
https://github.com/Celliusx3/HolidayPlanner
76495c6f7a00df0259f263bfbb5d054963fda7a1
4b1da33724eb86f3cb346574abb2a55f3b72c634
refs/heads/master
2020-04-10T08:18:44.744000
2018-12-08T04:25:57
2018-12-08T04:25:57
160,902,689
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.cellstudio.holidayplanner.presentation.component; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; /** * Created by coyan on 14/09/2018. */ public class DisableSwipeViewPager extends ViewPager { public DisableSwipeViewPager(Context context) { super(context); } public DisableSwipeViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { return false; } @Override public void setCurrentItem(int item, boolean smoothScroll) { super.setCurrentItem(item, false); } @Override public void setCurrentItem(int item) { super.setCurrentItem(item, false); } }
UTF-8
Java
934
java
DisableSwipeViewPager.java
Java
[ { "context": "mport android.view.MotionEvent;\n\n/**\n * Created by coyan on 14/09/2018.\n */\n\npublic class DisableSwipeView", "end": 232, "score": 0.9987746477127075, "start": 227, "tag": "USERNAME", "value": "coyan" } ]
null
[]
package com.app.cellstudio.holidayplanner.presentation.component; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; /** * Created by coyan on 14/09/2018. */ public class DisableSwipeViewPager extends ViewPager { public DisableSwipeViewPager(Context context) { super(context); } public DisableSwipeViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { return false; } @Override public boolean onTouchEvent(MotionEvent ev) { return false; } @Override public void setCurrentItem(int item, boolean smoothScroll) { super.setCurrentItem(item, false); } @Override public void setCurrentItem(int item) { super.setCurrentItem(item, false); } }
934
0.699143
0.689507
40
22.325001
21.83276
71
false
false
0
0
0
0
0
0
0.4
false
false
12
542387385bff0378145cd7274cc0f5b4a9c250e8
32,298,154,081,533
f3c921afb9dca43caae0a0a672fbdc1fe4e74cd9
/bob-service/src/main/java/com/cloud/example/ServiceBob.java
bf5868dcf954e02ed6f21298fcc40d06df5b34d6
[ "MIT" ]
permissive
kamlakant/spring-cloud-feign-demo
https://github.com/kamlakant/spring-cloud-feign-demo
2bd5a8a2e51b1844511683a7e577708cd0c088c6
607949fcd48ce848606edb9e8f80392201b7c243
refs/heads/master
2020-09-05T02:08:43.338000
2019-11-06T09:30:59
2019-11-06T09:30:59
219,953,486
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cloud.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @EnableFeignClients public class ServiceBob { @Value("${server.port}") private int serverPort; @Autowired private AliceClient aliceClient; public static void main(String[] args) { SpringApplication.run(ServiceBob.class, args); } @GetMapping("/generate-stuff") public String generateStuff() { return "Stuff by Bob " + serverPort; } @GetMapping("/get-stuff/alice") public String getAliceStuff() { return aliceClient.generateStuff(); } }
UTF-8
Java
1,008
java
ServiceBob.java
Java
[]
null
[]
package com.cloud.example; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @EnableFeignClients public class ServiceBob { @Value("${server.port}") private int serverPort; @Autowired private AliceClient aliceClient; public static void main(String[] args) { SpringApplication.run(ServiceBob.class, args); } @GetMapping("/generate-stuff") public String generateStuff() { return "Stuff by Bob " + serverPort; } @GetMapping("/get-stuff/alice") public String getAliceStuff() { return aliceClient.generateStuff(); } }
1,008
0.758929
0.758929
36
27
22.397917
68
false
false
0
0
0
0
0
0
0.388889
false
false
12
9adc1e41c41df89c6bb366f626d320e410304783
10,118,942,984,160
d387e911f9b115f00071fe9466e54b52419b3c35
/sandbox/src/main/java/org/robolectric/internal/bytecode/SandboxClassLoader.java
494a6cacc4f5cd56f4f41c6d89ee54bb4b8dd274
[ "MIT" ]
permissive
exloong/robolectric
https://github.com/exloong/robolectric
d0381641cfd37df1a2306ef4766b7c9926b77243
b55c877c771dfb49096d279d67686bb095a3936f
refs/heads/master
2020-04-21T00:17:37.848000
2019-02-04T19:27:26
2019-02-04T19:27:58
169,192,091
2
0
MIT
true
2019-02-05T04:51:13
2019-02-05T04:51:13
2019-02-04T22:20:02
2019-02-05T02:53:28
43,276
0
0
0
null
false
null
package org.robolectric.internal.bytecode; import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH; import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR; import static org.robolectric.util.ReflectionHelpers.ClassParameter.from; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import org.robolectric.util.Logger; import org.robolectric.util.PerfStatsCollector; import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.Util; /** * Class loader that modifies the bytecode of Android classes to insert calls to Robolectric's * shadow classes. */ public class SandboxClassLoader extends URLClassLoader { private final ClassLoader systemClassLoader; private final ClassLoader urls; private final InstrumentationConfiguration config; private final ClassInstrumentor classInstrumentor; private final ClassNodeProvider classNodeProvider; public SandboxClassLoader(InstrumentationConfiguration config) { this(ClassLoader.getSystemClassLoader(), config); } public SandboxClassLoader( ClassLoader systemClassLoader, InstrumentationConfiguration config, URL... urls) { super(getClassPathUrls(systemClassLoader), systemClassLoader.getParent()); this.systemClassLoader = systemClassLoader; this.config = config; this.urls = new URLClassLoader(urls, null); for (URL url : urls) { Logger.debug("Loading classes from: %s", url); } ClassInstrumentor.Decorator decorator = new ShadowDecorator(); classInstrumentor = createClassInstrumentor(decorator); classNodeProvider = new ClassNodeProvider() { @Override protected byte[] getClassBytes(String internalClassName) throws ClassNotFoundException { return getByteCode(internalClassName); } }; } private static URL[] getClassPathUrls(ClassLoader classloader) { if (classloader instanceof URLClassLoader) { return ((URLClassLoader) classloader).getURLs(); } return parseJavaClassPath(); } // TODO(b/65488446): Use a public API once one is available. private static URL[] parseJavaClassPath() { ImmutableList.Builder<URL> urls = ImmutableList.builder(); for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) { try { try { urls.add(new File(entry).toURI().toURL()); } catch (SecurityException e) { // File.toURI checks to see if the file is a directory urls.add(new URL("file", null, new File(entry).getAbsolutePath())); } } catch (MalformedURLException e) { Logger.strict("malformed classpath entry: " + entry, e); } } return urls.build().toArray(new URL[0]); } protected ClassInstrumentor createClassInstrumentor(ClassInstrumentor.Decorator decorator) { return InvokeDynamic.ENABLED ? new InvokeDynamicClassInstrumentor(decorator) : new OldClassInstrumentor(decorator); } @Override public URL getResource(String name) { if (config.shouldAcquireResource(name)) { return urls.getResource(name); } URL fromParent = super.getResource(name); if (fromParent != null) { return fromParent; } return urls.getResource(name); } private InputStream getClassBytesAsStreamPreferringLocalUrls(String resName) { InputStream fromUrlsClassLoader = urls.getResourceAsStream(resName); if (fromUrlsClassLoader != null) { return fromUrlsClassLoader; } return super.getResourceAsStream(resName); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (config.shouldAcquire(name)) { return PerfStatsCollector.getInstance().measure("load sandboxed class", () -> maybeInstrumentClass(name)); } else { return systemClassLoader.loadClass(name); } } protected Class<?> maybeInstrumentClass(String className) throws ClassNotFoundException { final byte[] origClassBytes = getByteCode(className); MutableClass mutableClass = PerfStatsCollector.getInstance().measure("analyze class", () -> classInstrumentor.analyzeClass(origClassBytes, config, classNodeProvider) ); try { final byte[] bytes; if (config.shouldInstrument(mutableClass)) { bytes = PerfStatsCollector.getInstance().measure("instrument class", () -> classInstrumentor.instrumentToBytes(mutableClass) ); } else { bytes = postProcessUninstrumentedClass(mutableClass, origClassBytes); } ensurePackage(className); return defineClass(className, bytes, 0, bytes.length); } catch (Exception e) { throw new ClassNotFoundException("couldn't load " + className, e); } catch (OutOfMemoryError e) { System.err.println("[ERROR] couldn't load " + className + " in " + this); throw e; } } protected byte[] postProcessUninstrumentedClass( MutableClass mutableClass, byte[] origClassBytes) { return origClassBytes; } @Override protected Package getPackage(String name) { Package aPackage = super.getPackage(name); if (aPackage != null) { return aPackage; } return ReflectionHelpers.callInstanceMethod(systemClassLoader, "getPackage", from(String.class, name)); } protected byte[] getByteCode(String className) throws ClassNotFoundException { String classFilename = className.replace('.', '/') + ".class"; try (InputStream classBytesStream = getClassBytesAsStreamPreferringLocalUrls(classFilename)) { if (classBytesStream == null) { throw new ClassNotFoundException(className); } return Util.readBytes(classBytesStream); } catch (IOException e) { throw new ClassNotFoundException("couldn't load " + className, e); } } private void ensurePackage(final String className) { int lastDotIndex = className.lastIndexOf('.'); if (lastDotIndex != -1) { String pckgName = className.substring(0, lastDotIndex); Package pckg = getPackage(pckgName); if (pckg == null) { definePackage(pckgName, null, null, null, null, null, null, null); } } } }
UTF-8
Java
6,360
java
SandboxClassLoader.java
Java
[]
null
[]
package org.robolectric.internal.bytecode; import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH; import static com.google.common.base.StandardSystemProperty.PATH_SEPARATOR; import static org.robolectric.util.ReflectionHelpers.ClassParameter.from; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import org.robolectric.util.Logger; import org.robolectric.util.PerfStatsCollector; import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.Util; /** * Class loader that modifies the bytecode of Android classes to insert calls to Robolectric's * shadow classes. */ public class SandboxClassLoader extends URLClassLoader { private final ClassLoader systemClassLoader; private final ClassLoader urls; private final InstrumentationConfiguration config; private final ClassInstrumentor classInstrumentor; private final ClassNodeProvider classNodeProvider; public SandboxClassLoader(InstrumentationConfiguration config) { this(ClassLoader.getSystemClassLoader(), config); } public SandboxClassLoader( ClassLoader systemClassLoader, InstrumentationConfiguration config, URL... urls) { super(getClassPathUrls(systemClassLoader), systemClassLoader.getParent()); this.systemClassLoader = systemClassLoader; this.config = config; this.urls = new URLClassLoader(urls, null); for (URL url : urls) { Logger.debug("Loading classes from: %s", url); } ClassInstrumentor.Decorator decorator = new ShadowDecorator(); classInstrumentor = createClassInstrumentor(decorator); classNodeProvider = new ClassNodeProvider() { @Override protected byte[] getClassBytes(String internalClassName) throws ClassNotFoundException { return getByteCode(internalClassName); } }; } private static URL[] getClassPathUrls(ClassLoader classloader) { if (classloader instanceof URLClassLoader) { return ((URLClassLoader) classloader).getURLs(); } return parseJavaClassPath(); } // TODO(b/65488446): Use a public API once one is available. private static URL[] parseJavaClassPath() { ImmutableList.Builder<URL> urls = ImmutableList.builder(); for (String entry : Splitter.on(PATH_SEPARATOR.value()).split(JAVA_CLASS_PATH.value())) { try { try { urls.add(new File(entry).toURI().toURL()); } catch (SecurityException e) { // File.toURI checks to see if the file is a directory urls.add(new URL("file", null, new File(entry).getAbsolutePath())); } } catch (MalformedURLException e) { Logger.strict("malformed classpath entry: " + entry, e); } } return urls.build().toArray(new URL[0]); } protected ClassInstrumentor createClassInstrumentor(ClassInstrumentor.Decorator decorator) { return InvokeDynamic.ENABLED ? new InvokeDynamicClassInstrumentor(decorator) : new OldClassInstrumentor(decorator); } @Override public URL getResource(String name) { if (config.shouldAcquireResource(name)) { return urls.getResource(name); } URL fromParent = super.getResource(name); if (fromParent != null) { return fromParent; } return urls.getResource(name); } private InputStream getClassBytesAsStreamPreferringLocalUrls(String resName) { InputStream fromUrlsClassLoader = urls.getResourceAsStream(resName); if (fromUrlsClassLoader != null) { return fromUrlsClassLoader; } return super.getResourceAsStream(resName); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (config.shouldAcquire(name)) { return PerfStatsCollector.getInstance().measure("load sandboxed class", () -> maybeInstrumentClass(name)); } else { return systemClassLoader.loadClass(name); } } protected Class<?> maybeInstrumentClass(String className) throws ClassNotFoundException { final byte[] origClassBytes = getByteCode(className); MutableClass mutableClass = PerfStatsCollector.getInstance().measure("analyze class", () -> classInstrumentor.analyzeClass(origClassBytes, config, classNodeProvider) ); try { final byte[] bytes; if (config.shouldInstrument(mutableClass)) { bytes = PerfStatsCollector.getInstance().measure("instrument class", () -> classInstrumentor.instrumentToBytes(mutableClass) ); } else { bytes = postProcessUninstrumentedClass(mutableClass, origClassBytes); } ensurePackage(className); return defineClass(className, bytes, 0, bytes.length); } catch (Exception e) { throw new ClassNotFoundException("couldn't load " + className, e); } catch (OutOfMemoryError e) { System.err.println("[ERROR] couldn't load " + className + " in " + this); throw e; } } protected byte[] postProcessUninstrumentedClass( MutableClass mutableClass, byte[] origClassBytes) { return origClassBytes; } @Override protected Package getPackage(String name) { Package aPackage = super.getPackage(name); if (aPackage != null) { return aPackage; } return ReflectionHelpers.callInstanceMethod(systemClassLoader, "getPackage", from(String.class, name)); } protected byte[] getByteCode(String className) throws ClassNotFoundException { String classFilename = className.replace('.', '/') + ".class"; try (InputStream classBytesStream = getClassBytesAsStreamPreferringLocalUrls(classFilename)) { if (classBytesStream == null) { throw new ClassNotFoundException(className); } return Util.readBytes(classBytesStream); } catch (IOException e) { throw new ClassNotFoundException("couldn't load " + className, e); } } private void ensurePackage(final String className) { int lastDotIndex = className.lastIndexOf('.'); if (lastDotIndex != -1) { String pckgName = className.substring(0, lastDotIndex); Package pckg = getPackage(pckgName); if (pckg == null) { definePackage(pckgName, null, null, null, null, null, null, null); } } } }
6,360
0.713208
0.711321
183
33.754097
28.465485
98
false
false
0
0
0
0
0
0
0.562842
false
false
12
a6c6045ada4a8e05d3fff47978b5c2cc6133e36b
12,137,577,615,730
ed2e2d63b607ebd68d507e2400eb529f1bc488f3
/adapter-generator/src/main/java/eu/chorevolution/transformations/generativeapproach/adgenerator/model/WSDLTypesMap.java
270d34cddca0242e7937f7077eb20fb4190669a3
[ "Apache-2.0" ]
permissive
chorevolution/transformations
https://github.com/chorevolution/transformations
012376213fe5bb7fc5dbaf0bca95ba6070da0a03
287abfe2f7733fc3e7df050c0f73a3ccf2d40caa
refs/heads/master
2023-04-14T00:35:37.382000
2021-04-25T17:03:07
2021-04-25T17:03:07
218,287,975
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2017 The CHOReVOLUTION project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.chorevolution.transformations.generativeapproach.adgenerator.model; import java.util.HashMap; import java.util.Map; import org.eclipse.emf.common.util.EList; import eu.chorevolution.modelingnotations.adapter.AdapterModel; import eu.chorevolution.modelingnotations.adapter.ChoreographyComplexItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyDataItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyEnumerationItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyMessage; import eu.chorevolution.modelingnotations.adapter.ChoreographySimpleItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyTask; import eu.chorevolution.modelingnotations.adapter.OccurencesType; import eu.chorevolution.transformations.generativeapproach.adgenerator.util.AdapterModelsUtility; public class WSDLTypesMap { private Map<String, WSDLType> wsdlItems; public WSDLTypesMap(AdapterModel adapterModel) { wsdlItems = new HashMap<>(); ChoreographyTask task = adapterModel.getHasChoreographyTasks().get(0); for (ChoreographyMessage message : task.getHasChoreographyMessages()) { recursiveBuilder(message.getHasChoreographyDataItem()); } } private WSDLType recursiveBuilder(ChoreographyDataItem choreographyDataItem) { WSDLType wsdlType = new WSDLType(); wsdlType.setName(choreographyDataItem.getName()); wsdlType.setMaxOccurs(getOccurrencesWSDLValue(choreographyDataItem.getMaxOccurs())); wsdlType.setMinOccurs(getOccurrencesWSDLValue(choreographyDataItem.getMinOccurs())); if (choreographyDataItem instanceof ChoreographyComplexItem) { ChoreographyComplexItem complexItem = (ChoreographyComplexItem) choreographyDataItem; EList<ChoreographyDataItem> innerItems = complexItem.getHasChoreographyDataItems(); if (innerItems != null) { for (ChoreographyDataItem item : innerItems) { wsdlType.getInnerItems().add(recursiveBuilder(item)); } } wsdlType.setType(complexItem.getTypeName()); wsdlType.setComplex(true); wsdlType.setEnumeration(false); this.wsdlItems.put(wsdlType.getType(), wsdlType); } else { ChoreographySimpleItem simpleItem = (ChoreographySimpleItem) choreographyDataItem; EList<ChoreographyEnumerationItem> enumerationList = simpleItem.getHasChoreographyEnumerationItems(); if (enumerationList != null && !enumerationList.isEmpty()) { wsdlType.setEnumeration(true); wsdlType.getEnumerationValues().addAll(AdapterModelsUtility.getSimpleItemEnumerationValues(simpleItem)); this.wsdlItems.put(wsdlType.getName(), wsdlType); } else { wsdlType.setEnumeration(false); } wsdlType.setComplex(false); wsdlType.setType(simpleItem.getType().getName()); } return wsdlType; } private String getOccurrencesWSDLValue(OccurencesType occurencesType) { switch (occurencesType) { case ONE: return "1"; case ZERO: return "0"; case UNBOUNDED: return "unbounded"; } return ""; } public Map<String, WSDLType> getWsdlItems() { return wsdlItems; } }
UTF-8
Java
3,642
java
WSDLTypesMap.java
Java
[]
null
[]
/* * Copyright 2017 The CHOReVOLUTION project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.chorevolution.transformations.generativeapproach.adgenerator.model; import java.util.HashMap; import java.util.Map; import org.eclipse.emf.common.util.EList; import eu.chorevolution.modelingnotations.adapter.AdapterModel; import eu.chorevolution.modelingnotations.adapter.ChoreographyComplexItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyDataItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyEnumerationItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyMessage; import eu.chorevolution.modelingnotations.adapter.ChoreographySimpleItem; import eu.chorevolution.modelingnotations.adapter.ChoreographyTask; import eu.chorevolution.modelingnotations.adapter.OccurencesType; import eu.chorevolution.transformations.generativeapproach.adgenerator.util.AdapterModelsUtility; public class WSDLTypesMap { private Map<String, WSDLType> wsdlItems; public WSDLTypesMap(AdapterModel adapterModel) { wsdlItems = new HashMap<>(); ChoreographyTask task = adapterModel.getHasChoreographyTasks().get(0); for (ChoreographyMessage message : task.getHasChoreographyMessages()) { recursiveBuilder(message.getHasChoreographyDataItem()); } } private WSDLType recursiveBuilder(ChoreographyDataItem choreographyDataItem) { WSDLType wsdlType = new WSDLType(); wsdlType.setName(choreographyDataItem.getName()); wsdlType.setMaxOccurs(getOccurrencesWSDLValue(choreographyDataItem.getMaxOccurs())); wsdlType.setMinOccurs(getOccurrencesWSDLValue(choreographyDataItem.getMinOccurs())); if (choreographyDataItem instanceof ChoreographyComplexItem) { ChoreographyComplexItem complexItem = (ChoreographyComplexItem) choreographyDataItem; EList<ChoreographyDataItem> innerItems = complexItem.getHasChoreographyDataItems(); if (innerItems != null) { for (ChoreographyDataItem item : innerItems) { wsdlType.getInnerItems().add(recursiveBuilder(item)); } } wsdlType.setType(complexItem.getTypeName()); wsdlType.setComplex(true); wsdlType.setEnumeration(false); this.wsdlItems.put(wsdlType.getType(), wsdlType); } else { ChoreographySimpleItem simpleItem = (ChoreographySimpleItem) choreographyDataItem; EList<ChoreographyEnumerationItem> enumerationList = simpleItem.getHasChoreographyEnumerationItems(); if (enumerationList != null && !enumerationList.isEmpty()) { wsdlType.setEnumeration(true); wsdlType.getEnumerationValues().addAll(AdapterModelsUtility.getSimpleItemEnumerationValues(simpleItem)); this.wsdlItems.put(wsdlType.getName(), wsdlType); } else { wsdlType.setEnumeration(false); } wsdlType.setComplex(false); wsdlType.setType(simpleItem.getType().getName()); } return wsdlType; } private String getOccurrencesWSDLValue(OccurencesType occurencesType) { switch (occurencesType) { case ONE: return "1"; case ZERO: return "0"; case UNBOUNDED: return "unbounded"; } return ""; } public Map<String, WSDLType> getWsdlItems() { return wsdlItems; } }
3,642
0.788852
0.785832
103
34.359222
31.432423
108
false
false
0
0
0
0
0
0
1.883495
false
false
12
c2089494e852448386caee0546e2886b9523941e
21,414,706,960,182
aa1e6fb49207ef7d3d7cc00b688fdb28895c6956
/P15009908/src/main/java/com/erim/sz/ticket/controller/TicketInformationController.java
5dbb28d2df6938e17a1413e76f472e6ec3a9322f
[]
no_license
zhanght86/erim
https://github.com/zhanght86/erim
f76fec9267200c6951a0a8c1fb3f723de88a039c
504d81bb4926e496c11a34641dcc67150e78dadc
refs/heads/master
2021-05-15T17:10:07.801000
2016-12-02T09:35:07
2016-12-02T09:35:07
107,489,023
1
0
null
true
2017-10-19T02:37:10
2017-10-19T02:37:10
2016-11-15T09:59:52
2016-12-02T09:35:40
34,249
0
0
0
null
null
null
package com.erim.sz.ticket.controller; 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 com.erim.core.exception.ErimException; import com.erim.sz.common.bean.TicketDetailBean; import com.erim.sz.ticket.service.TicketInformationService; /** * * @ClassName: TicketInformationController * @Description: 酒店基本信息 * @author 陈鹏 * @date 2015年8月2日 下午11:19:35 * */ @Controller public class TicketInformationController { @Autowired private TicketInformationService ticketService; /** * * @Description: 酒店列表页 * @param @param model * @param @param request * @param @return * @param @throws ErimException 设定文件 * @return String 返回类型 * @throws */ // @RequestMapping(value = "/ticket/information/ticketinformation") // public String showList(ModelMap model, @ModelAttribute("ticketInformation") TicketDetailBean ticketDetailBean) throws ErimException { // this.ticketService.showTicket(model, ticketDetailBean); // return "/ticket/detail/list"; // } /** * * @Title: insertPage * @Description: 新增页面 * @param @return * @param @throws ErimException 设定文件 * @return String 返回类型 * @throws */ @RequestMapping(value = "/ticket/information/ticketinformationPage") public String insertPage() throws ErimException { return "/ticket/information/ticketinformation"; } /** * * @Title: insert * @Description: 新增方法 * @param @param model * @param @param ticketDetailBean * @param @return * @param @throws ErimException 设定文件 * @return String 返回类型 * @throws */ @RequestMapping(value = "/ticket/information/ticketinformation") public String insert(ModelMap model, @ModelAttribute("ticketInformation") TicketDetailBean ticketDetailBean) throws ErimException { this.ticketService.insert(model, ticketDetailBean); return "index"; } }
UTF-8
Java
2,288
java
TicketInformationController.java
Java
[ { "context": "ationController \n* @Description: 酒店基本信息\n* @author 陈鹏\n* @date 2015年8月2日 下午11:19:35 \n*\n */\n@Controller\np", "end": 562, "score": 0.9994714856147766, "start": 560, "tag": "NAME", "value": "陈鹏" } ]
null
[]
package com.erim.sz.ticket.controller; 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 com.erim.core.exception.ErimException; import com.erim.sz.common.bean.TicketDetailBean; import com.erim.sz.ticket.service.TicketInformationService; /** * * @ClassName: TicketInformationController * @Description: 酒店基本信息 * @author 陈鹏 * @date 2015年8月2日 下午11:19:35 * */ @Controller public class TicketInformationController { @Autowired private TicketInformationService ticketService; /** * * @Description: 酒店列表页 * @param @param model * @param @param request * @param @return * @param @throws ErimException 设定文件 * @return String 返回类型 * @throws */ // @RequestMapping(value = "/ticket/information/ticketinformation") // public String showList(ModelMap model, @ModelAttribute("ticketInformation") TicketDetailBean ticketDetailBean) throws ErimException { // this.ticketService.showTicket(model, ticketDetailBean); // return "/ticket/detail/list"; // } /** * * @Title: insertPage * @Description: 新增页面 * @param @return * @param @throws ErimException 设定文件 * @return String 返回类型 * @throws */ @RequestMapping(value = "/ticket/information/ticketinformationPage") public String insertPage() throws ErimException { return "/ticket/information/ticketinformation"; } /** * * @Title: insert * @Description: 新增方法 * @param @param model * @param @param ticketDetailBean * @param @return * @param @throws ErimException 设定文件 * @return String 返回类型 * @throws */ @RequestMapping(value = "/ticket/information/ticketinformation") public String insert(ModelMap model, @ModelAttribute("ticketInformation") TicketDetailBean ticketDetailBean) throws ErimException { this.ticketService.insert(model, ticketDetailBean); return "index"; } }
2,288
0.692413
0.686929
73
28.986301
27.585728
139
false
false
0
0
0
0
0
0
0.315068
false
false
12
6dd792fd294d30131f4efbdc4f647ecdc8ad7ff9
32,547,262,200,782
3ba019d5cb66d79a9d66cdc5f098711a5365f891
/API/PickupRequest/PickupRequestWeb/src/main/java/com/estes/myestes/PickupRequest/util/AppConstant.java
458ff39c0cbb608db325e4bb1a65d749432186bf
[]
no_license
meataur/estes-express.com
https://github.com/meataur/estes-express.com
d94e4d3d28abc2f3240c9ff27d2ffc38b28cbd39
a71c6f2786edf677ad1c1a512bc8d54fa49484bf
refs/heads/master
2022-03-02T01:32:07.356000
2019-09-12T19:18:49
2019-09-12T19:18:49
208,119,348
0
0
null
false
2022-03-02T05:34:49
2019-09-12T18:31:24
2019-09-12T19:19:05
2022-03-02T05:34:46
3,672
0
0
23
Java
false
false
package com.estes.myestes.PickupRequest.util; public interface AppConstant { public static final String APP_CONFIG = "pickupRequest.config"; public static final String LOGGER = "logger"; public static final String LOCATION = "location"; String ORIGIN_DOMAIN = "originDomain"; // jvm custom property name for originDomain }
UTF-8
Java
328
java
AppConstant.java
Java
[]
null
[]
package com.estes.myestes.PickupRequest.util; public interface AppConstant { public static final String APP_CONFIG = "pickupRequest.config"; public static final String LOGGER = "logger"; public static final String LOCATION = "location"; String ORIGIN_DOMAIN = "originDomain"; // jvm custom property name for originDomain }
328
0.780488
0.780488
8
40
27.143139
84
false
false
0
0
0
0
0
0
1.125
false
false
12
335fc39e9f3869967c1135b8f975629ebab0147d
11,536,282,177,551
a0caa255f3dbe524437715adaee2094ac8eff9df
/src/main/java/p000/btp.java
d807d08588938e46a9b3d6223ab28075ed93038b
[]
no_license
AndroidTVDeveloper/com.google.android.tvlauncher
https://github.com/AndroidTVDeveloper/com.google.android.tvlauncher
16526208b5b48fd48931b09ed702fe606fe7d694
0f959c41bbb5a93e981145f371afdec2b3e207bc
refs/heads/master
2021-01-26T07:47:23.091000
2020-02-26T20:58:19
2020-02-26T20:58:19
243,363,961
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package p000; import android.accounts.Account; import android.os.IInterface; /* renamed from: btp */ /* compiled from: PG */ public interface btp extends IInterface { /* renamed from: b */ Account mo2437b(); }
UTF-8
Java
220
java
btp.java
Java
[]
null
[]
package p000; import android.accounts.Account; import android.os.IInterface; /* renamed from: btp */ /* compiled from: PG */ public interface btp extends IInterface { /* renamed from: b */ Account mo2437b(); }
220
0.695455
0.663636
11
19
13.184012
41
false
false
0
0
0
0
0
0
0.363636
false
false
12
949191d8bc7f8ff7808280275acca051327623ba
11,536,282,179,256
b817c1c6be2bf7b64ff7db38e42fc3f5c7755760
/src/Player/Account.java
fbd0ac300a27e95d2b8765ccc529db6e83a6dbd0
[]
no_license
Hold45/CDIO_del_2
https://github.com/Hold45/CDIO_del_2
969d2fbcb9eac0e0d5af7087dd2f6ff59fdd785f
580b81aebe00a6230931d94a129747f52afaeb06
refs/heads/master
2021-01-12T12:20:54.184000
2016-11-04T12:33:27
2016-11-04T12:33:27
72,445,443
0
0
null
false
2016-11-04T12:33:28
2016-10-31T14:39:52
2016-10-31T14:50:00
2016-11-04T12:33:28
556
0
0
0
Java
null
null
package Player; public class Account{ private int balance; Account(int balance){ this.balance = balance; } public int getMoney(){ return this.balance; } public Account setMoney(int value){ this.balance = value; return this; } public Account addMoney(int value){ this.balance += value; return this; } public boolean takeMoney(int value){ if (value>balance){ this.balance = 0; return false; } else{ this.balance -= value; return true; } } }
UTF-8
Java
486
java
Account.java
Java
[]
null
[]
package Player; public class Account{ private int balance; Account(int balance){ this.balance = balance; } public int getMoney(){ return this.balance; } public Account setMoney(int value){ this.balance = value; return this; } public Account addMoney(int value){ this.balance += value; return this; } public boolean takeMoney(int value){ if (value>balance){ this.balance = 0; return false; } else{ this.balance -= value; return true; } } }
486
0.666667
0.664609
31
14.709678
11.382481
37
false
false
0
0
0
0
0
0
1.83871
false
false
12
5f9e0a211adc55b521e8d44b85ec977df43fc780
30,399,778,526,951
1e264a0b306eeae73ea8bd0f3a52feffc80f3571
/news-web/src/main/java/by/epam/newsweb/provider/NewsManagerServiceExceptionHandler.java
afa8cd1d9f7c95ac878a5be2dd986be8bc834bf3
[]
no_license
dimadl/news-web
https://github.com/dimadl/news-web
29a78fadddb7bd07aecec2249d86649f355c915c
2af57ee7685cf5db3f818f72ffa7c6b29d1c3ee9
refs/heads/master
2017-12-07T11:44:19.627000
2015-12-24T08:20:55
2015-12-24T08:20:55
43,481,398
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package by.epam.newsweb.provider; import by.epam.newsapi.exception.TechnicalException; import by.epam.newsweb.response.ResponseError; import com.sun.jersey.api.client.ClientResponse; import org.springframework.stereotype.Component; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * Created by Dzmitry_Dydyshka on 9/22/2015. */ @Component @Provider public final class NewsManagerServiceExceptionHandler implements ExceptionMapper<TechnicalException> { @Override public Response toResponse(TechnicalException e) { return Response.status(ClientResponse.Status.BAD_REQUEST).entity(new ResponseError().putError(e.getMessage())). type(MediaType.APPLICATION_JSON).build(); } }
UTF-8
Java
812
java
NewsManagerServiceExceptionHandler.java
Java
[ { "context": "mport javax.ws.rs.ext.Provider;\n\n/**\n * Created by Dzmitry_Dydyshka on 9/22/2015.\n */\n@Component\n@Provider\npublic fin", "end": 411, "score": 0.8982633948326111, "start": 395, "tag": "USERNAME", "value": "Dzmitry_Dydyshka" } ]
null
[]
package by.epam.newsweb.provider; import by.epam.newsapi.exception.TechnicalException; import by.epam.newsweb.response.ResponseError; import com.sun.jersey.api.client.ClientResponse; import org.springframework.stereotype.Component; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * Created by Dzmitry_Dydyshka on 9/22/2015. */ @Component @Provider public final class NewsManagerServiceExceptionHandler implements ExceptionMapper<TechnicalException> { @Override public Response toResponse(TechnicalException e) { return Response.status(ClientResponse.Status.BAD_REQUEST).entity(new ResponseError().putError(e.getMessage())). type(MediaType.APPLICATION_JSON).build(); } }
812
0.775862
0.767241
27
29.074074
30.758228
119
false
false
0
0
0
0
0
0
0.37037
false
false
12
9c1b92999d8e9ca80b1dbc840725a26f01aa9fe5
5,738,076,330,088
82eeaaa4f6a4bf843b6085b3cd525dbd49ad0267
/src/in/ac/iitb/cse/wikiminer/WikiMarkup.java
01c041f6ffb3d9ee7e9bc8503573a1f93e205808
[]
no_license
SimoniShah/tac-service
https://github.com/SimoniShah/tac-service
8a3b0160f50adfb92a0356a16eb584a67632680e
5c807009dfe4841dd47d1046d4a0e6f4c59335e5
refs/heads/master
2021-01-14T09:20:02.277000
2015-07-30T09:25:41
2015-07-30T09:25:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package in.ac.iitb.cse.wikiminer; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WikiMarkup { private static Pattern markupPattern = Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.DOTALL | Pattern.MULTILINE); public WikiMarkup() { } public List<String> extractMentions(String markup) { Matcher matcher = markupPattern.matcher(markup); String annotation = null; List<String> mentionsList = new ArrayList<String>(); while (matcher.find()) { annotation = matcher.group(1); String[] arr = annotation.split("\\|"); mentionsList.add(arr.length > 1 ? arr[1] : arr[0]); } return mentionsList; } public static void main(String[] args) { // TODO Auto-generated method stub } }
UTF-8
Java
788
java
WikiMarkup.java
Java
[]
null
[]
package in.ac.iitb.cse.wikiminer; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WikiMarkup { private static Pattern markupPattern = Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.DOTALL | Pattern.MULTILINE); public WikiMarkup() { } public List<String> extractMentions(String markup) { Matcher matcher = markupPattern.matcher(markup); String annotation = null; List<String> mentionsList = new ArrayList<String>(); while (matcher.find()) { annotation = matcher.group(1); String[] arr = annotation.split("\\|"); mentionsList.add(arr.length > 1 ? arr[1] : arr[0]); } return mentionsList; } public static void main(String[] args) { // TODO Auto-generated method stub } }
788
0.694162
0.689086
34
22.17647
20.857317
76
false
false
0
0
0
0
0
0
1.441176
false
false
12
1136c1b32a6eb0b161d5bd547f4548d62aa101c9
22,204,980,940,121
ca030864a3a1c24be6b9d1802c2353da4ca0d441
/classes11.dex_source_from_JADX/com/facebook/pages/identity/cards/photos/PageIdentityPhotosGallery.java
119afdd7e78ad7d1de519decbbdf1f791d818b54
[]
no_license
pxson001/facebook-app
https://github.com/pxson001/facebook-app
87aa51e29195eeaae69adeb30219547f83a5b7b1
640630f078980f9818049625ebc42569c67c69f7
refs/heads/master
2020-04-07T20:36:45.758000
2018-03-07T09:04:57
2018-03-07T09:04:57
124,208,458
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.pages.identity.cards.photos; import android.content.Context; import android.support.v4.view.ViewPager.SimpleOnPageChangeListener; import android.util.AttributeSet; import android.view.View; import com.facebook.common.util.StringUtil; import com.facebook.graphql.model.GraphQLPhoto; import com.facebook.inject.FbInjector; import com.facebook.inject.IdBasedSingletonScopeProvider; import com.facebook.photos.consumptiongallery.ConsumptionPhoto; import com.facebook.photos.consumptiongallery.ConsumptionPhotoCache; import com.facebook.photos.mediagallery.MediaGalleryLauncherParamsFactory; import com.facebook.photos.mediagallery.launcher.MediaGalleryLauncher; import com.facebook.photos.mediagallery.ui.DefaultMediaGalleryLauncher; import com.facebook.ui.recyclableviewpool.RecyclableViewPoolManager; import com.facebook.widget.ListViewFriendlyViewPager; import com.google.common.collect.Lists; import java.util.List; import javax.inject.Inject; /* compiled from: privacyHasChanged */ public class PageIdentityPhotosGallery extends ListViewFriendlyViewPager { public PageIdentityPhotoGalleryAdapter f3611a; private List<Long> f3612b; private List<ConsumptionPhoto> f3613c; private ConsumptionPhotoCache f3614d; public OnPhotoDisplayedListener f3615e; /* compiled from: privacyHasChanged */ public interface OnPhotoDisplayedListener { void mo95a(String str); } /* compiled from: privacyHasChanged */ class C04941 extends SimpleOnPageChangeListener { final /* synthetic */ PageIdentityPhotosGallery f3610a; C04941(PageIdentityPhotosGallery pageIdentityPhotosGallery) { this.f3610a = pageIdentityPhotosGallery; } public final void e_(int i) { if (this.f3610a.f3615e != null) { this.f3610a.f3615e.mo95a(((GraphQLPhoto) this.f3610a.f3611a.a.get(i)).K()); } } } private static <T extends View> void m4649a(Class<T> cls, T t) { m4650a((Object) t, t.getContext()); } private static void m4650a(Object obj, Context context) { FbInjector fbInjector = FbInjector.get(context); ((PageIdentityPhotosGallery) obj).m4648a(ConsumptionPhotoCache.a(fbInjector), new PageIdentityPhotoGalleryAdapter((Context) fbInjector.getInstance(Context.class), IdBasedSingletonScopeProvider.a(fbInjector, 610), RecyclableViewPoolManager.a(fbInjector), (MediaGalleryLauncher) DefaultMediaGalleryLauncher.a(fbInjector), MediaGalleryLauncherParamsFactory.a(fbInjector))); } public PageIdentityPhotosGallery(Context context) { super(context); m4653h(); } public PageIdentityPhotosGallery(Context context, AttributeSet attributeSet) { super(context, attributeSet); m4653h(); } private void m4653h() { m4649a(PageIdentityPhotosGallery.class, (View) this); setOnPageChangeListener(new C04941(this)); setAdapter(this.f3611a); } @Inject private void m4648a(ConsumptionPhotoCache consumptionPhotoCache, PageIdentityPhotoGalleryAdapter pageIdentityPhotoGalleryAdapter) { this.f3614d = consumptionPhotoCache; this.f3611a = pageIdentityPhotoGalleryAdapter; } public void setPhotosCollections(List<GraphQLPhoto> list) { this.f3611a.a(list); m4651a((List) list); } private void m4651a(List<GraphQLPhoto> list) { this.f3612b = Lists.a(); this.f3613c = Lists.a(); if (list != null) { for (GraphQLPhoto graphQLPhoto : list) { if (!(StringUtil.a(graphQLPhoto.K()) || graphQLPhoto.L() == null || StringUtil.a(graphQLPhoto.L().b()))) { this.f3612b.add(Long.valueOf(Long.parseLong(graphQLPhoto.K()))); ConsumptionPhoto consumptionPhoto = new ConsumptionPhoto(Long.parseLong(graphQLPhoto.K())); consumptionPhoto.d = graphQLPhoto.L().b(); this.f3614d.a(consumptionPhoto); this.f3613c.add(consumptionPhoto); } } } } public void setOnPhotoDisplayedListener(OnPhotoDisplayedListener onPhotoDisplayedListener) { this.f3615e = onPhotoDisplayedListener; } }
UTF-8
Java
4,258
java
PageIdentityPhotosGallery.java
Java
[]
null
[]
package com.facebook.pages.identity.cards.photos; import android.content.Context; import android.support.v4.view.ViewPager.SimpleOnPageChangeListener; import android.util.AttributeSet; import android.view.View; import com.facebook.common.util.StringUtil; import com.facebook.graphql.model.GraphQLPhoto; import com.facebook.inject.FbInjector; import com.facebook.inject.IdBasedSingletonScopeProvider; import com.facebook.photos.consumptiongallery.ConsumptionPhoto; import com.facebook.photos.consumptiongallery.ConsumptionPhotoCache; import com.facebook.photos.mediagallery.MediaGalleryLauncherParamsFactory; import com.facebook.photos.mediagallery.launcher.MediaGalleryLauncher; import com.facebook.photos.mediagallery.ui.DefaultMediaGalleryLauncher; import com.facebook.ui.recyclableviewpool.RecyclableViewPoolManager; import com.facebook.widget.ListViewFriendlyViewPager; import com.google.common.collect.Lists; import java.util.List; import javax.inject.Inject; /* compiled from: privacyHasChanged */ public class PageIdentityPhotosGallery extends ListViewFriendlyViewPager { public PageIdentityPhotoGalleryAdapter f3611a; private List<Long> f3612b; private List<ConsumptionPhoto> f3613c; private ConsumptionPhotoCache f3614d; public OnPhotoDisplayedListener f3615e; /* compiled from: privacyHasChanged */ public interface OnPhotoDisplayedListener { void mo95a(String str); } /* compiled from: privacyHasChanged */ class C04941 extends SimpleOnPageChangeListener { final /* synthetic */ PageIdentityPhotosGallery f3610a; C04941(PageIdentityPhotosGallery pageIdentityPhotosGallery) { this.f3610a = pageIdentityPhotosGallery; } public final void e_(int i) { if (this.f3610a.f3615e != null) { this.f3610a.f3615e.mo95a(((GraphQLPhoto) this.f3610a.f3611a.a.get(i)).K()); } } } private static <T extends View> void m4649a(Class<T> cls, T t) { m4650a((Object) t, t.getContext()); } private static void m4650a(Object obj, Context context) { FbInjector fbInjector = FbInjector.get(context); ((PageIdentityPhotosGallery) obj).m4648a(ConsumptionPhotoCache.a(fbInjector), new PageIdentityPhotoGalleryAdapter((Context) fbInjector.getInstance(Context.class), IdBasedSingletonScopeProvider.a(fbInjector, 610), RecyclableViewPoolManager.a(fbInjector), (MediaGalleryLauncher) DefaultMediaGalleryLauncher.a(fbInjector), MediaGalleryLauncherParamsFactory.a(fbInjector))); } public PageIdentityPhotosGallery(Context context) { super(context); m4653h(); } public PageIdentityPhotosGallery(Context context, AttributeSet attributeSet) { super(context, attributeSet); m4653h(); } private void m4653h() { m4649a(PageIdentityPhotosGallery.class, (View) this); setOnPageChangeListener(new C04941(this)); setAdapter(this.f3611a); } @Inject private void m4648a(ConsumptionPhotoCache consumptionPhotoCache, PageIdentityPhotoGalleryAdapter pageIdentityPhotoGalleryAdapter) { this.f3614d = consumptionPhotoCache; this.f3611a = pageIdentityPhotoGalleryAdapter; } public void setPhotosCollections(List<GraphQLPhoto> list) { this.f3611a.a(list); m4651a((List) list); } private void m4651a(List<GraphQLPhoto> list) { this.f3612b = Lists.a(); this.f3613c = Lists.a(); if (list != null) { for (GraphQLPhoto graphQLPhoto : list) { if (!(StringUtil.a(graphQLPhoto.K()) || graphQLPhoto.L() == null || StringUtil.a(graphQLPhoto.L().b()))) { this.f3612b.add(Long.valueOf(Long.parseLong(graphQLPhoto.K()))); ConsumptionPhoto consumptionPhoto = new ConsumptionPhoto(Long.parseLong(graphQLPhoto.K())); consumptionPhoto.d = graphQLPhoto.L().b(); this.f3614d.a(consumptionPhoto); this.f3613c.add(consumptionPhoto); } } } } public void setOnPhotoDisplayedListener(OnPhotoDisplayedListener onPhotoDisplayedListener) { this.f3615e = onPhotoDisplayedListener; } }
4,258
0.71442
0.677078
105
39.55238
44.295753
378
false
false
0
0
0
0
0
0
0.638095
false
false
12
fd9dad41e2774776baf76d30dbef83e70f792fdf
27,290,222,262,289
8fc51e1ad1bff9dcd390a02be8d8ffb90b48ae20
/Exercise9.java
c0dc1ead6fe1a19a78032883ea3a99afddf3da5a
[]
no_license
jesla-junior/java_tuts
https://github.com/jesla-junior/java_tuts
a786c5f8942e5b6064dc3e45b4a0f9ac72cd70df
52235bd3a871b06d4a5dd4f79125c8373fda744d
refs/heads/master
2023-07-28T20:16:09.161000
2021-09-28T06:50:11
2021-09-28T06:50:11
271,594,651
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//Trying to demonstrate Composition //We will have 2 classes; Point and Line classes //The point class will create a point object consisting of 2 coordinates: x and y. It will also have methods carrying out operations on this point or the individual x and/or y coordinates //The line class will create a line object consisting of 2 points: say A and B. It will also contain methods carrying out operations on these points or the individual points, sometimes by invoking some methods from the point class. import java.util.Arrays; public class Exercise9{ public static void main (String[] args){ // Test constructor and toString() Line l1 = new Line(1, 2, 3, 4); System.out.println(l1); // Line's toString() //Line[start=(1,2),end=(3,4)] Line l2 = new Line(new Point(5,6), new Point(7,8)); // anonymous Point's instances System.out.println(l2); // Line's toString() //Line[start=(5,6),end=(7,8)] // Test Setters and Getters l1.setStart(new Point(11, 12)); l1.setEnd(new Point(13, 14)); System.out.println(l1); // Line's toString() //Line[start=(11,12),end=(13,14)] System.out.println("start is: " + l1.getStart()); // Point's toString() //start is: (11,12) System.out.println("end is: " + l1.getEnd()); // Point's toString() //end is: (13,14) l1.setStartX(21); l1.setStartY(22); l1.setEndX(23); l1.setEndY(24); System.out.println(l1); // Line's toString() //Line[start=(21,22),end=(23,24)] System.out.println("start's x is: " + l1.getStartX()); //start's x is: 21 System.out.println("start's y is: " + l1.getStartY()); //start's y is: 22 System.out.println("end's x is: " + l1.getEndX()); //end's x is: 23 System.out.println("end's y is: " + l1.getEndY()); //end's y is: 24 l1.setStartXY(31, 32); l1.setEndXY(33, 34); System.out.println(l1); // Line's toString() //Line[start=(31,32),end=(33,34)] System.out.println("start's x and y are: " + Arrays.toString(l1.getStartXY())); //start's x and y are: [31, 32] System.out.println("end's x and y are: " + Arrays.toString(l1.getEndXY())); //end's x and y are: [33, 34] // Test getLength() System.out.printf("length is: %.2f%n", l1.getLength()); //length is: 2.83 } } class Point{ private int x, y; //Constructors public Point(){ this.x = 0; this.y = 0; } public Point(int x, int y){ this.x = x; this.y = y; } public int getX(){ return x; } public void setX(int x){ this.x = x; } public int getY(){ return y; } public void setY(int y){ this.y = y; } public String toString(){ return "(" +x+ ", " +y+ ")"; } public int[] getXY(){ int[] resultArray = new int[2]; resultArray[0] = x; resultArray[1] = y; return resultArray; } public void setXY(int x, int y){ this.x = x; this.y = y; } //distance from this point to point coordinates given: x and y public double distance(int x, int y){ int differenceX = this.x - x; int differenceY = this.y - y; return Math.sqrt(differenceX*differenceX + differenceY*differenceY); } //distance from this point to given point A public double distance(Point A){ int differenceX = this.x - A.x; int differenceY = this.y - A.y; return Math.sqrt(differenceX*differenceX + differenceY*differenceY); } //distance from this point to origin (0,0) public double distance(){ return Math.sqrt(x*x + y*y); } }//End of class Point class Line{ private Point start; private Point end; //Constructors public Line(int x1, int y1, int x2, int y2){ this.start = new Point(x1, y1); this.end = new Point(x2, y2); } public Line(Point start, Point end){ this.start = start; this.end = end; } public Point getStart(){ return start; } public void setStart(Point start){ this.start = start; } public Point getEnd(){ return end; } public void setEnd(Point end){ this.end = end; } public int getStartX(){ return start.getX(); } public void setStartX(int x){ this.start.setX(x); } public int getStartY(){ return this.start.getY(); } public void setStartY(int y){ this.start.setY(y); } public void setStartXY(int x, int y){ this.start.setXY(x, y); } public int[] getStartXY(){ return this.start.getXY(); } public void setEndX(int x){ this.end.setX(x); } public int getEndX(){ return this.end.getX(); } public void setEndY(int y){ this.end.setY(y); } public int getEndY(){ return this.end.getY(); } public void setEndXY(int x, int y){ this.end.setXY(x, y); } public int[] getEndXY(){ return this.end.getXY(); } public String toString(){ return "Line[start=" +start+ ", end=" +end+ "]"; } //distance between the two points start and end public double getLength(){ return start.distance(end); } }//End of class Line
UTF-8
Java
5,935
java
Exercise9.java
Java
[]
null
[]
//Trying to demonstrate Composition //We will have 2 classes; Point and Line classes //The point class will create a point object consisting of 2 coordinates: x and y. It will also have methods carrying out operations on this point or the individual x and/or y coordinates //The line class will create a line object consisting of 2 points: say A and B. It will also contain methods carrying out operations on these points or the individual points, sometimes by invoking some methods from the point class. import java.util.Arrays; public class Exercise9{ public static void main (String[] args){ // Test constructor and toString() Line l1 = new Line(1, 2, 3, 4); System.out.println(l1); // Line's toString() //Line[start=(1,2),end=(3,4)] Line l2 = new Line(new Point(5,6), new Point(7,8)); // anonymous Point's instances System.out.println(l2); // Line's toString() //Line[start=(5,6),end=(7,8)] // Test Setters and Getters l1.setStart(new Point(11, 12)); l1.setEnd(new Point(13, 14)); System.out.println(l1); // Line's toString() //Line[start=(11,12),end=(13,14)] System.out.println("start is: " + l1.getStart()); // Point's toString() //start is: (11,12) System.out.println("end is: " + l1.getEnd()); // Point's toString() //end is: (13,14) l1.setStartX(21); l1.setStartY(22); l1.setEndX(23); l1.setEndY(24); System.out.println(l1); // Line's toString() //Line[start=(21,22),end=(23,24)] System.out.println("start's x is: " + l1.getStartX()); //start's x is: 21 System.out.println("start's y is: " + l1.getStartY()); //start's y is: 22 System.out.println("end's x is: " + l1.getEndX()); //end's x is: 23 System.out.println("end's y is: " + l1.getEndY()); //end's y is: 24 l1.setStartXY(31, 32); l1.setEndXY(33, 34); System.out.println(l1); // Line's toString() //Line[start=(31,32),end=(33,34)] System.out.println("start's x and y are: " + Arrays.toString(l1.getStartXY())); //start's x and y are: [31, 32] System.out.println("end's x and y are: " + Arrays.toString(l1.getEndXY())); //end's x and y are: [33, 34] // Test getLength() System.out.printf("length is: %.2f%n", l1.getLength()); //length is: 2.83 } } class Point{ private int x, y; //Constructors public Point(){ this.x = 0; this.y = 0; } public Point(int x, int y){ this.x = x; this.y = y; } public int getX(){ return x; } public void setX(int x){ this.x = x; } public int getY(){ return y; } public void setY(int y){ this.y = y; } public String toString(){ return "(" +x+ ", " +y+ ")"; } public int[] getXY(){ int[] resultArray = new int[2]; resultArray[0] = x; resultArray[1] = y; return resultArray; } public void setXY(int x, int y){ this.x = x; this.y = y; } //distance from this point to point coordinates given: x and y public double distance(int x, int y){ int differenceX = this.x - x; int differenceY = this.y - y; return Math.sqrt(differenceX*differenceX + differenceY*differenceY); } //distance from this point to given point A public double distance(Point A){ int differenceX = this.x - A.x; int differenceY = this.y - A.y; return Math.sqrt(differenceX*differenceX + differenceY*differenceY); } //distance from this point to origin (0,0) public double distance(){ return Math.sqrt(x*x + y*y); } }//End of class Point class Line{ private Point start; private Point end; //Constructors public Line(int x1, int y1, int x2, int y2){ this.start = new Point(x1, y1); this.end = new Point(x2, y2); } public Line(Point start, Point end){ this.start = start; this.end = end; } public Point getStart(){ return start; } public void setStart(Point start){ this.start = start; } public Point getEnd(){ return end; } public void setEnd(Point end){ this.end = end; } public int getStartX(){ return start.getX(); } public void setStartX(int x){ this.start.setX(x); } public int getStartY(){ return this.start.getY(); } public void setStartY(int y){ this.start.setY(y); } public void setStartXY(int x, int y){ this.start.setXY(x, y); } public int[] getStartXY(){ return this.start.getXY(); } public void setEndX(int x){ this.end.setX(x); } public int getEndX(){ return this.end.getX(); } public void setEndY(int y){ this.end.setY(y); } public int getEndY(){ return this.end.getY(); } public void setEndXY(int x, int y){ this.end.setXY(x, y); } public int[] getEndXY(){ return this.end.getXY(); } public String toString(){ return "Line[start=" +start+ ", end=" +end+ "]"; } //distance between the two points start and end public double getLength(){ return start.distance(end); } }//End of class Line
5,935
0.516933
0.494187
269
21.066914
24.6061
232
false
false
0
0
0
0
0
0
0.449814
false
false
12
e816195632da0e63c80ce8c42da5694254c2e8a9
20,701,742,400,272
e629f64fee80a5a2b4835c2d69e4a0d2b24fa914
/Battleship/src/Gameplay/PatrolBoat.java
3862cb0377dbcae3723edbbd6bebc278ad030917
[]
no_license
LuisEduardoER/sebattleship
https://github.com/LuisEduardoER/sebattleship
1eb7e2450886a71fdef7cbdeaec3ae34763d2006
3db0670fd6385b1eb66e2890cafaae896ab0e9b6
refs/heads/master
2020-12-24T14:18:31.890000
2007-04-14T05:48:06
2007-04-14T05:48:06
42,835,772
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Gameplay; /** * Describes the Patrol Boat ship * @author Nathan * */ public class PatrolBoat extends Ship{ public static final String name ="Patrol Boat"; public PatrolBoat(){ super(); size=2; placed = false; } }
UTF-8
Java
252
java
PatrolBoat.java
Java
[ { "context": "/**\r\n * Describes the Patrol Boat ship\r\n * @author Nathan\r\n *\r\n */\r\npublic class PatrolBoat extends Ship{\r\n", "end": 78, "score": 0.9993681907653809, "start": 72, "tag": "NAME", "value": "Nathan" } ]
null
[]
package Gameplay; /** * Describes the Patrol Boat ship * @author Nathan * */ public class PatrolBoat extends Ship{ public static final String name ="Patrol Boat"; public PatrolBoat(){ super(); size=2; placed = false; } }
252
0.630952
0.626984
15
14.666667
14.262616
48
false
false
0
0
0
0
0
0
0.933333
false
false
12
c12e5d3e7b73eb49250b72f2a452caba43e75c5a
9,646,496,560,787
a84519a6011be7782336e50ed2341e4a6575af27
/src/main/java/pk/com/habsoft/robosim/planning/pathsmoother/views/DrawingControlPanel.java
13c866e6ecd63348e819c737303208d091e31207
[ "Apache-2.0" ]
permissive
habsoft/robosim
https://github.com/habsoft/robosim
7206a38c61bf0c4482fa31ceb73e4b71a08fe363
30d172757ab59671d7ace6163d549b667435943a
refs/heads/develop
2020-12-25T18:08:42.644000
2017-07-06T02:53:40
2017-07-06T02:53:40
48,618,209
24
20
null
false
2017-10-24T22:17:45
2015-12-26T17:22:29
2017-07-26T21:26:47
2017-10-24T22:17:45
561
11
16
5
Java
false
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pk.com.habsoft.robosim.planning.pathsmoother.views; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSpinner; import javax.swing.JToggleButton; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class DrawingControlPanel extends JPanel implements ActionListener, ChangeListener { private static final long serialVersionUID = 1L; DrawingPanel drawingPanel = null; private JButton clearButton = new JButton("Clear"); JRadioButton rbDraw = new JRadioButton("Draw"); JRadioButton rbErase = new JRadioButton("Erase"); JRadioButton rbStart = new JRadioButton("Start"); JRadioButton rbFinish = new JRadioButton("Finish"); JToggleButton tbEditWorld = new JToggleButton("Edit World"); JSpinner spnRows = new JSpinner(); JSpinner spnColumns = new JSpinner(); private int drawMod = DrawingPanel.NONE; public void setDrawingPanel(DrawingPanel observer) { this.drawingPanel = observer; this.drawingPanel.setDrawingMod(drawMod); } public DrawingControlPanel(int rows, int columns) { setLayout(new FlowLayout()); tbEditWorld.addActionListener(this); tbEditWorld.setBackground(Color.GREEN); add(tbEditWorld); clearButton.addActionListener(this); clearButton.setEnabled(tbEditWorld.isSelected()); add(clearButton); rbDraw.addActionListener(this); rbDraw.setSelected(drawMod == DrawingPanel.NONE); rbDraw.setEnabled(tbEditWorld.isSelected()); add(rbDraw); rbErase.addActionListener(this); rbErase.setSelected(drawMod == DrawingPanel.ERASE); rbErase.setEnabled(tbEditWorld.isSelected()); add(rbErase); rbStart.addActionListener(this); rbStart.setSelected(drawMod == DrawingPanel.START); rbStart.setEnabled(tbEditWorld.isSelected()); add(rbStart); rbFinish.addActionListener(this); rbFinish.setSelected(drawMod == DrawingPanel.FINISH); rbFinish.setEnabled(tbEditWorld.isSelected()); add(rbFinish); ButtonGroup gp = new ButtonGroup(); gp.add(rbDraw); gp.add(rbErase); gp.add(rbStart); gp.add(rbFinish); spnRows.setModel(new SpinnerNumberModel(rows, 2, 100, 1)); spnRows.addChangeListener(this); spnRows.setEnabled(false); add(spnRows); spnColumns.setModel(new SpinnerNumberModel(columns, 2, 100, 1)); spnColumns.addChangeListener(this); spnColumns.setEnabled(false); add(spnColumns); add(new JLabel("Click Edit button to modify Robot World and drag mouse on Robot World to change it.")); } @Override public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj.equals(clearButton)) { if (tbEditWorld.isSelected()) { drawingPanel.clear(); } } else if (obj.equals(rbDraw)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.DRAW : DrawingPanel.NONE; } else if (obj.equals(rbErase)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.ERASE : DrawingPanel.NONE; } else if (obj.equals(rbStart)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.START : DrawingPanel.NONE; } else if (obj.equals(rbFinish)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.FINISH : DrawingPanel.NONE; } else if (obj.equals(tbEditWorld)) { spnRows.setEnabled(tbEditWorld.isSelected()); spnColumns.setEnabled(tbEditWorld.isSelected()); clearButton.setEnabled(tbEditWorld.isSelected()); rbDraw.setEnabled(tbEditWorld.isSelected()); rbErase.setEnabled(tbEditWorld.isSelected()); rbStart.setEnabled(tbEditWorld.isSelected()); rbFinish.setEnabled(tbEditWorld.isSelected()); if (tbEditWorld.isSelected()) { rbDraw.setSelected(true); drawMod = DrawingPanel.DRAW; } else { drawMod = DrawingPanel.NONE; } } drawingPanel.setDrawingMod(drawMod); } @Override public void stateChanged(ChangeEvent arg0) { drawingPanel.setWorldSize(Integer.parseInt(spnRows.getValue().toString()), Integer.parseInt(spnColumns.getValue().toString())); } }
UTF-8
Java
4,243
java
DrawingControlPanel.java
Java
[]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pk.com.habsoft.robosim.planning.pathsmoother.views; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSpinner; import javax.swing.JToggleButton; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class DrawingControlPanel extends JPanel implements ActionListener, ChangeListener { private static final long serialVersionUID = 1L; DrawingPanel drawingPanel = null; private JButton clearButton = new JButton("Clear"); JRadioButton rbDraw = new JRadioButton("Draw"); JRadioButton rbErase = new JRadioButton("Erase"); JRadioButton rbStart = new JRadioButton("Start"); JRadioButton rbFinish = new JRadioButton("Finish"); JToggleButton tbEditWorld = new JToggleButton("Edit World"); JSpinner spnRows = new JSpinner(); JSpinner spnColumns = new JSpinner(); private int drawMod = DrawingPanel.NONE; public void setDrawingPanel(DrawingPanel observer) { this.drawingPanel = observer; this.drawingPanel.setDrawingMod(drawMod); } public DrawingControlPanel(int rows, int columns) { setLayout(new FlowLayout()); tbEditWorld.addActionListener(this); tbEditWorld.setBackground(Color.GREEN); add(tbEditWorld); clearButton.addActionListener(this); clearButton.setEnabled(tbEditWorld.isSelected()); add(clearButton); rbDraw.addActionListener(this); rbDraw.setSelected(drawMod == DrawingPanel.NONE); rbDraw.setEnabled(tbEditWorld.isSelected()); add(rbDraw); rbErase.addActionListener(this); rbErase.setSelected(drawMod == DrawingPanel.ERASE); rbErase.setEnabled(tbEditWorld.isSelected()); add(rbErase); rbStart.addActionListener(this); rbStart.setSelected(drawMod == DrawingPanel.START); rbStart.setEnabled(tbEditWorld.isSelected()); add(rbStart); rbFinish.addActionListener(this); rbFinish.setSelected(drawMod == DrawingPanel.FINISH); rbFinish.setEnabled(tbEditWorld.isSelected()); add(rbFinish); ButtonGroup gp = new ButtonGroup(); gp.add(rbDraw); gp.add(rbErase); gp.add(rbStart); gp.add(rbFinish); spnRows.setModel(new SpinnerNumberModel(rows, 2, 100, 1)); spnRows.addChangeListener(this); spnRows.setEnabled(false); add(spnRows); spnColumns.setModel(new SpinnerNumberModel(columns, 2, 100, 1)); spnColumns.addChangeListener(this); spnColumns.setEnabled(false); add(spnColumns); add(new JLabel("Click Edit button to modify Robot World and drag mouse on Robot World to change it.")); } @Override public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if (obj.equals(clearButton)) { if (tbEditWorld.isSelected()) { drawingPanel.clear(); } } else if (obj.equals(rbDraw)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.DRAW : DrawingPanel.NONE; } else if (obj.equals(rbErase)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.ERASE : DrawingPanel.NONE; } else if (obj.equals(rbStart)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.START : DrawingPanel.NONE; } else if (obj.equals(rbFinish)) { drawMod = tbEditWorld.isSelected() ? DrawingPanel.FINISH : DrawingPanel.NONE; } else if (obj.equals(tbEditWorld)) { spnRows.setEnabled(tbEditWorld.isSelected()); spnColumns.setEnabled(tbEditWorld.isSelected()); clearButton.setEnabled(tbEditWorld.isSelected()); rbDraw.setEnabled(tbEditWorld.isSelected()); rbErase.setEnabled(tbEditWorld.isSelected()); rbStart.setEnabled(tbEditWorld.isSelected()); rbFinish.setEnabled(tbEditWorld.isSelected()); if (tbEditWorld.isSelected()) { rbDraw.setSelected(true); drawMod = DrawingPanel.DRAW; } else { drawMod = DrawingPanel.NONE; } } drawingPanel.setDrawingMod(drawMod); } @Override public void stateChanged(ChangeEvent arg0) { drawingPanel.setWorldSize(Integer.parseInt(spnRows.getValue().toString()), Integer.parseInt(spnColumns.getValue().toString())); } }
4,243
0.753948
0.751119
139
29.525179
22.939184
105
false
false
0
0
0
0
0
0
2.021583
false
false
12
514c1c5827f7bcf8f955df146eaf4f90d277dfe9
28,226,525,127,747
d4a66f634ef0989de6ad7ddd6d733b24f3ad02ae
/Maven_Accounting_Libs/mavenAccJournalEntryModule/src/main/java/com/krawler/hql/accounting/journalentry/service/AccJournalEntryModuleServiceImpl.java
534c3843e6dbd14150b0c3cd91c593f863e549e6
[]
no_license
cckmit/erp-4
https://github.com/cckmit/erp-4
2a47fac2f6b4e534165b22cf4a160a0eb07797b1
b5580270f868ce21258749b59299cb26a8d9ecd0
refs/heads/main
2023-07-12T19:52:30.165000
2021-08-31T17:50:13
2021-08-31T17:50:13
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.krawler.hql.accounting.journalentry.service; import com.krawler.common.admin.AuditAction; import com.krawler.common.admin.Company; import com.krawler.common.admin.ExtraCompanyPreferences; import com.krawler.common.admin.KWLCurrency; import com.krawler.common.admin.User; import com.krawler.common.service.ServiceException; import com.krawler.common.session.SessionExpiredException; import com.krawler.common.util.Constants; import com.krawler.common.util.StringUtil; import com.krawler.customFieldMaster.fieldDataManager; import com.krawler.esp.handlers.SendMailHandler; import com.krawler.hql.accounting.*; import com.krawler.spring.accounting.companypreferances.accCompanyPreferencesDAO; import com.krawler.spring.accounting.costCenter.CCConstants; import com.krawler.spring.accounting.currency.accCurrencyDAO; import com.krawler.spring.accounting.customer.accCustomerDAO; import com.krawler.spring.accounting.handler.AccountingHandlerDAO; import com.krawler.spring.accounting.handler.AccountingManager; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.GSTRTYPE; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.ITC_TRANSACTION_IDS; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.JEDID; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.JEID; import com.krawler.spring.accounting.journalentry.accJournalEntryController; import com.krawler.spring.accounting.journalentry.accJournalEntryDAO; import com.krawler.spring.accounting.multiLevelApprovalRule.AccMultiLevelApprovalDAO; import com.krawler.spring.accounting.payment.accPaymentDAO; import com.krawler.spring.accounting.payment.accPaymentService; import com.krawler.spring.auditTrailModule.auditTrailDAO; import com.krawler.spring.authHandler.authHandler; import com.krawler.spring.authHandler.authHandlerDAO; import com.krawler.spring.common.KwlReturnObject; import com.krawler.spring.common.kwlCommonTablesDAO; import com.krawler.spring.sessionHandler.sessionHandlerImpl; import com.krawler.utils.json.base.JSONArray; import com.krawler.utils.json.base.JSONException; import com.krawler.utils.json.base.JSONObject; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLDecoder; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.web.servlet.support.RequestContextUtils; /** * * @author krawler */ public class AccJournalEntryModuleServiceImpl implements AccJournalEntryModuleService, MessageSourceAware { private MessageSource messageSource; private HibernateTransactionManager txnManager; private accJournalEntryDAO accJournalEntryobj; private accCompanyPreferencesDAO accCompanyPreferencesObj; private accCurrencyDAO accCurrencyobj; private auditTrailDAO auditTrailObj; private AccountingHandlerDAO accountingHandlerDAOobj; private String successView; private fieldDataManager fieldDataManagercntrl; private accCustomerDAO accCustomerDAOobj; private accPaymentDAO accPaymentDAOobj; private accPaymentService accPaymentService; private AccMultiLevelApprovalDAO accMultiLevelApprovalDAOObj; private com.krawler.spring.common.fieldDataManager fieldDataManagercntrl1; private authHandlerDAO authHandlerDAOObj; private EnglishNumberToWords EnglishNumberToWordsOjb = new EnglishNumberToWords(); private kwlCommonTablesDAO kwlCommonTablesDAOObj; public void setKwlCommonTablesDAOObj(kwlCommonTablesDAO kwlCommonTablesDAOObj) { this.kwlCommonTablesDAOObj = kwlCommonTablesDAOObj; } public void setFieldDataManagercntrl1(com.krawler.spring.common.fieldDataManager fieldDataManagercntrl1) { this.fieldDataManagercntrl1 = fieldDataManagercntrl1; } public void setauthHandlerDAO(authHandlerDAO authHandlerDAOObj1) { this.authHandlerDAOObj = authHandlerDAOObj1; } public void setaccountingHandlerDAO(AccountingHandlerDAO AccountingHandlerDAOobj) { this.accountingHandlerDAOobj = AccountingHandlerDAOobj; } public void setaccMultiLevelApprovalDAOObj(AccMultiLevelApprovalDAO accMultiLevelApprovalDAO) { this.accMultiLevelApprovalDAOObj = accMultiLevelApprovalDAO; } public void setauditTrailDAO(auditTrailDAO auditTrailDAOObj) { this.auditTrailObj = auditTrailDAOObj; } public void setTxnManager(HibernateTransactionManager txManager) { this.txnManager = txManager; } public void setMessageSource(MessageSource ms) { this.messageSource = ms; } public void setaccJournalEntryDAO(accJournalEntryDAO accJournalEntryobj) { this.accJournalEntryobj = accJournalEntryobj; } public void setaccCompanyPreferencesDAO(accCompanyPreferencesDAO accCompanyPreferencesObj) { this.accCompanyPreferencesObj = accCompanyPreferencesObj; } public void setaccCurrencyDAO(accCurrencyDAO accCurrencyobj) { this.accCurrencyobj = accCurrencyobj; } public String getSuccessView() { return successView; } public void setFieldDataManager(fieldDataManager fieldDataManagercntrl) { this.fieldDataManagercntrl = fieldDataManagercntrl; } public void setSuccessView(String successView) { this.successView = successView; } public void setaccCustomerDAO(accCustomerDAO accCustomerDAOobj) { this.accCustomerDAOobj = accCustomerDAOobj; } public void setAccPaymentDAOobj(accPaymentDAO accPaymentDAOobj) { this.accPaymentDAOobj = accPaymentDAOobj; } public void setAccPaymentService(accPaymentService accPaymentService) { this.accPaymentService = accPaymentService; } public JSONObject saveJournalEntry(HttpServletRequest request, HttpServletResponse response) { JSONObject jobj = new JSONObject(); String msg = ""; String billno = ""; String billid = ""; String amount = ""; boolean issuccess = true; String butPendingForApproval = ""; try{ JSONObject paramJObj = new JSONObject(); try{Enumeration<String> attributes = request.getAttributeNames(); while(attributes.hasMoreElements()){ String attribute = attributes.nextElement(); paramJObj.put(attribute, request.getAttribute(attribute)); } Enumeration<String> parameters = request.getParameterNames(); while(parameters.hasMoreElements()){ String parameter = parameters.nextElement(); paramJObj.put(parameter, request.getParameter(parameter)); } } catch(JSONException e){ e.printStackTrace(); } String companyid = sessionHandlerImpl.getCompanyid(request); String userDateFormat = sessionHandlerImpl.getUserDateFormat(request); String userfullname = sessionHandlerImpl.getUserFullName(request); String currencyid = sessionHandlerImpl.getCurrencyID(request); paramJObj.put(Constants.companyKey, companyid); paramJObj.put("userdateformat", userDateFormat); paramJObj.put(Constants.currencyKey, currencyid); paramJObj.put(Constants.globalCurrencyKey, currencyid); paramJObj.put(Constants.userfullname, userfullname); String timezoneOffset = sessionHandlerImpl.getTimeZoneDifference(request); paramJObj.put("timezoneOffset", timezoneOffset); paramJObj.put("language", RequestContextUtils.getLocale(request).getLanguage()); jobj = saveJournalEntryJson(paramJObj); } catch(SessionExpiredException ex){ issuccess=false; Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { issuccess=false; Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { issuccess=false; ex.printStackTrace(); msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jobj.put("success", issuccess); jobj.put("msg", msg); jobj.put("billid", billid); jobj.put("billno", billno); jobj.put("amount", ""); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public JournalEntry saveJournalEntry(HttpServletRequest request, JSONObject dataMap, int counter) throws SessionExpiredException, ServiceException, AccountingException, JSONException { JournalEntry journalEntry = null; JSONObject paramJObj = new JSONObject(); try{Enumeration<String> attributes = request.getAttributeNames(); while(attributes.hasMoreElements()){ String attribute = attributes.nextElement(); paramJObj.put(attribute, request.getAttribute(attribute)); } Enumeration<String> parameters = request.getParameterNames(); while(parameters.hasMoreElements()){ String parameter = parameters.nextElement(); paramJObj.put(parameter, request.getParameter(parameter)); } } catch(JSONException e){ e.printStackTrace(); } String companyid = sessionHandlerImpl.getCompanyid(request); String userDateFormat = sessionHandlerImpl.getUserDateFormat(request); String userfullname = sessionHandlerImpl.getUserFullName(request); String currencyid = sessionHandlerImpl.getCurrencyID(request); paramJObj.put(Constants.companyKey, companyid); paramJObj.put("userdateformat", userDateFormat); paramJObj.put(Constants.currencyKey, currencyid); paramJObj.put(Constants.globalCurrencyKey, currencyid); paramJObj.put(Constants.userfullname, userfullname); String timezoneOffset = sessionHandlerImpl.getTimeZoneDifference(request); paramJObj.put("timezoneOffset", timezoneOffset); paramJObj.put("language", RequestContextUtils.getLocale(request).getLanguage()); journalEntry = saveJournalEntryJson(paramJObj, dataMap, counter); return journalEntry; } public JSONObject saveJournalEntryJson(JSONObject paramJobj) throws JSONException, SessionExpiredException, ServiceException{ JSONObject jobj = new JSONObject(); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Quotation_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null;//txnManager.getTransaction(def); try{ int counter = 0; JSONArray jarr = paramJobj.getJSONArray("jedata"); JSONArray respArray = new JSONArray(); for (int i = 0; i < jarr.length(); i++) { status = txnManager.getTransaction(def); JSONObject dataMap = jarr.getJSONObject(i); JournalEntry je = saveJournalEntryJson(paramJobj, dataMap, counter); JSONObject jeObj = new JSONObject(); jeObj.put("entryno", je.getEntryNumber()); jeObj.put("jeid", je.getID()); respArray.put(jeObj); // counter++; txnManager.commit(status); } String msg = messageSource.getMessage("acc.je1.save", null, Locale.forLanguageTag(paramJobj.getString("language"))); jobj.put("msg", msg); jobj.put("jarr", respArray); jobj.put("success", true); } catch(ServiceException e){ txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw ServiceException.FAILURE(e.getMessage(), e); } catch(SessionExpiredException e){ txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw ServiceException.FAILURE(e.getMessage(), e); } catch(JSONException e){ txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw new JSONException(e); } catch (AccountingException e) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw ServiceException.FAILURE(e.getMessage(), e); } return jobj; } public JournalEntry saveJournalEntryJson(JSONObject paramJobj, JSONObject dataMap, int counter) throws SessionExpiredException, ServiceException, AccountingException,JSONException { JournalEntry journalEntry = null; String companyid = paramJobj.getString(Constants.companyKey); String currencyid = paramJobj.getString(Constants.currencyKey); DateFormat df = authHandler.getDateOnlyFormat(); Calendar cal = Calendar.getInstance(); Date billdateVal = null; long billdateValue = 0; if(!StringUtil.isNullOrEmpty(paramJobj.optString("creationdate"))){ billdateValue = (long) Long.parseLong(paramJobj.get("creationdate").toString()); } else{ billdateValue = (new Date()).getTime(); } cal.setTimeInMillis(billdateValue); String timeZoneDifference = ""; if(paramJobj.has("timezoneOffset")){ timeZoneDifference = paramJobj.getString("timezoneOffset"); } cal.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDifference)); billdateVal = cal.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy hh:mm:ss aa"); try { billdateVal = df.parse(sdf.format(billdateVal)); } catch (ParseException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } double externalCurrencyRate = 1d; if (!StringUtil.isNullOrEmpty(currencyid)) { HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put(Constants.globalCurrencyKey, paramJobj.getString(Constants.currencyKey)); requestParams.put(Constants.companyKey, companyid); externalCurrencyRate = accCurrencyobj.getCurrencyToBaseRate(requestParams, currencyid, billdateVal); } double amount = 0; if(dataMap.has("amount")){ amount = Double.parseDouble(dataMap.get("amount").toString()); } String sales_Account = ""; String revenueaccount = ""; KwlReturnObject cap = accountingHandlerDAOobj.getObject(ExtraCompanyPreferences.class.getName(), companyid); ExtraCompanyPreferences preferences = (ExtraCompanyPreferences) cap.getEntityList().get(0); if (preferences.isRecurringDeferredRevenueRecognition()) { KwlReturnObject cap1 = accountingHandlerDAOobj.getObject(Account.class.getName(), preferences.getSalesAccount()); Account salesaccount = (Account) cap1.getEntityList().get(0); sales_Account = salesaccount.getID(); KwlReturnObject cap2 = accountingHandlerDAOobj.getObject(Account.class.getName(), preferences.getSalesRevenueRecognitionAccount()); Account revenueacc = (Account) cap2.getEntityList().get(0); revenueaccount = revenueacc.getID(); } else { throw new AccountingException("Please set Advance sales and Revenue Recognition Account for LMS"); } Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJobj); String jeentryNumber = null; String jeDatePrefix = ""; String jeDateAfterPrefix = ""; String jeDateSuffix = ""; boolean jeautogenflag = false; String jeSeqFormatId = ""; synchronized (this) { try { HashMap<String, Object> JEFormatParams = new HashMap<String, Object>(); JEFormatParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); JEFormatParams.put("modulename", "autojournalentry"); JEFormatParams.put(Constants.companyKey, companyid); JEFormatParams.put("isdefaultFormat", true); KwlReturnObject kwlObj = accCompanyPreferencesObj.getSequenceFormat(JEFormatParams); SequenceFormat format = (SequenceFormat) kwlObj.getEntityList().get(0); Map<String, Object> seqNumberMap = new HashMap<String, Object>(); seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, format.getID(), false, billdateVal); String nextAutoNoTemp = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number int sequence = Integer.parseInt((String)seqNumberMap.get(Constants.SEQNUMBER)); jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part sequence = sequence + counter; String number = "" + sequence; String action = "" + (sequence - counter); nextAutoNoTemp.replaceAll(action, number); jeentryNumber = nextAutoNoTemp.replaceAll(action, number); //next auto generated number jeSeqFormatId = format.getID(); jeautogenflag = true; jeDataMap.put("entrynumber", jeentryNumber); jeDataMap.put("autogenerated", jeautogenflag); jeDataMap.put(Constants.SEQFORMAT, jeSeqFormatId); jeDataMap.put(Constants.SEQNUMBER, number); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); } catch (ServiceException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } String invoiceId= dataMap.optString("invoiceId", ""); String invoiceNo= dataMap.optString("invoiceNo", ""); String memo="Manual JE For Revenue Recognition for Invoice "+invoiceNo; jeDataMap.put("entrydate", billdateVal); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, currencyid); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", 1); String custCode = dataMap.optString("studentid", ""); String CustomerId = ""; if (!StringUtil.isNullOrEmpty(custCode)) { KwlReturnObject resultcheck = accCustomerDAOobj.checkCustomerExistbyCode(custCode, companyid); if (!resultcheck.getEntityList().isEmpty()) { Customer customer = (Customer) resultcheck.getEntityList().get(0); CustomerId = customer.getID(); } } jeDataMap.put("customerid", CustomerId); journalEntry = accJournalEntryobj.getJournalEntry(jeDataMap); accJournalEntryobj.saveJournalEntryByObject(journalEntry); HashMap hashMap=new HashMap(); hashMap.put("invoiceId", invoiceId); hashMap.put("jeId", journalEntry.getID()); accJournalEntryobj.saveRevenueJEInvoiceMapping(hashMap); //custom code JSONArray jcustomarray = null; boolean customfieldArrayflag = true; String customfieldArray = dataMap.optString("customfieldArray", ""); //Custom Data from other Project customfieldArray = StringUtil.DecodeText(customfieldArray); if (!StringUtil.isNullOrEmpty(customfieldArray)) { HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); String mapWithFieldType = paramJobj.optString("mapWithFieldType",null); customrequestParams.put("customarray", customfieldArray); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("mapWithFieldType", mapWithFieldType); jcustomarray = fieldDataManagercntrl.createJSONArrForCustomFieldValueFromOtherSource(customrequestParams); customfieldArrayflag = false; } // Add Custom fields details if (!StringUtil.isNullOrEmpty(dataMap.optString("customfield", "")) || !StringUtil.isNullOrEmpty(customfieldArray)) { if (customfieldArrayflag) { jcustomarray = new JSONArray(dataMap.optString("customfield", "[]")); } HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); customrequestParams.put("customarray", jcustomarray); customrequestParams.put("modulename", Constants.Acc_JE_modulename); customrequestParams.put("moduleprimarykey", Constants.Acc_JEid); customrequestParams.put("modulerecid", journalEntry.getID()); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("customdataclasspath", Constants.Acc_BillInv_custom_data_classpath); KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams); if (customDataresult != null && customDataresult.getEntityList().size() > 0) { Map<String, Object> customjeDataMap = new HashMap<String, Object>(); customjeDataMap.put("accjecustomdataref", journalEntry.getID()); customjeDataMap.put("jeid", journalEntry.getID()); accJournalEntryobj.updateCustomFieldJournalEntry(customjeDataMap); } } JSONObject jedjson = new JSONObject(); jedjson.put("srno", 1); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", amount); jedjson.put("accountid", sales_Account); jedjson.put("debit", true); jedjson.put("jeid", journalEntry.getID()); KwlReturnObject jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); JournalEntryDetail jed = (JournalEntryDetail) jedresult.getEntityList().get(0); Set<JournalEntryDetail> detail = new HashSet(); detail.add(jed); jedjson = new JSONObject(); jedjson.put("srno", 2); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", amount); jedjson.put("accountid", revenueaccount); jedjson.put("debit", false); jedjson.put("jeid", journalEntry.getID()); jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); jed = (JournalEntryDetail) jedresult.getEntityList().get(0); detail.add(jed); journalEntry.setDetails(detail); accJournalEntryobj.saveJournalEntryDetailsSet(detail); Map<String, Object> auditTrailMap = new HashMap<String, Object>(); auditTrailMap.put(Constants.useridKey, paramJobj.getString("lid")); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJobj.optString(Constants.userfullname) + " has posted Journal Entry " + jeentryNumber +" for Revenue Recognition ", auditTrailMap,journalEntry.getID()); return journalEntry; } @Override public synchronized KwlReturnObject updateJEEntryNumberForNewJE(Map<String, Object> jeDataMap, JournalEntry JE, String companyid, String sequenceFormat,int approvedLevel) { String entryNumber = ""; List list = new ArrayList(); boolean successFlag=true; try { String nextJEAutoNo = null; //String sequenceformat = request.getParameter("sequenceformat"); String psotingDateStr = (String) jeDataMap.get("postingDate"); DateFormat df = authHandler.getDateOnlyFormat(); Date postingDate = null; if (!StringUtil.isNullOrEmpty(psotingDateStr)) { postingDate = df.parse(psotingDateStr); } Map<String,Object> paramMap=new HashMap<>(); paramMap.put("id",companyid); Object exPrefObject = kwlCommonTablesDAOObj.getRequestedObjectFields(ExtraCompanyPreferences.class, new String[]{"columnPref"}, paramMap); JSONObject jObj = StringUtil.isNullObject(exPrefObject) ? new JSONObject() : new JSONObject(exPrefObject.toString()); boolean isPostingDateCheck = false; if (!StringUtil.isNullObject(jObj) && jObj.has(Constants.IS_POSTING_DATE_CHECK) && jObj.get(Constants.IS_POSTING_DATE_CHECK) != null && jObj.optBoolean(Constants.IS_POSTING_DATE_CHECK, false)) { isPostingDateCheck = true; } if (!sequenceFormat.equals("NA") && !StringUtil.isNullOrEmpty(sequenceFormat)) { boolean seqformat_oldflag = false;//StringUtil.getBoolean(request.getParameter("seqformat_oldflag")); String nextAutoNo = ""; String nextAutoNoInt = ""; if (seqformat_oldflag) { nextJEAutoNo = accCompanyPreferencesObj.getNextAutoNumber(companyid, StaticValues.AUTONUM_JOURNALENTRY, sequenceFormat); } else { Map<String, Object> seqNumberMap = new HashMap<String, Object>(); if (postingDate != null && isPostingDateCheck) { seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, sequenceFormat, seqformat_oldflag, postingDate); } else { seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, sequenceFormat, seqformat_oldflag, JE.getEntryDate()); } nextJEAutoNo = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number nextAutoNoInt = (String)seqNumberMap.get(Constants.SEQNUMBER);//integer Part String jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part String jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part String jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part jeDataMap.put(Constants.SEQFORMAT, sequenceFormat); jeDataMap.put(Constants.SEQNUMBER, nextAutoNoInt); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); entryNumber = nextJEAutoNo; } } if (isPostingDateCheck && postingDate!=null) { jeDataMap.put("entrydate", postingDate); } else { jeDataMap.put("entrydate", JE.getEntryDate()); } jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("entrynumber", entryNumber); jeDataMap.put("jeid", JE.getID()); jeDataMap.put("istemplate", JE.getIstemplate()); jeDataMap.put("isReval", JE.getIsReval()); jeDataMap.put("isDraft", JE.isDraft()); jeDataMap.put("pendingapproval", approvedLevel); KwlReturnObject je1result = accJournalEntryobj.saveJournalEntry(jeDataMap); list.add(entryNumber); } catch (Exception e) { list.add(e.getMessage()); successFlag=false; Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, e); } return new KwlReturnObject(successFlag, "JE entry number has been updated successfully", null, list, list.size()); } @Override public String getNextChequeNumberForRecurredJE(String companyId, String bankAccountId) { String nextChequeNumber = ""; try { nextChequeNumber = accPaymentService.getNextChequeNumberForRecurredPayment(companyId,bankAccountId); } catch (Exception ex) { Logger.getLogger(accPaymentService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return nextChequeNumber; } @Override public KwlReturnObject addCheque(HashMap<String, Object> checkHM) { KwlReturnObject cqresult = null; try { cqresult = accPaymentDAOobj.addCheque(checkHM); } catch (Exception ex) { Logger.getLogger(accPaymentService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return cqresult; } public JSONObject saveJournalEntryRemoteApplication(HttpServletRequest request, HttpServletResponse response) { String msg = ""; boolean issuccess = true; JSONObject jobj = new JSONObject(); try { JSONObject paramJObj = new JSONObject(); Enumeration<String> attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = attributes.nextElement(); paramJObj.put(attribute, request.getAttribute(attribute)); } Enumeration<String> parameters = request.getParameterNames(); while (parameters.hasMoreElements()) { String parameter = parameters.nextElement(); paramJObj.put(parameter, request.getParameter(parameter)); } String companyid = sessionHandlerImpl.getCompanyid(request); String userDateFormat = sessionHandlerImpl.getUserDateFormat(request); paramJObj.put(Constants.companyKey, companyid); String currencyid = sessionHandlerImpl.getCurrencyID(request); paramJObj.put(Constants.currencyKey, currencyid); paramJObj.put(Constants.globalCurrencyKey, currencyid); String userfullname = sessionHandlerImpl.getUserFullName(request); paramJObj.put(Constants.userfullname, userfullname); paramJObj.put("userdateformat", userDateFormat); String userId = sessionHandlerImpl.getUserid(request); paramJObj.put(Constants.useridKey, userId); paramJObj.put("lid", userId); paramJObj.put("language", RequestContextUtils.getLocale(request).getLanguage()); jobj = saveJournalEntryRemoteApplicationJson(paramJObj); } catch (JSONException ex) { msg = "" + ex.getMessage(); issuccess=false; if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (SessionExpiredException ex) { issuccess=false; msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (ServiceException ex) { issuccess=false; msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { issuccess=false; msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jobj.put("success", issuccess); jobj.put("msg", msg); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public JournalEntry saveJournalEntryRemoteApplication(HttpServletRequest request, JSONObject dataMap) throws SessionExpiredException, ServiceException, AccountingException { JournalEntry journalEntry = null; try { String companyid = sessionHandlerImpl.getCompanyid(request); String currencyid = (!StringUtil.isNullOrEmpty(request.getParameter(Constants.currencyKey)) ? request.getParameter(Constants.currencyKey) : sessionHandlerImpl.getCurrencyID(request)); Map<String, Object> jeDataMap = AccountingManager.getGlobalParams(request); double externalCurrencyRate = 1d; String jeentryNumber = null; boolean jeautogenflag = false; String jeSeqFormatId = ""; synchronized (this) { try { HashMap<String, Object> JEFormatParams = new HashMap<String, Object>(); JEFormatParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); JEFormatParams.put("modulename", "autojournalentry"); JEFormatParams.put(Constants.companyKey, companyid); JEFormatParams.put("isdefaultFormat", true); KwlReturnObject kwlObj = accCompanyPreferencesObj.getSequenceFormat(JEFormatParams); SequenceFormat format = (SequenceFormat) kwlObj.getEntityList().get(0); Map<String, Object> seqNumberMap = new HashMap<String, Object>(); seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, format.getID(), false, null); // Since JE date is always system date with timezone, hence sending null. It has been hadled in called method String nextAutoNoTemp = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number String jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part String jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part String jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part int sequence = Integer.parseInt((String)seqNumberMap.get(Constants.SEQNUMBER)); sequence = sequence; String number = "" + sequence; String action = "" + (sequence); nextAutoNoTemp.replaceAll(action, number); jeentryNumber = nextAutoNoTemp.replaceAll(action, number); //next auto generated number jeSeqFormatId = format.getID(); jeautogenflag = true; jeDataMap.put("entrynumber", jeentryNumber); jeDataMap.put("autogenerated", jeautogenflag); jeDataMap.put(Constants.SEQFORMAT, jeSeqFormatId); jeDataMap.put(Constants.SEQNUMBER, number); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); } catch (ServiceException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } String memo = dataMap.optString("memo", ""); String auditmessage = dataMap.optString("auditmessage", ""); // jeDataMap.put("entrydate", new Date()); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, currencyid); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", 1); journalEntry = accJournalEntryobj.getJournalEntry(jeDataMap); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date newdate=authHandler.getDateWithTimeFormat().parse(authHandler.getConstantDateFormatter().format(new Date())); Date newdate=new Date(); String userdiff=journalEntry.getCompany().getCreator().getTimeZone()!=null?journalEntry.getCompany().getCreator().getTimeZone().getDifference() : journalEntry.getCompany().getTimeZone().getDifference(); sdf.setTimeZone(TimeZone.getTimeZone("GMT"+userdiff)); Date newcreatedate=authHandler.getDateWithTimeFormat().parse(sdf.format(newdate)); journalEntry.setEntryDate(newcreatedate); accJournalEntryobj.saveJournalEntryByObject(journalEntry); JSONArray jArr = new JSONArray(dataMap.optString("details")); Set<JournalEntryDetail> detail = new HashSet(); for (int i = 0; i < jArr.length(); i++) { JSONObject detailData = jArr.getJSONObject(i); JSONObject jedjson = new JSONObject(); jedjson.put("srno", i + 1); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", detailData.optString("amount")); jedjson.put("accountid", detailData.optString("accountid")); jedjson.put("debit", detailData.optBoolean("debit")); jedjson.put("jeid", journalEntry.getID()); jedjson.put("description", detailData.optString("description")); KwlReturnObject jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); JournalEntryDetail jed = (JournalEntryDetail) jedresult.getEntityList().get(0); detail.add(jed); } journalEntry.setDetails(detail); accJournalEntryobj.saveJournalEntryDetailsSet(detail); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + sessionHandlerImpl.getUserFullName(request) + " has posted Journal Entry " + jeentryNumber + " "+auditmessage, request, journalEntry.getID()); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return journalEntry; } public JSONObject saveJournalEntryRemoteApplicationJson(JSONObject paramJobj)throws SessionExpiredException, ServiceException, JSONException, AccountingException { JSONObject jobj = new JSONObject(); JSONArray array=new JSONArray(); String msg = ""; boolean issuccess = false; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Quotation_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null;//txnManager.getTransaction(def); try { int counter = 0; JSONObject inputdata = new JSONObject(paramJobj.get("data").toString()); JSONArray jarr = inputdata.getJSONArray("jedata"); for (int i = 0; i < jarr.length(); i++) { JSONObject dataMap1 = jarr.getJSONObject(i); JSONArray tempArr = dataMap1.getJSONArray("details"); for (int j = 0; j < tempArr.length(); j++) { status = txnManager.getTransaction(def); JSONObject dataMap = tempArr.getJSONObject(j); JournalEntry je = saveJournalEntryRemoteApplicationJson(paramJobj, dataMap); JSONObject returnObj=new JSONObject(); returnObj.put("historyid", dataMap.optString("historyid")); returnObj.put("jeid", je.getID()); returnObj.put("entryno", je.getEntryNumber()); txnManager.commit(status); array.put(returnObj); } } issuccess = true; msg = messageSource.getMessage("acc.je1.save", null, Locale.forLanguageTag(paramJobj.getString("language"))); jobj.put("jarr", array); jobj.put("success", issuccess); jobj.put("msg", msg); } catch (JSONException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw new JSONException(ex); } catch (SessionExpiredException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE(ex.getMessage(), ex); } catch (ServiceException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (AccountingException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw new AccountingException(ex); } finally { try { jobj.put("success", issuccess); jobj.put("msg", msg); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public JournalEntry saveJournalEntryRemoteApplicationJson(JSONObject paramJobj, JSONObject dataMap) throws SessionExpiredException, ServiceException, AccountingException { JournalEntry journalEntry = null; try { String companyid = paramJobj.getString(Constants.companyKey); String currencyid = paramJobj.getString(Constants.currencyKey); Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJobj); double externalCurrencyRate = 1d; String jeentryNumber = null; boolean jeautogenflag = false; String jeSeqFormatId = ""; synchronized (this) { try { HashMap<String, Object> JEFormatParams = new HashMap<String, Object>(); JEFormatParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); JEFormatParams.put("modulename", "autojournalentry"); JEFormatParams.put(Constants.companyKey, companyid); JEFormatParams.put("isdefaultFormat", true); KwlReturnObject kwlObj = accCompanyPreferencesObj.getSequenceFormat(JEFormatParams); SequenceFormat format = (SequenceFormat) kwlObj.getEntityList().get(0); Map<String, Object> seqNumberMap = new HashMap<String, Object>(); seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, format.getID(), false, null); // Since JE date is always system date with timezone, hence sending null. It has been hadled in called method String nextAutoNoTemp = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number String jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part String jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part String jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part int sequence = Integer.parseInt((String)seqNumberMap.get(Constants.SEQNUMBER)); sequence = sequence; String number = "" + sequence; String action = "" + (sequence); nextAutoNoTemp.replaceAll(action, number); jeentryNumber = nextAutoNoTemp.replaceAll(action, number); //next auto generated number jeSeqFormatId = format.getID(); jeautogenflag = true; jeDataMap.put("entrynumber", jeentryNumber); jeDataMap.put("autogenerated", jeautogenflag); jeDataMap.put(Constants.SEQFORMAT, jeSeqFormatId); jeDataMap.put(Constants.SEQNUMBER, number); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); } catch (ServiceException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } String memo = dataMap.optString("memo", ""); String auditmessage = dataMap.optString("auditmessage", ""); // jeDataMap.put("entrydate", new Date()); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, currencyid); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", 1); journalEntry = accJournalEntryobj.getJournalEntry(jeDataMap); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date newdate=authHandler.getDateWithTimeFormat().parse(authHandler.getConstantDateFormatter().format(new Date())); Date newdate=new Date(); String userdiff=journalEntry.getCompany().getCreator().getTimeZone()!=null?journalEntry.getCompany().getCreator().getTimeZone().getDifference() : journalEntry.getCompany().getTimeZone().getDifference(); sdf.setTimeZone(TimeZone.getTimeZone("GMT"+userdiff)); Date newcreatedate=authHandler.getDateWithTimeFormat().parse(sdf.format(newdate)); journalEntry.setEntryDate(newcreatedate); accJournalEntryobj.saveJournalEntryByObject(journalEntry); JSONArray jArr = new JSONArray(dataMap.optString("details")); Set<JournalEntryDetail> detail = new HashSet(); for (int i = 0; i < jArr.length(); i++) { JSONObject detailData = jArr.getJSONObject(i); JSONObject jedjson = new JSONObject(); jedjson.put("srno", i + 1); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", detailData.optString("amount")); jedjson.put("accountid", detailData.optString("accountid")); jedjson.put("debit", detailData.optBoolean("debit")); jedjson.put("jeid", journalEntry.getID()); jedjson.put("description", detailData.optString("description")); KwlReturnObject jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); JournalEntryDetail jed = (JournalEntryDetail) jedresult.getEntityList().get(0); detail.add(jed); } journalEntry.setDetails(detail); accJournalEntryobj.saveJournalEntryDetailsSet(detail); Map<String, Object> auditTrailMap = new HashMap<String, Object>(); auditTrailMap.put(Constants.useridKey, paramJobj.getString("lid")); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJobj.optString(Constants.userfullname) + " has posted Journal Entry " + jeentryNumber + " "+auditmessage, auditTrailMap, journalEntry.getID()); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return journalEntry; } /** * * @param requestparams * @return * @Desc : Update JournalEntry which is created using recurring process */ public JSONObject updateJournalEntry(JSONObject requestparams) { JSONObject jSONObject = new JSONObject(); JournalEntry journalEntry = null; boolean issuccess = false; String msg = ""; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("SP_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null; status = txnManager.getTransaction(def); try { Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(requestparams); String memo = requestparams.optString("memo", ""); String billid = requestparams.optString("jeid", ""); String sequenceformat = requestparams.optString("sequenceformat", ""); DateFormat df = (DateFormat) requestparams.opt("df"); if (StringUtil.isNullOrEmpty(billid)) { throw new AccountingException("Journal Entry Cannot be Saved"); } else { /** * Delete all JE Details */ accJournalEntryobj.deleteOnEditAccountJEs_optimized(billid); } /** * Copy all data from Original JE */ KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), billid); JournalEntry oldjournalEntry = (JournalEntry) jeresult.getEntityList().get(0); if (oldjournalEntry != null) { if (oldjournalEntry.getSeqformat() != null) { jeDataMap.put(Constants.SEQFORMAT, oldjournalEntry.getSeqformat().getID()); } jeDataMap.put(Constants.SEQNUMBER, oldjournalEntry.getSeqnumber()); jeDataMap.put(Constants.DATEPREFIX, oldjournalEntry.getDatePreffixValue()); jeDataMap.put(Constants.DATEAFTERPREFIX, oldjournalEntry.getDateAfterPreffixValue()); jeDataMap.put(Constants.DATESUFFIX, oldjournalEntry.getDateSuffixValue()); if (!sequenceformat.equals("NA")) { jeDataMap.put("entrynumber", oldjournalEntry.getEntryNumber()); } jeDataMap.put("entrynumber", oldjournalEntry.getEntryNumber()); jeDataMap.put("autogenerated", oldjournalEntry.isAutoGenerated()); jeDataMap.put("entrydate", df.parse(requestparams.optString("entrydate"))); jeDataMap.put("jeisedit", true); jeDataMap.put(Constants.companyKey, oldjournalEntry.getCompany().getCompanyID()); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, oldjournalEntry.getCurrency().getCurrencyID()); jeDataMap.put("externalCurrencyRate", oldjournalEntry.getExternalCurrencyRate()); jeDataMap.put("typevalue", oldjournalEntry.getTypeValue()); jeDataMap.put("DontCheckYearLock", true); jeDataMap.put("createdby", oldjournalEntry.getCreatedby().getUserID().toString()); jeDataMap.put("reversejournalentry", oldjournalEntry.getReverseJournalEntry()); jeDataMap.put("isreverseje", oldjournalEntry.isIsReverseJE()); jeDataMap.put("pendingapproval", oldjournalEntry.getPendingapproval()); jeDataMap.put("isReval", oldjournalEntry.getIsReval()); jeDataMap.put("revalInvoiceId", oldjournalEntry.getRevalInvoiceId()); jeDataMap.put("istemplate", 0); jeDataMap.put("typevalue", oldjournalEntry.getTypeValue()); jeDataMap.put("partlyJeEntryWithCnDn", oldjournalEntry.getPartlyJeEntryWithCnDn()); jeDataMap.put("parentid", oldjournalEntry.getParentJE().getID()); if (oldjournalEntry.getParentJE().getAccBillInvCustomData() != null) { jeDataMap.put("accjecustomdataref", oldjournalEntry.getParentJE().getID()); } if (oldjournalEntry.getCostcenter() != null) { jeDataMap.put("costcenterid", oldjournalEntry.getCostcenter().getID()); } if (oldjournalEntry.getPaymentMethod() != null) { jeDataMap.put("pmtmethod", oldjournalEntry.getPaymentMethod().getID()); } } jeDataMap.put("memo", memo); jeDataMap.put("jeisedit", true); jeDataMap.put(JEID, billid); /** * Save Journal Entry */ jeresult = accJournalEntryobj.saveJournalEntry(jeDataMap); journalEntry = (JournalEntry) jeresult.getEntityList().get(0); JSONArray jArr = new JSONArray(requestparams.optString("detail")); /** * Save JE Details */ KwlReturnObject jedresult = accJournalEntryobj.getJEDset(jArr, journalEntry.getCompany().getCompanyID(), journalEntry); HashSet jeDetails = (HashSet) jedresult.getEntityList().get(0); journalEntry.setDetails(jeDetails); accJournalEntryobj.saveJournalEntryDetailsSet(jeDetails); /** * Save Audit Trial */ Map<String, Object> auditTrailMap = new HashMap<String, Object>(); auditTrailMap.put(Constants.useridKey, requestparams.getString("lid")); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + requestparams.optString(Constants.userfullname) + " has updated Journal Entry " + journalEntry.getEntryNumber() + " ", auditTrailMap, journalEntry.getID()); txnManager.commit(status); issuccess = true; msg = messageSource.getMessage("acc.je1.save", null, Locale.forLanguageTag(requestparams.getString("language"))); } catch (SessionExpiredException ex) { if (status != null) { txnManager.rollback(status); } msg = ex.getMessage(); issuccess = false; Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { issuccess = false; if (status != null) { txnManager.rollback(status); } msg = ex.getMessage(); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jSONObject.put("success", issuccess); jSONObject.put("msg", msg); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jSONObject; } @Override /*Call from Web Application*/ public JSONObject saveJournalEntry(JSONObject paramJObj) { JSONObject jobj = new JSONObject(); JSONObject chequeobj=new JSONObject(); String msg = "", jeid = "", JENumber = ""; boolean issuccess = false; int level=0; JSONObject jobjDetails = new JSONObject(); JSONArray jArr = new JSONArray(); int journalEntryType=0; String pendingForApproval=""; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("JE_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); Double jeAmount=0.0; String entryNumber = paramJObj.optString("entryno", null); KwlReturnObject resultForJe = null; String chequeDetail = ""; String repeatedid=""; String intervalType = ""; int intervalUnit = 0; int noOfJEPost = 0; int noOfJERemainPost = 0; Date startdate = null; Date nextdate = null; Date expdate = null; RepeatedJE rje = null; int typeValue = 1;// 1 - Normal JE Entry, 2 - Partly JE Entry, 3- Fund Transfer TransactionStatus status = txnManager.getTransaction(def); String controlAccounts = "Control Account(s): "; boolean isWarning = paramJObj.optString("isWarning", null) != null ? Boolean.parseBoolean(paramJObj.optString("isWarning")) : false; try { String companyid = paramJObj.optString(Constants.companyKey); boolean jeedit = paramJObj.optString("jeedit", null) != null ? Boolean.parseBoolean(paramJObj.optString("jeedit")) : false; chequeDetail = !StringUtil.isNullOrEmpty(paramJObj.optString("chequeDetail", null)) ? paramJObj.optString("chequeDetail") : ""; if (!StringUtil.isNullOrEmpty(paramJObj.optString("typevalue", null))) { typeValue = Integer.parseInt(paramJObj.optString("typevalue")); } /* * ERP-39212 . check cheque number is belongs to any sequence formate or not */ if (typeValue == Constants.FundTransfer_Journal_Entry && !StringUtil.isNullOrEmpty(chequeDetail)) { JSONObject chequeDetailJObj = new JSONObject(chequeDetail); String chequeNumber = chequeDetailJObj.getString("chequeno"); String sequenceFormat = chequeDetailJObj.optString(Constants.sequenceformat); JSONObject chequeParamJObj = new JSONObject(); chequeParamJObj.put(Constants.companyKey, companyid); chequeParamJObj.put("chequeNumber", chequeNumber); chequeParamJObj.put(Constants.sequenceformat, sequenceFormat); List resultList = accCompanyPreferencesObj.checksChequeNumberForSequenceNumber(chequeNumber, companyid); if (!resultList.isEmpty()) { JSONObject resultJObj = new JSONObject(((resultList.get(2) != null) && (!StringUtil.isNullOrEmpty(resultList.get(2).toString()))) ? resultList.get(2).toString() : "{}" ); if (resultJObj.length() > 0) { String seqformatName = resultJObj.optString("formatName"); boolean isSeqnum = resultJObj.optBoolean("isSeqnum"); String seqformatId = resultJObj.optString("formatid"); if (sequenceFormat.equalsIgnoreCase("NA")) { //selected sequence formate is NA and cheque number is belongs to any sequence format. if (isSeqnum) { throw new AccountingException(messageSource.getMessage("acc.common.enterchequenumber", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + chequeNumber + "</b> " + messageSource.getMessage("acc.common.belongsto", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + ". " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + seqformatName + "</b> " + messageSource.getMessage("acc.common.insteadofcheque", null, Locale.forLanguageTag(paramJObj.getString(Constants.language)))); } } else { if (isSeqnum) { //cheque number is belong to other than selected sequence format if(!(sequenceFormat.equals(seqformatId))){ throw new AccountingException(messageSource.getMessage("acc.common.enterchequenumber", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + chequeNumber + "</b> " + messageSource.getMessage("acc.common.notbelongstoselectedsequenceformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + ". " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>"+seqformatName+"</b> " + messageSource.getMessage("acc.common.insteadofcheque", null, Locale.forLanguageTag(paramJObj.getString(Constants.language)))); } } else { //cheque number is not belong to any of the sequence format throw new AccountingException(messageSource.getMessage("acc.common.enterchequenumber", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + chequeNumber + "</b> " + messageSource.getMessage("acc.common.notBelongstoAnyOfTheAutoSequenceFormat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + ". " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>NA</b> " + messageSource.getMessage("acc.common.insteadofcheque", null, Locale.forLanguageTag(paramJObj.getString(Constants.language)))); } } } } } /** * createAsTransactionChkboxwithTemplate- used to create template along with transaction. */ boolean createAsTransactionChkboxwithTemplate = paramJObj.optString("createAsTransactionChkbox").equalsIgnoreCase("on") ? true : false; if (!paramJObj.has(Constants.sequenceformat) || StringUtil.isNullOrEmpty(paramJObj.optString(Constants.sequenceformat, null))) { String sequenceformatid = null; SequenceFormat jeSeqFormat = null; Map<String, Object> sfrequestParams = new HashMap<String, Object>(); sfrequestParams.put(Constants.companyKey, paramJObj.get(Constants.companyKey)); sfrequestParams.put("modulename", "autojournalentry"); KwlReturnObject seqFormatResult = accCompanyPreferencesObj.getSequenceFormat(sfrequestParams); List<SequenceFormat> ll = seqFormatResult.getEntityList(); if (ll.isEmpty()) { HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("modulename", "autojournalentry"); requestParams.put("numberofdigit", 6); requestParams.put("showleadingzero", true); requestParams.put("prefix", Constants.JE_DEFAULT_PREFIX); requestParams.put("sufix", ""); requestParams.put("startfrom", 0); requestParams.put("name", Constants.JE_DEFAULT_FORMAT); requestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); requestParams.put(Constants.companyKey, paramJObj.get(Constants.companyKey)); jeSeqFormat = accCompanyPreferencesObj.saveSequenceFormat(requestParams); paramJObj.put(Constants.sequenceformat, jeSeqFormat.getID()); } else if (ll.get(0) != null) { SequenceFormat format = (SequenceFormat) ll.get(0); sequenceformatid = format.getID(); paramJObj.put(Constants.sequenceformat, sequenceformatid); } }//end of sequenceformat if (StringUtil.isNullOrEmpty(paramJObj.optString(Constants.sequenceformat, null))) { JSONObject response = StringUtil.getErrorResponse("acc.common.erp33", paramJObj, "Sequence Format Details are missing.", messageSource); throw ServiceException.FAILURE(response.optString(Constants.RES_MESSAGE), "", false); } // List li = saveJournalEntry(paramJObj); /** * creating template for Journal Entry. * istemplate=2 //creating only template * istemplate=0 //creating only transaction */ if (createAsTransactionChkboxwithTemplate) { paramJObj.put("istemplate", 2); saveJournalEntryList(paramJObj); paramJObj.remove("istemplate"); } /** *creating Journal Entry. */ List li = saveJournalEntryList(paramJObj); if (li.get(2) != null) { JENumber = (String) li.get(2); } issuccess = true; KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), (String)li.get(0)); JournalEntry JE = (JournalEntry) jeresult.getEntityList().get(0); String jeId=JE.getID(); Set<JournalEntryDetail> jeDetails = JE.getDetails(); for (JournalEntryDetail journalEntryDetail : jeDetails) { if(journalEntryDetail.isDebit()) // As Debit and credit amount for JE are same , any one type can be picked for calculating amount jeAmount = jeAmount+journalEntryDetail.getAmount(); if( journalEntryDetail.getAccount() != null && !StringUtil.isNullOrEmpty(journalEntryDetail.getAccount().getUsedIn()) ){ controlAccounts += journalEntryDetail.getAccount().getAccountName() + (!StringUtil.isNullOrEmpty(journalEntryDetail.getAccount().getAcccode()) ? " ("+journalEntryDetail.getAccount().getAcccode()+")":"")+","; } } boolean printCheque = StringUtil.isNullOrEmpty(paramJObj.optString("printCheque", null)) ? false : Boolean.parseBoolean(paramJObj.optString("printCheque")); if (printCheque) { KwlReturnObject result = accountingHandlerDAOobj.getObject(PaymentMethod.class.getName(), paramJObj.optString("pmtmethod")); PaymentMethod payMethod = (PaymentMethod) result.getEntityList().get(0); HashMap<String, Object> requestParams = new HashMap<String, Object>(); if (!StringUtil.isNullOrEmpty(payMethod.getID())) { requestParams.put("bankid", payMethod.getID()); } boolean isnewlayout = false; ChequeLayout chequeLayout=null; DateFormat DATE_FORMAT = new SimpleDateFormat(Constants.DEFAULT_FORMAT_CHECK); String prefixbeforamt = ""; KwlReturnObject result1 = accPaymentDAOobj.getChequeLayout(requestParams); List list = result1.getEntityList(); Iterator itr = list.iterator(); while (itr.hasNext()) { chequeLayout = (ChequeLayout) itr.next(); chequeobj = new JSONObject(chequeLayout.getCoordinateinfo()); jobjDetails.put("dateLeft", chequeobj.optString("dateLeft","0")); jobjDetails.put("nameLeft", chequeobj.optString("nameLeft","0")); jobjDetails.put("amtinwordLeft", chequeobj.optString("amtinwordLeft","0")); jobjDetails.put("amtinwordLeftLine2", chequeobj.optString("amtinwordLeftLine2","0")); jobjDetails.put("amtLeft", chequeobj.optString("amtLeft","0")); jobjDetails.put("dateTop", chequeobj.optString("dateTop","0")); jobjDetails.put("nameTop", chequeobj.optString("nameTop","0")); jobjDetails.put("amtinwordTop", chequeobj.optString("amtinwordTop","0")); jobjDetails.put("amtinwordTopLine2", chequeobj.optString("amtinwordTopLine2","0")); jobjDetails.put("amtTop", chequeobj.optString("amtTop","0")); String dateformat = chequeLayout.getDateFormat().getJavaForm(); /* If 'AddCharacterInCheckDate' is true then don't remove '/' or '-' from check Date */ if (!chequeLayout.isAddCharacterInCheckDate()) { dateformat = dateformat.replaceAll("/", ""); dateformat = dateformat.replaceAll("-", ""); } DATE_FORMAT = new SimpleDateFormat(dateformat); prefixbeforamt = chequeLayout.getAppendcharacter(); isnewlayout = chequeLayout.isIsnewlayout(); } String formatted_date_with_spaces = ""; chequeDetail = paramJObj.optString("chequeDetail", null); if (!StringUtil.isNullOrEmpty(chequeDetail)) { JSONObject obj = new JSONObject(chequeDetail); Date cdate = new Date(obj.getString("payDate")); String chackdate = DATE_FORMAT.format(cdate); if (chequeLayout!=null && chequeLayout.isAddCharacterInCheckDate()) { formatted_date_with_spaces=chackdate; } else { for (int i = 0; i < chackdate.length(); i++) { formatted_date_with_spaces += chackdate.charAt(i); formatted_date_with_spaces += isnewlayout ? "&nbsp;&nbsp;&nbsp;" : "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; } } } String[] amount = (String[]) li.get(3); String[] amount1 = (String[]) li.get(4); String[] accName = (String[]) li.get(5); jobjDetails.put(amount[0], prefixbeforamt+amount[1]); String amount_first_line = ""; String amount_second_line = ""; String action=" Only."; if (amount1[1].length() > 34 && amount1[1].charAt(34) == ' ') { amount_first_line = amount1[1].substring(0, 34); amount_second_line = amount1[1].substring(34, amount1[1].length()); jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line +action); } else if (amount1[1].length() > 34) { amount_first_line = amount1[1].substring(0, 34); amount_first_line = amount1[1].substring(0, amount_first_line.lastIndexOf(" ")); amount_second_line = amount1[1].substring(amount_first_line.length(), amount1[1].length()); jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line + action); } else { if (amount1[1].length() < 27) { jobjDetails.put(amount1[0], amount1[1] + action); jobjDetails.put("amountinword1", ""); } else { jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", action); } } jobjDetails.put(accName[0], accName[1]); jobjDetails.put("date", formatted_date_with_spaces); jobjDetails.put("isnewlayout", isnewlayout); boolean isFontStylePresent = chequeobj.has("fontStyle") && !StringUtil.isNullOrEmpty(chequeobj.getString("fontStyle")) ? true : false; String fontStyle = chequeobj.has("fontStyle") && !StringUtil.isNullOrEmpty(chequeobj.getString("fontStyle")) ? chequeobj.getString("fontStyle") : ""; char fontStyleChar; if (fontStyle.equals("1")) { fontStyleChar = 'b'; } else if (fontStyle.equals("2")) { fontStyleChar = 'i'; } else { fontStyleChar = 'p'; } //for name if (chequeobj.has("dateFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("dateFontSize"))) { formatted_date_with_spaces = "<font size=" + chequeobj.getString("dateFontSize") + "><" + fontStyleChar + ">" + formatted_date_with_spaces + "</" + fontStyleChar + "></font> "; jobjDetails.put("date", formatted_date_with_spaces); } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("dateFontSize"))) { formatted_date_with_spaces = "<font size=" + chequeobj.getString("dateFontSize") + ">" + formatted_date_with_spaces + "</font> "; jobjDetails.put("date", formatted_date_with_spaces); } else { formatted_date_with_spaces = "<" + fontStyleChar + ">" + formatted_date_with_spaces + "</" + fontStyleChar + ">"; jobjDetails.put("date", formatted_date_with_spaces); } } //for name if (chequeobj.has("nameFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("nameFontSize"))) { accName[1] = "<font size=" + chequeobj.getString("nameFontSize") + "><" + fontStyleChar + ">" + accName[1] + "</" + fontStyleChar + "></font> "; jobjDetails.put(accName[0], accName[1]); } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("nameFontSize"))) { accName[1] = "<font size=" + chequeobj.getString("nameFontSize") + ">" + accName[1] + "</font> "; jobjDetails.put(accName[0], accName[1]); } else { accName[1] = "<" + fontStyleChar + ">" + accName[1] + "</" + fontStyleChar + ">"; jobjDetails.put(accName[0], accName[1]); } } //for amount in words if (chequeobj.has("amountInWordsFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("amountInWordsFontSize"))) { amount_first_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + "><" + fontStyleChar + ">" + amount_first_line + "</" + fontStyleChar + "></font> "; amount_second_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + "><" + fontStyleChar + ">" + amount_second_line +" "+action+ "</" + fontStyleChar + "></font> "; if (amount1[1].length() > 34) { jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line); } else if (amount1[1].length() < 27) { amount1[1] = "<font size=" + chequeobj.getString("amountInWordsFontSize") + "><" + fontStyleChar + ">" + amount1[1] +" "+action+ "</" + fontStyleChar + "></font> "; jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", ""); } } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("amountInWordsFontSize"))) { amount_first_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + ">" + amount_first_line + "</font> "; amount_second_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + ">" + amount_second_line +" "+action+ "</font> "; if (amount1[1].length() > 34) { jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line); } else if (amount1[1].length() < 27) { amount1[1] = "<font size=" + chequeobj.getString("amountInWordsFontSize") + ">" + amount1[1] +" "+action+ "</font> "; jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", ""); } } else { amount_first_line = "<" + fontStyleChar + ">" + amount_first_line + "</" + fontStyleChar + ">"; amount_second_line = "<" + fontStyleChar + ">" + amount_second_line +" "+action+ "</" + fontStyleChar + ">"; if (amount1[1].length() > 34) { jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line); } else if (amount1[1].length() < 27) { amount1[1] = "<" + fontStyleChar + ">" + amount1[1] +" "+action+ "</" + fontStyleChar + ">"; jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", ""); } } } //for amount in number if (chequeobj.has("amountFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("amountFontSize"))) { amount[1] = "<font size=" + chequeobj.getString("amountFontSize") + "><" + fontStyleChar + ">" + prefixbeforamt+amount[1] + "</" + fontStyleChar + "></font> "; jobjDetails.put(amount[0], amount[1]); } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("amountFontSize"))) { amount[1] = "<font size=" + chequeobj.getString("amountFontSize") + ">" + prefixbeforamt+amount[1] + "</font> "; jobjDetails.put(amount[0], amount[1]); } else { amount[1] = "<" + fontStyleChar + ">" + prefixbeforamt+amount[1] + "</" + fontStyleChar + ">"; jobjDetails.put(amount[0], amount[1]); } } jArr.put(jobjDetails); jeid=JE.getID(); String chequeno=""; if (li.get(6) != null) { chequeno = (String) li.get(6); } KwlReturnObject result2 = accJournalEntryobj.updateChequePrint(jeid,companyid); Map<String, Object> insertLogParams = new HashMap<String, Object>(); insertLogParams.put(Constants.reqHeader, (paramJObj.has(Constants.reqHeader) && paramJObj.get(Constants.reqHeader) != null) ? paramJObj.getString(Constants.reqHeader) : paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.remoteIPAddress, paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.useridKey, paramJObj.optString(Constants.useridKey)); // auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has printed a cheque "+chequeno+" for "+StringUtil.serverHTMLStripper(accName[1]) +" in Fund Transfer " + JENumber, request, jeid); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has printed a cheque " + chequeno + " for " + StringUtil.serverHTMLStripper(accName[1]) + " in Fund Transfer " + JENumber, insertLogParams, jeid); } if (!StringUtil.isNullOrEmpty(chequeDetail) && li.get(7) != null) { rje = (RepeatedJE) li.get(7); if (rje != null) { repeatedid = rje.getId(); intervalUnit = rje.getIntervalUnit(); intervalType = rje.getIntervalType(); noOfJEPost = rje.getNoOfJEpost(); noOfJERemainPost = rje.getNoOfRemainJEpost(); startdate = rje.getStartDate(); nextdate = rje.getNextDate(); expdate = rje.getExpireDate(); } } else if(StringUtil.isNullOrEmpty(chequeDetail) && li.get(3) != null) { rje = (RepeatedJE) li.get(3); if (rje != null) { repeatedid = rje.getId(); intervalUnit = rje.getIntervalUnit(); intervalType = rje.getIntervalType(); noOfJEPost = rje.getNoOfJEpost(); noOfJERemainPost = rje.getNoOfRemainJEpost(); startdate = rje.getStartDate(); nextdate = rje.getNextDate(); expdate = rje.getExpireDate(); } } txnManager.commit(status); String sequenceformat = paramJObj.optString("sequenceformat", "NA"); TransactionStatus AutoNoStatus = null; try { synchronized (this) { DefaultTransactionDefinition def1 = new DefaultTransactionDefinition(); def1.setName("AutoNum_Tx"); if (paramJObj.optBoolean(Constants.isdefaultHeaderMap)) {//same transaction is used to commit def1.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); } else { def1.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); } AutoNoStatus = txnManager.getTransaction(def1); if (sequenceformat.equals("NA") && !jeedit) { resultForJe = accJournalEntryobj.getJECount(entryNumber, companyid); while (resultForJe.getRecordTotalCount() > 0) { entryNumber = entryNumber + "-1"; resultForJe = accJournalEntryobj.getJECount(entryNumber, companyid); } JENumber = accJournalEntryobj.updateJEEntryNumberForNA(jeId, entryNumber); JE.setEntryNumber(entryNumber); } if (!jeedit && (!StringUtil.isNullOrEmpty(sequenceformat) && !sequenceformat.equals("NA"))) { //Post New JE with auto generated Entry No. // status = txnManager.getTransaction(def); Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJObj); // entryNumber = updateJEEntryNumberForNewJE(jeDataMap, JE, companyid, sequenceformat,JE.getPendingapproval()); KwlReturnObject returnObj = updateJEEntryNumberForNewJE(jeDataMap, JE, companyid, sequenceformat,JE.getPendingapproval()); if(returnObj.isSuccessFlag() && returnObj.getRecordTotalCount()>0){ entryNumber = (String) returnObj.getEntityList().get(0); } JENumber = entryNumber; } } } catch (Exception ex) { if (AutoNoStatus != null) { txnManager.rollback(AutoNoStatus); } Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } finally { if (AutoNoStatus != null) { txnManager.commit(AutoNoStatus); } } int approvalStatusLevel =11; journalEntryType = JE.getTypeValue(); String msgKey = ""; String currentUserId = paramJObj.optString(Constants.useridKey); // if (journalEntryType != 2) { // Currently , Party Journal Entry is excluded from the approval rules. approvalStatusLevel = approveJE(JE, paramJObj.optString(Constants.companyKey), level, String.valueOf(jeAmount), paramJObj, true, currentUserId); if (approvalStatusLevel != 11) { pendingForApproval = messageSource.getMessage("acc.field.butpendingforApproval", null, Locale.forLanguageTag(paramJObj.optString("language"))); msgKey = "acc.je2.save"; }else{ msgKey = "acc.je1.save"; } // } int istemplate = 0; if (!StringUtil.isNullOrEmpty(paramJObj.optString("istemplate", null))) { istemplate = Integer.parseInt(paramJObj.optString("istemplate")); } if (istemplate == 1) { msg = messageSource.getMessage("acc.field.JournalEntryandTemplatehasbeensavedsuccessfully", null, Locale.forLanguageTag(paramJObj.optString("language"))) + " " + pendingForApproval + "<br/>JE No: <b>" + JENumber + "</b>"; //"Journal Entry and Template has been saved successfully."; } else if (istemplate == 2) { msg = messageSource.getMessage("acc.field.JournalEntryTemplatehasbeensavedsuccessfully", null, Locale.forLanguageTag(paramJObj.optString("language"))); //"Journal Entry Template has been saved successfully."; } else { msg = messageSource.getMessage(msgKey, null, Locale.forLanguageTag(paramJObj.getString("language"))) + " " + pendingForApproval + "<br/>JE No: <b>" + JENumber + "</b>"; //"Journal Entry has been saved successfully"; if (!StringUtil.isNullOrEmpty(paramJObj.optString("createAsTransactionChkbox", "")) && paramJObj.optString("createAsTransactionChkbox").equalsIgnoreCase("on") && !StringUtil.isNullOrEmpty(paramJObj.optString("templatename", ""))) { msg += " Template Name: <b>" + paramJObj.optString("templatename", "") + "</b>"; } } String template = " template for record "; if (istemplate == 0) { template = ""; } String action = "added new"; if (jeedit == true) { action = "updated"; } Map<String, Object> insertLogParams = new HashMap<String, Object>(); insertLogParams.put(Constants.reqHeader, (paramJObj.has(Constants.reqHeader) && paramJObj.get(Constants.reqHeader) != null) ? paramJObj.getString(Constants.reqHeader) : paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.remoteIPAddress, paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.useridKey, paramJObj.optString(Constants.useridKey)); // auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has " + action + template + " Journal Entry " + JE.getEntryNumber()+(approvalStatusLevel != 11 ? " "+messageSource.getMessage("acc.field.whichispendingforApproval", null, null) : "") + (!controlAccounts.equals("Control Account(s): ") ? ". "+controlAccounts.substring(0, controlAccounts.length()-1) :""), request, JE.getID()); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has " + action + template + " Journal Entry " + JE.getEntryNumber() + (approvalStatusLevel != 11 ? " " + messageSource.getMessage("acc.field.whichispendingforApproval", null, null) : "") + (!controlAccounts.equals("Control Account(s): ") ? ". " + controlAccounts.substring(0, controlAccounts.length() - 1) : ""), insertLogParams, JE.getID()); if (!StringUtil.isNullOrEmpty(paramJObj.optString("createAsTransactionChkbox", "")) && paramJObj.optString("createAsTransactionChkbox").equalsIgnoreCase("on") && !StringUtil.isNullOrEmpty(paramJObj.optString("templatename", ""))) { auditTrailObj.insertAuditLog(AuditAction.TEMPLATE_CREATED, "User " + paramJObj.optString(Constants.userfullname) + " has " + action + " Document Template "+paramJObj.optString("templatename", "")+ " for record Journal Entry" , insertLogParams, JE.getID()); } jeid = li.get(0) != null ? (String) li.get(0) : ""; if (jeedit) { String oldjeid = (String) li.get(1); status = txnManager.getTransaction(def); deleteJEArray(oldjeid,journalEntryType,companyid); txnManager.commit(status); } } catch (SessionExpiredException ex) { txnManager.rollback(status); msg = ex.getMessage(); Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { txnManager.rollback(status); msg = "" + ex.getMessage(); Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jobj.put("success", issuccess); jobj.put("repeatedid", repeatedid); jobj.put("intervalUnit", intervalUnit); jobj.put("intervalType", intervalType); jobj.put("noOfJEPost", noOfJEPost); jobj.put("noOfJERemainPost", noOfJERemainPost); jobj.put("typeValue", typeValue); jobj.put("billno", JENumber); jobj.put("startdate", startdate); jobj.put("nextdate", nextdate); jobj.put("expdate", expdate); jobj.put("msg", msg); jobj.put("id", jeid); jobj.put("data", jArr); jobj.put("isWarning",isWarning); } catch (JSONException ex) { Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public List saveJournalEntryList(JSONObject paramJobj) throws SessionExpiredException, ServiceException, AccountingException { JournalEntry je = null; List ll = new ArrayList(); try { int istemplate = paramJobj.optString("istemplate", null) != null ? Integer.parseInt(paramJobj.optString("istemplate")) : 0; String companyid = paramJobj.optString(Constants.companyKey); String createdby = paramJobj.optString(Constants.useridKey); String entryNumber = paramJobj.optString("entryno", null); String jeid = ""; RepeatedJE rje = null; String oldjeid = ""; int typeValue = 1;// 1 - Normal JE Entry, 2 - Partly JE Entry, 3- Fund Transfer boolean jeedit = false; boolean isdeletecndnwithJE=false; String chequeno=""; String sequenceformat = paramJobj.optString("sequenceformat", "NA"); String jeId = paramJobj.optString("jeid", null); boolean isWarning = paramJobj.optString("isWarning", null) != null ? Boolean.parseBoolean(paramJobj.optString("isWarning")) : false; boolean includeInGSTReport = paramJobj.optString("includeingstreport", null) != null ? Boolean.parseBoolean(paramJobj.optString("includeingstreport")) : false; if (istemplate != 2 && sequenceformat.equals("NA")) { if(StringUtil.isNullOrEmpty(entryNumber)) // entryNumber is set to be blank in case of istemplate=2 (in template creation case) throw new AccountingException(messageSource.getMessage("acc.je1.excp2", null, Locale.forLanguageTag(paramJobj.optString("language")))); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("jeedit", null))) { jeedit = Boolean.parseBoolean(paramJobj.optString("jeedit")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("isdeletecndnwithJE", null))) { isdeletecndnwithJE = Boolean.parseBoolean(paramJobj.optString("isdeletecndnwithJE")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("typevalue", null))) { typeValue = Integer.parseInt(paramJobj.optString("typevalue")); } if (istemplate != 2 && sequenceformat.equals("NA") && jeedit) { // KwlReturnObject result = accJournalEntryobj.getJECountForEdit(entryNumber, companyid,jeId); int nocount = result.getRecordTotalCount(); if (nocount > 0) { throw new AccountingException("Journal entry number '" + entryNumber + "' already exists."); } } if (istemplate != 2 && sequenceformat.equals("NA")) {//In case of NA checks wheather this number can also be generated by a sequence format or not List list = accCompanyPreferencesObj.checksEntryNumberForSequenceNumber(Constants.Acc_GENERAL_LEDGER_ModuleId, entryNumber, companyid); if (!list.isEmpty()) { boolean isvalidEntryNumber = (Boolean) list.get(0); String formatName = (String) list.get(1); if (!isvalidEntryNumber) { throw new AccountingException(messageSource.getMessage("acc.common.enterdocumentnumber", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + entryNumber + "</b> " + messageSource.getMessage("acc.common.belongsto", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + formatName + "</b>. " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + formatName + "</b> " + messageSource.getMessage("acc.common.insteadof", null, Locale.forLanguageTag(paramJobj.optString("language")))); } } } int countryLanguageId = Constants.OtherCountryLanguageId; // 0 KwlReturnObject extraprefresult = accountingHandlerDAOobj.getObject(ExtraCompanyPreferences.class.getName(), companyid); ExtraCompanyPreferences extraCompanyPreferences = extraprefresult != null ? (ExtraCompanyPreferences) extraprefresult.getEntityList().get(0) : null; if (extraCompanyPreferences.isAmountInIndianWord()) { countryLanguageId = Constants.CountryIndiaLanguageId; //for india id is 1; } double externalCurrencyRate = StringUtil.getDouble(paramJobj.optString("externalcurrencyrate", "1")); DateFormat df = authHandler.getDateOnlyFormat(); Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJobj); // Check Cheque Detail is available or Not BigInteger oldChqNoIntValue = new BigInteger("0"); BigInteger chequesequencenumber = new BigInteger("0"); String chequeDetail = paramJobj.optString("chequeDetail", null); if (!StringUtil.isNullOrEmpty(chequeDetail)) { JSONObject obj = new JSONObject(chequeDetail); HashMap chequehm = new HashMap(); // cheque whether Cheque Number exist or not if already exist then don't let it save String oldChqNo = ""; if (jeedit) { String oldje = paramJobj.optString("jeid", null); KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), oldje); JournalEntry oldjournalEntry = (JournalEntry) jeresult.getEntityList().get(0); if (oldjournalEntry != null && oldjournalEntry.getCheque() != null) { oldChqNo = oldjournalEntry.getCheque().getChequeNo(); oldChqNoIntValue = oldjournalEntry.getCheque().getSequenceNumber(); } } KwlReturnObject companypref = accountingHandlerDAOobj.getObject(CompanyAccountPreferences.class.getName(), companyid); CompanyAccountPreferences compPref = (CompanyAccountPreferences)companypref.getEntityList().get(0); int chequeNoDuplicationSetting = compPref.getChequeNoDuplicate(); BigInteger nextSeqNumber = new BigInteger("0"); boolean checkForNextSequenceNumberAlso = true; boolean isChequeNumberInString = false; if (extraCompanyPreferences != null) { try {// USER can enter String values also in such case exception will come nextSeqNumber = new BigInteger(obj.getString("chequeno")); } catch (Exception ex) { checkForNextSequenceNumberAlso = false; isChequeNumberInString = true; } } else { checkForNextSequenceNumberAlso = false; } boolean isChequeNumberAvailable = false; boolean isEditCaseButChqNoChanged = false; if (!StringUtil.isNullOrEmpty(obj.optString("chequeno"))) { try {// OLD CHQ NO. can be String value also in such case exception will come HashMap chequeNohm = new HashMap(); chequeNohm.put("companyId", companyid); chequeNohm.put("nextChequeNumber", obj.optString("chequeno")); chequeNohm.put("sequenceNumber", nextSeqNumber); chequeNohm.put("checkForNextSequenceNumberAlso", checkForNextSequenceNumberAlso); chequeNohm.put("bankAccountId", obj.getString("bankAccountId")); JSONObject ChJobj = accCompanyPreferencesObj.isChequeNumberAvailable(chequeNohm); isChequeNumberAvailable = ChJobj.optBoolean("isChequeNumberAvailable"); chequesequencenumber =new BigInteger(ChJobj.optString("chequesequencenumber")); // if (!StringUtil.isNullOrEmpty(oldChqNo)) { // oldChqNoIntValue = new BigInteger(oldChqNo); // } if (!oldChqNoIntValue.equals(chequesequencenumber)) { isEditCaseButChqNoChanged = true; } if (isChequeNumberInString) { if (!oldChqNo.equals(obj.optString("chequeno"))) { isEditCaseButChqNoChanged = true; } } } catch (Exception ex) { if (!oldChqNo.equals(obj.optString("chequeno"))) { isEditCaseButChqNoChanged = true; } } } else { if (!oldChqNo.equals(obj.optString("chequeno"))) { isEditCaseButChqNoChanged = true; } } if (chequeNoDuplicationSetting == Constants.ChequeNoBlock || (chequeNoDuplicationSetting == Constants.ChequeNoWarn && isWarning)) { if (!StringUtil.isNullOrEmpty(obj.optString("chequeno")) && isChequeNumberAvailable && isEditCaseButChqNoChanged) { String msgForException = "Cheque Number : <b>" + obj.getString("chequeno") + "</b> is already exist. "; if (isWarning) { throw new AccountingException(msgForException+" "+messageSource.getMessage("acc.recurringMP.doYouWantToContinue", null, Locale.forLanguageTag(paramJobj.optString("language")))); } else { throw new AccountingException(msgForException + "Please enter different one. "); } } String chequeNumber = obj.optString("chequeno"); chequeNumber = "'" + chequeNumber + "'"; HashMap<String, Object> requestMap = new HashMap(); requestMap.put("bankAccountId", obj.getString("bankAccountId")); requestMap.put("chequeNumber", chequeNumber); KwlReturnObject resultRepeatedPaymentChequeDetails = accPaymentDAOobj.getRepeatedPaymentChequeDetailsForPaymentMethod(requestMap); List RPCD = resultRepeatedPaymentChequeDetails.getEntityList(); if (RPCD.size() > 0) { Object[] object = (Object[]) RPCD.get(0); String paymentNumber = (String) object[1]; String msgForException = messageSource.getMessage("acc.field.ChequeNumber", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " : <b>" + obj.getString("chequeno") + "</b> " + messageSource.getMessage("acc.recurringMP.chequeNoReserverd", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + paymentNumber + "</b>. "; if (isWarning) { throw new AccountingException(msgForException + " " + messageSource.getMessage("acc.recurringMP.doYouWantToContinue", null, Locale.forLanguageTag(paramJobj.optString("language")))); } else { throw new AccountingException(msgForException + messageSource.getMessage("acc.recurringMP.enteranotherChequeNo", null, Locale.forLanguageTag(paramJobj.optString("language")))); } } } String chequeseqformatID = obj.optString("sequenceformat",""); chequehm.put(Constants.SEQFORMAT, chequeseqformatID); if (!chequeseqformatID.equalsIgnoreCase("NA") && !chequeseqformatID.equalsIgnoreCase("")){ chequehm.put("isAutoGeneratedChequeNumber", true); } Map<String, Object> seqchequehm = new HashMap<>(); obj.put(Constants.companyKey, companyid); /** * getNextChequeNumber method to generate next sequence number using * sequence format,also saving the dateprefix and datesuffix in cheque table. */ obj.put(Constants.companyKey, companyid); obj.put("ischequeduplicatepref", compPref.getChequeNoDuplicate()); if (!StringUtil.isNullOrEmpty(sequenceformat) && !sequenceformat.equals("NA")) { //Edit case- check pevious check number and new entered number are same then no need to generate next number else generate next number. if(isEditCaseButChqNoChanged){//create and copy case- generate next number. seqchequehm = accCompanyPreferencesObj.getNextChequeNumber(obj); } } chequehm.put("companyId", companyid); chequehm.put("bankAccount", obj.getString("bankAccountId")); chequehm.put("createdFrom", 3); chequehm.put("sequenceNumber", chequesequencenumber); chequehm.put("chequeno", obj.optString("chequeno")); chequehm.put("description", StringUtil.DecodeText(obj.optString("description"))); chequehm.put("bankname", StringUtil.DecodeText(obj.optString("bankname"))); chequehm.put("duedate", df.parse(obj.getString("payDate"))); if (seqchequehm!=null&&!StringUtil.isNullOrEmpty(sequenceformat) && !sequenceformat.equals("NA") && seqchequehm.containsKey(Constants.SEQNUMBER)) { chequehm.put("sequenceNumber", (String) seqchequehm.get(Constants.SEQNUMBER)); } KwlReturnObject cqresult = accPaymentDAOobj.addCheque(chequehm); Cheque cheque = (Cheque) cqresult.getEntityList().get(0); if (cheque != null) { jeDataMap.put(CCConstants.JSON_cheque, cheque.getID()); chequeno=cheque.getChequeNo(); } } String costCenterId = paramJobj.optString(CCConstants.REQ_costcenter, null); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("createdby", createdby); jeDataMap.put("entrydate", df.parse(paramJobj.optString("entrydate"))); jeDataMap.put("memo", paramJobj.optString("memo")); if(jeedit){ jeDataMap.put("entrynumber", entryNumber); } else { jeDataMap.put("entrynumber", ""); } jeDataMap.put("autogenerated", sequenceformat.equals("NA") ? false : true); //nextJEAutoNo.equals(entryNumber)); jeDataMap.put(Constants.currencyKey,paramJobj.optString(Constants.currencyKey)); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", typeValue); jeDataMap.put("istemplate", istemplate); if (!StringUtil.isNullOrEmpty(paramJobj.optString("parentje", null))) { jeDataMap.put("parentid", paramJobj.optString("parentje")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("repeateid", null))) { jeDataMap.put("repeateid", paramJobj.optString("repeateid")); } if (jeedit) { oldjeid = paramJobj.optString("jeid", null); KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), oldjeid); JournalEntry oldjournalEntry = (JournalEntry) jeresult.getEntityList().get(0); if (oldjournalEntry != null) { if (oldjournalEntry.getSeqformat() != null) { jeDataMap.put(Constants.SEQFORMAT, oldjournalEntry.getSeqformat().getID()); } jeDataMap.put(Constants.SEQNUMBER, oldjournalEntry.getSeqnumber()); jeDataMap.put(Constants.DATEPREFIX, oldjournalEntry.getDatePreffixValue()); jeDataMap.put(Constants.DATEAFTERPREFIX, oldjournalEntry.getDateAfterPreffixValue()); jeDataMap.put(Constants.DATESUFFIX, oldjournalEntry.getDateSuffixValue()); if (!sequenceformat.equals("NA")) { jeDataMap.put("entrynumber", oldjournalEntry.getEntryNumber()); } jeDataMap.put("autogenerated", oldjournalEntry.isAutoGenerated()); /* Saving previous status of flag isfromeclaim At the time of edit JE */ boolean isFromEclaim = oldjournalEntry.isIsFromEclaim(); jeDataMap.put("isFromEclaim", isFromEclaim); } try { if (isdeletecndnwithJE) { KwlReturnObject cnresult= accJournalEntryobj.getCNFromJE(oldjeid, companyid); List list=cnresult.getEntityList(); if(!list.isEmpty()){ accJournalEntryobj.deletePartyJournalCN(list, companyid); } cnresult = accJournalEntryobj.getDNFromJE(oldjeid, companyid); list=cnresult.getEntityList(); if(!list.isEmpty()){ accJournalEntryobj.deletePartyJournalDN(list, companyid); } } //Delete entry from optimized table accJournalEntryobj.deleteOnEditAccountJEs_optimized(oldjeid); } catch (ServiceException ex) { if(!StringUtil.isNullObject(typeValue) && typeValue==Constants.Party_Journal_Entry){ throw new AccountingException("CN/DN are already used in other transaction(s)."); } else{ throw new AccountingException("Journal entry details are already in use."); } } jeDataMap.put("jeisedit", true); } if (!StringUtil.isNullOrEmpty(costCenterId)) { jeDataMap.put(CCConstants.JSON_costcenterid, costCenterId); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("paidToCmb", null))) { jeDataMap.put("paidToCmb", paramJobj.optString("paidToCmb")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("pmtmethod", null))) { jeDataMap.put("pmtmethod", paramJobj.optString("pmtmethod")); } jeDataMap.put("includeInGSTReport", includeInGSTReport); boolean isFromEclaim = paramJobj.has(Constants.isFromEclaim) ? paramJobj.getBoolean(Constants.isFromEclaim) : false; jeDataMap.put("isFromEclaim", isFromEclaim); jeDataMap.put(GSTRTYPE, paramJobj.optInt(GSTRTYPE,0)); jeDataMap.put(ITC_TRANSACTION_IDS, paramJobj.optString(ITC_TRANSACTION_IDS)); KwlReturnObject jeresult = accJournalEntryobj.saveJournalEntry(jeDataMap); je = (JournalEntry) jeresult.getEntityList().get(0); JSONArray jArr = new JSONArray(paramJobj.optString("detail", "[]")); if (jArr.length()== 0) { JSONObject response = StringUtil.getErrorResponse("acc.common.erp32", paramJobj, "Account Details are missing.", messageSource); throw ServiceException.FAILURE(response.optString(Constants.RES_MESSAGE), "", false); } KwlReturnObject jedresult = accJournalEntryobj.getJEDset(jArr, companyid,je); if (je.getTypeValue() == 3) { // typeValue: 3 Fund Transfer JE jArr = StringUtil.sortJsonArray(jArr, "debit", false, false); } HashSet jeDetails = (HashSet) jedresult.getEntityList().get(0); je.setDetails(jeDetails); accJournalEntryobj.saveJournalEntryDetailsSet(jeDetails); jeid = je.getID(); ll.add(jeid); ll.add(oldjeid); ll.add(je.getEntryNumber()); /* * Make custom field entry at line level */ double amount=0.0; for (Iterator<JournalEntryDetail> jEDIterator = jeDetails.iterator(); jEDIterator.hasNext();) { JournalEntryDetail jed = jEDIterator.next(); int srno = 0; if (!jed.isDebit()) { //check print credit amount amount = jed.getAmount(); } if (jed.getSrno() != 0) { srno = jed.getSrno(); JSONObject jobj = jArr.getJSONObject(--srno); if (!StringUtil.isNullOrEmpty(jobj.optString("customfield", ""))) { JSONArray jcustomarray = new JSONArray(jobj.optString("customfield", "[]")); if (jcustomarray.length() > 0 && isFromEclaim) { jcustomarray = fieldDataManagercntrl1.GetJsonArrayUsingFieldIds(jcustomarray, Constants.Acc_GENERAL_LEDGER_ModuleId, companyid, false); } HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); customrequestParams.put("customarray", jcustomarray); customrequestParams.put("modulename", Constants.Acc_JEDetail_modulename); customrequestParams.put("moduleprimarykey", Constants.Acc_JEDetailId);// Constants.Acc_JEDetail_recdetailId customrequestParams.put("modulerecid", jed.getID()); customrequestParams.put("recdetailId", jed.getID()); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("customdataclasspath", Constants.Acc_BillInvDetail_custom_data_classpath); KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams); if (customDataresult != null && customDataresult.getEntityList().size() > 0) { //jed.setAccJEDetailCustomData((AccJEDetailCustomData) hibernateTemplate.get(AccJEDetailCustomData.class, jed.getID())); JSONObject jedjson = new JSONObject(); jedjson.put("accjedetailcustomdata", jed.getID()); jedjson.put("jedid", jed.getID()); jedresult = accJournalEntryobj.updateJournalEntryDetails(jedjson); } } } } /* * Make custom field entry */ String customfield = paramJobj.optString("customfield", null); if (!StringUtil.isNullOrEmpty(customfield)) { JSONArray jcustomarray = new JSONArray(customfield); if (jcustomarray.length() > 0 && isFromEclaim) { jcustomarray = fieldDataManagercntrl1.GetJsonArrayUsingFieldIds(jcustomarray, Constants.Acc_GENERAL_LEDGER_ModuleId, companyid, true); } HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); customrequestParams.put("customarray", jcustomarray); customrequestParams.put("modulename", Constants.Acc_JE_modulename); customrequestParams.put("moduleprimarykey", Constants.Acc_JEid); customrequestParams.put("modulerecid", jeid); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("customdataclasspath", Constants.Acc_BillInv_custom_data_classpath); KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams); if (customDataresult != null && customDataresult.getEntityList().size() > 0) { Map<String, Object> customjeDataMap = new HashMap<String, Object>(); customjeDataMap.put("accjecustomdataref", jeid); customjeDataMap.put("jeid", jeid); customjeDataMap.put("istemplate", istemplate); jeresult = accJournalEntryobj.updateCustomFieldJournalEntry(customjeDataMap); } } //Save record as template if (!StringUtil.isNullOrEmpty(paramJobj.optString("templatename", null)) && (istemplate == 1 || istemplate == 2)) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); String moduletemplateid = paramJobj.optString("moduletemplateid", null); hashMap.put("templatename", paramJobj.optString("templatename", null)); if (!StringUtil.isNullOrEmpty(moduletemplateid)) { hashMap.put("moduletemplateid", moduletemplateid); } hashMap.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); hashMap.put("modulerecordid", jeid); hashMap.put(Constants.companyKey, companyid); /** * checks the template name is already exist in create and * edit template case */ KwlReturnObject result = accountingHandlerDAOobj.getModuleTemplateForTemplatename(hashMap); int nocount = result.getRecordTotalCount(); if (nocount > 0) { throw new AccountingException(messageSource.getMessage("acc.tmp.templateNameAlreadyExists", null, Locale.forLanguageTag(paramJobj.optString("language")))); } accountingHandlerDAOobj.saveModuleTemplate(hashMap); } //Insert new entries again in optimized table. accJournalEntryobj.saveAccountJEs_optimized(jeid); rje = (RepeatedJE) je.getRepeateJE(); if (!StringUtil.isNullOrEmpty(chequeDetail)) { String name = "";//request.getParameter("paidToCmb"); KwlReturnObject custObj = accountingHandlerDAOobj.getObject(MasterItem.class.getName(), paramJobj.optString("paidToCmb")); if (custObj.getEntityList().get(0) != null) { MasterItem obj = (MasterItem) custObj.getEntityList().get(0); if (obj != null) { name = obj.getValue(); } } String basecurrency = paramJobj.optString(Constants.currencyKey); String amont1 = "" + amount; KwlReturnObject result2 = accountingHandlerDAOobj.getObject(KWLCurrency.class.getName(), basecurrency); KWLCurrency currency = (KWLCurrency) result2.getEntityList().get(0); String netinword = EnglishNumberToWordsOjb.convert(Double.parseDouble(String.valueOf(amont1)), currency,countryLanguageId); DecimalFormat def = new DecimalFormat("#,###,###,##0.00"); name=StringUtil.DecodeText(name); String amt = def.format(amount); ll.add(new String[]{"amount", amt}); ll.add(new String[]{"amountinword", netinword}); ll.add(new String[]{"accountName", name}); ll.add(chequeno); ll.add(rje); } else { ll.add(rje); } }/* catch (UnsupportedEncodingException ex) { throw ServiceException.FAILURE("saveJournalEntry : " + ex.getMessage(), ex); }*/ catch (ParseException ex) { throw ServiceException.FAILURE("saveJournalEntry : " + ex.getMessage(), ex); // Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { throw ServiceException.FAILURE("saveJournalEntry : " + ex.getMessage(), ex); } return ll; } public void deleteJEArray(String oldjeid, int journalEntryType, String companyid) throws ServiceException, AccountingException, SessionExpiredException { try { //delete old invoice JournalEntryDetail jed = null; if (!StringUtil.isNullOrEmpty(oldjeid)) { KwlReturnObject result = accJournalEntryobj.getJournalEntryDetail(oldjeid, companyid); List list = result.getEntityList(); Iterator itr = list.iterator(); while (itr.hasNext()) { jed = (JournalEntryDetail) itr.next(); //Sagar - No need to revert entry from optimized table as entries are already reverted from calling main function in edit case. result = accJournalEntryobj.deleteJournalEntryDetailRow(jed.getID(), companyid); } // getting chequeid in case of fund transfer result = accJournalEntryobj.getChequeIdLinkedToJournalEntry(oldjeid, companyid); String chequeId = ""; if (result != null) { List chequeList = result.getEntityList(); if (!chequeList.isEmpty()) { chequeId = (String) chequeList.get(0); } } //delete the reconcialation details in case if presentr for the JE // if(journalEntryType ==3){//Only in case if Journal Entry is Fund Transfer type JE result = accJournalEntryobj.DeleteBankReconciliationDetail(oldjeid, companyid); result = accJournalEntryobj.DeleteBankUnReconciliationDetail(oldjeid, companyid); // } result = accJournalEntryobj.permanentDeleteJournalEntry(oldjeid, companyid); result = accJournalEntryobj.deleteJECustomData(oldjeid); if (!StringUtil.isNullOrEmpty(chequeId)) { result = accPaymentDAOobj.deleteChequePermanently(chequeId, companyid); } } } catch (Exception ex) { //Logger.getLogger(accInvoiceController.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE(ex.getMessage(), ex); } } /* Note: while making whanges in this function (approveJE) also make chages in 'AccJournalEntryCMN/approveJE' function. * */ @Override public int approveJE(JournalEntry JE, String companyid, int level, String amount, JSONObject paramJobj, boolean fromCreate, String currentUser) throws SessionExpiredException, AccountingException, ServiceException, ScriptException, MessagingException { boolean hasAuthority = false; if (!fromCreate) { // check if the currently logged in user has authority or not to approve pending JE...but only in case when this method is called from approveJournalEntry method String thisUser = currentUser; KwlReturnObject userclass = accountingHandlerDAOobj.getObject(User.class.getName(), thisUser); User user = (User) userclass.getEntityList().get(0); if (AccountingManager.isCompanyAdmin(user)) { hasAuthority = true; } else { hasAuthority = accJournalEntryobj.checkForRule(level, companyid, amount, thisUser); } } else { hasAuthority = true; } if (hasAuthority) { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String requisitionApprovalSubject = "Journal Entry: %s - Approval Notification"; String requisitionApprovalHtmlMsg = "<html><head><title>Deskera Accounting - Your Deskera Account</title></head><style type='text/css'>" + "a:link, a:visited, a:active {\n" + " color: #03C;" + "}\n" + "body {\n" + " font-family: Arial, Helvetica, sans-serif;" + " color: #000;" + " font-size: 13px;" + "}\n" + "</style><body>" + "<p>Hi All,</p>" + "<p></p>" + "<p>%s has created journal entry %s and sent it to you for approval. at level "+(level+1)+"</p>" + "<p>Please review and approve it (Journal Entry Number: %s).</p>" + "<p></p>" + "<p>Company Name:- %s</p>" + "<p>Please check on Url:- %s</p>" + "<p>Thanks</p>" + "<p>This is an auto generated email. Do not reply<br>"; String requisitionApprovalPlainMsg = "Hi All,\n\n" + "%s has created journal entry %s and sent it to you for approval. at level "+(level+1)+"\n" + "Please review and approve it (Journal Entry Number: %s).\n\n" + "Company Name:- %s \n" + "Please check on Url:- %s \n" + "Thanks\n\n" + "This is an auto generated email. Do not reply\n"; int approvalStatus = 11; KwlReturnObject cap = accountingHandlerDAOobj.getObject(CompanyAccountPreferences.class.getName(), companyid); CompanyAccountPreferences preferences = (CompanyAccountPreferences) cap.getEntityList().get(0); String jeNumber = JE.getEntryNumber(); String jeID = JE.getID(); HashMap<String, Object> qdDataMap = new HashMap<String, Object>(); qdDataMap.put(Constants.companyKey, companyid); qdDataMap.put("level", level + 1); qdDataMap.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); KwlReturnObject flowresult = accMultiLevelApprovalDAOObj.getMultiApprovalRuleData(qdDataMap); Iterator itr = flowresult.getEntityList().iterator(); //String fromEmailId = Constants.ADMIN_EMAILID; KwlReturnObject returnObject = accountingHandlerDAOobj.getObject(Company.class.getName(),companyid); Company company = (Company) returnObject.getEntityList().get(0); Map<String, Object> smtpConfigMap = authHandler.getSMTPConfigMap(company); while (itr.hasNext()) { Object[] row = (Object[]) itr.next(); String rule = row[2].toString(); String creator = (!StringUtil.isNullOrEmpty(row[6].toString())) ? row[6].toString() : ""; boolean sendForApproval = false; String[] creators = creator.split(","); for (int i = 0; i < creators.length; i++) { if (creators[i].equals(paramJobj.optString(Constants.useridKey))) { sendForApproval = true; break; } } rule = rule.replaceAll("[$$]+", amount); /* * send mail to approvers on any of one below condition is true - * 1 - If level exist and rule is not set * 2 - If level and expression rule exist * 3 - If creator rule exist */ if (StringUtil.isNullOrEmpty(rule) || (!StringUtil.isNullOrEmpty(rule) && Boolean.parseBoolean(engine.eval(rule).toString())) || sendForApproval) { // send emails try { if (Boolean.parseBoolean(row[3].toString()) && preferences.isSendapprovalmail()) {//If allow to send approval mail in company account preferences String fromName = "User"; String fromEmailId = (!company.isEmailFromCompanyCreator())?Constants.ADMIN_EMAILID:authHandlerDAOObj.getSysEmailIdByCompanyID(company.getCompanyID()); fromName = paramJobj.optString(Constants.username); // String fromEmailId1 = StringUtil.isNullOrEmpty(JE.getCompany().getEmailID()) ? authHandlerDAOObj.getSysEmailIdByCompanyID(JE.getCompany().getCompanyID()) : JE.getCompany().getEmailID(); // if (!StringUtil.isNullOrEmpty(fromEmailId1)) { // fromEmailId = fromEmailId1; // } String subject = String.format(requisitionApprovalSubject, jeNumber); String htmlMsg = String.format(requisitionApprovalHtmlMsg, fromName, jeNumber, jeNumber, company.getCompanyName(), paramJobj.optString(Constants.PAGE_URL)); String plainMsg = String.format(requisitionApprovalPlainMsg, fromName, jeNumber, jeNumber , company.getCompanyName(), paramJobj.optString(Constants.PAGE_URL)); ArrayList<String> emailArray = new ArrayList<String>(); String[] emails = {}; qdDataMap.put("ruleid", row[0].toString()); KwlReturnObject userResult = accMultiLevelApprovalDAOObj.getApprovalRuleTargetUsers(qdDataMap); Iterator useritr = userResult.getEntityList().iterator(); while (useritr.hasNext()) { Object[] userrow = (Object[]) useritr.next(); emailArray.add(userrow[3].toString()); } emails = emailArray.toArray(emails); if (!StringUtil.isNullOrEmpty(preferences.getApprovalEmails())) { String[] compPrefMailIds = preferences.getApprovalEmails().split(","); emails = AccountingManager.getMergedMailIds(emails, compPrefMailIds); } if (emails.length > 0) { SendMailHandler.postMail(emails, subject, htmlMsg, plainMsg, fromEmailId, smtpConfigMap); } } } catch (MessagingException ex) { Logger.getLogger(JournalEntry.class.getName()).log(Level.SEVERE, null, ex); } approvalStatus = level + 1; } } accJournalEntryobj.approvePendingJE(jeID, companyid, approvalStatus); return approvalStatus; } else { return Constants.NoAuthorityToApprove; // It return fixed value 999 which indecates that current logged in user has no authority to approve the transaction } } public class EnglishNumberToWords { private final String[] tensNames = { "", " Ten", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety" }; private final String[] numNames = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen" }; private String convertLessThanOneThousand(int number) { String soFar; if (number % 100 < 20) { soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) { return soFar; } return numNames[number] + " Hundred" + soFar; } private String convertLessOne(int number, KWLCurrency currency) { String soFar; String val = currency.getAfterDecimalName(); if (number % 100 < 20) { soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) { return " And " + soFar + " " + val; } return " And " + numNames[number] + " " + val + soFar; } public String convert(Double number, KWLCurrency currency, int countryLanguageId) { if (number == 0) { return "Zero"; } String answer = ""; if (countryLanguageId == Constants.OtherCountryLanguageId) { // For universal conversion of amount in words. i.e. in Billion,trillion etc answer = universalConvert(number, currency); } else if (countryLanguageId == Constants.CountryIndiaLanguageId) { // For Indian word format.ie. in lakhs, crores answer = indianConvert(number, currency); } return answer; } public String universalConvert(Double number, KWLCurrency currency) { boolean isNegative = false; if (number < 0) { isNegative = true; number = -1 * number; } String snumber = Double.toString(number); String mask = "000000000000.00"; DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number); int billions = Integer.parseInt(snumber.substring(0, 3)); int millions = Integer.parseInt(snumber.substring(3, 6)); int hundredThousands = Integer.parseInt(snumber.substring(6, 9)); int thousands = Integer.parseInt(snumber.substring(9, 12)); int fractions = Integer.parseInt(snumber.substring(13, 15)); String tradBillions; switch (billions) { case 0: tradBillions = ""; break; case 1: tradBillions = convertLessThanOneThousand(billions) + " Billion "; break; default: tradBillions = convertLessThanOneThousand(billions) + " Billion "; } String result = tradBillions; String tradMillions; switch (millions) { case 0: tradMillions = ""; break; case 1: tradMillions = convertLessThanOneThousand(millions) + " Million "; break; default: tradMillions = convertLessThanOneThousand(millions) + " Million "; } result = result + tradMillions; String tradHundredThousands; switch (hundredThousands) { case 0: tradHundredThousands = ""; break; case 1: tradHundredThousands = "One Thousand "; break; default: tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " Thousand "; } result = result + tradHundredThousands; String tradThousand; tradThousand = convertLessThanOneThousand(thousands); result = result + tradThousand; String paises; switch (fractions) { case 0: paises = ""; break; default: paises = convertLessOne(fractions, currency); } result = result + paises; //to be done later result = result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " "); if (isNegative) { result = "Minus " + result; } // result = result.substring(0, 1).toUpperCase() + result.substring(1).toLowerCase(); // Make first letter of operand capital. return result; } public String indianConvert(Double number, KWLCurrency currency) { boolean isNegative = false; if (number < 0) { isNegative = true; number = -1 * number; } String snumber = Double.toString(number); String mask = "000000000000000.00"; //ERP-17681 DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number); int n = Integer.parseInt(snumber.substring(0, 15)); int fractions = Integer.parseInt(snumber.split("\\.").length != 0 ? snumber.split("\\.")[1] : "0"); if (n == 0) { return "Zero"; } String arr1[] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; String arr2[] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; String unit[] = {"Arab", "Crore", "Lakh", "Thousand", "Hundred", ""}; int factor[] = {1000000000, 10000000, 100000, 1000, 100, 1}; String answer = "", paises = ""; if (n < 0) { answer = "Minus"; n = -n; } int quotient, units, tens; for (int i = 0; i < factor.length; i++) { quotient = n / factor[i]; if (quotient > 0) { if (quotient < 20) { answer = answer + " " + arr1[quotient - 1]; } else { units = quotient % 10; tens = quotient / 10; if (units > 0) { answer = answer + " " + arr2[tens - 2] + " " + arr1[units - 1]; } else { answer = answer + " " + arr2[tens - 2] + " "; } } answer = answer + " " + unit[i]; } n = n % factor[i]; } switch (fractions) { case 0: paises = ""; break; default: paises = convertLessOne(fractions, currency); } answer = answer + paises; //to be done later return answer.trim(); } } }
UTF-8
Java
141,565
java
AccJournalEntryModuleServiceImpl.java
Java
[ { "context": "et.support.RequestContextUtils;\n\n/**\n *\n * @author krawler\n */\npublic class AccJournalEntryModuleServiceImpl", "end": 3417, "score": 0.9993418455123901, "start": 3410, "tag": "USERNAME", "value": "krawler" }, { "context": "ring(\"language\")));\n msgKey = \"acc.je2.save\";\n }else{\n msgK", "end": 87457, "score": 0.9514759182929993, "start": 87445, "tag": "KEY", "value": "acc.je2.save" }, { "context": " }else{\n msgKey = \"acc.je1.save\";\n }\n// }\n \n ", "end": 87525, "score": 0.9900241494178772, "start": 87513, "tag": "KEY", "value": "acc.je1.save" }, { "context": "es\n String fromName = \"User\";\n String fromEmailId ", "end": 130765, "score": 0.8961434364318848, "start": 130761, "tag": "NAME", "value": "User" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.krawler.hql.accounting.journalentry.service; import com.krawler.common.admin.AuditAction; import com.krawler.common.admin.Company; import com.krawler.common.admin.ExtraCompanyPreferences; import com.krawler.common.admin.KWLCurrency; import com.krawler.common.admin.User; import com.krawler.common.service.ServiceException; import com.krawler.common.session.SessionExpiredException; import com.krawler.common.util.Constants; import com.krawler.common.util.StringUtil; import com.krawler.customFieldMaster.fieldDataManager; import com.krawler.esp.handlers.SendMailHandler; import com.krawler.hql.accounting.*; import com.krawler.spring.accounting.companypreferances.accCompanyPreferencesDAO; import com.krawler.spring.accounting.costCenter.CCConstants; import com.krawler.spring.accounting.currency.accCurrencyDAO; import com.krawler.spring.accounting.customer.accCustomerDAO; import com.krawler.spring.accounting.handler.AccountingHandlerDAO; import com.krawler.spring.accounting.handler.AccountingManager; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.GSTRTYPE; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.ITC_TRANSACTION_IDS; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.JEDID; import static com.krawler.spring.accounting.journalentry.JournalEntryConstants.JEID; import com.krawler.spring.accounting.journalentry.accJournalEntryController; import com.krawler.spring.accounting.journalentry.accJournalEntryDAO; import com.krawler.spring.accounting.multiLevelApprovalRule.AccMultiLevelApprovalDAO; import com.krawler.spring.accounting.payment.accPaymentDAO; import com.krawler.spring.accounting.payment.accPaymentService; import com.krawler.spring.auditTrailModule.auditTrailDAO; import com.krawler.spring.authHandler.authHandler; import com.krawler.spring.authHandler.authHandlerDAO; import com.krawler.spring.common.KwlReturnObject; import com.krawler.spring.common.kwlCommonTablesDAO; import com.krawler.spring.sessionHandler.sessionHandlerImpl; import com.krawler.utils.json.base.JSONArray; import com.krawler.utils.json.base.JSONException; import com.krawler.utils.json.base.JSONObject; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLDecoder; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.MessagingException; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.MessageSource; import org.springframework.context.MessageSourceAware; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.web.servlet.support.RequestContextUtils; /** * * @author krawler */ public class AccJournalEntryModuleServiceImpl implements AccJournalEntryModuleService, MessageSourceAware { private MessageSource messageSource; private HibernateTransactionManager txnManager; private accJournalEntryDAO accJournalEntryobj; private accCompanyPreferencesDAO accCompanyPreferencesObj; private accCurrencyDAO accCurrencyobj; private auditTrailDAO auditTrailObj; private AccountingHandlerDAO accountingHandlerDAOobj; private String successView; private fieldDataManager fieldDataManagercntrl; private accCustomerDAO accCustomerDAOobj; private accPaymentDAO accPaymentDAOobj; private accPaymentService accPaymentService; private AccMultiLevelApprovalDAO accMultiLevelApprovalDAOObj; private com.krawler.spring.common.fieldDataManager fieldDataManagercntrl1; private authHandlerDAO authHandlerDAOObj; private EnglishNumberToWords EnglishNumberToWordsOjb = new EnglishNumberToWords(); private kwlCommonTablesDAO kwlCommonTablesDAOObj; public void setKwlCommonTablesDAOObj(kwlCommonTablesDAO kwlCommonTablesDAOObj) { this.kwlCommonTablesDAOObj = kwlCommonTablesDAOObj; } public void setFieldDataManagercntrl1(com.krawler.spring.common.fieldDataManager fieldDataManagercntrl1) { this.fieldDataManagercntrl1 = fieldDataManagercntrl1; } public void setauthHandlerDAO(authHandlerDAO authHandlerDAOObj1) { this.authHandlerDAOObj = authHandlerDAOObj1; } public void setaccountingHandlerDAO(AccountingHandlerDAO AccountingHandlerDAOobj) { this.accountingHandlerDAOobj = AccountingHandlerDAOobj; } public void setaccMultiLevelApprovalDAOObj(AccMultiLevelApprovalDAO accMultiLevelApprovalDAO) { this.accMultiLevelApprovalDAOObj = accMultiLevelApprovalDAO; } public void setauditTrailDAO(auditTrailDAO auditTrailDAOObj) { this.auditTrailObj = auditTrailDAOObj; } public void setTxnManager(HibernateTransactionManager txManager) { this.txnManager = txManager; } public void setMessageSource(MessageSource ms) { this.messageSource = ms; } public void setaccJournalEntryDAO(accJournalEntryDAO accJournalEntryobj) { this.accJournalEntryobj = accJournalEntryobj; } public void setaccCompanyPreferencesDAO(accCompanyPreferencesDAO accCompanyPreferencesObj) { this.accCompanyPreferencesObj = accCompanyPreferencesObj; } public void setaccCurrencyDAO(accCurrencyDAO accCurrencyobj) { this.accCurrencyobj = accCurrencyobj; } public String getSuccessView() { return successView; } public void setFieldDataManager(fieldDataManager fieldDataManagercntrl) { this.fieldDataManagercntrl = fieldDataManagercntrl; } public void setSuccessView(String successView) { this.successView = successView; } public void setaccCustomerDAO(accCustomerDAO accCustomerDAOobj) { this.accCustomerDAOobj = accCustomerDAOobj; } public void setAccPaymentDAOobj(accPaymentDAO accPaymentDAOobj) { this.accPaymentDAOobj = accPaymentDAOobj; } public void setAccPaymentService(accPaymentService accPaymentService) { this.accPaymentService = accPaymentService; } public JSONObject saveJournalEntry(HttpServletRequest request, HttpServletResponse response) { JSONObject jobj = new JSONObject(); String msg = ""; String billno = ""; String billid = ""; String amount = ""; boolean issuccess = true; String butPendingForApproval = ""; try{ JSONObject paramJObj = new JSONObject(); try{Enumeration<String> attributes = request.getAttributeNames(); while(attributes.hasMoreElements()){ String attribute = attributes.nextElement(); paramJObj.put(attribute, request.getAttribute(attribute)); } Enumeration<String> parameters = request.getParameterNames(); while(parameters.hasMoreElements()){ String parameter = parameters.nextElement(); paramJObj.put(parameter, request.getParameter(parameter)); } } catch(JSONException e){ e.printStackTrace(); } String companyid = sessionHandlerImpl.getCompanyid(request); String userDateFormat = sessionHandlerImpl.getUserDateFormat(request); String userfullname = sessionHandlerImpl.getUserFullName(request); String currencyid = sessionHandlerImpl.getCurrencyID(request); paramJObj.put(Constants.companyKey, companyid); paramJObj.put("userdateformat", userDateFormat); paramJObj.put(Constants.currencyKey, currencyid); paramJObj.put(Constants.globalCurrencyKey, currencyid); paramJObj.put(Constants.userfullname, userfullname); String timezoneOffset = sessionHandlerImpl.getTimeZoneDifference(request); paramJObj.put("timezoneOffset", timezoneOffset); paramJObj.put("language", RequestContextUtils.getLocale(request).getLanguage()); jobj = saveJournalEntryJson(paramJObj); } catch(SessionExpiredException ex){ issuccess=false; Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { issuccess=false; Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { issuccess=false; ex.printStackTrace(); msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jobj.put("success", issuccess); jobj.put("msg", msg); jobj.put("billid", billid); jobj.put("billno", billno); jobj.put("amount", ""); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public JournalEntry saveJournalEntry(HttpServletRequest request, JSONObject dataMap, int counter) throws SessionExpiredException, ServiceException, AccountingException, JSONException { JournalEntry journalEntry = null; JSONObject paramJObj = new JSONObject(); try{Enumeration<String> attributes = request.getAttributeNames(); while(attributes.hasMoreElements()){ String attribute = attributes.nextElement(); paramJObj.put(attribute, request.getAttribute(attribute)); } Enumeration<String> parameters = request.getParameterNames(); while(parameters.hasMoreElements()){ String parameter = parameters.nextElement(); paramJObj.put(parameter, request.getParameter(parameter)); } } catch(JSONException e){ e.printStackTrace(); } String companyid = sessionHandlerImpl.getCompanyid(request); String userDateFormat = sessionHandlerImpl.getUserDateFormat(request); String userfullname = sessionHandlerImpl.getUserFullName(request); String currencyid = sessionHandlerImpl.getCurrencyID(request); paramJObj.put(Constants.companyKey, companyid); paramJObj.put("userdateformat", userDateFormat); paramJObj.put(Constants.currencyKey, currencyid); paramJObj.put(Constants.globalCurrencyKey, currencyid); paramJObj.put(Constants.userfullname, userfullname); String timezoneOffset = sessionHandlerImpl.getTimeZoneDifference(request); paramJObj.put("timezoneOffset", timezoneOffset); paramJObj.put("language", RequestContextUtils.getLocale(request).getLanguage()); journalEntry = saveJournalEntryJson(paramJObj, dataMap, counter); return journalEntry; } public JSONObject saveJournalEntryJson(JSONObject paramJobj) throws JSONException, SessionExpiredException, ServiceException{ JSONObject jobj = new JSONObject(); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Quotation_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null;//txnManager.getTransaction(def); try{ int counter = 0; JSONArray jarr = paramJobj.getJSONArray("jedata"); JSONArray respArray = new JSONArray(); for (int i = 0; i < jarr.length(); i++) { status = txnManager.getTransaction(def); JSONObject dataMap = jarr.getJSONObject(i); JournalEntry je = saveJournalEntryJson(paramJobj, dataMap, counter); JSONObject jeObj = new JSONObject(); jeObj.put("entryno", je.getEntryNumber()); jeObj.put("jeid", je.getID()); respArray.put(jeObj); // counter++; txnManager.commit(status); } String msg = messageSource.getMessage("acc.je1.save", null, Locale.forLanguageTag(paramJobj.getString("language"))); jobj.put("msg", msg); jobj.put("jarr", respArray); jobj.put("success", true); } catch(ServiceException e){ txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw ServiceException.FAILURE(e.getMessage(), e); } catch(SessionExpiredException e){ txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw ServiceException.FAILURE(e.getMessage(), e); } catch(JSONException e){ txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw new JSONException(e); } catch (AccountingException e) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, e); throw ServiceException.FAILURE(e.getMessage(), e); } return jobj; } public JournalEntry saveJournalEntryJson(JSONObject paramJobj, JSONObject dataMap, int counter) throws SessionExpiredException, ServiceException, AccountingException,JSONException { JournalEntry journalEntry = null; String companyid = paramJobj.getString(Constants.companyKey); String currencyid = paramJobj.getString(Constants.currencyKey); DateFormat df = authHandler.getDateOnlyFormat(); Calendar cal = Calendar.getInstance(); Date billdateVal = null; long billdateValue = 0; if(!StringUtil.isNullOrEmpty(paramJobj.optString("creationdate"))){ billdateValue = (long) Long.parseLong(paramJobj.get("creationdate").toString()); } else{ billdateValue = (new Date()).getTime(); } cal.setTimeInMillis(billdateValue); String timeZoneDifference = ""; if(paramJobj.has("timezoneOffset")){ timeZoneDifference = paramJobj.getString("timezoneOffset"); } cal.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDifference)); billdateVal = cal.getTime(); SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy hh:mm:ss aa"); try { billdateVal = df.parse(sdf.format(billdateVal)); } catch (ParseException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } double externalCurrencyRate = 1d; if (!StringUtil.isNullOrEmpty(currencyid)) { HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put(Constants.globalCurrencyKey, paramJobj.getString(Constants.currencyKey)); requestParams.put(Constants.companyKey, companyid); externalCurrencyRate = accCurrencyobj.getCurrencyToBaseRate(requestParams, currencyid, billdateVal); } double amount = 0; if(dataMap.has("amount")){ amount = Double.parseDouble(dataMap.get("amount").toString()); } String sales_Account = ""; String revenueaccount = ""; KwlReturnObject cap = accountingHandlerDAOobj.getObject(ExtraCompanyPreferences.class.getName(), companyid); ExtraCompanyPreferences preferences = (ExtraCompanyPreferences) cap.getEntityList().get(0); if (preferences.isRecurringDeferredRevenueRecognition()) { KwlReturnObject cap1 = accountingHandlerDAOobj.getObject(Account.class.getName(), preferences.getSalesAccount()); Account salesaccount = (Account) cap1.getEntityList().get(0); sales_Account = salesaccount.getID(); KwlReturnObject cap2 = accountingHandlerDAOobj.getObject(Account.class.getName(), preferences.getSalesRevenueRecognitionAccount()); Account revenueacc = (Account) cap2.getEntityList().get(0); revenueaccount = revenueacc.getID(); } else { throw new AccountingException("Please set Advance sales and Revenue Recognition Account for LMS"); } Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJobj); String jeentryNumber = null; String jeDatePrefix = ""; String jeDateAfterPrefix = ""; String jeDateSuffix = ""; boolean jeautogenflag = false; String jeSeqFormatId = ""; synchronized (this) { try { HashMap<String, Object> JEFormatParams = new HashMap<String, Object>(); JEFormatParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); JEFormatParams.put("modulename", "autojournalentry"); JEFormatParams.put(Constants.companyKey, companyid); JEFormatParams.put("isdefaultFormat", true); KwlReturnObject kwlObj = accCompanyPreferencesObj.getSequenceFormat(JEFormatParams); SequenceFormat format = (SequenceFormat) kwlObj.getEntityList().get(0); Map<String, Object> seqNumberMap = new HashMap<String, Object>(); seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, format.getID(), false, billdateVal); String nextAutoNoTemp = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number int sequence = Integer.parseInt((String)seqNumberMap.get(Constants.SEQNUMBER)); jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part sequence = sequence + counter; String number = "" + sequence; String action = "" + (sequence - counter); nextAutoNoTemp.replaceAll(action, number); jeentryNumber = nextAutoNoTemp.replaceAll(action, number); //next auto generated number jeSeqFormatId = format.getID(); jeautogenflag = true; jeDataMap.put("entrynumber", jeentryNumber); jeDataMap.put("autogenerated", jeautogenflag); jeDataMap.put(Constants.SEQFORMAT, jeSeqFormatId); jeDataMap.put(Constants.SEQNUMBER, number); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); } catch (ServiceException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } String invoiceId= dataMap.optString("invoiceId", ""); String invoiceNo= dataMap.optString("invoiceNo", ""); String memo="Manual JE For Revenue Recognition for Invoice "+invoiceNo; jeDataMap.put("entrydate", billdateVal); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, currencyid); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", 1); String custCode = dataMap.optString("studentid", ""); String CustomerId = ""; if (!StringUtil.isNullOrEmpty(custCode)) { KwlReturnObject resultcheck = accCustomerDAOobj.checkCustomerExistbyCode(custCode, companyid); if (!resultcheck.getEntityList().isEmpty()) { Customer customer = (Customer) resultcheck.getEntityList().get(0); CustomerId = customer.getID(); } } jeDataMap.put("customerid", CustomerId); journalEntry = accJournalEntryobj.getJournalEntry(jeDataMap); accJournalEntryobj.saveJournalEntryByObject(journalEntry); HashMap hashMap=new HashMap(); hashMap.put("invoiceId", invoiceId); hashMap.put("jeId", journalEntry.getID()); accJournalEntryobj.saveRevenueJEInvoiceMapping(hashMap); //custom code JSONArray jcustomarray = null; boolean customfieldArrayflag = true; String customfieldArray = dataMap.optString("customfieldArray", ""); //Custom Data from other Project customfieldArray = StringUtil.DecodeText(customfieldArray); if (!StringUtil.isNullOrEmpty(customfieldArray)) { HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); String mapWithFieldType = paramJobj.optString("mapWithFieldType",null); customrequestParams.put("customarray", customfieldArray); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("mapWithFieldType", mapWithFieldType); jcustomarray = fieldDataManagercntrl.createJSONArrForCustomFieldValueFromOtherSource(customrequestParams); customfieldArrayflag = false; } // Add Custom fields details if (!StringUtil.isNullOrEmpty(dataMap.optString("customfield", "")) || !StringUtil.isNullOrEmpty(customfieldArray)) { if (customfieldArrayflag) { jcustomarray = new JSONArray(dataMap.optString("customfield", "[]")); } HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); customrequestParams.put("customarray", jcustomarray); customrequestParams.put("modulename", Constants.Acc_JE_modulename); customrequestParams.put("moduleprimarykey", Constants.Acc_JEid); customrequestParams.put("modulerecid", journalEntry.getID()); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("customdataclasspath", Constants.Acc_BillInv_custom_data_classpath); KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams); if (customDataresult != null && customDataresult.getEntityList().size() > 0) { Map<String, Object> customjeDataMap = new HashMap<String, Object>(); customjeDataMap.put("accjecustomdataref", journalEntry.getID()); customjeDataMap.put("jeid", journalEntry.getID()); accJournalEntryobj.updateCustomFieldJournalEntry(customjeDataMap); } } JSONObject jedjson = new JSONObject(); jedjson.put("srno", 1); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", amount); jedjson.put("accountid", sales_Account); jedjson.put("debit", true); jedjson.put("jeid", journalEntry.getID()); KwlReturnObject jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); JournalEntryDetail jed = (JournalEntryDetail) jedresult.getEntityList().get(0); Set<JournalEntryDetail> detail = new HashSet(); detail.add(jed); jedjson = new JSONObject(); jedjson.put("srno", 2); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", amount); jedjson.put("accountid", revenueaccount); jedjson.put("debit", false); jedjson.put("jeid", journalEntry.getID()); jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); jed = (JournalEntryDetail) jedresult.getEntityList().get(0); detail.add(jed); journalEntry.setDetails(detail); accJournalEntryobj.saveJournalEntryDetailsSet(detail); Map<String, Object> auditTrailMap = new HashMap<String, Object>(); auditTrailMap.put(Constants.useridKey, paramJobj.getString("lid")); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJobj.optString(Constants.userfullname) + " has posted Journal Entry " + jeentryNumber +" for Revenue Recognition ", auditTrailMap,journalEntry.getID()); return journalEntry; } @Override public synchronized KwlReturnObject updateJEEntryNumberForNewJE(Map<String, Object> jeDataMap, JournalEntry JE, String companyid, String sequenceFormat,int approvedLevel) { String entryNumber = ""; List list = new ArrayList(); boolean successFlag=true; try { String nextJEAutoNo = null; //String sequenceformat = request.getParameter("sequenceformat"); String psotingDateStr = (String) jeDataMap.get("postingDate"); DateFormat df = authHandler.getDateOnlyFormat(); Date postingDate = null; if (!StringUtil.isNullOrEmpty(psotingDateStr)) { postingDate = df.parse(psotingDateStr); } Map<String,Object> paramMap=new HashMap<>(); paramMap.put("id",companyid); Object exPrefObject = kwlCommonTablesDAOObj.getRequestedObjectFields(ExtraCompanyPreferences.class, new String[]{"columnPref"}, paramMap); JSONObject jObj = StringUtil.isNullObject(exPrefObject) ? new JSONObject() : new JSONObject(exPrefObject.toString()); boolean isPostingDateCheck = false; if (!StringUtil.isNullObject(jObj) && jObj.has(Constants.IS_POSTING_DATE_CHECK) && jObj.get(Constants.IS_POSTING_DATE_CHECK) != null && jObj.optBoolean(Constants.IS_POSTING_DATE_CHECK, false)) { isPostingDateCheck = true; } if (!sequenceFormat.equals("NA") && !StringUtil.isNullOrEmpty(sequenceFormat)) { boolean seqformat_oldflag = false;//StringUtil.getBoolean(request.getParameter("seqformat_oldflag")); String nextAutoNo = ""; String nextAutoNoInt = ""; if (seqformat_oldflag) { nextJEAutoNo = accCompanyPreferencesObj.getNextAutoNumber(companyid, StaticValues.AUTONUM_JOURNALENTRY, sequenceFormat); } else { Map<String, Object> seqNumberMap = new HashMap<String, Object>(); if (postingDate != null && isPostingDateCheck) { seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, sequenceFormat, seqformat_oldflag, postingDate); } else { seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, sequenceFormat, seqformat_oldflag, JE.getEntryDate()); } nextJEAutoNo = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number nextAutoNoInt = (String)seqNumberMap.get(Constants.SEQNUMBER);//integer Part String jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part String jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part String jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part jeDataMap.put(Constants.SEQFORMAT, sequenceFormat); jeDataMap.put(Constants.SEQNUMBER, nextAutoNoInt); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); entryNumber = nextJEAutoNo; } } if (isPostingDateCheck && postingDate!=null) { jeDataMap.put("entrydate", postingDate); } else { jeDataMap.put("entrydate", JE.getEntryDate()); } jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("entrynumber", entryNumber); jeDataMap.put("jeid", JE.getID()); jeDataMap.put("istemplate", JE.getIstemplate()); jeDataMap.put("isReval", JE.getIsReval()); jeDataMap.put("isDraft", JE.isDraft()); jeDataMap.put("pendingapproval", approvedLevel); KwlReturnObject je1result = accJournalEntryobj.saveJournalEntry(jeDataMap); list.add(entryNumber); } catch (Exception e) { list.add(e.getMessage()); successFlag=false; Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, e); } return new KwlReturnObject(successFlag, "JE entry number has been updated successfully", null, list, list.size()); } @Override public String getNextChequeNumberForRecurredJE(String companyId, String bankAccountId) { String nextChequeNumber = ""; try { nextChequeNumber = accPaymentService.getNextChequeNumberForRecurredPayment(companyId,bankAccountId); } catch (Exception ex) { Logger.getLogger(accPaymentService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return nextChequeNumber; } @Override public KwlReturnObject addCheque(HashMap<String, Object> checkHM) { KwlReturnObject cqresult = null; try { cqresult = accPaymentDAOobj.addCheque(checkHM); } catch (Exception ex) { Logger.getLogger(accPaymentService.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return cqresult; } public JSONObject saveJournalEntryRemoteApplication(HttpServletRequest request, HttpServletResponse response) { String msg = ""; boolean issuccess = true; JSONObject jobj = new JSONObject(); try { JSONObject paramJObj = new JSONObject(); Enumeration<String> attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = attributes.nextElement(); paramJObj.put(attribute, request.getAttribute(attribute)); } Enumeration<String> parameters = request.getParameterNames(); while (parameters.hasMoreElements()) { String parameter = parameters.nextElement(); paramJObj.put(parameter, request.getParameter(parameter)); } String companyid = sessionHandlerImpl.getCompanyid(request); String userDateFormat = sessionHandlerImpl.getUserDateFormat(request); paramJObj.put(Constants.companyKey, companyid); String currencyid = sessionHandlerImpl.getCurrencyID(request); paramJObj.put(Constants.currencyKey, currencyid); paramJObj.put(Constants.globalCurrencyKey, currencyid); String userfullname = sessionHandlerImpl.getUserFullName(request); paramJObj.put(Constants.userfullname, userfullname); paramJObj.put("userdateformat", userDateFormat); String userId = sessionHandlerImpl.getUserid(request); paramJObj.put(Constants.useridKey, userId); paramJObj.put("lid", userId); paramJObj.put("language", RequestContextUtils.getLocale(request).getLanguage()); jobj = saveJournalEntryRemoteApplicationJson(paramJObj); } catch (JSONException ex) { msg = "" + ex.getMessage(); issuccess=false; if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (SessionExpiredException ex) { issuccess=false; msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (ServiceException ex) { issuccess=false; msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { issuccess=false; msg = "" + ex.getMessage(); if (ex.getMessage() == null) { msg = ex.getCause().getMessage(); } Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jobj.put("success", issuccess); jobj.put("msg", msg); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public JournalEntry saveJournalEntryRemoteApplication(HttpServletRequest request, JSONObject dataMap) throws SessionExpiredException, ServiceException, AccountingException { JournalEntry journalEntry = null; try { String companyid = sessionHandlerImpl.getCompanyid(request); String currencyid = (!StringUtil.isNullOrEmpty(request.getParameter(Constants.currencyKey)) ? request.getParameter(Constants.currencyKey) : sessionHandlerImpl.getCurrencyID(request)); Map<String, Object> jeDataMap = AccountingManager.getGlobalParams(request); double externalCurrencyRate = 1d; String jeentryNumber = null; boolean jeautogenflag = false; String jeSeqFormatId = ""; synchronized (this) { try { HashMap<String, Object> JEFormatParams = new HashMap<String, Object>(); JEFormatParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); JEFormatParams.put("modulename", "autojournalentry"); JEFormatParams.put(Constants.companyKey, companyid); JEFormatParams.put("isdefaultFormat", true); KwlReturnObject kwlObj = accCompanyPreferencesObj.getSequenceFormat(JEFormatParams); SequenceFormat format = (SequenceFormat) kwlObj.getEntityList().get(0); Map<String, Object> seqNumberMap = new HashMap<String, Object>(); seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, format.getID(), false, null); // Since JE date is always system date with timezone, hence sending null. It has been hadled in called method String nextAutoNoTemp = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number String jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part String jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part String jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part int sequence = Integer.parseInt((String)seqNumberMap.get(Constants.SEQNUMBER)); sequence = sequence; String number = "" + sequence; String action = "" + (sequence); nextAutoNoTemp.replaceAll(action, number); jeentryNumber = nextAutoNoTemp.replaceAll(action, number); //next auto generated number jeSeqFormatId = format.getID(); jeautogenflag = true; jeDataMap.put("entrynumber", jeentryNumber); jeDataMap.put("autogenerated", jeautogenflag); jeDataMap.put(Constants.SEQFORMAT, jeSeqFormatId); jeDataMap.put(Constants.SEQNUMBER, number); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); } catch (ServiceException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } String memo = dataMap.optString("memo", ""); String auditmessage = dataMap.optString("auditmessage", ""); // jeDataMap.put("entrydate", new Date()); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, currencyid); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", 1); journalEntry = accJournalEntryobj.getJournalEntry(jeDataMap); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date newdate=authHandler.getDateWithTimeFormat().parse(authHandler.getConstantDateFormatter().format(new Date())); Date newdate=new Date(); String userdiff=journalEntry.getCompany().getCreator().getTimeZone()!=null?journalEntry.getCompany().getCreator().getTimeZone().getDifference() : journalEntry.getCompany().getTimeZone().getDifference(); sdf.setTimeZone(TimeZone.getTimeZone("GMT"+userdiff)); Date newcreatedate=authHandler.getDateWithTimeFormat().parse(sdf.format(newdate)); journalEntry.setEntryDate(newcreatedate); accJournalEntryobj.saveJournalEntryByObject(journalEntry); JSONArray jArr = new JSONArray(dataMap.optString("details")); Set<JournalEntryDetail> detail = new HashSet(); for (int i = 0; i < jArr.length(); i++) { JSONObject detailData = jArr.getJSONObject(i); JSONObject jedjson = new JSONObject(); jedjson.put("srno", i + 1); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", detailData.optString("amount")); jedjson.put("accountid", detailData.optString("accountid")); jedjson.put("debit", detailData.optBoolean("debit")); jedjson.put("jeid", journalEntry.getID()); jedjson.put("description", detailData.optString("description")); KwlReturnObject jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); JournalEntryDetail jed = (JournalEntryDetail) jedresult.getEntityList().get(0); detail.add(jed); } journalEntry.setDetails(detail); accJournalEntryobj.saveJournalEntryDetailsSet(detail); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + sessionHandlerImpl.getUserFullName(request) + " has posted Journal Entry " + jeentryNumber + " "+auditmessage, request, journalEntry.getID()); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return journalEntry; } public JSONObject saveJournalEntryRemoteApplicationJson(JSONObject paramJobj)throws SessionExpiredException, ServiceException, JSONException, AccountingException { JSONObject jobj = new JSONObject(); JSONArray array=new JSONArray(); String msg = ""; boolean issuccess = false; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Quotation_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null;//txnManager.getTransaction(def); try { int counter = 0; JSONObject inputdata = new JSONObject(paramJobj.get("data").toString()); JSONArray jarr = inputdata.getJSONArray("jedata"); for (int i = 0; i < jarr.length(); i++) { JSONObject dataMap1 = jarr.getJSONObject(i); JSONArray tempArr = dataMap1.getJSONArray("details"); for (int j = 0; j < tempArr.length(); j++) { status = txnManager.getTransaction(def); JSONObject dataMap = tempArr.getJSONObject(j); JournalEntry je = saveJournalEntryRemoteApplicationJson(paramJobj, dataMap); JSONObject returnObj=new JSONObject(); returnObj.put("historyid", dataMap.optString("historyid")); returnObj.put("jeid", je.getID()); returnObj.put("entryno", je.getEntryNumber()); txnManager.commit(status); array.put(returnObj); } } issuccess = true; msg = messageSource.getMessage("acc.je1.save", null, Locale.forLanguageTag(paramJobj.getString("language"))); jobj.put("jarr", array); jobj.put("success", issuccess); jobj.put("msg", msg); } catch (JSONException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw new JSONException(ex); } catch (SessionExpiredException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE(ex.getMessage(), ex); } catch (ServiceException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw ex; } catch (AccountingException ex) { txnManager.rollback(status); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw new AccountingException(ex); } finally { try { jobj.put("success", issuccess); jobj.put("msg", msg); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public JournalEntry saveJournalEntryRemoteApplicationJson(JSONObject paramJobj, JSONObject dataMap) throws SessionExpiredException, ServiceException, AccountingException { JournalEntry journalEntry = null; try { String companyid = paramJobj.getString(Constants.companyKey); String currencyid = paramJobj.getString(Constants.currencyKey); Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJobj); double externalCurrencyRate = 1d; String jeentryNumber = null; boolean jeautogenflag = false; String jeSeqFormatId = ""; synchronized (this) { try { HashMap<String, Object> JEFormatParams = new HashMap<String, Object>(); JEFormatParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); JEFormatParams.put("modulename", "autojournalentry"); JEFormatParams.put(Constants.companyKey, companyid); JEFormatParams.put("isdefaultFormat", true); KwlReturnObject kwlObj = accCompanyPreferencesObj.getSequenceFormat(JEFormatParams); SequenceFormat format = (SequenceFormat) kwlObj.getEntityList().get(0); Map<String, Object> seqNumberMap = new HashMap<String, Object>(); seqNumberMap = accCompanyPreferencesObj.getNextAutoNumber_Modified(companyid, StaticValues.AUTONUM_JOURNALENTRY, format.getID(), false, null); // Since JE date is always system date with timezone, hence sending null. It has been hadled in called method String nextAutoNoTemp = (String)seqNumberMap.get(Constants.AUTO_ENTRYNUMBER); //next auto generated number String jeDatePrefix = (String)seqNumberMap.get(Constants.DATEPREFIX);//Date Prefix Part String jeDateAfterPrefix = (String)seqNumberMap.get(Constants.DATEAFTERPREFIX); //Date After Prefix Part String jeDateSuffix = (String)seqNumberMap.get(Constants.DATESUFFIX);//Date Suffix Part int sequence = Integer.parseInt((String)seqNumberMap.get(Constants.SEQNUMBER)); sequence = sequence; String number = "" + sequence; String action = "" + (sequence); nextAutoNoTemp.replaceAll(action, number); jeentryNumber = nextAutoNoTemp.replaceAll(action, number); //next auto generated number jeSeqFormatId = format.getID(); jeautogenflag = true; jeDataMap.put("entrynumber", jeentryNumber); jeDataMap.put("autogenerated", jeautogenflag); jeDataMap.put(Constants.SEQFORMAT, jeSeqFormatId); jeDataMap.put(Constants.SEQNUMBER, number); jeDataMap.put(Constants.DATEPREFIX, jeDatePrefix); jeDataMap.put(Constants.DATEAFTERPREFIX, jeDateAfterPrefix); jeDataMap.put(Constants.DATESUFFIX, jeDateSuffix); } catch (ServiceException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } String memo = dataMap.optString("memo", ""); String auditmessage = dataMap.optString("auditmessage", ""); // jeDataMap.put("entrydate", new Date()); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, currencyid); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", 1); journalEntry = accJournalEntryobj.getJournalEntry(jeDataMap); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date newdate=authHandler.getDateWithTimeFormat().parse(authHandler.getConstantDateFormatter().format(new Date())); Date newdate=new Date(); String userdiff=journalEntry.getCompany().getCreator().getTimeZone()!=null?journalEntry.getCompany().getCreator().getTimeZone().getDifference() : journalEntry.getCompany().getTimeZone().getDifference(); sdf.setTimeZone(TimeZone.getTimeZone("GMT"+userdiff)); Date newcreatedate=authHandler.getDateWithTimeFormat().parse(sdf.format(newdate)); journalEntry.setEntryDate(newcreatedate); accJournalEntryobj.saveJournalEntryByObject(journalEntry); JSONArray jArr = new JSONArray(dataMap.optString("details")); Set<JournalEntryDetail> detail = new HashSet(); for (int i = 0; i < jArr.length(); i++) { JSONObject detailData = jArr.getJSONObject(i); JSONObject jedjson = new JSONObject(); jedjson.put("srno", i + 1); jedjson.put(Constants.companyKey, companyid); jedjson.put("amount", detailData.optString("amount")); jedjson.put("accountid", detailData.optString("accountid")); jedjson.put("debit", detailData.optBoolean("debit")); jedjson.put("jeid", journalEntry.getID()); jedjson.put("description", detailData.optString("description")); KwlReturnObject jedresult = accJournalEntryobj.addJournalEntryDetails(jedjson); JournalEntryDetail jed = (JournalEntryDetail) jedresult.getEntityList().get(0); detail.add(jed); } journalEntry.setDetails(detail); accJournalEntryobj.saveJournalEntryDetailsSet(detail); Map<String, Object> auditTrailMap = new HashMap<String, Object>(); auditTrailMap.put(Constants.useridKey, paramJobj.getString("lid")); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJobj.optString(Constants.userfullname) + " has posted Journal Entry " + jeentryNumber + " "+auditmessage, auditTrailMap, journalEntry.getID()); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } return journalEntry; } /** * * @param requestparams * @return * @Desc : Update JournalEntry which is created using recurring process */ public JSONObject updateJournalEntry(JSONObject requestparams) { JSONObject jSONObject = new JSONObject(); JournalEntry journalEntry = null; boolean issuccess = false; String msg = ""; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("SP_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = null; status = txnManager.getTransaction(def); try { Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(requestparams); String memo = requestparams.optString("memo", ""); String billid = requestparams.optString("jeid", ""); String sequenceformat = requestparams.optString("sequenceformat", ""); DateFormat df = (DateFormat) requestparams.opt("df"); if (StringUtil.isNullOrEmpty(billid)) { throw new AccountingException("Journal Entry Cannot be Saved"); } else { /** * Delete all JE Details */ accJournalEntryobj.deleteOnEditAccountJEs_optimized(billid); } /** * Copy all data from Original JE */ KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), billid); JournalEntry oldjournalEntry = (JournalEntry) jeresult.getEntityList().get(0); if (oldjournalEntry != null) { if (oldjournalEntry.getSeqformat() != null) { jeDataMap.put(Constants.SEQFORMAT, oldjournalEntry.getSeqformat().getID()); } jeDataMap.put(Constants.SEQNUMBER, oldjournalEntry.getSeqnumber()); jeDataMap.put(Constants.DATEPREFIX, oldjournalEntry.getDatePreffixValue()); jeDataMap.put(Constants.DATEAFTERPREFIX, oldjournalEntry.getDateAfterPreffixValue()); jeDataMap.put(Constants.DATESUFFIX, oldjournalEntry.getDateSuffixValue()); if (!sequenceformat.equals("NA")) { jeDataMap.put("entrynumber", oldjournalEntry.getEntryNumber()); } jeDataMap.put("entrynumber", oldjournalEntry.getEntryNumber()); jeDataMap.put("autogenerated", oldjournalEntry.isAutoGenerated()); jeDataMap.put("entrydate", df.parse(requestparams.optString("entrydate"))); jeDataMap.put("jeisedit", true); jeDataMap.put(Constants.companyKey, oldjournalEntry.getCompany().getCompanyID()); jeDataMap.put("memo", memo); jeDataMap.put(Constants.currencyKey, oldjournalEntry.getCurrency().getCurrencyID()); jeDataMap.put("externalCurrencyRate", oldjournalEntry.getExternalCurrencyRate()); jeDataMap.put("typevalue", oldjournalEntry.getTypeValue()); jeDataMap.put("DontCheckYearLock", true); jeDataMap.put("createdby", oldjournalEntry.getCreatedby().getUserID().toString()); jeDataMap.put("reversejournalentry", oldjournalEntry.getReverseJournalEntry()); jeDataMap.put("isreverseje", oldjournalEntry.isIsReverseJE()); jeDataMap.put("pendingapproval", oldjournalEntry.getPendingapproval()); jeDataMap.put("isReval", oldjournalEntry.getIsReval()); jeDataMap.put("revalInvoiceId", oldjournalEntry.getRevalInvoiceId()); jeDataMap.put("istemplate", 0); jeDataMap.put("typevalue", oldjournalEntry.getTypeValue()); jeDataMap.put("partlyJeEntryWithCnDn", oldjournalEntry.getPartlyJeEntryWithCnDn()); jeDataMap.put("parentid", oldjournalEntry.getParentJE().getID()); if (oldjournalEntry.getParentJE().getAccBillInvCustomData() != null) { jeDataMap.put("accjecustomdataref", oldjournalEntry.getParentJE().getID()); } if (oldjournalEntry.getCostcenter() != null) { jeDataMap.put("costcenterid", oldjournalEntry.getCostcenter().getID()); } if (oldjournalEntry.getPaymentMethod() != null) { jeDataMap.put("pmtmethod", oldjournalEntry.getPaymentMethod().getID()); } } jeDataMap.put("memo", memo); jeDataMap.put("jeisedit", true); jeDataMap.put(JEID, billid); /** * Save Journal Entry */ jeresult = accJournalEntryobj.saveJournalEntry(jeDataMap); journalEntry = (JournalEntry) jeresult.getEntityList().get(0); JSONArray jArr = new JSONArray(requestparams.optString("detail")); /** * Save JE Details */ KwlReturnObject jedresult = accJournalEntryobj.getJEDset(jArr, journalEntry.getCompany().getCompanyID(), journalEntry); HashSet jeDetails = (HashSet) jedresult.getEntityList().get(0); journalEntry.setDetails(jeDetails); accJournalEntryobj.saveJournalEntryDetailsSet(jeDetails); /** * Save Audit Trial */ Map<String, Object> auditTrailMap = new HashMap<String, Object>(); auditTrailMap.put(Constants.useridKey, requestparams.getString("lid")); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + requestparams.optString(Constants.userfullname) + " has updated Journal Entry " + journalEntry.getEntryNumber() + " ", auditTrailMap, journalEntry.getID()); txnManager.commit(status); issuccess = true; msg = messageSource.getMessage("acc.je1.save", null, Locale.forLanguageTag(requestparams.getString("language"))); } catch (SessionExpiredException ex) { if (status != null) { txnManager.rollback(status); } msg = ex.getMessage(); issuccess = false; Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { issuccess = false; if (status != null) { txnManager.rollback(status); } msg = ex.getMessage(); Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jSONObject.put("success", issuccess); jSONObject.put("msg", msg); } catch (JSONException ex) { Logger.getLogger(AccJournalEntryModuleServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } } return jSONObject; } @Override /*Call from Web Application*/ public JSONObject saveJournalEntry(JSONObject paramJObj) { JSONObject jobj = new JSONObject(); JSONObject chequeobj=new JSONObject(); String msg = "", jeid = "", JENumber = ""; boolean issuccess = false; int level=0; JSONObject jobjDetails = new JSONObject(); JSONArray jArr = new JSONArray(); int journalEntryType=0; String pendingForApproval=""; DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("JE_Tx"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); Double jeAmount=0.0; String entryNumber = paramJObj.optString("entryno", null); KwlReturnObject resultForJe = null; String chequeDetail = ""; String repeatedid=""; String intervalType = ""; int intervalUnit = 0; int noOfJEPost = 0; int noOfJERemainPost = 0; Date startdate = null; Date nextdate = null; Date expdate = null; RepeatedJE rje = null; int typeValue = 1;// 1 - Normal JE Entry, 2 - Partly JE Entry, 3- Fund Transfer TransactionStatus status = txnManager.getTransaction(def); String controlAccounts = "Control Account(s): "; boolean isWarning = paramJObj.optString("isWarning", null) != null ? Boolean.parseBoolean(paramJObj.optString("isWarning")) : false; try { String companyid = paramJObj.optString(Constants.companyKey); boolean jeedit = paramJObj.optString("jeedit", null) != null ? Boolean.parseBoolean(paramJObj.optString("jeedit")) : false; chequeDetail = !StringUtil.isNullOrEmpty(paramJObj.optString("chequeDetail", null)) ? paramJObj.optString("chequeDetail") : ""; if (!StringUtil.isNullOrEmpty(paramJObj.optString("typevalue", null))) { typeValue = Integer.parseInt(paramJObj.optString("typevalue")); } /* * ERP-39212 . check cheque number is belongs to any sequence formate or not */ if (typeValue == Constants.FundTransfer_Journal_Entry && !StringUtil.isNullOrEmpty(chequeDetail)) { JSONObject chequeDetailJObj = new JSONObject(chequeDetail); String chequeNumber = chequeDetailJObj.getString("chequeno"); String sequenceFormat = chequeDetailJObj.optString(Constants.sequenceformat); JSONObject chequeParamJObj = new JSONObject(); chequeParamJObj.put(Constants.companyKey, companyid); chequeParamJObj.put("chequeNumber", chequeNumber); chequeParamJObj.put(Constants.sequenceformat, sequenceFormat); List resultList = accCompanyPreferencesObj.checksChequeNumberForSequenceNumber(chequeNumber, companyid); if (!resultList.isEmpty()) { JSONObject resultJObj = new JSONObject(((resultList.get(2) != null) && (!StringUtil.isNullOrEmpty(resultList.get(2).toString()))) ? resultList.get(2).toString() : "{}" ); if (resultJObj.length() > 0) { String seqformatName = resultJObj.optString("formatName"); boolean isSeqnum = resultJObj.optBoolean("isSeqnum"); String seqformatId = resultJObj.optString("formatid"); if (sequenceFormat.equalsIgnoreCase("NA")) { //selected sequence formate is NA and cheque number is belongs to any sequence format. if (isSeqnum) { throw new AccountingException(messageSource.getMessage("acc.common.enterchequenumber", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + chequeNumber + "</b> " + messageSource.getMessage("acc.common.belongsto", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + ". " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + seqformatName + "</b> " + messageSource.getMessage("acc.common.insteadofcheque", null, Locale.forLanguageTag(paramJObj.getString(Constants.language)))); } } else { if (isSeqnum) { //cheque number is belong to other than selected sequence format if(!(sequenceFormat.equals(seqformatId))){ throw new AccountingException(messageSource.getMessage("acc.common.enterchequenumber", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + chequeNumber + "</b> " + messageSource.getMessage("acc.common.notbelongstoselectedsequenceformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + ". " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>"+seqformatName+"</b> " + messageSource.getMessage("acc.common.insteadofcheque", null, Locale.forLanguageTag(paramJObj.getString(Constants.language)))); } } else { //cheque number is not belong to any of the sequence format throw new AccountingException(messageSource.getMessage("acc.common.enterchequenumber", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>" + chequeNumber + "</b> " + messageSource.getMessage("acc.common.notBelongstoAnyOfTheAutoSequenceFormat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + ". " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJObj.getString(Constants.language))) + " <b>NA</b> " + messageSource.getMessage("acc.common.insteadofcheque", null, Locale.forLanguageTag(paramJObj.getString(Constants.language)))); } } } } } /** * createAsTransactionChkboxwithTemplate- used to create template along with transaction. */ boolean createAsTransactionChkboxwithTemplate = paramJObj.optString("createAsTransactionChkbox").equalsIgnoreCase("on") ? true : false; if (!paramJObj.has(Constants.sequenceformat) || StringUtil.isNullOrEmpty(paramJObj.optString(Constants.sequenceformat, null))) { String sequenceformatid = null; SequenceFormat jeSeqFormat = null; Map<String, Object> sfrequestParams = new HashMap<String, Object>(); sfrequestParams.put(Constants.companyKey, paramJObj.get(Constants.companyKey)); sfrequestParams.put("modulename", "autojournalentry"); KwlReturnObject seqFormatResult = accCompanyPreferencesObj.getSequenceFormat(sfrequestParams); List<SequenceFormat> ll = seqFormatResult.getEntityList(); if (ll.isEmpty()) { HashMap<String, Object> requestParams = new HashMap<String, Object>(); requestParams.put("modulename", "autojournalentry"); requestParams.put("numberofdigit", 6); requestParams.put("showleadingzero", true); requestParams.put("prefix", Constants.JE_DEFAULT_PREFIX); requestParams.put("sufix", ""); requestParams.put("startfrom", 0); requestParams.put("name", Constants.JE_DEFAULT_FORMAT); requestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); requestParams.put(Constants.companyKey, paramJObj.get(Constants.companyKey)); jeSeqFormat = accCompanyPreferencesObj.saveSequenceFormat(requestParams); paramJObj.put(Constants.sequenceformat, jeSeqFormat.getID()); } else if (ll.get(0) != null) { SequenceFormat format = (SequenceFormat) ll.get(0); sequenceformatid = format.getID(); paramJObj.put(Constants.sequenceformat, sequenceformatid); } }//end of sequenceformat if (StringUtil.isNullOrEmpty(paramJObj.optString(Constants.sequenceformat, null))) { JSONObject response = StringUtil.getErrorResponse("acc.common.erp33", paramJObj, "Sequence Format Details are missing.", messageSource); throw ServiceException.FAILURE(response.optString(Constants.RES_MESSAGE), "", false); } // List li = saveJournalEntry(paramJObj); /** * creating template for Journal Entry. * istemplate=2 //creating only template * istemplate=0 //creating only transaction */ if (createAsTransactionChkboxwithTemplate) { paramJObj.put("istemplate", 2); saveJournalEntryList(paramJObj); paramJObj.remove("istemplate"); } /** *creating Journal Entry. */ List li = saveJournalEntryList(paramJObj); if (li.get(2) != null) { JENumber = (String) li.get(2); } issuccess = true; KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), (String)li.get(0)); JournalEntry JE = (JournalEntry) jeresult.getEntityList().get(0); String jeId=JE.getID(); Set<JournalEntryDetail> jeDetails = JE.getDetails(); for (JournalEntryDetail journalEntryDetail : jeDetails) { if(journalEntryDetail.isDebit()) // As Debit and credit amount for JE are same , any one type can be picked for calculating amount jeAmount = jeAmount+journalEntryDetail.getAmount(); if( journalEntryDetail.getAccount() != null && !StringUtil.isNullOrEmpty(journalEntryDetail.getAccount().getUsedIn()) ){ controlAccounts += journalEntryDetail.getAccount().getAccountName() + (!StringUtil.isNullOrEmpty(journalEntryDetail.getAccount().getAcccode()) ? " ("+journalEntryDetail.getAccount().getAcccode()+")":"")+","; } } boolean printCheque = StringUtil.isNullOrEmpty(paramJObj.optString("printCheque", null)) ? false : Boolean.parseBoolean(paramJObj.optString("printCheque")); if (printCheque) { KwlReturnObject result = accountingHandlerDAOobj.getObject(PaymentMethod.class.getName(), paramJObj.optString("pmtmethod")); PaymentMethod payMethod = (PaymentMethod) result.getEntityList().get(0); HashMap<String, Object> requestParams = new HashMap<String, Object>(); if (!StringUtil.isNullOrEmpty(payMethod.getID())) { requestParams.put("bankid", payMethod.getID()); } boolean isnewlayout = false; ChequeLayout chequeLayout=null; DateFormat DATE_FORMAT = new SimpleDateFormat(Constants.DEFAULT_FORMAT_CHECK); String prefixbeforamt = ""; KwlReturnObject result1 = accPaymentDAOobj.getChequeLayout(requestParams); List list = result1.getEntityList(); Iterator itr = list.iterator(); while (itr.hasNext()) { chequeLayout = (ChequeLayout) itr.next(); chequeobj = new JSONObject(chequeLayout.getCoordinateinfo()); jobjDetails.put("dateLeft", chequeobj.optString("dateLeft","0")); jobjDetails.put("nameLeft", chequeobj.optString("nameLeft","0")); jobjDetails.put("amtinwordLeft", chequeobj.optString("amtinwordLeft","0")); jobjDetails.put("amtinwordLeftLine2", chequeobj.optString("amtinwordLeftLine2","0")); jobjDetails.put("amtLeft", chequeobj.optString("amtLeft","0")); jobjDetails.put("dateTop", chequeobj.optString("dateTop","0")); jobjDetails.put("nameTop", chequeobj.optString("nameTop","0")); jobjDetails.put("amtinwordTop", chequeobj.optString("amtinwordTop","0")); jobjDetails.put("amtinwordTopLine2", chequeobj.optString("amtinwordTopLine2","0")); jobjDetails.put("amtTop", chequeobj.optString("amtTop","0")); String dateformat = chequeLayout.getDateFormat().getJavaForm(); /* If 'AddCharacterInCheckDate' is true then don't remove '/' or '-' from check Date */ if (!chequeLayout.isAddCharacterInCheckDate()) { dateformat = dateformat.replaceAll("/", ""); dateformat = dateformat.replaceAll("-", ""); } DATE_FORMAT = new SimpleDateFormat(dateformat); prefixbeforamt = chequeLayout.getAppendcharacter(); isnewlayout = chequeLayout.isIsnewlayout(); } String formatted_date_with_spaces = ""; chequeDetail = paramJObj.optString("chequeDetail", null); if (!StringUtil.isNullOrEmpty(chequeDetail)) { JSONObject obj = new JSONObject(chequeDetail); Date cdate = new Date(obj.getString("payDate")); String chackdate = DATE_FORMAT.format(cdate); if (chequeLayout!=null && chequeLayout.isAddCharacterInCheckDate()) { formatted_date_with_spaces=chackdate; } else { for (int i = 0; i < chackdate.length(); i++) { formatted_date_with_spaces += chackdate.charAt(i); formatted_date_with_spaces += isnewlayout ? "&nbsp;&nbsp;&nbsp;" : "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; } } } String[] amount = (String[]) li.get(3); String[] amount1 = (String[]) li.get(4); String[] accName = (String[]) li.get(5); jobjDetails.put(amount[0], prefixbeforamt+amount[1]); String amount_first_line = ""; String amount_second_line = ""; String action=" Only."; if (amount1[1].length() > 34 && amount1[1].charAt(34) == ' ') { amount_first_line = amount1[1].substring(0, 34); amount_second_line = amount1[1].substring(34, amount1[1].length()); jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line +action); } else if (amount1[1].length() > 34) { amount_first_line = amount1[1].substring(0, 34); amount_first_line = amount1[1].substring(0, amount_first_line.lastIndexOf(" ")); amount_second_line = amount1[1].substring(amount_first_line.length(), amount1[1].length()); jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line + action); } else { if (amount1[1].length() < 27) { jobjDetails.put(amount1[0], amount1[1] + action); jobjDetails.put("amountinword1", ""); } else { jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", action); } } jobjDetails.put(accName[0], accName[1]); jobjDetails.put("date", formatted_date_with_spaces); jobjDetails.put("isnewlayout", isnewlayout); boolean isFontStylePresent = chequeobj.has("fontStyle") && !StringUtil.isNullOrEmpty(chequeobj.getString("fontStyle")) ? true : false; String fontStyle = chequeobj.has("fontStyle") && !StringUtil.isNullOrEmpty(chequeobj.getString("fontStyle")) ? chequeobj.getString("fontStyle") : ""; char fontStyleChar; if (fontStyle.equals("1")) { fontStyleChar = 'b'; } else if (fontStyle.equals("2")) { fontStyleChar = 'i'; } else { fontStyleChar = 'p'; } //for name if (chequeobj.has("dateFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("dateFontSize"))) { formatted_date_with_spaces = "<font size=" + chequeobj.getString("dateFontSize") + "><" + fontStyleChar + ">" + formatted_date_with_spaces + "</" + fontStyleChar + "></font> "; jobjDetails.put("date", formatted_date_with_spaces); } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("dateFontSize"))) { formatted_date_with_spaces = "<font size=" + chequeobj.getString("dateFontSize") + ">" + formatted_date_with_spaces + "</font> "; jobjDetails.put("date", formatted_date_with_spaces); } else { formatted_date_with_spaces = "<" + fontStyleChar + ">" + formatted_date_with_spaces + "</" + fontStyleChar + ">"; jobjDetails.put("date", formatted_date_with_spaces); } } //for name if (chequeobj.has("nameFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("nameFontSize"))) { accName[1] = "<font size=" + chequeobj.getString("nameFontSize") + "><" + fontStyleChar + ">" + accName[1] + "</" + fontStyleChar + "></font> "; jobjDetails.put(accName[0], accName[1]); } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("nameFontSize"))) { accName[1] = "<font size=" + chequeobj.getString("nameFontSize") + ">" + accName[1] + "</font> "; jobjDetails.put(accName[0], accName[1]); } else { accName[1] = "<" + fontStyleChar + ">" + accName[1] + "</" + fontStyleChar + ">"; jobjDetails.put(accName[0], accName[1]); } } //for amount in words if (chequeobj.has("amountInWordsFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("amountInWordsFontSize"))) { amount_first_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + "><" + fontStyleChar + ">" + amount_first_line + "</" + fontStyleChar + "></font> "; amount_second_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + "><" + fontStyleChar + ">" + amount_second_line +" "+action+ "</" + fontStyleChar + "></font> "; if (amount1[1].length() > 34) { jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line); } else if (amount1[1].length() < 27) { amount1[1] = "<font size=" + chequeobj.getString("amountInWordsFontSize") + "><" + fontStyleChar + ">" + amount1[1] +" "+action+ "</" + fontStyleChar + "></font> "; jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", ""); } } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("amountInWordsFontSize"))) { amount_first_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + ">" + amount_first_line + "</font> "; amount_second_line = "<font size=" + chequeobj.getString("amountInWordsFontSize") + ">" + amount_second_line +" "+action+ "</font> "; if (amount1[1].length() > 34) { jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line); } else if (amount1[1].length() < 27) { amount1[1] = "<font size=" + chequeobj.getString("amountInWordsFontSize") + ">" + amount1[1] +" "+action+ "</font> "; jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", ""); } } else { amount_first_line = "<" + fontStyleChar + ">" + amount_first_line + "</" + fontStyleChar + ">"; amount_second_line = "<" + fontStyleChar + ">" + amount_second_line +" "+action+ "</" + fontStyleChar + ">"; if (amount1[1].length() > 34) { jobjDetails.put(amount1[0], amount_first_line); jobjDetails.put("amountinword1", amount_second_line); } else if (amount1[1].length() < 27) { amount1[1] = "<" + fontStyleChar + ">" + amount1[1] +" "+action+ "</" + fontStyleChar + ">"; jobjDetails.put(amount1[0], amount1[1]); jobjDetails.put("amountinword1", ""); } } } //for amount in number if (chequeobj.has("amountFontSize") || isFontStylePresent) { if (isFontStylePresent && !StringUtil.isNullOrEmpty(chequeobj.getString("amountFontSize"))) { amount[1] = "<font size=" + chequeobj.getString("amountFontSize") + "><" + fontStyleChar + ">" + prefixbeforamt+amount[1] + "</" + fontStyleChar + "></font> "; jobjDetails.put(amount[0], amount[1]); } else if (!StringUtil.isNullOrEmpty(chequeobj.getString("amountFontSize"))) { amount[1] = "<font size=" + chequeobj.getString("amountFontSize") + ">" + prefixbeforamt+amount[1] + "</font> "; jobjDetails.put(amount[0], amount[1]); } else { amount[1] = "<" + fontStyleChar + ">" + prefixbeforamt+amount[1] + "</" + fontStyleChar + ">"; jobjDetails.put(amount[0], amount[1]); } } jArr.put(jobjDetails); jeid=JE.getID(); String chequeno=""; if (li.get(6) != null) { chequeno = (String) li.get(6); } KwlReturnObject result2 = accJournalEntryobj.updateChequePrint(jeid,companyid); Map<String, Object> insertLogParams = new HashMap<String, Object>(); insertLogParams.put(Constants.reqHeader, (paramJObj.has(Constants.reqHeader) && paramJObj.get(Constants.reqHeader) != null) ? paramJObj.getString(Constants.reqHeader) : paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.remoteIPAddress, paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.useridKey, paramJObj.optString(Constants.useridKey)); // auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has printed a cheque "+chequeno+" for "+StringUtil.serverHTMLStripper(accName[1]) +" in Fund Transfer " + JENumber, request, jeid); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has printed a cheque " + chequeno + " for " + StringUtil.serverHTMLStripper(accName[1]) + " in Fund Transfer " + JENumber, insertLogParams, jeid); } if (!StringUtil.isNullOrEmpty(chequeDetail) && li.get(7) != null) { rje = (RepeatedJE) li.get(7); if (rje != null) { repeatedid = rje.getId(); intervalUnit = rje.getIntervalUnit(); intervalType = rje.getIntervalType(); noOfJEPost = rje.getNoOfJEpost(); noOfJERemainPost = rje.getNoOfRemainJEpost(); startdate = rje.getStartDate(); nextdate = rje.getNextDate(); expdate = rje.getExpireDate(); } } else if(StringUtil.isNullOrEmpty(chequeDetail) && li.get(3) != null) { rje = (RepeatedJE) li.get(3); if (rje != null) { repeatedid = rje.getId(); intervalUnit = rje.getIntervalUnit(); intervalType = rje.getIntervalType(); noOfJEPost = rje.getNoOfJEpost(); noOfJERemainPost = rje.getNoOfRemainJEpost(); startdate = rje.getStartDate(); nextdate = rje.getNextDate(); expdate = rje.getExpireDate(); } } txnManager.commit(status); String sequenceformat = paramJObj.optString("sequenceformat", "NA"); TransactionStatus AutoNoStatus = null; try { synchronized (this) { DefaultTransactionDefinition def1 = new DefaultTransactionDefinition(); def1.setName("AutoNum_Tx"); if (paramJObj.optBoolean(Constants.isdefaultHeaderMap)) {//same transaction is used to commit def1.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); } else { def1.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); } AutoNoStatus = txnManager.getTransaction(def1); if (sequenceformat.equals("NA") && !jeedit) { resultForJe = accJournalEntryobj.getJECount(entryNumber, companyid); while (resultForJe.getRecordTotalCount() > 0) { entryNumber = entryNumber + "-1"; resultForJe = accJournalEntryobj.getJECount(entryNumber, companyid); } JENumber = accJournalEntryobj.updateJEEntryNumberForNA(jeId, entryNumber); JE.setEntryNumber(entryNumber); } if (!jeedit && (!StringUtil.isNullOrEmpty(sequenceformat) && !sequenceformat.equals("NA"))) { //Post New JE with auto generated Entry No. // status = txnManager.getTransaction(def); Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJObj); // entryNumber = updateJEEntryNumberForNewJE(jeDataMap, JE, companyid, sequenceformat,JE.getPendingapproval()); KwlReturnObject returnObj = updateJEEntryNumberForNewJE(jeDataMap, JE, companyid, sequenceformat,JE.getPendingapproval()); if(returnObj.isSuccessFlag() && returnObj.getRecordTotalCount()>0){ entryNumber = (String) returnObj.getEntityList().get(0); } JENumber = entryNumber; } } } catch (Exception ex) { if (AutoNoStatus != null) { txnManager.rollback(AutoNoStatus); } Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } finally { if (AutoNoStatus != null) { txnManager.commit(AutoNoStatus); } } int approvalStatusLevel =11; journalEntryType = JE.getTypeValue(); String msgKey = ""; String currentUserId = paramJObj.optString(Constants.useridKey); // if (journalEntryType != 2) { // Currently , Party Journal Entry is excluded from the approval rules. approvalStatusLevel = approveJE(JE, paramJObj.optString(Constants.companyKey), level, String.valueOf(jeAmount), paramJObj, true, currentUserId); if (approvalStatusLevel != 11) { pendingForApproval = messageSource.getMessage("acc.field.butpendingforApproval", null, Locale.forLanguageTag(paramJObj.optString("language"))); msgKey = "acc.je2.save"; }else{ msgKey = "acc.je1.save"; } // } int istemplate = 0; if (!StringUtil.isNullOrEmpty(paramJObj.optString("istemplate", null))) { istemplate = Integer.parseInt(paramJObj.optString("istemplate")); } if (istemplate == 1) { msg = messageSource.getMessage("acc.field.JournalEntryandTemplatehasbeensavedsuccessfully", null, Locale.forLanguageTag(paramJObj.optString("language"))) + " " + pendingForApproval + "<br/>JE No: <b>" + JENumber + "</b>"; //"Journal Entry and Template has been saved successfully."; } else if (istemplate == 2) { msg = messageSource.getMessage("acc.field.JournalEntryTemplatehasbeensavedsuccessfully", null, Locale.forLanguageTag(paramJObj.optString("language"))); //"Journal Entry Template has been saved successfully."; } else { msg = messageSource.getMessage(msgKey, null, Locale.forLanguageTag(paramJObj.getString("language"))) + " " + pendingForApproval + "<br/>JE No: <b>" + JENumber + "</b>"; //"Journal Entry has been saved successfully"; if (!StringUtil.isNullOrEmpty(paramJObj.optString("createAsTransactionChkbox", "")) && paramJObj.optString("createAsTransactionChkbox").equalsIgnoreCase("on") && !StringUtil.isNullOrEmpty(paramJObj.optString("templatename", ""))) { msg += " Template Name: <b>" + paramJObj.optString("templatename", "") + "</b>"; } } String template = " template for record "; if (istemplate == 0) { template = ""; } String action = "added new"; if (jeedit == true) { action = "updated"; } Map<String, Object> insertLogParams = new HashMap<String, Object>(); insertLogParams.put(Constants.reqHeader, (paramJObj.has(Constants.reqHeader) && paramJObj.get(Constants.reqHeader) != null) ? paramJObj.getString(Constants.reqHeader) : paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.remoteIPAddress, paramJObj.optString(Constants.remoteIPAddress)); insertLogParams.put(Constants.useridKey, paramJObj.optString(Constants.useridKey)); // auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has " + action + template + " Journal Entry " + JE.getEntryNumber()+(approvalStatusLevel != 11 ? " "+messageSource.getMessage("acc.field.whichispendingforApproval", null, null) : "") + (!controlAccounts.equals("Control Account(s): ") ? ". "+controlAccounts.substring(0, controlAccounts.length()-1) :""), request, JE.getID()); auditTrailObj.insertAuditLog(AuditAction.JOURNAL_ENTRY_MADE, "User " + paramJObj.optString(Constants.userfullname) + " has " + action + template + " Journal Entry " + JE.getEntryNumber() + (approvalStatusLevel != 11 ? " " + messageSource.getMessage("acc.field.whichispendingforApproval", null, null) : "") + (!controlAccounts.equals("Control Account(s): ") ? ". " + controlAccounts.substring(0, controlAccounts.length() - 1) : ""), insertLogParams, JE.getID()); if (!StringUtil.isNullOrEmpty(paramJObj.optString("createAsTransactionChkbox", "")) && paramJObj.optString("createAsTransactionChkbox").equalsIgnoreCase("on") && !StringUtil.isNullOrEmpty(paramJObj.optString("templatename", ""))) { auditTrailObj.insertAuditLog(AuditAction.TEMPLATE_CREATED, "User " + paramJObj.optString(Constants.userfullname) + " has " + action + " Document Template "+paramJObj.optString("templatename", "")+ " for record Journal Entry" , insertLogParams, JE.getID()); } jeid = li.get(0) != null ? (String) li.get(0) : ""; if (jeedit) { String oldjeid = (String) li.get(1); status = txnManager.getTransaction(def); deleteJEArray(oldjeid,journalEntryType,companyid); txnManager.commit(status); } } catch (SessionExpiredException ex) { txnManager.rollback(status); msg = ex.getMessage(); Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { txnManager.rollback(status); msg = "" + ex.getMessage(); Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } finally { try { jobj.put("success", issuccess); jobj.put("repeatedid", repeatedid); jobj.put("intervalUnit", intervalUnit); jobj.put("intervalType", intervalType); jobj.put("noOfJEPost", noOfJEPost); jobj.put("noOfJERemainPost", noOfJERemainPost); jobj.put("typeValue", typeValue); jobj.put("billno", JENumber); jobj.put("startdate", startdate); jobj.put("nextdate", nextdate); jobj.put("expdate", expdate); jobj.put("msg", msg); jobj.put("id", jeid); jobj.put("data", jArr); jobj.put("isWarning",isWarning); } catch (JSONException ex) { Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } } return jobj; } public List saveJournalEntryList(JSONObject paramJobj) throws SessionExpiredException, ServiceException, AccountingException { JournalEntry je = null; List ll = new ArrayList(); try { int istemplate = paramJobj.optString("istemplate", null) != null ? Integer.parseInt(paramJobj.optString("istemplate")) : 0; String companyid = paramJobj.optString(Constants.companyKey); String createdby = paramJobj.optString(Constants.useridKey); String entryNumber = paramJobj.optString("entryno", null); String jeid = ""; RepeatedJE rje = null; String oldjeid = ""; int typeValue = 1;// 1 - Normal JE Entry, 2 - Partly JE Entry, 3- Fund Transfer boolean jeedit = false; boolean isdeletecndnwithJE=false; String chequeno=""; String sequenceformat = paramJobj.optString("sequenceformat", "NA"); String jeId = paramJobj.optString("jeid", null); boolean isWarning = paramJobj.optString("isWarning", null) != null ? Boolean.parseBoolean(paramJobj.optString("isWarning")) : false; boolean includeInGSTReport = paramJobj.optString("includeingstreport", null) != null ? Boolean.parseBoolean(paramJobj.optString("includeingstreport")) : false; if (istemplate != 2 && sequenceformat.equals("NA")) { if(StringUtil.isNullOrEmpty(entryNumber)) // entryNumber is set to be blank in case of istemplate=2 (in template creation case) throw new AccountingException(messageSource.getMessage("acc.je1.excp2", null, Locale.forLanguageTag(paramJobj.optString("language")))); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("jeedit", null))) { jeedit = Boolean.parseBoolean(paramJobj.optString("jeedit")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("isdeletecndnwithJE", null))) { isdeletecndnwithJE = Boolean.parseBoolean(paramJobj.optString("isdeletecndnwithJE")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("typevalue", null))) { typeValue = Integer.parseInt(paramJobj.optString("typevalue")); } if (istemplate != 2 && sequenceformat.equals("NA") && jeedit) { // KwlReturnObject result = accJournalEntryobj.getJECountForEdit(entryNumber, companyid,jeId); int nocount = result.getRecordTotalCount(); if (nocount > 0) { throw new AccountingException("Journal entry number '" + entryNumber + "' already exists."); } } if (istemplate != 2 && sequenceformat.equals("NA")) {//In case of NA checks wheather this number can also be generated by a sequence format or not List list = accCompanyPreferencesObj.checksEntryNumberForSequenceNumber(Constants.Acc_GENERAL_LEDGER_ModuleId, entryNumber, companyid); if (!list.isEmpty()) { boolean isvalidEntryNumber = (Boolean) list.get(0); String formatName = (String) list.get(1); if (!isvalidEntryNumber) { throw new AccountingException(messageSource.getMessage("acc.common.enterdocumentnumber", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + entryNumber + "</b> " + messageSource.getMessage("acc.common.belongsto", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + formatName + "</b>. " + messageSource.getMessage("acc.common.plselectseqformat", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + formatName + "</b> " + messageSource.getMessage("acc.common.insteadof", null, Locale.forLanguageTag(paramJobj.optString("language")))); } } } int countryLanguageId = Constants.OtherCountryLanguageId; // 0 KwlReturnObject extraprefresult = accountingHandlerDAOobj.getObject(ExtraCompanyPreferences.class.getName(), companyid); ExtraCompanyPreferences extraCompanyPreferences = extraprefresult != null ? (ExtraCompanyPreferences) extraprefresult.getEntityList().get(0) : null; if (extraCompanyPreferences.isAmountInIndianWord()) { countryLanguageId = Constants.CountryIndiaLanguageId; //for india id is 1; } double externalCurrencyRate = StringUtil.getDouble(paramJobj.optString("externalcurrencyrate", "1")); DateFormat df = authHandler.getDateOnlyFormat(); Map<String, Object> jeDataMap = AccountingManager.getGlobalParamsJson(paramJobj); // Check Cheque Detail is available or Not BigInteger oldChqNoIntValue = new BigInteger("0"); BigInteger chequesequencenumber = new BigInteger("0"); String chequeDetail = paramJobj.optString("chequeDetail", null); if (!StringUtil.isNullOrEmpty(chequeDetail)) { JSONObject obj = new JSONObject(chequeDetail); HashMap chequehm = new HashMap(); // cheque whether Cheque Number exist or not if already exist then don't let it save String oldChqNo = ""; if (jeedit) { String oldje = paramJobj.optString("jeid", null); KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), oldje); JournalEntry oldjournalEntry = (JournalEntry) jeresult.getEntityList().get(0); if (oldjournalEntry != null && oldjournalEntry.getCheque() != null) { oldChqNo = oldjournalEntry.getCheque().getChequeNo(); oldChqNoIntValue = oldjournalEntry.getCheque().getSequenceNumber(); } } KwlReturnObject companypref = accountingHandlerDAOobj.getObject(CompanyAccountPreferences.class.getName(), companyid); CompanyAccountPreferences compPref = (CompanyAccountPreferences)companypref.getEntityList().get(0); int chequeNoDuplicationSetting = compPref.getChequeNoDuplicate(); BigInteger nextSeqNumber = new BigInteger("0"); boolean checkForNextSequenceNumberAlso = true; boolean isChequeNumberInString = false; if (extraCompanyPreferences != null) { try {// USER can enter String values also in such case exception will come nextSeqNumber = new BigInteger(obj.getString("chequeno")); } catch (Exception ex) { checkForNextSequenceNumberAlso = false; isChequeNumberInString = true; } } else { checkForNextSequenceNumberAlso = false; } boolean isChequeNumberAvailable = false; boolean isEditCaseButChqNoChanged = false; if (!StringUtil.isNullOrEmpty(obj.optString("chequeno"))) { try {// OLD CHQ NO. can be String value also in such case exception will come HashMap chequeNohm = new HashMap(); chequeNohm.put("companyId", companyid); chequeNohm.put("nextChequeNumber", obj.optString("chequeno")); chequeNohm.put("sequenceNumber", nextSeqNumber); chequeNohm.put("checkForNextSequenceNumberAlso", checkForNextSequenceNumberAlso); chequeNohm.put("bankAccountId", obj.getString("bankAccountId")); JSONObject ChJobj = accCompanyPreferencesObj.isChequeNumberAvailable(chequeNohm); isChequeNumberAvailable = ChJobj.optBoolean("isChequeNumberAvailable"); chequesequencenumber =new BigInteger(ChJobj.optString("chequesequencenumber")); // if (!StringUtil.isNullOrEmpty(oldChqNo)) { // oldChqNoIntValue = new BigInteger(oldChqNo); // } if (!oldChqNoIntValue.equals(chequesequencenumber)) { isEditCaseButChqNoChanged = true; } if (isChequeNumberInString) { if (!oldChqNo.equals(obj.optString("chequeno"))) { isEditCaseButChqNoChanged = true; } } } catch (Exception ex) { if (!oldChqNo.equals(obj.optString("chequeno"))) { isEditCaseButChqNoChanged = true; } } } else { if (!oldChqNo.equals(obj.optString("chequeno"))) { isEditCaseButChqNoChanged = true; } } if (chequeNoDuplicationSetting == Constants.ChequeNoBlock || (chequeNoDuplicationSetting == Constants.ChequeNoWarn && isWarning)) { if (!StringUtil.isNullOrEmpty(obj.optString("chequeno")) && isChequeNumberAvailable && isEditCaseButChqNoChanged) { String msgForException = "Cheque Number : <b>" + obj.getString("chequeno") + "</b> is already exist. "; if (isWarning) { throw new AccountingException(msgForException+" "+messageSource.getMessage("acc.recurringMP.doYouWantToContinue", null, Locale.forLanguageTag(paramJobj.optString("language")))); } else { throw new AccountingException(msgForException + "Please enter different one. "); } } String chequeNumber = obj.optString("chequeno"); chequeNumber = "'" + chequeNumber + "'"; HashMap<String, Object> requestMap = new HashMap(); requestMap.put("bankAccountId", obj.getString("bankAccountId")); requestMap.put("chequeNumber", chequeNumber); KwlReturnObject resultRepeatedPaymentChequeDetails = accPaymentDAOobj.getRepeatedPaymentChequeDetailsForPaymentMethod(requestMap); List RPCD = resultRepeatedPaymentChequeDetails.getEntityList(); if (RPCD.size() > 0) { Object[] object = (Object[]) RPCD.get(0); String paymentNumber = (String) object[1]; String msgForException = messageSource.getMessage("acc.field.ChequeNumber", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " : <b>" + obj.getString("chequeno") + "</b> " + messageSource.getMessage("acc.recurringMP.chequeNoReserverd", null, Locale.forLanguageTag(paramJobj.optString("language"))) + " <b>" + paymentNumber + "</b>. "; if (isWarning) { throw new AccountingException(msgForException + " " + messageSource.getMessage("acc.recurringMP.doYouWantToContinue", null, Locale.forLanguageTag(paramJobj.optString("language")))); } else { throw new AccountingException(msgForException + messageSource.getMessage("acc.recurringMP.enteranotherChequeNo", null, Locale.forLanguageTag(paramJobj.optString("language")))); } } } String chequeseqformatID = obj.optString("sequenceformat",""); chequehm.put(Constants.SEQFORMAT, chequeseqformatID); if (!chequeseqformatID.equalsIgnoreCase("NA") && !chequeseqformatID.equalsIgnoreCase("")){ chequehm.put("isAutoGeneratedChequeNumber", true); } Map<String, Object> seqchequehm = new HashMap<>(); obj.put(Constants.companyKey, companyid); /** * getNextChequeNumber method to generate next sequence number using * sequence format,also saving the dateprefix and datesuffix in cheque table. */ obj.put(Constants.companyKey, companyid); obj.put("ischequeduplicatepref", compPref.getChequeNoDuplicate()); if (!StringUtil.isNullOrEmpty(sequenceformat) && !sequenceformat.equals("NA")) { //Edit case- check pevious check number and new entered number are same then no need to generate next number else generate next number. if(isEditCaseButChqNoChanged){//create and copy case- generate next number. seqchequehm = accCompanyPreferencesObj.getNextChequeNumber(obj); } } chequehm.put("companyId", companyid); chequehm.put("bankAccount", obj.getString("bankAccountId")); chequehm.put("createdFrom", 3); chequehm.put("sequenceNumber", chequesequencenumber); chequehm.put("chequeno", obj.optString("chequeno")); chequehm.put("description", StringUtil.DecodeText(obj.optString("description"))); chequehm.put("bankname", StringUtil.DecodeText(obj.optString("bankname"))); chequehm.put("duedate", df.parse(obj.getString("payDate"))); if (seqchequehm!=null&&!StringUtil.isNullOrEmpty(sequenceformat) && !sequenceformat.equals("NA") && seqchequehm.containsKey(Constants.SEQNUMBER)) { chequehm.put("sequenceNumber", (String) seqchequehm.get(Constants.SEQNUMBER)); } KwlReturnObject cqresult = accPaymentDAOobj.addCheque(chequehm); Cheque cheque = (Cheque) cqresult.getEntityList().get(0); if (cheque != null) { jeDataMap.put(CCConstants.JSON_cheque, cheque.getID()); chequeno=cheque.getChequeNo(); } } String costCenterId = paramJobj.optString(CCConstants.REQ_costcenter, null); jeDataMap.put(Constants.companyKey, companyid); jeDataMap.put("createdby", createdby); jeDataMap.put("entrydate", df.parse(paramJobj.optString("entrydate"))); jeDataMap.put("memo", paramJobj.optString("memo")); if(jeedit){ jeDataMap.put("entrynumber", entryNumber); } else { jeDataMap.put("entrynumber", ""); } jeDataMap.put("autogenerated", sequenceformat.equals("NA") ? false : true); //nextJEAutoNo.equals(entryNumber)); jeDataMap.put(Constants.currencyKey,paramJobj.optString(Constants.currencyKey)); jeDataMap.put("externalCurrencyRate", externalCurrencyRate); jeDataMap.put("typevalue", typeValue); jeDataMap.put("istemplate", istemplate); if (!StringUtil.isNullOrEmpty(paramJobj.optString("parentje", null))) { jeDataMap.put("parentid", paramJobj.optString("parentje")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("repeateid", null))) { jeDataMap.put("repeateid", paramJobj.optString("repeateid")); } if (jeedit) { oldjeid = paramJobj.optString("jeid", null); KwlReturnObject jeresult = accountingHandlerDAOobj.getObject(JournalEntry.class.getName(), oldjeid); JournalEntry oldjournalEntry = (JournalEntry) jeresult.getEntityList().get(0); if (oldjournalEntry != null) { if (oldjournalEntry.getSeqformat() != null) { jeDataMap.put(Constants.SEQFORMAT, oldjournalEntry.getSeqformat().getID()); } jeDataMap.put(Constants.SEQNUMBER, oldjournalEntry.getSeqnumber()); jeDataMap.put(Constants.DATEPREFIX, oldjournalEntry.getDatePreffixValue()); jeDataMap.put(Constants.DATEAFTERPREFIX, oldjournalEntry.getDateAfterPreffixValue()); jeDataMap.put(Constants.DATESUFFIX, oldjournalEntry.getDateSuffixValue()); if (!sequenceformat.equals("NA")) { jeDataMap.put("entrynumber", oldjournalEntry.getEntryNumber()); } jeDataMap.put("autogenerated", oldjournalEntry.isAutoGenerated()); /* Saving previous status of flag isfromeclaim At the time of edit JE */ boolean isFromEclaim = oldjournalEntry.isIsFromEclaim(); jeDataMap.put("isFromEclaim", isFromEclaim); } try { if (isdeletecndnwithJE) { KwlReturnObject cnresult= accJournalEntryobj.getCNFromJE(oldjeid, companyid); List list=cnresult.getEntityList(); if(!list.isEmpty()){ accJournalEntryobj.deletePartyJournalCN(list, companyid); } cnresult = accJournalEntryobj.getDNFromJE(oldjeid, companyid); list=cnresult.getEntityList(); if(!list.isEmpty()){ accJournalEntryobj.deletePartyJournalDN(list, companyid); } } //Delete entry from optimized table accJournalEntryobj.deleteOnEditAccountJEs_optimized(oldjeid); } catch (ServiceException ex) { if(!StringUtil.isNullObject(typeValue) && typeValue==Constants.Party_Journal_Entry){ throw new AccountingException("CN/DN are already used in other transaction(s)."); } else{ throw new AccountingException("Journal entry details are already in use."); } } jeDataMap.put("jeisedit", true); } if (!StringUtil.isNullOrEmpty(costCenterId)) { jeDataMap.put(CCConstants.JSON_costcenterid, costCenterId); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("paidToCmb", null))) { jeDataMap.put("paidToCmb", paramJobj.optString("paidToCmb")); } if (!StringUtil.isNullOrEmpty(paramJobj.optString("pmtmethod", null))) { jeDataMap.put("pmtmethod", paramJobj.optString("pmtmethod")); } jeDataMap.put("includeInGSTReport", includeInGSTReport); boolean isFromEclaim = paramJobj.has(Constants.isFromEclaim) ? paramJobj.getBoolean(Constants.isFromEclaim) : false; jeDataMap.put("isFromEclaim", isFromEclaim); jeDataMap.put(GSTRTYPE, paramJobj.optInt(GSTRTYPE,0)); jeDataMap.put(ITC_TRANSACTION_IDS, paramJobj.optString(ITC_TRANSACTION_IDS)); KwlReturnObject jeresult = accJournalEntryobj.saveJournalEntry(jeDataMap); je = (JournalEntry) jeresult.getEntityList().get(0); JSONArray jArr = new JSONArray(paramJobj.optString("detail", "[]")); if (jArr.length()== 0) { JSONObject response = StringUtil.getErrorResponse("acc.common.erp32", paramJobj, "Account Details are missing.", messageSource); throw ServiceException.FAILURE(response.optString(Constants.RES_MESSAGE), "", false); } KwlReturnObject jedresult = accJournalEntryobj.getJEDset(jArr, companyid,je); if (je.getTypeValue() == 3) { // typeValue: 3 Fund Transfer JE jArr = StringUtil.sortJsonArray(jArr, "debit", false, false); } HashSet jeDetails = (HashSet) jedresult.getEntityList().get(0); je.setDetails(jeDetails); accJournalEntryobj.saveJournalEntryDetailsSet(jeDetails); jeid = je.getID(); ll.add(jeid); ll.add(oldjeid); ll.add(je.getEntryNumber()); /* * Make custom field entry at line level */ double amount=0.0; for (Iterator<JournalEntryDetail> jEDIterator = jeDetails.iterator(); jEDIterator.hasNext();) { JournalEntryDetail jed = jEDIterator.next(); int srno = 0; if (!jed.isDebit()) { //check print credit amount amount = jed.getAmount(); } if (jed.getSrno() != 0) { srno = jed.getSrno(); JSONObject jobj = jArr.getJSONObject(--srno); if (!StringUtil.isNullOrEmpty(jobj.optString("customfield", ""))) { JSONArray jcustomarray = new JSONArray(jobj.optString("customfield", "[]")); if (jcustomarray.length() > 0 && isFromEclaim) { jcustomarray = fieldDataManagercntrl1.GetJsonArrayUsingFieldIds(jcustomarray, Constants.Acc_GENERAL_LEDGER_ModuleId, companyid, false); } HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); customrequestParams.put("customarray", jcustomarray); customrequestParams.put("modulename", Constants.Acc_JEDetail_modulename); customrequestParams.put("moduleprimarykey", Constants.Acc_JEDetailId);// Constants.Acc_JEDetail_recdetailId customrequestParams.put("modulerecid", jed.getID()); customrequestParams.put("recdetailId", jed.getID()); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("customdataclasspath", Constants.Acc_BillInvDetail_custom_data_classpath); KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams); if (customDataresult != null && customDataresult.getEntityList().size() > 0) { //jed.setAccJEDetailCustomData((AccJEDetailCustomData) hibernateTemplate.get(AccJEDetailCustomData.class, jed.getID())); JSONObject jedjson = new JSONObject(); jedjson.put("accjedetailcustomdata", jed.getID()); jedjson.put("jedid", jed.getID()); jedresult = accJournalEntryobj.updateJournalEntryDetails(jedjson); } } } } /* * Make custom field entry */ String customfield = paramJobj.optString("customfield", null); if (!StringUtil.isNullOrEmpty(customfield)) { JSONArray jcustomarray = new JSONArray(customfield); if (jcustomarray.length() > 0 && isFromEclaim) { jcustomarray = fieldDataManagercntrl1.GetJsonArrayUsingFieldIds(jcustomarray, Constants.Acc_GENERAL_LEDGER_ModuleId, companyid, true); } HashMap<String, Object> customrequestParams = new HashMap<String, Object>(); customrequestParams.put("customarray", jcustomarray); customrequestParams.put("modulename", Constants.Acc_JE_modulename); customrequestParams.put("moduleprimarykey", Constants.Acc_JEid); customrequestParams.put("modulerecid", jeid); customrequestParams.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); customrequestParams.put(Constants.companyKey, companyid); customrequestParams.put("customdataclasspath", Constants.Acc_BillInv_custom_data_classpath); KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams); if (customDataresult != null && customDataresult.getEntityList().size() > 0) { Map<String, Object> customjeDataMap = new HashMap<String, Object>(); customjeDataMap.put("accjecustomdataref", jeid); customjeDataMap.put("jeid", jeid); customjeDataMap.put("istemplate", istemplate); jeresult = accJournalEntryobj.updateCustomFieldJournalEntry(customjeDataMap); } } //Save record as template if (!StringUtil.isNullOrEmpty(paramJobj.optString("templatename", null)) && (istemplate == 1 || istemplate == 2)) { HashMap<String, Object> hashMap = new HashMap<String, Object>(); String moduletemplateid = paramJobj.optString("moduletemplateid", null); hashMap.put("templatename", paramJobj.optString("templatename", null)); if (!StringUtil.isNullOrEmpty(moduletemplateid)) { hashMap.put("moduletemplateid", moduletemplateid); } hashMap.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); hashMap.put("modulerecordid", jeid); hashMap.put(Constants.companyKey, companyid); /** * checks the template name is already exist in create and * edit template case */ KwlReturnObject result = accountingHandlerDAOobj.getModuleTemplateForTemplatename(hashMap); int nocount = result.getRecordTotalCount(); if (nocount > 0) { throw new AccountingException(messageSource.getMessage("acc.tmp.templateNameAlreadyExists", null, Locale.forLanguageTag(paramJobj.optString("language")))); } accountingHandlerDAOobj.saveModuleTemplate(hashMap); } //Insert new entries again in optimized table. accJournalEntryobj.saveAccountJEs_optimized(jeid); rje = (RepeatedJE) je.getRepeateJE(); if (!StringUtil.isNullOrEmpty(chequeDetail)) { String name = "";//request.getParameter("paidToCmb"); KwlReturnObject custObj = accountingHandlerDAOobj.getObject(MasterItem.class.getName(), paramJobj.optString("paidToCmb")); if (custObj.getEntityList().get(0) != null) { MasterItem obj = (MasterItem) custObj.getEntityList().get(0); if (obj != null) { name = obj.getValue(); } } String basecurrency = paramJobj.optString(Constants.currencyKey); String amont1 = "" + amount; KwlReturnObject result2 = accountingHandlerDAOobj.getObject(KWLCurrency.class.getName(), basecurrency); KWLCurrency currency = (KWLCurrency) result2.getEntityList().get(0); String netinword = EnglishNumberToWordsOjb.convert(Double.parseDouble(String.valueOf(amont1)), currency,countryLanguageId); DecimalFormat def = new DecimalFormat("#,###,###,##0.00"); name=StringUtil.DecodeText(name); String amt = def.format(amount); ll.add(new String[]{"amount", amt}); ll.add(new String[]{"amountinword", netinword}); ll.add(new String[]{"accountName", name}); ll.add(chequeno); ll.add(rje); } else { ll.add(rje); } }/* catch (UnsupportedEncodingException ex) { throw ServiceException.FAILURE("saveJournalEntry : " + ex.getMessage(), ex); }*/ catch (ParseException ex) { throw ServiceException.FAILURE("saveJournalEntry : " + ex.getMessage(), ex); // Logger.getLogger(accJournalEntryController.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { throw ServiceException.FAILURE("saveJournalEntry : " + ex.getMessage(), ex); } return ll; } public void deleteJEArray(String oldjeid, int journalEntryType, String companyid) throws ServiceException, AccountingException, SessionExpiredException { try { //delete old invoice JournalEntryDetail jed = null; if (!StringUtil.isNullOrEmpty(oldjeid)) { KwlReturnObject result = accJournalEntryobj.getJournalEntryDetail(oldjeid, companyid); List list = result.getEntityList(); Iterator itr = list.iterator(); while (itr.hasNext()) { jed = (JournalEntryDetail) itr.next(); //Sagar - No need to revert entry from optimized table as entries are already reverted from calling main function in edit case. result = accJournalEntryobj.deleteJournalEntryDetailRow(jed.getID(), companyid); } // getting chequeid in case of fund transfer result = accJournalEntryobj.getChequeIdLinkedToJournalEntry(oldjeid, companyid); String chequeId = ""; if (result != null) { List chequeList = result.getEntityList(); if (!chequeList.isEmpty()) { chequeId = (String) chequeList.get(0); } } //delete the reconcialation details in case if presentr for the JE // if(journalEntryType ==3){//Only in case if Journal Entry is Fund Transfer type JE result = accJournalEntryobj.DeleteBankReconciliationDetail(oldjeid, companyid); result = accJournalEntryobj.DeleteBankUnReconciliationDetail(oldjeid, companyid); // } result = accJournalEntryobj.permanentDeleteJournalEntry(oldjeid, companyid); result = accJournalEntryobj.deleteJECustomData(oldjeid); if (!StringUtil.isNullOrEmpty(chequeId)) { result = accPaymentDAOobj.deleteChequePermanently(chequeId, companyid); } } } catch (Exception ex) { //Logger.getLogger(accInvoiceController.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE(ex.getMessage(), ex); } } /* Note: while making whanges in this function (approveJE) also make chages in 'AccJournalEntryCMN/approveJE' function. * */ @Override public int approveJE(JournalEntry JE, String companyid, int level, String amount, JSONObject paramJobj, boolean fromCreate, String currentUser) throws SessionExpiredException, AccountingException, ServiceException, ScriptException, MessagingException { boolean hasAuthority = false; if (!fromCreate) { // check if the currently logged in user has authority or not to approve pending JE...but only in case when this method is called from approveJournalEntry method String thisUser = currentUser; KwlReturnObject userclass = accountingHandlerDAOobj.getObject(User.class.getName(), thisUser); User user = (User) userclass.getEntityList().get(0); if (AccountingManager.isCompanyAdmin(user)) { hasAuthority = true; } else { hasAuthority = accJournalEntryobj.checkForRule(level, companyid, amount, thisUser); } } else { hasAuthority = true; } if (hasAuthority) { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); String requisitionApprovalSubject = "Journal Entry: %s - Approval Notification"; String requisitionApprovalHtmlMsg = "<html><head><title>Deskera Accounting - Your Deskera Account</title></head><style type='text/css'>" + "a:link, a:visited, a:active {\n" + " color: #03C;" + "}\n" + "body {\n" + " font-family: Arial, Helvetica, sans-serif;" + " color: #000;" + " font-size: 13px;" + "}\n" + "</style><body>" + "<p>Hi All,</p>" + "<p></p>" + "<p>%s has created journal entry %s and sent it to you for approval. at level "+(level+1)+"</p>" + "<p>Please review and approve it (Journal Entry Number: %s).</p>" + "<p></p>" + "<p>Company Name:- %s</p>" + "<p>Please check on Url:- %s</p>" + "<p>Thanks</p>" + "<p>This is an auto generated email. Do not reply<br>"; String requisitionApprovalPlainMsg = "Hi All,\n\n" + "%s has created journal entry %s and sent it to you for approval. at level "+(level+1)+"\n" + "Please review and approve it (Journal Entry Number: %s).\n\n" + "Company Name:- %s \n" + "Please check on Url:- %s \n" + "Thanks\n\n" + "This is an auto generated email. Do not reply\n"; int approvalStatus = 11; KwlReturnObject cap = accountingHandlerDAOobj.getObject(CompanyAccountPreferences.class.getName(), companyid); CompanyAccountPreferences preferences = (CompanyAccountPreferences) cap.getEntityList().get(0); String jeNumber = JE.getEntryNumber(); String jeID = JE.getID(); HashMap<String, Object> qdDataMap = new HashMap<String, Object>(); qdDataMap.put(Constants.companyKey, companyid); qdDataMap.put("level", level + 1); qdDataMap.put(Constants.moduleid, Constants.Acc_GENERAL_LEDGER_ModuleId); KwlReturnObject flowresult = accMultiLevelApprovalDAOObj.getMultiApprovalRuleData(qdDataMap); Iterator itr = flowresult.getEntityList().iterator(); //String fromEmailId = Constants.ADMIN_EMAILID; KwlReturnObject returnObject = accountingHandlerDAOobj.getObject(Company.class.getName(),companyid); Company company = (Company) returnObject.getEntityList().get(0); Map<String, Object> smtpConfigMap = authHandler.getSMTPConfigMap(company); while (itr.hasNext()) { Object[] row = (Object[]) itr.next(); String rule = row[2].toString(); String creator = (!StringUtil.isNullOrEmpty(row[6].toString())) ? row[6].toString() : ""; boolean sendForApproval = false; String[] creators = creator.split(","); for (int i = 0; i < creators.length; i++) { if (creators[i].equals(paramJobj.optString(Constants.useridKey))) { sendForApproval = true; break; } } rule = rule.replaceAll("[$$]+", amount); /* * send mail to approvers on any of one below condition is true - * 1 - If level exist and rule is not set * 2 - If level and expression rule exist * 3 - If creator rule exist */ if (StringUtil.isNullOrEmpty(rule) || (!StringUtil.isNullOrEmpty(rule) && Boolean.parseBoolean(engine.eval(rule).toString())) || sendForApproval) { // send emails try { if (Boolean.parseBoolean(row[3].toString()) && preferences.isSendapprovalmail()) {//If allow to send approval mail in company account preferences String fromName = "User"; String fromEmailId = (!company.isEmailFromCompanyCreator())?Constants.ADMIN_EMAILID:authHandlerDAOObj.getSysEmailIdByCompanyID(company.getCompanyID()); fromName = paramJobj.optString(Constants.username); // String fromEmailId1 = StringUtil.isNullOrEmpty(JE.getCompany().getEmailID()) ? authHandlerDAOObj.getSysEmailIdByCompanyID(JE.getCompany().getCompanyID()) : JE.getCompany().getEmailID(); // if (!StringUtil.isNullOrEmpty(fromEmailId1)) { // fromEmailId = fromEmailId1; // } String subject = String.format(requisitionApprovalSubject, jeNumber); String htmlMsg = String.format(requisitionApprovalHtmlMsg, fromName, jeNumber, jeNumber, company.getCompanyName(), paramJobj.optString(Constants.PAGE_URL)); String plainMsg = String.format(requisitionApprovalPlainMsg, fromName, jeNumber, jeNumber , company.getCompanyName(), paramJobj.optString(Constants.PAGE_URL)); ArrayList<String> emailArray = new ArrayList<String>(); String[] emails = {}; qdDataMap.put("ruleid", row[0].toString()); KwlReturnObject userResult = accMultiLevelApprovalDAOObj.getApprovalRuleTargetUsers(qdDataMap); Iterator useritr = userResult.getEntityList().iterator(); while (useritr.hasNext()) { Object[] userrow = (Object[]) useritr.next(); emailArray.add(userrow[3].toString()); } emails = emailArray.toArray(emails); if (!StringUtil.isNullOrEmpty(preferences.getApprovalEmails())) { String[] compPrefMailIds = preferences.getApprovalEmails().split(","); emails = AccountingManager.getMergedMailIds(emails, compPrefMailIds); } if (emails.length > 0) { SendMailHandler.postMail(emails, subject, htmlMsg, plainMsg, fromEmailId, smtpConfigMap); } } } catch (MessagingException ex) { Logger.getLogger(JournalEntry.class.getName()).log(Level.SEVERE, null, ex); } approvalStatus = level + 1; } } accJournalEntryobj.approvePendingJE(jeID, companyid, approvalStatus); return approvalStatus; } else { return Constants.NoAuthorityToApprove; // It return fixed value 999 which indecates that current logged in user has no authority to approve the transaction } } public class EnglishNumberToWords { private final String[] tensNames = { "", " Ten", " Twenty", " Thirty", " Forty", " Fifty", " Sixty", " Seventy", " Eighty", " Ninety" }; private final String[] numNames = { "", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine", " Ten", " Eleven", " Twelve", " Thirteen", " Fourteen", " Fifteen", " Sixteen", " Seventeen", " Eighteen", " Nineteen" }; private String convertLessThanOneThousand(int number) { String soFar; if (number % 100 < 20) { soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) { return soFar; } return numNames[number] + " Hundred" + soFar; } private String convertLessOne(int number, KWLCurrency currency) { String soFar; String val = currency.getAfterDecimalName(); if (number % 100 < 20) { soFar = numNames[number % 100]; number /= 100; } else { soFar = numNames[number % 10]; number /= 10; soFar = tensNames[number % 10] + soFar; number /= 10; } if (number == 0) { return " And " + soFar + " " + val; } return " And " + numNames[number] + " " + val + soFar; } public String convert(Double number, KWLCurrency currency, int countryLanguageId) { if (number == 0) { return "Zero"; } String answer = ""; if (countryLanguageId == Constants.OtherCountryLanguageId) { // For universal conversion of amount in words. i.e. in Billion,trillion etc answer = universalConvert(number, currency); } else if (countryLanguageId == Constants.CountryIndiaLanguageId) { // For Indian word format.ie. in lakhs, crores answer = indianConvert(number, currency); } return answer; } public String universalConvert(Double number, KWLCurrency currency) { boolean isNegative = false; if (number < 0) { isNegative = true; number = -1 * number; } String snumber = Double.toString(number); String mask = "000000000000.00"; DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number); int billions = Integer.parseInt(snumber.substring(0, 3)); int millions = Integer.parseInt(snumber.substring(3, 6)); int hundredThousands = Integer.parseInt(snumber.substring(6, 9)); int thousands = Integer.parseInt(snumber.substring(9, 12)); int fractions = Integer.parseInt(snumber.substring(13, 15)); String tradBillions; switch (billions) { case 0: tradBillions = ""; break; case 1: tradBillions = convertLessThanOneThousand(billions) + " Billion "; break; default: tradBillions = convertLessThanOneThousand(billions) + " Billion "; } String result = tradBillions; String tradMillions; switch (millions) { case 0: tradMillions = ""; break; case 1: tradMillions = convertLessThanOneThousand(millions) + " Million "; break; default: tradMillions = convertLessThanOneThousand(millions) + " Million "; } result = result + tradMillions; String tradHundredThousands; switch (hundredThousands) { case 0: tradHundredThousands = ""; break; case 1: tradHundredThousands = "One Thousand "; break; default: tradHundredThousands = convertLessThanOneThousand(hundredThousands) + " Thousand "; } result = result + tradHundredThousands; String tradThousand; tradThousand = convertLessThanOneThousand(thousands); result = result + tradThousand; String paises; switch (fractions) { case 0: paises = ""; break; default: paises = convertLessOne(fractions, currency); } result = result + paises; //to be done later result = result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b", " "); if (isNegative) { result = "Minus " + result; } // result = result.substring(0, 1).toUpperCase() + result.substring(1).toLowerCase(); // Make first letter of operand capital. return result; } public String indianConvert(Double number, KWLCurrency currency) { boolean isNegative = false; if (number < 0) { isNegative = true; number = -1 * number; } String snumber = Double.toString(number); String mask = "000000000000000.00"; //ERP-17681 DecimalFormat df = new DecimalFormat(mask); snumber = df.format(number); int n = Integer.parseInt(snumber.substring(0, 15)); int fractions = Integer.parseInt(snumber.split("\\.").length != 0 ? snumber.split("\\.")[1] : "0"); if (n == 0) { return "Zero"; } String arr1[] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; String arr2[] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; String unit[] = {"Arab", "Crore", "Lakh", "Thousand", "Hundred", ""}; int factor[] = {1000000000, 10000000, 100000, 1000, 100, 1}; String answer = "", paises = ""; if (n < 0) { answer = "Minus"; n = -n; } int quotient, units, tens; for (int i = 0; i < factor.length; i++) { quotient = n / factor[i]; if (quotient > 0) { if (quotient < 20) { answer = answer + " " + arr1[quotient - 1]; } else { units = quotient % 10; tens = quotient / 10; if (units > 0) { answer = answer + " " + arr2[tens - 2] + " " + arr1[units - 1]; } else { answer = answer + " " + arr2[tens - 2] + " "; } } answer = answer + " " + unit[i]; } n = n % factor[i]; } switch (fractions) { case 0: paises = ""; break; default: paises = convertLessOne(fractions, currency); } answer = answer + paises; //to be done later return answer.trim(); } } }
141,565
0.587843
0.583937
2,370
58.732067
49.542023
668
false
false
0
0
0
0
0
0
1.039662
false
false
12
fb90183e83629433f9fe10f36f0c80baf91c6dd1
16,887,811,427,061
bcde1da6f6343abf21f8a5e9afb9ed6fd323cf6b
/src/com/assignment/StockExchange.java
87a01610e3daf14148ca895951fd7e3fdb901d2e
[ "MIT" ]
permissive
siddhantmittal024/MiniBrokerageSystem
https://github.com/siddhantmittal024/MiniBrokerageSystem
70c8839dcb0ac541f9501ca03edece0a4d3ec414
10199d4e095fb37d7ad8450cc1291b84885928ba
refs/heads/main
2023-01-11T10:54:47.626000
2020-11-10T17:40:36
2020-11-10T17:40:36
308,254,012
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.assignment; import java.util.*; // Two StockExchanges namely NSE and BSE // Stocks will be stored in each accordingly // A stock can be added to NSE,BSE or both. // Create a new stock and add it to StockExchange class StockExchange{ //ticker for the stock String exchangeName; // arraylist for NSE stockExchange private final ArrayList<Stock> NSE = new ArrayList<Stock>(); // arraylist for BSE stockExchange private final ArrayList<Stock> BSE = new ArrayList<Stock>(); // to add stocks to stockExchange private HashMap<String,Stock> stocks = new HashMap<String,Stock>(); //creating/initiating a new stockExchange namely NSE/BSE public StockExchange(String name) { this.stocks = new HashMap<String, Stock>(); this.exchangeName = name; } // add a new stock to the stockExchange public void addStock(String scrip, String sect, double open, double high, double low, double close) { Stock st = new Stock(sect, open, high, low, close); stocks.put(scrip, st); System.out.println("Added scrip: " + scrip); } // returns all stocks registered in the stockExchange public void getAllStocks() { System.out.println("Scrips:"); for (String tick : stocks.keySet()) { String temp = "Scrip : " + tick + ", Sector : " + stocks.get(tick).getSector() + ", "; temp += stocks.get(tick).toString(); System.out.println(temp); } } // to return stock of a particular ticker public Stock getIndividualStock(String ticker){ return stocks.get(ticker); } // to return all stocks sector-wise public void getSectorWiseStocks(String sect) { System.out.println("Scripts listed in " + sect + ":"); for (String tick : stocks.keySet()) { if (stocks.get(tick).getSector().equals(sect)) { String temp = "Scrip : " + tick + ", "; temp += stocks.get(tick).toString(); System.out.println(temp); } } } // delete a stock for a given ticker public void deleteStock(String ticker) { //Delete Stock from here System.out.println("Deleted scrip: " + ticker); stocks.remove(ticker); } }
UTF-8
Java
2,355
java
StockExchange.java
Java
[]
null
[]
package com.assignment; import java.util.*; // Two StockExchanges namely NSE and BSE // Stocks will be stored in each accordingly // A stock can be added to NSE,BSE or both. // Create a new stock and add it to StockExchange class StockExchange{ //ticker for the stock String exchangeName; // arraylist for NSE stockExchange private final ArrayList<Stock> NSE = new ArrayList<Stock>(); // arraylist for BSE stockExchange private final ArrayList<Stock> BSE = new ArrayList<Stock>(); // to add stocks to stockExchange private HashMap<String,Stock> stocks = new HashMap<String,Stock>(); //creating/initiating a new stockExchange namely NSE/BSE public StockExchange(String name) { this.stocks = new HashMap<String, Stock>(); this.exchangeName = name; } // add a new stock to the stockExchange public void addStock(String scrip, String sect, double open, double high, double low, double close) { Stock st = new Stock(sect, open, high, low, close); stocks.put(scrip, st); System.out.println("Added scrip: " + scrip); } // returns all stocks registered in the stockExchange public void getAllStocks() { System.out.println("Scrips:"); for (String tick : stocks.keySet()) { String temp = "Scrip : " + tick + ", Sector : " + stocks.get(tick).getSector() + ", "; temp += stocks.get(tick).toString(); System.out.println(temp); } } // to return stock of a particular ticker public Stock getIndividualStock(String ticker){ return stocks.get(ticker); } // to return all stocks sector-wise public void getSectorWiseStocks(String sect) { System.out.println("Scripts listed in " + sect + ":"); for (String tick : stocks.keySet()) { if (stocks.get(tick).getSector().equals(sect)) { String temp = "Scrip : " + tick + ", "; temp += stocks.get(tick).toString(); System.out.println(temp); } } } // delete a stock for a given ticker public void deleteStock(String ticker) { //Delete Stock from here System.out.println("Deleted scrip: " + ticker); stocks.remove(ticker); } }
2,355
0.602972
0.602972
65
34.23077
23.924091
105
false
false
0
0
0
0
0
0
0.6
false
false
12
75229c748544707ddee4aaf2db17442b87d1a608
14,362,370,663,464
20e19edc76c4078287b1f0fcc42531f2add6c92a
/app/src/main/java/dk/lagoona/sikkertnabolag/Models/AlarmSystem.java
a31f2ffd94e95b0944cb807c4f043bdbd3e0599c
[]
no_license
binhxpham/SikkertNabolag
https://github.com/binhxpham/SikkertNabolag
27e8f9973706a320a9eb2ed0a32c5c97e866c15f
0ade45b0d7249b7b8a1fdfbc076cc4439ca25ab5
refs/heads/master
2016-09-13T06:14:41.808000
2016-09-12T13:19:36
2016-09-12T13:19:36
64,432,320
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dk.lagoona.sikkertnabolag.Models; /** * Created by binhpham on 05/05/16. */ import com.backendless.Backendless; import com.backendless.BackendlessUser; import com.backendless.geo.GeoPoint; import java.io.Serializable; public class AlarmSystem implements Serializable { private String objectId; private java.util.Date created; private java.util.Date updated; private String image; private String name; public String getObjectId() { return this.objectId; } public java.util.Date getUpdated() { return this.updated; } public String getImage() { return this.image; } public String getName() { return this.name; } public java.util.Date getCreated() { return this.created; } public void setObjectId(String objectId) { this.objectId = objectId; } public void setUpdated(java.util.Date updated) { this.updated = updated; } public void setImage(String image) { this.image = image; } public void setName(String name) { this.name = name; } public void setCreated(java.util.Date created) { this.created = created; } public AlarmSystem save() { return Backendless.Data.of(AlarmSystem.class).save(this); } public Long remove() { return Backendless.Data.of(AlarmSystem.class).remove(this); } public static AlarmSystem findById(String id) { return Backendless.Data.of(AlarmSystem.class).findById(id); } public static AlarmSystem findFirst() { return Backendless.Data.of(AlarmSystem.class).findFirst(); } public static AlarmSystem findLast() { return Backendless.Data.of(AlarmSystem.class).findLast(); } }
UTF-8
Java
1,781
java
AlarmSystem.java
Java
[ { "context": ".lagoona.sikkertnabolag.Models;\n\n/**\n * Created by binhpham on 05/05/16.\n */\n\nimport com.backendless.Backendl", "end": 69, "score": 0.9996193647384644, "start": 61, "tag": "USERNAME", "value": "binhpham" } ]
null
[]
package dk.lagoona.sikkertnabolag.Models; /** * Created by binhpham on 05/05/16. */ import com.backendless.Backendless; import com.backendless.BackendlessUser; import com.backendless.geo.GeoPoint; import java.io.Serializable; public class AlarmSystem implements Serializable { private String objectId; private java.util.Date created; private java.util.Date updated; private String image; private String name; public String getObjectId() { return this.objectId; } public java.util.Date getUpdated() { return this.updated; } public String getImage() { return this.image; } public String getName() { return this.name; } public java.util.Date getCreated() { return this.created; } public void setObjectId(String objectId) { this.objectId = objectId; } public void setUpdated(java.util.Date updated) { this.updated = updated; } public void setImage(String image) { this.image = image; } public void setName(String name) { this.name = name; } public void setCreated(java.util.Date created) { this.created = created; } public AlarmSystem save() { return Backendless.Data.of(AlarmSystem.class).save(this); } public Long remove() { return Backendless.Data.of(AlarmSystem.class).remove(this); } public static AlarmSystem findById(String id) { return Backendless.Data.of(AlarmSystem.class).findById(id); } public static AlarmSystem findFirst() { return Backendless.Data.of(AlarmSystem.class).findFirst(); } public static AlarmSystem findLast() { return Backendless.Data.of(AlarmSystem.class).findLast(); } }
1,781
0.653004
0.649635
82
20.719513
20.41238
67
false
false
0
0
0
0
0
0
0.304878
false
false
12
b5e924ab97bdff5ee2acccf3d01b054d52b7a840
3,435,973,898,604
3438195531c7ea60592442c4d95aa2a24d31aaca
/src/main/java/Graphics/Lists/RequestList.java
e9b622cf58e4382fb63680b6d8230756df1888f5
[]
no_license
AdvProg2020/Project_team-24
https://github.com/AdvProg2020/Project_team-24
24f77e0b74728215c155ee614fef24fa30b0a61f
13087495ee3b007d34fc9f284e8df2145aa49c69
refs/heads/master
2021-05-21T20:37:34.736000
2020-07-29T19:15:06
2020-07-29T19:15:06
252,789,324
0
0
null
false
2021-02-11T19:55:45
2020-04-03T16:52:01
2020-07-29T19:15:09
2021-02-11T19:55:45
87,305
0
0
1
Java
false
false
package Graphics.Lists; import Controller.Controllers.ManagerController; import Exceptions.AccountDoesNotExistException; import Graphics.Tools.SceneBuilder; import Model.Models.Auction; import Model.Models.Product; import Model.Models.Request; import Model.Tools.ForPend; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.ResourceBundle; public class RequestList implements SceneBuilder, Initializable { private static ManagerController managerController = ManagerController.getInstance(); public TableView<Request> request_table; public TableColumn<Request, Pane> ar_btn; public TableColumn<Request, String> request_type; public TableColumn<Request, String> request_info; public TableColumn<Request, String> request_mode; public TableColumn<Request, String> request_name; @Override public Scene sceneBuilder() { try { return FXMLLoader.load(new File("src/main/resources/Graphics/RequestList/RequestList.fxml").toURI().toURL()); } catch (IOException e) { e.printStackTrace(); System.exit(0); } return null; } @Override public void initialize(URL location, ResourceBundle resources) { init(); } private void init() { List<Request> list = managerController.showAllRequests(); request_table.setItems(FXCollections.observableList(list)); request_name.setCellValueFactory(param -> { ForPend forPend = param.getValue().getForPend(); return new SimpleStringProperty(forPend instanceof Product ? ((Product) forPend).getName() : ((Auction) forPend).getName()); }); request_mode.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getClass().getSimpleName())); request_info.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getInformation())); request_type.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getTypeOfRequest())); ar_btn.setCellValueFactory(param -> new SimpleObjectProperty<>(setChoicePane(param.getValue()))); } @NotNull @Contract("_ -> new") private Pane setChoicePane(Request request) { HBox hBox = new HBox(); Button accept = new Button("accept"); Button decline = new Button("decline"); accept.setOnAction(event -> { try { request.acceptRequest(); } catch (AccountDoesNotExistException e) { e.printStackTrace(); } init(); }); decline.setOnAction(event -> { try { request.declineRequest(); } catch (AccountDoesNotExistException e) { e.printStackTrace(); } init(); }); hBox.getChildren().addAll(accept,decline); return new Pane(hBox); } }
UTF-8
Java
3,513
java
RequestList.java
Java
[]
null
[]
package Graphics.Lists; import Controller.Controllers.ManagerController; import Exceptions.AccountDoesNotExistException; import Graphics.Tools.SceneBuilder; import Model.Models.Auction; import Model.Models.Product; import Model.Models.Request; import Model.Tools.ForPend; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.ResourceBundle; public class RequestList implements SceneBuilder, Initializable { private static ManagerController managerController = ManagerController.getInstance(); public TableView<Request> request_table; public TableColumn<Request, Pane> ar_btn; public TableColumn<Request, String> request_type; public TableColumn<Request, String> request_info; public TableColumn<Request, String> request_mode; public TableColumn<Request, String> request_name; @Override public Scene sceneBuilder() { try { return FXMLLoader.load(new File("src/main/resources/Graphics/RequestList/RequestList.fxml").toURI().toURL()); } catch (IOException e) { e.printStackTrace(); System.exit(0); } return null; } @Override public void initialize(URL location, ResourceBundle resources) { init(); } private void init() { List<Request> list = managerController.showAllRequests(); request_table.setItems(FXCollections.observableList(list)); request_name.setCellValueFactory(param -> { ForPend forPend = param.getValue().getForPend(); return new SimpleStringProperty(forPend instanceof Product ? ((Product) forPend).getName() : ((Auction) forPend).getName()); }); request_mode.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getClass().getSimpleName())); request_info.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getInformation())); request_type.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getTypeOfRequest())); ar_btn.setCellValueFactory(param -> new SimpleObjectProperty<>(setChoicePane(param.getValue()))); } @NotNull @Contract("_ -> new") private Pane setChoicePane(Request request) { HBox hBox = new HBox(); Button accept = new Button("accept"); Button decline = new Button("decline"); accept.setOnAction(event -> { try { request.acceptRequest(); } catch (AccountDoesNotExistException e) { e.printStackTrace(); } init(); }); decline.setOnAction(event -> { try { request.declineRequest(); } catch (AccountDoesNotExistException e) { e.printStackTrace(); } init(); }); hBox.getChildren().addAll(accept,decline); return new Pane(hBox); } }
3,513
0.687447
0.687162
101
33.782177
28.838095
136
false
false
0
0
0
0
0
0
0.683168
false
false
12
6f7ae5b9735ef29dc80a11bf29cd0a4f16c494a3
14,027,363,242,572
a229e98185273e78e3c544d6351b416871cd912f
/summerb-validation/src/test/java/org/summerb/validation/jakarta/test_data/AbstractInterface.java
49627e77e8dc0b9a2bd3e6933086121addfec691
[ "Apache-2.0" ]
permissive
skarpushin/summerb
https://github.com/skarpushin/summerb
c1751986c79b8218edbff8c7ef5796ba15d63d45
bc63a1c401e79518d7f48487780236763d6036df
refs/heads/master
2023-06-06T23:21:04.282000
2023-06-02T19:08:42
2023-06-02T19:08:42
36,518,071
8
5
Apache-2.0
false
2023-04-21T13:00:19
2015-05-29T17:10:39
2021-12-15T11:39:16
2023-04-21T12:54:49
2,739
7
2
9
Java
false
false
package org.summerb.validation.jakarta.test_data; import javax.validation.constraints.Pattern; import org.summerb.validation.jakarta.AnnotationProcessor; public interface AbstractInterface extends AnnotationProcessor<Pattern> {}
UTF-8
Java
232
java
AbstractInterface.java
Java
[]
null
[]
package org.summerb.validation.jakarta.test_data; import javax.validation.constraints.Pattern; import org.summerb.validation.jakarta.AnnotationProcessor; public interface AbstractInterface extends AnnotationProcessor<Pattern> {}
232
0.853448
0.853448
7
32.142857
29.142157
74
false
false
0
0
0
0
0
0
0.428571
false
false
12
ce1baab2bfd4b5da21883fc6a1858f2a49d30a37
7,541,962,630,063
b002a71a536bb7d434e557fe3f86ff83496b3175
/src/com.github.dshea89.hrlplus/ReportGenerator.java
6b80a612efcd80765e211c0cf8e62126ca5ead66
[]
no_license
dshea89/HRLPlus
https://github.com/dshea89/HRLPlus
f154968877703e549daa9fa7e6556a156a7220f1
4768474d35d27e4542b7b0e5af30bf60766842c9
refs/heads/master
2021-07-13T12:28:07.733000
2020-08-16T13:53:10
2020-08-16T13:53:10
189,754,339
5
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.dshea89.hrlplus; import java.util.Vector; import java.util.Hashtable; import java.lang.String; import java.awt.TextArea; import java.awt.event.*; import java.io.*; import java.util.Date; import javax.swing.JEditorPane; /** A class for handling the output of various aspects of the theory * to files, to the screen (GUI) and to the standard out. * * @author Simon Colton, started 15th October 2001 * @version 1.0 */ public class ReportGenerator implements Serializable { /** The text output to the screen. */ public String output_text = ""; /** The output file which is being written to. */ public PrintWriter output_file = null; /** The name of the directory where all the report files are. */ public String input_files_directory = ""; /** The on-screen text area. */ public JEditorPane report_output_text = new JEditorPane(); /** The command line arguments to give to the individual reports. */ public Vector command_line_arguments = new Vector(); /** The vector of objects to report over. Note that this is actually * set by the report pseudo-code. */ public Vector objects_to_report = new Vector(); /** The sort field. Note that this is actually * set by the report pseudo-code. */ public String sort_key = ""; /** The value below which objects in the report will not be reported, * which can be reset by a report. */ public double prune_less_than = 0; /** A counter, which can be reset by a report. */ public int counter = 0; /** The old value (set by the report). */ public String old_value = ""; /** The number of runs_through the reporting cycle (can be set by the report * and utilised by the report). */ public int number_of_runs_through = 1; /** This executes the reports. */ public void runReports(Theory theory, String report_names[]) { output_text = ""; number_of_runs_through = 1; for (int i=0; i<report_names.length; i++) { sort_key = ""; objects_to_report = new Vector(); old_value = ""; Report report = new Report(input_files_directory + report_names[i]); for (int run_through = 0; run_through<number_of_runs_through; run_through++) { report.pseudo_code_interpreter.local_alias_hashtable.put("theory", theory); report.pseudo_code_interpreter.local_alias_hashtable.put("stage", "start"); report.pseudo_code_interpreter.local_alias_hashtable.put("screen", report_output_text); report.pseudo_code_interpreter.local_alias_hashtable.put("this", this); report.pseudo_code_interpreter.local_alias_hashtable.put("run_through", new Integer(run_through)); report.runReport(); counter = 0; SortableVector sorted_objects = new SortableVector(); sorted_objects.prune_less_than = prune_less_than; for (int j=0; j<objects_to_report.size(); j++) { if (!sort_key.equals("")) sorted_objects.addElement(objects_to_report.elementAt(j), sort_key); else sorted_objects.addElement(objects_to_report.elementAt(j)); } for (int j=0; j<sorted_objects.size(); j++) { report.pseudo_code_interpreter.local_alias_hashtable = new Hashtable(); report.pseudo_code_interpreter.local_alias_hashtable.put("run_through", new Integer(run_through)); report.pseudo_code_interpreter.local_alias_hashtable.put("screen", report_output_text); report.pseudo_code_interpreter.local_alias_hashtable.put("counter", Integer.toString(counter)); report.pseudo_code_interpreter.local_alias_hashtable.put("stage", "main"); report.pseudo_code_interpreter.local_alias_hashtable.put("theory", theory); report.pseudo_code_interpreter.local_alias_hashtable.put("object", sorted_objects.elementAt(j)); report.pseudo_code_interpreter.local_alias_hashtable.put("old_value", old_value); report.pseudo_code_interpreter.local_alias_hashtable.put("this", this); report.runReport(); counter++; } report.pseudo_code_interpreter.local_alias_hashtable.put("this", this); report.pseudo_code_interpreter.local_alias_hashtable.put("run_through", new Integer(run_through)); report.pseudo_code_interpreter.local_alias_hashtable.put("theory", theory); report.pseudo_code_interpreter.local_alias_hashtable.put("screen", report_output_text); report.pseudo_code_interpreter.local_alias_hashtable.put("stage", "end"); report.runReport(); } } report_output_text.setText(output_text); report_output_text.setCaretPosition(0); } public void writeToScreen(String s) { output_text = output_text + s; } public void writeToFile(String s) { output_file.write(s); } public void writeToScreenAndFile(String s) { output_file.write(s); output_text = output_text + s; } public void openFileForWriting(String fn) { try { output_file = new PrintWriter(new BufferedWriter(new FileWriter(fn, false))); } catch(Exception e) { writeToScreen("cannot open file: " + fn); } } public void openFileForAppend(String fn) { try { output_file = new PrintWriter(new BufferedWriter(new FileWriter(fn, true))); } catch(Exception e) { writeToScreen("cannot open file: " + fn); } } public void closeFile() { output_file.close(); } public void clearScreen() { report_output_text.setText(""); } public String getDate() { Date d = new Date(); String output = d.toString(); return output.substring(0, output.lastIndexOf(":")+3); } }
UTF-8
Java
6,371
java
ReportGenerator.java
Java
[ { "context": "creen (GUI) and to the standard out.\n *\n * @author Simon Colton, started 15th October 2001\n * @version 1.0 */\n\npu", "end": 393, "score": 0.999213695526123, "start": 381, "tag": "NAME", "value": "Simon Colton" } ]
null
[]
package com.github.dshea89.hrlplus; import java.util.Vector; import java.util.Hashtable; import java.lang.String; import java.awt.TextArea; import java.awt.event.*; import java.io.*; import java.util.Date; import javax.swing.JEditorPane; /** A class for handling the output of various aspects of the theory * to files, to the screen (GUI) and to the standard out. * * @author <NAME>, started 15th October 2001 * @version 1.0 */ public class ReportGenerator implements Serializable { /** The text output to the screen. */ public String output_text = ""; /** The output file which is being written to. */ public PrintWriter output_file = null; /** The name of the directory where all the report files are. */ public String input_files_directory = ""; /** The on-screen text area. */ public JEditorPane report_output_text = new JEditorPane(); /** The command line arguments to give to the individual reports. */ public Vector command_line_arguments = new Vector(); /** The vector of objects to report over. Note that this is actually * set by the report pseudo-code. */ public Vector objects_to_report = new Vector(); /** The sort field. Note that this is actually * set by the report pseudo-code. */ public String sort_key = ""; /** The value below which objects in the report will not be reported, * which can be reset by a report. */ public double prune_less_than = 0; /** A counter, which can be reset by a report. */ public int counter = 0; /** The old value (set by the report). */ public String old_value = ""; /** The number of runs_through the reporting cycle (can be set by the report * and utilised by the report). */ public int number_of_runs_through = 1; /** This executes the reports. */ public void runReports(Theory theory, String report_names[]) { output_text = ""; number_of_runs_through = 1; for (int i=0; i<report_names.length; i++) { sort_key = ""; objects_to_report = new Vector(); old_value = ""; Report report = new Report(input_files_directory + report_names[i]); for (int run_through = 0; run_through<number_of_runs_through; run_through++) { report.pseudo_code_interpreter.local_alias_hashtable.put("theory", theory); report.pseudo_code_interpreter.local_alias_hashtable.put("stage", "start"); report.pseudo_code_interpreter.local_alias_hashtable.put("screen", report_output_text); report.pseudo_code_interpreter.local_alias_hashtable.put("this", this); report.pseudo_code_interpreter.local_alias_hashtable.put("run_through", new Integer(run_through)); report.runReport(); counter = 0; SortableVector sorted_objects = new SortableVector(); sorted_objects.prune_less_than = prune_less_than; for (int j=0; j<objects_to_report.size(); j++) { if (!sort_key.equals("")) sorted_objects.addElement(objects_to_report.elementAt(j), sort_key); else sorted_objects.addElement(objects_to_report.elementAt(j)); } for (int j=0; j<sorted_objects.size(); j++) { report.pseudo_code_interpreter.local_alias_hashtable = new Hashtable(); report.pseudo_code_interpreter.local_alias_hashtable.put("run_through", new Integer(run_through)); report.pseudo_code_interpreter.local_alias_hashtable.put("screen", report_output_text); report.pseudo_code_interpreter.local_alias_hashtable.put("counter", Integer.toString(counter)); report.pseudo_code_interpreter.local_alias_hashtable.put("stage", "main"); report.pseudo_code_interpreter.local_alias_hashtable.put("theory", theory); report.pseudo_code_interpreter.local_alias_hashtable.put("object", sorted_objects.elementAt(j)); report.pseudo_code_interpreter.local_alias_hashtable.put("old_value", old_value); report.pseudo_code_interpreter.local_alias_hashtable.put("this", this); report.runReport(); counter++; } report.pseudo_code_interpreter.local_alias_hashtable.put("this", this); report.pseudo_code_interpreter.local_alias_hashtable.put("run_through", new Integer(run_through)); report.pseudo_code_interpreter.local_alias_hashtable.put("theory", theory); report.pseudo_code_interpreter.local_alias_hashtable.put("screen", report_output_text); report.pseudo_code_interpreter.local_alias_hashtable.put("stage", "end"); report.runReport(); } } report_output_text.setText(output_text); report_output_text.setCaretPosition(0); } public void writeToScreen(String s) { output_text = output_text + s; } public void writeToFile(String s) { output_file.write(s); } public void writeToScreenAndFile(String s) { output_file.write(s); output_text = output_text + s; } public void openFileForWriting(String fn) { try { output_file = new PrintWriter(new BufferedWriter(new FileWriter(fn, false))); } catch(Exception e) { writeToScreen("cannot open file: " + fn); } } public void openFileForAppend(String fn) { try { output_file = new PrintWriter(new BufferedWriter(new FileWriter(fn, true))); } catch(Exception e) { writeToScreen("cannot open file: " + fn); } } public void closeFile() { output_file.close(); } public void clearScreen() { report_output_text.setText(""); } public String getDate() { Date d = new Date(); String output = d.toString(); return output.substring(0, output.lastIndexOf(":")+3); } }
6,365
0.590645
0.587192
194
31.840206
32.103733
118
false
false
0
0
0
0
0
0
0.536082
false
false
12
3820854cf466faac01a40aa34c420fd0ecb9d25c
16,080,357,562,069
ac9799e50839b33c762ecd5ec3780d7b7fe15ff9
/src/main/java/jerarquicas/dinamicas/ArbolBin.java
86b1fff06ebf0141ba68ef5aa2b9314b1149cd89
[]
no_license
DevJuani/Data-Structure
https://github.com/DevJuani/Data-Structure
edd94948ca4a81d78103a2fc2568130a4e872ae3
2173bd44e1700d1c11baee6fe3bcffd704c71efe
refs/heads/main
2023-05-30T23:34:47.160000
2021-06-28T14:31:51
2021-06-28T14:31:51
375,176,735
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jerarquicas.dinamicas; import lineales.dinamicas.Lista; public class ArbolBin { private NodoArbol raiz; //Constructor public ArbolBin(){ this.raiz = null; } //Modificadores public boolean insertar (Object elemNuevo, Object elemPadre, char lugar){ boolean exito = false; if(this.esVacio()){ this.raiz = new NodoArbol(elemNuevo); exito = true; } else { NodoArbol nodoPadre = obtenerNodo(this.raiz, elemPadre); if(nodoPadre != null){ if( lugar == 'I' && nodoPadre.getIzquierdo() == null){ nodoPadre.setIzquierdo(new NodoArbol(elemNuevo)); exito = true; } else { if(lugar == 'D' && nodoPadre.getDerecho() == null){ nodoPadre.setDerecho(new NodoArbol(elemNuevo)); exito = true; } } } } return exito; } public void vaciar(){ this.raiz = null; } //Observadores private NodoArbol obtenerNodo(NodoArbol nodo, Object buscado){ NodoArbol resultado = null; if(nodo != null){ if(nodo.getElem().equals(buscado)){ resultado = nodo; } else { resultado = obtenerNodo(nodo.getIzquierdo(), buscado); if(resultado == null){ resultado = obtenerNodo(nodo.getDerecho(), buscado); } } } return resultado; } public boolean esVacio(){ return this.raiz == null; } public int altira(){ int altura = 0; altura = this.getCantNiveles(this.raiz, altura); return altura; } private int getCantNiveles(NodoArbol nodo, int nivel){ if(nodo != null){ nivel = Math.max(this.getCantNiveles(nodo.getIzquierdo(), nivel + 1), this.getCantNiveles(nodo.getDerecho(), nivel+1)); } else { nivel--; } return nivel; } public int nivel (Object elemento){ int nivel; nivel = buscarNivel(this.raiz, 0, elemento); return nivel; } private int buscarNivel(NodoArbol nodo, int nivel, Object elemento){ int retorna = -1; if(nodo != null){ if(nodo.getElem().equals(elemento)){ retorna = nivel; } else { retorna = buscarNivel(nodo.getIzquierdo(), nivel + 1, elemento); } } return retorna; } public Object padre (Object elemento){ Object padre = null; padre = buscarPadre(this.raiz, elemento, padre); return padre; } private Object buscarPadre(NodoArbol nodo, Object hijo, Object padre){ Object retorna = null; if(nodo != null){ if(nodo.getElem().equals(hijo)){ retorna = padre; } else { retorna = buscarPadre(nodo.getIzquierdo(), hijo, nodo.getElem()); if(retorna == null){ retorna = buscarPadre(nodo.getDerecho(), hijo, nodo.getElem()); } } } return retorna; } public Lista listarPreorden() { Lista lista = new Lista(); listarPreordenAux(this.raiz, lista); return lista; } private void listarPreordenAux(NodoArbol nodo, Lista lista) { if (nodo != null) { lista.insertar(nodo.getElem(), lista.longitud() + 1); listarPreordenAux(nodo.getIzquierdo(), lista); listarPreordenAux(nodo.getDerecho(), lista); } } public Lista listarInorden() { Lista lista = new Lista(); listarInordenAux(this.raiz, lista); return lista; } private void listarInordenAux(NodoArbol nodo, Lista lista) { if (nodo != null) { listarInordenAux(nodo.getIzquierdo(), lista); lista.insertar(nodo.getElem(), lista.longitud() + 1); listarInordenAux(nodo.getDerecho(), lista); } } public Lista listarPosorden() { Lista lista = new Lista(); listarPosordenAux(this.raiz, lista); return lista; } private void listarPosordenAux(NodoArbol nodo, Lista lista) { if (nodo != null) { listarPosordenAux(nodo.getIzquierdo(), lista); listarPosordenAux(nodo.getDerecho(), lista); lista.insertar(nodo.getElem(), lista.longitud() + 1); } } public Lista listarPorNiveles() { Lista lista = new Lista(); if (this.raiz != null) { lista.insertar(this.raiz.getElem(), 1); listarPorNivelesAux(this.raiz, lista); } return lista; } private void listarPorNivelesAux(NodoArbol nodo, Lista lista) { if (nodo != null) { if (nodo.getIzquierdo() != null) { lista.insertar(nodo.getIzquierdo().getElem(), lista.longitud() + 1); } if (nodo.getDerecho() != null) { lista.insertar(nodo.getDerecho().getElem(), lista.longitud() + 1); } listarPorNivelesAux(nodo.getIzquierdo(), lista); listarPorNivelesAux(nodo.getDerecho(), lista); } } // Propias del tipo @Override public ArbolBin clone() { ArbolBin copia = new ArbolBin(); if (!this.esVacio()) { copia.raiz = clonAux(this.raiz); } return copia; } private NodoArbol clonAux(NodoArbol nodo) { NodoArbol nuevo = new NodoArbol(nodo.getElem()); if (nodo.getIzquierdo() != null) { nuevo.setIzquierdo(clonAux(nodo.getIzquierdo())); } if (nodo.getDerecho() != null) { nuevo.setDerecho(clonAux(nodo.getDerecho())); } return nuevo; } public Lista frontera() { Lista retorno = new Lista(); fronteraAux(this.raiz, retorno); return retorno; } private void fronteraAux(NodoArbol raiz, Lista lista) { if (raiz != null) { if (raiz.getIzquierdo() == null && raiz.getDerecho() == null) { lista.insertar(raiz.getElem(), lista.longitud() + 1); } else { if (raiz.getIzquierdo() != null) { fronteraAux(raiz.getIzquierdo(), lista); } if (raiz.getDerecho() != null) { fronteraAux(raiz.getDerecho(), lista); } } } } public boolean verificarPatron(Lista listaPatron) { boolean retorno = false; // Evaluamos que la lista no esta vacia if (listaPatron.esVacia()) { // En caso de que la lista este vacia y el arbol este vacio if (this.raiz == null) { retorno = true; } } else { // En caso de no estar la lista vacia y que el arbol no lo este if (this.raiz != null) { retorno = verificarPatronAux(this.raiz, listaPatron); } } return retorno; } private boolean verificarPatronAux(NodoArbol raiz, Lista listaPatron) { // Verificamos si el elemento en el frente de la lista es igual a la raiz boolean retorno = false; if (raiz != null && !listaPatron.esVacia()) { // Comparamos con la raiz Object primerElemento = listaPatron.recuperar(1); if (raiz.getElem().equals(primerElemento)) { // Si esta sacamos este elemento en la lista y llamamos con el HI boolean retornoIzquierdo = false; listaPatron.eliminar(1); retorno = true; if (raiz.getIzquierdo() != null) { retornoIzquierdo = verificarPatronAux(raiz.getIzquierdo(), listaPatron); retorno = retornoIzquierdo; } // Si no encontro el patron por el HI, lo busca por le HD if (raiz.getDerecho() != null && !retornoIzquierdo) { retorno = verificarPatronAux(raiz.getDerecho(), listaPatron); } } } return retorno; } public void modificarSubarboles(Object d1, Object d2, Object d3) { this.modificarSubarbolesAux(this.raiz, d1, d2, d3); } private void modificarSubarbolesAux(NodoArbol nodoActual, Object d1, Object d2, Object d3) { // Precondición: d1 debe ser distinto de d2 y d3 para no entrar en bucle if (nodoActual != null) { if (nodoActual.getIzquierdo() != null) { if (nodoActual.getElem().equals(d1)) { nodoActual.getIzquierdo().setValor(d2); } modificarSubarbolesAux(nodoActual.getIzquierdo(), d1, d2, d3); } else { if (nodoActual.getElem().equals(d1)) { nodoActual.setIzquierdo(new NodoArbol(d2)); } } if (nodoActual.getDerecho() != null) { if (nodoActual.getElem().equals(d1)) { nodoActual.getDerecho().setValor(d3); } modificarSubarbolesAux(nodoActual.getDerecho(), d1, d2, d3); } else { if (nodoActual.getElem().equals(d1)) { nodoActual.setDerecho(new NodoArbol(d3)); } } } } // Testing public String toString() { String cadena = "Arbol vacio"; if (this.raiz != null) { cadena = ""; cadena = stringAux(this.raiz, cadena); } return cadena; } private String stringAux(NodoArbol nodo, String cadena) { String cadena2 = cadena; cadena2 += "Nodo:" + nodo.getElem(); if (nodo.getIzquierdo() != null) { cadena2 += " HI:" + nodo.getIzquierdo().getElem(); } else { cadena2 += " HI:-"; } if (nodo.getDerecho() != null) { cadena2 += " HD:" + nodo.getDerecho().getElem() + "\n"; } else { cadena2 += " HD:- \n"; } if (nodo.getIzquierdo() != null) { cadena2 = stringAux(nodo.getIzquierdo(), cadena2); } if (nodo.getDerecho() != null) { cadena2 = stringAux(nodo.getDerecho(), cadena2); } return cadena2; } }
UTF-8
Java
10,871
java
ArbolBin.java
Java
[]
null
[]
package jerarquicas.dinamicas; import lineales.dinamicas.Lista; public class ArbolBin { private NodoArbol raiz; //Constructor public ArbolBin(){ this.raiz = null; } //Modificadores public boolean insertar (Object elemNuevo, Object elemPadre, char lugar){ boolean exito = false; if(this.esVacio()){ this.raiz = new NodoArbol(elemNuevo); exito = true; } else { NodoArbol nodoPadre = obtenerNodo(this.raiz, elemPadre); if(nodoPadre != null){ if( lugar == 'I' && nodoPadre.getIzquierdo() == null){ nodoPadre.setIzquierdo(new NodoArbol(elemNuevo)); exito = true; } else { if(lugar == 'D' && nodoPadre.getDerecho() == null){ nodoPadre.setDerecho(new NodoArbol(elemNuevo)); exito = true; } } } } return exito; } public void vaciar(){ this.raiz = null; } //Observadores private NodoArbol obtenerNodo(NodoArbol nodo, Object buscado){ NodoArbol resultado = null; if(nodo != null){ if(nodo.getElem().equals(buscado)){ resultado = nodo; } else { resultado = obtenerNodo(nodo.getIzquierdo(), buscado); if(resultado == null){ resultado = obtenerNodo(nodo.getDerecho(), buscado); } } } return resultado; } public boolean esVacio(){ return this.raiz == null; } public int altira(){ int altura = 0; altura = this.getCantNiveles(this.raiz, altura); return altura; } private int getCantNiveles(NodoArbol nodo, int nivel){ if(nodo != null){ nivel = Math.max(this.getCantNiveles(nodo.getIzquierdo(), nivel + 1), this.getCantNiveles(nodo.getDerecho(), nivel+1)); } else { nivel--; } return nivel; } public int nivel (Object elemento){ int nivel; nivel = buscarNivel(this.raiz, 0, elemento); return nivel; } private int buscarNivel(NodoArbol nodo, int nivel, Object elemento){ int retorna = -1; if(nodo != null){ if(nodo.getElem().equals(elemento)){ retorna = nivel; } else { retorna = buscarNivel(nodo.getIzquierdo(), nivel + 1, elemento); } } return retorna; } public Object padre (Object elemento){ Object padre = null; padre = buscarPadre(this.raiz, elemento, padre); return padre; } private Object buscarPadre(NodoArbol nodo, Object hijo, Object padre){ Object retorna = null; if(nodo != null){ if(nodo.getElem().equals(hijo)){ retorna = padre; } else { retorna = buscarPadre(nodo.getIzquierdo(), hijo, nodo.getElem()); if(retorna == null){ retorna = buscarPadre(nodo.getDerecho(), hijo, nodo.getElem()); } } } return retorna; } public Lista listarPreorden() { Lista lista = new Lista(); listarPreordenAux(this.raiz, lista); return lista; } private void listarPreordenAux(NodoArbol nodo, Lista lista) { if (nodo != null) { lista.insertar(nodo.getElem(), lista.longitud() + 1); listarPreordenAux(nodo.getIzquierdo(), lista); listarPreordenAux(nodo.getDerecho(), lista); } } public Lista listarInorden() { Lista lista = new Lista(); listarInordenAux(this.raiz, lista); return lista; } private void listarInordenAux(NodoArbol nodo, Lista lista) { if (nodo != null) { listarInordenAux(nodo.getIzquierdo(), lista); lista.insertar(nodo.getElem(), lista.longitud() + 1); listarInordenAux(nodo.getDerecho(), lista); } } public Lista listarPosorden() { Lista lista = new Lista(); listarPosordenAux(this.raiz, lista); return lista; } private void listarPosordenAux(NodoArbol nodo, Lista lista) { if (nodo != null) { listarPosordenAux(nodo.getIzquierdo(), lista); listarPosordenAux(nodo.getDerecho(), lista); lista.insertar(nodo.getElem(), lista.longitud() + 1); } } public Lista listarPorNiveles() { Lista lista = new Lista(); if (this.raiz != null) { lista.insertar(this.raiz.getElem(), 1); listarPorNivelesAux(this.raiz, lista); } return lista; } private void listarPorNivelesAux(NodoArbol nodo, Lista lista) { if (nodo != null) { if (nodo.getIzquierdo() != null) { lista.insertar(nodo.getIzquierdo().getElem(), lista.longitud() + 1); } if (nodo.getDerecho() != null) { lista.insertar(nodo.getDerecho().getElem(), lista.longitud() + 1); } listarPorNivelesAux(nodo.getIzquierdo(), lista); listarPorNivelesAux(nodo.getDerecho(), lista); } } // Propias del tipo @Override public ArbolBin clone() { ArbolBin copia = new ArbolBin(); if (!this.esVacio()) { copia.raiz = clonAux(this.raiz); } return copia; } private NodoArbol clonAux(NodoArbol nodo) { NodoArbol nuevo = new NodoArbol(nodo.getElem()); if (nodo.getIzquierdo() != null) { nuevo.setIzquierdo(clonAux(nodo.getIzquierdo())); } if (nodo.getDerecho() != null) { nuevo.setDerecho(clonAux(nodo.getDerecho())); } return nuevo; } public Lista frontera() { Lista retorno = new Lista(); fronteraAux(this.raiz, retorno); return retorno; } private void fronteraAux(NodoArbol raiz, Lista lista) { if (raiz != null) { if (raiz.getIzquierdo() == null && raiz.getDerecho() == null) { lista.insertar(raiz.getElem(), lista.longitud() + 1); } else { if (raiz.getIzquierdo() != null) { fronteraAux(raiz.getIzquierdo(), lista); } if (raiz.getDerecho() != null) { fronteraAux(raiz.getDerecho(), lista); } } } } public boolean verificarPatron(Lista listaPatron) { boolean retorno = false; // Evaluamos que la lista no esta vacia if (listaPatron.esVacia()) { // En caso de que la lista este vacia y el arbol este vacio if (this.raiz == null) { retorno = true; } } else { // En caso de no estar la lista vacia y que el arbol no lo este if (this.raiz != null) { retorno = verificarPatronAux(this.raiz, listaPatron); } } return retorno; } private boolean verificarPatronAux(NodoArbol raiz, Lista listaPatron) { // Verificamos si el elemento en el frente de la lista es igual a la raiz boolean retorno = false; if (raiz != null && !listaPatron.esVacia()) { // Comparamos con la raiz Object primerElemento = listaPatron.recuperar(1); if (raiz.getElem().equals(primerElemento)) { // Si esta sacamos este elemento en la lista y llamamos con el HI boolean retornoIzquierdo = false; listaPatron.eliminar(1); retorno = true; if (raiz.getIzquierdo() != null) { retornoIzquierdo = verificarPatronAux(raiz.getIzquierdo(), listaPatron); retorno = retornoIzquierdo; } // Si no encontro el patron por el HI, lo busca por le HD if (raiz.getDerecho() != null && !retornoIzquierdo) { retorno = verificarPatronAux(raiz.getDerecho(), listaPatron); } } } return retorno; } public void modificarSubarboles(Object d1, Object d2, Object d3) { this.modificarSubarbolesAux(this.raiz, d1, d2, d3); } private void modificarSubarbolesAux(NodoArbol nodoActual, Object d1, Object d2, Object d3) { // Precondición: d1 debe ser distinto de d2 y d3 para no entrar en bucle if (nodoActual != null) { if (nodoActual.getIzquierdo() != null) { if (nodoActual.getElem().equals(d1)) { nodoActual.getIzquierdo().setValor(d2); } modificarSubarbolesAux(nodoActual.getIzquierdo(), d1, d2, d3); } else { if (nodoActual.getElem().equals(d1)) { nodoActual.setIzquierdo(new NodoArbol(d2)); } } if (nodoActual.getDerecho() != null) { if (nodoActual.getElem().equals(d1)) { nodoActual.getDerecho().setValor(d3); } modificarSubarbolesAux(nodoActual.getDerecho(), d1, d2, d3); } else { if (nodoActual.getElem().equals(d1)) { nodoActual.setDerecho(new NodoArbol(d3)); } } } } // Testing public String toString() { String cadena = "Arbol vacio"; if (this.raiz != null) { cadena = ""; cadena = stringAux(this.raiz, cadena); } return cadena; } private String stringAux(NodoArbol nodo, String cadena) { String cadena2 = cadena; cadena2 += "Nodo:" + nodo.getElem(); if (nodo.getIzquierdo() != null) { cadena2 += " HI:" + nodo.getIzquierdo().getElem(); } else { cadena2 += " HI:-"; } if (nodo.getDerecho() != null) { cadena2 += " HD:" + nodo.getDerecho().getElem() + "\n"; } else { cadena2 += " HD:- \n"; } if (nodo.getIzquierdo() != null) { cadena2 = stringAux(nodo.getIzquierdo(), cadena2); } if (nodo.getDerecho() != null) { cadena2 = stringAux(nodo.getDerecho(), cadena2); } return cadena2; } }
10,871
0.50644
0.501656
316
32.38924
24.099421
131
false
false
0
0
0
0
0
0
0.594937
false
false
12
03d98953da01572c1a3928a831fe8574c5394d49
28,638,841,991,600
1c537a761c95a80ddbbc372c0547883547780daa
/net/minecraft/server/v1_8_R3/LayerIsland.java
08785fe394714a61772fc16710e375cee34f4bbb
[]
no_license
NiotGG/spigot-1.8.8
https://github.com/NiotGG/spigot-1.8.8
eae8881f4a37eaecb58442e3558bea2634247b54
b2bbec2f037678a3f99d298a5a6a6cb1b98e79ce
refs/heads/master
2020-03-31T13:21:08.009000
2018-10-09T13:00:33
2018-10-09T13:00:33
152,251,977
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/* */ package net.minecraft.server.v1_8_R3; /* */ /* */ public class LayerIsland extends GenLayer { /* */ public LayerIsland(long paramLong) { /* 5 */ super(paramLong); /* */ } /* */ /* */ public int[] a(int paramInt1, int paramInt2, int paramInt3, int paramInt4) /* */ { /* 10 */ int[] arrayOfInt = IntCache.a(paramInt3 * paramInt4); /* 11 */ for (int i = 0; i < paramInt4; i++) { /* 12 */ for (int j = 0; j < paramInt3; j++) { /* 13 */ a(paramInt1 + j, paramInt2 + i); /* 14 */ arrayOfInt[(j + i * paramInt3)] = (a(10) == 0 ? 1 : 0); /* */ } /* */ } /* */ /* 18 */ if ((paramInt1 > -paramInt3) && (paramInt1 <= 0) && (paramInt2 > -paramInt4) && (paramInt2 <= 0)) { /* 19 */ arrayOfInt[(-paramInt1 + -paramInt2 * paramInt3)] = 1; /* */ } /* 21 */ return arrayOfInt; /* */ } /* */ } /* Location: C:\Users\USUARIO\Desktop\spigot-1.8.8-R0.1-SNAPSHOT-latest.jar!\net\minecraft\server\v1_8_R3\LayerIsland.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
UTF-8
Java
1,116
java
LayerIsland.java
Java
[]
null
[]
/* */ package net.minecraft.server.v1_8_R3; /* */ /* */ public class LayerIsland extends GenLayer { /* */ public LayerIsland(long paramLong) { /* 5 */ super(paramLong); /* */ } /* */ /* */ public int[] a(int paramInt1, int paramInt2, int paramInt3, int paramInt4) /* */ { /* 10 */ int[] arrayOfInt = IntCache.a(paramInt3 * paramInt4); /* 11 */ for (int i = 0; i < paramInt4; i++) { /* 12 */ for (int j = 0; j < paramInt3; j++) { /* 13 */ a(paramInt1 + j, paramInt2 + i); /* 14 */ arrayOfInt[(j + i * paramInt3)] = (a(10) == 0 ? 1 : 0); /* */ } /* */ } /* */ /* 18 */ if ((paramInt1 > -paramInt3) && (paramInt1 <= 0) && (paramInt2 > -paramInt4) && (paramInt2 <= 0)) { /* 19 */ arrayOfInt[(-paramInt1 + -paramInt2 * paramInt3)] = 1; /* */ } /* 21 */ return arrayOfInt; /* */ } /* */ } /* Location: C:\Users\USUARIO\Desktop\spigot-1.8.8-R0.1-SNAPSHOT-latest.jar!\net\minecraft\server\v1_8_R3\LayerIsland.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
1,116
0.500896
0.442652
29
37.517242
33.17625
136
false
false
0
0
0
0
0
0
0.517241
false
false
12
f5ebfc43d8a88e6c7610a7ce557c7f304e3f7a4d
11,948,599,026,680
367b2d29881cb1d562addd5d0c6398966eb590b0
/android_app/src/com/svenkapudija/imagewall/models/Location.java
741bf0cd1de055ce245dbdebcc88b36b97959bdb
[ "Apache-2.0" ]
permissive
Rudianasaja/ImageWall
https://github.com/Rudianasaja/ImageWall
5ffe7caf310e240878dba05d5eb2473f7d4b599f
d437d776951474133e8b92293cf097d0b328dcbb
refs/heads/master
2020-12-31T05:40:54.642000
2013-04-28T20:26:22
2013-04-28T20:26:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.svenkapudija.imagewall.models; import android.os.Parcel; import android.os.Parcelable; import com.j256.ormlite.field.DatabaseField; public class Location implements Parcelable { @DatabaseField(generatedId = true) private int id; @DatabaseField private double lat; @DatabaseField private double lon; public Location() { // TODO Auto-generated constructor stub } public Location(double lat, double lon) { this.lat = lat; this.lon = lon; } public double distanceTo(Location other) { float[] results = new float[2]; android.location.Location.distanceBetween(getLat(), getLon(), other.getLat(), other.getLon(), results); return results[0]; } public double getLat() { return lat; } public double getLon() { return lon; } public void setLat(double lat) { this.lat = lat; } public void setLon(double lon) { this.lon = lon; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeInt(id); parcel.writeDouble(lat); parcel.writeDouble(lon); } public void readFromParcel(Parcel source) { id = source.readInt(); lat = source.readDouble(); lon = source.readDouble(); } public static final Parcelable.Creator<Location> CREATOR = new Parcelable.Creator<Location>() { public Location createFromParcel(Parcel in) { Location route = new Location(); route.readFromParcel(in); return route; } @Override public Location[] newArray(int size) { return new Location[size]; } }; @Override public String toString() { return "Location [id=" + id + ", lat=" + lat + ", lon=" + lon + "]"; } }
UTF-8
Java
1,764
java
Location.java
Java
[ { "context": "package com.svenkapudija.imagewall.models;\n\nimport android.os.Parce", "end": 17, "score": 0.5062814950942993, "start": 14, "tag": "USERNAME", "value": "enk" } ]
null
[]
package com.svenkapudija.imagewall.models; import android.os.Parcel; import android.os.Parcelable; import com.j256.ormlite.field.DatabaseField; public class Location implements Parcelable { @DatabaseField(generatedId = true) private int id; @DatabaseField private double lat; @DatabaseField private double lon; public Location() { // TODO Auto-generated constructor stub } public Location(double lat, double lon) { this.lat = lat; this.lon = lon; } public double distanceTo(Location other) { float[] results = new float[2]; android.location.Location.distanceBetween(getLat(), getLon(), other.getLat(), other.getLon(), results); return results[0]; } public double getLat() { return lat; } public double getLon() { return lon; } public void setLat(double lat) { this.lat = lat; } public void setLon(double lon) { this.lon = lon; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeInt(id); parcel.writeDouble(lat); parcel.writeDouble(lon); } public void readFromParcel(Parcel source) { id = source.readInt(); lat = source.readDouble(); lon = source.readDouble(); } public static final Parcelable.Creator<Location> CREATOR = new Parcelable.Creator<Location>() { public Location createFromParcel(Parcel in) { Location route = new Location(); route.readFromParcel(in); return route; } @Override public Location[] newArray(int size) { return new Location[size]; } }; @Override public String toString() { return "Location [id=" + id + ", lat=" + lat + ", lon=" + lon + "]"; } }
1,764
0.681406
0.678005
94
17.776596
19.893415
105
false
false
0
0
0
0
0
0
1.62766
false
false
7
2c1a9edcdfb9c651133177dac84df49746923343
30,219,389,908,140
886086f836d47fd1743faa401b4ea8e063c2ac0a
/src/Search/Dfs/Permutation.java
5f00b88139adc54f394b0023de49adeaf6eba96c
[]
no_license
ntk01/algorithm
https://github.com/ntk01/algorithm
f4fdbe653b3211f62635ea76206c07b2dfa12c49
af33cbc9486915e5386538df25fbd447fac0aa1c
refs/heads/master
2022-03-07T02:40:02.124000
2022-02-08T14:43:43
2022-02-08T14:43:43
202,575,552
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//https://atcoder.jp/contests/abc054/tasks/abc054_c package Search.Dfs; import java.util.*; public class Permutation { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); List<Integer>[] lists = new ArrayList[n]; int cnt = 0; public static void main(String[] args) { new Permutation().run(); } void run() { for (int i=0; i<n; i++) lists[i] = new ArrayList<>(); for (int i=0; i<m; i++) { int s = sc.nextInt() - 1; int t = sc.nextInt() - 1; lists[s].add(t); lists[t].add(s); } String str = "0"; for (int i=1; i<n; i++) str += i; permutation(str, ""); System.out.print(cnt); } void permutation(String s, String res) { if (s.length() <= 1) { String tmp = res + s; if (tmp.charAt(0) == '0') { boolean f = true; for (int i=0; i<n-1; i++) { int now = Integer.parseInt(tmp.substring(i, i+1)); int next = Integer.parseInt(tmp.substring(i+1, i+2)); if (!lists[now].contains(next)) { f = false; break; } } if (f) cnt++; } } else { for (int i=0; i<s.length(); i++) { permutation(s.substring(0, i) + s.substring(i+1), res + s.charAt(i)); } } } }
UTF-8
Java
1,524
java
Permutation.java
Java
[]
null
[]
//https://atcoder.jp/contests/abc054/tasks/abc054_c package Search.Dfs; import java.util.*; public class Permutation { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); List<Integer>[] lists = new ArrayList[n]; int cnt = 0; public static void main(String[] args) { new Permutation().run(); } void run() { for (int i=0; i<n; i++) lists[i] = new ArrayList<>(); for (int i=0; i<m; i++) { int s = sc.nextInt() - 1; int t = sc.nextInt() - 1; lists[s].add(t); lists[t].add(s); } String str = "0"; for (int i=1; i<n; i++) str += i; permutation(str, ""); System.out.print(cnt); } void permutation(String s, String res) { if (s.length() <= 1) { String tmp = res + s; if (tmp.charAt(0) == '0') { boolean f = true; for (int i=0; i<n-1; i++) { int now = Integer.parseInt(tmp.substring(i, i+1)); int next = Integer.parseInt(tmp.substring(i+1, i+2)); if (!lists[now].contains(next)) { f = false; break; } } if (f) cnt++; } } else { for (int i=0; i<s.length(); i++) { permutation(s.substring(0, i) + s.substring(i+1), res + s.charAt(i)); } } } }
1,524
0.426509
0.410761
60
24.383333
20.436153
85
false
false
0
0
0
0
0
0
0.683333
false
false
7
42fcfffe67ddce6a2faabd45f38e4dc03aba3589
10,471,130,316,768
47606bcd117792a78fa082ec2110a7bbd7385572
/src/test/java/com/geomenum/core/domainmodel/menu/CoreSubmenuTests.java
82726bf201d68cdf6b3b06d04d39678df8e69f1c
[ "Apache-2.0" ]
permissive
martinjeannot/geomenum
https://github.com/martinjeannot/geomenum
62a52781f2d5ed6f8c2835ccdd214eff45327c63
ea4ef1a85089e3d35530b018806372f22d35e2aa
refs/heads/master
2021-01-12T05:30:51.465000
2017-01-03T19:22:12
2017-01-03T19:22:12
77,944,630
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright (c) 2014 Geomenum Inc. All Rights Reserved. */ package com.geomenum.core.domainmodel.menu; import com.geomenum.core.domainmodel.AbstractCoreDomainModelUnitTests; import org.testng.annotations.Test; import javax.validation.ValidationException; import static com.geomenum.core.domainmodel.menu.CoreSubmenuFixtures.*; import static org.testng.Assert.*; public class CoreSubmenuTests extends AbstractCoreDomainModelUnitTests { public void fromMap() { assertNotNull(CoreSubmenu.of(CoreSubmenuFixtures.newDto())); } public void toMap() { assertEquals(standardSubmenu().toMap(), CoreSubmenuFixtures.newDto()); } @Test(expectedExceptions = {ValidationException.class}) public void createWithNullId() { CoreSubmenu.of(newDtoWithoutId()); } @Test(expectedExceptions = {ValidationException.class}, expectedExceptionsMessageRegExp = "\\[com.geomenum.core.domainmodel.menu.CoreSubmenu\\] Validation failed :\n" + "localizedNames : may not be empty\n") public void createWithInvalidDto() { assertNull(CoreSubmenu.of(invalidDto())); } /*public void createNewSubmenu() { assertNotNull(CoreSubmenu.createNewSubmenu(MESSAGE_SOURCE, Lists.newArrayList(Locale.ENGLISH))); }*/ }
UTF-8
Java
1,305
java
CoreSubmenuTests.java
Java
[]
null
[]
/* * Copyright (c) 2014 Geomenum Inc. All Rights Reserved. */ package com.geomenum.core.domainmodel.menu; import com.geomenum.core.domainmodel.AbstractCoreDomainModelUnitTests; import org.testng.annotations.Test; import javax.validation.ValidationException; import static com.geomenum.core.domainmodel.menu.CoreSubmenuFixtures.*; import static org.testng.Assert.*; public class CoreSubmenuTests extends AbstractCoreDomainModelUnitTests { public void fromMap() { assertNotNull(CoreSubmenu.of(CoreSubmenuFixtures.newDto())); } public void toMap() { assertEquals(standardSubmenu().toMap(), CoreSubmenuFixtures.newDto()); } @Test(expectedExceptions = {ValidationException.class}) public void createWithNullId() { CoreSubmenu.of(newDtoWithoutId()); } @Test(expectedExceptions = {ValidationException.class}, expectedExceptionsMessageRegExp = "\\[com.geomenum.core.domainmodel.menu.CoreSubmenu\\] Validation failed :\n" + "localizedNames : may not be empty\n") public void createWithInvalidDto() { assertNull(CoreSubmenu.of(invalidDto())); } /*public void createNewSubmenu() { assertNotNull(CoreSubmenu.createNewSubmenu(MESSAGE_SOURCE, Lists.newArrayList(Locale.ENGLISH))); }*/ }
1,305
0.721839
0.718774
40
31.625
32.275909
124
false
false
0
0
0
0
0
0
0.35
false
false
7
32aa0aec891c2afee04cbf622c029b78252bac1c
22,995,254,951,880
b87403924ac496030afcfde844bb4a02c0f8f9f3
/plenumkode_v17/2017-02-22/Ytre.java
427b780fbc8a7a9f3f891496e89f6d771d3724d0
[]
no_license
soranhm/INF1010
https://github.com/soranhm/INF1010
513328e8befd7f6283014166850f7b51b645d8ad
026cd8e1b02c39de1abf9e427ad7694aff255d67
refs/heads/master
2022-11-19T19:05:00.978000
2020-07-19T13:23:42
2020-07-19T13:23:42
280,864,719
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Ytre { private int tall; public Ytre() { tall = 2; } public void metode() { tall++; } public class Indre { private int tall; public Indre() { tall = 0; } public void indreMetode() { System.out.println("Tall:" + tall); System.out.println("this.tall:" + this.tall); System.out.println("Ytre.this.tall:" + Ytre.this.tall); //tall2++; } } }
UTF-8
Java
498
java
Ytre.java
Java
[]
null
[]
public class Ytre { private int tall; public Ytre() { tall = 2; } public void metode() { tall++; } public class Indre { private int tall; public Indre() { tall = 0; } public void indreMetode() { System.out.println("Tall:" + tall); System.out.println("this.tall:" + this.tall); System.out.println("Ytre.this.tall:" + Ytre.this.tall); //tall2++; } } }
498
0.465863
0.459839
26
18.192308
17.387041
67
false
false
0
0
0
0
0
0
0.346154
false
false
7
d293229071cc8e629174a206d0147307d18b9894
32,117,765,489,033
e67198dbb402033fc9101efc7010dd767377f431
/rabbitmq/rabbitmq.consumer.two/src/main/java/com/course/rabbitmq/two/entity/InvoiceCreatedMessage.java
6d69de8716e76a3b59d7ae9ab10311fe1e2a9bc3
[ "Apache-2.0" ]
permissive
a2z-ice/spring-cloud-with-kubernetes
https://github.com/a2z-ice/spring-cloud-with-kubernetes
db266e9cc771280d8f933c5ce0b7a77c792b9ab8
1954de854b253a66140b5ac5ad6c3b6a2665c308
refs/heads/advance
2023-09-03T15:05:27.648000
2023-08-01T12:21:26
2023-08-01T12:21:26
186,196,516
1
1
Apache-2.0
false
2023-03-02T23:27:35
2019-05-12T01:01:50
2023-02-19T13:25:08
2023-03-02T23:27:35
57,027
2
3
4
Java
false
false
package com.course.rabbitmq.two.entity; import java.time.LocalDate; import com.fasterxml.jackson.annotation.JsonFormat; public class InvoiceCreatedMessage { private double amount; @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate createdDate; private String currency; private String invoiceNumber; public InvoiceCreatedMessage() { } public InvoiceCreatedMessage(double amount, LocalDate createdDate, String currency, String invoiceNumber) { super(); this.amount = amount; this.createdDate = createdDate; this.currency = currency; this.invoiceNumber = invoiceNumber; } public double getAmount() { return amount; } public LocalDate getCreatedDate() { return createdDate; } public String getCurrency() { return currency; } public String getInvoiceNumber() { return invoiceNumber; } public void setAmount(double amount) { this.amount = amount; } public void setCreatedDate(LocalDate createdDate) { this.createdDate = createdDate; } public void setCurrency(String currency) { this.currency = currency; } public void setInvoiceNumber(String invoiceNumber) { this.invoiceNumber = invoiceNumber; } @Override public String toString() { return "InvoiceCreatedMessage [amount=" + amount + ", createdDate=" + createdDate + ", currency=" + currency + ", invoiceNumber=" + invoiceNumber + "]"; } }
UTF-8
Java
1,368
java
InvoiceCreatedMessage.java
Java
[]
null
[]
package com.course.rabbitmq.two.entity; import java.time.LocalDate; import com.fasterxml.jackson.annotation.JsonFormat; public class InvoiceCreatedMessage { private double amount; @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate createdDate; private String currency; private String invoiceNumber; public InvoiceCreatedMessage() { } public InvoiceCreatedMessage(double amount, LocalDate createdDate, String currency, String invoiceNumber) { super(); this.amount = amount; this.createdDate = createdDate; this.currency = currency; this.invoiceNumber = invoiceNumber; } public double getAmount() { return amount; } public LocalDate getCreatedDate() { return createdDate; } public String getCurrency() { return currency; } public String getInvoiceNumber() { return invoiceNumber; } public void setAmount(double amount) { this.amount = amount; } public void setCreatedDate(LocalDate createdDate) { this.createdDate = createdDate; } public void setCurrency(String currency) { this.currency = currency; } public void setInvoiceNumber(String invoiceNumber) { this.invoiceNumber = invoiceNumber; } @Override public String toString() { return "InvoiceCreatedMessage [amount=" + amount + ", createdDate=" + createdDate + ", currency=" + currency + ", invoiceNumber=" + invoiceNumber + "]"; } }
1,368
0.736842
0.736842
68
19.117647
22.916428
110
false
false
0
0
0
0
0
0
1.279412
false
false
7
f26b3f316677f8eb431d9cf029c2cb736449f311
14,946,486,231,874
addb717e6e9afbaecd34390275f624e76a2e5748
/src/main/java/com/github/libgraviton/workerbase/model/file/MetadataAction.java
66ed497d66d15c5ae8be0e9aa0c8dca6bcbf4700
[]
no_license
alebon/graviton-worker-base-java
https://github.com/alebon/graviton-worker-base-java
0898b30541f763120e181ee1443dd55e7e24d6be
340e156f5f6db6cb644ad113fb33d50e07564242
refs/heads/master
2020-12-03T06:41:38.843000
2016-04-21T07:53:18
2016-04-21T07:53:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.libgraviton.workerbase.model.file; /** * <p>MetadataAction class.</p> * * @author Dario Nuevo * @version $Id: $Id */ public class MetadataAction { public String command; /** * <p>Getter for the field <code>command</code>.</p> * * @return a {@link java.lang.String} object. */ public String getCommand() { return command; } /** * <p>Setter for the field <code>command</code>.</p> * * @param command a {@link java.lang.String} object. */ public void setCommand(String command) { this.command = command; } }
UTF-8
Java
619
java
MetadataAction.java
Java
[ { "context": "\n/**\n * <p>MetadataAction class.</p>\n *\n * @author Dario Nuevo\n * @version $Id: $Id\n */\npublic class MetadataAct", "end": 116, "score": 0.999860405921936, "start": 105, "tag": "NAME", "value": "Dario Nuevo" } ]
null
[]
package com.github.libgraviton.workerbase.model.file; /** * <p>MetadataAction class.</p> * * @author <NAME> * @version $Id: $Id */ public class MetadataAction { public String command; /** * <p>Getter for the field <code>command</code>.</p> * * @return a {@link java.lang.String} object. */ public String getCommand() { return command; } /** * <p>Setter for the field <code>command</code>.</p> * * @param command a {@link java.lang.String} object. */ public void setCommand(String command) { this.command = command; } }
614
0.581583
0.581583
28
21.107143
19.191402
56
false
false
0
0
0
0
0
0
0.142857
false
false
7
19ca390e10f51cafc1c3e9e186508e38e8f1b395
28,965,259,508,745
987e6b6a6b112d41d9751c9b714900348df9a8a1
/spring-ws-core/src/main/java/org/springframework/ws/soap/axiom/AxiomSoap11Header.java
9ec4a7bf744e19da9784e0f988f0260df25d5a3b
[ "Apache-2.0" ]
permissive
gloriousking/spring-ws
https://github.com/gloriousking/spring-ws
3b47fb19c2d3a2b1ae34e74315bfa73f3fbf504c
694f3d814ed65d6c79cc210989005eaee2ac759d
refs/heads/master
2020-02-29T01:16:29.241000
2017-04-05T05:53:45
2017-04-05T05:53:45
88,234,086
2
0
null
true
2017-04-14T04:53:23
2017-04-14T04:53:23
2017-04-05T01:36:08
2017-04-05T05:53:51
19,745
0
0
0
null
null
null
/* * Copyright 2005-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ws.soap.axiom; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.axiom.soap.RolePlayer; import org.apache.axiom.soap.SOAPFactory; import org.apache.axiom.soap.SOAPHeader; import org.apache.axiom.soap.SOAPHeaderBlock; import org.springframework.util.ObjectUtils; import org.springframework.ws.soap.SoapHeaderElement; import org.springframework.ws.soap.soap11.Soap11Header; /** * Axiom-specific version of {@code org.springframework.ws.soap.Soap11Header}. * * @author Arjen Poutsma * @since 1.0.0 */ class AxiomSoap11Header extends AxiomSoapHeader implements Soap11Header { AxiomSoap11Header(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { super(axiomHeader, axiomFactory); } @Override @SuppressWarnings("unchecked") public Iterator<SoapHeaderElement> examineHeaderElementsToProcess(final String[] actors) { RolePlayer rolePlayer = null; if (!ObjectUtils.isEmpty(actors)) { rolePlayer = new RolePlayer() { public List<?> getRoles() { return Arrays.asList(actors); } public boolean isUltimateDestination() { return false; } }; } Iterator<SOAPHeaderBlock> result = (Iterator<SOAPHeaderBlock>)getAxiomHeader().getHeadersToProcess(rolePlayer); return new AxiomSoapHeaderElementIterator(result); } }
UTF-8
Java
1,953
java
AxiomSoap11Header.java
Java
[ { "context": "ringframework.ws.soap.Soap11Header}.\n *\n * @author Arjen Poutsma\n * @since 1.0.0\n */\nclass AxiomSoap11Header exten", "end": 1179, "score": 0.9998668432235718, "start": 1166, "tag": "NAME", "value": "Arjen Poutsma" } ]
null
[]
/* * Copyright 2005-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.ws.soap.axiom; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.axiom.soap.RolePlayer; import org.apache.axiom.soap.SOAPFactory; import org.apache.axiom.soap.SOAPHeader; import org.apache.axiom.soap.SOAPHeaderBlock; import org.springframework.util.ObjectUtils; import org.springframework.ws.soap.SoapHeaderElement; import org.springframework.ws.soap.soap11.Soap11Header; /** * Axiom-specific version of {@code org.springframework.ws.soap.Soap11Header}. * * @author <NAME> * @since 1.0.0 */ class AxiomSoap11Header extends AxiomSoapHeader implements Soap11Header { AxiomSoap11Header(SOAPHeader axiomHeader, SOAPFactory axiomFactory) { super(axiomHeader, axiomFactory); } @Override @SuppressWarnings("unchecked") public Iterator<SoapHeaderElement> examineHeaderElementsToProcess(final String[] actors) { RolePlayer rolePlayer = null; if (!ObjectUtils.isEmpty(actors)) { rolePlayer = new RolePlayer() { public List<?> getRoles() { return Arrays.asList(actors); } public boolean isUltimateDestination() { return false; } }; } Iterator<SOAPHeaderBlock> result = (Iterator<SOAPHeaderBlock>)getAxiomHeader().getHeadersToProcess(rolePlayer); return new AxiomSoapHeaderElementIterator(result); } }
1,946
0.760369
0.746544
63
30
28.114279
113
false
false
0
0
0
0
0
0
1.190476
false
false
7
371f8a5e1570d1494a541d0b6a2666d306cf340f
12,601,434,066,421
3b275dcc90163359a7171f9e4bea462c8b91719a
/EnergyMon/Master.java
6ba0ebb3493b4a5761736455fcc74d9467a6e190
[]
no_license
EmonFan/RS485PiAVR
https://github.com/EmonFan/RS485PiAVR
6484c3a2afb6192f3de0f96cb78ac9d21cdaed08
43b7af6daa6a643d27ce7e08c6103bba064c86c6
refs/heads/master
2021-04-02T14:13:41.440000
2020-03-18T23:15:10
2020-03-18T23:15:10
248,284,237
0
0
null
false
2020-03-18T23:15:12
2020-03-18T16:26:40
2020-03-18T22:42:31
2020-03-18T23:15:11
302
0
0
0
C
false
false
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import com.pi4j.io.serial.SerialPortException; public class Master { private static final int PKT_LEADIN_BYTE = 0x99; private static final int PKT_START_BYTE = 0xaa; private static final int SLAVE_BASE = 0xa0; private static final int MASTER_ID = 0x0b; private static final int PKTF_ACK = 0x01; private static final int PKTF_NACK = 0x02; private static final int PKTF_REQACK = 0x04; private static final int PKTF_REQID = 0x08; private static final int PKTF_COMMAND = 0x10; private static final int PKTF_RESERVED = 0x20; private static final int PKT_N_LEADIN = 4; //Bytes before PKT_FLAG private static final int PKT_LEADIN = 0x00; private static final int PKT_START = 0x01; private static final int PKT_DEST = 0x02; private static final int PKT_SOURCE = 0x03; private static final int PKT_FLAG = 0x04; private static final int PKT_LENGTH = 0x05; private static final int PKT_DATA = 0x06; private static final int PKT_CHECKSUM = 0x07; private static final int PKT_VALID = 0x08; private static final int PKT_NOT_VALID = 0x09; //Define the supported slave commands private static final int ENUMERATE_COUNT = 0xD0; private static final int ENUMERATE_ITEM = 0xD1; private static final int TRANSMIT_ITEM = 0xD2; public static void main(String[] args) throws InterruptedException { System.out.println("Master ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #07 as an output pin for our RS485 transmit mode pin final GpioPinDigitalOutput readEnable = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07); // create an instance of the serial communications class final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // print out the data received to the console String sData = event.getData(); char [] charArray = sData.toCharArray(); StringBuilder sb = new StringBuilder(); for (char b : charArray) { sb.append(String.format("%02X:", (byte)b)); } System.out.println(sb.toString()); } }); //Enable RS485 transmit mode readEnable.high(); try { // open the default serial port provided on the GPIO header serial.open(Serial.DEFAULT_COM_PORT, 230400); try { // write individual bytes to the serial transmit buffer //[PKT_LEADIN_BYTE, PKT_START_BYTE, slaveID, MASTER_ID, PKTF_REQID, 0x01, 0x00]) serial.write((byte) PKT_LEADIN_BYTE); serial.write((byte) PKT_START_BYTE); serial.write((byte) 0xa5); serial.write((byte) 0x0b); serial.write((byte) PKTF_REQID); serial.write((byte) 0x01); serial.write((byte) 0x00); serial.write((byte) 0xb8); } catch(IllegalStateException ex){ ex.printStackTrace(); } } catch(SerialPortException ex) { System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage()); return; } //Enable RS485 receive mode readEnable.low(); System.out.println("Sleeping for 3 seconds"); // wait 3 second before continuing Thread.sleep(3000); } }
UTF-8
Java
3,726
java
Master.java
Java
[]
null
[]
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import com.pi4j.io.serial.SerialPortException; public class Master { private static final int PKT_LEADIN_BYTE = 0x99; private static final int PKT_START_BYTE = 0xaa; private static final int SLAVE_BASE = 0xa0; private static final int MASTER_ID = 0x0b; private static final int PKTF_ACK = 0x01; private static final int PKTF_NACK = 0x02; private static final int PKTF_REQACK = 0x04; private static final int PKTF_REQID = 0x08; private static final int PKTF_COMMAND = 0x10; private static final int PKTF_RESERVED = 0x20; private static final int PKT_N_LEADIN = 4; //Bytes before PKT_FLAG private static final int PKT_LEADIN = 0x00; private static final int PKT_START = 0x01; private static final int PKT_DEST = 0x02; private static final int PKT_SOURCE = 0x03; private static final int PKT_FLAG = 0x04; private static final int PKT_LENGTH = 0x05; private static final int PKT_DATA = 0x06; private static final int PKT_CHECKSUM = 0x07; private static final int PKT_VALID = 0x08; private static final int PKT_NOT_VALID = 0x09; //Define the supported slave commands private static final int ENUMERATE_COUNT = 0xD0; private static final int ENUMERATE_ITEM = 0xD1; private static final int TRANSMIT_ITEM = 0xD2; public static void main(String[] args) throws InterruptedException { System.out.println("Master ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #07 as an output pin for our RS485 transmit mode pin final GpioPinDigitalOutput readEnable = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07); // create an instance of the serial communications class final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // print out the data received to the console String sData = event.getData(); char [] charArray = sData.toCharArray(); StringBuilder sb = new StringBuilder(); for (char b : charArray) { sb.append(String.format("%02X:", (byte)b)); } System.out.println(sb.toString()); } }); //Enable RS485 transmit mode readEnable.high(); try { // open the default serial port provided on the GPIO header serial.open(Serial.DEFAULT_COM_PORT, 230400); try { // write individual bytes to the serial transmit buffer //[PKT_LEADIN_BYTE, PKT_START_BYTE, slaveID, MASTER_ID, PKTF_REQID, 0x01, 0x00]) serial.write((byte) PKT_LEADIN_BYTE); serial.write((byte) PKT_START_BYTE); serial.write((byte) 0xa5); serial.write((byte) 0x0b); serial.write((byte) PKTF_REQID); serial.write((byte) 0x01); serial.write((byte) 0x00); serial.write((byte) 0xb8); } catch(IllegalStateException ex){ ex.printStackTrace(); } } catch(SerialPortException ex) { System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage()); return; } //Enable RS485 receive mode readEnable.low(); System.out.println("Sleeping for 3 seconds"); // wait 3 second before continuing Thread.sleep(3000); } }
3,726
0.678476
0.647075
110
32.863636
23.16403
91
false
false
0
0
0
0
0
0
0.609091
false
false
7
649f17c36e65c108fd6d0bca8a5474990357382e
33,775,622,828,175
b24818a948152b06c7d85ac442e9b37cb6becbbc
/src/main/java/com/ash/experiments/performance/whitespace/Class1311.java
52a5c70a301f7608f56f89c47e1bc73d6f411f28
[]
no_license
ajorpheus/whitespace-perf-test
https://github.com/ajorpheus/whitespace-perf-test
d0797b6aa3eea1435eaa1032612f0874537c58b8
d2b695aa09c6066fbba0aceb230fa4e308670b32
refs/heads/master
2020-04-17T23:38:39.420000
2014-06-02T09:27:17
2014-06-02T09:27:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Class1311 {}
UTF-8
Java
41
java
Class1311.java
Java
[]
null
[]
public class Class1311 {}
41
0.487805
0.390244
1
25
0
25
false
false
0
0
0
0
0
0
0
false
false
7
f2240293a6ea3b74c1fe41552960c3161968413f
13,494,787,267,318
ff2950931ad24467c7f29c19ef63ae90fd469dba
/app/src/main/java/com/xmfraker/cargo/view/CommonDialog.java
0d5dd71f092738f4b35968f320d9fbcf9174a3cc
[]
no_license
ws00801526/Cargo
https://github.com/ws00801526/Cargo
0e82c5edb315e3189aad1fd892dd9581f64e5cf6
251fdac3a584d25699327b59db26931087e50200
refs/heads/master
2020-05-14T23:50:48.456000
2019-05-18T16:22:34
2019-05-18T16:22:34
182,002,544
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xmfraker.cargo.view; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.TextView; import com.xmfraker.cargo.R; public class CommonDialog extends Dialog implements View.OnClickListener { private TextView contentTxt; private TextView titleTxt; private TextView submitTxt; private TextView cancelTxt; private Context mContext; private String mContent = ""; private String mTitle = ""; private OnCloseListener mListener; private String mPositive = ""; private String mNegative = ""; public CommonDialog(Context context) { super(context); this.mContext = context; } public CommonDialog(Context context, OnCloseListener listener) { super(context); this.mContext = context; this.mListener = listener; } public CommonDialog setTitle(String title) { mTitle = title; return this; } public CommonDialog setContent(String content) { mContent = content; return this; } public CommonDialog setPositive(String positive) { mPositive = positive; return this; } public CommonDialog setNegative(String negative) { mNegative = negative; return this; } public CommonDialog setListener(OnCloseListener listener) { mListener = listener; return this; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog_common); setCanceledOnTouchOutside(false); initView(); } private void initView() { contentTxt = findViewById(R.id.content); titleTxt = findViewById(R.id.title); submitTxt = findViewById(R.id.submit); submitTxt.setOnClickListener(this); cancelTxt = findViewById(R.id.cancel); cancelTxt.setOnClickListener(this); setText(titleTxt, mTitle); setText(contentTxt, mContent); setText(submitTxt, mPositive); setText(cancelTxt, mNegative); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.cancel: if (mListener != null) { mListener.onClick(this, false); } break; case R.id.submit: if (mListener != null) { mListener.onClick(this, true); } break; } this.dismiss(); } private void setText(TextView textView, String text) { if (text == null || text.isEmpty()) { textView.setVisibility(View.GONE); } else { textView.setText(text); textView.setVisibility(View.VISIBLE); } } public interface OnCloseListener { void onClick(Dialog dialog, boolean confirm); } }
UTF-8
Java
3,054
java
CommonDialog.java
Java
[]
null
[]
package com.xmfraker.cargo.view; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.TextView; import com.xmfraker.cargo.R; public class CommonDialog extends Dialog implements View.OnClickListener { private TextView contentTxt; private TextView titleTxt; private TextView submitTxt; private TextView cancelTxt; private Context mContext; private String mContent = ""; private String mTitle = ""; private OnCloseListener mListener; private String mPositive = ""; private String mNegative = ""; public CommonDialog(Context context) { super(context); this.mContext = context; } public CommonDialog(Context context, OnCloseListener listener) { super(context); this.mContext = context; this.mListener = listener; } public CommonDialog setTitle(String title) { mTitle = title; return this; } public CommonDialog setContent(String content) { mContent = content; return this; } public CommonDialog setPositive(String positive) { mPositive = positive; return this; } public CommonDialog setNegative(String negative) { mNegative = negative; return this; } public CommonDialog setListener(OnCloseListener listener) { mListener = listener; return this; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog_common); setCanceledOnTouchOutside(false); initView(); } private void initView() { contentTxt = findViewById(R.id.content); titleTxt = findViewById(R.id.title); submitTxt = findViewById(R.id.submit); submitTxt.setOnClickListener(this); cancelTxt = findViewById(R.id.cancel); cancelTxt.setOnClickListener(this); setText(titleTxt, mTitle); setText(contentTxt, mContent); setText(submitTxt, mPositive); setText(cancelTxt, mNegative); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.cancel: if (mListener != null) { mListener.onClick(this, false); } break; case R.id.submit: if (mListener != null) { mListener.onClick(this, true); } break; } this.dismiss(); } private void setText(TextView textView, String text) { if (text == null || text.isEmpty()) { textView.setVisibility(View.GONE); } else { textView.setText(text); textView.setVisibility(View.VISIBLE); } } public interface OnCloseListener { void onClick(Dialog dialog, boolean confirm); } }
3,054
0.614931
0.614931
117
25.102564
18.694752
74
false
false
0
0
0
0
0
0
0.581197
false
false
7
dcf7f3117ef6ecb69b4c1ffcd50a59919f997925
231,928,282,557
a1266e15656c69a990ec0c719f8c0e113827e46e
/stone/src/main/java/com/coldraincn/stone/ast/NumberLiteral.java
cf1d0b07b44442382882e7c9ad31755d56730ce0
[]
no_license
coldraincn/compillerstudy
https://github.com/coldraincn/compillerstudy
ebfc8dc1269a9b7bce0e47594d20553a5fcbead0
3827fcf08d6f7fb6a3267ca483e4b02b025656c8
refs/heads/master
2021-01-09T11:02:39.543000
2020-06-05T12:10:13
2020-06-05T12:10:13
242,275,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.coldraincn.stone.ast; import com.coldraincn.chap6.Environment; import com.coldraincn.stone.Lexer; import com.coldraincn.stone.Token; public class NumberLiteral extends ASTLeaf { public NumberLiteral(Token t) { super(t); } public int value() { return token().getNumber(); } public Object eval(Environment e) { return value(); } }
UTF-8
Java
361
java
NumberLiteral.java
Java
[]
null
[]
package com.coldraincn.stone.ast; import com.coldraincn.chap6.Environment; import com.coldraincn.stone.Lexer; import com.coldraincn.stone.Token; public class NumberLiteral extends ASTLeaf { public NumberLiteral(Token t) { super(t); } public int value() { return token().getNumber(); } public Object eval(Environment e) { return value(); } }
361
0.728532
0.725762
14
24.857143
21.839863
57
false
false
0
0
0
0
0
0
0.5
false
false
7
1c7d0cb51657ae6e6679214c9b20adffbdab4ccf
35,613,868,820,303
2b109ed7dbd02e2386285fb6abe574b1ed2567d2
/src/main/java/com/jins/book/springboot/domain/posts/PostsRepository.java
6296ee587ed267f1493a0924900292b5b1258577
[]
no_license
JinHee8989/springbootAndAWS
https://github.com/JinHee8989/springbootAndAWS
3f2b4afd8b8014d66eee48b99d0c06d53612bab0
308d8994d05b8dd87fe818a30b0507673cef3d9b
refs/heads/master
2023-03-08T01:54:45.029000
2021-02-24T14:18:20
2021-02-24T14:18:20
330,416,580
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jins.book.springboot.domain.posts; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.Arrays; import java.util.List; public interface PostsRepository extends JpaRepository<Posts,Long> { //JpsRepository<Entity클래스, PK타입>하면 기본적인 CRUD 메소드가 자동으로 생성됨 @Query(value = "SELECT p FROM Posts p ORDER BY p.id DESC") List<Posts> findAllDesc(); }
UTF-8
Java
484
java
PostsRepository.java
Java
[]
null
[]
package com.jins.book.springboot.domain.posts; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.Arrays; import java.util.List; public interface PostsRepository extends JpaRepository<Posts,Long> { //JpsRepository<Entity클래스, PK타입>하면 기본적인 CRUD 메소드가 자동으로 생성됨 @Query(value = "SELECT p FROM Posts p ORDER BY p.id DESC") List<Posts> findAllDesc(); }
484
0.781818
0.781818
14
30.428572
35.473763
127
false
false
0
0
0
0
0
0
0.571429
false
false
7
fd6dfa9a784269145809f8077c2db984312dc158
33,045,478,399,502
b4fbc667fc436cc554c2c385d7072da678ed67dd
/src/main/java/com/librarystill/pojo/ViewAddress.java
296d0fbff4cc02a86d89d9991b2f295918d8e4ef
[]
no_license
leiwangit/librarystill
https://github.com/leiwangit/librarystill
cf6c789a6a6af348ab94da8cf5847dde49add3d3
91f4ceeee3a4e3792d5dc229aa45c2c8f15b62bf
refs/heads/master
2020-03-27T04:28:09.692000
2018-09-22T03:28:47
2018-09-22T03:28:47
145,942,379
1
9
null
false
2018-08-24T08:32:06
2018-08-24T04:28:50
2018-08-24T08:20:49
2018-08-24T08:20:48
8,995
0
9
1
HTML
false
null
package com.librarystill.pojo; public class ViewAddress { private int vId; private String vName; private String vProvince; private String vCity; private String vArea; private String vAddress; private String vPhone; private int vWeight; public int getvWeight() { return vWeight; } public void setvWeight(int vWeight) { this.vWeight = vWeight; } public int getvId() { return vId; } public void setvId(int vId) { this.vId = vId; } public String getvName() { return vName; } public void setvName(String vName) { this.vName = vName; } public String getvProvince() { return vProvince; } public void setvProvince(String vProvince) { this.vProvince = vProvince; } public String getvCity() { return vCity; } public void setvCity(String vCity) { this.vCity = vCity; } public String getvArea() { return vArea; } public void setvArea(String vArea) { this.vArea = vArea; } public String getvAddress() { return vAddress; } public void setvAddress(String vAddress) { this.vAddress = vAddress; } public String getvPhone() { return vPhone; } public void setvPhone(String vPhone) { this.vPhone = vPhone; } }
UTF-8
Java
1,395
java
ViewAddress.java
Java
[]
null
[]
package com.librarystill.pojo; public class ViewAddress { private int vId; private String vName; private String vProvince; private String vCity; private String vArea; private String vAddress; private String vPhone; private int vWeight; public int getvWeight() { return vWeight; } public void setvWeight(int vWeight) { this.vWeight = vWeight; } public int getvId() { return vId; } public void setvId(int vId) { this.vId = vId; } public String getvName() { return vName; } public void setvName(String vName) { this.vName = vName; } public String getvProvince() { return vProvince; } public void setvProvince(String vProvince) { this.vProvince = vProvince; } public String getvCity() { return vCity; } public void setvCity(String vCity) { this.vCity = vCity; } public String getvArea() { return vArea; } public void setvArea(String vArea) { this.vArea = vArea; } public String getvAddress() { return vAddress; } public void setvAddress(String vAddress) { this.vAddress = vAddress; } public String getvPhone() { return vPhone; } public void setvPhone(String vPhone) { this.vPhone = vPhone; } }
1,395
0.589247
0.589247
76
17.355263
14.551817
48
false
false
0
0
0
0
0
0
0.328947
false
false
7
38715275822db1c773831e6f290404f724a361b7
12,189,117,203,014
4b7640c01198b1705be1ea33b3a685e2296e2214
/email-consumer/src/main/java/br/com/deveria/devtest/emailconsumer/EmailConsumerApplication.java
b8ef7666da61276efb938e6ef543eed83f1903d3
[]
no_license
thiagobcar/dev-test
https://github.com/thiagobcar/dev-test
862d8a11f93816dabb4a4d28ac0b8a10c7e48a7c
6336633703d18f41ea6728c3d408ab50dce09630
refs/heads/master
2020-04-02T11:49:53.905000
2018-10-29T04:26:37
2018-10-29T04:26:37
154,408,608
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.deveria.devtest.emailconsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @EnableConfigurationProperties @SpringBootApplication public class EmailConsumerApplication { public static void main(String[] args) { SpringApplication.run(EmailConsumerApplication.class, args); } }
UTF-8
Java
455
java
EmailConsumerApplication.java
Java
[]
null
[]
package br.com.deveria.devtest.emailconsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @EnableConfigurationProperties @SpringBootApplication public class EmailConsumerApplication { public static void main(String[] args) { SpringApplication.run(EmailConsumerApplication.class, args); } }
455
0.852747
0.852747
14
31.5
27.062757
81
false
false
0
0
0
0
0
0
0.714286
false
false
7
06a7ce27b308aa3be1f489eacc9e1edb8f4b9882
5,145,370,859,242
5a895cc38c3228bededf242dca6bbd2d0aa9515c
/src/main/java/com/tangwh/dto/AccessTokenDTO.java
40073e2396513463339b7d9ee8cd6b1c6d3f64ac
[]
no_license
small-howe/TechnicalCommunity
https://github.com/small-howe/TechnicalCommunity
954bfc41a26233e4a88d87e4c9532985451ceebc
1acd6fae818450168afaa1258f80a5e115a4671d
refs/heads/master
2022-07-05T14:50:59.595000
2020-07-02T01:24:13
2020-07-02T01:24:13
202,955,725
0
0
null
false
2022-06-21T01:41:24
2019-08-18T03:33:37
2020-07-02T01:24:17
2022-06-21T01:41:23
2,670
0
0
2
Java
false
false
package com.tangwh.dto; import lombok.Data; /** * Created by codedrinker on 2019/4/24. */ // alt + fn+f12 get set 方法(全选属性 shift+向下) 和 创建类 //导包 alt+ 回车 //提取变量 ctrl + alt +v // ctrl +e 切换临时的目录 //shift +f12 当前页面最大化 // 双击 shift 查找页面并进入 // ctrl +alt +L 格式化代码 //shift + Enter 换行 @Data public class AccessTokenDTO { //必填。您在注册时从GitHub收到的客户ID 。 private String client_id; // 需要。您从GitHub收到的GitHub应用程序的客户机密 private String client_secret; //需要。您收到的代码作为对第1步的回复。 private String code; // 应用程序中的URL,用于在授权后发送用户 private String redirect_uri; //您在步骤1中提供的不可思议的随机字符串。 private String state; }
UTF-8
Java
899
java
AccessTokenDTO.java
Java
[ { "context": "ngwh.dto;\n\n\nimport lombok.Data;\n\n/**\n * Created by codedrinker on 2019/4/24.\n */\n// alt + fn+f12 get set 方法(全选属性", "end": 76, "score": 0.9994679093360901, "start": 65, "tag": "USERNAME", "value": "codedrinker" } ]
null
[]
package com.tangwh.dto; import lombok.Data; /** * Created by codedrinker on 2019/4/24. */ // alt + fn+f12 get set 方法(全选属性 shift+向下) 和 创建类 //导包 alt+ 回车 //提取变量 ctrl + alt +v // ctrl +e 切换临时的目录 //shift +f12 当前页面最大化 // 双击 shift 查找页面并进入 // ctrl +alt +L 格式化代码 //shift + Enter 换行 @Data public class AccessTokenDTO { //必填。您在注册时从GitHub收到的客户ID 。 private String client_id; // 需要。您从GitHub收到的GitHub应用程序的客户机密 private String client_secret; //需要。您收到的代码作为对第1步的回复。 private String code; // 应用程序中的URL,用于在授权后发送用户 private String redirect_uri; //您在步骤1中提供的不可思议的随机字符串。 private String state; }
899
0.670947
0.65008
30
19.766666
12.909127
49
false
false
0
0
0
0
0
0
0.266667
false
false
7
23ad6d883473fe189329bfcd00e18cda75005164
19,301,583,046,127
781d9d8be81e311b344f52cc38074bf492073670
/src/com/doyd/utils/CookieUtil.java
3740986571adbdcd5709d9fb71777ac33a3b76a6
[]
no_license
Hidden21/doydisuuue
https://github.com/Hidden21/doydisuuue
04766f38ada2d366327ffff27d9c8295f0597fbc
1105b04416a3764a71a6d539154ad0a4dfa450f9
refs/heads/master
2020-04-15T19:15:51.460000
2014-07-18T14:25:39
2014-07-18T14:25:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.doyd.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieUtil { private static final String USER_NAME = "USER_NAME"; private static final String LOGIN_AT = "LOGIN_AT"; private static final String USER_RT = "USER_RT"; private static final String USER_BL = "USER_BL"; private static final String USER_STATE = "USER_STATE"; // private static final String EXPIRY_AT = "EXPIRY_AT"; private static final String HX1 = "doyd"; private static final String HX2 = "!@#$"; private static final String HX3 = "+-*/"; private static final int MAX_AGE = 3 * 24 * 3600; public static void addCookie(HttpServletResponse response,String cookieName,String value){ Cookie cook = new Cookie(cookieName,String.valueOf(value)); cook.setPath("/"); cook.setMaxAge(60 * 60 * 24*30*365); response.addCookie(cook); } public static String getCookie(HttpServletRequest request,String cookieName){ String value = ""; Cookie[] cs = request.getCookies(); if (cs != null && cs.length >1) {//获取cookie信息 for(Cookie c:cs){ if(cookieName.equals(c.getName())){ value = c.getValue(); break; } } } return value; } /** * 登录成功后保存COOKIE状态 * @param request * @param response * @param loginUserName * @param autoLoginState 以后访问页面时,是否自动登陆,true以后自动登陆, false以后不自动登陆 * @param autoLogin 当前登录时,true:cookie自动登陆, false:手动登录 */ public static void addLoginCookies(HttpServletRequest request, HttpServletResponse response, String loginUserName, boolean autoLoginState, boolean autoLogin){ if(StringUtil.isEmpty(loginUserName) || response==null){ return; } int maxAge = -1; if(autoLogin){ maxAge = MAX_AGE; }else{ maxAge = autoLoginState?MAX_AGE:-1; } deleteCookies(request, response, false); String path = request.getContextPath(); // String domain = request.getHeader("host"); //用户名 Cookie userNameCookie = new Cookie(USER_NAME, loginUserName); userNameCookie.setPath(path); userNameCookie.setMaxAge(maxAge); // userNameCookie.setDomain(domain); response.addCookie(userNameCookie); //登录时间 long loginAt = System.currentTimeMillis()/1000l;//登录时间 Cookie loginAtCookie = new Cookie(LOGIN_AT, loginAt+""); loginAtCookie.setPath(path); loginAtCookie.setMaxAge(maxAge); // loginAtCookie.setDomain(domain); response.addCookie(loginAtCookie); //随机标签 String userRandomTag = DoydTagCheck.generateTag((int)(loginAt%1000), 16); Cookie userRandomTagCookie = new Cookie(USER_RT, userRandomTag); userRandomTagCookie.setPath(path); userRandomTagCookie.setMaxAge(maxAge); // userRandomTagCookie.setDomain(domain); response.addCookie(userRandomTagCookie); //防伪标签bogus label String userBogusLabel = getUserBogusLabel(loginUserName, loginAt, userRandomTag); Cookie userBogusLabelCookie = new Cookie(USER_BL, userBogusLabel); userBogusLabelCookie.setPath(path); userBogusLabelCookie.setMaxAge(maxAge); // userBogusLabelCookie.setDomain(domain); response.addCookie(userBogusLabelCookie); //当前登录标签 String userState = getUserState(loginUserName, loginAt, userRandomTag, userBogusLabel); Cookie userStateCookie = new Cookie(USER_STATE, userState); userStateCookie.setPath(path); userStateCookie.setMaxAge(-1); // userStateCookie.setDomain(domain); response.addCookie(userStateCookie); } /** * 检查是否合法的COOKIE<br/> * 0:无效<br/> * 1:有效,但是还没有登录<br/> * 2:有效,且已经登录<br/> * @param cookies * @param checkUserState 是否检查登录标签 * */ public static int checkLoginCookies(Cookie[] cookies){ if(cookies==null || cookies.length<=0){ return 0; } String loginUserName = null; long loginAt = 0l; String userRandomTag = null; String userBogusLabel = null; String userState = null; for(Cookie cookie: cookies){ if(cookie.getMaxAge()==0){ continue; } if(USER_NAME.equals(cookie.getName())){ loginUserName = cookie.getValue(); }else if(LOGIN_AT.equals(cookie.getName())){ loginAt = StringUtil.parseLong(cookie.getValue()); }else if(USER_RT.equals(cookie.getName())){ userRandomTag = cookie.getValue(); }else if(USER_BL.equals(cookie.getName())){ userBogusLabel = cookie.getValue(); }else if(USER_STATE.equals(cookie.getName())){ userState = cookie.getValue(); } } if(StringUtil.isEmpty(loginUserName) || loginAt<(System.currentTimeMillis()/1000-MAX_AGE) || StringUtil.isEmpty(userRandomTag) || StringUtil.isEmpty(userBogusLabel) ){ return 0; } if(!DoydTagCheck.checkTag((int)(loginAt%1000), userRandomTag)){ return 0; } String tmpUserBogusLabel = getUserBogusLabel(loginUserName, loginAt, userRandomTag); if(StringUtil.isNotEmpty(userState)){ String tmpUserState = getUserState(loginUserName, loginAt, userRandomTag, userBogusLabel); return userBogusLabel.equals(tmpUserBogusLabel) && userState.equals(tmpUserState)?2:0; }else{ return userBogusLabel.equals(tmpUserBogusLabel)?1:0; } } public static String getSuNameValue(Cookie[] cookies){ return getValue(cookies, USER_NAME); } public static String getValue(Cookie[] cookies, String name){ if(cookies==null || cookies.length<=0 || StringUtil.isEmpty(name)){ return null; } for(Cookie cookie: cookies){ if(name.equals(cookie.getName())){ String value = cookie.getValue(); return value; } } return null; } public static void deleteCookies(HttpServletRequest request, HttpServletResponse response, boolean deleteSessionId){ String path = request.getContextPath(); // String domain = request.getHeader("host"); Cookie[] cookies = request.getCookies(); if(cookies==null || cookies.length<=0){ return; } for(Cookie cookie: cookies){ if("JSESSIONID".equalsIgnoreCase(cookie.getName()) && !deleteSessionId){ continue; } cookie.setMaxAge(0); cookie.setPath(path); // c.setDomain(domain); response.addCookie(cookie); } } private static String getUserBogusLabel(String loginUserName, long loginAt, String userRandomTag){ return EncryptUtil.MD5(loginUserName + HX2 + loginAt + HX1 + userRandomTag); } private static String getUserState(String loginUserName, long loginAt, String userRandomTag, String userBogusLabel){ return EncryptUtil.MD5(loginUserName + HX1 +loginAt + HX2 + userRandomTag + HX3 + userBogusLabel); } }
UTF-8
Java
6,865
java
CookieUtil.java
Java
[ { "context": "Util {\r\n\tprivate static final String USER_NAME = \"USER_NAME\";\r\n\tprivate static final String LOGIN_AT = \"LOGIN", "end": 237, "score": 0.9989205002784729, "start": 228, "tag": "USERNAME", "value": "USER_NAME" }, { "context": "名\r\n\t\tCookie userNameCookie = new Cookie(USER_NAME, loginUserName);\r\n\t\tuserNameCookie.setPath(path);\r\n\t\tuserNameCoo", "end": 2119, "score": 0.9297181367874146, "start": 2106, "tag": "USERNAME", "value": "loginUserName" }, { "context": "abel\r\n\t\tString userBogusLabel = getUserBogusLabel(loginUserName, loginAt, userRandomTag);\r\n\t\tCookie userBogusLabe", "end": 2952, "score": 0.8438389301300049, "start": 2939, "tag": "USERNAME", "value": "loginUserName" }, { "context": "\t//当前登录标签\r\n\t\tString userState = getUserState(loginUserName, loginAt, userRandomTag, userBogusLabel);\r\n\t\tCook", "end": 3285, "score": 0.9602169394493103, "start": 3277, "tag": "USERNAME", "value": "UserName" }, { "context": "<=0){\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tString loginUserName = null;\r\n\t\tlong loginAt = 0l;\r\n\t\tString userRandomTag = ", "end": 3859, "score": 0.6283692717552185, "start": 3855, "tag": "USERNAME", "value": "null" } ]
null
[]
package com.doyd.utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieUtil { private static final String USER_NAME = "USER_NAME"; private static final String LOGIN_AT = "LOGIN_AT"; private static final String USER_RT = "USER_RT"; private static final String USER_BL = "USER_BL"; private static final String USER_STATE = "USER_STATE"; // private static final String EXPIRY_AT = "EXPIRY_AT"; private static final String HX1 = "doyd"; private static final String HX2 = "!@#$"; private static final String HX3 = "+-*/"; private static final int MAX_AGE = 3 * 24 * 3600; public static void addCookie(HttpServletResponse response,String cookieName,String value){ Cookie cook = new Cookie(cookieName,String.valueOf(value)); cook.setPath("/"); cook.setMaxAge(60 * 60 * 24*30*365); response.addCookie(cook); } public static String getCookie(HttpServletRequest request,String cookieName){ String value = ""; Cookie[] cs = request.getCookies(); if (cs != null && cs.length >1) {//获取cookie信息 for(Cookie c:cs){ if(cookieName.equals(c.getName())){ value = c.getValue(); break; } } } return value; } /** * 登录成功后保存COOKIE状态 * @param request * @param response * @param loginUserName * @param autoLoginState 以后访问页面时,是否自动登陆,true以后自动登陆, false以后不自动登陆 * @param autoLogin 当前登录时,true:cookie自动登陆, false:手动登录 */ public static void addLoginCookies(HttpServletRequest request, HttpServletResponse response, String loginUserName, boolean autoLoginState, boolean autoLogin){ if(StringUtil.isEmpty(loginUserName) || response==null){ return; } int maxAge = -1; if(autoLogin){ maxAge = MAX_AGE; }else{ maxAge = autoLoginState?MAX_AGE:-1; } deleteCookies(request, response, false); String path = request.getContextPath(); // String domain = request.getHeader("host"); //用户名 Cookie userNameCookie = new Cookie(USER_NAME, loginUserName); userNameCookie.setPath(path); userNameCookie.setMaxAge(maxAge); // userNameCookie.setDomain(domain); response.addCookie(userNameCookie); //登录时间 long loginAt = System.currentTimeMillis()/1000l;//登录时间 Cookie loginAtCookie = new Cookie(LOGIN_AT, loginAt+""); loginAtCookie.setPath(path); loginAtCookie.setMaxAge(maxAge); // loginAtCookie.setDomain(domain); response.addCookie(loginAtCookie); //随机标签 String userRandomTag = DoydTagCheck.generateTag((int)(loginAt%1000), 16); Cookie userRandomTagCookie = new Cookie(USER_RT, userRandomTag); userRandomTagCookie.setPath(path); userRandomTagCookie.setMaxAge(maxAge); // userRandomTagCookie.setDomain(domain); response.addCookie(userRandomTagCookie); //防伪标签bogus label String userBogusLabel = getUserBogusLabel(loginUserName, loginAt, userRandomTag); Cookie userBogusLabelCookie = new Cookie(USER_BL, userBogusLabel); userBogusLabelCookie.setPath(path); userBogusLabelCookie.setMaxAge(maxAge); // userBogusLabelCookie.setDomain(domain); response.addCookie(userBogusLabelCookie); //当前登录标签 String userState = getUserState(loginUserName, loginAt, userRandomTag, userBogusLabel); Cookie userStateCookie = new Cookie(USER_STATE, userState); userStateCookie.setPath(path); userStateCookie.setMaxAge(-1); // userStateCookie.setDomain(domain); response.addCookie(userStateCookie); } /** * 检查是否合法的COOKIE<br/> * 0:无效<br/> * 1:有效,但是还没有登录<br/> * 2:有效,且已经登录<br/> * @param cookies * @param checkUserState 是否检查登录标签 * */ public static int checkLoginCookies(Cookie[] cookies){ if(cookies==null || cookies.length<=0){ return 0; } String loginUserName = null; long loginAt = 0l; String userRandomTag = null; String userBogusLabel = null; String userState = null; for(Cookie cookie: cookies){ if(cookie.getMaxAge()==0){ continue; } if(USER_NAME.equals(cookie.getName())){ loginUserName = cookie.getValue(); }else if(LOGIN_AT.equals(cookie.getName())){ loginAt = StringUtil.parseLong(cookie.getValue()); }else if(USER_RT.equals(cookie.getName())){ userRandomTag = cookie.getValue(); }else if(USER_BL.equals(cookie.getName())){ userBogusLabel = cookie.getValue(); }else if(USER_STATE.equals(cookie.getName())){ userState = cookie.getValue(); } } if(StringUtil.isEmpty(loginUserName) || loginAt<(System.currentTimeMillis()/1000-MAX_AGE) || StringUtil.isEmpty(userRandomTag) || StringUtil.isEmpty(userBogusLabel) ){ return 0; } if(!DoydTagCheck.checkTag((int)(loginAt%1000), userRandomTag)){ return 0; } String tmpUserBogusLabel = getUserBogusLabel(loginUserName, loginAt, userRandomTag); if(StringUtil.isNotEmpty(userState)){ String tmpUserState = getUserState(loginUserName, loginAt, userRandomTag, userBogusLabel); return userBogusLabel.equals(tmpUserBogusLabel) && userState.equals(tmpUserState)?2:0; }else{ return userBogusLabel.equals(tmpUserBogusLabel)?1:0; } } public static String getSuNameValue(Cookie[] cookies){ return getValue(cookies, USER_NAME); } public static String getValue(Cookie[] cookies, String name){ if(cookies==null || cookies.length<=0 || StringUtil.isEmpty(name)){ return null; } for(Cookie cookie: cookies){ if(name.equals(cookie.getName())){ String value = cookie.getValue(); return value; } } return null; } public static void deleteCookies(HttpServletRequest request, HttpServletResponse response, boolean deleteSessionId){ String path = request.getContextPath(); // String domain = request.getHeader("host"); Cookie[] cookies = request.getCookies(); if(cookies==null || cookies.length<=0){ return; } for(Cookie cookie: cookies){ if("JSESSIONID".equalsIgnoreCase(cookie.getName()) && !deleteSessionId){ continue; } cookie.setMaxAge(0); cookie.setPath(path); // c.setDomain(domain); response.addCookie(cookie); } } private static String getUserBogusLabel(String loginUserName, long loginAt, String userRandomTag){ return EncryptUtil.MD5(loginUserName + HX2 + loginAt + HX1 + userRandomTag); } private static String getUserState(String loginUserName, long loginAt, String userRandomTag, String userBogusLabel){ return EncryptUtil.MD5(loginUserName + HX1 +loginAt + HX2 + userRandomTag + HX3 + userBogusLabel); } }
6,865
0.695967
0.685999
198
31.439394
25.784536
117
false
false
0
0
0
0
0
0
2.727273
false
false
7
820e8e62579e34e8775746bab3c74c9f09b52a93
2,061,584,304,483
786de115ca1c3b6b382d1557e4d33d0fe862db6f
/src/main/java/com/qdm/cg/common/repositry/UserRepositry.java
f49292ebac119cecc6084301c81e2cbd7b6b0762
[]
no_license
lakshmijava4/QDMProject
https://github.com/lakshmijava4/QDMProject
c3dbe618fc1211f2f4823e6b9292ddbbdcab8117
3fc69a5d5456587466b29f1eeba7451cad93f68f
refs/heads/master
2022-12-13T23:17:35.911000
2020-08-17T15:28:58
2020-08-17T15:28:58
288,202,616
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qdm.cg.common.repositry; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.qdm.cg.common.modal.User; @Repository public interface UserRepositry extends JpaRepository<User, Integer>{ }
UTF-8
Java
274
java
UserRepositry.java
Java
[]
null
[]
package com.qdm.cg.common.repositry; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.qdm.cg.common.modal.User; @Repository public interface UserRepositry extends JpaRepository<User, Integer>{ }
274
0.824818
0.824818
12
21.833334
25.396303
68
false
false
0
0
0
0
0
0
0.416667
false
false
7
2ff4c0c707b87ddaac6337b5b23119507e4444f9
2,061,584,302,973
da32100d5546b023ed2ab948ccdd075909d3d1db
/client/src/main/java/view/ViewManager.java
c6b2d118519787f30023d8bc2297299b79f2499d
[ "MIT" ]
permissive
pomaretta/nominal
https://github.com/pomaretta/nominal
f13257719493acffa01699a8529665ec666422c7
143f4869a6f2296379c0e579ddc22320720c4c01
refs/heads/main
2023-07-16T14:37:46.831000
2021-08-25T09:36:15
2021-08-25T09:37:40
346,730,334
1
3
MIT
false
2021-08-25T09:34:59
2021-03-11T14:31:05
2021-05-17T09:34:00
2021-08-25T09:34:58
2,278
1
3
0
Java
false
false
package view; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.layout.Pane; import java.util.ArrayList; public class ViewManager { private final BaseController controller; private final Pane root; private final ArrayList<ViewController> viewControllers; public ViewManager(Pane root,BaseController baseController) { this.root = root; this.controller = baseController; this.viewControllers = new ArrayList<>(); } public BaseController getController() { return controller; } public ArrayList<ViewController> getViewControllers() { return viewControllers; } private Parent loadView(String url) { Parent root = null; FXMLLoader loader = new FXMLLoader(); try { loader.setLocation(getClass().getResource(url)); root = loader.load(); ViewController viewController = loader.getController(); viewController.setManager(this); viewController.run(); this.viewControllers.add(viewController); } catch (Exception e){ System.out.println(e.getMessage()); } return root; } public void switchScenes(String url){ Parent view = loadView(url); this.root.getChildren().clear(); this.root.getChildren().add(view); } }
UTF-8
Java
1,385
java
ViewManager.java
Java
[]
null
[]
package view; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.layout.Pane; import java.util.ArrayList; public class ViewManager { private final BaseController controller; private final Pane root; private final ArrayList<ViewController> viewControllers; public ViewManager(Pane root,BaseController baseController) { this.root = root; this.controller = baseController; this.viewControllers = new ArrayList<>(); } public BaseController getController() { return controller; } public ArrayList<ViewController> getViewControllers() { return viewControllers; } private Parent loadView(String url) { Parent root = null; FXMLLoader loader = new FXMLLoader(); try { loader.setLocation(getClass().getResource(url)); root = loader.load(); ViewController viewController = loader.getController(); viewController.setManager(this); viewController.run(); this.viewControllers.add(viewController); } catch (Exception e){ System.out.println(e.getMessage()); } return root; } public void switchScenes(String url){ Parent view = loadView(url); this.root.getChildren().clear(); this.root.getChildren().add(view); } }
1,385
0.642599
0.642599
52
25.634615
20.544538
67
false
false
0
0
0
0
0
0
0.519231
false
false
7
945e3cb1cdcf9b39ebf8a5ed9c570ab3df1eda58
2,740,189,161,280
a77174e58eeeeb831c7645699803f46d5330b27a
/06RestfulMicroServiceWithDB/src/main/java/com/divya/controller/BlogController.java
8ffabfb8ad6d4baf3e484fa2ded4c7151b7c4cc1
[ "MIT" ]
permissive
DivyaMaddipudi/SpringBoot-Personal-Archive
https://github.com/DivyaMaddipudi/SpringBoot-Personal-Archive
696fce0f3a4795a5a127bf3b4f4abfe78fea786b
6104ba219556145baf0a1056a9477d3443fd6475
refs/heads/main
2022-12-22T08:13:21.180000
2020-09-28T08:44:16
2020-09-28T08:44:16
293,125,621
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.divya.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.divya.entity.Blog; import com.divya.services.BlogServices; @RestController public class BlogController { @Autowired private BlogServices service; @RequestMapping("/blogs") public List<Blog> getBlogs() { return service.getBlogs(); } @RequestMapping("/blogs/{id}") public Blog getBlog(@PathVariable int id) { return service.getBlog(id); } @RequestMapping(method = RequestMethod.POST, value = "/blogs") public void addBlog(@RequestBody Blog blog) { service.addBlog(blog); } @RequestMapping(method = RequestMethod.PUT, value = "/blogs/{id}") public void updateBlog(@RequestBody Blog blog) { service.updateBlog(blog); } @RequestMapping(method = RequestMethod.DELETE, value = "/blogs/{id}") public void deleteBlog(@PathVariable int id) { service.deleteBlog(id); } }
UTF-8
Java
1,244
java
BlogController.java
Java
[]
null
[]
package com.divya.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.divya.entity.Blog; import com.divya.services.BlogServices; @RestController public class BlogController { @Autowired private BlogServices service; @RequestMapping("/blogs") public List<Blog> getBlogs() { return service.getBlogs(); } @RequestMapping("/blogs/{id}") public Blog getBlog(@PathVariable int id) { return service.getBlog(id); } @RequestMapping(method = RequestMethod.POST, value = "/blogs") public void addBlog(@RequestBody Blog blog) { service.addBlog(blog); } @RequestMapping(method = RequestMethod.PUT, value = "/blogs/{id}") public void updateBlog(@RequestBody Blog blog) { service.updateBlog(blog); } @RequestMapping(method = RequestMethod.DELETE, value = "/blogs/{id}") public void deleteBlog(@PathVariable int id) { service.deleteBlog(id); } }
1,244
0.766881
0.766881
47
25.468084
23.463736
70
false
false
0
0
0
0
0
0
1.148936
false
false
7
6348b2f5b8994166eabe08e4c2c6c50ef56e9454
2,327,872,328,696
f5e3ec2746fe7808ea39dcccab097d84d830cfaf
/private-components/swingui/src/main/java/org/limewire/ui/swing/util/MagnetHandlerImpl.java
5a6df2df412b59637c77d46a9f5e0c2147b2c746
[]
no_license
givannitrisya/LimeWire-Pirate-Edition
https://github.com/givannitrisya/LimeWire-Pirate-Edition
912f04e3ed21722c4d5806c94349e44973083a43
3c33894a41b530579985b3743c2c8ca5a9eff675
refs/heads/master
2021-01-23T19:15:55.891000
2017-09-10T09:32:40
2017-09-10T09:32:40
102,813,521
0
0
null
true
2017-09-08T03:31:47
2017-09-08T03:31:46
2017-08-13T08:48:25
2010-11-25T14:12:47
64,428
0
0
0
null
null
null
package org.limewire.ui.swing.util; import java.io.File; import javax.swing.JOptionPane; import org.limewire.core.api.download.DownloadAction; import org.limewire.core.api.download.DownloadException; import org.limewire.core.api.download.DownloadListManager; import org.limewire.core.api.magnet.MagnetLink; import org.limewire.core.api.search.SearchCategory; import org.limewire.inject.LazySingleton; import org.limewire.ui.swing.components.FocusJOptionPane; import org.limewire.ui.swing.search.DefaultSearchInfo; import org.limewire.ui.swing.search.SearchHandler; import com.google.inject.Inject; import com.google.inject.Provider; @LazySingleton class MagnetHandlerImpl implements MagnetHandler { private final DownloadListManager downloadListManager; private final SearchHandler searchHandler; private final Provider<DownloadExceptionHandler> downloadExceptionHandler; private static volatile int torrentDownloadMagnetCount = 0; private static volatile int gnutellaDownloadMagnetCount = 0; private static volatile int searchMagnetCount = 0; @Inject MagnetHandlerImpl(SearchHandler searchHandler, DownloadListManager downloadListManager, Provider<DownloadExceptionHandler> downloadExceptionHandler) { this.downloadListManager = downloadListManager; this.searchHandler = searchHandler; this.downloadExceptionHandler = downloadExceptionHandler; } /** * Handles the given magnet file by either starting a search or starting to * download the file specified in the magnet. */ public void handleMagnet(final MagnetLink magnet) { SwingUtils.invokeNowOrLater(new Runnable() { @Override public void run() { if(magnet.isGnutellaDownloadable()) { downloadMagnet(magnet); } else if(magnet.isTorrentDownloadable()) { downloadTorrent(magnet); } else if(magnet.isKeywordTopicOnly()) { searchHandler.doSearch(DefaultSearchInfo. createKeywordSearch(magnet.getQueryString(), SearchCategory.ALL)); searchMagnetCount++; } else { FocusJOptionPane.showMessageDialog(GuiUtils.getMainFrame(), I18n.tr("The magnet link is invalid."), I18n.tr("Invalid Magnet Link"), JOptionPane.INFORMATION_MESSAGE); } } }); } private void downloadTorrent(MagnetLink magnet) { try { downloadListManager.addTorrentDownload(magnet.getName(), magnet.getURN(), magnet.getTrackerUrls()); torrentDownloadMagnetCount++; } catch(DownloadException e) { downloadExceptionHandler.get().handleDownloadException( new TorrentDownloadAction(magnet), e, true); } } private void downloadMagnet(MagnetLink magnet) { try { downloadListManager.addDownload(magnet, null, false); gnutellaDownloadMagnetCount++; } catch (DownloadException e) { downloadExceptionHandler.get().handleDownloadException( new MagnetDownloadAction(magnet), e, true); } } private class TorrentDownloadAction implements DownloadAction { private final MagnetLink magnet; TorrentDownloadAction(MagnetLink magnet) { this.magnet = magnet; } @Override public void download(File saveFile, boolean overwrite) throws DownloadException { downloadListManager.addTorrentDownload(magnet.getName(), magnet.getURN(), magnet.getTrackerUrls()); torrentDownloadMagnetCount++; } @Override public void downloadCanceled(DownloadException ignored) { } } private class MagnetDownloadAction implements DownloadAction { private final MagnetLink magnet; MagnetDownloadAction(MagnetLink magnet) { this.magnet = magnet; } @Override public void download(File saveFile, boolean overwrite) throws DownloadException { downloadListManager.addDownload(magnet, saveFile, overwrite); gnutellaDownloadMagnetCount++; } @Override public void downloadCanceled(DownloadException ignored) {} } }
UTF-8
Java
4,640
java
MagnetHandlerImpl.java
Java
[]
null
[]
package org.limewire.ui.swing.util; import java.io.File; import javax.swing.JOptionPane; import org.limewire.core.api.download.DownloadAction; import org.limewire.core.api.download.DownloadException; import org.limewire.core.api.download.DownloadListManager; import org.limewire.core.api.magnet.MagnetLink; import org.limewire.core.api.search.SearchCategory; import org.limewire.inject.LazySingleton; import org.limewire.ui.swing.components.FocusJOptionPane; import org.limewire.ui.swing.search.DefaultSearchInfo; import org.limewire.ui.swing.search.SearchHandler; import com.google.inject.Inject; import com.google.inject.Provider; @LazySingleton class MagnetHandlerImpl implements MagnetHandler { private final DownloadListManager downloadListManager; private final SearchHandler searchHandler; private final Provider<DownloadExceptionHandler> downloadExceptionHandler; private static volatile int torrentDownloadMagnetCount = 0; private static volatile int gnutellaDownloadMagnetCount = 0; private static volatile int searchMagnetCount = 0; @Inject MagnetHandlerImpl(SearchHandler searchHandler, DownloadListManager downloadListManager, Provider<DownloadExceptionHandler> downloadExceptionHandler) { this.downloadListManager = downloadListManager; this.searchHandler = searchHandler; this.downloadExceptionHandler = downloadExceptionHandler; } /** * Handles the given magnet file by either starting a search or starting to * download the file specified in the magnet. */ public void handleMagnet(final MagnetLink magnet) { SwingUtils.invokeNowOrLater(new Runnable() { @Override public void run() { if(magnet.isGnutellaDownloadable()) { downloadMagnet(magnet); } else if(magnet.isTorrentDownloadable()) { downloadTorrent(magnet); } else if(magnet.isKeywordTopicOnly()) { searchHandler.doSearch(DefaultSearchInfo. createKeywordSearch(magnet.getQueryString(), SearchCategory.ALL)); searchMagnetCount++; } else { FocusJOptionPane.showMessageDialog(GuiUtils.getMainFrame(), I18n.tr("The magnet link is invalid."), I18n.tr("Invalid Magnet Link"), JOptionPane.INFORMATION_MESSAGE); } } }); } private void downloadTorrent(MagnetLink magnet) { try { downloadListManager.addTorrentDownload(magnet.getName(), magnet.getURN(), magnet.getTrackerUrls()); torrentDownloadMagnetCount++; } catch(DownloadException e) { downloadExceptionHandler.get().handleDownloadException( new TorrentDownloadAction(magnet), e, true); } } private void downloadMagnet(MagnetLink magnet) { try { downloadListManager.addDownload(magnet, null, false); gnutellaDownloadMagnetCount++; } catch (DownloadException e) { downloadExceptionHandler.get().handleDownloadException( new MagnetDownloadAction(magnet), e, true); } } private class TorrentDownloadAction implements DownloadAction { private final MagnetLink magnet; TorrentDownloadAction(MagnetLink magnet) { this.magnet = magnet; } @Override public void download(File saveFile, boolean overwrite) throws DownloadException { downloadListManager.addTorrentDownload(magnet.getName(), magnet.getURN(), magnet.getTrackerUrls()); torrentDownloadMagnetCount++; } @Override public void downloadCanceled(DownloadException ignored) { } } private class MagnetDownloadAction implements DownloadAction { private final MagnetLink magnet; MagnetDownloadAction(MagnetLink magnet) { this.magnet = magnet; } @Override public void download(File saveFile, boolean overwrite) throws DownloadException { downloadListManager.addDownload(magnet, saveFile, overwrite); gnutellaDownloadMagnetCount++; } @Override public void downloadCanceled(DownloadException ignored) {} } }
4,640
0.636638
0.635129
133
33.887218
25.093105
79
false
false
0
0
0
0
0
0
0.473684
false
false
7
a9b39ca40c18c3803f0e5a4c6149390af91addf6
10,651,518,934,385
67ddf436f7857f03b38882512869f4188a2c80ab
/DataStructures/src/com/michielherpers/linkedlists/ExerciseLinkedList.java
800bb171b05c3e3897e30c5e76d67f9e8853de2f
[]
no_license
MichielHWT/Algorithms-and-Data-Structures
https://github.com/MichielHWT/Algorithms-and-Data-Structures
1ee77efc60b8a383e76dee78e65198011279ce91
4e14b2954c1283c48f8efe74537f945ff502309d
refs/heads/master
2023-05-15T11:17:25.251000
2021-06-01T07:48:17
2021-06-01T07:48:17
364,895,332
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.michielherpers.linkedlists; import java.util.Arrays; import java.util.LinkedList; public class ExerciseLinkedList { public static void main(String[] args) { LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.addLast(1); linkedList.addLast(10); linkedList.addLast(16); linkedList.addLast(88); System.out.println(Arrays.toString(linkedList.toArray())); //reverse() LinkedList<Integer> reversed = Exercise1.reverse(linkedList); System.out.println(Arrays.toString(reversed.toArray())); } } class Exercise1{ //Using a Singly Linked List, reverse the linked list by creating a method reverse() //Note that I am now using the non-custom LinkedList public static LinkedList<Integer> reverse(LinkedList<Integer> linkedList){ //O(n) if(linkedList != null && linkedList.size() > 2) { LinkedList<Integer> newLinkedList = new LinkedList<>(); int index = linkedList.size() - 1; int value = 0; while (index >= 0) { value = linkedList.get(index); newLinkedList.addLast(value); index--; } return newLinkedList; } else if(linkedList == null){ return null; } else{ return linkedList; } } }
UTF-8
Java
1,393
java
ExerciseLinkedList.java
Java
[ { "context": "package com.michielherpers.linkedlists;\n\nimport java.util.Arrays;\nimport", "end": 22, "score": 0.5570034980773926, "start": 19, "tag": "USERNAME", "value": "her" } ]
null
[]
package com.michielherpers.linkedlists; import java.util.Arrays; import java.util.LinkedList; public class ExerciseLinkedList { public static void main(String[] args) { LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.addLast(1); linkedList.addLast(10); linkedList.addLast(16); linkedList.addLast(88); System.out.println(Arrays.toString(linkedList.toArray())); //reverse() LinkedList<Integer> reversed = Exercise1.reverse(linkedList); System.out.println(Arrays.toString(reversed.toArray())); } } class Exercise1{ //Using a Singly Linked List, reverse the linked list by creating a method reverse() //Note that I am now using the non-custom LinkedList public static LinkedList<Integer> reverse(LinkedList<Integer> linkedList){ //O(n) if(linkedList != null && linkedList.size() > 2) { LinkedList<Integer> newLinkedList = new LinkedList<>(); int index = linkedList.size() - 1; int value = 0; while (index >= 0) { value = linkedList.get(index); newLinkedList.addLast(value); index--; } return newLinkedList; } else if(linkedList == null){ return null; } else{ return linkedList; } } }
1,393
0.594401
0.585068
49
27.44898
24.35709
88
false
false
0
0
0
0
0
0
0.428571
false
false
7
cb005184db1e41a77d609a29c0a564ed571a17bb
16,612,933,540,840
54d24738d235d9c972a08ff5b9f10718b460a653
/src/main/java/br/com/bomfilme/bean/UserData.java
a7fb9141e1e851436cde192e7417d34c691b4e78
[]
no_license
jacksongarcia/locadora
https://github.com/jacksongarcia/locadora
d802b011050fafa4cf93e77f65b76681a49ae9a8
1353a77c4ff4c5d05923710cfd774f05ee9efec3
refs/heads/master
2016-09-05T23:49:36.794000
2015-09-14T06:53:02
2015-09-14T06:53:02
42,331,404
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.bomfilme.bean; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Inject; import br.com.bomfilme.controller.CollectionManager; import br.com.bomfilme.controller.UserManager; import br.com.bomfilme.model.product.Product; import br.com.bomfilme.model.user.User; @ManagedBean @SessionScoped public class UserData { @Inject private UserManager userManager; private Product product; public String getUserName() { User user = (User)FacesContext.getCurrentInstance().getExternalContext(). getSessionMap().get("user"); if (user != null) return user.getName(); return null; } public List<Product> addCar() { String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"); String media = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("media"); CollectionManager cl = CollectionManager.getInstance(); if(id != null && !id.equals("") && media != null && !media.equals("")){ List<Product> product; product = cl.searchProduct(id); if ((media.equals("DVD") && (product.get(0).getLengthMediaDVD() > 0)) || (media.equals("BLU-RAY") && (product.get(0).getLengthMediaBluRay() > 0))) { userManager.addProductCar(product.get(0), media); return product; } return null; } return null; } public boolean isExistsProduct() { String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"); String media = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("media"); CollectionManager cl = CollectionManager.getInstance(); if(id != null && !id.equals("") && media != null && !media.equals("")){ List<Product> product; product = cl.searchProduct(id); if(userManager.getListProduct().containsKey(product)) return true; } return false; } public List<Product> getListCar() { List<Product> list = new ArrayList<Product>(); for (Map.Entry<Product,String> pair : userManager.getListProduct().entrySet()) { list.add(pair.getKey()); } return list; } public int getCountProduct() { if(getUserName() != null) return userManager.getCountProduct(); return 0; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
UTF-8
Java
2,512
java
UserData.java
Java
[]
null
[]
package br.com.bomfilme.bean; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Inject; import br.com.bomfilme.controller.CollectionManager; import br.com.bomfilme.controller.UserManager; import br.com.bomfilme.model.product.Product; import br.com.bomfilme.model.user.User; @ManagedBean @SessionScoped public class UserData { @Inject private UserManager userManager; private Product product; public String getUserName() { User user = (User)FacesContext.getCurrentInstance().getExternalContext(). getSessionMap().get("user"); if (user != null) return user.getName(); return null; } public List<Product> addCar() { String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"); String media = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("media"); CollectionManager cl = CollectionManager.getInstance(); if(id != null && !id.equals("") && media != null && !media.equals("")){ List<Product> product; product = cl.searchProduct(id); if ((media.equals("DVD") && (product.get(0).getLengthMediaDVD() > 0)) || (media.equals("BLU-RAY") && (product.get(0).getLengthMediaBluRay() > 0))) { userManager.addProductCar(product.get(0), media); return product; } return null; } return null; } public boolean isExistsProduct() { String id = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"); String media = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("media"); CollectionManager cl = CollectionManager.getInstance(); if(id != null && !id.equals("") && media != null && !media.equals("")){ List<Product> product; product = cl.searchProduct(id); if(userManager.getListProduct().containsKey(product)) return true; } return false; } public List<Product> getListCar() { List<Product> list = new ArrayList<Product>(); for (Map.Entry<Product,String> pair : userManager.getListProduct().entrySet()) { list.add(pair.getKey()); } return list; } public int getCountProduct() { if(getUserName() != null) return userManager.getCountProduct(); return 0; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
2,512
0.714172
0.711783
88
27.545454
27.574654
110
false
false
0
0
0
0
0
0
2.034091
false
false
7
227d2ba74dde69702220a3f339e5abdf7b9357ef
970,662,629,189
dbecd9d4215f686fea33962bb64b495c239614ee
/hw03-annotations/src/main/java/ru/otus/testfw/AdditionalTests.java
284ac01954488fa6813fc021d80bbfe57e167867
[]
no_license
SlotW/otus_java_2019_03
https://github.com/SlotW/otus_java_2019_03
1652241f0a62f9da24b5cb266dca47393a07bdb6
488871d3b75fb050fa52a1e06c299b8986f64bd2
refs/heads/master
2022-06-11T13:46:20.361000
2019-08-12T12:44:59
2019-08-12T12:44:59
178,446,604
0
0
null
false
2022-05-20T21:05:07
2019-03-29T17:10:05
2019-08-12T12:45:02
2022-05-20T21:05:07
90
0
0
5
Java
false
false
package ru.otus.testfw; import ru.otus.testfw.annotations.*; /** * Created by Alexandr Byankin on 28.04.2019 */ public class AdditionalTests { @BeforeAll public static void beforeAll(){ System.out.println("Вызов beforeALl"); } @BeforeEach public void beforeEach(){ System.out.println("Вызов beforeEach"); throw new RuntimeException(); } @Test public void simpleTest(){ System.out.println("Тест"); } @AfterEach public void afterEach(){ System.out.println("Вызов afterEach"); } @AfterAll public void afterAll(){ System.out.println("Вызов afterAll"); } }
UTF-8
Java
694
java
AdditionalTests.java
Java
[ { "context": "t ru.otus.testfw.annotations.*;\n\n/**\n * Created by Alexandr Byankin on 28.04.2019\n */\npublic class AdditionalTests {\n", "end": 97, "score": 0.9998541474342346, "start": 81, "tag": "NAME", "value": "Alexandr Byankin" } ]
null
[]
package ru.otus.testfw; import ru.otus.testfw.annotations.*; /** * Created by <NAME> on 28.04.2019 */ public class AdditionalTests { @BeforeAll public static void beforeAll(){ System.out.println("Вызов beforeALl"); } @BeforeEach public void beforeEach(){ System.out.println("Вызов beforeEach"); throw new RuntimeException(); } @Test public void simpleTest(){ System.out.println("Тест"); } @AfterEach public void afterEach(){ System.out.println("Вызов afterEach"); } @AfterAll public void afterAll(){ System.out.println("Вызов afterAll"); } }
684
0.61791
0.60597
36
17.611111
16.655458
47
false
false
0
0
0
0
0
0
0.222222
false
false
7
e6810fa2f6ff36032f18d4ff6efb68c9213f9885
3,341,484,623,368
287ebf513edfc6390fe8f02c14b084118981fee8
/FlashHandler/src/test/java/org/qiunet/flash/handler/Test.java
abb4fe8cb66a0810d253e4eb676ac6ac12cdc846
[ "Apache-2.0" ]
permissive
zheng0324jian/DuoDuo
https://github.com/zheng0324jian/DuoDuo
1cceb2099557c0a2dbad7b3d2e1401e0301a0b61
19306ee4da6ada4087dccd9ef34d1b1329f0f8aa
refs/heads/master
2023-02-12T13:30:49.358000
2021-01-07T09:07:25
2021-01-07T09:07:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.qiunet.flash.handler; import org.qiunet.flash.handler.bootstrap.hook.MyHook; import org.qiunet.flash.handler.netty.server.BootstrapServer; import org.qiunet.flash.handler.netty.server.hook.Hook; import org.qiunet.flash.handler.netty.server.param.TcpBootstrapParams; import org.qiunet.flash.handler.startup.context.StartupContext; import org.qiunet.utils.scanner.ClassScanner; /** * 用来debug 跟踪内部测试用 * Created by qiunet. * 17/12/15 */ public class Test { private static Hook hook = new MyHook(); public static void main(String[] args) throws Exception { ClassScanner.getInstance().scanner(); BootstrapServer.createBootstrap(hook).tcpListener( TcpBootstrapParams.custom() .setStartupContext(new StartupContext()) .setPort(8888) .setEncryption(true) .build() ).await(); } }
UTF-8
Java
843
java
Test.java
Java
[ { "context": "lassScanner;\n\n/**\n * 用来debug 跟踪内部测试用\n * Created by qiunet.\n * 17/12/15\n */\npublic class Test {\n\tprivate sta", "end": 433, "score": 0.9996052384376526, "start": 427, "tag": "USERNAME", "value": "qiunet" } ]
null
[]
package org.qiunet.flash.handler; import org.qiunet.flash.handler.bootstrap.hook.MyHook; import org.qiunet.flash.handler.netty.server.BootstrapServer; import org.qiunet.flash.handler.netty.server.hook.Hook; import org.qiunet.flash.handler.netty.server.param.TcpBootstrapParams; import org.qiunet.flash.handler.startup.context.StartupContext; import org.qiunet.utils.scanner.ClassScanner; /** * 用来debug 跟踪内部测试用 * Created by qiunet. * 17/12/15 */ public class Test { private static Hook hook = new MyHook(); public static void main(String[] args) throws Exception { ClassScanner.getInstance().scanner(); BootstrapServer.createBootstrap(hook).tcpListener( TcpBootstrapParams.custom() .setStartupContext(new StartupContext()) .setPort(8888) .setEncryption(true) .build() ).await(); } }
843
0.756364
0.744242
28
28.464285
22.332684
70
false
false
0
0
0
0
0
0
1.642857
false
false
7
3b124d9011dd12d2daa3a8a33b24bf3620d514b0
26,199,300,533,732
c5e3f5e7ad9ed477862032c8815896194466e46e
/src/com/Gender.java
5088ca4423c46caf311f45d79de3cee23772b40f
[]
no_license
sanjeevpk/weblearning
https://github.com/sanjeevpk/weblearning
8c93b1ad77b1aa780dcafd523cf00ff5dfc8b51a
00b361bfb9fe6992a9e5ce958afed1f6b1ddaed0
refs/heads/master
2021-01-10T21:39:01.847000
2013-07-17T09:37:52
2013-07-17T09:37:52
32,135,466
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com; /** * @author sankulka * */ public enum Gender { MALE, FEMALE }
UTF-8
Java
108
java
Gender.java
Java
[ { "context": "/**\r\n * \r\n */\r\npackage com;\r\n\r\n/**\r\n * @author sankulka\r\n *\r\n */\r\npublic enum Gender {\r\n\tMALE,\r\n\tFEMALE\r\n", "end": 55, "score": 0.9993755221366882, "start": 47, "tag": "USERNAME", "value": "sankulka" } ]
null
[]
/** * */ package com; /** * @author sankulka * */ public enum Gender { MALE, FEMALE }
108
0.462963
0.462963
13
6.307693
6.341373
20
false
false
0
0
0
0
0
0
0.307692
false
false
7
4b6b83c1de064a6a4efb1a6b8bb3752d74a50218
26,946,624,858,683
2e871f255bcf4f03af16400341b3a284af60d2bd
/src/com/smit/service/push/PushDataServiceImpl.java
d087b792b0ff5122c1a1da79277baacb2de9d3c5
[]
no_license
RyanFu/cmsserver
https://github.com/RyanFu/cmsserver
67b6ea4eaf2f70c57a2161d9c0a479f03ea5c7a8
957cd1e739a1a184d625150889e3ff16ee0873e1
refs/heads/master
2020-12-25T08:50:35.874000
2011-12-29T05:31:05
2011-12-29T05:31:05
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.smit.service.push; import java.util.List; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.MessageTypeFilter; import org.jivesoftware.smack.filter.NotFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.provider.ProviderManager; import com.smit.service.push.packet.FeedUpdateIQ; import com.smit.service.push.packet.PresenceListener; import com.smit.service.push.packet.PushServerIQ; import com.smit.service.push.packet.PushServiceInfIQ; import com.smit.service.push.packet.PushServiceInfIQListener; import com.smit.service.push.packet.PushServiceInfIQProvider; import com.smit.service.push.packet.PushUserIQ; import com.smit.service.push.packet.UserQueryIQ; import com.smit.service.push.packet.UserQueryIQListener; import com.smit.service.push.packet.UserQueryIQProvider; public class PushDataServiceImpl implements IPushDataService { private static String resource = "contentServer"; private XMPPConnection connection = null; private IPushManageService pushManageService = null; private String user; public boolean login(String host,String user,String password){ this.user = user; ConnectionConfiguration config = new ConnectionConfiguration(host,5222, resource); connection = new XMPPConnection(config); try{ connection.connect(); connection.login(user,password); initLogin(); getInitInf(); }catch(XMPPException e){ e.printStackTrace(); return false; }catch(Exception e){ e.printStackTrace(); return false; } return true; } public boolean logout(){ if(connection == null) return false; connection.disconnect(); return true; } public boolean isConnected(){ if(connection == null) return false; if(connection.isConnected() && connection.isAuthenticated()){ return true; } return false; } private boolean sendPacket(Packet packet){ if(!isConnected()){ return false; } connection.sendPacket(packet); return true; } /* * send data to push server */ public boolean sendPushDataFromDevToAll( String pushServiceName, boolean bDelay, String collapseKey, String title, String ticker, String uri, String message){ return this.sendPushDataFromDev(pushServiceName,null, bDelay, collapseKey, title, ticker, uri, message); } /* * if pushIdList == null,it will send the data to all */ public boolean sendPushDataFromDev( String pushServiceName, List<String> pushIdList, boolean bDelay, String collapseKey, String title, String ticker, String uri, String message){ PushServerIQ iq = new PushServerIQ(); if(pushIdList == null){ iq.setToAll("all"); }else{ iq.setToAll("false"); iq.setPushIDList(pushIdList); } iq.setPushServiceName(pushServiceName); iq.setDelay(bDelay); iq.setCollapseKey(collapseKey); iq.setTitle(title); iq.setTicker(ticker); iq.setUri(uri); iq.setMessage(message); iq.toXML(); return this.sendPacket(iq); } public boolean sendPushDataFromUser( List<String> userList, boolean bDelay, String collapseKey, String title, String ticker, String uri, String message, String type) throws Exception{ PushUserIQ iq = new PushUserIQ(); if(userList == null){ return false; } iq.setIQType(type); iq.setUserList(userList); iq.setDelay(bDelay); iq.setCollapseKey(collapseKey); iq.setTitle(title); iq.setTicker(ticker); iq.setUri(uri); iq.setMessage(message); System.out.println(iq.toXML()); return this.sendPacket(iq); } public XMPPConnection getConnection(){ return this.connection; } public boolean sendQueryResourceId(String userName) { // UserQueryIQ iq1 = new UserQueryIQ(); // iq1.setUserAccount(userName); // iq1.setOpCodeSave(); // iq1.setDeviceId("111111"); // iq1.setDeviceName("111111"); // iq1.setResource("1111111"); // this.sendPacket(iq1); UserQueryIQ iq = new UserQueryIQ(); iq.setUserAccount(userName); iq.setOpCodeQuery(); return this.sendPacket(iq); } private void initLogin(){ // packet provider ProviderManager.getInstance().addIQProvider(UserQueryIQ.getElementName(), UserQueryIQ.getNamespace(), new UserQueryIQProvider()); ProviderManager.getInstance().addIQProvider(PushServiceInfIQ.getElementName(), PushServiceInfIQ.getNamespace(), new PushServiceInfIQProvider()); PacketFilter packetFilter = new PacketTypeFilter( UserQueryIQ.class); UserQueryIQListener uqlistener = new UserQueryIQListener(); uqlistener.setPushManageService(pushManageService); uqlistener.setXmppConnection(connection); connection.addPacketListener(uqlistener, packetFilter); connection.addPacketListener(new PushServiceInfIQListener(), new PacketTypeFilter(PushServiceInfIQ.class)); PacketFilter charFilter = new MessageTypeFilter(Message.Type.chat); // TODO-ANDREW test need to delete NotFilter notFilter = new NotFilter(charFilter); connection.addPacketListener(new PacketListener(){ public void processPacket(Packet packet) { System.out.println(packet.toXML()); } },notFilter); PacketFilter presenceFilter = new PacketTypeFilter(Presence.class); PresenceListener presenceListener = new PresenceListener(); connection.addPacketListener(presenceListener,presenceFilter); presenceListener.setPushManageService(pushManageService); } private void getInitInf(){ //获取用户的所有的resource id sendQueryResourceId(user+"@"+connection.getServiceName()); //sendPushServiceInf("web","test2"); } public boolean sendPushServiceInf(String serviceName, String account) { PushServiceInfIQ iq = new PushServiceInfIQ(); iq.setUserAccount(account); iq.setPushServiceName(serviceName); this.sendPacket(iq); return true; } public boolean sendNoteFromCms(String url) { FeedUpdateIQ iq = new FeedUpdateIQ(); iq.setType(IQ.Type.SET); iq.setFeed(url); this.sendPacket(iq); return true; } public IPushManageService getPushManageService() { return pushManageService; } public void setPushManageService(IPushManageService pushManageService) { this.pushManageService = pushManageService; } public String getServerName(){ return connection.getServiceName(); } }
UTF-8
Java
6,850
java
PushDataServiceImpl.java
Java
[ { "context": "g host,String user,String password){\n\t\tthis.user = user;\n\t\tConnectionConfiguration config = new Connectio", "end": 1558, "score": 0.9983853101730347, "start": 1554, "tag": "USERNAME", "value": "user" }, { "context": "Q iq1 = new UserQueryIQ();\n//\t\tiq1.setUserAccount(userName);\n//\t\tiq1.setOpCodeSave();\n//\t\tiq1.setDeviceId(\"1", "end": 4181, "score": 0.7660781741142273, "start": 4173, "tag": "USERNAME", "value": "userName" }, { "context": "eryIQ iq = new UserQueryIQ();\n\t\tiq.setUserAccount(userName);\n\t\tiq.setOpCodeQuery();\n\t\treturn this.sendPacket", "end": 4400, "score": 0.7711439728736877, "start": 4392, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.smit.service.push; import java.util.List; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.MessageTypeFilter; import org.jivesoftware.smack.filter.NotFilter; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketTypeFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smack.provider.ProviderManager; import com.smit.service.push.packet.FeedUpdateIQ; import com.smit.service.push.packet.PresenceListener; import com.smit.service.push.packet.PushServerIQ; import com.smit.service.push.packet.PushServiceInfIQ; import com.smit.service.push.packet.PushServiceInfIQListener; import com.smit.service.push.packet.PushServiceInfIQProvider; import com.smit.service.push.packet.PushUserIQ; import com.smit.service.push.packet.UserQueryIQ; import com.smit.service.push.packet.UserQueryIQListener; import com.smit.service.push.packet.UserQueryIQProvider; public class PushDataServiceImpl implements IPushDataService { private static String resource = "contentServer"; private XMPPConnection connection = null; private IPushManageService pushManageService = null; private String user; public boolean login(String host,String user,String password){ this.user = user; ConnectionConfiguration config = new ConnectionConfiguration(host,5222, resource); connection = new XMPPConnection(config); try{ connection.connect(); connection.login(user,password); initLogin(); getInitInf(); }catch(XMPPException e){ e.printStackTrace(); return false; }catch(Exception e){ e.printStackTrace(); return false; } return true; } public boolean logout(){ if(connection == null) return false; connection.disconnect(); return true; } public boolean isConnected(){ if(connection == null) return false; if(connection.isConnected() && connection.isAuthenticated()){ return true; } return false; } private boolean sendPacket(Packet packet){ if(!isConnected()){ return false; } connection.sendPacket(packet); return true; } /* * send data to push server */ public boolean sendPushDataFromDevToAll( String pushServiceName, boolean bDelay, String collapseKey, String title, String ticker, String uri, String message){ return this.sendPushDataFromDev(pushServiceName,null, bDelay, collapseKey, title, ticker, uri, message); } /* * if pushIdList == null,it will send the data to all */ public boolean sendPushDataFromDev( String pushServiceName, List<String> pushIdList, boolean bDelay, String collapseKey, String title, String ticker, String uri, String message){ PushServerIQ iq = new PushServerIQ(); if(pushIdList == null){ iq.setToAll("all"); }else{ iq.setToAll("false"); iq.setPushIDList(pushIdList); } iq.setPushServiceName(pushServiceName); iq.setDelay(bDelay); iq.setCollapseKey(collapseKey); iq.setTitle(title); iq.setTicker(ticker); iq.setUri(uri); iq.setMessage(message); iq.toXML(); return this.sendPacket(iq); } public boolean sendPushDataFromUser( List<String> userList, boolean bDelay, String collapseKey, String title, String ticker, String uri, String message, String type) throws Exception{ PushUserIQ iq = new PushUserIQ(); if(userList == null){ return false; } iq.setIQType(type); iq.setUserList(userList); iq.setDelay(bDelay); iq.setCollapseKey(collapseKey); iq.setTitle(title); iq.setTicker(ticker); iq.setUri(uri); iq.setMessage(message); System.out.println(iq.toXML()); return this.sendPacket(iq); } public XMPPConnection getConnection(){ return this.connection; } public boolean sendQueryResourceId(String userName) { // UserQueryIQ iq1 = new UserQueryIQ(); // iq1.setUserAccount(userName); // iq1.setOpCodeSave(); // iq1.setDeviceId("111111"); // iq1.setDeviceName("111111"); // iq1.setResource("1111111"); // this.sendPacket(iq1); UserQueryIQ iq = new UserQueryIQ(); iq.setUserAccount(userName); iq.setOpCodeQuery(); return this.sendPacket(iq); } private void initLogin(){ // packet provider ProviderManager.getInstance().addIQProvider(UserQueryIQ.getElementName(), UserQueryIQ.getNamespace(), new UserQueryIQProvider()); ProviderManager.getInstance().addIQProvider(PushServiceInfIQ.getElementName(), PushServiceInfIQ.getNamespace(), new PushServiceInfIQProvider()); PacketFilter packetFilter = new PacketTypeFilter( UserQueryIQ.class); UserQueryIQListener uqlistener = new UserQueryIQListener(); uqlistener.setPushManageService(pushManageService); uqlistener.setXmppConnection(connection); connection.addPacketListener(uqlistener, packetFilter); connection.addPacketListener(new PushServiceInfIQListener(), new PacketTypeFilter(PushServiceInfIQ.class)); PacketFilter charFilter = new MessageTypeFilter(Message.Type.chat); // TODO-ANDREW test need to delete NotFilter notFilter = new NotFilter(charFilter); connection.addPacketListener(new PacketListener(){ public void processPacket(Packet packet) { System.out.println(packet.toXML()); } },notFilter); PacketFilter presenceFilter = new PacketTypeFilter(Presence.class); PresenceListener presenceListener = new PresenceListener(); connection.addPacketListener(presenceListener,presenceFilter); presenceListener.setPushManageService(pushManageService); } private void getInitInf(){ //获取用户的所有的resource id sendQueryResourceId(user+"@"+connection.getServiceName()); //sendPushServiceInf("web","test2"); } public boolean sendPushServiceInf(String serviceName, String account) { PushServiceInfIQ iq = new PushServiceInfIQ(); iq.setUserAccount(account); iq.setPushServiceName(serviceName); this.sendPacket(iq); return true; } public boolean sendNoteFromCms(String url) { FeedUpdateIQ iq = new FeedUpdateIQ(); iq.setType(IQ.Type.SET); iq.setFeed(url); this.sendPacket(iq); return true; } public IPushManageService getPushManageService() { return pushManageService; } public void setPushManageService(IPushManageService pushManageService) { this.pushManageService = pushManageService; } public String getServerName(){ return connection.getServiceName(); } }
6,850
0.730465
0.725929
234
28.200855
20.440403
92
false
false
0
0
0
0
0
0
2.213675
false
false
7
beec4305b931431ac2863524ea2f2caba9537ecb
32,384,053,447,715
a97a215f59f3f37a62787b580ad66a1abe48e20b
/assignment6-arrays/src/com/shpp/cs/assignments/arrays/hg/HistogramEqualizationLogic.java
0a8321c8151a61fcb633cc189958a66770e6b9c5
[]
no_license
shpp-cs-2015-07/cs-a-etereza
https://github.com/shpp-cs-2015-07/cs-a-etereza
6c725e627892f4cb4e3b06e44a4709b3bda71fbc
053afd35c5f53cea0ab051253f1a574cec3f2dea
refs/heads/master
2018-01-07T12:25:19.097000
2015-09-14T07:30:59
2015-09-14T07:30:59
39,378,651
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shpp.cs.assignments.arrays.hg; public class HistogramEqualizationLogic { private static final int MAX_LUMINANCE = 255; /** * Given the luminances of the pixels in an image, returns a histogram of the frequencies of * those luminances. * <p> * You can assume that pixel luminances range from 0 to MAX_LUMINANCE, inclusive. * * @param luminances The luminances in the picture. * @return A histogram of those luminances. */ public static int[] histogramFor(int[][] luminances) { /* TODO: Implement this method! */ int[] result = new int[256]; int k = 0; while (k <= MAX_LUMINANCE) { int n = 0; for (int i = 0; i < luminances.length; i++) for (int j = 0; j < luminances[i].length; j++) if (k == luminances[i][j]) n++; result[k] = n; k++; } return result; } /** * Given a histogram of the luminances in an image, returns an array of the cumulative * frequencies of that image. Each entry of this array should be equal to the sum of all * the array entries up to and including its index in the input histogram array. * <p> * For example, given the array [1, 2, 3, 4, 5], the result should be [1, 3, 6, 10, 15]. * * @param histogram The input histogram. * @return The cumulative frequency array. */ public static int[] cumulativeSumFor(int[] histogram) { /* TODO: Implement this method! */ int[] result = new int[256]; int counter = 0; result[0] = histogram[0]; for (int i = 1; i < histogram.length; i++) { result[i] = result[i - 1] + histogram[i]; } return result; } /** * Returns the total number of pixels in the given image. * * @param luminances A matrix of the luminances within an image. * @return The total number of pixels in that image. */ public static int totalPixelsIn(int[][] luminances) { int result = 0; for (int i = 0; i < luminances.length; i++) for (int j = 0; j < luminances[i].length; j++) result++; return result; } /** * Applies the histogram equalization algorithm to the given image, represented by a matrix * of its luminances. * <p> * You are strongly encouraged to use the three methods you have implemented above in order to * implement this method. * * @param luminances The luminances of the input image. * @return The luminances of the image formed by applying histogram equalization. */ public static int[][] equalize(int[][] luminances) { /* TODO: Implement this method! */ int[][] result = luminances; int totalPixels = totalPixelsIn(luminances); // create a histogram of the image int[] gist = histogramFor(luminances); // convert a histogram into a cumulative int[] sovHist = cumulativeSumFor(gist); for (int i = 0; i < luminances.length; i++) for (int j = 0; j < luminances[i].length; j++) { int pixel = luminances[i][j]; result[i][j] = MAX_LUMINANCE * sovHist[pixel] / totalPixels; } return result; } }
UTF-8
Java
3,353
java
HistogramEqualizationLogic.java
Java
[]
null
[]
package com.shpp.cs.assignments.arrays.hg; public class HistogramEqualizationLogic { private static final int MAX_LUMINANCE = 255; /** * Given the luminances of the pixels in an image, returns a histogram of the frequencies of * those luminances. * <p> * You can assume that pixel luminances range from 0 to MAX_LUMINANCE, inclusive. * * @param luminances The luminances in the picture. * @return A histogram of those luminances. */ public static int[] histogramFor(int[][] luminances) { /* TODO: Implement this method! */ int[] result = new int[256]; int k = 0; while (k <= MAX_LUMINANCE) { int n = 0; for (int i = 0; i < luminances.length; i++) for (int j = 0; j < luminances[i].length; j++) if (k == luminances[i][j]) n++; result[k] = n; k++; } return result; } /** * Given a histogram of the luminances in an image, returns an array of the cumulative * frequencies of that image. Each entry of this array should be equal to the sum of all * the array entries up to and including its index in the input histogram array. * <p> * For example, given the array [1, 2, 3, 4, 5], the result should be [1, 3, 6, 10, 15]. * * @param histogram The input histogram. * @return The cumulative frequency array. */ public static int[] cumulativeSumFor(int[] histogram) { /* TODO: Implement this method! */ int[] result = new int[256]; int counter = 0; result[0] = histogram[0]; for (int i = 1; i < histogram.length; i++) { result[i] = result[i - 1] + histogram[i]; } return result; } /** * Returns the total number of pixels in the given image. * * @param luminances A matrix of the luminances within an image. * @return The total number of pixels in that image. */ public static int totalPixelsIn(int[][] luminances) { int result = 0; for (int i = 0; i < luminances.length; i++) for (int j = 0; j < luminances[i].length; j++) result++; return result; } /** * Applies the histogram equalization algorithm to the given image, represented by a matrix * of its luminances. * <p> * You are strongly encouraged to use the three methods you have implemented above in order to * implement this method. * * @param luminances The luminances of the input image. * @return The luminances of the image formed by applying histogram equalization. */ public static int[][] equalize(int[][] luminances) { /* TODO: Implement this method! */ int[][] result = luminances; int totalPixels = totalPixelsIn(luminances); // create a histogram of the image int[] gist = histogramFor(luminances); // convert a histogram into a cumulative int[] sovHist = cumulativeSumFor(gist); for (int i = 0; i < luminances.length; i++) for (int j = 0; j < luminances[i].length; j++) { int pixel = luminances[i][j]; result[i][j] = MAX_LUMINANCE * sovHist[pixel] / totalPixels; } return result; } }
3,353
0.576499
0.565762
103
31.553398
28.158266
98
false
false
0
0
0
0
0
0
0.504854
false
false
7
b805f6a6ef030500561427f782ad19fc113ba55c
14,310,831,086,284
985a3f016f26fffc0b7520cf2835c9daa5769e1b
/app/src/main/java/com/nit/tourguide/dao/ExpenseDao.java
5028cf3d6cb60b90027ab964e1e788b190037bf6
[]
no_license
nurul-islam01/Tour-Guide
https://github.com/nurul-islam01/Tour-Guide
ffdedffde9eb3bc419b2828181fcccf310b90099
27da802ff662ee6fb3f3329d56b3462c32c36b74
refs/heads/master
2021-05-22T16:41:08.155000
2020-04-22T03:47:38
2020-04-22T03:47:38
253,006,949
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nit.tourguide.dao; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.nit.tourguide.dben.Expense; import java.util.List; @Dao public interface ExpenseDao { @Insert void insert(Expense expense); @Update void update(Expense expense); @Delete void delete(Expense expense); @Query("SELECT * FROM expense WHERE tourId=(:tourId)") LiveData<List<Expense>> getAllExpense(int tourId); @Query("DELETE FROM expense") void deleteAllExpense(); }
UTF-8
Java
631
java
ExpenseDao.java
Java
[]
null
[]
package com.nit.tourguide.dao; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; import com.nit.tourguide.dben.Expense; import java.util.List; @Dao public interface ExpenseDao { @Insert void insert(Expense expense); @Update void update(Expense expense); @Delete void delete(Expense expense); @Query("SELECT * FROM expense WHERE tourId=(:tourId)") LiveData<List<Expense>> getAllExpense(int tourId); @Query("DELETE FROM expense") void deleteAllExpense(); }
631
0.732171
0.732171
31
19.354839
16.836115
58
false
false
0
0
0
0
0
0
0.451613
false
false
7
9f9bcc3b0acf8b27a19c1df5c50280a3c65359a2
34,926,674,071,190
7a171c2bd62b562981a5cd7fc23f01f2908abe27
/InvalidValueException.java
6268c7ca8ad9df0d795c4e74d0202f6f24c3f742
[]
no_license
amichaiman/shir-gali
https://github.com/amichaiman/shir-gali
02120b5110aaadc0d60af78fea7cf0721fe68f40
b1a05e5f3fa27309d0adffe1a24c95e787bc11d6
refs/heads/master
2020-06-25T10:20:25.471000
2019-07-28T13:08:05
2019-07-28T13:08:05
199,282,371
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class InvalidValueException extends Throwable { }
UTF-8
Java
58
java
InvalidValueException.java
Java
[]
null
[]
public class InvalidValueException extends Throwable { }
58
0.827586
0.827586
3
18.333334
25.223446
54
false
false
0
0
0
0
0
0
0
false
false
7
a8678c79af2271ec652bafca7532d4d2a475c4f9
30,683,246,426,739
021903f93da55a8cede864f21334bcd3febf15b1
/src/model/Order.java
99ed5e2bd7cc804972bf2852f472f79683973dc7
[]
no_license
CptPorse/DanishCrownJPA
https://github.com/CptPorse/DanishCrownJPA
d878c3c63162b017df779dd0f9f93013ad26d9f7
3b7a955f1d0c6e9db56fa3eefe059e7644df7fc3
refs/heads/master
2021-03-12T19:48:38.928000
2013-05-22T21:28:59
2013-05-22T21:28:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.eclipse.jdt.annotation.NonNullByDefault; import dao.Dao; @NonNullByDefault @Entity @Table(name = "\"Order\"") public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id") private long id; private int orderNumber; private double weightMarginPercent = 2; private double weightMarginKilo; @Temporal(value = TemporalType.TIMESTAMP) private Date loadingDate; @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) private List<SubOrder> subOrders = new ArrayList<SubOrder>(); public Order() { } public Order(int orderNumber, Date loadingDate) { super(); this.orderNumber = orderNumber; this.loadingDate = loadingDate; } public int getOrderNumber() { return orderNumber; } public void setOrderNumber(int orderNumber) { this.orderNumber = orderNumber; Dao.updateDatabase(this); } public double getWeightMarginPercent() { return weightMarginPercent; } public void setWeightMarginPercent(double weightMarginPercent) { this.weightMarginPercent = weightMarginPercent; Dao.updateDatabase(this); } public double getWeightMarginKilo() { return weightMarginKilo; } public void setWeightMarginKilo(double weightMarginKilo) { this.weightMarginKilo = weightMarginKilo; Dao.updateDatabase(this); } public Date getLoadingDate() { return loadingDate; } public void setLoadingDate(Date loadingDate) { this.loadingDate = loadingDate; Dao.updateDatabase(this); } /** * Returns a list of sub-orders in this Order. */ public ArrayList<SubOrder> getSubOrders() { return new ArrayList<SubOrder>(subOrders); } /** * Adds the sub-order to this Order. */ public void addSubOrder(SubOrder subOrder) { subOrders.add(subOrder); subOrder.setOrder(this); weightMarginKilo = calculateWeightMargin(); subOrder.getTrailer().setTrailerState(TrailerState.ENROUTE); Dao.updateDatabase(this); } /** * Removes the sub-order from this Order. */ public void removeSubOrder(SubOrder subOrder) { subOrders.remove(subOrder); Dao.updateDatabase(this); } private double calculateWeightMargin() { double totalWeight = 0; for (SubOrder subOrder : subOrders) { totalWeight += subOrder.getEstimatedWeight(); } return totalWeight * ((weightMarginPercent / 100)); } @Override public String toString() { return "Order ID: " + orderNumber; } }
UTF-8
Java
2,982
java
Order.java
Java
[]
null
[]
package model; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.eclipse.jdt.annotation.NonNullByDefault; import dao.Dao; @NonNullByDefault @Entity @Table(name = "\"Order\"") public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "order_id") private long id; private int orderNumber; private double weightMarginPercent = 2; private double weightMarginKilo; @Temporal(value = TemporalType.TIMESTAMP) private Date loadingDate; @OneToMany(mappedBy = "order", cascade = CascadeType.ALL) private List<SubOrder> subOrders = new ArrayList<SubOrder>(); public Order() { } public Order(int orderNumber, Date loadingDate) { super(); this.orderNumber = orderNumber; this.loadingDate = loadingDate; } public int getOrderNumber() { return orderNumber; } public void setOrderNumber(int orderNumber) { this.orderNumber = orderNumber; Dao.updateDatabase(this); } public double getWeightMarginPercent() { return weightMarginPercent; } public void setWeightMarginPercent(double weightMarginPercent) { this.weightMarginPercent = weightMarginPercent; Dao.updateDatabase(this); } public double getWeightMarginKilo() { return weightMarginKilo; } public void setWeightMarginKilo(double weightMarginKilo) { this.weightMarginKilo = weightMarginKilo; Dao.updateDatabase(this); } public Date getLoadingDate() { return loadingDate; } public void setLoadingDate(Date loadingDate) { this.loadingDate = loadingDate; Dao.updateDatabase(this); } /** * Returns a list of sub-orders in this Order. */ public ArrayList<SubOrder> getSubOrders() { return new ArrayList<SubOrder>(subOrders); } /** * Adds the sub-order to this Order. */ public void addSubOrder(SubOrder subOrder) { subOrders.add(subOrder); subOrder.setOrder(this); weightMarginKilo = calculateWeightMargin(); subOrder.getTrailer().setTrailerState(TrailerState.ENROUTE); Dao.updateDatabase(this); } /** * Removes the sub-order from this Order. */ public void removeSubOrder(SubOrder subOrder) { subOrders.remove(subOrder); Dao.updateDatabase(this); } private double calculateWeightMargin() { double totalWeight = 0; for (SubOrder subOrder : subOrders) { totalWeight += subOrder.getEstimatedWeight(); } return totalWeight * ((weightMarginPercent / 100)); } @Override public String toString() { return "Order ID: " + orderNumber; } }
2,982
0.715292
0.713615
140
19.299999
18.616697
63
false
false
0
0
0
0
0
0
1.257143
false
false
7
1c16c96ebe0f38af3736e1e9e0a26e6ffd19787c
17,033,840,363,778
6f672fb72caedccb841ee23f53e32aceeaf1895e
/Photography/amazon_photos_source/src/com/amazon/gallery/thor/app/activity/GalleryNavigationSetting.java
87bd743e7ee0686cf11884f8591dcbbea1163c10
[]
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.amazon.gallery.thor.app.activity; public final class GalleryNavigationSetting extends Enum { private static final GalleryNavigationSetting $VALUES[]; public static final GalleryNavigationSetting BACK; public static final GalleryNavigationSetting ICON; public static final GalleryNavigationSetting LEFT; public static final GalleryNavigationSetting NONE; private GalleryNavigationSetting(String s, int i) { super(s, i); } public static GalleryNavigationSetting valueOf(String s) { return (GalleryNavigationSetting)Enum.valueOf(com/amazon/gallery/thor/app/activity/GalleryNavigationSetting, s); } public static GalleryNavigationSetting[] values() { return (GalleryNavigationSetting[])$VALUES.clone(); } static { ICON = new GalleryNavigationSetting("ICON", 0); LEFT = new GalleryNavigationSetting("LEFT", 1); NONE = new GalleryNavigationSetting("NONE", 2); BACK = new GalleryNavigationSetting("BACK", 3); $VALUES = (new GalleryNavigationSetting[] { ICON, LEFT, NONE, BACK }); } }
UTF-8
Java
1,324
java
GalleryNavigationSetting.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.9996102452278137, "start": 45, "tag": "NAME", "value": "Pavel Kouznetsov" } ]
null
[]
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.amazon.gallery.thor.app.activity; public final class GalleryNavigationSetting extends Enum { private static final GalleryNavigationSetting $VALUES[]; public static final GalleryNavigationSetting BACK; public static final GalleryNavigationSetting ICON; public static final GalleryNavigationSetting LEFT; public static final GalleryNavigationSetting NONE; private GalleryNavigationSetting(String s, int i) { super(s, i); } public static GalleryNavigationSetting valueOf(String s) { return (GalleryNavigationSetting)Enum.valueOf(com/amazon/gallery/thor/app/activity/GalleryNavigationSetting, s); } public static GalleryNavigationSetting[] values() { return (GalleryNavigationSetting[])$VALUES.clone(); } static { ICON = new GalleryNavigationSetting("ICON", 0); LEFT = new GalleryNavigationSetting("LEFT", 1); NONE = new GalleryNavigationSetting("NONE", 2); BACK = new GalleryNavigationSetting("BACK", 3); $VALUES = (new GalleryNavigationSetting[] { ICON, LEFT, NONE, BACK }); } }
1,314
0.700151
0.691843
42
30.523809
28.822311
120
false
false
0
0
0
0
0
0
0.571429
false
false
7
c2ebcb58daa4e738a047f637d2afa6159e8e054c
19,353,122,637,139
b318c83364fca2acc968f6353b5ec4fa440b2800
/Essentials/src/main/java/com/huskydreaming/essentials/commands/teleportation/spawn/SetSpawnCommand.java
aa39c9834073be7f230eab264b8f73cdca32477f
[ "Apache-2.0" ]
permissive
HuskyDreaming/HuskySuite
https://github.com/HuskyDreaming/HuskySuite
4d212daf68ccc3d00214b49aa855a71820502830
ef7eb6edf44c73f2c067a1b8db3d44eea0bf10ae
refs/heads/master
2023-08-11T09:10:50.681000
2021-09-28T20:17:21
2021-09-28T20:17:21
409,812,098
1
0
Apache-2.0
false
2021-09-24T03:00:01
2021-09-24T02:54:30
2021-09-24T02:57:59
2021-09-24T03:00:00
0
0
0
0
null
false
false
package com.huskydreaming.essentials.commands.teleportation.spawn; import com.huskydreaming.core.resources.base.CommandBase; import com.huskydreaming.essentials.managers.SpawnManager; import org.bukkit.entity.Player; public class SetSpawnCommand extends CommandBase { private final SpawnManager spawnManager; public SetSpawnCommand(SpawnManager spawnManager) { super("setspawn"); this.spawnManager = spawnManager; } @Override public boolean run(Player player, String[] strings) { spawnManager.setSpawn(player); player.sendMessage("You have set the global spawn."); return false; } }
UTF-8
Java
652
java
SetSpawnCommand.java
Java
[]
null
[]
package com.huskydreaming.essentials.commands.teleportation.spawn; import com.huskydreaming.core.resources.base.CommandBase; import com.huskydreaming.essentials.managers.SpawnManager; import org.bukkit.entity.Player; public class SetSpawnCommand extends CommandBase { private final SpawnManager spawnManager; public SetSpawnCommand(SpawnManager spawnManager) { super("setspawn"); this.spawnManager = spawnManager; } @Override public boolean run(Player player, String[] strings) { spawnManager.setSpawn(player); player.sendMessage("You have set the global spawn."); return false; } }
652
0.73773
0.73773
22
28.636364
24.163357
66
false
false
0
0
0
0
0
0
0.5
false
false
7
c6b956e7438ff0a205e37f39cff49c22a337907d
30,185,030,191,626
30567e9f541e103cb1ea87669401284a3bc3ad01
/Uebung_3_a/src/Aufgabe3/Speise.java
4e55fcd56e8b4fadcc66885893408d5c7cec9432
[]
no_license
leickmann/Systementwicklung
https://github.com/leickmann/Systementwicklung
21f46703970a51206555a9d8486a38470e345686
edf9f7aed84418d762b240508866470048f58c71
refs/heads/master
2020-09-14T03:27:44.063000
2020-02-02T20:14:42
2020-02-02T20:14:42
223,002,389
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Aufgabe3; public class Speise extends SpeisekartenKomponente { private double preis; private boolean isVegetarisch; public Speise(String name, String beschreibung, double preis, boolean isVegetarisch){ super(name, beschreibung); this.preis = preis; this.isVegetarisch = isVegetarisch; } public void ausgeben(){ System.out.println("\tSpeiseName: " + super.getName() + " | Preis: " + this.preis + " | vegetarisch: " + this.isVegetarisch()); } public double getPreis(){ return this.preis; } public String isVegetarisch(){ if (this.isVegetarisch == true) { return "Ja"; } else return "Nein"; } }
UTF-8
Java
671
java
Speise.java
Java
[]
null
[]
package Aufgabe3; public class Speise extends SpeisekartenKomponente { private double preis; private boolean isVegetarisch; public Speise(String name, String beschreibung, double preis, boolean isVegetarisch){ super(name, beschreibung); this.preis = preis; this.isVegetarisch = isVegetarisch; } public void ausgeben(){ System.out.println("\tSpeiseName: " + super.getName() + " | Preis: " + this.preis + " | vegetarisch: " + this.isVegetarisch()); } public double getPreis(){ return this.preis; } public String isVegetarisch(){ if (this.isVegetarisch == true) { return "Ja"; } else return "Nein"; } }
671
0.66468
0.663189
30
20.433332
28.287434
133
false
false
0
0
0
0
0
0
1.6
false
false
7
b380cb88ce1fade14cb1479c70349fe08946329e
32,315,333,973,326
62d1d433d4440d450b806c35ef91788052ee2f77
/src/Controller/user/ProductServlet.java
95bb405c03cd5dc6212c0f3eed7d7a71ee779cb7
[]
no_license
teebeiz/baove-ps04378
https://github.com/teebeiz/baove-ps04378
9cb94c33d82b264f89d39b68ba34f2d31a013a91
7d57ae1e47c77a9d37658d8c48066a2a10aee7da
refs/heads/master
2021-01-20T02:37:33.732000
2017-04-26T02:48:02
2017-04-26T02:48:02
89,430,254
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Controller.user; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import DAO.Productdao; import Model.Product; /** * Servlet implementation class ProductServlet */ public class ProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; Productdao prd = new Productdao(); public ProductServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if(action.equalsIgnoreCase("products")){ int cate_id = Integer.parseInt(request.getParameter("cate_id")); List<Product> pr = prd.fillallprca(cate_id); request.setAttribute("listpr", pr); Productdao prd = new Productdao(); request.setAttribute("prd", prd); request.setAttribute("cate_id", request.getParameter("cate_id")); request.getRequestDispatcher("products.jsp").forward(request, response); } else if(action.equalsIgnoreCase("single")){ int pr_id = Integer.parseInt(request.getParameter("pr_id")); Product pr = prd.fillpr(pr_id); request.setAttribute("pr", pr); request.setAttribute("listprre", prd.fillallprrela(pr.getCate_id(), pr.getPr_id())); Productdao prd = new Productdao(); request.setAttribute("prd", prd); request.setAttribute("pr_id", request.getParameter("pr_id")); request.getRequestDispatcher("single.jsp").forward(request, response); } else if(action.equalsIgnoreCase("productll")){ } } }
UTF-8
Java
2,251
java
ProductServlet.java
Java
[]
null
[]
package Controller.user; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import DAO.Productdao; import Model.Product; /** * Servlet implementation class ProductServlet */ public class ProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; Productdao prd = new Productdao(); public ProductServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if(action.equalsIgnoreCase("products")){ int cate_id = Integer.parseInt(request.getParameter("cate_id")); List<Product> pr = prd.fillallprca(cate_id); request.setAttribute("listpr", pr); Productdao prd = new Productdao(); request.setAttribute("prd", prd); request.setAttribute("cate_id", request.getParameter("cate_id")); request.getRequestDispatcher("products.jsp").forward(request, response); } else if(action.equalsIgnoreCase("single")){ int pr_id = Integer.parseInt(request.getParameter("pr_id")); Product pr = prd.fillpr(pr_id); request.setAttribute("pr", pr); request.setAttribute("listprre", prd.fillallprrela(pr.getCate_id(), pr.getPr_id())); Productdao prd = new Productdao(); request.setAttribute("prd", prd); request.setAttribute("pr_id", request.getParameter("pr_id")); request.getRequestDispatcher("single.jsp").forward(request, response); } else if(action.equalsIgnoreCase("productll")){ } } }
2,251
0.712128
0.711684
71
29.704226
29.22154
119
false
false
0
0
0
0
0
0
1.901408
false
false
7
380996c3dea710c1a838bea9fb1b78abb812d8bb
34,497,177,347,105
0a7e8f3eb4f69c3d10ee49947680a48f69d5c378
/src/test/java/posters/tests/smoke/SearchTest.java
466769e560184ecbc2c4614155965af51689be22
[ "MIT" ]
permissive
Xceptance/neodymium-example
https://github.com/Xceptance/neodymium-example
2d787774d97901a17b12bdc60ff7a14c978e32b4
6195fd8006be5f848180cbad9f929af919c2c373
refs/heads/master
2023-08-31T17:05:05.327000
2023-08-31T08:51:53
2023-08-31T08:51:53
100,612,072
8
7
MIT
false
2023-08-31T08:51:54
2017-08-17T14:25:57
2021-12-20T14:01:16
2023-08-31T08:51:53
842
10
7
3
Java
false
false
package posters.tests.smoke; import org.junit.Before; import org.junit.Test; import com.xceptance.neodymium.module.statement.testdata.DataSet; import com.xceptance.neodymium.module.statement.testdata.SuppressDataSets; import com.xceptance.neodymium.util.DataUtils; import io.qameta.allure.Owner; import io.qameta.allure.Severity; import io.qameta.allure.SeverityLevel; import io.qameta.allure.junit4.Tag; import posters.flows.OpenHomePageFlow; import posters.tests.AbstractTest; import posters.tests.testdata.pageobjects.components.SearchTestData; @Owner("Tim Brown") @Severity(SeverityLevel.MINOR) @Tag("smoke") @SuppressDataSets public class SearchTest extends AbstractTest { private SearchTestData searchTestData; @Before public void setup() { searchTestData = DataUtils.get(SearchTestData.class); } @Test @DataSet(1) public void testSearching() { // go to homepage var homePage = OpenHomePageFlow.flow(); // go to category page var categoryPage = homePage.header.search.categoryPageResult(searchTestData.getSearchTerm()); categoryPage.validate(searchTestData.getSearchTerm(), searchTestData.getExpectedResultCount()); //go to product detail page final String productName = categoryPage.getProductNameByPosition(searchTestData.getResultPosition()); var productDetailPage = categoryPage.clickProductByPosition(searchTestData.getResultPosition()); productDetailPage.validate(productName); // go to homepage homePage = productDetailPage.openHomePage(); } @Test @DataSet(2) public void testSearchingWithoutResult() { // go to homepage var homePage = OpenHomePageFlow.flow(); // go to no hits page var noHitsPage = homePage.header.search.noHitsPageResult(searchTestData.getSearchTerm()); noHitsPage.validateStructure(); // go to homepage homePage = noHitsPage.openHomePage(); } }
UTF-8
Java
2,033
java
SearchTest.java
Java
[ { "context": "a.pageobjects.components.SearchTestData;\n\n@Owner(\"Tim Brown\")\n@Severity(SeverityLevel.MINOR)\n@Tag(\"smoke\")\n@S", "end": 569, "score": 0.9997169971466064, "start": 560, "tag": "NAME", "value": "Tim Brown" } ]
null
[]
package posters.tests.smoke; import org.junit.Before; import org.junit.Test; import com.xceptance.neodymium.module.statement.testdata.DataSet; import com.xceptance.neodymium.module.statement.testdata.SuppressDataSets; import com.xceptance.neodymium.util.DataUtils; import io.qameta.allure.Owner; import io.qameta.allure.Severity; import io.qameta.allure.SeverityLevel; import io.qameta.allure.junit4.Tag; import posters.flows.OpenHomePageFlow; import posters.tests.AbstractTest; import posters.tests.testdata.pageobjects.components.SearchTestData; @Owner("<NAME>") @Severity(SeverityLevel.MINOR) @Tag("smoke") @SuppressDataSets public class SearchTest extends AbstractTest { private SearchTestData searchTestData; @Before public void setup() { searchTestData = DataUtils.get(SearchTestData.class); } @Test @DataSet(1) public void testSearching() { // go to homepage var homePage = OpenHomePageFlow.flow(); // go to category page var categoryPage = homePage.header.search.categoryPageResult(searchTestData.getSearchTerm()); categoryPage.validate(searchTestData.getSearchTerm(), searchTestData.getExpectedResultCount()); //go to product detail page final String productName = categoryPage.getProductNameByPosition(searchTestData.getResultPosition()); var productDetailPage = categoryPage.clickProductByPosition(searchTestData.getResultPosition()); productDetailPage.validate(productName); // go to homepage homePage = productDetailPage.openHomePage(); } @Test @DataSet(2) public void testSearchingWithoutResult() { // go to homepage var homePage = OpenHomePageFlow.flow(); // go to no hits page var noHitsPage = homePage.header.search.noHitsPageResult(searchTestData.getSearchTerm()); noHitsPage.validateStructure(); // go to homepage homePage = noHitsPage.openHomePage(); } }
2,030
0.716183
0.714707
66
29.80303
28.063898
109
false
false
0
0
0
0
0
0
0.409091
false
false
7
0caaa6ce6a421ebd54d32e97b0863610c3960304
33,045,478,418,552
a38001a2714d89c48e4c9b7b432b7a9d4bc8e0ec
/src/main/java/edu/umn/cs/distributedkeyvaluestore/client/Clients.java
d76ed1f641ae698e5ff3bc28ebd2ead58e7bcb73
[]
no_license
jayapriya90/distributed-key-value-store
https://github.com/jayapriya90/distributed-key-value-store
6d78681882379802eab005dfa87ef65ef087081c
938746d9bd5cd44415b66bf7bcfc91f8355633bf
refs/heads/master
2021-01-10T10:37:12.553000
2017-06-13T21:43:39
2017-06-13T21:43:39
54,757,526
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.umn.cs.distributedkeyvaluestore.client; import edu.umn.cs.distributedkeyvaluestore.*; import edu.umn.cs.distributedkeyvaluestore.common.Constants; import edu.umn.cs.distributedkeyvaluestore.fileserver.FileServer; import org.apache.commons.cli.*; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.*; /** * Created by jayapriya on 3/27/16. */ /** * usage: clients * -i <arg> CSV list of request sequence in filename=contents format. * Example: file1,file2,file3=value3 is RRW (read, read, write) sequence. * -f <arg> File containing each line with read/write request in filename=contents format. * Example: input.txt contents for RRW sequence * file1 * file2 * file3=value3 * -n <arg> Number of concurrent clients (Each client will run in a thread) * -h <arg> Hostname for coordinator (default: localhost) * -p Print file servers metadata * --help Help */ public class Clients { private static final Logger LOG = LoggerFactory.getLogger(Clients.class); public static void main(String[] args) throws FileNotFoundException { // input is either // 1) csv of read, write operations. For read operations simply specify the filename to read. // For write operation specify in filename=contents format. // 2) specify input file with each line in the above format HelpFormatter formatter = new HelpFormatter(); // arguments that can be passed to this application Options options = new Options(); options.addOption("i", true, "CSV list of request sequence in filename=contents format.\n" + "Example: file1,file2,file3=value3 is RRW (read, read, write) sequence."); options.addOption("f", true, "File containing each line with read/write request in filename=contents format.\n" + "Example: input.txt contents for RRW sequence\n" + "file1\n" + "file2\n" + "file3=value3"); options.addOption("n", true, "Number of concurrent clients (Each client will run in a thread)"); options.addOption("h", true, "Hostname for coordinator (default: localhost)"); options.addOption("p", false, "Print file servers metadata"); options.addOption("help", false, "Help"); // command line parser for the above options CommandLineParser cliParser = new GnuParser(); try { CommandLine cli = cliParser.parse(options, args); // print help if (cli.hasOption("help")) { formatter.printHelp("clients", options); return; } String coordinatorHost = "localhost"; if (cli.hasOption("h")) { coordinatorHost = cli.getOptionValue("h"); } // only -p is specified if (cli.hasOption("p") && (!cli.hasOption("f") && !cli.hasOption("i"))) { printFileServerMetadata(coordinatorHost); return; } if (!cli.hasOption("f") && !cli.hasOption("i")) { System.err.println("-f or -i option has to be specified."); formatter.printHelp("client", options); return; } if (cli.hasOption("f") && cli.hasOption("i")) { System.err.println("Both -f and -i option cannot be specified. Specify either one."); formatter.printHelp("client", options); return; } // default 3 clients, that run in different threads int nClients = 3; List<String> input = null; if (cli.hasOption("f")) { String inputFilename = cli.getOptionValue("f"); input = readFile(inputFilename); } if (cli.hasOption("i")) { String[] tokens = cli.getOptionValue("i").split(","); input = new ArrayList<String>(); for (String token : tokens) { input.add(token); } } if (cli.hasOption("n")) { nClients = Integer.parseInt(cli.getOptionValue("n")); } LOG.info("#clients: " + nClients + ". Starting thread pool of size: " + nClients + " for each client"); ExecutorService executorService = Executors.newFixedThreadPool(nClients); if (input != null) { LOG.info("Total requests: " + input.size()); List<String> reqSequence = getRequestSequence(input); LOG.info("Request sequence: " + reqSequence); LOG.info("Requests: " + input); } List<Future<ResponseWithTime>> futures = new ArrayList<Future<ResponseWithTime>>(); for (String request : input) { FileServerInfo randomServer = getRandomServerFromCoordinator(coordinatorHost); RequestThread callable = new RequestThread(request, randomServer); Future<ResponseWithTime> futureResponse = executorService.submit(callable); futures.add(futureResponse); } // write request and execution time as CSV file so that its easy for plotting File output = new File("output.txt"); FileWriter fileWriter = new FileWriter(output, false); for (int i = 0; i < futures.size(); i++) { try { String request = input.get(i); ResponseWithTime responseWithTime = futures.get(i).get(); long execTime = responseWithTime.executionTime; Object response = responseWithTime.response; String csvString = ""; if (response instanceof ReadResponse) { ReadResponse readResponse = (ReadResponse) response; LOG.info("Got read response: " + readResponse + " for request: " + request + " in " + execTime + " ms"); csvString = "R," + request + "," + execTime + "\n"; } if (response instanceof WriteResponse) { WriteResponse writeResponse = (WriteResponse) response; LOG.info("Got write response: " + writeResponse + " for request: " + request + " in " + execTime + " ms"); csvString = "W," + request + "," + execTime + "\n"; } if (fileWriter != null) { fileWriter.write(csvString); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } if (fileWriter != null) { fileWriter.close(); } executorService.shutdownNow(); if (cli.hasOption("p")) { printFileServerMetadata(coordinatorHost); return; } } catch (ParseException e) { // if wrong format is specified System.err.println("Invalid option."); formatter.printHelp("clients", options); } catch (TException e) { e.printStackTrace(); } catch (IOException e) { // in case of exception ignore as this file is just for convenience } } private static void printFileServerMetadata(String coordinatorHost) throws TException { TTransport nodeSocket = new TSocket(coordinatorHost, Constants.COORDINATOR_PORT); try { nodeSocket.open(); TProtocol protocol = new TBinaryProtocol(nodeSocket); CoordinatorEndPoints.Client client = new CoordinatorEndPoints.Client(protocol); Map<FileServerInfo, FileServerMetaData> metadata = client.getMetadata(); System.out.println("\n"); System.out.println("-----------------------------------------------------------------------------"); System.out.println(" FILE SERVER METADATA "); System.out.println("-----------------------------------------------------------------------------"); for (Map.Entry<FileServerInfo, FileServerMetaData> entry : metadata.entrySet()) { System.out.println("Metadata from server: " + entry.getKey()); for (FileInfo fileInfo : entry.getValue().getFileinfos()) { System.out.println(fileInfo); } System.out.println("\n"); } System.out.println("-----------------------------------------------------------------------------"); } finally { if (nodeSocket != null) { nodeSocket.close(); } } } private static FileServerInfo getRandomServerFromCoordinator(String coordinatorHost) throws TException { LOG.info("Connecting to coordinator at " + coordinatorHost + " to get random node for client."); TTransport nodeSocket = new TSocket(coordinatorHost, Constants.COORDINATOR_PORT); try { nodeSocket.open(); TProtocol protocol = new TBinaryProtocol(nodeSocket); CoordinatorEndPoints.Client client = new CoordinatorEndPoints.Client(protocol); FileServerResponse fileServerResponse = client.getFileServer(); if (fileServerResponse.getStatus().equals(Status.NO_NODE_FOUND)) { LOG.error("No nodes found in the system for clients to connect!"); return null; } LOG.info("Returning node: " + fileServerResponse.getFileServerInfo() + " for client"); return fileServerResponse.getFileServerInfo(); } finally { if (nodeSocket != null) { nodeSocket.close(); } } } private static List<String> getRequestSequence(List<String> input) { List<String> seq = new ArrayList<String>(); for (String row : input) { if (row.contains("=")) { seq.add("W"); } else { seq.add("R"); } } return seq; } private static List<String> readFile(String inputFilename) throws FileNotFoundException { List<String> input = new ArrayList<String>(); Scanner scanner = new Scanner(new File(inputFilename)); while (scanner.hasNext()) { input.add(scanner.nextLine()); } return input; } private static class ResponseWithTime { long executionTime; Object response; public ResponseWithTime(long execTime, Object response) { this.executionTime = execTime; this.response = response; } } private static class RequestThread implements Callable<ResponseWithTime> { private String requestString; private FileServerInfo server; public RequestThread(String request, FileServerInfo fileServerInfo) { this.requestString = request; this.server = fileServerInfo; } @Override public ResponseWithTime call() throws Exception { long start = System.currentTimeMillis(); TTransport nodeSocket = new TSocket(server.getHostname(), server.getPort()); try { nodeSocket.open(); TProtocol protocol = new TBinaryProtocol(nodeSocket); FileServerEndPoints.Client client = new FileServerEndPoints.Client(protocol); if (requestString.contains("=")) { // write request String[] tokens = requestString.split("="); String filename = tokens[0]; String contents = tokens[1]; LOG.info("Sending write request (filename: " + filename + " contents: " + contents + ") to " + server); WriteResponse writeResponse = client.write(filename, contents); long end = System.currentTimeMillis(); return new ResponseWithTime(end - start, writeResponse); } else { // read request LOG.info("Sending read request (filename: " + requestString + ") to " + server); ReadResponse readResponse = client.read(requestString); long end = System.currentTimeMillis(); return new ResponseWithTime(end - start, readResponse); } } finally { if (nodeSocket != null) { nodeSocket.close(); } } } } }
UTF-8
Java
13,366
java
Clients.java
Java
[ { "context": "\nimport java.util.concurrent.*;\n\n/**\n * Created by jayapriya on 3/27/16.\n */\n\n/**\n * usage: clients\n * -i <arg", "end": 813, "score": 0.9997047185897827, "start": 804, "tag": "USERNAME", "value": "jayapriya" } ]
null
[]
package edu.umn.cs.distributedkeyvaluestore.client; import edu.umn.cs.distributedkeyvaluestore.*; import edu.umn.cs.distributedkeyvaluestore.common.Constants; import edu.umn.cs.distributedkeyvaluestore.fileserver.FileServer; import org.apache.commons.cli.*; import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.concurrent.*; /** * Created by jayapriya on 3/27/16. */ /** * usage: clients * -i <arg> CSV list of request sequence in filename=contents format. * Example: file1,file2,file3=value3 is RRW (read, read, write) sequence. * -f <arg> File containing each line with read/write request in filename=contents format. * Example: input.txt contents for RRW sequence * file1 * file2 * file3=value3 * -n <arg> Number of concurrent clients (Each client will run in a thread) * -h <arg> Hostname for coordinator (default: localhost) * -p Print file servers metadata * --help Help */ public class Clients { private static final Logger LOG = LoggerFactory.getLogger(Clients.class); public static void main(String[] args) throws FileNotFoundException { // input is either // 1) csv of read, write operations. For read operations simply specify the filename to read. // For write operation specify in filename=contents format. // 2) specify input file with each line in the above format HelpFormatter formatter = new HelpFormatter(); // arguments that can be passed to this application Options options = new Options(); options.addOption("i", true, "CSV list of request sequence in filename=contents format.\n" + "Example: file1,file2,file3=value3 is RRW (read, read, write) sequence."); options.addOption("f", true, "File containing each line with read/write request in filename=contents format.\n" + "Example: input.txt contents for RRW sequence\n" + "file1\n" + "file2\n" + "file3=value3"); options.addOption("n", true, "Number of concurrent clients (Each client will run in a thread)"); options.addOption("h", true, "Hostname for coordinator (default: localhost)"); options.addOption("p", false, "Print file servers metadata"); options.addOption("help", false, "Help"); // command line parser for the above options CommandLineParser cliParser = new GnuParser(); try { CommandLine cli = cliParser.parse(options, args); // print help if (cli.hasOption("help")) { formatter.printHelp("clients", options); return; } String coordinatorHost = "localhost"; if (cli.hasOption("h")) { coordinatorHost = cli.getOptionValue("h"); } // only -p is specified if (cli.hasOption("p") && (!cli.hasOption("f") && !cli.hasOption("i"))) { printFileServerMetadata(coordinatorHost); return; } if (!cli.hasOption("f") && !cli.hasOption("i")) { System.err.println("-f or -i option has to be specified."); formatter.printHelp("client", options); return; } if (cli.hasOption("f") && cli.hasOption("i")) { System.err.println("Both -f and -i option cannot be specified. Specify either one."); formatter.printHelp("client", options); return; } // default 3 clients, that run in different threads int nClients = 3; List<String> input = null; if (cli.hasOption("f")) { String inputFilename = cli.getOptionValue("f"); input = readFile(inputFilename); } if (cli.hasOption("i")) { String[] tokens = cli.getOptionValue("i").split(","); input = new ArrayList<String>(); for (String token : tokens) { input.add(token); } } if (cli.hasOption("n")) { nClients = Integer.parseInt(cli.getOptionValue("n")); } LOG.info("#clients: " + nClients + ". Starting thread pool of size: " + nClients + " for each client"); ExecutorService executorService = Executors.newFixedThreadPool(nClients); if (input != null) { LOG.info("Total requests: " + input.size()); List<String> reqSequence = getRequestSequence(input); LOG.info("Request sequence: " + reqSequence); LOG.info("Requests: " + input); } List<Future<ResponseWithTime>> futures = new ArrayList<Future<ResponseWithTime>>(); for (String request : input) { FileServerInfo randomServer = getRandomServerFromCoordinator(coordinatorHost); RequestThread callable = new RequestThread(request, randomServer); Future<ResponseWithTime> futureResponse = executorService.submit(callable); futures.add(futureResponse); } // write request and execution time as CSV file so that its easy for plotting File output = new File("output.txt"); FileWriter fileWriter = new FileWriter(output, false); for (int i = 0; i < futures.size(); i++) { try { String request = input.get(i); ResponseWithTime responseWithTime = futures.get(i).get(); long execTime = responseWithTime.executionTime; Object response = responseWithTime.response; String csvString = ""; if (response instanceof ReadResponse) { ReadResponse readResponse = (ReadResponse) response; LOG.info("Got read response: " + readResponse + " for request: " + request + " in " + execTime + " ms"); csvString = "R," + request + "," + execTime + "\n"; } if (response instanceof WriteResponse) { WriteResponse writeResponse = (WriteResponse) response; LOG.info("Got write response: " + writeResponse + " for request: " + request + " in " + execTime + " ms"); csvString = "W," + request + "," + execTime + "\n"; } if (fileWriter != null) { fileWriter.write(csvString); } } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } if (fileWriter != null) { fileWriter.close(); } executorService.shutdownNow(); if (cli.hasOption("p")) { printFileServerMetadata(coordinatorHost); return; } } catch (ParseException e) { // if wrong format is specified System.err.println("Invalid option."); formatter.printHelp("clients", options); } catch (TException e) { e.printStackTrace(); } catch (IOException e) { // in case of exception ignore as this file is just for convenience } } private static void printFileServerMetadata(String coordinatorHost) throws TException { TTransport nodeSocket = new TSocket(coordinatorHost, Constants.COORDINATOR_PORT); try { nodeSocket.open(); TProtocol protocol = new TBinaryProtocol(nodeSocket); CoordinatorEndPoints.Client client = new CoordinatorEndPoints.Client(protocol); Map<FileServerInfo, FileServerMetaData> metadata = client.getMetadata(); System.out.println("\n"); System.out.println("-----------------------------------------------------------------------------"); System.out.println(" FILE SERVER METADATA "); System.out.println("-----------------------------------------------------------------------------"); for (Map.Entry<FileServerInfo, FileServerMetaData> entry : metadata.entrySet()) { System.out.println("Metadata from server: " + entry.getKey()); for (FileInfo fileInfo : entry.getValue().getFileinfos()) { System.out.println(fileInfo); } System.out.println("\n"); } System.out.println("-----------------------------------------------------------------------------"); } finally { if (nodeSocket != null) { nodeSocket.close(); } } } private static FileServerInfo getRandomServerFromCoordinator(String coordinatorHost) throws TException { LOG.info("Connecting to coordinator at " + coordinatorHost + " to get random node for client."); TTransport nodeSocket = new TSocket(coordinatorHost, Constants.COORDINATOR_PORT); try { nodeSocket.open(); TProtocol protocol = new TBinaryProtocol(nodeSocket); CoordinatorEndPoints.Client client = new CoordinatorEndPoints.Client(protocol); FileServerResponse fileServerResponse = client.getFileServer(); if (fileServerResponse.getStatus().equals(Status.NO_NODE_FOUND)) { LOG.error("No nodes found in the system for clients to connect!"); return null; } LOG.info("Returning node: " + fileServerResponse.getFileServerInfo() + " for client"); return fileServerResponse.getFileServerInfo(); } finally { if (nodeSocket != null) { nodeSocket.close(); } } } private static List<String> getRequestSequence(List<String> input) { List<String> seq = new ArrayList<String>(); for (String row : input) { if (row.contains("=")) { seq.add("W"); } else { seq.add("R"); } } return seq; } private static List<String> readFile(String inputFilename) throws FileNotFoundException { List<String> input = new ArrayList<String>(); Scanner scanner = new Scanner(new File(inputFilename)); while (scanner.hasNext()) { input.add(scanner.nextLine()); } return input; } private static class ResponseWithTime { long executionTime; Object response; public ResponseWithTime(long execTime, Object response) { this.executionTime = execTime; this.response = response; } } private static class RequestThread implements Callable<ResponseWithTime> { private String requestString; private FileServerInfo server; public RequestThread(String request, FileServerInfo fileServerInfo) { this.requestString = request; this.server = fileServerInfo; } @Override public ResponseWithTime call() throws Exception { long start = System.currentTimeMillis(); TTransport nodeSocket = new TSocket(server.getHostname(), server.getPort()); try { nodeSocket.open(); TProtocol protocol = new TBinaryProtocol(nodeSocket); FileServerEndPoints.Client client = new FileServerEndPoints.Client(protocol); if (requestString.contains("=")) { // write request String[] tokens = requestString.split("="); String filename = tokens[0]; String contents = tokens[1]; LOG.info("Sending write request (filename: " + filename + " contents: " + contents + ") to " + server); WriteResponse writeResponse = client.write(filename, contents); long end = System.currentTimeMillis(); return new ResponseWithTime(end - start, writeResponse); } else { // read request LOG.info("Sending read request (filename: " + requestString + ") to " + server); ReadResponse readResponse = client.read(requestString); long end = System.currentTimeMillis(); return new ResponseWithTime(end - start, readResponse); } } finally { if (nodeSocket != null) { nodeSocket.close(); } } } } }
13,366
0.554092
0.551848
317
41.16404
30.77462
123
false
false
0
0
0
0
0
0
0.599369
false
false
7
4528e90f1bfb9e15161dfca44720d21594aaead5
38,285,338,478,360
8f9ae2e7c095be551fc912f7418c0bcde360eec2
/snail_project/snail_weixin/src/main/java/com/du/weixin/controller/user/UserController.java
0784e8ffa8398ff100ec124978ad83b4e72dfb9d
[]
no_license
athc/snail
https://github.com/athc/snail
7719d47bae6decb9e331d8d641c3fd701a9bd7cc
187b8595653a23293dff5195caf74ce12b6355e2
refs/heads/master
2020-03-14T17:45:29.398000
2018-05-01T15:19:44
2018-05-01T15:19:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.du.weixin.controller.user; /** * @author dellll */ public class UserController { }
UTF-8
Java
98
java
UserController.java
Java
[ { "context": "age com.du.weixin.controller.user;\n\n/**\n * @author dellll\n */\npublic class UserController {\n}\n", "end": 61, "score": 0.9995301961898804, "start": 55, "tag": "USERNAME", "value": "dellll" } ]
null
[]
package com.du.weixin.controller.user; /** * @author dellll */ public class UserController { }
98
0.704082
0.704082
7
13
14.192554
38
false
false
0
0
0
0
0
0
0.142857
false
false
7
49592159b36bab492aac632af3e5432fda3aeedc
35,785,667,517,862
1931a406be7b3a04d72f7ac6bfc0ea2d22394687
/src/main/java/com/oet/application/repository/AuthorityRepository.java
b1fa58008da2260799042176e614fce3e5681f67
[]
no_license
batugokce/online-education-tool
https://github.com/batugokce/online-education-tool
f196e87f7456c2023b266548823158c67dad3c69
797d43d6c5a55bc0d366de98c237f53d0e95efdb
refs/heads/master
2023-07-13T08:33:09.969000
2021-08-18T18:11:52
2021-08-18T18:11:52
397,693,806
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.oet.application.repository; import com.oet.application.entity.Authority; import org.springframework.data.jpa.repository.JpaRepository; public interface AuthorityRepository extends JpaRepository<Authority, Long> { Authority findByAuthority(String authority); }
UTF-8
Java
280
java
AuthorityRepository.java
Java
[]
null
[]
package com.oet.application.repository; import com.oet.application.entity.Authority; import org.springframework.data.jpa.repository.JpaRepository; public interface AuthorityRepository extends JpaRepository<Authority, Long> { Authority findByAuthority(String authority); }
280
0.828571
0.828571
10
27
28.499123
77
false
false
0
0
0
0
0
0
0.5
false
false
7
a89fd84c7fa558d159f2bbdc349bd80a734863c9
94,489,329,629
effe9cd3e604e0d8acc989efa506c03c1a4c6d1b
/src/main/java/edu/fiuba/algo3/modelo/exclusividad/Exclusividad.java
353d566906427f4c3d6aea33069dcbfc579fb5c1
[]
no_license
nicolasmns/Algo3-TP2-Kahoot
https://github.com/nicolasmns/Algo3-TP2-Kahoot
1057897427f1b27ba45bcf37d5a378b5d8a5fa05
08058c0a940e6b64beff6d6ba32f5b88ff1c2ff1
refs/heads/master
2022-12-08T03:58:40.289000
2020-08-27T03:35:26
2020-08-27T03:35:26
289,108,830
1
0
null
true
2020-08-20T20:55:25
2020-08-20T20:55:24
2020-08-20T20:03:45
2020-08-20T20:03:42
32,626
0
0
0
null
false
false
package edu.fiuba.algo3.modelo.exclusividad; import edu.fiuba.algo3.modelo.Respuesta; import java.util.ArrayList; public interface Exclusividad { void aplicarExclusividad(ArrayList<Respuesta> respuestas); int verMagnitud(); void aplicarPuntos(Respuesta respuesta, int puntos); }
UTF-8
Java
309
java
Exclusividad.java
Java
[]
null
[]
package edu.fiuba.algo3.modelo.exclusividad; import edu.fiuba.algo3.modelo.Respuesta; import java.util.ArrayList; public interface Exclusividad { void aplicarExclusividad(ArrayList<Respuesta> respuestas); int verMagnitud(); void aplicarPuntos(Respuesta respuesta, int puntos); }
309
0.747573
0.7411
13
21.76923
22.41275
62
false
false
0
0
0
0
0
0
0.538462
false
false
7
d4478395242e9e0a6b1a3c3adcf8acfc3018a5bf
36,120,674,972,721
a51ff38428092be631358520f46a396e5a7c2ecf
/planmanager/WEB-INF/classes/org/study/web/JoinController.java
fa8eebd43026c91d36ec6a87162de6d6b71cd155
[]
no_license
k-sangwon/sangwon
https://github.com/k-sangwon/sangwon
2a264f65f33492083dd3cb884617c4a3d1360d0d
59ac65636e7c1692beedf526b96eb1440b78c8e0
refs/heads/master
2020-03-26T04:48:37.091000
2018-08-13T03:15:58
2018-08-13T03:15:58
144,229,894
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.study.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.study.dao.UserDao; import org.study.model.User; @WebServlet("/join") public class JoinController extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.getRequestDispatcher("/WEB-INF/views/joinForm.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String id = request.getParameter("id"); String pw = request.getParameter("pw"); String name = request.getParameter("name"); String tel =request.getParameter("tel"); String addr =request.getParameter("addr"); User user = new User(); user.setId(id); user.setPw(pw); user.setName(name); user.setTel(tel); user.setAddr(addr); //System.out.println(user); UserDao dao = new UserDao(); if (dao.addUser(user)) { // 사용자 추가 성공 request.setAttribute("error", "사용자 추가가 성공했습니다. 로그인 하세요"); request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response); } else { request.setAttribute("error", "아이디가 중복합니다"); request.getRequestDispatcher("/WEB-INF/views/joinForm.jsp").forward(request, response); } } }
UHC
Java
1,653
java
JoinController.java
Java
[ { "context": "ser.setId(id);\r\n\t\tuser.setPw(pw);\r\n\t\tuser.setName(name);\r\n\t\tuser.setTel(tel);\r\n\t\tuser.setAddr(addr);\r\n\t\t", "end": 1111, "score": 0.9841256141662598, "start": 1107, "tag": "NAME", "value": "name" } ]
null
[]
package org.study.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.study.dao.UserDao; import org.study.model.User; @WebServlet("/join") public class JoinController extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.getRequestDispatcher("/WEB-INF/views/joinForm.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String id = request.getParameter("id"); String pw = request.getParameter("pw"); String name = request.getParameter("name"); String tel =request.getParameter("tel"); String addr =request.getParameter("addr"); User user = new User(); user.setId(id); user.setPw(pw); user.setName(name); user.setTel(tel); user.setAddr(addr); //System.out.println(user); UserDao dao = new UserDao(); if (dao.addUser(user)) { // 사용자 추가 성공 request.setAttribute("error", "사용자 추가가 성공했습니다. 로그인 하세요"); request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response); } else { request.setAttribute("error", "아이디가 중복합니다"); request.getRequestDispatcher("/WEB-INF/views/joinForm.jsp").forward(request, response); } } }
1,653
0.719874
0.719874
54
27.388889
25.350445
90
false
false
0
0
0
0
0
0
1.962963
false
false
7
687b47a01fa1a7ea81fe175a83d523613da532d4
12,438,225,341,699
9f48a6ed0896948ae038b69c354b65bbb9bac3c2
/app/src/main/java/id/net/iconpln/fso/polda/model/BasicResponse.java
da647b1aa9be6cb022188302dc695e21b687b70f
[]
no_license
adhiozcan/github-fso-polda
https://github.com/adhiozcan/github-fso-polda
496ca61c6b55a4be768bd7401c2293a02a0d3eb7
05a03452e3062fe618d34f7623406309bdd23f08
refs/heads/master
2021-01-21T12:11:18.764000
2017-05-19T07:49:39
2017-05-19T07:49:39
91,780,313
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package id.net.iconpln.fso.polda.model; import com.google.gson.annotations.SerializedName; /** * Created by Ozcan on 16/12/2016. */ public class BasicResponse { @SerializedName("data") private Status status; public String getStatus() { return status.getIsSuccess(); } }
UTF-8
Java
300
java
BasicResponse.java
Java
[ { "context": "son.annotations.SerializedName;\n\n/**\n * Created by Ozcan on 16/12/2016.\n */\n\npublic class BasicResponse {\n", "end": 116, "score": 0.9989220499992371, "start": 111, "tag": "USERNAME", "value": "Ozcan" } ]
null
[]
package id.net.iconpln.fso.polda.model; import com.google.gson.annotations.SerializedName; /** * Created by Ozcan on 16/12/2016. */ public class BasicResponse { @SerializedName("data") private Status status; public String getStatus() { return status.getIsSuccess(); } }
300
0.686667
0.66
16
17.75
17.137314
50
false
false
0
0
0
0
0
0
0.25
false
false
7
7a9f33bee44357d7e32ff87305e00b1e4fdacace
29,128,468,270,213
6f16476f722f74f1fe15b9425d44d8128cbdb7c4
/src/main/java/com/prayerlaputa/im/study/protocol/response/LoginResponsePacket.java
9d47a84094995258299bb572cfff729be5bd66f8
[]
no_license
evasnowind/netty-im
https://github.com/evasnowind/netty-im
0816cc68041b40178a4e3e1ad843c939b0f9befb
81da65fb720f68f30a661b2c67a52f656712ea33
refs/heads/master
2022-12-24T18:56:50.078000
2020-09-30T12:32:32
2020-10-09T05:55:17
295,985,706
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.prayerlaputa.im.study.protocol.response; import com.prayerlaputa.im.study.protocol.Packet; import com.prayerlaputa.im.study.protocol.command.Command; import lombok.Data; /** * @author chenglong.yu * created on 2020/9/17 */ @Data public class LoginResponsePacket extends Packet { private boolean success; private String reason; private String userId; private String userName; @Override public Byte getCommand() { return Command.LOGIN_RESPONSE; } }
UTF-8
Java
501
java
LoginResponsePacket.java
Java
[ { "context": "mmand.Command;\nimport lombok.Data;\n\n/**\n * @author chenglong.yu\n * created on 2020/9/17\n */\n@Data\npublic class Lo", "end": 211, "score": 0.999294102191925, "start": 199, "tag": "NAME", "value": "chenglong.yu" } ]
null
[]
package com.prayerlaputa.im.study.protocol.response; import com.prayerlaputa.im.study.protocol.Packet; import com.prayerlaputa.im.study.protocol.command.Command; import lombok.Data; /** * @author chenglong.yu * created on 2020/9/17 */ @Data public class LoginResponsePacket extends Packet { private boolean success; private String reason; private String userId; private String userName; @Override public Byte getCommand() { return Command.LOGIN_RESPONSE; } }
501
0.732535
0.718563
22
21.772728
18.2929
58
false
false
0
0
0
0
0
0
0.409091
false
false
7
93f43e3facefae1236b44533dc1e01816c4710d0
37,400,575,216,172
7cf6bd5cfb7c2079e944bce687b355f767d2382d
/src/main/java/org/wsclient/controller/ClientController.java
e4d6d8345d66ca6f759994e816dbb15aac4d2b1c
[]
no_license
georgeGates/ws-client
https://github.com/georgeGates/ws-client
f35ddf45c04d4c57d2e4a75e6717291a3300abb1
a0c35560b179d0af02300ddff2afbded38491675
refs/heads/master
2020-07-03T19:23:33.302000
2019-08-13T00:33:51
2019-08-13T00:33:51
202,022,926
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.wsclient.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.wsclient.dto.ClientDTO; import org.wsclient.model.Client; import org.wsclient.service.ClientService; /** * * @author George Compton - george.compton@hotmail.com * @since 2019.08.12 * */ @RestController @RequestMapping("/api/") public class ClientController { private final ClientService service; @Autowired public ClientController(ClientService service) { this.service = service; } @PostMapping("/client") public ClientDTO create(@Valid @RequestBody Client client) { return this.service.create(client); } @PutMapping("/client") public ClientDTO update(@RequestBody Client client) { return this.service.edit(client); } @GetMapping("/client") public Page<Client> getAll(Pageable pageable) { return this.service.findAll(pageable); } @GetMapping("/client/{id}") public ClientDTO getById(@PathVariable Long id) { return this.service.findById(id); } @DeleteMapping("/client/{id}") public ResponseEntity<?> delete(@PathVariable Long id) { return this.service.delete(id); } }
UTF-8
Java
1,879
java
ClientController.java
Java
[ { "context": "ent.service.ClientService;\r\n\r\n/**\r\n * \r\n * @author George Compton - george.compton@hotmail.com\r\n * @since 2019.08.1", "end": 926, "score": 0.9996856451034546, "start": 912, "tag": "NAME", "value": "George Compton" }, { "context": "tService;\r\n\r\n/**\r\n * \r\n * @author George Compton - george.compton@hotmail.com\r\n * @since 2019.08.12\r\n *\r\n */\r\n@RestController\r\n", "end": 955, "score": 0.9999335408210754, "start": 929, "tag": "EMAIL", "value": "george.compton@hotmail.com" } ]
null
[]
package org.wsclient.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.wsclient.dto.ClientDTO; import org.wsclient.model.Client; import org.wsclient.service.ClientService; /** * * @author <NAME> - <EMAIL> * @since 2019.08.12 * */ @RestController @RequestMapping("/api/") public class ClientController { private final ClientService service; @Autowired public ClientController(ClientService service) { this.service = service; } @PostMapping("/client") public ClientDTO create(@Valid @RequestBody Client client) { return this.service.create(client); } @PutMapping("/client") public ClientDTO update(@RequestBody Client client) { return this.service.edit(client); } @GetMapping("/client") public Page<Client> getAll(Pageable pageable) { return this.service.findAll(pageable); } @GetMapping("/client/{id}") public ClientDTO getById(@PathVariable Long id) { return this.service.findById(id); } @DeleteMapping("/client/{id}") public ResponseEntity<?> delete(@PathVariable Long id) { return this.service.delete(id); } }
1,852
0.747738
0.743481
63
27.825397
22.61657
62
false
false
0
0
0
0
0
0
0.825397
false
false
7
c44047369af3e6bab10032aba0c7bf558d65ac1e
19,894,288,582,477
cd94da7e649975014bba842699802e9918aac99d
/src/main/java/com/yunforge/collect/model/TaskDetail_.java
687860d1a15f46b984b97a37d4e4509c9661a278
[]
no_license
kayie77/pcs
https://github.com/kayie77/pcs
7250680a7b2322752bb2b529ba9e9038ecdb36b1
8efc9e4e207c6560ea1f51f059c0c36649a88e34
refs/heads/master
2020-04-26T12:25:09.035000
2019-03-03T08:22:03
2019-03-03T08:22:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yunforge.collect.model; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2016-01-15T10:24:55.524+0800") @StaticMetamodel(TaskDetail.class) public class TaskDetail_ { public static volatile SingularAttribute<TaskDetail, String> id; public static volatile SingularAttribute<TaskDetail, String> dataID; public static volatile SingularAttribute<TaskDetail, Date> beginDate; public static volatile SingularAttribute<TaskDetail, Date> endDate; public static volatile SingularAttribute<TaskDetail, String> cron; public static volatile SingularAttribute<TaskDetail, String> timeframe; public static volatile SingularAttribute<TaskDetail, Integer> nullable; public static volatile SingularAttribute<TaskDetail, String> checkExp; public static volatile SingularAttribute<TaskDetail, String> remark; public static volatile SingularAttribute<TaskDetail, AgrProCategory2> agrProCategory2; public static volatile SingularAttribute<TaskDetail, TaskMain> taskMain; public static volatile ListAttribute<TaskDetail, DataReoprtedDetail> dataReoprtedDetails; }
UTF-8
Java
1,287
java
TaskDetail_.java
Java
[]
null
[]
package com.yunforge.collect.model; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.ListAttribute; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2016-01-15T10:24:55.524+0800") @StaticMetamodel(TaskDetail.class) public class TaskDetail_ { public static volatile SingularAttribute<TaskDetail, String> id; public static volatile SingularAttribute<TaskDetail, String> dataID; public static volatile SingularAttribute<TaskDetail, Date> beginDate; public static volatile SingularAttribute<TaskDetail, Date> endDate; public static volatile SingularAttribute<TaskDetail, String> cron; public static volatile SingularAttribute<TaskDetail, String> timeframe; public static volatile SingularAttribute<TaskDetail, Integer> nullable; public static volatile SingularAttribute<TaskDetail, String> checkExp; public static volatile SingularAttribute<TaskDetail, String> remark; public static volatile SingularAttribute<TaskDetail, AgrProCategory2> agrProCategory2; public static volatile SingularAttribute<TaskDetail, TaskMain> taskMain; public static volatile ListAttribute<TaskDetail, DataReoprtedDetail> dataReoprtedDetails; }
1,287
0.826729
0.808858
24
51.625
26.167429
90
false
false
0
0
0
0
0
0
1.791667
false
false
7
02cb15b26a85fcbd43616f823c4801d1158273e5
37,091,337,576,295
012e9bd5bfbc5ceca4e36af55a7ddf4fce98b403
/code/app/src/main/java/com/yzb/card/king/ui/bonus/model/RedBagRecOrSendImpl.java
38508019a3a7d3507ea0510716bf56e892ed9112
[]
no_license
litliang/ms
https://github.com/litliang/ms
a7152567c2f0e4d663efdda39503642edd33b4b6
d7483bc76d43e060906c47acc1bc2c3179838249
refs/heads/master
2021-09-01T23:51:50.934000
2017-12-29T07:30:49
2017-12-29T07:30:49
115,697,248
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yzb.card.king.ui.bonus.model; import com.yzb.card.king.http.CommonServerRequest; import com.yzb.card.king.http.DataCallBack; import java.util.Map; /** * 类 名: 红包领取记录实现类 * 作 者: gaolei * 日 期:2016年12月22日 * 描 述:Model实现类 */ public class RedBagRecOrSendImpl implements RedBagRecOrSendDao { private DataCallBack callBack; public RedBagRecOrSendImpl(DataCallBack callBack) { this.callBack = callBack; } @Override public void setBillDetail(Map<String, Object> map, String serviceName, int type) { CommonServerRequest request = new CommonServerRequest(); request.sendReuqest(map,serviceName,type); request.setOnDataLoadFinish(callBack); } }
UTF-8
Java
765
java
RedBagRecOrSendImpl.java
Java
[ { "context": "port java.util.Map;\n\n/**\n * 类 名: 红包领取记录实现类\n * 作 者: gaolei\n * 日 期:2016年12月22日\n * 描 述:Model实现类\n */\n\npublic cl", "end": 198, "score": 0.9994733333587646, "start": 192, "tag": "USERNAME", "value": "gaolei" } ]
null
[]
package com.yzb.card.king.ui.bonus.model; import com.yzb.card.king.http.CommonServerRequest; import com.yzb.card.king.http.DataCallBack; import java.util.Map; /** * 类 名: 红包领取记录实现类 * 作 者: gaolei * 日 期:2016年12月22日 * 描 述:Model实现类 */ public class RedBagRecOrSendImpl implements RedBagRecOrSendDao { private DataCallBack callBack; public RedBagRecOrSendImpl(DataCallBack callBack) { this.callBack = callBack; } @Override public void setBillDetail(Map<String, Object> map, String serviceName, int type) { CommonServerRequest request = new CommonServerRequest(); request.sendReuqest(map,serviceName,type); request.setOnDataLoadFinish(callBack); } }
765
0.720113
0.708861
30
22.700001
24.329885
86
false
false
0
0
0
0
0
0
0.466667
false
false
7
54c8e1bd0d41e01ed40bfbf49b3dd8d2f1e8aa21
17,918,603,602,742
c776901247b319a615e7c6ebecab40e5829c9ac6
/flow-demo/src/main/java/demo/entity/ModifyAccount.java
a1e34f30e6663f39d75c9a49a0611dcc8c5472f5
[]
no_license
YuanCoder/bekit-demo
https://github.com/YuanCoder/bekit-demo
90c4002aafa673ffecbaed7025ad3bbf6af0ef7c
427ec3813f256fcf010e1ba1ec3b7bf55ec9c8dd
refs/heads/master
2020-05-18T06:34:15.490000
2018-04-23T04:51:44
2018-04-23T04:51:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 作者:钟勋 (e-mail:zhongxunking@163.com) */ /* * 修订记录: * @author 钟勋 2017-04-08 01:13 创建 */ package demo.entity; import demo.enums.Direction; import demo.enums.ModifyAccountStatus; import demo.enums.ModifyAccountType; import demo.enums.TransferStatus; import javax.persistence.*; /** * 修改账务记录 */ @Entity @Table(indexes = {@Index(unique = true, columnList = "transferBizNo,transferStatus")}) public class ModifyAccount { @Id @GeneratedValue @Column private Long id; // 转账交易流水号 @Column(length = 20) private String transferBizNo; // 转行交易状态 @Column(length = 40) @Enumerated(EnumType.STRING) private TransferStatus transferStatus; // 类型 @Column(length = 40) @Enumerated(EnumType.STRING) private ModifyAccountType type; // 账号 @Column(length = 20) private String accountNo; // 方向 @Column(length = 40) @Enumerated(EnumType.STRING) private Direction direction; // 金额 @Column private Long amount; // 状态 @Column(length = 40) @Enumerated(EnumType.STRING) private ModifyAccountStatus status; // 调用账务系统的订单号 @Column(length = 40) private String refOrderNo; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTransferBizNo() { return transferBizNo; } public void setTransferBizNo(String transferBizNo) { this.transferBizNo = transferBizNo; } public TransferStatus getTransferStatus() { return transferStatus; } public void setTransferStatus(TransferStatus transferStatus) { this.transferStatus = transferStatus; } public ModifyAccountType getType() { return type; } public void setType(ModifyAccountType type) { this.type = type; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public ModifyAccountStatus getStatus() { return status; } public void setStatus(ModifyAccountStatus status) { this.status = status; } public String getRefOrderNo() { return refOrderNo; } public void setRefOrderNo(String refOrderNo) { this.refOrderNo = refOrderNo; } }
UTF-8
Java
2,749
java
ModifyAccount.java
Java
[ { "context": "/* \n * 作者:钟勋 (e-mail:zhongxunking@163.com)\n */\n\n/*\n * 修订记录:\n *", "end": 12, "score": 0.9994751811027527, "start": 10, "tag": "NAME", "value": "钟勋" }, { "context": "/* \n * 作者:钟勋 (e-mail:zhongxunking@163.com)\n */\n\n/*\n * 修订记录:\n * @author 钟勋 2017-04-08 01:13 ", "end": 41, "score": 0.9999237060546875, "start": 21, "tag": "EMAIL", "value": "zhongxunking@163.com" }, { "context": "zhongxunking@163.com)\n */\n\n/*\n * 修订记录:\n * @author 钟勋 2017-04-08 01:13 创建\n */\npackage demo.entity;\n\nimp", "end": 73, "score": 0.9989843368530273, "start": 71, "tag": "NAME", "value": "钟勋" } ]
null
[]
/* * 作者:钟勋 (e-mail:<EMAIL>) */ /* * 修订记录: * @author 钟勋 2017-04-08 01:13 创建 */ package demo.entity; import demo.enums.Direction; import demo.enums.ModifyAccountStatus; import demo.enums.ModifyAccountType; import demo.enums.TransferStatus; import javax.persistence.*; /** * 修改账务记录 */ @Entity @Table(indexes = {@Index(unique = true, columnList = "transferBizNo,transferStatus")}) public class ModifyAccount { @Id @GeneratedValue @Column private Long id; // 转账交易流水号 @Column(length = 20) private String transferBizNo; // 转行交易状态 @Column(length = 40) @Enumerated(EnumType.STRING) private TransferStatus transferStatus; // 类型 @Column(length = 40) @Enumerated(EnumType.STRING) private ModifyAccountType type; // 账号 @Column(length = 20) private String accountNo; // 方向 @Column(length = 40) @Enumerated(EnumType.STRING) private Direction direction; // 金额 @Column private Long amount; // 状态 @Column(length = 40) @Enumerated(EnumType.STRING) private ModifyAccountStatus status; // 调用账务系统的订单号 @Column(length = 40) private String refOrderNo; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTransferBizNo() { return transferBizNo; } public void setTransferBizNo(String transferBizNo) { this.transferBizNo = transferBizNo; } public TransferStatus getTransferStatus() { return transferStatus; } public void setTransferStatus(TransferStatus transferStatus) { this.transferStatus = transferStatus; } public ModifyAccountType getType() { return type; } public void setType(ModifyAccountType type) { this.type = type; } public String getAccountNo() { return accountNo; } public void setAccountNo(String accountNo) { this.accountNo = accountNo; } public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public ModifyAccountStatus getStatus() { return status; } public void setStatus(ModifyAccountStatus status) { this.status = status; } public String getRefOrderNo() { return refOrderNo; } public void setRefOrderNo(String refOrderNo) { this.refOrderNo = refOrderNo; } }
2,736
0.636295
0.625331
137
18.30657
17.418659
86
false
false
0
0
0
0
0
0
0.255474
false
false
7
010428aaf8fcb266d55a4640ed3defa1cc5c5c90
33,998,961,150,880
f534b6554965b5fbc3577dae25d2625c83326f5e
/riot_discovery/src/main/java/com/muugi/riot/discovery/main/contract/DiscoveryContract.java
ed39b88dd5de739649f007187291b404cc529f8e
[]
no_license
scauzhangpeng/RiotGame
https://github.com/scauzhangpeng/RiotGame
f44fb103df19754bfb599422b796a9d9e8f04dac
e968b1eeea62764d20f9461ed2a8c24dd78a579a
refs/heads/master
2021-01-15T13:18:55.613000
2019-04-24T15:34:41
2019-04-24T15:34:41
99,668,579
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.muugi.riot.discovery.main.contract; import com.muugi.riot.discovery.main.bean.Club; import com.muugi.riot.discovery.main.bean.DiscoveryMenu; import com.xyz.basiclib.mvp.BasePresenter; import com.xyz.basiclib.mvp.BaseView; import java.util.List; /** * Created by ZP on 2018/1/24. */ public interface DiscoveryContract { interface View extends BaseView { void showClubs(List<Club.ClubsBean> clubs); void showDiscoveryMenu(List<DiscoveryMenu> menu); } abstract class Presenter extends BasePresenter<View> { public abstract void getClubs(); public abstract void getDiscoveryMenu(); } }
UTF-8
Java
652
java
DiscoveryContract.java
Java
[ { "context": "seView;\n\nimport java.util.List;\n\n/**\n * Created by ZP on 2018/1/24.\n */\n\npublic interface DiscoveryCont", "end": 280, "score": 0.9986859560012817, "start": 278, "tag": "USERNAME", "value": "ZP" } ]
null
[]
package com.muugi.riot.discovery.main.contract; import com.muugi.riot.discovery.main.bean.Club; import com.muugi.riot.discovery.main.bean.DiscoveryMenu; import com.xyz.basiclib.mvp.BasePresenter; import com.xyz.basiclib.mvp.BaseView; import java.util.List; /** * Created by ZP on 2018/1/24. */ public interface DiscoveryContract { interface View extends BaseView { void showClubs(List<Club.ClubsBean> clubs); void showDiscoveryMenu(List<DiscoveryMenu> menu); } abstract class Presenter extends BasePresenter<View> { public abstract void getClubs(); public abstract void getDiscoveryMenu(); } }
652
0.728528
0.717791
27
23.148148
22.323719
58
false
false
0
0
0
0
0
0
0.37037
false
false
7