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
c45bba771c8b28e42da3643ac4a64b61a347740d
37,529,424,264,063
429368a49704128e664a625de101251f8be1425c
/src/com/sb/ci/utility/POJOFactory.java
eb70f8b47d7efd14a06e4b84c9a899c138e447b8
[ "MIT" ]
permissive
Obbay2/ThunderstormCI
https://github.com/Obbay2/ThunderstormCI
7ce4ed9dec959ca2af45ee406e366d4c2350e0a6
5f30ce4fd14bfed3902ee91ed0803845acbdd97d
refs/heads/master
2021-01-15T09:15:17.063000
2016-04-17T07:30:45
2016-04-17T07:30:45
56,412,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sb.ci.utility; import java.util.HashMap; import java.util.Map; import com.sb.ci.exception.CIException; import com.sb.ci.model.BasePOJO; import com.sb.ci.model.Competition; import com.sb.ci.model.Game; import com.sb.ci.model.Robot; import com.sb.ci.model.RobotDetails; import com.sb.ci.model.Round; import com.sb.ci.model.Score; import com.sb.ci.model.Team; public class POJOFactory { private static Map<String, Class<? extends BasePOJO>> classes = new HashMap<String, Class<? extends BasePOJO>>(); static { register(Team.TABLE_NAME.toUpperCase(), Team.class); register(Game.TABLE_NAME.toUpperCase(), Game.class); register(Competition.TABLE_NAME.toUpperCase(), Competition.class); register(Robot.TABLE_NAME.toUpperCase(), Robot.class); register(RobotDetails.TABLE_NAME.toUpperCase(), RobotDetails.class); register(Score.TABLE_NAME.toUpperCase(), Score.class); register(Round.TABLE_NAME.toUpperCase(), Round.class); } public static void register(String tableName, Class<? extends BasePOJO> pojoClass) { classes.put(tableName.toUpperCase(), pojoClass); } public static BasePOJO getInstance(String tableName) { BasePOJO result = null; Class<? extends BasePOJO> clazz = classes.get(tableName.toUpperCase()); try { result = clazz.newInstance(); } catch (Exception e) { throw new CIException(e); } return result; } }
UTF-8
Java
1,378
java
POJOFactory.java
Java
[]
null
[]
package com.sb.ci.utility; import java.util.HashMap; import java.util.Map; import com.sb.ci.exception.CIException; import com.sb.ci.model.BasePOJO; import com.sb.ci.model.Competition; import com.sb.ci.model.Game; import com.sb.ci.model.Robot; import com.sb.ci.model.RobotDetails; import com.sb.ci.model.Round; import com.sb.ci.model.Score; import com.sb.ci.model.Team; public class POJOFactory { private static Map<String, Class<? extends BasePOJO>> classes = new HashMap<String, Class<? extends BasePOJO>>(); static { register(Team.TABLE_NAME.toUpperCase(), Team.class); register(Game.TABLE_NAME.toUpperCase(), Game.class); register(Competition.TABLE_NAME.toUpperCase(), Competition.class); register(Robot.TABLE_NAME.toUpperCase(), Robot.class); register(RobotDetails.TABLE_NAME.toUpperCase(), RobotDetails.class); register(Score.TABLE_NAME.toUpperCase(), Score.class); register(Round.TABLE_NAME.toUpperCase(), Round.class); } public static void register(String tableName, Class<? extends BasePOJO> pojoClass) { classes.put(tableName.toUpperCase(), pojoClass); } public static BasePOJO getInstance(String tableName) { BasePOJO result = null; Class<? extends BasePOJO> clazz = classes.get(tableName.toUpperCase()); try { result = clazz.newInstance(); } catch (Exception e) { throw new CIException(e); } return result; } }
1,378
0.743106
0.743106
49
27.12245
25.317278
114
false
false
0
0
0
0
0
0
1.673469
false
false
14
ae39d0275e2c77552d2c0eda0ab89d4f6366a7ea
39,685,497,820,989
0d9e7a351710dee26e25670cb3bc570b04428458
/src/InventoryGUI/LVL.java
56718213d8b25b3d9b3feb33194b602161e13690
[]
no_license
ChristianCornelis/InventoryProgram
https://github.com/ChristianCornelis/InventoryProgram
6a818c749434237a19f845fd314dd489abaaa547
d142b8a290b0f815b988d26a4c1394c071ac8329
refs/heads/master
2021-01-12T05:31:23.428000
2017-01-16T22:32:25
2017-01-16T22:32:25
77,947,938
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 InventoryGUI; import InventoryGUI.Exceptions.NegativeQuantityException; /** * * @author Christian Cornelis */ public class LVL extends Item{ private String length; private String width; /** * Constructor for an LVL item object * @param _type represents the type (LVL) * @param _quantity represents the quantity * @param _length represents the length * @param _width represents the width */ public LVL (String _type, int _quantity, String _length, String _width) throws NegativeQuantityException { super (_type, _quantity); this.length = _length; this.width = _width; } //accessor methods /** * Accessor method to get length * @return represents the length */ public String getLength() { return this.length; } /** * Accessor method to get the width * @return represents the width */ public String getWidth() { return this.width; } //mutator methods /** * Mutator method for length * @param _length represents the length to update */ public void setLength(String _length) { this.length = _length; } /** * Mutator method for width * @param _width represents the width to update */ public void setWidth (String _width) { this.width = _width; } /** * toString method * @return returns a string containing all components of the object */ @Override public String toString() { return(super.toString() + "\nLength: " + this.getLength() + "\nWidth: " + this.getWidth() + "\n"); } /** * Equals method to see if an object is equal to this LVL object * @param otherObject represents the object to compare * @return represents whether the object is equal to the LVL object */ @Override public boolean equals(Object otherObject) { if (otherObject == null) return false; else if (getClass() != otherObject.getClass()) return false; else { LVL other = (LVL)otherObject; //checking if all aspects of the other are the same return (this.getType().equals(other.getType()) && this.getQuantity() == (other.getQuantity()) && this.getWidth().equals(other.getWidth()) && this.getLength().equals(other.getLength())); } } /** * Data dump to be used to output data to a file * @return returns a string containing LVL info formatted to be printed to a file */ @Override public String dataDump() { return("type = \"lvl\"" + "\r\n" + super.dataDump() + "length = \"" + this.getLength() + "\"" + "\r\n" + "width = \"" + this.getWidth() + "\"" + "\r\n"); } }
UTF-8
Java
3,043
java
LVL.java
Java
[ { "context": "ions.NegativeQuantityException;\n\n/**\n *\n * @author Christian Cornelis\n */\npublic class LVL extends Item{\n private St", "end": 303, "score": 0.9998113512992859, "start": 285, "tag": "NAME", "value": "Christian Cornelis" } ]
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 InventoryGUI; import InventoryGUI.Exceptions.NegativeQuantityException; /** * * @author <NAME> */ public class LVL extends Item{ private String length; private String width; /** * Constructor for an LVL item object * @param _type represents the type (LVL) * @param _quantity represents the quantity * @param _length represents the length * @param _width represents the width */ public LVL (String _type, int _quantity, String _length, String _width) throws NegativeQuantityException { super (_type, _quantity); this.length = _length; this.width = _width; } //accessor methods /** * Accessor method to get length * @return represents the length */ public String getLength() { return this.length; } /** * Accessor method to get the width * @return represents the width */ public String getWidth() { return this.width; } //mutator methods /** * Mutator method for length * @param _length represents the length to update */ public void setLength(String _length) { this.length = _length; } /** * Mutator method for width * @param _width represents the width to update */ public void setWidth (String _width) { this.width = _width; } /** * toString method * @return returns a string containing all components of the object */ @Override public String toString() { return(super.toString() + "\nLength: " + this.getLength() + "\nWidth: " + this.getWidth() + "\n"); } /** * Equals method to see if an object is equal to this LVL object * @param otherObject represents the object to compare * @return represents whether the object is equal to the LVL object */ @Override public boolean equals(Object otherObject) { if (otherObject == null) return false; else if (getClass() != otherObject.getClass()) return false; else { LVL other = (LVL)otherObject; //checking if all aspects of the other are the same return (this.getType().equals(other.getType()) && this.getQuantity() == (other.getQuantity()) && this.getWidth().equals(other.getWidth()) && this.getLength().equals(other.getLength())); } } /** * Data dump to be used to output data to a file * @return returns a string containing LVL info formatted to be printed to a file */ @Override public String dataDump() { return("type = \"lvl\"" + "\r\n" + super.dataDump() + "length = \"" + this.getLength() + "\"" + "\r\n" + "width = \"" + this.getWidth() + "\"" + "\r\n"); } }
3,031
0.588564
0.588564
111
26.414415
31.043842
197
false
false
0
0
0
0
0
0
0.216216
false
false
14
c7cd99ea10f8239710bf9d8273cf8e3b11c44e2e
35,141,422,471,040
73c621d368029767afa41e1e3a8f08516db637ed
/teretanaTamara/src/main/java/com/example/teretanaTamara/domain/dto/MemberDto.java
f30b27eb8d2fc4713f0d20da54b31553d0674109
[]
no_license
tackica86/Gym
https://github.com/tackica86/Gym
5b25a386e92236d7371d9892d984abf2297a1628
43fb99ea3407ed9d299c0ff27f4025a4abb3b036
refs/heads/master
2020-06-09T20:38:30.640000
2019-07-02T13:32:58
2019-07-02T13:32:58
193,502,088
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.teretanaTamara.domain.dto; import com.example.teretanaTamara.domain.Coupon; import com.example.teretanaTamara.domain.Subscription; public class MemberDto { private String name; private String surname; private String email; private Subscription subscription; private Coupon coupon; public MemberDto() { super(); } public MemberDto(String name, String surname, String email, Subscription subscription, Coupon coupon) { super(); this.name = name; this.surname = surname; this.email = email; this.subscription = subscription; this.coupon = coupon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Subscription getSubscription() { return subscription; } public void setSubscription(Subscription subscription) { this.subscription = subscription; } public Coupon getCoupon() { return coupon; } public void setCoupon(Coupon coupon) { this.coupon = coupon; } @Override public String toString() { return "MemberDto [name=" + name + ", surname=" + surname + ", email=" + email + ", subscription=" + subscription + ", coupon=" + coupon + "]"; } }
UTF-8
Java
1,421
java
MemberDto.java
Java
[]
null
[]
package com.example.teretanaTamara.domain.dto; import com.example.teretanaTamara.domain.Coupon; import com.example.teretanaTamara.domain.Subscription; public class MemberDto { private String name; private String surname; private String email; private Subscription subscription; private Coupon coupon; public MemberDto() { super(); } public MemberDto(String name, String surname, String email, Subscription subscription, Coupon coupon) { super(); this.name = name; this.surname = surname; this.email = email; this.subscription = subscription; this.coupon = coupon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Subscription getSubscription() { return subscription; } public void setSubscription(Subscription subscription) { this.subscription = subscription; } public Coupon getCoupon() { return coupon; } public void setCoupon(Coupon coupon) { this.coupon = coupon; } @Override public String toString() { return "MemberDto [name=" + name + ", surname=" + surname + ", email=" + email + ", subscription=" + subscription + ", coupon=" + coupon + "]"; } }
1,421
0.70373
0.70373
74
18.202703
21.048195
104
false
false
0
0
0
0
0
0
1.486486
false
false
14
545ab177ca80afeb500ecc34419132d745d3a641
36,936,718,784,699
5039b38b4d97ab669a98c950ba7745ae1c266ef4
/src/main/java/memo/communication/strategy/ShopItemNotificationStrategy.java
4134ca13d2ceee2333b0ebde4aca4f3adbc4b4f6
[]
no_license
lehoffma/memo
https://github.com/lehoffma/memo
7afc0cb6555225a1850abb6b8bfd8a740a46dabb
0723348e3f76738872c0cd333cf7e89bcf474df5
refs/heads/develop
2023-03-06T23:10:08.113000
2022-07-26T14:57:00
2022-07-26T14:57:00
79,556,593
2
1
null
false
2023-03-03T07:53:32
2017-01-20T12:18:37
2021-12-24T07:54:51
2023-03-03T07:53:31
24,563
1
1
66
TypeScript
false
false
package memo.communication.strategy; import memo.communication.NotificationRepository; import memo.communication.model.Notification; import memo.communication.model.NotificationType; import memo.model.*; import memo.util.JsonHelper; import memo.util.MapBuilder; import memo.util.Util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.annotation.PreDestroy; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.BiPredicate; import java.util.function.Function; @Named @ApplicationScoped public class ShopItemNotificationStrategy extends BaseNotificationStrategy<ShopItem> { private static final Logger logger = LogManager.getLogger(ShopItemNotificationStrategy.class); private NotificationRepository notificationRepository; private ExecutorService executorService = Executors.newFixedThreadPool(1); public ShopItemNotificationStrategy() { super(); } @Inject public ShopItemNotificationStrategy(NotificationRepository notificationRepository) { super(); this.notificationRepository = notificationRepository; } @PreDestroy public void onDestroy() { this.executorService.shutdownNow(); } private void sendCreationEmails(ShopItem item) { if (item != null) { List<User> responsibleUsers = item.getAuthor(); String dataAsString = JsonHelper.toString(new MapBuilder<String, Object>() .buildPut("itemId", item.getId())); responsibleUsers.forEach(user -> notificationRepository.save( new Notification() .setUser(user) .setNotificationType(NotificationType.RESPONSIBLE_USER) .setData(dataAsString) )); } } public void post(ShopItem item) { this.async(() -> this.sendCreationEmails(item), executorService); } private static class ChangelogEntry { private String previous; private String current; public String getPrevious() { return previous; } public ChangelogEntry setPrevious(String previous) { this.previous = previous; return this; } public String getCurrent() { return current; } public ChangelogEntry setCurrent(String current) { this.current = current; return this; } } private <T> Map<String, ChangelogEntry> addToChangelog(Map<String, ChangelogEntry> changes, ShopItem current, ShopItem previous, String key, Function<ShopItem, T> getValue, BiPredicate<T, T> isEqual) { return this.addToChangelog(changes, current, previous, key, getValue, isEqual, Object::toString); } private <T> Map<String, ChangelogEntry> addToChangelog(Map<String, ChangelogEntry> changes, ShopItem current, ShopItem previous, String key, Function<ShopItem, T> getValue, BiPredicate<T, T> isEqual, Function<T, String> toString ) { T currentValue = getValue.apply(current); T previousValue = getValue.apply(previous); if (!isEqual.test(currentValue, previousValue)) { changes.put(key, new ChangelogEntry() .setPrevious(toString.apply(previousValue)) .setCurrent(toString.apply(currentValue)) ); } return changes; } private Map<String, ChangelogEntry> getChangelog(ShopItem current, ShopItem previous) { //todo this might be a bit much for the database, especially if the description is long and there are a lot of participants //title, description, price, datetime, capacity, route, vehicle, paymentMethods, paymentLimit Map<String, ChangelogEntry> changes = new HashMap<>(); this.addToChangelog(changes, current, previous, "title", ShopItem::getTitle, String::equalsIgnoreCase); this.addToChangelog(changes, current, previous, "description", ShopItem::getDescription, String::equalsIgnoreCase); return changes; } private void sendObjectHasChangedNotifications(ShopItem changedItem) { //notify participants of changes List<OrderedItem> orders = new ArrayList<>(changedItem.getOrders()); //todo save "changelog", i.e. which attributes have been changed? String changelogDataAsString = JsonHelper.toString(new MapBuilder<String, Object>() .buildPut("itemId", changedItem.getId()) // .buildPut("changes", this.getChangelog(changedItem, previous)) ); orders.stream() .map(OrderedItem::getOrder) .map(Order::getUser) .distinct() .forEach(participant -> notificationRepository.save( new Notification() .setUser(participant) .setNotificationType(NotificationType.OBJECT_HAS_CHANGED) .setData(changelogDataAsString) )); } private void notifyNewlyAddedUsers(List<User> newUsers, List<User> previousUsers, NotificationType notificationType, String itemDataAsString) { //notify newly added users newUsers.stream() //only send mails to newly added users .filter(user -> previousUsers.stream().noneMatch(it -> it.getId().equals(user.getId()))) .forEach(user -> notificationRepository.save( new Notification() .setUser(user) .setNotificationType(notificationType) .setData(itemDataAsString) )); } private void notifyUsersAboutEventCapacityChange(ShopItem changedItem, ShopItem previous, String itemDataAsString) { //only if capacity has been increased if (changedItem.getCapacity() <= previous.getCapacity()) { return; } //get distinct users on waiting list changedItem.getWaitingList().stream() .map(WaitingListEntry::getUser) .filter(Util.distinctByKey(User::getId)) //save notification for each one .forEach(user -> notificationRepository.save( new Notification() .setUser(user) .setNotificationType(NotificationType.WAITING_LIST_CAPACITY_CHANGE) .setData(itemDataAsString) )); } protected void sendUpdateEmails(ShopItem changedItem, ShopItem previous) { if (changedItem == null) { return; } this.sendObjectHasChangedNotifications(changedItem); String itemDataAsString = JsonHelper.toString(new MapBuilder<String, Object>() .buildPut("itemId", changedItem.getId())); this.notifyNewlyAddedUsers( changedItem.getAuthor(), previous.getAuthor(), NotificationType.RESPONSIBLE_USER, itemDataAsString ); this.notifyNewlyAddedUsers( changedItem.getReportWriters(), previous.getReportWriters(), NotificationType.MARKED_AS_REPORT_WRITER, itemDataAsString ); this.notifyUsersAboutEventCapacityChange(changedItem, previous, itemDataAsString); } public void put(ShopItem item, ShopItem previous) { this.async(() -> this.sendUpdateEmails(item, previous), executorService); } }
UTF-8
Java
8,566
java
ShopItemNotificationStrategy.java
Java
[]
null
[]
package memo.communication.strategy; import memo.communication.NotificationRepository; import memo.communication.model.Notification; import memo.communication.model.NotificationType; import memo.model.*; import memo.util.JsonHelper; import memo.util.MapBuilder; import memo.util.Util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.annotation.PreDestroy; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.inject.Named; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.BiPredicate; import java.util.function.Function; @Named @ApplicationScoped public class ShopItemNotificationStrategy extends BaseNotificationStrategy<ShopItem> { private static final Logger logger = LogManager.getLogger(ShopItemNotificationStrategy.class); private NotificationRepository notificationRepository; private ExecutorService executorService = Executors.newFixedThreadPool(1); public ShopItemNotificationStrategy() { super(); } @Inject public ShopItemNotificationStrategy(NotificationRepository notificationRepository) { super(); this.notificationRepository = notificationRepository; } @PreDestroy public void onDestroy() { this.executorService.shutdownNow(); } private void sendCreationEmails(ShopItem item) { if (item != null) { List<User> responsibleUsers = item.getAuthor(); String dataAsString = JsonHelper.toString(new MapBuilder<String, Object>() .buildPut("itemId", item.getId())); responsibleUsers.forEach(user -> notificationRepository.save( new Notification() .setUser(user) .setNotificationType(NotificationType.RESPONSIBLE_USER) .setData(dataAsString) )); } } public void post(ShopItem item) { this.async(() -> this.sendCreationEmails(item), executorService); } private static class ChangelogEntry { private String previous; private String current; public String getPrevious() { return previous; } public ChangelogEntry setPrevious(String previous) { this.previous = previous; return this; } public String getCurrent() { return current; } public ChangelogEntry setCurrent(String current) { this.current = current; return this; } } private <T> Map<String, ChangelogEntry> addToChangelog(Map<String, ChangelogEntry> changes, ShopItem current, ShopItem previous, String key, Function<ShopItem, T> getValue, BiPredicate<T, T> isEqual) { return this.addToChangelog(changes, current, previous, key, getValue, isEqual, Object::toString); } private <T> Map<String, ChangelogEntry> addToChangelog(Map<String, ChangelogEntry> changes, ShopItem current, ShopItem previous, String key, Function<ShopItem, T> getValue, BiPredicate<T, T> isEqual, Function<T, String> toString ) { T currentValue = getValue.apply(current); T previousValue = getValue.apply(previous); if (!isEqual.test(currentValue, previousValue)) { changes.put(key, new ChangelogEntry() .setPrevious(toString.apply(previousValue)) .setCurrent(toString.apply(currentValue)) ); } return changes; } private Map<String, ChangelogEntry> getChangelog(ShopItem current, ShopItem previous) { //todo this might be a bit much for the database, especially if the description is long and there are a lot of participants //title, description, price, datetime, capacity, route, vehicle, paymentMethods, paymentLimit Map<String, ChangelogEntry> changes = new HashMap<>(); this.addToChangelog(changes, current, previous, "title", ShopItem::getTitle, String::equalsIgnoreCase); this.addToChangelog(changes, current, previous, "description", ShopItem::getDescription, String::equalsIgnoreCase); return changes; } private void sendObjectHasChangedNotifications(ShopItem changedItem) { //notify participants of changes List<OrderedItem> orders = new ArrayList<>(changedItem.getOrders()); //todo save "changelog", i.e. which attributes have been changed? String changelogDataAsString = JsonHelper.toString(new MapBuilder<String, Object>() .buildPut("itemId", changedItem.getId()) // .buildPut("changes", this.getChangelog(changedItem, previous)) ); orders.stream() .map(OrderedItem::getOrder) .map(Order::getUser) .distinct() .forEach(participant -> notificationRepository.save( new Notification() .setUser(participant) .setNotificationType(NotificationType.OBJECT_HAS_CHANGED) .setData(changelogDataAsString) )); } private void notifyNewlyAddedUsers(List<User> newUsers, List<User> previousUsers, NotificationType notificationType, String itemDataAsString) { //notify newly added users newUsers.stream() //only send mails to newly added users .filter(user -> previousUsers.stream().noneMatch(it -> it.getId().equals(user.getId()))) .forEach(user -> notificationRepository.save( new Notification() .setUser(user) .setNotificationType(notificationType) .setData(itemDataAsString) )); } private void notifyUsersAboutEventCapacityChange(ShopItem changedItem, ShopItem previous, String itemDataAsString) { //only if capacity has been increased if (changedItem.getCapacity() <= previous.getCapacity()) { return; } //get distinct users on waiting list changedItem.getWaitingList().stream() .map(WaitingListEntry::getUser) .filter(Util.distinctByKey(User::getId)) //save notification for each one .forEach(user -> notificationRepository.save( new Notification() .setUser(user) .setNotificationType(NotificationType.WAITING_LIST_CAPACITY_CHANGE) .setData(itemDataAsString) )); } protected void sendUpdateEmails(ShopItem changedItem, ShopItem previous) { if (changedItem == null) { return; } this.sendObjectHasChangedNotifications(changedItem); String itemDataAsString = JsonHelper.toString(new MapBuilder<String, Object>() .buildPut("itemId", changedItem.getId())); this.notifyNewlyAddedUsers( changedItem.getAuthor(), previous.getAuthor(), NotificationType.RESPONSIBLE_USER, itemDataAsString ); this.notifyNewlyAddedUsers( changedItem.getReportWriters(), previous.getReportWriters(), NotificationType.MARKED_AS_REPORT_WRITER, itemDataAsString ); this.notifyUsersAboutEventCapacityChange(changedItem, previous, itemDataAsString); } public void put(ShopItem item, ShopItem previous) { this.async(() -> this.sendUpdateEmails(item, previous), executorService); } }
8,566
0.586271
0.585921
216
38.657406
31.59441
131
false
false
0
0
0
0
0
0
0.648148
false
false
14
426a411e80a0d48adea6b42d2d984b55ca99a88e
37,125,697,343,221
d1f72a8733e14f18822b6576dfd7f80bffca5727
/src/main/java/com/gdn/database/GetBotInformation.java
2e230ce6624ad8180f0f843854fbf8608955e472
[]
no_license
avinasht24/GetInformation
https://github.com/avinasht24/GetInformation
271c45190b889b09da1de33bb2da81ebfbf6a640
e0c83432733216c225e571c02b62d724d765c492
refs/heads/master
2020-03-24T03:45:25.824000
2018-07-26T11:30:06
2018-07-26T11:30:06
142,431,887
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gdn.database; import java.awt.List; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Properties; import com.gdn.qabot.controller.QaBotController; /** * Created by avinash.t */ public class GetBotInformation extends QaBotController{ public static Connection apiconn =null; public String getApiInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp1="<a href=\""; String temp2="\">Click Here for "+bot_keyword+" API URL<a/>"; outputUrl=temp1.concat(outputUrl).concat(temp2); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getCenterInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp1="<a href=\""; String temp2="\">Click Here for "+bot_keyword+" Center URL<a/>"; outputUrl=temp1.concat(outputUrl).concat(temp2); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getProductInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp1="<a href=\""; String temp2="\">Click Here for "+bot_keyword+" Product URL<a/>"; outputUrl=temp1.concat(outputUrl).concat(temp2); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getUserInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp2="Username & Password details for "+bot_keyword+" is :"; outputUrl=temp2.concat(outputUrl); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getPromoInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp2="Public Voucher Code :"; outputUrl=temp2.concat(outputUrl); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public ArrayList<ArrayList<String>> getEnvironment() { //String [][] environmentList = null; ArrayList<ArrayList<String>> environmentList= new ArrayList<ArrayList<String>>(); ArrayList<String> environmentKeyList= new ArrayList<String>(); ArrayList<String> environmentNameList= new ArrayList<String>(); connect(); String sql = "select environment,environment_name from bot_environment"; String environment=null; String environment_name=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); int i=0; while (rs.next()) { int j=0; environment=rs.getString("environment"); environment_name=rs.getString("environment_name"); environmentKeyList.add(environment); environmentNameList.add(environment_name); i++; } environmentList.add(environmentKeyList); environmentList.add(environmentNameList); APP_LOGS.debug("EnvironementList"+environmentList); APP_LOGS.debug("Env List:"+environmentList); rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); e.getMessage(); } return environmentList; } public void connect() { try { // db parameters try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String url = "jdbc:sqlite:/Users/avinash.t/Avinash/botdb/qabot.db"; // create a connection to the database apiconn= DriverManager.getConnection(url); APP_LOGS.debug("Connection: " + apiconn); if (apiconn!= null) { DatabaseMetaData meta = apiconn.getMetaData(); APP_LOGS.debug("The driver name is " + meta.getDriverName()); } APP_LOGS.debug("Connection to SQLite has been established."); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); } } }
UTF-8
Java
8,467
java
GetBotInformation.java
Java
[ { "context": "abot.controller.QaBotController;\n/**\n * Created by avinash.t\n */\npublic class GetBotInformation extends QaBotC", "end": 447, "score": 0.9984405636787415, "start": 438, "tag": "USERNAME", "value": "avinash.t" } ]
null
[]
package com.gdn.database; import java.awt.List; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Properties; import com.gdn.qabot.controller.QaBotController; /** * Created by avinash.t */ public class GetBotInformation extends QaBotController{ public static Connection apiconn =null; public String getApiInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp1="<a href=\""; String temp2="\">Click Here for "+bot_keyword+" API URL<a/>"; outputUrl=temp1.concat(outputUrl).concat(temp2); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getCenterInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp1="<a href=\""; String temp2="\">Click Here for "+bot_keyword+" Center URL<a/>"; outputUrl=temp1.concat(outputUrl).concat(temp2); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getProductInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp1="<a href=\""; String temp2="\">Click Here for "+bot_keyword+" Product URL<a/>"; outputUrl=temp1.concat(outputUrl).concat(temp2); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getUserInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp2="Username & Password details for "+bot_keyword+" is :"; outputUrl=temp2.concat(outputUrl); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public String getPromoInformation(String environment, String source_type, String bot_keyword) { connect(); String sql = "select url from bot_config where environment='"+environment+"' and source_type='"+source_type+"' and bot_keyword='"+bot_keyword+"' "; String outputUrl=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); // loop through the result set while (rs.next()) { outputUrl=rs.getString("url"); String temp2="Public Voucher Code :"; outputUrl=temp2.concat(outputUrl); APP_LOGS.debug(outputUrl); } rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); outputUrl=e.getMessage(); } return outputUrl; } public ArrayList<ArrayList<String>> getEnvironment() { //String [][] environmentList = null; ArrayList<ArrayList<String>> environmentList= new ArrayList<ArrayList<String>>(); ArrayList<String> environmentKeyList= new ArrayList<String>(); ArrayList<String> environmentNameList= new ArrayList<String>(); connect(); String sql = "select environment,environment_name from bot_environment"; String environment=null; String environment_name=null; try { Statement stmt= apiconn.createStatement(); APP_LOGS.debug("Statement:"+stmt); APP_LOGS.debug("SQL:"+sql); ResultSet rs = stmt.executeQuery(sql); int i=0; while (rs.next()) { int j=0; environment=rs.getString("environment"); environment_name=rs.getString("environment_name"); environmentKeyList.add(environment); environmentNameList.add(environment_name); i++; } environmentList.add(environmentKeyList); environmentList.add(environmentNameList); APP_LOGS.debug("EnvironementList"+environmentList); APP_LOGS.debug("Env List:"+environmentList); rs.close(); stmt.close(); apiconn.close(); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); e.getMessage(); } return environmentList; } public void connect() { try { // db parameters try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String url = "jdbc:sqlite:/Users/avinash.t/Avinash/botdb/qabot.db"; // create a connection to the database apiconn= DriverManager.getConnection(url); APP_LOGS.debug("Connection: " + apiconn); if (apiconn!= null) { DatabaseMetaData meta = apiconn.getMetaData(); APP_LOGS.debug("The driver name is " + meta.getDriverName()); } APP_LOGS.debug("Connection to SQLite has been established."); } catch (SQLException e) { APP_LOGS.debug(e.getMessage()); } } }
8,467
0.555451
0.553325
278
29.456835
28.001989
149
false
false
0
0
0
0
0
0
1.172662
false
false
14
a06f6a64829faaaee9af6cdacb63abcb969118ec
9,912,784,536,315
251ed4d232df69e9e5a6a039b086d9475658b63d
/app/src/main/java/com/weather/app/testapp/ui/utils/ConvertToModel.java
9c67e71d63cd42bb3dd29754c3c692b242ea132b
[]
no_license
stefanionescu/WeatherApp
https://github.com/stefanionescu/WeatherApp
b663387af13358f15361e4499568d08e60c7efdd
34f7774f7056b0ea8c1db698e1a633b3e23552b3
refs/heads/master
2021-01-20T10:53:37.546000
2017-08-30T21:14:54
2017-08-30T21:14:54
101,652,794
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.weather.app.testapp.ui.utils; import com.weather.app.testapp.domain.model.Forecast; import com.weather.app.testapp.ui.viewmodel.ForecastViewModel; import com.weather.app.testapp.ui.viewmodel.Model; import java.util.ArrayList; import java.util.List; public class ConvertToModel { public List<Model> convertToModelViewList(List<Forecast> londonForecasts) { List<Model> modelList = new ArrayList<Model>(); for (Forecast forecast : londonForecasts) { modelList.add(new ForecastViewModel(forecast)); } return modelList; } }
UTF-8
Java
593
java
ConvertToModel.java
Java
[]
null
[]
package com.weather.app.testapp.ui.utils; import com.weather.app.testapp.domain.model.Forecast; import com.weather.app.testapp.ui.viewmodel.ForecastViewModel; import com.weather.app.testapp.ui.viewmodel.Model; import java.util.ArrayList; import java.util.List; public class ConvertToModel { public List<Model> convertToModelViewList(List<Forecast> londonForecasts) { List<Model> modelList = new ArrayList<Model>(); for (Forecast forecast : londonForecasts) { modelList.add(new ForecastViewModel(forecast)); } return modelList; } }
593
0.72344
0.72344
25
22.719999
25.348009
79
false
false
0
0
0
0
0
0
0.36
false
false
14
33659d6d8d513f8ffaacef7fd27a71945530defd
11,321,533,807,498
ee708a3de04965a715c9432db65c95d2aff993f3
/hk-emi/hk-emi-core/src/main/java/com/hk/emi/core/repository/CityRepository.java
c09785f029e9a612802895031aa003322a38bfed
[]
no_license
huankai/hk-modules
https://github.com/huankai/hk-modules
5da1bd58acd0f2d07acfe5bd2c025250ef061650
9fe3a2e98cf650a00a785ea56431c8710240a041
refs/heads/master
2021-09-10T22:55:54.535000
2018-04-03T16:01:09
2018-04-03T16:01:09
114,425,871
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.hk.emi.core.repository; import com.hk.core.repository.StringRepository; import com.hk.emi.core.domain.City; import java.util.List; /** * @author huangkai */ public interface CityRepository extends StringRepository<City> { /** * 查询下级 * * @param parentId * @return */ List<City> findByParentId(String parentId); }
UTF-8
Java
405
java
CityRepository.java
Java
[ { "context": "City;\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n * @author huangkai\r\n */\r\npublic interface CityRepository extends Str", "end": 191, "score": 0.999168336391449, "start": 183, "tag": "USERNAME", "value": "huangkai" } ]
null
[]
/** * */ package com.hk.emi.core.repository; import com.hk.core.repository.StringRepository; import com.hk.emi.core.domain.City; import java.util.List; /** * @author huangkai */ public interface CityRepository extends StringRepository<City> { /** * 查询下级 * * @param parentId * @return */ List<City> findByParentId(String parentId); }
405
0.617128
0.617128
23
15.26087
17.971518
64
false
false
0
0
0
0
0
0
0.217391
false
false
14
c37c4e615855a8a3a6d6176574e5939eadf2d694
2,783,138,825,661
b29f0e8bf21fd25d8af16111e53a961b8a392ab1
/src/f3.java
4ce4589b916b0e0bb68f62dd99894be318ba5dc2
[]
no_license
sambhav8154/Online-Shopping
https://github.com/sambhav8154/Online-Shopping
18c89eecbcdede0487c47b2fa74a5cdd06ebdf17
f6315fb6a3a5ef52acf6af1126f18d6810227dc5
refs/heads/master
2020-04-07T13:53:54.904000
2018-11-20T17:27:42
2018-11-20T17:27:42
158,426,364
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Toolkit; /* * 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. */ /** * * @author hp */ public class f3 extends javax.swing.JFrame { /** * Creates new form f3 */ public f3() { initComponents(); setIcon(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Online Shopping System"); setMinimumSize(new java.awt.Dimension(720, 470)); getContentPane().setLayout(null); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/f3.jpeg"))); // NOI18N getContentPane().add(jLabel1); jLabel1.setBounds(25, 11, 193, 358); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("BUY"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(323, 328, 61, 25); jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton2.setText("Back"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(585, 328, 65, 25); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("Rs 17,990"); getContentPane().add(jLabel2); jLabel2.setBounds(323, 279, 70, 17); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Highlights"); getContentPane().add(jLabel3); jLabel3.setBounds(293, 30, 78, 22); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setText("6 GB RAM | 64 GB ROM | Expandable Upto 256 GB"); getContentPane().add(jLabel4); jLabel4.setBounds(293, 70, 312, 15); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("6 inch Full HD Display"); getContentPane().add(jLabel5); jLabel5.setBounds(293, 103, 130, 15); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setText("16MP Rear Camera | 16MP + 8MP Dual Front Camera"); getContentPane().add(jLabel6); jLabel6.setBounds(293, 136, 328, 15); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel7.setText("4000 mAh Battery"); getContentPane().add(jLabel7); jLabel7.setBounds(293, 169, 114, 15); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel8.setText("Front-mounted Fingerprint Reader"); getContentPane().add(jLabel8); jLabel8.setBounds(293, 202, 212, 15); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel9.setText("Qualcomm MSM8976 Pro Snapdragon 653 octa-core Processor"); getContentPane().add(jLabel9); jLabel9.setBounds(293, 235, 386, 14); jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bg.jpg"))); // NOI18N getContentPane().add(jLabel10); jLabel10.setBounds(-30, -30, 770, 540); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked // TODO add your handling code here: new buy().setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton1MouseClicked private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked // TODO add your handling code here: new oppo().setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton2MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new f3().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; // End of variables declaration//GEN-END:variables private void setIcon() { setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("mi.jpg"))); //To change body of generated methods, choose Tools | Templates. } }
UTF-8
Java
7,513
java
f3.java
Java
[ { "context": "the template in the editor.\n */\n\n/**\n *\n * @author hp\n */\npublic class f3 extends javax.swing.JFrame {\n", "end": 233, "score": 0.9988590478897095, "start": 231, "tag": "USERNAME", "value": "hp" } ]
null
[]
import java.awt.Toolkit; /* * 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. */ /** * * @author hp */ public class f3 extends javax.swing.JFrame { /** * Creates new form f3 */ public f3() { initComponents(); setIcon(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Online Shopping System"); setMinimumSize(new java.awt.Dimension(720, 470)); getContentPane().setLayout(null); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/f3.jpeg"))); // NOI18N getContentPane().add(jLabel1); jLabel1.setBounds(25, 11, 193, 358); jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton1.setText("BUY"); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(323, 328, 61, 25); jButton2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jButton2.setText("Back"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(585, 328, 65, 25); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel2.setText("Rs 17,990"); getContentPane().add(jLabel2); jLabel2.setBounds(323, 279, 70, 17); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setText("Highlights"); getContentPane().add(jLabel3); jLabel3.setBounds(293, 30, 78, 22); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setText("6 GB RAM | 64 GB ROM | Expandable Upto 256 GB"); getContentPane().add(jLabel4); jLabel4.setBounds(293, 70, 312, 15); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("6 inch Full HD Display"); getContentPane().add(jLabel5); jLabel5.setBounds(293, 103, 130, 15); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setText("16MP Rear Camera | 16MP + 8MP Dual Front Camera"); getContentPane().add(jLabel6); jLabel6.setBounds(293, 136, 328, 15); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel7.setText("4000 mAh Battery"); getContentPane().add(jLabel7); jLabel7.setBounds(293, 169, 114, 15); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel8.setText("Front-mounted Fingerprint Reader"); getContentPane().add(jLabel8); jLabel8.setBounds(293, 202, 212, 15); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel9.setText("Qualcomm MSM8976 Pro Snapdragon 653 octa-core Processor"); getContentPane().add(jLabel9); jLabel9.setBounds(293, 235, 386, 14); jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bg.jpg"))); // NOI18N getContentPane().add(jLabel10); jLabel10.setBounds(-30, -30, 770, 540); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked // TODO add your handling code here: new buy().setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton1MouseClicked private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked // TODO add your handling code here: new oppo().setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton2MouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(f3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new f3().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; // End of variables declaration//GEN-END:variables private void setIcon() { setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("mi.jpg"))); //To change body of generated methods, choose Tools | Templates. } }
7,513
0.63277
0.591907
186
39.387096
30.108418
159
false
false
0
0
0
0
0
0
0.913979
false
false
14
c907c6481366700246792059d7431f98d87b41ff
29,102,698,415,519
023fdef5e1c4a7126df143ba00cf90920885ee0d
/src/main/java/dsAlgo/Problem.java
fe6531358561ef2168cf3a0f24313165dd8c3513
[ "Apache-2.0" ]
permissive
kogupta/scala-playground
https://github.com/kogupta/scala-playground
8722bc0fbb1eea4558794c37f009a5e92498b89a
bfd4f01146c9eb343a4b450111e20e373d285c3a
refs/heads/master
2017-12-02T07:07:56.837000
2017-10-15T17:13:46
2017-10-15T17:13:46
85,054,620
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dsAlgo; import com.google.caliper.Benchmark; import it.unimi.dsi.fastutil.objects.Object2IntArrayMap; import java.util.*; /** * A problem famous with `clay pot` company :P * * Build a structure which supports `insert(T t)`, `delete(T t)` and `T random()` in constant time. * * Solution: * - from SO of course: * https://stackoverflow.com/questions/5682218/data-structure-insert-remove-contains-get-random-element-all-at-o1 * */ class Problem { private interface ConstantOps<T> { void insert(T t); void delete(T t); T random(); boolean isEmpty(); } private static final class Structure<T> implements ConstantOps<T> { private final Random r; private final Object2IntArrayMap<T> xs; private final ArrayList<T> indices; private Structure() { r = new Random(); xs = new Object2IntArrayMap<>(); indices = new ArrayList<>(); } @Override public void insert(T t) { check(); if (!xs.containsKey(t)) { indices.add(t); // append at the end xs.put(t, indices.size() - 1); } } @Override public void delete(T t) { if (xs.containsKey(t)) { int index = xs.getInt(t); int lastIndex = indices.size() - 1; T last = indices.get(lastIndex); Collections.swap(indices, index, lastIndex); indices.remove(lastIndex); xs.put(last, index); xs.removeInt(t); check(); } } private void check() { boolean b = xs.size() == indices.size(); if (!b) { System.out.println("------------------------------------"); System.out.println(xs.size() + " -vs- " + indices.size()); for (T t : indices) { if (xs.containsKey(t)) { int index = xs.getInt(t); T t1 = indices.get(index); if (t != t1) { System.out.println("Index: " + index + ", map: " + t + ", array: " + t1); } } else { System.out.println(t + " in array, not in map"); } } display(); } assert b; } private void display() { System.out.println(xs + " -vs- " + indices); try { Thread.sleep(100); } catch (InterruptedException ignore) { } } @Override public T random() { int index = r.nextInt(indices.size()); return indices.get(index); } @Override public boolean isEmpty() { return xs.isEmpty(); } } private static final class DSBenchmark { @Benchmark void testInserts(int reps) { Structure<Integer> structure = new Structure<>(); for (int i = 0; i < reps; i++) { for (int j = 0; j < 100_000; j++) { structure.insert(j); } } } } public static void main(String[] args) { ConstantOps<Character> ds = new Structure<>(); Random r = new Random(); int range = 'z' - 'a'; for (int i = 0; i < 1000; i++) { char next = (char) ('a' + r.nextInt(range)); double d = r.nextDouble(); if (d < 0.3) ds.delete(next); else if (d >= 0.3 && d < 0.7) ds.insert(next); else if (!ds.isEmpty()) System.out.println(ds.random()); } } }
UTF-8
Java
3,224
java
Problem.java
Java
[]
null
[]
package dsAlgo; import com.google.caliper.Benchmark; import it.unimi.dsi.fastutil.objects.Object2IntArrayMap; import java.util.*; /** * A problem famous with `clay pot` company :P * * Build a structure which supports `insert(T t)`, `delete(T t)` and `T random()` in constant time. * * Solution: * - from SO of course: * https://stackoverflow.com/questions/5682218/data-structure-insert-remove-contains-get-random-element-all-at-o1 * */ class Problem { private interface ConstantOps<T> { void insert(T t); void delete(T t); T random(); boolean isEmpty(); } private static final class Structure<T> implements ConstantOps<T> { private final Random r; private final Object2IntArrayMap<T> xs; private final ArrayList<T> indices; private Structure() { r = new Random(); xs = new Object2IntArrayMap<>(); indices = new ArrayList<>(); } @Override public void insert(T t) { check(); if (!xs.containsKey(t)) { indices.add(t); // append at the end xs.put(t, indices.size() - 1); } } @Override public void delete(T t) { if (xs.containsKey(t)) { int index = xs.getInt(t); int lastIndex = indices.size() - 1; T last = indices.get(lastIndex); Collections.swap(indices, index, lastIndex); indices.remove(lastIndex); xs.put(last, index); xs.removeInt(t); check(); } } private void check() { boolean b = xs.size() == indices.size(); if (!b) { System.out.println("------------------------------------"); System.out.println(xs.size() + " -vs- " + indices.size()); for (T t : indices) { if (xs.containsKey(t)) { int index = xs.getInt(t); T t1 = indices.get(index); if (t != t1) { System.out.println("Index: " + index + ", map: " + t + ", array: " + t1); } } else { System.out.println(t + " in array, not in map"); } } display(); } assert b; } private void display() { System.out.println(xs + " -vs- " + indices); try { Thread.sleep(100); } catch (InterruptedException ignore) { } } @Override public T random() { int index = r.nextInt(indices.size()); return indices.get(index); } @Override public boolean isEmpty() { return xs.isEmpty(); } } private static final class DSBenchmark { @Benchmark void testInserts(int reps) { Structure<Integer> structure = new Structure<>(); for (int i = 0; i < reps; i++) { for (int j = 0; j < 100_000; j++) { structure.insert(j); } } } } public static void main(String[] args) { ConstantOps<Character> ds = new Structure<>(); Random r = new Random(); int range = 'z' - 'a'; for (int i = 0; i < 1000; i++) { char next = (char) ('a' + r.nextInt(range)); double d = r.nextDouble(); if (d < 0.3) ds.delete(next); else if (d >= 0.3 && d < 0.7) ds.insert(next); else if (!ds.isEmpty()) System.out.println(ds.random()); } } }
3,224
0.53629
0.524504
130
23.799999
21.667204
115
false
false
0
0
0
0
0
0
0.484615
false
false
14
683a4cb6c06d2e2a12374030a0730fb94fa6b7b8
15,745,350,123,090
b247c6a174781d58eb139f406fb9e714c0e2d0f4
/plugin/src/de/chille/mds/plugin/tree/TreeMetamodel.java
ae39a2d1ac17993551baa294b9519d84d3263c08
[]
no_license
BackupTheBerlios/metadataserver
https://github.com/BackupTheBerlios/metadataserver
38b2b6ce93e298914b67feac1598d8c8c89722e1
0372cd839ccf7709e599d4c2bf41b5cb789a7fe5
refs/heads/master
2020-04-22T00:27:56.916000
2003-02-04T16:38:37
2003-02-04T16:38:37
40,077,559
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.chille.mds.plugin.tree; import de.chille.mds.soap.MDSObjectBean; public class TreeMetamodel extends TreeParent { public TreeMetamodel(MDSObjectBean bean) { super(bean); } }
UTF-8
Java
189
java
TreeMetamodel.java
Java
[]
null
[]
package de.chille.mds.plugin.tree; import de.chille.mds.soap.MDSObjectBean; public class TreeMetamodel extends TreeParent { public TreeMetamodel(MDSObjectBean bean) { super(bean); } }
189
0.783069
0.783069
9
20.111111
19.364597
47
false
false
0
0
0
0
0
0
0.777778
false
false
14
bba984e2b63571fc85b54da18088035d585b82f0
15,745,350,124,652
33fce9ad1d5091d7f55895969d9624f4350f468d
/practise-project-1/src/main/java/com/example/demo/Demo.java
91469e45beec5f1ebe5674fa4d76028a026edce9
[]
no_license
Avinash1765/practise_repo
https://github.com/Avinash1765/practise_repo
bfc8ae82184894637946b31fc6647ed41268fcc2
94875a0526c21a2ba2ac8d8132a1de811ffe7aee
refs/heads/master
2023-09-06T02:15:37.132000
2021-07-16T04:24:10
2021-07-16T04:24:10
155,971,814
0
0
null
false
2023-08-20T22:05:48
2018-11-03T10:18:06
2021-07-16T04:24:22
2023-08-20T22:05:47
6,561
0
0
42
Java
false
false
package com.example.demo; import java.util.Arrays; public class Demo { public static void main(String[] args) { String a="08"; int ab=Integer.parseInt(a); System.out.println(ab); } }
UTF-8
Java
194
java
Demo.java
Java
[]
null
[]
package com.example.demo; import java.util.Arrays; public class Demo { public static void main(String[] args) { String a="08"; int ab=Integer.parseInt(a); System.out.println(ab); } }
194
0.690722
0.680412
12
15.166667
13.569778
41
false
false
0
0
0
0
0
0
1.083333
false
false
14
82d374355e90ac4ab4276d143998284b0627cd22
11,046,655,906,644
fb3f0253327edacb616650716c74ec43e8b78f00
/socket/src/main/java/com/xuhao/android/libsocket/sdk/connection/interfacies/IAction.java
662bf9ebb625e2d28ae7c0e41d82b6af112fcfef
[ "Apache-2.0", "MIT" ]
permissive
shaobuliao/OkSocket
https://github.com/shaobuliao/OkSocket
b829c010fe50dda67a6419fb446c46fb5a70a6ba
40c51f361356321da7f051677e152fc3ef1ca96c
refs/heads/release-2.0.3
2020-03-20T23:48:05.090000
2018-06-04T07:19:36
2018-06-04T07:19:36
137,863,977
1
0
MIT
true
2018-06-19T08:40:56
2018-06-19T08:40:55
2018-06-19T05:48:30
2018-06-16T20:15:21
2,308
0
0
0
null
false
null
package com.xuhao.android.libsocket.sdk.connection.interfacies; public interface IAction { //数据key String ACTION_DATA = "action_data"; //socket读线程启动响应 String ACTION_READ_THREAD_START = "action_read_thread_start"; //socket读线程关闭响应 String ACTION_READ_THREAD_SHUTDOWN = "action_read_thread_shutdown"; //socket写线程启动响应 String ACTION_WRITE_THREAD_START = "action_write_thread_start"; //socket写线程关闭响应 String ACTION_WRITE_THREAD_SHUTDOWN = "action_write_thread_shutdown"; //收到推送消息响应 String ACTION_READ_COMPLETE = "action_read_complete"; //写给服务器响应 String ACTION_WRITE_COMPLETE = "action_write_complete"; //socket连接服务器成功响应 String ACTION_CONNECTION_SUCCESS = "action_connection_success"; //socket连接服务器失败响应 String ACTION_CONNECTION_FAILED = "action_connection_failed"; //socket与服务器断开连接 String ACTION_DISCONNECTION = "action_disconnection"; //发送心跳请求 String ACTION_PULSE_REQUEST = "action_pulse_request"; }
UTF-8
Java
1,134
java
IAction.java
Java
[]
null
[]
package com.xuhao.android.libsocket.sdk.connection.interfacies; public interface IAction { //数据key String ACTION_DATA = "action_data"; //socket读线程启动响应 String ACTION_READ_THREAD_START = "action_read_thread_start"; //socket读线程关闭响应 String ACTION_READ_THREAD_SHUTDOWN = "action_read_thread_shutdown"; //socket写线程启动响应 String ACTION_WRITE_THREAD_START = "action_write_thread_start"; //socket写线程关闭响应 String ACTION_WRITE_THREAD_SHUTDOWN = "action_write_thread_shutdown"; //收到推送消息响应 String ACTION_READ_COMPLETE = "action_read_complete"; //写给服务器响应 String ACTION_WRITE_COMPLETE = "action_write_complete"; //socket连接服务器成功响应 String ACTION_CONNECTION_SUCCESS = "action_connection_success"; //socket连接服务器失败响应 String ACTION_CONNECTION_FAILED = "action_connection_failed"; //socket与服务器断开连接 String ACTION_DISCONNECTION = "action_disconnection"; //发送心跳请求 String ACTION_PULSE_REQUEST = "action_pulse_request"; }
1,134
0.721429
0.721429
26
36.73077
24.393501
73
false
false
0
0
0
0
0
0
0.461538
false
false
14
cffa9604b10a2ac360f165e8bc9a54cc585fbf2b
13,872,744,425,920
b421652425d249f662024d0a818319d51dd8c84d
/src/com/are/reparto/UploadInfo.java
6d9eb89d049d4ad978e39c9577183f95f4e65679
[]
no_license
arivera29/ReaderReparto
https://github.com/arivera29/ReaderReparto
619787ef60294b0b4ffe1c8793441846b298e19a
f8226050eae3924f84e6ba956d34e17ccf169cd8
refs/heads/master
2020-03-21T01:59:49.531000
2018-06-20T03:09:57
2018-06-20T03:09:57
137,973,786
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.are.reparto; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; public class UploadInfo { private static ArrayList<Configuracion> configuracion; private static String[] fields; private static db conexion = null; public static void main(String[] args) { // TODO Auto-generated method stub String cFields = "NIC,SIMBOLO_VARIABLE,FECHA_VENCIMIENTO,FECHA_PAGO_OPORTUNO,FECHA_EMISION,NUMERO_FACTURA,INDICATIVO_SUMINISTRO,CIIU,TIPO_COBRO,SECUENCIAL_RECIBO,NIS,TIPO_SERVICIO,ORDEN_LECTURA,MEDIDOR,LECT_ANTERIOR,LECT_ACTUAL,FECHA_LECTURA_ACTUAL,CONSUMO_FACTURADO,VALOR_FACTURA,GRUPO_FAMILIAR,PRECIO_UNITARIO_CU,IND_VISUSALIZACION_BARCODI,IMPORTE_TOTAL_DEUDA,CANTIDAD_FACTURAS_ADEUDADAS,DESC_ANOMALIA_LECTURA,IMPORTE_TOTAL_FACTURA,SUBTOTAL_FACTURA,DESCRIPCION_TARIFA,CONSUMO_PROMEDIO,DIAS_FACTURADOS,CLAVE_ORDEN_FACTURA,PROPIEDAD_EQUIPO_MEDIDA,UNICOM,RUTA,ITINERARIO"; fields = cFields.split(","); readConfiguracion(); if (configuracion.size() != fields.length) { System.out.println("Longitud de campos y configuración es diferente. Fields: " + fields.length + " Configuracion: " + configuracion.size()); Utilidades.AgregarLog("Longitud de campos y configuración es diferente. Fields: " + fields.length + " Configuracion: " + configuracion.size()); return; } if (configuracion.size() > 0) { System.out.println("Campos a leer: " + configuracion.size()); Utilidades.AgregarLog("Campos a leer: " + configuracion.size()); String ruta = "C:\\REPARTO\\"; File directorio = new File(ruta); Utilidades.AgregarLog("Descomprimiendo archivos ruta:" + ruta); DescomprimirArchivosCarpeta(directorio); Utilidades.AgregarLog("Procesando archivos de reparto en ruta:" + ruta); ProcesarDirectorio(directorio); } else { System.out.println("No se ha cargado la configuracion"); Utilidades.AgregarLog("No se ha cargado la configuracion"); } } public static boolean GuardarRegistro(String[] fila, String filename) { boolean resultado = false; File f = new File(filename); String sql = ""; try { sql = "INSERT INTO reparto ("; for (int x = 0; x < fields.length; x++) { sql += fields[x] + ","; } sql += "FECHA_CARGA, USUARIO_CARGA, FILE_ORIGEN) VALUES ("; for (int x = 0; x < fields.length; x++) { sql += "?,"; } sql += "SYSDATETIME(), 'reader',?)"; System.out.println("Guardando registro."); Utilidades.AgregarLog("Guardando registro."); java.sql.PreparedStatement pst = conexion.getConnection().prepareStatement(sql); for (int x = 0; x < fila.length; x++) { if (fields[x].equals("IMPORTE_TOTAL_DEUDA") || fields[x].equals("IMPORTE_TOTAL_FACTURA") || fields[x].equals("SUBTOTAL_FACTURA") || fields[x].equals("CONSUMO_PROMEDIO") || fields[x].equals("CONSUMO_PROMEDIO")) { fila[x] = fila[x].replace(".", ""); fila[x] = fila[x].replace(",", "."); } pst.setString(x+1, fila[x].trim()); } pst.setString(fila.length+1, filename); if (conexion.Update(pst) > 0) { System.out.println("Registro guardado correctamente"); Utilidades.AgregarLog("Registro guardado correctamente"); conexion.Commit(); resultado = true; } } catch (SQLException ex) { System.out.println("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); Utilidades.AgregarLog("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); } return resultado; } public static void readConfiguracion() { configuracion = new ArrayList<Configuracion>(); String rutaFileConfiguracion = "C:\\LECTURAS\\configuracion.txt"; String cadena; FileReader f; try { f = new FileReader(rutaFileConfiguracion); BufferedReader b = new BufferedReader(f); while ((cadena = b.readLine()) != null) { String[] fila = cadena.split(" "); if (fila.length == 3) { Configuracion c = new Configuracion(); c.setNombre(fila[0]); c.setPosInicial(Integer.parseInt(fila[1])); c.setPosFinal(Integer.parseInt(fila[2])); configuracion.add(c); } } b.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Error: " + e.getMessage()); Utilidades.AgregarLog("Error: " + e.getMessage()); } } private static void EscribirArchivo(String fila) { FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("C:\\LECTURAS\\SALIDA.TXT", true); String finLinea = "\r\n"; pw = new PrintWriter(fichero); pw.append(fila + finLinea); } catch (Exception e) { e.printStackTrace(); } finally { if (fichero != null) { try { fichero.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void ProcesarDirectorio(File directorio) { System.out.println("Procesando Directorio: " + directorio.getPath()); Utilidades.AgregarLog("Procesando Directorio: " + directorio.getPath()); File[] ficheros = directorio.listFiles(); for (File fichero : ficheros) { if (fichero.isDirectory()) { ProcesarDirectorio(fichero); } else { System.out.println("Validando nombre archivo: " + fichero.getName().substring(0, 7)); Utilidades.AgregarLog("Validando nombre archivo: " + fichero.getName().substring(0, 7)); if (!getExtension(fichero.getName()).equals(".Z")) { System.out.println("Procesando archivo: " + fichero.getPath()); Utilidades.AgregarLog("Procesando archivo: " + fichero.getPath()); ProcesarArchivo(fichero.getPath()); }else { System.out.println("Archivo: " + fichero.getPath() + " DESCARTADO..."); Utilidades.AgregarLog("Archivo: " + fichero.getPath() + " DESCARTADO..."); } /* if (fichero.getName().substring(0, 7).equals("FNORMAL")) { System.out.println("Validando Extension archivo: " + getExtension(fichero.getName())); Utilidades.AgregarLog("Validando Extension archivo: " + getExtension(fichero.getName())); if (!getExtension(fichero.getName()).equals(".Z")) { // Procesa archivo no comprimido System.out.println("Procesando archivo: " + fichero.getPath()); Utilidades.AgregarLog("Procesando archivo: " + fichero.getPath()); ProcesarArchivo(fichero.getPath()); } else { // Descomprimir y procesar. System.out.println("Descomprimir archivo: " + fichero.getPath()); Utilidades.AgregarLog("Descomprimir archivo: " + fichero.getPath()); } } else { System.out.println("Archivo: " + fichero.getPath() + " DESCARTADO..."); Utilidades.AgregarLog("Archivo: " + fichero.getPath() + " DESCARTADO..."); } */ } } } public static void ProcesarArchivo(String filename) { String cadena; FileReader f; try { f = new FileReader(filename); BufferedReader b = new BufferedReader(f); int cont = 0; conexion = new db(); while ((cadena = b.readLine()) != null) { cont++; System.out.println("Longitud de la cadena: " + cadena.length() + " Fila: " + cont); Utilidades.AgregarLog("Longitud de la cadena: " + cadena.length() + " Fila: " + cont); if (cadena.length() > 8000) { if (cadena.substring(0, 1).equals("1")) { String[] fila = new String[fields.length]; for (int x = 0; x < configuracion.size(); x++) { Configuracion c = configuracion.get(x); //System.out.println("Leyendo campo: " + c.getNombre() + " PosIni: " + c.getPosInicial() + " PosFin: " + c.getPosFinal()); String campo = cadena.substring(c.getPosInicial() - 1, c.getPosFinal()-1); //System.out.println(fields[x] + "=" + campo); //Utilidades.AgregarLog(fields[x] + "=" + campo); fila[x] = campo; } GuardarRegistro(fila, filename); } } } b.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Error: " + e.getMessage()); Utilidades.AgregarLog("Error: " + e.getMessage()); } catch (SQLException ex) { System.out.println("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); Utilidades.AgregarLog("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); } finally { if (conexion != null) { try { conexion.Close(); } catch (SQLException ex) { System.out.println("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); Utilidades.AgregarLog("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); } } } } public static String getExtension(String name) { String extension = ""; if (name.lastIndexOf('.') > 0) { // get last index for '.' char int lastIndex = name.lastIndexOf('.'); // get extension extension = name.substring(lastIndex); } return extension; } public static void DescomprimirArchivosCarpeta(File directorio) { System.out.println("Procesando Directorio: " + directorio.getPath()); Utilidades.AgregarLog("Procesando Directorio: " + directorio.getPath()); File[] ficheros = directorio.listFiles(); for (File fichero : ficheros) { if (fichero.isDirectory()) { DescomprimirArchivosCarpeta(fichero); } else { if (getExtension(fichero.getName()).equals(".Z")) { // Procesa archivo no comprimido System.out.println("Descomprimiendo archivo: " + fichero.getPath()); Utilidades.AgregarLog("Descomprimiendo archivo: " + fichero.getPath()); Utilidades.DescomprimirArchivo(fichero.getPath(), fichero.getParent()); } } } } }
UTF-8
Java
12,133
java
UploadInfo.java
Java
[]
null
[]
package com.are.reparto; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; public class UploadInfo { private static ArrayList<Configuracion> configuracion; private static String[] fields; private static db conexion = null; public static void main(String[] args) { // TODO Auto-generated method stub String cFields = "NIC,SIMBOLO_VARIABLE,FECHA_VENCIMIENTO,FECHA_PAGO_OPORTUNO,FECHA_EMISION,NUMERO_FACTURA,INDICATIVO_SUMINISTRO,CIIU,TIPO_COBRO,SECUENCIAL_RECIBO,NIS,TIPO_SERVICIO,ORDEN_LECTURA,MEDIDOR,LECT_ANTERIOR,LECT_ACTUAL,FECHA_LECTURA_ACTUAL,CONSUMO_FACTURADO,VALOR_FACTURA,GRUPO_FAMILIAR,PRECIO_UNITARIO_CU,IND_VISUSALIZACION_BARCODI,IMPORTE_TOTAL_DEUDA,CANTIDAD_FACTURAS_ADEUDADAS,DESC_ANOMALIA_LECTURA,IMPORTE_TOTAL_FACTURA,SUBTOTAL_FACTURA,DESCRIPCION_TARIFA,CONSUMO_PROMEDIO,DIAS_FACTURADOS,CLAVE_ORDEN_FACTURA,PROPIEDAD_EQUIPO_MEDIDA,UNICOM,RUTA,ITINERARIO"; fields = cFields.split(","); readConfiguracion(); if (configuracion.size() != fields.length) { System.out.println("Longitud de campos y configuración es diferente. Fields: " + fields.length + " Configuracion: " + configuracion.size()); Utilidades.AgregarLog("Longitud de campos y configuración es diferente. Fields: " + fields.length + " Configuracion: " + configuracion.size()); return; } if (configuracion.size() > 0) { System.out.println("Campos a leer: " + configuracion.size()); Utilidades.AgregarLog("Campos a leer: " + configuracion.size()); String ruta = "C:\\REPARTO\\"; File directorio = new File(ruta); Utilidades.AgregarLog("Descomprimiendo archivos ruta:" + ruta); DescomprimirArchivosCarpeta(directorio); Utilidades.AgregarLog("Procesando archivos de reparto en ruta:" + ruta); ProcesarDirectorio(directorio); } else { System.out.println("No se ha cargado la configuracion"); Utilidades.AgregarLog("No se ha cargado la configuracion"); } } public static boolean GuardarRegistro(String[] fila, String filename) { boolean resultado = false; File f = new File(filename); String sql = ""; try { sql = "INSERT INTO reparto ("; for (int x = 0; x < fields.length; x++) { sql += fields[x] + ","; } sql += "FECHA_CARGA, USUARIO_CARGA, FILE_ORIGEN) VALUES ("; for (int x = 0; x < fields.length; x++) { sql += "?,"; } sql += "SYSDATETIME(), 'reader',?)"; System.out.println("Guardando registro."); Utilidades.AgregarLog("Guardando registro."); java.sql.PreparedStatement pst = conexion.getConnection().prepareStatement(sql); for (int x = 0; x < fila.length; x++) { if (fields[x].equals("IMPORTE_TOTAL_DEUDA") || fields[x].equals("IMPORTE_TOTAL_FACTURA") || fields[x].equals("SUBTOTAL_FACTURA") || fields[x].equals("CONSUMO_PROMEDIO") || fields[x].equals("CONSUMO_PROMEDIO")) { fila[x] = fila[x].replace(".", ""); fila[x] = fila[x].replace(",", "."); } pst.setString(x+1, fila[x].trim()); } pst.setString(fila.length+1, filename); if (conexion.Update(pst) > 0) { System.out.println("Registro guardado correctamente"); Utilidades.AgregarLog("Registro guardado correctamente"); conexion.Commit(); resultado = true; } } catch (SQLException ex) { System.out.println("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); Utilidades.AgregarLog("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); } return resultado; } public static void readConfiguracion() { configuracion = new ArrayList<Configuracion>(); String rutaFileConfiguracion = "C:\\LECTURAS\\configuracion.txt"; String cadena; FileReader f; try { f = new FileReader(rutaFileConfiguracion); BufferedReader b = new BufferedReader(f); while ((cadena = b.readLine()) != null) { String[] fila = cadena.split(" "); if (fila.length == 3) { Configuracion c = new Configuracion(); c.setNombre(fila[0]); c.setPosInicial(Integer.parseInt(fila[1])); c.setPosFinal(Integer.parseInt(fila[2])); configuracion.add(c); } } b.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Error: " + e.getMessage()); Utilidades.AgregarLog("Error: " + e.getMessage()); } } private static void EscribirArchivo(String fila) { FileWriter fichero = null; PrintWriter pw = null; try { fichero = new FileWriter("C:\\LECTURAS\\SALIDA.TXT", true); String finLinea = "\r\n"; pw = new PrintWriter(fichero); pw.append(fila + finLinea); } catch (Exception e) { e.printStackTrace(); } finally { if (fichero != null) { try { fichero.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void ProcesarDirectorio(File directorio) { System.out.println("Procesando Directorio: " + directorio.getPath()); Utilidades.AgregarLog("Procesando Directorio: " + directorio.getPath()); File[] ficheros = directorio.listFiles(); for (File fichero : ficheros) { if (fichero.isDirectory()) { ProcesarDirectorio(fichero); } else { System.out.println("Validando nombre archivo: " + fichero.getName().substring(0, 7)); Utilidades.AgregarLog("Validando nombre archivo: " + fichero.getName().substring(0, 7)); if (!getExtension(fichero.getName()).equals(".Z")) { System.out.println("Procesando archivo: " + fichero.getPath()); Utilidades.AgregarLog("Procesando archivo: " + fichero.getPath()); ProcesarArchivo(fichero.getPath()); }else { System.out.println("Archivo: " + fichero.getPath() + " DESCARTADO..."); Utilidades.AgregarLog("Archivo: " + fichero.getPath() + " DESCARTADO..."); } /* if (fichero.getName().substring(0, 7).equals("FNORMAL")) { System.out.println("Validando Extension archivo: " + getExtension(fichero.getName())); Utilidades.AgregarLog("Validando Extension archivo: " + getExtension(fichero.getName())); if (!getExtension(fichero.getName()).equals(".Z")) { // Procesa archivo no comprimido System.out.println("Procesando archivo: " + fichero.getPath()); Utilidades.AgregarLog("Procesando archivo: " + fichero.getPath()); ProcesarArchivo(fichero.getPath()); } else { // Descomprimir y procesar. System.out.println("Descomprimir archivo: " + fichero.getPath()); Utilidades.AgregarLog("Descomprimir archivo: " + fichero.getPath()); } } else { System.out.println("Archivo: " + fichero.getPath() + " DESCARTADO..."); Utilidades.AgregarLog("Archivo: " + fichero.getPath() + " DESCARTADO..."); } */ } } } public static void ProcesarArchivo(String filename) { String cadena; FileReader f; try { f = new FileReader(filename); BufferedReader b = new BufferedReader(f); int cont = 0; conexion = new db(); while ((cadena = b.readLine()) != null) { cont++; System.out.println("Longitud de la cadena: " + cadena.length() + " Fila: " + cont); Utilidades.AgregarLog("Longitud de la cadena: " + cadena.length() + " Fila: " + cont); if (cadena.length() > 8000) { if (cadena.substring(0, 1).equals("1")) { String[] fila = new String[fields.length]; for (int x = 0; x < configuracion.size(); x++) { Configuracion c = configuracion.get(x); //System.out.println("Leyendo campo: " + c.getNombre() + " PosIni: " + c.getPosInicial() + " PosFin: " + c.getPosFinal()); String campo = cadena.substring(c.getPosInicial() - 1, c.getPosFinal()-1); //System.out.println(fields[x] + "=" + campo); //Utilidades.AgregarLog(fields[x] + "=" + campo); fila[x] = campo; } GuardarRegistro(fila, filename); } } } b.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Error: " + e.getMessage()); Utilidades.AgregarLog("Error: " + e.getMessage()); } catch (SQLException ex) { System.out.println("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); Utilidades.AgregarLog("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); } finally { if (conexion != null) { try { conexion.Close(); } catch (SQLException ex) { System.out.println("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); Utilidades.AgregarLog("Error: " + ex.getErrorCode() + ", " + ex.getMessage()); } } } } public static String getExtension(String name) { String extension = ""; if (name.lastIndexOf('.') > 0) { // get last index for '.' char int lastIndex = name.lastIndexOf('.'); // get extension extension = name.substring(lastIndex); } return extension; } public static void DescomprimirArchivosCarpeta(File directorio) { System.out.println("Procesando Directorio: " + directorio.getPath()); Utilidades.AgregarLog("Procesando Directorio: " + directorio.getPath()); File[] ficheros = directorio.listFiles(); for (File fichero : ficheros) { if (fichero.isDirectory()) { DescomprimirArchivosCarpeta(fichero); } else { if (getExtension(fichero.getName()).equals(".Z")) { // Procesa archivo no comprimido System.out.println("Descomprimiendo archivo: " + fichero.getPath()); Utilidades.AgregarLog("Descomprimiendo archivo: " + fichero.getPath()); Utilidades.DescomprimirArchivo(fichero.getPath(), fichero.getParent()); } } } } }
12,133
0.518836
0.516445
272
42.599266
44.872997
579
false
false
0
0
0
0
0
0
0.764706
false
false
14
6bb7c483dbfa5ff6e5d8310de925d2b5a8863a8f
137,439,013,121
140daf989b68daebe9cbb7387061fffe3ff289f6
/app/src/main/java/com/example/karen/registrationproject/view/activity/DashboardActivity.java
223ce3d49737dfa0b3e6a04e02065ee6c18da571
[]
no_license
madhatterph/RegistrationProject
https://github.com/madhatterph/RegistrationProject
0037747b0ef42af2ee32d73891743f39174ec0a5
11adb3c0f402f721df8a368f73cd359fbeae47f0
refs/heads/master
2021-06-09T21:55:36.058000
2016-12-06T09:57:33
2016-12-06T09:57:33
75,717,759
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.karen.registrationproject.view.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.example.karen.registrationproject.R; import com.example.karen.registrationproject.api.model.AttendanceItem; import com.example.karen.registrationproject.view.adapter.AttendanceAdapter; import java.util.ArrayList; import java.util.List; import static android.R.attr.value; public class DashboardActivity extends AppCompatActivity implements View.OnClickListener { Button db_btn_login; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); Intent intent = getIntent(); String value = intent.getStringExtra("login"); db_btn_login = (Button) findViewById(R.id.dashboard_btn_login); db_btn_login.setOnClickListener(this); List<AttendanceItem> attendanceItems = new ArrayList<>(); AttendanceItem attendanceItem = new AttendanceItem(); attendanceItem.date = "Oct. 20, 2016"; attendanceItem.timeIn = "10:00 AM"; attendanceItem.timeOut = "7:10 PM"; attendanceItem.totalHours = "8 hrs"; attendanceItem.task = "Database"; attendanceItems.add(attendanceItem); attendanceItem = new AttendanceItem(); attendanceItem.date = "Oct. 21, 2016"; attendanceItem.timeIn = "11:15 AM"; attendanceItem.timeOut = "8:00 PM"; attendanceItems.add(attendanceItem); attendanceItem = new AttendanceItem(); attendanceItem.date = "Oct. 22, 2016"; attendanceItem.timeIn = "07:15 AM"; attendanceItems.add(attendanceItem); AttendanceAdapter myAdapter=new AttendanceAdapter(this, attendanceItems); ListView listView = (ListView) findViewById(R.id.dashboard_listview); listView.setAdapter(myAdapter); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.dashboard_btn_login: SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean("TimeIn", true); editor.apply(); Intent intent = new Intent(this, ListViewScreenActivity.class); intent.putExtra("login", value); //Optional parameters DashboardActivity.this.startActivity(intent); break; } } }
UTF-8
Java
2,945
java
DashboardActivity.java
Java
[]
null
[]
package com.example.karen.registrationproject.view.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import com.example.karen.registrationproject.R; import com.example.karen.registrationproject.api.model.AttendanceItem; import com.example.karen.registrationproject.view.adapter.AttendanceAdapter; import java.util.ArrayList; import java.util.List; import static android.R.attr.value; public class DashboardActivity extends AppCompatActivity implements View.OnClickListener { Button db_btn_login; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dashboard); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); Intent intent = getIntent(); String value = intent.getStringExtra("login"); db_btn_login = (Button) findViewById(R.id.dashboard_btn_login); db_btn_login.setOnClickListener(this); List<AttendanceItem> attendanceItems = new ArrayList<>(); AttendanceItem attendanceItem = new AttendanceItem(); attendanceItem.date = "Oct. 20, 2016"; attendanceItem.timeIn = "10:00 AM"; attendanceItem.timeOut = "7:10 PM"; attendanceItem.totalHours = "8 hrs"; attendanceItem.task = "Database"; attendanceItems.add(attendanceItem); attendanceItem = new AttendanceItem(); attendanceItem.date = "Oct. 21, 2016"; attendanceItem.timeIn = "11:15 AM"; attendanceItem.timeOut = "8:00 PM"; attendanceItems.add(attendanceItem); attendanceItem = new AttendanceItem(); attendanceItem.date = "Oct. 22, 2016"; attendanceItem.timeIn = "07:15 AM"; attendanceItems.add(attendanceItem); AttendanceAdapter myAdapter=new AttendanceAdapter(this, attendanceItems); ListView listView = (ListView) findViewById(R.id.dashboard_listview); listView.setAdapter(myAdapter); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.dashboard_btn_login: SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean("TimeIn", true); editor.apply(); Intent intent = new Intent(this, ListViewScreenActivity.class); intent.putExtra("login", value); //Optional parameters DashboardActivity.this.startActivity(intent); break; } } }
2,945
0.667912
0.655008
84
33.059525
25.783602
90
false
false
0
0
0
0
0
0
0.714286
false
false
14
cfa0b21efccb2a31f57fb15cc2ee3367349f8126
8,495,445,321,563
185d49e5bc5cfbc045cb4e7ee9162d2b805f679b
/edu/ocp/nio2/files/operations/NewBufferedReaderWriter.java
cae02d095501c63802e2f553dce40f701d3ef4a4
[]
no_license
ismael6/OCP
https://github.com/ismael6/OCP
ac7ea24ff8f8b360ad4f77ca59cc80088cd9c434
563b9704e6d16f0934e111ede860b057cba270f9
refs/heads/master
2020-04-16T17:45:28.181000
2019-03-11T16:38:35
2019-03-11T16:38:35
165,787,341
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ocp.nio2.files.operations; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; /** * @author IsmaSp6 * * glues Buffered Reader/Writer with NIO2 Path * * * newBufferedReader: BufferedReader (Path, Charset) * newBufferedWriter: BufferedWriter (Path, Charset) * */ public class NewBufferedReaderWriter { static void read() throws IOException { try(BufferedReader br = Files.newBufferedReader( Paths.get("/user/file.txt"), Charset.defaultCharset())){ String line = null; while((line = br.readLine()) != null) { System.out.println(line); } } } static void write() throws IOException{ try(BufferedWriter bw = Files.newBufferedWriter( Paths.get("/user/file.txt"), Charset.defaultCharset())){ bw.write("fasdasg"); } } }
UTF-8
Java
929
java
NewBufferedReaderWriter.java
Java
[ { "context": "Files;\nimport java.nio.file.Paths;\n\n/**\n * @author IsmaSp6\n *\n *\tglues Buffered Reader/Writer with NIO2 Path", "end": 242, "score": 0.9996111392974854, "start": 235, "tag": "USERNAME", "value": "IsmaSp6" } ]
null
[]
package edu.ocp.nio2.files.operations; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; /** * @author IsmaSp6 * * glues Buffered Reader/Writer with NIO2 Path * * * newBufferedReader: BufferedReader (Path, Charset) * newBufferedWriter: BufferedWriter (Path, Charset) * */ public class NewBufferedReaderWriter { static void read() throws IOException { try(BufferedReader br = Files.newBufferedReader( Paths.get("/user/file.txt"), Charset.defaultCharset())){ String line = null; while((line = br.readLine()) != null) { System.out.println(line); } } } static void write() throws IOException{ try(BufferedWriter bw = Files.newBufferedWriter( Paths.get("/user/file.txt"), Charset.defaultCharset())){ bw.write("fasdasg"); } } }
929
0.691066
0.687836
42
21.119047
16.485495
52
false
false
0
0
0
0
0
0
1.880952
false
false
14
e372772f66034750ae7701ae0831288f65ede90d
13,477,607,434,998
6fa5bb54f989de7fa6d829ed5c1651654f740e7e
/src/main/java/org/cobweb/cobweb2/plugins/production/Product.java
2436325350428da740e9190eca08bb5e7e378aa0
[]
no_license
BokaiWang/cobweb2
https://github.com/BokaiWang/cobweb2
bafe2439e4f9b0437fd9b42c33c8c03c2ea1a286
cdf7fc50f98805baecfe5b518a62338b837f9712
refs/heads/master
2023-07-17T20:39:38.843000
2021-08-26T21:59:57
2021-08-26T21:59:57
370,817,615
0
0
null
true
2021-06-02T13:30:05
2021-05-25T20:17:54
2021-05-25T20:17:55
2021-06-02T13:30:05
12,097
0
0
0
null
false
false
package org.cobweb.cobweb2.plugins.production; import org.cobweb.cobweb2.core.Agent; import org.cobweb.cobweb2.core.Drop; import org.cobweb.cobweb2.core.Location; import org.cobweb.cobweb2.plugins.TemporaryEffect; import org.cobweb.cobweb2.plugins.production.ProductionMapper.ProductionCause; public class Product implements Drop { private final ProductionMapper productionMapper; final Location loc; private long expiryTime; Product(float value, Agent producer, ProductionMapper productionMapper, long expiryPeriod) { this.value = value; this.producer = producer; this.loc = producer.getPosition(); this.productionMapper = productionMapper; this.expiryTime = productionMapper.simulation.getTime() + expiryPeriod; productionMapper.updateValues(this, true); productionMapper.getAgentState(producer).unsoldProducts++; } private Agent producer; private float value; @Override public void update() { if (productionMapper.simulation.getTime() >= expiryTime) productionMapper.remove(this); } public float getValue() { return value; } @Override public boolean canStep(Agent agent) { return true; } @Override public void prepareRemove() { productionMapper.updateValues(this, false); productionMapper.getAgentState(producer).unsoldProducts--; this.value = 0; } public Location getLocation() { return loc; } @Override public void onStep(Agent buyer) { if (producer != buyer && productionMapper.simulation.getRandom().nextFloat() <= 0.3f) { ProductionAgentParams agentParams = productionMapper.getAgentState(producer).agentParams; int price = agentParams.productPrice.getValue(); if (!buyer.enoughEnergy(price)) return; producer.changeEnergy(+price, new ProductSoldCause()); buyer.changeEnergy(-price, new ProductBoughtCause()); TemporaryEffect effect = new TemporaryEffect( buyer, agentParams.productEffect, new ProductEffectSource(producer)); productionMapper.applyEffect(effect); productionMapper.remove(this); } } private static class ProductEffectSource { private Agent producer; public ProductEffectSource(Agent producer) { this.producer = producer; } @Override public int hashCode() { return producer.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof ProductEffectSource) { ProductEffectSource other = (ProductEffectSource) obj; return this.producer.equals(other.producer); } return false; } } public static class ProductSoldCause extends ProductionCause { @Override public String getName() { return "Product Sold"; } } public static class ProductBoughtCause extends ProductionCause { @Override public String getName() { return "Product Bought"; } } @Override public int getProducerType() { return producer.getType(); } }
UTF-8
Java
2,942
java
Product.java
Java
[]
null
[]
package org.cobweb.cobweb2.plugins.production; import org.cobweb.cobweb2.core.Agent; import org.cobweb.cobweb2.core.Drop; import org.cobweb.cobweb2.core.Location; import org.cobweb.cobweb2.plugins.TemporaryEffect; import org.cobweb.cobweb2.plugins.production.ProductionMapper.ProductionCause; public class Product implements Drop { private final ProductionMapper productionMapper; final Location loc; private long expiryTime; Product(float value, Agent producer, ProductionMapper productionMapper, long expiryPeriod) { this.value = value; this.producer = producer; this.loc = producer.getPosition(); this.productionMapper = productionMapper; this.expiryTime = productionMapper.simulation.getTime() + expiryPeriod; productionMapper.updateValues(this, true); productionMapper.getAgentState(producer).unsoldProducts++; } private Agent producer; private float value; @Override public void update() { if (productionMapper.simulation.getTime() >= expiryTime) productionMapper.remove(this); } public float getValue() { return value; } @Override public boolean canStep(Agent agent) { return true; } @Override public void prepareRemove() { productionMapper.updateValues(this, false); productionMapper.getAgentState(producer).unsoldProducts--; this.value = 0; } public Location getLocation() { return loc; } @Override public void onStep(Agent buyer) { if (producer != buyer && productionMapper.simulation.getRandom().nextFloat() <= 0.3f) { ProductionAgentParams agentParams = productionMapper.getAgentState(producer).agentParams; int price = agentParams.productPrice.getValue(); if (!buyer.enoughEnergy(price)) return; producer.changeEnergy(+price, new ProductSoldCause()); buyer.changeEnergy(-price, new ProductBoughtCause()); TemporaryEffect effect = new TemporaryEffect( buyer, agentParams.productEffect, new ProductEffectSource(producer)); productionMapper.applyEffect(effect); productionMapper.remove(this); } } private static class ProductEffectSource { private Agent producer; public ProductEffectSource(Agent producer) { this.producer = producer; } @Override public int hashCode() { return producer.hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof ProductEffectSource) { ProductEffectSource other = (ProductEffectSource) obj; return this.producer.equals(other.producer); } return false; } } public static class ProductSoldCause extends ProductionCause { @Override public String getName() { return "Product Sold"; } } public static class ProductBoughtCause extends ProductionCause { @Override public String getName() { return "Product Bought"; } } @Override public int getProducerType() { return producer.getType(); } }
2,942
0.722298
0.719239
113
24.053097
23.627209
93
false
false
0
0
0
0
0
0
1.876106
false
false
14
2cd46f623ad3086860fdcf17cbfae4a03d943689
20,607,253,120,950
96d5bc340f5d207a22de7803ebf56cb50dfca53b
/app/src/main/java/com/cokimutai/med_manager/data/MedCounterViewModelFactory.java
448e62a9025d0335d5c92b2b63a05d16f476046e
[]
no_license
kimmco/Med_Manager
https://github.com/kimmco/Med_Manager
1f3cb472eb82ef445fcb32827b68b059bd097160
fcec14eb5a3b5bd4ff503d59b2e7461a061a1e27
refs/heads/master
2020-05-24T19:23:48.623000
2019-10-16T11:24:04
2019-10-16T11:24:04
187,432,885
0
0
null
false
2019-10-16T11:24:05
2019-05-19T04:15:07
2019-10-16T11:22:27
2019-10-16T11:24:05
0
0
0
0
null
false
false
package com.cokimutai.med_manager.data; import android.arch.lifecycle.ViewModel; import android.arch.lifecycle.ViewModelProvider; import android.support.annotation.NonNull; public class MedCounterViewModelFactory extends ViewModelProvider.NewInstanceFactory { private final MedDatabase db; private final int medCounter; public MedCounterViewModelFactory(MedDatabase mDb, int medCount){ db = mDb; medCounter = medCount; } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { return (T) new MedCounterViewModel(db, medCounter); } }
UTF-8
Java
626
java
MedCounterViewModelFactory.java
Java
[]
null
[]
package com.cokimutai.med_manager.data; import android.arch.lifecycle.ViewModel; import android.arch.lifecycle.ViewModelProvider; import android.support.annotation.NonNull; public class MedCounterViewModelFactory extends ViewModelProvider.NewInstanceFactory { private final MedDatabase db; private final int medCounter; public MedCounterViewModelFactory(MedDatabase mDb, int medCount){ db = mDb; medCounter = medCount; } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { return (T) new MedCounterViewModel(db, medCounter); } }
626
0.744409
0.744409
21
28.809525
26.238138
86
false
false
0
0
0
0
0
0
0.52381
false
false
14
829556bc07d1ffa339761c3eb439ab0f6a58c99f
4,406,636,449,239
c8fb1e4f4f74ce161d5732081ce7c4b6b0ae8366
/corba/src/main/java/ca/concordia/encs/distributed/corba/model/ClinicServiceHolder.java
41ae8c14e2fa3a3aacc781a894a25b604eac98b9
[]
no_license
takeitallsource/distributed-systems
https://github.com/takeitallsource/distributed-systems
09a0aebfc3ac8f77b53302787f9373d7c01d1da6
75ba8a2eab17f78725f1397929819e892719aec5
refs/heads/master
2021-01-21T10:34:18.577000
2017-02-28T16:28:37
2017-02-28T16:28:37
83,453,309
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package ca.concordia.encs.distributed.corba.model; /** * ca/concordia/encs/distributed/corba/model/ClinicServiceHolder.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from ClinicServices.idl * Monday, July 4, 2016 11:59:07 AM CDT */ public final class ClinicServiceHolder implements org.omg.CORBA.portable.Streamable { public ca.concordia.encs.distributed.corba.model.ClinicService value = null; public ClinicServiceHolder () { } public ClinicServiceHolder (ca.concordia.encs.distributed.corba.model.ClinicService initialValue) { value = initialValue; } public void _read (org.omg.CORBA.portable.InputStream i) { value = ca.concordia.encs.distributed.corba.model.ClinicServiceHelper.read (i); } public void _write (org.omg.CORBA.portable.OutputStream o) { ca.concordia.encs.distributed.corba.model.ClinicServiceHelper.write (o, value); } public org.omg.CORBA.TypeCode _type () { return ca.concordia.encs.distributed.corba.model.ClinicServiceHelper.type (); } }
UTF-8
Java
1,044
java
ClinicServiceHolder.java
Java
[]
null
[]
package ca.concordia.encs.distributed.corba.model; /** * ca/concordia/encs/distributed/corba/model/ClinicServiceHolder.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from ClinicServices.idl * Monday, July 4, 2016 11:59:07 AM CDT */ public final class ClinicServiceHolder implements org.omg.CORBA.portable.Streamable { public ca.concordia.encs.distributed.corba.model.ClinicService value = null; public ClinicServiceHolder () { } public ClinicServiceHolder (ca.concordia.encs.distributed.corba.model.ClinicService initialValue) { value = initialValue; } public void _read (org.omg.CORBA.portable.InputStream i) { value = ca.concordia.encs.distributed.corba.model.ClinicServiceHelper.read (i); } public void _write (org.omg.CORBA.portable.OutputStream o) { ca.concordia.encs.distributed.corba.model.ClinicServiceHelper.write (o, value); } public org.omg.CORBA.TypeCode _type () { return ca.concordia.encs.distributed.corba.model.ClinicServiceHelper.type (); } }
1,044
0.747126
0.734674
38
26.473684
32.617992
99
false
false
0
0
0
0
0
0
0.263158
false
false
14
a4442d1f423debb8091a1e5738ac0f49c8434f34
30,399,778,561,398
f023ad84cd298cd584633ae6e7a975753ac3d1a7
/app/src/main/java/com/pdscjxy/serverapp/fragment/base/BaseFragment.java
a8beffd41019c2e507da7379aac71e76d5eb6e77
[]
no_license
1835434698/DemoApp
https://github.com/1835434698/DemoApp
3b9806ebeeecfcb0d38574665f74ee83a049f6aa
5f78a7a8be86877ef8b01f9efb67203cb80fc815
refs/heads/master
2021-08-31T16:57:15.984000
2017-12-22T04:37:33
2017-12-22T04:37:33
108,794,858
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pdscjxy.serverapp.fragment.base; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.pdscjxy.serverapp.R; import com.pdscjxy.serverapp.activity.base.BaseActivity; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by Administrator on 2017/10/26. */ public class BaseFragment extends Fragment { private Unbinder unbinder; public View root; // private LoadingView mLoadingView = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub root = inflater.inflate(R.layout.fragment_base, null); return root; } public void setView(int layoutResID) { LinearLayout content_linear = (LinearLayout) root.findViewById(R.id.fragment_content_view); content_linear.addView(View.inflate(getActivity(), layoutResID, null), new LinearLayout.LayoutParams(-1, -1)); unbinder = ButterKnife.bind(this,root); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } // /** 清除contentView里面的加载进度 */ // public void removeProgress() { // if (mLoadingView != null&&root!=null) { // LinearLayout contentView = (LinearLayout) root.findViewById(R.id.fragment_content_view); // contentView.removeView(mLoadingView.getLoadingView()); // mLoadingView = null; // } // } public View findViewById(int viewID){ return root.findViewById(viewID); } // /** 显示嵌入式进度条 */ // public void showProgress() { // removeProgress(); // addLoadView(); // } // // private void addLoadView() { // if (mLoadingView == null&&root!=null) { // mLoadingView = new LoadingView(getActivity()); // LinearLayout contentView = (LinearLayout) root.findViewById(R.id.fragment_content_view); // LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -1); // contentView.addView(mLoadingView.getLoadingView(), 0, params); // } // } @Override public void setUserVisibleHint(boolean isVisibleToUser) { // TODO Auto-generated method stub super.setUserVisibleHint(isVisibleToUser); if(getUserVisibleHint()&&root!=null) { delayLoad(); } } public void delayLoad(){ } public void showWaitDialog(String msg){ Activity activity= getActivity(); if(activity!=null&&!activity.isFinishing()){ if(activity instanceof BaseActivity){ ((BaseActivity)activity).showWaitDialog(msg); } } } public void hideWaitDialog(){ Activity activity= getActivity(); if(activity!=null&&!activity.isFinishing()){ if(activity instanceof BaseActivity){ ((BaseActivity)activity).hideWaitDialog(); } } } }
UTF-8
Java
3,185
java
BaseFragment.java
Java
[ { "context": ";\nimport butterknife.Unbinder;\n\n\n/**\n * Created by Administrator on 2017/10/26.\n */\n\npublic class BaseFragment ex", "end": 455, "score": 0.8910356760025024, "start": 442, "tag": "USERNAME", "value": "Administrator" } ]
null
[]
package com.pdscjxy.serverapp.fragment.base; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.pdscjxy.serverapp.R; import com.pdscjxy.serverapp.activity.base.BaseActivity; import butterknife.ButterKnife; import butterknife.Unbinder; /** * Created by Administrator on 2017/10/26. */ public class BaseFragment extends Fragment { private Unbinder unbinder; public View root; // private LoadingView mLoadingView = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub root = inflater.inflate(R.layout.fragment_base, null); return root; } public void setView(int layoutResID) { LinearLayout content_linear = (LinearLayout) root.findViewById(R.id.fragment_content_view); content_linear.addView(View.inflate(getActivity(), layoutResID, null), new LinearLayout.LayoutParams(-1, -1)); unbinder = ButterKnife.bind(this,root); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } // /** 清除contentView里面的加载进度 */ // public void removeProgress() { // if (mLoadingView != null&&root!=null) { // LinearLayout contentView = (LinearLayout) root.findViewById(R.id.fragment_content_view); // contentView.removeView(mLoadingView.getLoadingView()); // mLoadingView = null; // } // } public View findViewById(int viewID){ return root.findViewById(viewID); } // /** 显示嵌入式进度条 */ // public void showProgress() { // removeProgress(); // addLoadView(); // } // // private void addLoadView() { // if (mLoadingView == null&&root!=null) { // mLoadingView = new LoadingView(getActivity()); // LinearLayout contentView = (LinearLayout) root.findViewById(R.id.fragment_content_view); // LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -1); // contentView.addView(mLoadingView.getLoadingView(), 0, params); // } // } @Override public void setUserVisibleHint(boolean isVisibleToUser) { // TODO Auto-generated method stub super.setUserVisibleHint(isVisibleToUser); if(getUserVisibleHint()&&root!=null) { delayLoad(); } } public void delayLoad(){ } public void showWaitDialog(String msg){ Activity activity= getActivity(); if(activity!=null&&!activity.isFinishing()){ if(activity instanceof BaseActivity){ ((BaseActivity)activity).showWaitDialog(msg); } } } public void hideWaitDialog(){ Activity activity= getActivity(); if(activity!=null&&!activity.isFinishing()){ if(activity instanceof BaseActivity){ ((BaseActivity)activity).hideWaitDialog(); } } } }
3,185
0.644875
0.640432
102
29.892157
26.742016
118
false
false
0
0
0
0
0
0
0.480392
false
false
14
844079eca030decbdba49a40d45d02df2b3d3d84
28,862,180,237,870
32bd2c8ea56999a6dc94f02f793bad89dcfb37ac
/Queue/src/datastructures/Queue.java
1d80ff5468d0891a0f57fac408226e5d34be5260
[]
no_license
yash0508rajpal/Alorithms-and-DataStructures
https://github.com/yash0508rajpal/Alorithms-and-DataStructures
0fe2f0285e96149a3ea10d41545487f112aba0a3
ed3b53411f75f3eb1f04923afb4b9f50fe367656
refs/heads/master
2021-01-10T01:13:10.153000
2016-03-21T01:58:23
2016-03-21T01:58:23
53,879,122
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package datastructures; public class Queue{ private Node start; private Node end; private int size; public Queue(){ this.size = 0; start = null; end = null; } public void enqueue(int data){ Node nptr = new Node(data,null); size++; if(start == null){ start = nptr; end = start; } else{ end.setLink(nptr); end = nptr; } } public int getSize(){ return this.size; } public int dequeue(){ Node temp = start.getLink(); int data = start.getData(); start = temp; size --; return data; } public int front(){ return start.getData(); } public int end(){ return end.getData(); } public void display(){ if(size == 0){ System.out.println("queue is empty"); return; } if(start.getLink() == null){ System.out.println(start.getData()); return; } Node ptr = start; while(ptr.getLink()!= null){ System.out.print(ptr.getData() + "\t"); ptr = ptr.getLink(); } System.out.println(ptr.getData()); } }
UTF-8
Java
1,064
java
Queue.java
Java
[]
null
[]
package datastructures; public class Queue{ private Node start; private Node end; private int size; public Queue(){ this.size = 0; start = null; end = null; } public void enqueue(int data){ Node nptr = new Node(data,null); size++; if(start == null){ start = nptr; end = start; } else{ end.setLink(nptr); end = nptr; } } public int getSize(){ return this.size; } public int dequeue(){ Node temp = start.getLink(); int data = start.getData(); start = temp; size --; return data; } public int front(){ return start.getData(); } public int end(){ return end.getData(); } public void display(){ if(size == 0){ System.out.println("queue is empty"); return; } if(start.getLink() == null){ System.out.println(start.getData()); return; } Node ptr = start; while(ptr.getLink()!= null){ System.out.print(ptr.getData() + "\t"); ptr = ptr.getLink(); } System.out.println(ptr.getData()); } }
1,064
0.558271
0.556391
67
13.910448
11.626952
42
false
false
0
0
0
0
0
0
2.074627
false
false
14
faa90831d4095945687739e38070e98a074d40e8
25,048,249,283,157
50fa1ae480127fd75bf1cbe898a0c6c506dab57e
/src/main/java/JavaCore/ThreadJavaRush/Test11.java
1e3eaaf52ac412dad857383733ee7e2c3dfcbd5e
[]
no_license
ShabanovAn/spring-app1
https://github.com/ShabanovAn/spring-app1
d4d4fb9a4b2831fbccbfe7875f6a2406f48c2877
b2526c0424db2ccd9b361f4bca9ee63b6d010176
refs/heads/master
2023-01-06T17:08:51.452000
2020-10-27T13:02:55
2020-10-27T13:02:55
307,701,615
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package JavaCore.ThreadJavaRush; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Test11 { public static void main(String[] args) throws InterruptedException { Lock lock = new ReentrantLock(); Runnable task = () -> { lock.lock(); System.out.println("Thread"); lock.unlock(); }; lock.lock(); Thread t = new Thread(task); t.start(); System.out.println("Main"); Thread.currentThread().sleep(2000); lock.unlock(); } }
UTF-8
Java
585
java
Test11.java
Java
[]
null
[]
package JavaCore.ThreadJavaRush; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Test11 { public static void main(String[] args) throws InterruptedException { Lock lock = new ReentrantLock(); Runnable task = () -> { lock.lock(); System.out.println("Thread"); lock.unlock(); }; lock.lock(); Thread t = new Thread(task); t.start(); System.out.println("Main"); Thread.currentThread().sleep(2000); lock.unlock(); } }
585
0.589744
0.579487
21
26.857143
17.626511
72
false
false
0
0
0
0
0
0
0.666667
false
false
14
716fd223a0d88f05e5a62765a49bd75f45c24e80
18,794,776,889,668
924fc44c9f2b8e49a77e1bb686c8ad7b18bde904
/Film.java
20f38413ba8270355349cad0f8ed5da547ef5ea9
[]
no_license
lagvna/PP2013-CarBlackBox
https://github.com/lagvna/PP2013-CarBlackBox
09f722bf282712274f7e3978af0cf11d3cc45616
9212027a1d403fce2c8825aa96583a6b1b0f8926
refs/heads/master
2021-05-26T23:15:10.978000
2014-01-29T04:55:32
2014-01-29T04:55:32
13,617,158
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; /** * Class Film */ public class Film { // // Fields // public Minute[10] film; // // Constructors // public Film () { }; // // Methods // // // Accessor methods // /** * Set the value of film * @param newVar the new value of film */ public void setFilm ( Minute[10] newVar ) { film = newVar; } /** * Get the value of film * @return the value of film */ public Minute[10] getFilm ( ) { return film; } // // Other methods // /** * @return Film */ public Film makeFilm( ) { } /** */ public void addNextMinute( ) { } }
UTF-8
Java
664
java
Film.java
Java
[]
null
[]
import java.util.*; /** * Class Film */ public class Film { // // Fields // public Minute[10] film; // // Constructors // public Film () { }; // // Methods // // // Accessor methods // /** * Set the value of film * @param newVar the new value of film */ public void setFilm ( Minute[10] newVar ) { film = newVar; } /** * Get the value of film * @return the value of film */ public Minute[10] getFilm ( ) { return film; } // // Other methods // /** * @return Film */ public Film makeFilm( ) { } /** */ public void addNextMinute( ) { } }
664
0.486446
0.47741
64
9.359375
11.055778
45
false
false
0
0
0
0
0
0
0.078125
false
false
14
af6a5d21656a5bc46780d6270e71329c53d977f1
20,710,332,306,097
1fe45aa6a56d99634b75118c8033ef710f5613b2
/IndianPremiearLeageeMvvm/app/src/main/java/com/bridgelabz/indianpremiearleageemvvm/utility/HttpconnectionManager.java
fc8a019dc2f83afc1ba9541358bfbe52b668d645
[]
no_license
laxmannakka/AndroidApps
https://github.com/laxmannakka/AndroidApps
3b4dccfe8821fcd97ad5fad33f3fa3d30c5cd13a
03257960ae1af970a33c5080d93afce4a6ece81c
refs/heads/master
2021-01-20T22:16:08.497000
2016-07-13T04:38:23
2016-07-13T04:38:23
63,214,609
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bridgelabz.indianpremiearleageemvvm.utility; import android.databinding.BindingAdapter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.bridgelabz.indianpremiearleageemvvm.R; import com.squareup.picasso.Picasso; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by bridgelabz1 on 23/6/16. */ public class HttpconnectionManager { public static String getDataFromjson(String uri) { URL url; InputStream in; try { url = new URL(uri); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(httpURLConnection.getInputStream()); // Calling the convertStrean to String return convertStreamToString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private static String convertStreamToString(InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } public static Bitmap imageDownload(String uri) { URL url; InputStream image; try { url = new URL(uri); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); image = new BufferedInputStream(httpURLConnection.getInputStream()); return BitmapFactory.decodeStream(image); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @BindingAdapter({"bind:imageUrl"}) public static void loadImage(ImageView view, String imageUrl) { Picasso.with(view.getContext()) .load(imageUrl) .placeholder(R.drawable.images) .into(view); } }
UTF-8
Java
2,177
java
HttpconnectionManager.java
Java
[ { "context": "Exception;\nimport java.net.URL;\n\n/**\n * Created by bridgelabz1 on 23/6/16.\n */\n\npublic class HttpconnectionManag", "end": 511, "score": 0.9996294975280762, "start": 500, "tag": "USERNAME", "value": "bridgelabz1" } ]
null
[]
package com.bridgelabz.indianpremiearleageemvvm.utility; import android.databinding.BindingAdapter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageView; import com.bridgelabz.indianpremiearleageemvvm.R; import com.squareup.picasso.Picasso; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by bridgelabz1 on 23/6/16. */ public class HttpconnectionManager { public static String getDataFromjson(String uri) { URL url; InputStream in; try { url = new URL(uri); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(httpURLConnection.getInputStream()); // Calling the convertStrean to String return convertStreamToString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } private static String convertStreamToString(InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } public static Bitmap imageDownload(String uri) { URL url; InputStream image; try { url = new URL(uri); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); image = new BufferedInputStream(httpURLConnection.getInputStream()); return BitmapFactory.decodeStream(image); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @BindingAdapter({"bind:imageUrl"}) public static void loadImage(ImageView view, String imageUrl) { Picasso.with(view.getContext()) .load(imageUrl) .placeholder(R.drawable.images) .into(view); } }
2,177
0.647221
0.644465
77
27.259741
23.710594
91
false
false
0
0
0
0
0
0
0.454545
false
false
14
c677a296bb7b8170417bf9d2a15f626011103480
13,400,297,986,100
7b344cfbf25ce3fd5187b36c0824f57c504ebac1
/BowlingLeague/ejbModule/application/service/league/LeagueServiceRemote.java
04e0c92326be9f134a2dbc0920bfd771e75c5dce
[]
no_license
rafgitdz/bowlingproject-ferroukh-foucault
https://github.com/rafgitdz/bowlingproject-ferroukh-foucault
30738d6ffa7616a021ca522b4dc099f60776674b
db10a8dd4edc69203a05bb72bcc2385003a9b845
refs/heads/master
2021-01-25T06:06:04.183000
2012-01-06T02:48:57
2012-01-06T02:48:57
42,301,812
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package application.service.league; import javax.ejb.Remote; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; import domain.model.team.league.LeagueStatus; @WebService(name = "leagueService") @SOAPBinding(style = Style.RPC) @Remote public interface LeagueServiceRemote { @WebMethod public void deleteLeague(String name); @WebMethod public void startLeague(String leagueName); @WebMethod public String[] getTeams(String leagueName); @WebMethod public LeagueStatus getLeagueStatus(String leagueName); @WebMethod public void goNextRound(String leagueName); @WebMethod public boolean isCurrentRoundOver(String leagueName); @WebMethod public String[] getRanking(String leagueName); @WebMethod public int getScore(String teamName); @WebMethod public String[] getLeagues(); @WebMethod public String[] getTeamsLeftSideSchedule(String leagueName, int round); @WebMethod public String[] getTeamsRightSideSchedule(String leagueName, int round); @WebMethod public String getScoreChallenge(String leagueName, int round, String team1, String team2); @WebMethod public int getNumberRounds(String leagueName); }
UTF-8
Java
1,228
java
LeagueServiceRemote.java
Java
[]
null
[]
package application.service.league; import javax.ejb.Remote; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; import domain.model.team.league.LeagueStatus; @WebService(name = "leagueService") @SOAPBinding(style = Style.RPC) @Remote public interface LeagueServiceRemote { @WebMethod public void deleteLeague(String name); @WebMethod public void startLeague(String leagueName); @WebMethod public String[] getTeams(String leagueName); @WebMethod public LeagueStatus getLeagueStatus(String leagueName); @WebMethod public void goNextRound(String leagueName); @WebMethod public boolean isCurrentRoundOver(String leagueName); @WebMethod public String[] getRanking(String leagueName); @WebMethod public int getScore(String teamName); @WebMethod public String[] getLeagues(); @WebMethod public String[] getTeamsLeftSideSchedule(String leagueName, int round); @WebMethod public String[] getTeamsRightSideSchedule(String leagueName, int round); @WebMethod public String getScoreChallenge(String leagueName, int round, String team1, String team2); @WebMethod public int getNumberRounds(String leagueName); }
1,228
0.792345
0.790717
54
21.74074
22.301125
91
false
false
0
0
0
0
0
0
1.055556
false
false
14
b972f29e37358b62e63fcbeb47ff784ec6a8ccac
25,615,184,980,149
d1491e884f1484e156107169cd3079d531e2318c
/Admin.java
bc83cdd7e2655a4c7478cb209d40e43e60880c0c
[]
no_license
dhmzz/Enkapsulasi-dan-Inheritance-
https://github.com/dhmzz/Enkapsulasi-dan-Inheritance-
446cd5bf9c940c165309edce897687cf394e4ce1
a2d3f482ce2dd538a98d6d2fcfb3d358e406c0b5
refs/heads/master
2023-04-16T13:13:19.686000
2021-04-17T17:23:07
2021-04-17T17:23:07
358,936,578
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 toko1; /** * * @author Dhimaz Nur Ramadhan */ public class Admin { private String admin; float Harga; int Total; String Merk; public void display(){ System.out.println("-------------------------------------"); System.out.println("Smartphone yang tersedia di entry : "); System.out.println("1.Mi QuadCamera(4)"); System.out.println("2.Realme TripleCamera(3)"); System.out.println("3.Apple TripleCamera(3)"); System.out.println("-------------------------------------"); System.out.println("TV yang tersedia di entry(Jenis) : "); System.out.println("1.LG (LED TV)"); System.out.println("2.Samsung (LCD TV)"); System.out.println("3.Mi (SmartTV)"); System.out.println("-------------------------------------"); System.out.println("Kipas Angin yang tersedia di entry : "); System.out.println("1.LG 5inc"); System.out.println("2.Samsung 6inc"); System.out.println("3.Maspion 7inc"); System.out.println(""); } public void setadmin(String admin){ this.admin = admin; } public String getadmin(){ return admin; } public void setHarga(float Harga){ this.Harga=Harga; } public float getHarga(){ return Harga; } public void setTotal(int Total){ this.Total=Total; } public int getTotal(){ return Total; } public void setMerk(String Merk){ this.Merk = Merk; } public String getMerk(){ return Merk; } }
UTF-8
Java
1,846
java
Admin.java
Java
[ { "context": " the editor.\n */\npackage toko1;\n\n/**\n *\n * @author Dhimaz Nur Ramadhan\n */\npublic class Admin {\n private String admin", "end": 238, "score": 0.9998763799667358, "start": 219, "tag": "NAME", "value": "Dhimaz Nur Ramadhan" } ]
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 toko1; /** * * @author <NAME> */ public class Admin { private String admin; float Harga; int Total; String Merk; public void display(){ System.out.println("-------------------------------------"); System.out.println("Smartphone yang tersedia di entry : "); System.out.println("1.Mi QuadCamera(4)"); System.out.println("2.Realme TripleCamera(3)"); System.out.println("3.Apple TripleCamera(3)"); System.out.println("-------------------------------------"); System.out.println("TV yang tersedia di entry(Jenis) : "); System.out.println("1.LG (LED TV)"); System.out.println("2.Samsung (LCD TV)"); System.out.println("3.Mi (SmartTV)"); System.out.println("-------------------------------------"); System.out.println("Kipas Angin yang tersedia di entry : "); System.out.println("1.LG 5inc"); System.out.println("2.Samsung 6inc"); System.out.println("3.Maspion 7inc"); System.out.println(""); } public void setadmin(String admin){ this.admin = admin; } public String getadmin(){ return admin; } public void setHarga(float Harga){ this.Harga=Harga; } public float getHarga(){ return Harga; } public void setTotal(int Total){ this.Total=Total; } public int getTotal(){ return Total; } public void setMerk(String Merk){ this.Merk = Merk; } public String getMerk(){ return Merk; } }
1,833
0.535211
0.526544
65
27.4
21.97117
79
false
false
0
0
0
0
0
0
0.492308
false
false
14
6a2ca7952d16527f988ce0299ff0b7585658ba69
22,514,218,586,417
f22773ae7b058e3c62669f4adbd00d569419bd4c
/src/main/java/org/lieying/web/controller/JobHunterController.java
7852ca6963b9ed2069400e444353ce82ebc583be
[]
no_license
lieying-project/lieying-server
https://github.com/lieying-project/lieying-server
942a1c0acefd3dc790876cf2376eb127ccddd2b6
b78f852c46abaea7f2b5059e24328f830861fa46
refs/heads/main
2023-05-08T07:32:44.873000
2021-05-29T03:04:58
2021-05-29T03:04:58
326,411,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.lieying.web.controller; import com.alibaba.fastjson.JSON; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.lieying.bean.*; import org.lieying.core.CommonResult; import org.lieying.core.ResultCode; import org.lieying.core.ResultGenerator; import org.lieying.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @Api(value = "求职者信息接口", tags = "求职者") @RestController @RequestMapping("/jobHunter") public class JobHunterController { @Autowired private JobHunterService jobHunterService; @Autowired private JobHunterReportService jobHunterReportService; @Autowired private ResumeService resumeService; @Autowired private VolunteerExperienceService volunteerExperienceService; @Autowired private ProjectExperienceService projectExperienceService; @Autowired private CredentialService credentialService; @Autowired private EducationExperienceService educationExperienceService; @Autowired private InternshipExperienceService internshipExperienceService; @Autowired private SocialHomepageService socialHomepageService; /* * 查询所有求职者信息 */ @ApiOperation(value = "查询所有求职者", notes = "查询数据库中所有的求职者信息") @GetMapping(value = "/all", produces = "application/json;charset=UTF-8") public CommonResult allJobHunter() { return ResultGenerator.genSuccessfulResult(jobHunterService.queryAllJobHunter()); } /* * 查询单个求职者 * @param jobHunterId 求职者id * */ @ApiOperation(value = "查询单个求职者", notes = "根据求职者编号查询单个求职者信息") @ApiImplicitParams({ @ApiImplicitParam(name = "jobHunterId", value = "求职者编号", required = true, paramType = "query", dataType = "Integer"), }) @GetMapping(value = "/{jobHunterId}") public CommonResult getJobHunterById(@PathVariable int jobHunterId) { return ResultGenerator.genSuccessfulResult(jobHunterService.queryDetailJobHunterById(jobHunterId)); } /* * 求职者所有简历 * @param jobhunterId 简历id */ @ApiOperation(value = "查询求职者所有简历信息", notes = "根据求职者编号查询所有简历信息") @ApiImplicitParams({ @ApiImplicitParam(name = "jobHunterId", value = "求职者编号", required = true, paramType = "query", dataType = "Integer"), }) @GetMapping(value = "/{jobHunterId}/resumes") public CommonResult getJobHunterResumesByJobHunterId(@PathVariable int jobHunterId) { return ResultGenerator.genSuccessfulResult(resumeService.queryResumesByJobHunterId(jobHunterId)); } /* * 简历详情 * @param resumeId 简历id */ @ApiOperation(value = "查询单个简历信息", notes = "根据简历编号查询单个简历信息") @ApiImplicitParams({ @ApiImplicitParam(name = "resumeId", value = "简历编号", required = true, paramType = "query", dataType = "Integer"), }) @GetMapping(value = "/resume/{resumeId}") public CommonResult getResumeById(@PathVariable int resumeId) { return ResultGenerator.genSuccessfulResult(resumeService.queryResumeById(resumeId)); } /* * 添加简历 * */ @ApiOperation(value = "添加简历", notes = "查询数据库中单个简历信息") @PostMapping(value = "/resume/save") public CommonResult addResume(@RequestBody Resume resume) { return ResultGenerator.genEditSuccessfulResult(resumeService.addResume(resume)); } /* * 更新简历 * */ @ApiOperation(value = "更新简历", notes = "更新简历") @PostMapping(value = "/resume/update") public CommonResult updateResume(@RequestBody Resume resume) { return ResultGenerator.genEditSuccessfulResult(resumeService.modifyResume(resume)); } /* * 添加志愿经历 * */ @ApiOperation(value = "添加志愿经历", notes = "添加志愿经历") @PostMapping(value = "/resume/volunteer/save") public CommonResult addVolunteerExperience(@RequestBody VolunteerExperience volunteerExperience) { return ResultGenerator.genEditSuccessfulResult(volunteerExperienceService.addVolunteerExperience(volunteerExperience)); } /* * 更新志愿经历 * */ @ApiOperation(value = "更新志愿经历", notes = "更新志愿经历") @PostMapping(value = "/resume/volunteer/update") public CommonResult updateVolunteerExperience(@RequestBody VolunteerExperience volunteerExperience) { return ResultGenerator.genEditSuccessfulResult(volunteerExperienceService.modifyVolunteerExperience(volunteerExperience)); } /* * 添加项目经历 * */ @ApiOperation(value = "添加项目经历", notes = "添加项目经历") @PostMapping(value = "/resume/project/save") public CommonResult addProjectExperience(@RequestBody ProjectExperience projectExperience) { return ResultGenerator.genEditSuccessfulResult(projectExperienceService.addProjectExperience(projectExperience)); } /* * 更新项目经历 * */ @ApiOperation(value = "更新项目经历", notes = "更新项目经历") @PostMapping(value = "/resume/project/update") public CommonResult updateProjectExperience(@RequestBody ProjectExperience projectExperience) { return ResultGenerator.genEditSuccessfulResult(projectExperienceService.modifyProjectExperience(projectExperience)); } /* * 添加实习经历 * */ @ApiOperation(value = "添加实习经历", notes = "添加实习经历") @PostMapping(value = "/resume/internship/save") public CommonResult addInternshipExperience(@RequestBody InternshipExperience internshipExperience) { return ResultGenerator.genEditSuccessfulResult(internshipExperienceService.addInternshipExperience(internshipExperience)); } /* * 更新实习经历 * */ @ApiOperation(value = "更新实习经历", notes = "更新实习经历") @PostMapping(value = "/resume/internship/update") public CommonResult updateInternshipExperience(@RequestBody InternshipExperience internshipExperience) { return ResultGenerator.genEditSuccessfulResult(internshipExperienceService.modifyInternshipExperience(internshipExperience)); } /* * 添加资格证书 * */ @ApiOperation(value = "添加资格证书", notes = "添加资格证书") @PostMapping(value = "/resume/credential/save") public CommonResult addCredential(@RequestBody Credential credential) { return ResultGenerator.genEditSuccessfulResult(credentialService.addCredential(credential)); } /* * 更新资格证书 * */ @ApiOperation(value = "更新资格证书", notes = "更新资格证书") @PostMapping(value = "/resume/credential/update") public CommonResult updateCredential(@RequestBody Credential credential) { return ResultGenerator.genEditSuccessfulResult(credentialService.modifyCredential(credential)); } /* * 添加教育经历 * */ @ApiOperation(value = "添加教育经历", notes = "添加教育经历") @PostMapping(value = "/resume/education/save") public CommonResult saveEducationExperience(@RequestBody EducationExperience educationExperience) { System.out.println(educationExperience); return ResultGenerator.genEditSuccessfulResult(educationExperienceService.addEducationExperience(educationExperience)); } /* * 更新教育经历 * */ @ApiOperation(value = "更新教育经历", notes = "更新教育经历") @PutMapping(value = "/resume/education/update") public CommonResult updateEducationExperience(@RequestBody EducationExperience educationExperience) { return ResultGenerator.genEditSuccessfulResult(educationExperienceService.updateEducationExperience(educationExperience)); } /* * 添加社交主页 * */ @ApiOperation(value = "添加社交主页", notes = "添加社交主页") @PostMapping(value = "/resume/socialHomepage/save") public CommonResult saveSocialHomepage(@RequestBody SocialHomepage socialHomepage) { return ResultGenerator.genEditSuccessfulResult(socialHomepageService.addSocialhomepage(socialHomepage)); } /* * 更新社交主页 * */ @ApiOperation(value = "更新社交主页", notes = "更新社交主页") @PostMapping(value = "/resume/socialHomepage/update") public CommonResult updateSocialHomepage(@RequestBody SocialHomepage socialHomepage) { return ResultGenerator.genEditSuccessfulResult(socialHomepageService.modifySocialhomepage(socialHomepage)); } /* * 求职者登录 * */ @ApiOperation(value = "求职者登录", notes = "求职者登录") @PostMapping(value = "/login") public CommonResult jobHunterLogin(@RequestBody JobHunter jobHunter, HttpServletResponse response) { System.out.println(jobHunter); // String token = request.getHeader("token"); // jobHunter.setToken(token); JobHunter jobHunter1 = jobHunterService.queryJobHunterByUsernameAndPassword( jobHunter.getUsername(), jobHunter.getPassword()); System.out.println(jobHunter1 == null); if (jobHunter1 == null) { return null; } String token = jobHunter1.getToken(); System.out.println(token); //System.out.println(token.length()); response.setHeader("Access-Control-Expose-Headers", "token"); response.setHeader("token", token); return ResultGenerator.genSuccessfulResult(jobHunter1); } /* * 求职者注册 * */ @ApiOperation(value = "求职者注册", notes = "求职者注册") @PostMapping(value = "/register") public CommonResult jobHunterRegister(@RequestBody JobHunter jobHunter) { return ResultGenerator.genEditSuccessfulResult(jobHunterService.addJobHunter(jobHunter.getUsername(), jobHunter.getPassword(), jobHunter.getPhone())); } /* * 更新求职者 * */ @ApiOperation(value = "更新求职者", notes = "更新求职者") @PutMapping(value = "/update") public CommonResult updateJobHunter(@RequestBody JobHunter jobHunter) { return ResultGenerator.genEditSuccessfulResult(jobHunterService.modifyJobHunter(jobHunter)); } /* * 根据求职者id和职位id获取举报信息 * @param jobHunterId 求职者id * @param positionId 职位id */ @ApiOperation(value = "根据求职者id和职位id获取举报信息", notes = "根据求职者id和职位id获取举报信息") @GetMapping(value = "/report/{jobHunterId}/{positionId}") public CommonResult getJobHunterReportByJobHunterIdAndPositionId( @PathVariable int jobHunterId, @PathVariable int positionId) { return ResultGenerator.genSuccessfulResult(jobHunterReportService.queryJobHunterReportByJobHunterIdAndPositionId(jobHunterId, positionId)); } /* * 保存求职者举报信息 * */ @ApiOperation(value = "保存求职者举报信息", notes = "保存求职者举报信息") @PostMapping(value = "/report/save") public CommonResult saveJobHunterReport(@RequestBody JobHunterReport jobHunterReport) { return ResultGenerator.genEditSuccessfulResult(jobHunterReportService.addJobHunterReport(jobHunterReport)); } /* * 更新举报信息 * */ @ApiOperation(value = "更新求职者举报信息", notes = "更新求职者举报信息") @PutMapping(value = "/report/update") public CommonResult updateJobHunterReport(@RequestBody JobHunterReport jobHunterReport) { //System.out.println(jobHunterReport); return ResultGenerator.genEditSuccessfulResult(jobHunterReportService.updateJobHunterReport(jobHunterReport)); } }
UTF-8
Java
12,242
java
JobHunterController.java
Java
[ { "context": " return null;\n }\n String token = jobHunter1.getToken();\n System.out.println(tok", "end": 8906, "score": 0.51297926902771, "start": 8903, "tag": "KEY", "value": "job" }, { "context": "return null;\n }\n String token = jobHunter1.getToken();\n System.out.println(token);\n ", "end": 8913, "score": 0.4416993260383606, "start": 8907, "tag": "PASSWORD", "value": "unter1" }, { "context": "null;\n }\n String token = jobHunter1.getToken();\n System.out.println(token);\n //S", "end": 8922, "score": 0.554703414440155, "start": 8914, "tag": "KEY", "value": "getToken" } ]
null
[]
package org.lieying.web.controller; import com.alibaba.fastjson.JSON; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.lieying.bean.*; import org.lieying.core.CommonResult; import org.lieying.core.ResultCode; import org.lieying.core.ResultGenerator; import org.lieying.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @Api(value = "求职者信息接口", tags = "求职者") @RestController @RequestMapping("/jobHunter") public class JobHunterController { @Autowired private JobHunterService jobHunterService; @Autowired private JobHunterReportService jobHunterReportService; @Autowired private ResumeService resumeService; @Autowired private VolunteerExperienceService volunteerExperienceService; @Autowired private ProjectExperienceService projectExperienceService; @Autowired private CredentialService credentialService; @Autowired private EducationExperienceService educationExperienceService; @Autowired private InternshipExperienceService internshipExperienceService; @Autowired private SocialHomepageService socialHomepageService; /* * 查询所有求职者信息 */ @ApiOperation(value = "查询所有求职者", notes = "查询数据库中所有的求职者信息") @GetMapping(value = "/all", produces = "application/json;charset=UTF-8") public CommonResult allJobHunter() { return ResultGenerator.genSuccessfulResult(jobHunterService.queryAllJobHunter()); } /* * 查询单个求职者 * @param jobHunterId 求职者id * */ @ApiOperation(value = "查询单个求职者", notes = "根据求职者编号查询单个求职者信息") @ApiImplicitParams({ @ApiImplicitParam(name = "jobHunterId", value = "求职者编号", required = true, paramType = "query", dataType = "Integer"), }) @GetMapping(value = "/{jobHunterId}") public CommonResult getJobHunterById(@PathVariable int jobHunterId) { return ResultGenerator.genSuccessfulResult(jobHunterService.queryDetailJobHunterById(jobHunterId)); } /* * 求职者所有简历 * @param jobhunterId 简历id */ @ApiOperation(value = "查询求职者所有简历信息", notes = "根据求职者编号查询所有简历信息") @ApiImplicitParams({ @ApiImplicitParam(name = "jobHunterId", value = "求职者编号", required = true, paramType = "query", dataType = "Integer"), }) @GetMapping(value = "/{jobHunterId}/resumes") public CommonResult getJobHunterResumesByJobHunterId(@PathVariable int jobHunterId) { return ResultGenerator.genSuccessfulResult(resumeService.queryResumesByJobHunterId(jobHunterId)); } /* * 简历详情 * @param resumeId 简历id */ @ApiOperation(value = "查询单个简历信息", notes = "根据简历编号查询单个简历信息") @ApiImplicitParams({ @ApiImplicitParam(name = "resumeId", value = "简历编号", required = true, paramType = "query", dataType = "Integer"), }) @GetMapping(value = "/resume/{resumeId}") public CommonResult getResumeById(@PathVariable int resumeId) { return ResultGenerator.genSuccessfulResult(resumeService.queryResumeById(resumeId)); } /* * 添加简历 * */ @ApiOperation(value = "添加简历", notes = "查询数据库中单个简历信息") @PostMapping(value = "/resume/save") public CommonResult addResume(@RequestBody Resume resume) { return ResultGenerator.genEditSuccessfulResult(resumeService.addResume(resume)); } /* * 更新简历 * */ @ApiOperation(value = "更新简历", notes = "更新简历") @PostMapping(value = "/resume/update") public CommonResult updateResume(@RequestBody Resume resume) { return ResultGenerator.genEditSuccessfulResult(resumeService.modifyResume(resume)); } /* * 添加志愿经历 * */ @ApiOperation(value = "添加志愿经历", notes = "添加志愿经历") @PostMapping(value = "/resume/volunteer/save") public CommonResult addVolunteerExperience(@RequestBody VolunteerExperience volunteerExperience) { return ResultGenerator.genEditSuccessfulResult(volunteerExperienceService.addVolunteerExperience(volunteerExperience)); } /* * 更新志愿经历 * */ @ApiOperation(value = "更新志愿经历", notes = "更新志愿经历") @PostMapping(value = "/resume/volunteer/update") public CommonResult updateVolunteerExperience(@RequestBody VolunteerExperience volunteerExperience) { return ResultGenerator.genEditSuccessfulResult(volunteerExperienceService.modifyVolunteerExperience(volunteerExperience)); } /* * 添加项目经历 * */ @ApiOperation(value = "添加项目经历", notes = "添加项目经历") @PostMapping(value = "/resume/project/save") public CommonResult addProjectExperience(@RequestBody ProjectExperience projectExperience) { return ResultGenerator.genEditSuccessfulResult(projectExperienceService.addProjectExperience(projectExperience)); } /* * 更新项目经历 * */ @ApiOperation(value = "更新项目经历", notes = "更新项目经历") @PostMapping(value = "/resume/project/update") public CommonResult updateProjectExperience(@RequestBody ProjectExperience projectExperience) { return ResultGenerator.genEditSuccessfulResult(projectExperienceService.modifyProjectExperience(projectExperience)); } /* * 添加实习经历 * */ @ApiOperation(value = "添加实习经历", notes = "添加实习经历") @PostMapping(value = "/resume/internship/save") public CommonResult addInternshipExperience(@RequestBody InternshipExperience internshipExperience) { return ResultGenerator.genEditSuccessfulResult(internshipExperienceService.addInternshipExperience(internshipExperience)); } /* * 更新实习经历 * */ @ApiOperation(value = "更新实习经历", notes = "更新实习经历") @PostMapping(value = "/resume/internship/update") public CommonResult updateInternshipExperience(@RequestBody InternshipExperience internshipExperience) { return ResultGenerator.genEditSuccessfulResult(internshipExperienceService.modifyInternshipExperience(internshipExperience)); } /* * 添加资格证书 * */ @ApiOperation(value = "添加资格证书", notes = "添加资格证书") @PostMapping(value = "/resume/credential/save") public CommonResult addCredential(@RequestBody Credential credential) { return ResultGenerator.genEditSuccessfulResult(credentialService.addCredential(credential)); } /* * 更新资格证书 * */ @ApiOperation(value = "更新资格证书", notes = "更新资格证书") @PostMapping(value = "/resume/credential/update") public CommonResult updateCredential(@RequestBody Credential credential) { return ResultGenerator.genEditSuccessfulResult(credentialService.modifyCredential(credential)); } /* * 添加教育经历 * */ @ApiOperation(value = "添加教育经历", notes = "添加教育经历") @PostMapping(value = "/resume/education/save") public CommonResult saveEducationExperience(@RequestBody EducationExperience educationExperience) { System.out.println(educationExperience); return ResultGenerator.genEditSuccessfulResult(educationExperienceService.addEducationExperience(educationExperience)); } /* * 更新教育经历 * */ @ApiOperation(value = "更新教育经历", notes = "更新教育经历") @PutMapping(value = "/resume/education/update") public CommonResult updateEducationExperience(@RequestBody EducationExperience educationExperience) { return ResultGenerator.genEditSuccessfulResult(educationExperienceService.updateEducationExperience(educationExperience)); } /* * 添加社交主页 * */ @ApiOperation(value = "添加社交主页", notes = "添加社交主页") @PostMapping(value = "/resume/socialHomepage/save") public CommonResult saveSocialHomepage(@RequestBody SocialHomepage socialHomepage) { return ResultGenerator.genEditSuccessfulResult(socialHomepageService.addSocialhomepage(socialHomepage)); } /* * 更新社交主页 * */ @ApiOperation(value = "更新社交主页", notes = "更新社交主页") @PostMapping(value = "/resume/socialHomepage/update") public CommonResult updateSocialHomepage(@RequestBody SocialHomepage socialHomepage) { return ResultGenerator.genEditSuccessfulResult(socialHomepageService.modifySocialhomepage(socialHomepage)); } /* * 求职者登录 * */ @ApiOperation(value = "求职者登录", notes = "求职者登录") @PostMapping(value = "/login") public CommonResult jobHunterLogin(@RequestBody JobHunter jobHunter, HttpServletResponse response) { System.out.println(jobHunter); // String token = request.getHeader("token"); // jobHunter.setToken(token); JobHunter jobHunter1 = jobHunterService.queryJobHunterByUsernameAndPassword( jobHunter.getUsername(), jobHunter.getPassword()); System.out.println(jobHunter1 == null); if (jobHunter1 == null) { return null; } String token = jobH<PASSWORD>.getToken(); System.out.println(token); //System.out.println(token.length()); response.setHeader("Access-Control-Expose-Headers", "token"); response.setHeader("token", token); return ResultGenerator.genSuccessfulResult(jobHunter1); } /* * 求职者注册 * */ @ApiOperation(value = "求职者注册", notes = "求职者注册") @PostMapping(value = "/register") public CommonResult jobHunterRegister(@RequestBody JobHunter jobHunter) { return ResultGenerator.genEditSuccessfulResult(jobHunterService.addJobHunter(jobHunter.getUsername(), jobHunter.getPassword(), jobHunter.getPhone())); } /* * 更新求职者 * */ @ApiOperation(value = "更新求职者", notes = "更新求职者") @PutMapping(value = "/update") public CommonResult updateJobHunter(@RequestBody JobHunter jobHunter) { return ResultGenerator.genEditSuccessfulResult(jobHunterService.modifyJobHunter(jobHunter)); } /* * 根据求职者id和职位id获取举报信息 * @param jobHunterId 求职者id * @param positionId 职位id */ @ApiOperation(value = "根据求职者id和职位id获取举报信息", notes = "根据求职者id和职位id获取举报信息") @GetMapping(value = "/report/{jobHunterId}/{positionId}") public CommonResult getJobHunterReportByJobHunterIdAndPositionId( @PathVariable int jobHunterId, @PathVariable int positionId) { return ResultGenerator.genSuccessfulResult(jobHunterReportService.queryJobHunterReportByJobHunterIdAndPositionId(jobHunterId, positionId)); } /* * 保存求职者举报信息 * */ @ApiOperation(value = "保存求职者举报信息", notes = "保存求职者举报信息") @PostMapping(value = "/report/save") public CommonResult saveJobHunterReport(@RequestBody JobHunterReport jobHunterReport) { return ResultGenerator.genEditSuccessfulResult(jobHunterReportService.addJobHunterReport(jobHunterReport)); } /* * 更新举报信息 * */ @ApiOperation(value = "更新求职者举报信息", notes = "更新求职者举报信息") @PutMapping(value = "/report/update") public CommonResult updateJobHunterReport(@RequestBody JobHunterReport jobHunterReport) { //System.out.println(jobHunterReport); return ResultGenerator.genEditSuccessfulResult(jobHunterReportService.updateJobHunterReport(jobHunterReport)); } }
12,246
0.710932
0.710394
303
35.831684
37.096359
158
false
false
0
0
0
0
0
0
0.363036
false
false
14
650f42c100fb6369ee811225d1a3ab361dad24c9
19,447,611,941,744
5a020d266ce13abb98ccf2d449704a7eff738a9e
/src/main/java/game/core/Players/PlayerFactory.java
23a3f04b5991b49ad964b4f08403cfbeff71459a
[]
no_license
Katerina-codes/tic_tac_toe_java
https://github.com/Katerina-codes/tic_tac_toe_java
cc89358da6917b1b1cf4ba60e7814cfbbe370086
962b18b9b99018692be91cedc02b0423e3d95b93
refs/heads/master
2021-05-05T06:39:04.954000
2018-05-08T08:29:37
2018-05-08T08:29:37
118,812,729
1
0
null
false
2018-05-08T08:29:38
2018-01-24T19:37:53
2018-04-25T06:43:34
2018-05-08T08:29:38
281
1
0
2
Java
false
null
package game.core.Players; import game.core.Mark; import game.core.UI; import java.util.Arrays; import java.util.List; import static game.core.Mark.O; import static game.core.Mark.X; public class PlayerFactory { private final UI ui; private final Mark playerOne; private final Mark playerTwo; public PlayerFactory(UI ui) { this.ui = ui; this.playerOne = X; this.playerTwo = O; } public List<Player> getPlayerTypes(String players) { Player[] humanVsHuman = {new HumanPlayer(ui, playerOne), new HumanPlayer(ui, playerTwo)}; Player[] humanVsComputer = {new HumanPlayer(ui, playerOne), new Computer(playerTwo)}; Player[] computerVsHuman = {new Computer(playerOne), new HumanPlayer(ui, playerTwo)}; Player[] computerVsComputer = {new Computer(playerOne), new Computer(playerTwo)}; Player[] humanVsUnbeatablePlayer = {new HumanPlayer(ui, playerOne), new UnbeatableComputer(playerTwo)}; Player[] unbeatablePlayerVsHuman = {new UnbeatableComputer(playerOne), new HumanPlayer(ui, playerTwo)}; Player[] unbeatableVsUnbeatable = {new UnbeatableComputer(playerOne), new UnbeatableComputer(playerTwo)}; switch (players) { case UI.HUMAN_VS_HUMAN: return Arrays.asList(humanVsHuman); case UI.HUMAN_VS_COMPUTER: return Arrays.asList(humanVsComputer); case UI.COMPUTER_VS_HUMAN: return Arrays.asList(computerVsHuman); case UI.COMPUTER_VS_COMPUTER: return Arrays.asList(computerVsComputer); case UI.HUMAN_VS_UNBEATABLE_PLAYER: return Arrays.asList(humanVsUnbeatablePlayer); case UI.UNBEATABLE_PLAYER_VS_HUMAN: return Arrays.asList(unbeatablePlayerVsHuman); case UI.UNBEATABLE_PLAYER_VS_UNBEATABLE_PLAYER: return Arrays.asList(unbeatableVsUnbeatable); default: throw new RuntimeException("Unsupported player type"); } } }
UTF-8
Java
2,060
java
PlayerFactory.java
Java
[]
null
[]
package game.core.Players; import game.core.Mark; import game.core.UI; import java.util.Arrays; import java.util.List; import static game.core.Mark.O; import static game.core.Mark.X; public class PlayerFactory { private final UI ui; private final Mark playerOne; private final Mark playerTwo; public PlayerFactory(UI ui) { this.ui = ui; this.playerOne = X; this.playerTwo = O; } public List<Player> getPlayerTypes(String players) { Player[] humanVsHuman = {new HumanPlayer(ui, playerOne), new HumanPlayer(ui, playerTwo)}; Player[] humanVsComputer = {new HumanPlayer(ui, playerOne), new Computer(playerTwo)}; Player[] computerVsHuman = {new Computer(playerOne), new HumanPlayer(ui, playerTwo)}; Player[] computerVsComputer = {new Computer(playerOne), new Computer(playerTwo)}; Player[] humanVsUnbeatablePlayer = {new HumanPlayer(ui, playerOne), new UnbeatableComputer(playerTwo)}; Player[] unbeatablePlayerVsHuman = {new UnbeatableComputer(playerOne), new HumanPlayer(ui, playerTwo)}; Player[] unbeatableVsUnbeatable = {new UnbeatableComputer(playerOne), new UnbeatableComputer(playerTwo)}; switch (players) { case UI.HUMAN_VS_HUMAN: return Arrays.asList(humanVsHuman); case UI.HUMAN_VS_COMPUTER: return Arrays.asList(humanVsComputer); case UI.COMPUTER_VS_HUMAN: return Arrays.asList(computerVsHuman); case UI.COMPUTER_VS_COMPUTER: return Arrays.asList(computerVsComputer); case UI.HUMAN_VS_UNBEATABLE_PLAYER: return Arrays.asList(humanVsUnbeatablePlayer); case UI.UNBEATABLE_PLAYER_VS_HUMAN: return Arrays.asList(unbeatablePlayerVsHuman); case UI.UNBEATABLE_PLAYER_VS_UNBEATABLE_PLAYER: return Arrays.asList(unbeatableVsUnbeatable); default: throw new RuntimeException("Unsupported player type"); } } }
2,060
0.658738
0.658738
53
37.867924
31.66275
113
false
false
0
0
0
0
0
0
0.773585
false
false
14
6171b330e34c6706f0ec576c8513ac2eab767d9f
29,884,382,466,235
33f3fde6098114744d17b0dd0fbb34120bb58d60
/src/com/lbl/regprecise/ent/AssignIdentityGenerator.java
57309611c33118b9bd81ed8b040953af28908211
[]
no_license
novichkov-lab/RegPreciseDao
https://github.com/novichkov-lab/RegPreciseDao
a0ce0c287486fa058ec716ac1983d61e376f53f0
08ac0b8d21d917a052db2a010398b60ab1fe16cb
refs/heads/master
2020-12-26T11:42:06.780000
2015-01-16T08:54:50
2015-01-16T08:54:50
28,799,028
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lbl.regprecise.ent; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; import org.hibernate.id.Assigned; import org.hibernate.id.IdentityGenerator; /** * @author Pavel Novichkov * */ public class AssignIdentityGenerator extends IdentityGenerator{ public static final int IDENTITY_GENERATOR_TYPE = 0; public static final int ASSIGN_GENERATOR_TYPE = 1; public static int generatorType = IDENTITY_GENERATOR_TYPE; private static Assigned assignGenerator = new Assigned(); public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { switch(generatorType) { case IDENTITY_GENERATOR_TYPE: return super.generate(session, obj); case ASSIGN_GENERATOR_TYPE: return assignGenerator.generate(session, obj); } return 0; } }
UTF-8
Java
872
java
AssignIdentityGenerator.java
Java
[ { "context": "rg.hibernate.id.IdentityGenerator;\n\n/**\n * @author Pavel Novichkov\n *\n */\npublic class AssignIdentityGenerator exten", "end": 260, "score": 0.9997892379760742, "start": 245, "tag": "NAME", "value": "Pavel Novichkov" } ]
null
[]
package com.lbl.regprecise.ent; import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; import org.hibernate.id.Assigned; import org.hibernate.id.IdentityGenerator; /** * @author <NAME> * */ public class AssignIdentityGenerator extends IdentityGenerator{ public static final int IDENTITY_GENERATOR_TYPE = 0; public static final int ASSIGN_GENERATOR_TYPE = 1; public static int generatorType = IDENTITY_GENERATOR_TYPE; private static Assigned assignGenerator = new Assigned(); public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { switch(generatorType) { case IDENTITY_GENERATOR_TYPE: return super.generate(session, obj); case ASSIGN_GENERATOR_TYPE: return assignGenerator.generate(session, obj); } return 0; } }
863
0.774083
0.770642
35
23.914286
25.427063
77
false
false
0
0
0
0
0
0
1.314286
false
false
14
3cb29fee8ee0f7029fda773b74472ebea6ffb99b
21,251,498,200,677
00698a323994e911ac41d881b3f09893b567f4b3
/bataille/src/main/java/upmc/game/Game.java
695ea987b13439bbbbef05f1cdcb31c59d7260f4
[ "Apache-2.0" ]
permissive
JKoehren/la-bataille
https://github.com/JKoehren/la-bataille
994bbde81319cbd2a86beda176533775328bea8a
0dc57be9627f9ab2442183e6e578d3b7a79eb16f
refs/heads/master
2021-07-12T17:20:03.051000
2017-10-14T20:57:44
2017-10-14T20:57:44
103,251,482
0
0
null
true
2017-09-12T09:36:58
2017-09-12T09:36:58
2017-09-10T18:19:37
2017-09-10T18:37:40
8
0
0
0
null
null
null
package upmc.game; import java.util.Scanner; public class Game { private Joueur J1; private Joueur J2; private Joueur winner; private boolean win; private boolean joker = false; public Scanner console = new Scanner( System.in ); private int nbCartes; private Paquet jeuDeCarte = new Paquet(); public Game( Joueur Player1, Joueur Player2, int nombreC, String modeplay ) { //Assignation des joueurs et du nombre de carte J1 = Player1; J2 = Player2; if( nombreC == 54 ) { joker = true; nombreC -= 2 ; } nbCartes = nombreC; //Creation du paquet de carte for( int i = 0 ; i < 4 ; i++ ) { //4 Couleurs for( int j = 13 - ( nbCartes / 4 ) ; j < 13 ; j++ ) { //13 cartes dans un paquet de 52, 8 dans un de 32 jeuDeCarte.addCard( new Carte( j, i ) ); } } if( joker ) { //2 Joker du paquet de 54 jeuDeCarte.addCard(new Carte(13,5)); jeuDeCarte.addCard(new Carte(13,5)); nbCartes += 2; } win = false; //Creation des decks joueur //Pour reinitialiser les mains des joueurs en cas de restart J1.createPaquet(); J2.createPaquet(); //Melange des cartes jeuDeCarte.melange(); //Attribution des cartes en boucle inversee (plus rapide) for( int i = nbCartes - 1 ; i >= 0 ; i-- ) { if( i > ( nbCartes / 2 -1 ) ) { J1.deck.addCard( jeuDeCarte.getCard( i ) ); } else { J2.deck.addCard( jeuDeCarte.getCard( i ) ); } } System.out.println( "Appuyer sur entree pour retourner une carte chacun ('exit' pour quitter le jeu)" ); if( modeplay == "points" ) { modePts(); } else { modeCartes(); } System.out.print( "\nET LE GAGNANT EST : " + winner ); if ( modeplay == "points" ) System.out.print( " avec " + winner.nbPts() + " points" ); System.out.println( " !!!" ); } //Tour de jeu mode points private void modePts() { do { System.out.flush(); if ( console.nextLine().equals( "exit" ) ) System.exit( 0 ); System.out.println( J1 + "(" + J1.nbPts() + "pts) : " + J1.deck.getCard( 0 ) + " VS " + J2.deck.getCard( 0 ) + " : " + J2 + "(" + J2.nbPts() + "pts)" ); if( J1.deck.getCard( 0 ).compare( J2.deck.getCard( 0 ) ) != 0){ switch( J1.deck.getCard( 0 ).compare( J2.deck.getCard( 0 ) ) ) { case 1: J1.addPts(); winner = J1; break; case 2: J2.addPts(); winner = J2; break; } System.out.println( winner + " gagne 1 point -> total:" + winner.nbPts() ); }else{ System.out.println( "Bataille ! 2 points chacun" ); J1.addPts(); J1.addPts(); J2.addPts(); J2.addPts(); } J1.deck.removeCard( J1.deck.getCard( 0 ) ); J2.deck.removeCard( J2.deck.getCard( 0 ) ); if( J1.deck.nbCard() == 0 ) { win=true; winner = new Joueur( "Egalite parfaite ! Incroyable" ); if( J1.nbPts() > J2.nbPts() ) winner = J1; if( J2.nbPts() > J1.nbPts() ) winner = J2; } } while ( !win ); } //Tour de jeu mode carte private void modeCartes() { do { //Pour des raisons de facilite, les paquets sont melanges a chaque tirage J1.deck.melange(); J2.deck.melange(); System.out.flush(); if ( console.nextLine().equals( "exit" ) ) System.exit( 0 ); System.out.println( J1 + "(" + J1.deck.nbCard() + ") : " + J1.deck.getCard( 0 ) + " VS " + J2.deck.getCard( 0 ) + " : " + J2 + "(" + J2.deck.nbCard() + ")" ); //Resultat de manche resultCarte( J1.deck.getCard( 0 ).compare( J2.deck.getCard( 0 ) ) ); if( J1.deck.nbCard() == 0 ) { winner = J2; win = true; } if( J2.deck.nbCard() == 0 ) { winner = J1; win = true; } } while( !win ); } //Algo du tour pour mode carte private void resultCarte( int res ) { switch( res ) { //J1 gagne case 1: System.out.println( J1 + "(" + ( J1.deck.nbCard() + 1 ) + ") remporte la carte de " + J2 + "(" + ( J2.deck.nbCard() - 1 ) + ") !\n" ); J1.deck.addCard( J2.deck.getCard( 0 ) ); J2.deck.removeCard( J2.deck.getCard( 0 ) ); break; //J2 gagne case 2: System.out.println( J1 + "(" + ( J1.deck.nbCard() - 1 ) + ") offre sa carte a  " + J2 + "(" + ( J2.deck.nbCard() + 1 ) + ") !\n" ); J2.deck.addCard( J1.deck.getCard( 0 ) ); J1.deck.removeCard( J1.deck.getCard( 0 ) ); break; //Bataille case 0: int i = 0; while( J1.deck.getCard( i ).compare( J2.deck.getCard( i ) ) == 0 ) { if( J1.deck.nbCard() < i + 2 ) { System.out.println( J1 + "n'a plus assez de cartes" ); winner=J2; win=true; return; } if( J1.deck.nbCard() < i + 2 ) { System.out.println( J2 + "n'a plus assez de cartes" ); winner=J1; win=true; return; } System.out.println( "BATAILLE !\n" + J1 + "(" + J1.deck.nbCard() + ") : Carte cachee --- Carte cachee : " + J2 + "(" + J2.deck.nbCard() + ")" ); System.out.println( J1 + "(" + J1.deck.nbCard() + ") : " + J1.deck.getCard( i+2 ) + " VS " + J2.deck.getCard( i+2 ) + " : " + J2 + "(" + J2.deck.nbCard() + ")" ); i += 2; } if( J1.deck.getCard( i ).compare( J2.deck.getCard( i ) ) == 1 ){ winner = J1; for( int j = 0; j <= i; j++ ) { J1.deck.addCard( J2.deck.getCard( j ) ); J2.deck.removeCard( J2.deck.getCard( j ) ); } }else{ winner = J2; for( int j = 0; j <= i; j++ ) { J2.deck.addCard( J1.deck.getCard( j ) ); J1.deck.removeCard( J1.deck.getCard( j ) ); } } System.out.println( winner + " gagne cette petite bataille et remporte " + ( i + 1 ) + " cartes !\n" ); break; } } }
ISO-8859-1
Java
5,930
java
Game.java
Java
[]
null
[]
package upmc.game; import java.util.Scanner; public class Game { private Joueur J1; private Joueur J2; private Joueur winner; private boolean win; private boolean joker = false; public Scanner console = new Scanner( System.in ); private int nbCartes; private Paquet jeuDeCarte = new Paquet(); public Game( Joueur Player1, Joueur Player2, int nombreC, String modeplay ) { //Assignation des joueurs et du nombre de carte J1 = Player1; J2 = Player2; if( nombreC == 54 ) { joker = true; nombreC -= 2 ; } nbCartes = nombreC; //Creation du paquet de carte for( int i = 0 ; i < 4 ; i++ ) { //4 Couleurs for( int j = 13 - ( nbCartes / 4 ) ; j < 13 ; j++ ) { //13 cartes dans un paquet de 52, 8 dans un de 32 jeuDeCarte.addCard( new Carte( j, i ) ); } } if( joker ) { //2 Joker du paquet de 54 jeuDeCarte.addCard(new Carte(13,5)); jeuDeCarte.addCard(new Carte(13,5)); nbCartes += 2; } win = false; //Creation des decks joueur //Pour reinitialiser les mains des joueurs en cas de restart J1.createPaquet(); J2.createPaquet(); //Melange des cartes jeuDeCarte.melange(); //Attribution des cartes en boucle inversee (plus rapide) for( int i = nbCartes - 1 ; i >= 0 ; i-- ) { if( i > ( nbCartes / 2 -1 ) ) { J1.deck.addCard( jeuDeCarte.getCard( i ) ); } else { J2.deck.addCard( jeuDeCarte.getCard( i ) ); } } System.out.println( "Appuyer sur entree pour retourner une carte chacun ('exit' pour quitter le jeu)" ); if( modeplay == "points" ) { modePts(); } else { modeCartes(); } System.out.print( "\nET LE GAGNANT EST : " + winner ); if ( modeplay == "points" ) System.out.print( " avec " + winner.nbPts() + " points" ); System.out.println( " !!!" ); } //Tour de jeu mode points private void modePts() { do { System.out.flush(); if ( console.nextLine().equals( "exit" ) ) System.exit( 0 ); System.out.println( J1 + "(" + J1.nbPts() + "pts) : " + J1.deck.getCard( 0 ) + " VS " + J2.deck.getCard( 0 ) + " : " + J2 + "(" + J2.nbPts() + "pts)" ); if( J1.deck.getCard( 0 ).compare( J2.deck.getCard( 0 ) ) != 0){ switch( J1.deck.getCard( 0 ).compare( J2.deck.getCard( 0 ) ) ) { case 1: J1.addPts(); winner = J1; break; case 2: J2.addPts(); winner = J2; break; } System.out.println( winner + " gagne 1 point -> total:" + winner.nbPts() ); }else{ System.out.println( "Bataille ! 2 points chacun" ); J1.addPts(); J1.addPts(); J2.addPts(); J2.addPts(); } J1.deck.removeCard( J1.deck.getCard( 0 ) ); J2.deck.removeCard( J2.deck.getCard( 0 ) ); if( J1.deck.nbCard() == 0 ) { win=true; winner = new Joueur( "Egalite parfaite ! Incroyable" ); if( J1.nbPts() > J2.nbPts() ) winner = J1; if( J2.nbPts() > J1.nbPts() ) winner = J2; } } while ( !win ); } //Tour de jeu mode carte private void modeCartes() { do { //Pour des raisons de facilite, les paquets sont melanges a chaque tirage J1.deck.melange(); J2.deck.melange(); System.out.flush(); if ( console.nextLine().equals( "exit" ) ) System.exit( 0 ); System.out.println( J1 + "(" + J1.deck.nbCard() + ") : " + J1.deck.getCard( 0 ) + " VS " + J2.deck.getCard( 0 ) + " : " + J2 + "(" + J2.deck.nbCard() + ")" ); //Resultat de manche resultCarte( J1.deck.getCard( 0 ).compare( J2.deck.getCard( 0 ) ) ); if( J1.deck.nbCard() == 0 ) { winner = J2; win = true; } if( J2.deck.nbCard() == 0 ) { winner = J1; win = true; } } while( !win ); } //Algo du tour pour mode carte private void resultCarte( int res ) { switch( res ) { //J1 gagne case 1: System.out.println( J1 + "(" + ( J1.deck.nbCard() + 1 ) + ") remporte la carte de " + J2 + "(" + ( J2.deck.nbCard() - 1 ) + ") !\n" ); J1.deck.addCard( J2.deck.getCard( 0 ) ); J2.deck.removeCard( J2.deck.getCard( 0 ) ); break; //J2 gagne case 2: System.out.println( J1 + "(" + ( J1.deck.nbCard() - 1 ) + ") offre sa carte a  " + J2 + "(" + ( J2.deck.nbCard() + 1 ) + ") !\n" ); J2.deck.addCard( J1.deck.getCard( 0 ) ); J1.deck.removeCard( J1.deck.getCard( 0 ) ); break; //Bataille case 0: int i = 0; while( J1.deck.getCard( i ).compare( J2.deck.getCard( i ) ) == 0 ) { if( J1.deck.nbCard() < i + 2 ) { System.out.println( J1 + "n'a plus assez de cartes" ); winner=J2; win=true; return; } if( J1.deck.nbCard() < i + 2 ) { System.out.println( J2 + "n'a plus assez de cartes" ); winner=J1; win=true; return; } System.out.println( "BATAILLE !\n" + J1 + "(" + J1.deck.nbCard() + ") : Carte cachee --- Carte cachee : " + J2 + "(" + J2.deck.nbCard() + ")" ); System.out.println( J1 + "(" + J1.deck.nbCard() + ") : " + J1.deck.getCard( i+2 ) + " VS " + J2.deck.getCard( i+2 ) + " : " + J2 + "(" + J2.deck.nbCard() + ")" ); i += 2; } if( J1.deck.getCard( i ).compare( J2.deck.getCard( i ) ) == 1 ){ winner = J1; for( int j = 0; j <= i; j++ ) { J1.deck.addCard( J2.deck.getCard( j ) ); J2.deck.removeCard( J2.deck.getCard( j ) ); } }else{ winner = J2; for( int j = 0; j <= i; j++ ) { J2.deck.addCard( J1.deck.getCard( j ) ); J1.deck.removeCard( J1.deck.getCard( j ) ); } } System.out.println( winner + " gagne cette petite bataille et remporte " + ( i + 1 ) + " cartes !\n" ); break; } } }
5,930
0.512228
0.482037
206
26.781553
31.316669
167
false
false
0
0
0
0
0
0
3.398058
false
false
14
c2b33a6ec82a261fc1b27fe4e765478778450b70
18,202,071,432,468
fba9eea182c4d2040c969250af42597aca7a2265
/morank/src/main/java/searchdto/commentsVO.java
b38f23c2b64bb7f578f00e1435291d3c2f75b559
[]
no_license
What-The-Pork/web_html
https://github.com/What-The-Pork/web_html
b11040aa85bc56763e2a1847c28197ec67c39d4c
09412ba2bb2e80217e03c3388a4ae7c5c54878c4
refs/heads/master
2023-09-02T06:27:38.777000
2021-10-25T08:41:21
2021-10-25T08:41:21
369,132,228
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package searchdto; // ´ñ±Û ÀÚ¹Ù ºóÁî public class commentsVO { private String info_id; private String user_img; private String user_id; private String comments_info; private int comment_id; public String getInfo_id() { return info_id; } public void setInfo_id(String info_id) { this.info_id = info_id; } public String getUser_img() { return user_img; } public void setUser_img(String user_img) { this.user_img = user_img; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getComments_info() { return comments_info; } public void setComments_info(String comments_info) { this.comments_info = comments_info; } public int getComment_id() { return comment_id; } public void setComment_id(int comment_id) { this.comment_id = comment_id; } public commentsVO() { } public commentsVO(String info_id, String user_img, String user_id, String comments_info, int comment_id) { super(); this.info_id = info_id; this.user_img = user_img; this.user_id = user_id; this.comments_info = comments_info; this.comment_id = comment_id; } }
WINDOWS-1252
Java
1,206
java
commentsVO.java
Java
[]
null
[]
package searchdto; // ´ñ±Û ÀÚ¹Ù ºóÁî public class commentsVO { private String info_id; private String user_img; private String user_id; private String comments_info; private int comment_id; public String getInfo_id() { return info_id; } public void setInfo_id(String info_id) { this.info_id = info_id; } public String getUser_img() { return user_img; } public void setUser_img(String user_img) { this.user_img = user_img; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getComments_info() { return comments_info; } public void setComments_info(String comments_info) { this.comments_info = comments_info; } public int getComment_id() { return comment_id; } public void setComment_id(int comment_id) { this.comment_id = comment_id; } public commentsVO() { } public commentsVO(String info_id, String user_img, String user_id, String comments_info, int comment_id) { super(); this.info_id = info_id; this.user_img = user_img; this.user_id = user_id; this.comments_info = comments_info; this.comment_id = comment_id; } }
1,206
0.675879
0.675042
77
14.506494
18.173496
107
false
false
0
0
0
0
0
0
1.220779
false
false
14
0315c646d9e099ce545485c68ee0f1dc9558fe53
30,296,699,310,810
6690bc6a485ab737af5b58f423406b286dd9dc9a
/osuCelebrity-core/src/main/java/me/reddev/osucelebrity/core/api/CurrentPlayerService.java
082f77bf488f7fe62f0ed72a3faad1e6fc21dd39
[ "MIT" ]
permissive
FYPetro/OsuCelebrity
https://github.com/FYPetro/OsuCelebrity
79927640af997ec406a75d4ee3e57024cd4805cc
3b39d6846929989bcd76a271730c9af2dc560efa
refs/heads/master
2017-05-21T03:11:27.894000
2016-01-31T22:36:32
2016-01-31T22:36:32
46,972,618
1
0
null
true
2015-11-27T09:51:11
2015-11-27T09:51:10
2015-11-27T09:51:08
2015-11-26T23:16:36
404
0
0
0
null
null
null
package me.reddev.osucelebrity.core.api; import lombok.Data; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import me.reddev.osucelebrity.core.CoreSettings; import me.reddev.osucelebrity.core.QueuedPlayer; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.core.Spectator; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.OsuStatus; import me.reddev.osucelebrity.osu.OsuStatus.Type; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.apache.commons.lang3.StringUtils; import org.tillerino.osuApiModel.types.GameMode; import org.tillerino.osuApiModel.types.UserId; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Singleton @Path("/current") @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class CurrentPlayerService { @Data public static class CurrentPlayer { String name; @UserId @Setter(onParam = @__(@UserId)) @Getter(onMethod = @__(@UserId)) int id; String playingFor; double health; String beatmap; int rank; double pp; int playCount; double level; double accuracy; String country; int gameMode; String nextPlayer; String source; int queueSize; } private final PersistenceManagerFactory pmf; private final Spectator spectator; private final CoreSettings coreSettings; private final Osu osu; private final OsuApi api; private final ExecutorService exec; /** * Shows details about the player currently being spectated. */ @GET @Produces(MediaType.APPLICATION_JSON) public CurrentPlayer current() { PersistenceManager pm = pmf.getPersistenceManager(); try { CurrentPlayer response = new CurrentPlayer(); QueuedPlayer queued = spectator.getCurrentPlayer(pm); if (queued != null) { OsuUser player = queued.getPlayer(); response.setName(player.getUserName()); response.setPlayingFor(formatDuration(System.currentTimeMillis() - queued.getStartedAt())); long timeLeft = Math.max(0, queued.getStoppingAt() - queued.getLastRemainingTimeUpdate()); response.setHealth(timeLeft / (double) coreSettings.getDefaultSpecDuration()); response.setId(player.getUserId()); response.setSource(queued.getQueueSource() == QueueSource.AUTO ? "auto" : "queue"); ApiUser apiUser = getApiUser(response, queued.getPlayer()); if (apiUser != null) { response.rank = apiUser.getRank(); response.pp = apiUser.getPp(); response.playCount = apiUser.getPlayCount(); response.level = apiUser.getLevel(); response.accuracy = apiUser.getAccuracy(); response.country = apiUser.getCountry(); response.gameMode = apiUser.getGameMode(); } } OsuStatus clientStatus = osu.getClientStatus(); if (clientStatus != null && clientStatus.getType() == Type.PLAYING) { response.setBeatmap(clientStatus.getDetail()); } QueuedPlayer nextPlayer = spectator.getNextPlayer(pm); if (nextPlayer != null) { response.nextPlayer = nextPlayer.getPlayer().getUserName(); } response.setQueueSize(spectator.getQueueSize(pm)); return response; } finally { pm.close(); } } /** * Format duration as a human-readable time string. * @param millis duration in milliseconds. * @return hh:mm:ss or mm:ss */ public static String formatDuration(long millis) { millis /= 1000; long seconds = millis % 60; millis /= 60; long minutes = millis % 60; millis /= 60; long hours = millis; String formatted = ":" + StringUtils.leftPad(String.valueOf(seconds), 2, '0'); String stringMinutes = String.valueOf(minutes); if (hours > 0) { return hours + ":" + StringUtils.leftPad(stringMinutes, 2, '0') + formatted; } return stringMinutes + formatted; } private ApiUser getApiUser(CurrentPlayer currentPlayer, OsuUser osuUser) { Future<ApiUser> request = exec.submit(() -> getApiUserTransient(currentPlayer.getId(), osuUser.getGameMode(), 60 * 1000L)); try { return request.get(500, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { request = exec.submit(() -> getApiUserTransient(currentPlayer.getId(), osuUser.getGameMode(), 0)); try { return request.get(500, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e1) { return null; } } } private ApiUser getApiUserTransient(@UserId int userid, @GameMode int gameMode, long maxAge) throws IOException { PersistenceManager pm = pmf.getPersistenceManager(); try { ApiUser userData = api.getUserData(userid, gameMode, pm, maxAge); if (userData != null) { pm.makeTransient(userData); } return userData; } finally { pm.close(); } } }
UTF-8
Java
5,582
java
CurrentPlayerService.java
Java
[]
null
[]
package me.reddev.osucelebrity.core.api; import lombok.Data; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import me.reddev.osucelebrity.core.CoreSettings; import me.reddev.osucelebrity.core.QueuedPlayer; import me.reddev.osucelebrity.core.QueuedPlayer.QueueSource; import me.reddev.osucelebrity.core.Spectator; import me.reddev.osucelebrity.osu.Osu; import me.reddev.osucelebrity.osu.OsuStatus; import me.reddev.osucelebrity.osu.OsuStatus.Type; import me.reddev.osucelebrity.osu.OsuUser; import me.reddev.osucelebrity.osuapi.ApiUser; import me.reddev.osucelebrity.osuapi.OsuApi; import org.apache.commons.lang3.StringUtils; import org.tillerino.osuApiModel.types.GameMode; import org.tillerino.osuApiModel.types.UserId; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Singleton @Path("/current") @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class CurrentPlayerService { @Data public static class CurrentPlayer { String name; @UserId @Setter(onParam = @__(@UserId)) @Getter(onMethod = @__(@UserId)) int id; String playingFor; double health; String beatmap; int rank; double pp; int playCount; double level; double accuracy; String country; int gameMode; String nextPlayer; String source; int queueSize; } private final PersistenceManagerFactory pmf; private final Spectator spectator; private final CoreSettings coreSettings; private final Osu osu; private final OsuApi api; private final ExecutorService exec; /** * Shows details about the player currently being spectated. */ @GET @Produces(MediaType.APPLICATION_JSON) public CurrentPlayer current() { PersistenceManager pm = pmf.getPersistenceManager(); try { CurrentPlayer response = new CurrentPlayer(); QueuedPlayer queued = spectator.getCurrentPlayer(pm); if (queued != null) { OsuUser player = queued.getPlayer(); response.setName(player.getUserName()); response.setPlayingFor(formatDuration(System.currentTimeMillis() - queued.getStartedAt())); long timeLeft = Math.max(0, queued.getStoppingAt() - queued.getLastRemainingTimeUpdate()); response.setHealth(timeLeft / (double) coreSettings.getDefaultSpecDuration()); response.setId(player.getUserId()); response.setSource(queued.getQueueSource() == QueueSource.AUTO ? "auto" : "queue"); ApiUser apiUser = getApiUser(response, queued.getPlayer()); if (apiUser != null) { response.rank = apiUser.getRank(); response.pp = apiUser.getPp(); response.playCount = apiUser.getPlayCount(); response.level = apiUser.getLevel(); response.accuracy = apiUser.getAccuracy(); response.country = apiUser.getCountry(); response.gameMode = apiUser.getGameMode(); } } OsuStatus clientStatus = osu.getClientStatus(); if (clientStatus != null && clientStatus.getType() == Type.PLAYING) { response.setBeatmap(clientStatus.getDetail()); } QueuedPlayer nextPlayer = spectator.getNextPlayer(pm); if (nextPlayer != null) { response.nextPlayer = nextPlayer.getPlayer().getUserName(); } response.setQueueSize(spectator.getQueueSize(pm)); return response; } finally { pm.close(); } } /** * Format duration as a human-readable time string. * @param millis duration in milliseconds. * @return hh:mm:ss or mm:ss */ public static String formatDuration(long millis) { millis /= 1000; long seconds = millis % 60; millis /= 60; long minutes = millis % 60; millis /= 60; long hours = millis; String formatted = ":" + StringUtils.leftPad(String.valueOf(seconds), 2, '0'); String stringMinutes = String.valueOf(minutes); if (hours > 0) { return hours + ":" + StringUtils.leftPad(stringMinutes, 2, '0') + formatted; } return stringMinutes + formatted; } private ApiUser getApiUser(CurrentPlayer currentPlayer, OsuUser osuUser) { Future<ApiUser> request = exec.submit(() -> getApiUserTransient(currentPlayer.getId(), osuUser.getGameMode(), 60 * 1000L)); try { return request.get(500, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { request = exec.submit(() -> getApiUserTransient(currentPlayer.getId(), osuUser.getGameMode(), 0)); try { return request.get(500, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e1) { return null; } } } private ApiUser getApiUserTransient(@UserId int userid, @GameMode int gameMode, long maxAge) throws IOException { PersistenceManager pm = pmf.getPersistenceManager(); try { ApiUser userData = api.getUserData(userid, gameMode, pm, maxAge); if (userData != null) { pm.makeTransient(userData); } return userData; } finally { pm.close(); } } }
5,582
0.692046
0.686134
189
28.534391
24.829687
99
false
false
0
0
0
0
0
0
0.634921
false
false
12
dfddcd4076c3efdc18e704d9aead6adc1a79d09c
10,780,367,926,464
4e8cd32727bce62638b2d74246154b6f0de34449
/src/main/java/com/ram/funculture/config/Knife4jConfig.java
bc5a6eb905397d1cabea830a9730a444bc0f3528
[]
no_license
QVQ-wzj/FunCulture
https://github.com/QVQ-wzj/FunCulture
7944dd295aefa65fe412aa71680b7003eb59e9b8
9ff62423933acec2c9e54aa02d97c7cbfbce16ac
refs/heads/main
2023-08-28T00:09:24.153000
2021-10-26T13:16:11
2021-10-26T13:28:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ram.funculture.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.oas.annotations.EnableOpenApi; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @EnableOpenApi // 开启Swagger自定义接口文档 @Configuration // 相当于Spring配置中的<beans> public class Knife4jConfig { @Bean(value = "defaultApi") public Docket defaultApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .groupName("文娱") .select() .apis(RequestHandlerSelectors.basePackage("com.max.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("文娱 RESTful APIs") .description("文娱") .termsOfServiceUrl("http://www.xxxxx.com/") .build(); } }
UTF-8
Java
1,309
java
Knife4jConfig.java
Java
[]
null
[]
package com.ram.funculture.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.oas.annotations.EnableOpenApi; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @EnableOpenApi // 开启Swagger自定义接口文档 @Configuration // 相当于Spring配置中的<beans> public class Knife4jConfig { @Bean(value = "defaultApi") public Docket defaultApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .groupName("文娱") .select() .apis(RequestHandlerSelectors.basePackage("com.max.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("文娱 RESTful APIs") .description("文娱") .termsOfServiceUrl("http://www.xxxxx.com/") .build(); } }
1,309
0.686957
0.685376
33
37.363636
19.711277
80
false
false
0
0
0
0
0
0
0.363636
false
false
12
4786bf57110d9ba60321f25f52e4278713002b3b
8,057,358,657,877
2dbe1d8f099f344386a6d0d03432a4c9b72ac449
/src/com/sky/app/ThemeManager.java
31996b72578f79dcff48bec1838fbf4b2485e6f6
[]
no_license
sky24987/observer
https://github.com/sky24987/observer
dff1d5584da9afc5b81f8dbfe35585420004b44a
4769642e08dd4996380bda4d446b43c965580aaa
refs/heads/master
2016-09-05T22:15:03.917000
2013-03-14T06:15:17
2013-03-14T06:15:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sky.app; import java.util.Observable; public class ThemeManager extends Observable{ private static ThemeManager instance = new ThemeManager(); private ThemeManager() { // TODO Auto-generated constructor stub } public static ThemeManager getInstance() { return instance; } public void changeTheme() { super.setChanged(); notifyObservers("数据改变了"); } }
GB18030
Java
426
java
ThemeManager.java
Java
[]
null
[]
package com.sky.app; import java.util.Observable; public class ThemeManager extends Observable{ private static ThemeManager instance = new ThemeManager(); private ThemeManager() { // TODO Auto-generated constructor stub } public static ThemeManager getInstance() { return instance; } public void changeTheme() { super.setChanged(); notifyObservers("数据改变了"); } }
426
0.682692
0.682692
24
15.333333
17.676884
59
false
false
0
0
0
0
0
0
1.125
false
false
12
9b252d35867d024a092f5502edf530dbbf17db06
10,290,741,653,575
a3c4574a6aaedaf4341df350089bdfa2509d178e
/src/main/java/uk/gov/hmcts/ccd/v2/external/resource/DocumentsResource.java
43f49cdf0ec8474ad0ea65350a9f4c1708a1f926
[ "MIT" ]
permissive
swalker125/ccd-data-store-api
https://github.com/swalker125/ccd-data-store-api
8da258911c1ce8080e675b18e53fef788775e054
8be557a1706001ac64f0b97101d31641893352fc
refs/heads/master
2022-11-25T23:38:11.960000
2020-06-03T21:24:19
2020-06-03T21:24:19
274,905,205
0
0
MIT
true
2020-06-25T12:00:52
2020-06-25T12:00:51
2020-06-03T21:24:27
2020-06-25T10:41:03
18,028
0
0
0
null
false
false
package uk.gov.hmcts.ccd.v2.external.resource; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.springframework.hateoas.RepresentationModel; import uk.gov.hmcts.ccd.domain.model.definition.Document; import uk.gov.hmcts.ccd.v2.external.controller.DocumentController; import java.util.List; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @Data @NoArgsConstructor public class DocumentsResource extends RepresentationModel { List<Document> documentResources; public DocumentsResource(@NonNull String caseId, @NonNull List<Document> documents) { documentResources = documents; add(linkTo(methodOn(DocumentController.class).getDocuments(caseId)).withSelfRel()); } }
UTF-8
Java
848
java
DocumentsResource.java
Java
[]
null
[]
package uk.gov.hmcts.ccd.v2.external.resource; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.springframework.hateoas.RepresentationModel; import uk.gov.hmcts.ccd.domain.model.definition.Document; import uk.gov.hmcts.ccd.v2.external.controller.DocumentController; import java.util.List; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; @Data @NoArgsConstructor public class DocumentsResource extends RepresentationModel { List<Document> documentResources; public DocumentsResource(@NonNull String caseId, @NonNull List<Document> documents) { documentResources = documents; add(linkTo(methodOn(DocumentController.class).getDocuments(caseId)).withSelfRel()); } }
848
0.806604
0.804245
27
30.407408
30.797136
91
true
false
0
0
0
0
0
0
0.518519
false
false
12
ae8825fd7e9bec5e69ab4542ac0ba83055056d98
27,496,380,641,609
19f0c4981cc44c59cf79a939b1e11756127495f2
/com.onpositive.dside.ui/src/com/onpositive/musket_core/ValidationResult.java
55240a044233c18968d79cc56b4586af84454b1f
[]
no_license
musket-ml/ds-ide
https://github.com/musket-ml/ds-ide
ab67cc622798c09fa81c38d0d7f269b39cb4a0fe
ef19f882360124a617e94bf9733c9ee723ff5eb0
refs/heads/master
2022-02-02T10:34:22.169000
2020-10-14T17:09:58
2020-10-14T17:09:58
177,293,757
0
0
null
false
2022-01-21T23:40:58
2019-03-23T13:41:54
2020-10-14T17:10:04
2022-01-21T23:40:58
32,590
0
0
23
Java
false
false
package com.onpositive.musket_core; public class ValidationResult { public ValidationResult() { } public ValidationResult(Object obj) { } }
UTF-8
Java
161
java
ValidationResult.java
Java
[]
null
[]
package com.onpositive.musket_core; public class ValidationResult { public ValidationResult() { } public ValidationResult(Object obj) { } }
161
0.68323
0.68323
11
12.636364
15.575462
38
false
false
0
0
0
0
0
0
0.636364
false
false
12
471c0f55a3434e2202dc32ec54322ce9894cf7ad
7,241,314,923,785
4ffa8ba2b65980e5965dc8c6a636590d37a2731d
/src/main/java/gui/Start.java
6c17dde38d1ff680f6601f8cebde8fa8fcfd2fb0
[ "Apache-2.0" ]
permissive
MXDTeam/zsrc
https://github.com/MXDTeam/zsrc
afcc2b0722aabafbdac2d8250b5c28c619deb2a9
72fd6a3b780891e334b8513d02de87c689e2b3bc
refs/heads/main
2023-06-20T11:18:41.480000
2021-07-20T08:51:51
2021-07-20T08:51:51
386,961,173
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gui; import client.Class2; import client.DebugWindow; import client.MapleCharacter; import client.SkillFactory; import database.DatabaseConnection; import gui.Jieya.解压文件; import gui.控制台.控制台1号; import gui.控制台.聊天记录显示; import gui.控制台.脚本更新器; import gui.未分类.广告; import handling.cashshop.CashShopServer; import handling.channel.ChannelServer; import handling.channel.MapleGuildRanking; import handling.login.LoginInformationProvider; import handling.login.LoginServer; import handling.world.MapleParty; import handling.world.World; import handling.world.family.MapleFamilyBuff; import server.Timer; import server.*; import server.Timer.*; import server.custom.bossrank3.BossRankManager3; import server.custom.forum.Forum_Section; import server.events.MapleOxQuizFactory; import server.life.MapleLifeFactory; import server.maps.MapleMapFactory; import server.quest.MapleQuest; import tools.FileoutputUtil; import tools.MaplePacketCreator; import tools.packet.UIPacket; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import static a.本地数据库.*; import static a.用法大全.关系验证; import static a.用法大全.本地取广播; import static abc.Game.数据库数据导入; import static abc.Game.版本; import static abc.sancu.FileDemo_05.删除文件; import static gui.QQ通信.*; import static gui.ZEVMS.下载文件; import static gui.活动野外通缉.随机通缉; import static server.MapleCarnivalChallenge.getJobNameById; import static tools.FileoutputUtil.CurrentReadable_Time; public class Start { public static boolean Check = true; public static final Start instance = new Start(); private static final int maxUsers = 0; public static ZEVMS2 CashGui; public static 控制台1号 服务端功能开关; public static 广告 广告; public static 聊天记录显示 信息输出; public static 脚本更新器 更新通知; public static DebugWindow DebugWindow; public static Map<String, Integer> ConfigValuesMap = new HashMap<>(); public static Map<String, Integer> 地图吸怪检测 = new HashMap<>(); public static Map<String, Integer> 技能范围检测 = new HashMap<>(); public static Map<String, Integer> PVP技能伤害 = new HashMap<>(); public static Map<String, Integer> 个人信息设置 = new HashMap<>(); public static void main(String[] args) throws IOException, InterruptedException { startServer(); } public static void startServer() throws InterruptedException, IOException { MapleParty.每日清理 = 0; long start = System.currentTimeMillis(); 数据库数据导入(); GetConfigValues(); Check = false; System.out.println("\r\n○ 开始启动服务端"); // MapleParty.IP地址 = ServerProperties.getProperty("ZEV.IP"); // MapleParty.开服名字 = ServerProperties.getProperty("ZEV.name"); System.out.println("○ 游戏名字 : " + MapleParty.开服名字); System.out.println("○ 游戏地址 : " + MapleParty.IP地址); try { try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET loggedin = 0")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET lastGainHM = 0")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 202")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 201")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 200")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 500")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 501")) { ps.executeUpdate(); } } catch (SQLException ex) { throw new RuntimeException("[重置数据值出错] Please check if the SQL server is active."); } System.out.println("○ 开始加载各项数据"); World.init(); System.out.println("○ 开始加载时间线程"); 时间线程(); System.out.println("○ 开始游戏商城"); LoginInformationProvider.getInstance(); System.out.println("○ 开始加载任务信息1"); MapleQuest.initQuests(); System.out.println("○ 开始加载任务信息2"); MapleLifeFactory.loadQuestCounts(); System.out.println("○ 开始加载背包物品1"); ItemMakerFactory.getInstance(); System.out.println("○ 开始加载背包物品2"); MapleItemInformationProvider.getInstance().load(); System.out.println("○ 开始加载刷怪线程"); World.registerRespawn(); System.out.println("○ 开始加载备用刷怪线程"); World.registerRespawn2(); System.out.println("○ 开始加载反应堆1"); System.out.println("○ 开始加载反应堆2"); RandomRewards.getInstance(); System.out.println("○ 开始加载技能信息"); SkillFactory.getSkill(99999999); System.out.println("○ 开始加载活动信息"); MapleOxQuizFactory.getInstance().initialize(); MapleCarnivalFactory.getInstance(); System.out.println("○ 开始加载家族信息"); MapleGuildRanking.getInstance().RankingUpdate(); System.out.println("○ 开始加载学院信息"); MapleFamilyBuff.getBuffEntry(); new Thread(QQMsgServer.getInstance()).start(); System.out.println("○ 开始加载装备附魔信息"); GetFuMoInfo(); System.out.println("○ 开始加载云防护黑名单"); GetCloudBacklist(); System.out.println("○ 开始加载技能范围检测"); 读取技能范围检测(); System.out.println("○ 开始加载地图吸怪检测"); 读取地图吸怪检测(); System.out.println("○ 开始加载PVP技能配置"); 读取技能PVP伤害(); System.out.println("○ 开始加载个人配置信息"); 读取技个人信息设置(); 重置仙人数据(); System.out.println("○ 开始加载游戏论坛"); System.out.println("○ 开始加载游戏邮箱"); System.out.println("○ 开始加载传送点数据"); Forum_Section.loadAllSection(); System.out.println("○ 开始加载登陆服务器"); //MapleServerHandler.registerMBean(); MTSStorage.load(); PredictCardFactory.getInstance().initialize(); CashItemFactory.getInstance().initialize(); System.out.println("○ 开始加载游戏倍率信息"); LoginServer.run_startup_configurations(); //怪物攻城 //RespawnManager.getInstance().run(); System.out.println("○ 开始加载游戏频道信息"); ChannelServer.startChannel_Main(); LoginServer.setOn(); System.out.println("○ 开始加载新建NPC位置信息"); MapleMapFactory.loadCustomLife(); System.out.println("○ 开始加载游戏商城物品"); CashShopServer.run_startup_configurations(); CheatTimer.getInstance().register(AutobanManager.getInstance(), 60000); //new ZevmsLauncherServer(60000).start(); //好像是掉落物品? //ChannelServer.getInstance(1).getMapFactory().getMap(749030000).spawnRandDrop(); //WorldTimer.getInstance().register(new World.Respawn(), 10000); Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown())); try { SpeedRunner.getInstance().loadSpeedRuns(); } catch (SQLException e) { System.out.println("SpeedRunner错误:" + e); } WorldTimer.getInstance().register(DatabaseConnection.CloseSQLConnections, 10 * 60 * 1000);//18 System.out.println("○ 商城: " + CurrentReadable_Time() + " 读取商城上架时装完成"); //游戏倍率显示 System.out.println("○ 游戏倍率信息"); //显示经验倍率,不能超过100倍 if (Integer.parseInt(ServerProperties.getProperty("ZEV.Exp", "1")) > 100) { System.out.println("○ 游戏经验倍率: 100 倍 (上限)"); } else { System.out.println("○ 游戏经验倍率: " + Integer.parseInt(ServerProperties.getProperty("ZEV.Exp", "1")) + " 倍 "); } //显示物品倍率,不能超过100倍 if (Integer.parseInt(ServerProperties.getProperty("ZEV.Drop", "1")) > 100) { System.out.println("○ 游戏物品倍率:100 倍 (上限)"); } else { System.out.println("○ 游戏物品倍率:" + Integer.parseInt(ServerProperties.getProperty("ZEV.Drop", "1")) + " 倍 "); } //显示金币倍率,不能超过100倍 if (Integer.parseInt(ServerProperties.getProperty("ZEV.Meso", "1")) > 100) { System.out.println("○ 游戏金币倍率:100 倍 (上限)"); } else { System.out.println("○ 游戏金币倍率:" + Integer.parseInt(ServerProperties.getProperty("ZEV.Meso", "1")) + " 倍 "); } System.out.println("○ 启动自动存档线程"); 自动存档(5); System.out.println("○ 启动角色福利泡点线程"); 福利泡点(30); System.out.println("○ 启动雇佣福利泡点线程"); 福利泡点2(30); System.out.println("○ 启动数据库通信线程"); 定时查询(3); System.out.println("○ 启动服务端内存回收线程"); //回收内存(30); System.out.println("○ 启动记录在线时长线程"); System.out.println("○ 启动记录在线时长补救线程"); 记录在线时间(1); //回收地图(60 * 3); System.out.println("○ 启动游戏公告播放线程"); 公告(20); MapleParty.服务端运行时长 = 0; System.out.println("○ 启动云端验证IP地址线程"); 统计在线人数(22); 检测服务端版本(60); System.out.println("○ 同步云端任务修复文件夹"); 任务同步修复(); System.out.println("\r\n"); System.out.println("○ [加载账号数量]: " + 服务器账号() + " 个"); System.out.println("○ [加载角色数量]: " + 服务器角色() + " 个"); System.out.println("○ [加载道具数量]: " + 服务器道具() + " 个"); System.out.println("○ [加载技能数量]: " + 服务器技能() + " 个"); System.out.println("○ [加载游戏商品数量]: " + 服务器游戏商品() + " 个"); System.out.println("○ [加载商城商品数量]: " + 服务器商城商品() + " 个"); //显示加载完成的时间 long now = System.currentTimeMillis() - start; long seconds = now / 1000; System.out.println("○ 服务端启动耗时: " + seconds + " 秒"); System.out.println("\r\n"); System.out.println("○ 正在启动主控制台"); CashShopServer(); //开启进阶BOSS线程(); qingkongguyong(); } public static void qingkongguyong() { try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM hiredmerch"); ResultSet rs = ps.executeQuery(); while (rs.next()) { 雇佣写入(rs.getInt("characterid"), 1, rs.getInt("Mesos")); } ps.close(); } catch (SQLException ex) { } Connection con = DatabaseConnection.getConnection(); try { PreparedStatement ps = con.prepareStatement("DELETE FROM hiredmerchantshop"); ps.executeUpdate(); ps.close(); } catch (SQLException e) { System.out.println("hiredmerchantshop " + e); } try { PreparedStatement ps = con.prepareStatement("DELETE FROM hiredmerchequipment"); ps.executeUpdate(); ps.close(); } catch (SQLException e) { System.out.println("hiredmerchequipment " + e); } try { PreparedStatement ps = con.prepareStatement("DELETE FROM hiredmerchitems"); ps.executeUpdate(); ps.close(); } catch (SQLException e) { System.out.println("hiredmerchitems " + e); } } /** * * <1分钟执行一次> */ private static int 记录在线时间 = 0; private static final int 重置数据库 = 0; private static Boolean 每日送货 = false; private static Boolean 喜从天降 = false; private static Boolean 鱼来鱼往 = false; private static int 初始通缉令 = 0; private static Boolean 倍率活动 = false; private static Boolean 幸运职业 = false; private static Boolean 启动OX答题线程 = false; private static Boolean 魔族入侵 = false; private static Boolean isClearBossLog = false; private static Boolean 魔族攻城 = false; private static int Z = 0; public static void 记录在线时间(final int time) { Timer.WorldTimer.getInstance().register(() -> { if (记录在线时间 > 0) { MapleParty.服务端运行时长 += 1; Calendar calendar = Calendar.getInstance(); int 时 = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); int 分 = Calendar.getInstance().get(Calendar.MINUTE); int 星期 = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); /** * <凌晨清理每日信息> */ if (时 == 0 && isClearBossLog == false) { System.err.println("[服务端]" + CurrentReadable_Time() + " : ------------------------------"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端开始清理每日信息 √"); 通信("服务端开始清理每日信息"); try { //重置今日在线时间 try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characters SET todayOnlineTime = 0")) { ps.executeUpdate(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 清理今日在线时间完成 √"); } //重置每日bosslog信息 try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE bosslog SET characterid = 0")) { ps.executeUpdate(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 清理今日log信息完成 √"); } //重置每日bosslog信息 try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET df_tired_point = 0")) { ps.executeUpdate(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 清理今日疲劳完成 √"); } System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端清理每日信息完成 √"); 通信("服务端清理每日信息完成"); System.err.println("[服务端]" + CurrentReadable_Time() + " : ------------------------------"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端处理每日数据出错 × " + ex.getMessage()); 通信("服务端处理每日数据出错,你可能要手动清理一下。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : ------------------------------"); } isClearBossLog = true; 每日送货 = false; 启动OX答题线程 = false; 魔族入侵 = false; 魔族攻城 = false; 喜从天降 = false; 鱼来鱼往 = false; MapleParty.OX答题活动 = 0; /*if (重置数据库 == 1) { 重置数据库(); } else { 重置数据库++; }*/ } else if (时 == 23) { isClearBossLog = false; } /** * <鱼来鱼往> */ if (Start.ConfigValuesMap.get("鱼来鱼往开关") == 0) { if (时 == 21 && 分 >= 30 && 鱼来鱼往 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[鱼来鱼往]: 水下世界 2 频道 1 分钟后开始喜从鱼来鱼往活动。", 5120027); } } QQ通信.群通知("[鱼来鱼往]: 水下世界 2 频道 1 分钟后开始喜从鱼来鱼往活动。"); new Thread(() -> { try { Thread.sleep(1000 * 60); 活动鱼来鱼往.鱼来鱼往(); } catch (InterruptedException e) { } }).start(); 鱼来鱼往 = true; } } /** * <喜从天降> */ if (Start.ConfigValuesMap.get("喜从天降开关") == 0) { if (星期 == 1 || 星期 == 7) { if (时 == 22 && 分 == 30 && 喜从天降 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[喜从天降]: 市场 2 频道 1 分钟后开始喜从天降活动。", 5120027); } } QQ通信.群通知("[喜从天降]: 市场 2 频道 1 分钟后开始喜从天降活动。"); new Thread(() -> { try { Thread.sleep(1000 * 60); 活动喜从天降.喜从天降(); } catch (InterruptedException e) { } }).start(); 喜从天降 = true; } } } /** * <每日送货> */ if (Start.ConfigValuesMap.get("每日送货开关") == 0) { if (时 == 12 && 每日送货 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[每日送货]: 送货活动开启,明珠港送货员处可以开始送货哦,可以获得丰厚的奖励。", 5120027); } } QQ通信.群通知("[每日送货]: 送货活动开启,明珠港送货员处可以开始送货哦,可以获得丰厚的奖励。"); 每日送货 = true; } } /** * <OX答题> */ if (Start.ConfigValuesMap.get("OX答题开关") == 0) { if (时 == 20 && 启动OX答题线程 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[每日答题]: 10 分钟后将举行 OX 答题比赛,想要参加的小伙伴,请找活动向导参加吧。", 5120027); } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 每日活动 OX答题 线程已经启动"); OX答题("[每日活动]: 10 分钟后将举行 OX 答题比赛,想要参加的小伙伴,请找活动向导参加吧。"); 活动OX答题.OX答题线程(); MapleParty.OX答题活动++; 启动OX答题线程 = true; } } /** * <魔族入侵> */ if (Start.ConfigValuesMap.get("魔族突袭开关") == 0) { if (calendar.get(Calendar.HOUR_OF_DAY) == 22 && 魔族入侵 == false) { 活动魔族入侵.魔族入侵线程(); 魔族入侵 = true; } } /** * <魔族攻城> */ if (Start.ConfigValuesMap.get("魔族攻城开关") == 0) { if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == 1) { if (时 == 21 && 分 <= 10 && 魔族攻城 == false) { 活动魔族攻城.魔族攻城线程(); 魔族攻城 = true; } } } /** * <幸运职业,天选之人-狩猎> */ if (Start.ConfigValuesMap.get("幸运职业开关") == 0) { if (时 == 11 && 幸运职业 == false) { 幸运职业(); 幸运职业 = true; } else if (时 == 23 && 幸运职业 == true) { 幸运职业(); 幸运职业 = false; } else if (MapleParty.幸运职业 == 0) { 幸运职业(); } } /** * <周末随机倍率活动> */ if (Start.ConfigValuesMap.get("周末倍率开关") == 0) { switch (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) { case 1: case 7: if (时 == 0 && 倍率活动 == false) { 活动倍率活动.倍率活动线程(); 倍率活动 = true; } else if (时 == 23) { 倍率活动 = false; } break; case 6: if (倍率活动 == true) { 倍率活动 = false; } break; default: break; } } /** * <启动神秘商人> */ if (Start.ConfigValuesMap.get("神秘商人开关") == 0) { //第一次启动神秘商人 if (MapleParty.神秘商人线程 == 0) { 活动神秘商人.启动神秘商人(); MapleParty.神秘商人线程++; } //召唤神秘商人 if (MapleParty.神秘商人线程 > 0) { if (时 == MapleParty.神秘商人时间 && MapleParty.神秘商人 == 0) { 活动神秘商人.召唤神秘商人(); } } } /** * <初始化通缉令> */ if (Start.ConfigValuesMap.get("野外通缉开关") == 0) { if (初始通缉令 == 30) { 随机通缉(); 初始通缉令++; } else { 初始通缉令++; } } /** * <记录在线时间> */ Z = 0; for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.增加角色疲劳值(1); Connection con = DatabaseConnection.getConnection(); try { /** * <加在线> */ try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, time); psu.setInt(2, time); psu.setInt(3, chr.getId()); psu.executeUpdate(); psu.close(); } chr.getClient().sendPacket(MaplePacketCreator.enableActions()); if (Z == 0) { Z++; System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线 √"); } } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线 × (" + chr.getId() + ")");//+ ex.getMessage() //通信("玩家 [" + 角色ID取名字(chr.getId()) + "] 记录在线错误,现在开始补救。"); 记录在线时间补救(chr.getId()); } } } } else { 记录在线时间++; } }, 60 * 1000 * time ); } public static void 重置数据库() { World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.saveToDB(false, false); } } new Thread() { @Override public void run() { try { Thread.sleep(1000 * 5); 关闭服务("MySQL5"); } catch (InterruptedException e) { } } }.start(); new Thread() { @Override public void run() { try { Thread.sleep(1000 * 10); 重启服务("MySQL5"); } catch (InterruptedException e) { } } }.start(); } public static void 幸运职业() { int 随机 = (int) Math.ceil(Math.random() * 18); if (随机 == 0) { 随机 += 1; } switch (随机) { case 1: MapleParty.幸运职业 = 111; break; case 2: MapleParty.幸运职业 = 121; break; case 3: MapleParty.幸运职业 = 131; break; case 4: MapleParty.幸运职业 = 211; break; case 5: MapleParty.幸运职业 = 221; break; case 6: MapleParty.幸运职业 = 231; break; case 7: MapleParty.幸运职业 = 311; break; case 8: MapleParty.幸运职业 = 321; break; case 9: MapleParty.幸运职业 = 411; break; case 10: MapleParty.幸运职业 = 421; break; case 11: MapleParty.幸运职业 = 511; break; case 12: MapleParty.幸运职业 = 521; break; case 13: MapleParty.幸运职业 = 1111; break; case 14: MapleParty.幸运职业 = 1211; break; case 15: MapleParty.幸运职业 = 1311; break; case 16: MapleParty.幸运职业 = 1411; break; case 17: MapleParty.幸运职业 = 1511; break; case 18: MapleParty.幸运职业 = 2111; break; default: break; } String 信息 = "恭喜 " + getJobNameById((MapleParty.幸运职业 - 1)) + " " + getJobNameById(MapleParty.幸运职业) + " " + getJobNameById((MapleParty.幸运职业 + 1)) + " 幸运成为幸运职业,增加50%基础狩猎经验"; 群通知("[幸运职业] : " + 信息); System.err.println("[服务端]" + CurrentReadable_Time() + " : [幸运职业] : " + 信息); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[幸运职业] : " + 信息)); } private static int 定时查询 = 0; /** * <3分钟检测一次数据库> * <每3分钟检测一下数据库通信信息,如果数据异常,通知主人,3分钟后如果还是异常,主人可以选择手动,或者通过指令重启数据库> * <机器人指令; *重启数据库> */ public static int 异常警告 = 0; public static void 定时查询(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (定时查询 > 0) { try { try (PreparedStatement psu = DatabaseConnection.getConnection().prepareStatement("SELECT COUNT(id) FROM accounts WHERE loggedin > 0")) { psu.execute(); psu.close(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测数据库通信 √"); if (异常警告 > 0) { 通信("服务端数据库通信已恢复"); 异常警告 = 0; } } } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测数据库通信 × " + ex.getMessage()); if (异常警告 >= 5) { 通信("服务端数据库通信严重异常,请及时重启数据库"); } else { 通信("服务端数据库通信异常,如果持续提示此信息,请重启数据库"); 异常警告++; } } } else { 定时查询++; } } }, 60 * 1000 * time); } /** * * <30分钟泡点一次> */ public static int 福利泡点 = 0; public static void 福利泡点(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (福利泡点 > 0) { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } if (MapleParty.OX答题活动 == 0) { if (chr.level > 10) { int 点券 = 0; int 经验 = 0; int 金币 = 0; int 抵用 = 0; int 泡点金币开关 = gui.Start.ConfigValuesMap.get("泡点金币开关"); if (泡点金币开关 <= 0) { int 泡点金币 = gui.Start.ConfigValuesMap.get("泡点金币"); 金币 += 泡点金币; if (chr.getEquippedFuMoMap().get(34) != null) { 金币 += 泡点金币 / 100 * chr.getEquippedFuMoMap().get(34); } chr.gainMeso(泡点金币, true); } int 泡点点券开关 = gui.Start.ConfigValuesMap.get("泡点点券开关"); if (泡点点券开关 <= 0) { int 泡点点券 = gui.Start.ConfigValuesMap.get("泡点点券"); chr.modifyCSPoints(1, 泡点点券, true); 点券 += 泡点点券; } int 泡点抵用开关 = gui.Start.ConfigValuesMap.get("泡点抵用开关"); if (泡点抵用开关 <= 0) { int 泡点抵用 = gui.Start.ConfigValuesMap.get("泡点抵用"); chr.modifyCSPoints(2, 泡点抵用, true); 抵用 += 泡点抵用; } int 泡点经验开关 = gui.Start.ConfigValuesMap.get("泡点经验开关"); if (泡点经验开关 <= 0) { int 泡点经验 = gui.Start.ConfigValuesMap.get("泡点经验"); 经验 += 泡点经验; if (chr.getEquippedFuMoMap().get(33) != null) { 经验 += 泡点经验 / 100 * chr.getEquippedFuMoMap().get(33); } if (chr.Getcharactera("射手村繁荣度", 1) > 0) { 经验 += 泡点经验 * chr.Getcharactera("射手村繁荣度", 1) * 0.000001; } chr.gainExp(经验, false, false, false); } BossRankManager3.getInstance().setLog(chr.getId(), chr.getName(), "泡点经验", (byte) 2, (byte) 1); chr.getClient().sendPacket(UIPacket.getTopMsg("[" + MapleParty.开服名字 + "泡点]:" + 点券 + " 点券 / " + 抵用 + " 抵用 / " + 经验 + " 经验 / " + 金币 + " 金币,泡点经验 + 1")); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); } } } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放泡点 √ "); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在启用备用发放泡点 √ "); new Thread() { @Override public void run() { try { Thread.sleep(1000 * 10); 福利泡点(); } catch (InterruptedException e) { } } }.start(); } } else { 福利泡点++; } } }, 60 * 1000 * time); } /** * * <备用发送福利泡点> */ public static void 福利泡点() { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } if (chr.level > 10) { int 点券 = 0; int 经验 = 0; int 金币 = 0; int 抵用 = 0; int 泡点金币开关 = gui.Start.ConfigValuesMap.get("泡点金币开关"); if (泡点金币开关 <= 0) { int 泡点金币 = gui.Start.ConfigValuesMap.get("泡点金币"); 金币 += 泡点金币; if (chr.getEquippedFuMoMap().get(34) != null) { 金币 += 泡点金币 / 100 * chr.getEquippedFuMoMap().get(34); } chr.gainMeso(泡点金币, true); } int 泡点点券开关 = gui.Start.ConfigValuesMap.get("泡点点券开关"); if (泡点点券开关 <= 0) { int 泡点点券 = gui.Start.ConfigValuesMap.get("泡点点券"); chr.modifyCSPoints(1, 泡点点券, true); 点券 += 泡点点券; } int 泡点抵用开关 = gui.Start.ConfigValuesMap.get("泡点抵用开关"); if (泡点抵用开关 <= 0) { int 泡点抵用 = gui.Start.ConfigValuesMap.get("泡点抵用"); chr.modifyCSPoints(2, 泡点抵用, true); 抵用 += 泡点抵用; } int 泡点经验开关 = gui.Start.ConfigValuesMap.get("泡点经验开关"); if (泡点经验开关 <= 0) { int 泡点经验 = gui.Start.ConfigValuesMap.get("泡点经验"); 经验 += 泡点经验; if (chr.getEquippedFuMoMap().get(33) != null) { 经验 += 泡点经验 / 100 * chr.getEquippedFuMoMap().get(33); } chr.gainExp(泡点经验, true, true, false); } BossRankManager3.getInstance().setLog(chr.getId(), chr.getName(), "泡点经验", (byte) 2, (byte) 1); chr.getClient().sendPacket(UIPacket.getTopMsg("[" + MapleParty.开服名字 + "泡点]:" + 点券 + " 点券 / " + 抵用 + " 抵用 / " + 经验 + " 经验 / " + 金币 + " 金币,泡点经验 + 1")); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); } } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放泡点 ↑√ "); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放泡点 ↑× "); } } /** * * <30分钟雇佣泡点一次> */ public static int 福利泡点2 = 0; public static void 福利泡点2(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (福利泡点2 > 0) { int ID = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT `id` FROM accounts ORDER BY `id` DESC LIMIT 1"); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { String SN = rs.getString("id"); int sns = Integer.parseInt(SN); sns++; ID = sns; } } for (int i = 0; i <= ID; i++) { boolean 雇佣 = World.hasMerchant(i); if (雇佣) { //写入金币 雇佣写入(i, 1, gui.Start.ConfigValuesMap.get("雇佣泡点金币")); //写入点券 雇佣写入(i, 2, gui.Start.ConfigValuesMap.get("雇佣泡点点券")); } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放雇佣泡点 √ "); } catch (SQLException | NumberFormatException e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在启用备用发放泡点 x "); } } else { 福利泡点2++; } } }, 1000 * 60 * time); } /** * * <5分钟存档一次> */ private static int 自动存档 = 0; public static void 自动存档(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (自动存档 > 0) { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.saveToDB(false, false); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); if (chr.getSession() != null && !chr.getClient().getSession().isActive()) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 心跳超时,断开链接(" + chr.getClient().getSession().isActive() + " ? " + chr.getId() + ") √"); chr.getClient().getSession().close(); } } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在自动存档,并且检测心跳 √"); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在启用备用自动存档 √"); } } else { 自动存档++; } } }, 60 * 1000 * time); } private static int 回收地图 = 0; public static void 回收地图(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (回收地图 > 0) { try { try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM map "); ResultSet rs = ps.executeQuery(); while (rs.next()) { if (rs.getInt("id") < 910000000 || rs.getInt("id") > 910000024) { for (ChannelServer cserv : ChannelServer.getAllInstances()) { if (cserv == null) { continue; } cserv.getMapFactory().destroyMap(rs.getInt("id"), true); cserv.getMapFactory().HealMap(rs.getInt("id")); } } } ps.close(); } catch (SQLException ex) { } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在回收地图 √"); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在回收地图 √"); } } else { 回收地图++; } } }, 60 * 1000 * time); } /** * * <备用自动存档> */ public static void 自动存档() { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.saveToDB(false, false); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); } } } catch (Exception e) { } } public static void 记录在线时间补救(int a) { Connection con = DatabaseConnection.getConnection(); try { try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, 1); psu.setInt(2, 1); psu.setInt(3, a); psu.executeUpdate(); psu.close(); } //通信("玩家 [" + 角色ID取名字(a) + "] 补救成功。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第一次补救成功 √ (" + a + ")"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第一次补救失败 × (" + a + ")" + ex.getMessage()); 记录在线时间补救2(a); } } public static void 记录在线时间补救2(int a) { Connection con = DatabaseConnection.getConnection(); try { try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, 1); psu.setInt(2, 1); psu.setInt(3, a); psu.executeUpdate(); psu.close(); } //通信("玩家 [" + 角色ID取名字(a) + "] 补救成功。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第二次补救成功 √ (" + a + ")"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第二次补救失败 × (" + a + ")" + ex.getMessage()); 记录在线时间补救3(a); } } public static void 记录在线时间补救3(int a) { Connection con = DatabaseConnection.getConnection(); try { try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, 1); psu.setInt(2, 1); psu.setInt(3, a); psu.executeUpdate(); psu.close(); } //通信("玩家 [" + 角色ID取名字(a) + "] 补救成功。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第三次补救成功 √ (" + a + ")"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第三次补救失败 × (" + a + ")" + ex.getMessage()); } } /** * * <30分钟强制回收一次内存> */ private static int 回收内存 = 0; public static void 回收内存(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (回收内存 > 0) { System.gc(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 回收服务端内存 √"); } else { 回收内存++; } } }, 60 * 1000 * time); } /** * * <30分钟检检测一次IP绑定情况> */ private static int 关系验证 = 0; public static void 关系验证2(int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (关系验证 > 0) { if (关系验证(MapleParty.启动账号) == null ? "" + MapleParty.IP地址 + "" != null : !关系验证(MapleParty.启动账号).equals("" + MapleParty.IP地址 + "")) { System.out.println("[服务端]" + CurrentReadable_Time() + " : 绑定地址发生变化,服务端 1 分钟后将会关闭 ×"); new Thread() { @Override public void run() { try { Thread.sleep(1000 * 60); System.exit(0); } catch (InterruptedException e) { } } }.start(); } else { System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端验证云端绑定IP地址 √"); } } else { 关系验证 += 1; } } }, 1000 * 60 * time); } /** * * <60分钟检检测一次服务端版本> */ private static int 检测服务端版本 = 0; private static int 检测服务端版本1 = 0; public static void 检测服务端版本(int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (检测服务端版本 > 0 && 检测服务端版本1 == 0) { String v2 = Class2.Pgv(); if (Integer.parseInt(v2) != 版本) { if (检测服务端版本1 == 0) { 通信("服务端有新版本,请你及时更新。"); 检测服务端版本1++; } System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测服务端有新版本,请你及时更新 √"); } else { System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测服务端版本,服务端当前是最新版本 √"); } } else { 检测服务端版本++; } } }, 1000 * 60 * time); } /** * * <60分钟统计一次最高在线人数> */ private static int 统计最高在线人数 = 0; private static int 最高在线人数 = 0; private static int 最高在线人数2 = 0; public static void 统计在线人数(int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (统计最高在线人数 > 0) { int p = 0; try { Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT * FROM accounts WHERE loggedin > 0"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } ps.close(); } } catch (SQLException Ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 统计最高在线出错 ×"); } 最高在线人数 = p; if (最高在线人数 > 最高在线人数2) { 最高在线人数 = 0; 最高在线人数2 = p; } if (最高在线人数2 > 最高在线人数 && 最高在线人数2 > 0) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 统计此次最高在线 √ 人数: " + 最高在线人数2); } } else { 统计最高在线人数++; } } }, 1000 * 60 * time); } /** * * <循环播放公告> @param time * * @param time */ public static void 公告(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { String 公告 = 本地取广播(); if (!"".equals(公告)) { World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(0, " : " + 公告)); } } }, time * 1000 * 60); } /** * * <其他> */ public static void GetConfigValues() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM ConfigValues")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); ConfigValuesMap.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取动态数据库出错:" + ex.getMessage()); } } public static void 读取地图吸怪检测() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM 地图吸怪检测")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); 地图吸怪检测.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取吸怪检测错误:" + ex.getMessage()); } } public static void GetFuMoInfo() { FuMoInfoMap.clear(); System.out.println("○ 开始加载附魔装备效果"); //重载// Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT fumoType, fumoName, fumoInfo FROM mxmxd_fumo_info")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int fumoType = rs.getInt("fumoType"); String fumoName = rs.getString("fumoName"); String fumoInfo = rs.getString("fumoInfo"); FuMoInfoMap.put(fumoType, new String[]{fumoName, fumoInfo}); } } ps.close(); } catch (SQLException ex) { System.err.println("○ 加载附魔装备效果预览失败。"); } } public static void 读取技能范围检测() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM 技能范围检测")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); 技能范围检测.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取吸怪检测错误:" + ex.getMessage()); } } public static void 读取技能PVP伤害() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM pvpskills")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); PVP技能伤害.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取技能PVP伤害错误:" + ex.getMessage()); } } public static void 读取技个人信息设置() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM jiezoudashi")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); 个人信息设置.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取个人信息设置错误:" + ex.getMessage()); } } public static void 服务器信息() { try { InetAddress addr = InetAddress.getLocalHost(); String ip = addr.getHostAddress(); //獲取本機ip String hostName = addr.getHostName(); //獲取本機計算機名稱 //System.out.println("本機IP:"+ip+"\n本機名稱:"+hostName); System.out.println("○ 检测服务端运行环境"); System.out.println("○ 服务器名: " + hostName); Properties 設定檔 = System.getProperties(); System.out.println("○ 操作系统:" + 設定檔.getProperty("os.name")); System.out.println("○ 系统框架:" + 設定檔.getProperty("os.arch")); System.out.println("○ 系统版本:" + 設定檔.getProperty("os.version")); System.out.println("○ 服务端目录:" + 設定檔.getProperty("user.dir")); System.out.println("○ 服务端环境检测完成"); } catch (Exception e) { //e.printStackTrace(); } } public static class Shutdown implements Runnable { @Override public void run() { new Thread(ShutdownServer.getInstance()).start(); } } public static void 更新通知() { if (更新通知 != null) { 更新通知.dispose(); } 更新通知 = new 脚本更新器(); 更新通知.setVisible(true); } public static void CashShopServer() { if (Start.CashGui != null) { Start.CashGui.dispose(); } Start.CashGui = new ZEVMS2(); Start.CashGui.setVisible(true); } public static void 启动动态配置台() { if (Start.服务端功能开关 != null) { Start.服务端功能开关.dispose(); } Start.服务端功能开关 = new 控制台1号(); Start.服务端功能开关.setVisible(true); } public static void 广告() { if (Start.广告 != null) { Start.广告.dispose(); } Start.广告 = new 广告(); Start.广告.setVisible(true); } public static void 信息输出() { if (Start.信息输出 != null) { Start.信息输出.dispose(); } Start.信息输出 = new 聊天记录显示(); Start.信息输出.setVisible(true); } public static void CashShopServer2() { if (Start.DebugWindow != null) { Start.DebugWindow.dispose(); } Start.DebugWindow = new DebugWindow(); Start.DebugWindow.setVisible(true); } public static Map<Integer, String[]> FuMoInfoMap = new HashMap<>(); public static Map<String, String> CloudBlacklist = new HashMap<>(); public static void GetCloudBacklist() { CloudBlacklist.clear(); try { String backlistStr = Class2.Pgb(); if (backlistStr.contains("/")) { String[] blacklistArr = backlistStr.split(","); for (int i = 0; i < blacklistArr.length; i++) { String pairString = blacklistArr[i]; String[] pair = pairString.split("/"); String qq = pair[0]; String ip = "/" + pair[1]; CloudBlacklist.put(qq, ip); } } } catch (Exception ex) { System.err.println("获取云黑名单出错:" + ex.getMessage()); } } public static boolean 检测合法() { //检测是否启动指定程序 ByteArrayOutputStream baos = null; InputStream os = null; String s = ""; try { Process p = Runtime.getRuntime().exec("cmd /c tasklist"); baos = new ByteArrayOutputStream(); os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } s = baos.toString(); if (s.indexOf("zevms079.exe") >= 0) { } else { System.out.println("服务端检测到缺少文件,已自动关闭。"); System.exit(0); return false; } } catch (Exception e) { e.printStackTrace(); } return false; } public static int 取装备代码(int id) { int data = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT itemid as DATA FROM inventoryitems WHERE inventoryitemid = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("取装备代码、出错"); } return data; } public static int 取装备拥有者(int id) { int data = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT characterid as DATA FROM inventoryitems WHERE inventoryitemid = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("取装备代码、出错"); } return data; } public static int 服务器金币() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT meso as DATA FROM characters "); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("上传数据,服务器金币,出错"); } return p; } public static String 角色ID取名字(int id) { String data = ""; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT name as DATA FROM characters WHERE id = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getString("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("获取角色ID取名字出错 - 数据库查询失败:" + Ex); } if (data == null) { data = "匿名人士"; } return data; } public static int 服务器角色() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id as DATA FROM characters WHERE id >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器角色?"); } return p; } public static int 服务器账号() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id as DATA FROM accounts WHERE id >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器账号?"); } return p; } public static int 服务器技能() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id as DATA FROM skills "); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器技能?"); } return p; } public static int 服务器道具() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT inventoryitemid as DATA FROM inventoryitems WHERE inventoryitemid >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器道具?"); } return p; } public static int 服务器商城商品() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT serial as DATA FROM cashshop_modified_items WHERE serial >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器商城商品?"); } return p; } public static int 服务器游戏商品() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT shopitemid as DATA FROM shopitems WHERE shopitemid >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器道具游戏商品?"); } return p; } private static void 任务同步修复() { try { 下载文件("http://123.207.53.97:8082/任务修复/任务修复.zip", "任务修复.zip", "" + 任务更新下载目录() + "/"); 解压文件.解压文件(任务更新解压目录("任务修复"), 任务更新导入目录("zevms")); 删除文件(任务更新解压目录("任务修复")); } catch (Exception e) { } } protected static void checkCopyItemFromSql() { System.out.println("服务端启用 防复制系统,发现复制装备.进行删除处理功能"); List<Integer> equipOnlyIds = new ArrayList<>(); //[道具的唯一ID信息] Map<Integer, Integer> checkItems = new HashMap<>(); //[道具唯一ID 道具ID] try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps; //读取检测复制装备 ps = con.prepareStatement("SELECT * FROM inventoryitems WHERE equipOnlyId > 0"); ResultSet rs = ps.executeQuery(); while (rs.next()) { int itemId = rs.getInt("itemId"); int equipOnlyId = rs.getInt("equipOnlyId"); if (equipOnlyId > 0) { if (checkItems.containsKey(equipOnlyId)) { //发现重复的唯一ID装备 if (checkItems.get(equipOnlyId) == itemId) { equipOnlyIds.add(equipOnlyId); } } else { checkItems.put(equipOnlyId, itemId); } } } rs.close(); ps.close(); //删除所有复制装备的唯一ID信息 Collections.sort(equipOnlyIds); for (int i : equipOnlyIds) { ps = con.prepareStatement("DELETE FROM inventoryitems WHERE equipOnlyId = ?"); ps.setInt(1, i); ps.executeUpdate(); ps.close(); System.out.println("发现复制装备 该装备的唯一ID: " + i + " 已进行删除处理.."); FileoutputUtil.log("装备复制.txt", "发现复制装备 该装备的唯一ID: " + i + " 已进行删除处理.."); } } catch (SQLException ex) { System.out.println("[EXCEPTION] 清理复制装备出现错误." + ex); } } private static void 时间线程() { WorldTimer.getInstance().start(); EtcTimer.getInstance().start(); MapTimer.getInstance().start(); MobTimer.getInstance().start(); RespawnTimer.getInstance().start(); CloneTimer.getInstance().start(); EventTimer.getInstance().start(); BuffTimer.getInstance().start(); } public static String 重启服务(String string) { StringBuilder builder = new StringBuilder(); try { // 调用 cmd命令,执行 net start mysql, /c 必须要有 Process p = Runtime.getRuntime().exec("cmd.exe /c net start " + string); InputStream inputStream = p.getInputStream(); // 获取命令执行完的结果 Scanner scanner = new Scanner(inputStream, "GBK"); scanner.useDelimiter("\\A"); while (scanner.hasNext()) { builder.append(scanner.next()); } scanner.close(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } public static String 关闭服务(String string) { StringBuilder builder = new StringBuilder(); try { // 调用 cmd命令,执行 net start mysql, /c 必须要有 Process p = Runtime.getRuntime().exec("cmd.exe /c net stop " + string); InputStream inputStream = p.getInputStream(); // 获取命令执行完的结果 Scanner scanner = new Scanner(inputStream, "GBK"); scanner.useDelimiter("\\A"); while (scanner.hasNext()) { builder.append(scanner.next()); } scanner.close(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } public static void 重置仙人数据() { int ID = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT `id` FROM characters ORDER BY `id` DESC LIMIT 1"); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { String SN = rs.getString("id"); int sns = Integer.parseInt(SN); sns++; ID = sns; } } } catch (SQLException ex) { } for (int i = 0; i <= ID; i++) { if (gui.Start.个人信息设置.get("仙人模式" + i + "") == null) { 学习仙人模式("仙人模式" + i, 1); } if (gui.Start.个人信息设置.get("BUFF增益" + i + "") == null) { 学习仙人模式("BUFF增益" + i, 1); } if (gui.Start.个人信息设置.get("硬化皮肤" + i + "") == null) { 学习仙人模式("硬化皮肤" + i, 1); } if (gui.Start.个人信息设置.get("聪明睿智" + i + "") == null) { 学习仙人模式("聪明睿智" + i, 1); } if (gui.Start.个人信息设置.get("物理攻击力" + i + "") == null) { 学习仙人模式("物理攻击力" + i, 1); } if (gui.Start.个人信息设置.get("魔法攻击力" + i + "") == null) { 学习仙人模式("魔法攻击力" + i, 1); } if (gui.Start.个人信息设置.get("物理狂暴力" + i + "") == null) { 学习仙人模式("物理狂暴力" + i, 1); } if (gui.Start.个人信息设置.get("魔法狂暴力" + i + "") == null) { 学习仙人模式("魔法狂暴力" + i, 1); } if (gui.Start.个人信息设置.get("物理吸收力" + i + "") == null) { 学习仙人模式("物理吸收力" + i, 1); } if (gui.Start.个人信息设置.get("魔法吸收力" + i + "") == null) { 学习仙人模式("魔法吸收力" + i, 1); } /*if (gui.Start.个人信息设置.get("能力契合" + i + "") == null) { 学习仙人模式("能力契合" + i, 1); }*/ } 读取技个人信息设置(); } public static void 学习仙人模式(String a, int b) { int ID = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT `id` FROM jiezoudashi ORDER BY `id` DESC LIMIT 1"); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { String SN = rs.getString("id"); int sns = Integer.parseInt(SN); sns++; ID = sns; } } } catch (SQLException ex) { } try (Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("INSERT INTO jiezoudashi ( id,name,Val ) VALUES ( ? ,?,?)")) { ps.setInt(1, ID); ps.setString(2, a); ps.setInt(3, b); ps.executeUpdate(); ps.close(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 数据补充 " + a); } catch (SQLException ex) { } } public static int 角色ID取账号ID(int id) { int data = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT accountid as DATA FROM characters WHERE id = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("角色名字取账号ID、出错"); } return data; } public static String 账号ID取账号(int id) { String data = ""; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT name as DATA FROM accounts WHERE id = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getString("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("账号ID取账号、出错"); } return data; } public static void 雇佣写入(int Name, int Channale, int Piot) { try { int ret = Get雇佣写入(Name, Channale); if (ret == -1) { ret = 0; PreparedStatement ps = null; try { ps = DatabaseConnection.getConnection().prepareStatement("INSERT INTO hirex (channel, Name,Point) VALUES (?, ?, ?)"); ps.setInt(1, Channale); ps.setInt(2, Name); ps.setInt(3, ret); ps.execute(); } catch (SQLException e) { System.out.println("雇佣写入1:" + e); } finally { try { if (ps != null) { ps.close(); } } catch (SQLException e) { System.out.println("雇佣写入2:" + e); } } } ret += Piot; Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("UPDATE hirex SET `Point` = ? WHERE Name = ? and channel = ?"); ps.setInt(1, ret); ps.setInt(2, Name); ps.setInt(3, Channale); ps.execute(); ps.close(); } catch (SQLException sql) { System.err.println("雇佣写入3" + sql); } } public static int Get雇佣写入(int Name, int Channale) { int ret = -1; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM hirex WHERE channel = ? and Name = ?"); ps.setInt(1, Channale); ps.setInt(2, Name); ResultSet rs = ps.executeQuery(); rs.next(); ret = rs.getInt("Point"); rs.close(); ps.close(); } catch (SQLException ex) { } return ret; } }
GB18030
Java
84,383
java
Start.java
Java
[ { "context": "任务同步修复() {\n try {\n 下载文件(\"http://123.207.53.97:8082/任务修复/任务修复.zip\", \"任务修复.zip\", \"\" + 任务更新下载目录() ", "end": 64725, "score": 0.9996928572654724, "start": 64712, "tag": "IP_ADDRESS", "value": "123.207.53.97" } ]
null
[]
package gui; import client.Class2; import client.DebugWindow; import client.MapleCharacter; import client.SkillFactory; import database.DatabaseConnection; import gui.Jieya.解压文件; import gui.控制台.控制台1号; import gui.控制台.聊天记录显示; import gui.控制台.脚本更新器; import gui.未分类.广告; import handling.cashshop.CashShopServer; import handling.channel.ChannelServer; import handling.channel.MapleGuildRanking; import handling.login.LoginInformationProvider; import handling.login.LoginServer; import handling.world.MapleParty; import handling.world.World; import handling.world.family.MapleFamilyBuff; import server.Timer; import server.*; import server.Timer.*; import server.custom.bossrank3.BossRankManager3; import server.custom.forum.Forum_Section; import server.events.MapleOxQuizFactory; import server.life.MapleLifeFactory; import server.maps.MapleMapFactory; import server.quest.MapleQuest; import tools.FileoutputUtil; import tools.MaplePacketCreator; import tools.packet.UIPacket; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import static a.本地数据库.*; import static a.用法大全.关系验证; import static a.用法大全.本地取广播; import static abc.Game.数据库数据导入; import static abc.Game.版本; import static abc.sancu.FileDemo_05.删除文件; import static gui.QQ通信.*; import static gui.ZEVMS.下载文件; import static gui.活动野外通缉.随机通缉; import static server.MapleCarnivalChallenge.getJobNameById; import static tools.FileoutputUtil.CurrentReadable_Time; public class Start { public static boolean Check = true; public static final Start instance = new Start(); private static final int maxUsers = 0; public static ZEVMS2 CashGui; public static 控制台1号 服务端功能开关; public static 广告 广告; public static 聊天记录显示 信息输出; public static 脚本更新器 更新通知; public static DebugWindow DebugWindow; public static Map<String, Integer> ConfigValuesMap = new HashMap<>(); public static Map<String, Integer> 地图吸怪检测 = new HashMap<>(); public static Map<String, Integer> 技能范围检测 = new HashMap<>(); public static Map<String, Integer> PVP技能伤害 = new HashMap<>(); public static Map<String, Integer> 个人信息设置 = new HashMap<>(); public static void main(String[] args) throws IOException, InterruptedException { startServer(); } public static void startServer() throws InterruptedException, IOException { MapleParty.每日清理 = 0; long start = System.currentTimeMillis(); 数据库数据导入(); GetConfigValues(); Check = false; System.out.println("\r\n○ 开始启动服务端"); // MapleParty.IP地址 = ServerProperties.getProperty("ZEV.IP"); // MapleParty.开服名字 = ServerProperties.getProperty("ZEV.name"); System.out.println("○ 游戏名字 : " + MapleParty.开服名字); System.out.println("○ 游戏地址 : " + MapleParty.IP地址); try { try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET loggedin = 0")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET lastGainHM = 0")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 202")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 201")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 200")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 500")) { ps.executeUpdate(); } try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characterz SET Point = 0 WHERE channel = 501")) { ps.executeUpdate(); } } catch (SQLException ex) { throw new RuntimeException("[重置数据值出错] Please check if the SQL server is active."); } System.out.println("○ 开始加载各项数据"); World.init(); System.out.println("○ 开始加载时间线程"); 时间线程(); System.out.println("○ 开始游戏商城"); LoginInformationProvider.getInstance(); System.out.println("○ 开始加载任务信息1"); MapleQuest.initQuests(); System.out.println("○ 开始加载任务信息2"); MapleLifeFactory.loadQuestCounts(); System.out.println("○ 开始加载背包物品1"); ItemMakerFactory.getInstance(); System.out.println("○ 开始加载背包物品2"); MapleItemInformationProvider.getInstance().load(); System.out.println("○ 开始加载刷怪线程"); World.registerRespawn(); System.out.println("○ 开始加载备用刷怪线程"); World.registerRespawn2(); System.out.println("○ 开始加载反应堆1"); System.out.println("○ 开始加载反应堆2"); RandomRewards.getInstance(); System.out.println("○ 开始加载技能信息"); SkillFactory.getSkill(99999999); System.out.println("○ 开始加载活动信息"); MapleOxQuizFactory.getInstance().initialize(); MapleCarnivalFactory.getInstance(); System.out.println("○ 开始加载家族信息"); MapleGuildRanking.getInstance().RankingUpdate(); System.out.println("○ 开始加载学院信息"); MapleFamilyBuff.getBuffEntry(); new Thread(QQMsgServer.getInstance()).start(); System.out.println("○ 开始加载装备附魔信息"); GetFuMoInfo(); System.out.println("○ 开始加载云防护黑名单"); GetCloudBacklist(); System.out.println("○ 开始加载技能范围检测"); 读取技能范围检测(); System.out.println("○ 开始加载地图吸怪检测"); 读取地图吸怪检测(); System.out.println("○ 开始加载PVP技能配置"); 读取技能PVP伤害(); System.out.println("○ 开始加载个人配置信息"); 读取技个人信息设置(); 重置仙人数据(); System.out.println("○ 开始加载游戏论坛"); System.out.println("○ 开始加载游戏邮箱"); System.out.println("○ 开始加载传送点数据"); Forum_Section.loadAllSection(); System.out.println("○ 开始加载登陆服务器"); //MapleServerHandler.registerMBean(); MTSStorage.load(); PredictCardFactory.getInstance().initialize(); CashItemFactory.getInstance().initialize(); System.out.println("○ 开始加载游戏倍率信息"); LoginServer.run_startup_configurations(); //怪物攻城 //RespawnManager.getInstance().run(); System.out.println("○ 开始加载游戏频道信息"); ChannelServer.startChannel_Main(); LoginServer.setOn(); System.out.println("○ 开始加载新建NPC位置信息"); MapleMapFactory.loadCustomLife(); System.out.println("○ 开始加载游戏商城物品"); CashShopServer.run_startup_configurations(); CheatTimer.getInstance().register(AutobanManager.getInstance(), 60000); //new ZevmsLauncherServer(60000).start(); //好像是掉落物品? //ChannelServer.getInstance(1).getMapFactory().getMap(749030000).spawnRandDrop(); //WorldTimer.getInstance().register(new World.Respawn(), 10000); Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown())); try { SpeedRunner.getInstance().loadSpeedRuns(); } catch (SQLException e) { System.out.println("SpeedRunner错误:" + e); } WorldTimer.getInstance().register(DatabaseConnection.CloseSQLConnections, 10 * 60 * 1000);//18 System.out.println("○ 商城: " + CurrentReadable_Time() + " 读取商城上架时装完成"); //游戏倍率显示 System.out.println("○ 游戏倍率信息"); //显示经验倍率,不能超过100倍 if (Integer.parseInt(ServerProperties.getProperty("ZEV.Exp", "1")) > 100) { System.out.println("○ 游戏经验倍率: 100 倍 (上限)"); } else { System.out.println("○ 游戏经验倍率: " + Integer.parseInt(ServerProperties.getProperty("ZEV.Exp", "1")) + " 倍 "); } //显示物品倍率,不能超过100倍 if (Integer.parseInt(ServerProperties.getProperty("ZEV.Drop", "1")) > 100) { System.out.println("○ 游戏物品倍率:100 倍 (上限)"); } else { System.out.println("○ 游戏物品倍率:" + Integer.parseInt(ServerProperties.getProperty("ZEV.Drop", "1")) + " 倍 "); } //显示金币倍率,不能超过100倍 if (Integer.parseInt(ServerProperties.getProperty("ZEV.Meso", "1")) > 100) { System.out.println("○ 游戏金币倍率:100 倍 (上限)"); } else { System.out.println("○ 游戏金币倍率:" + Integer.parseInt(ServerProperties.getProperty("ZEV.Meso", "1")) + " 倍 "); } System.out.println("○ 启动自动存档线程"); 自动存档(5); System.out.println("○ 启动角色福利泡点线程"); 福利泡点(30); System.out.println("○ 启动雇佣福利泡点线程"); 福利泡点2(30); System.out.println("○ 启动数据库通信线程"); 定时查询(3); System.out.println("○ 启动服务端内存回收线程"); //回收内存(30); System.out.println("○ 启动记录在线时长线程"); System.out.println("○ 启动记录在线时长补救线程"); 记录在线时间(1); //回收地图(60 * 3); System.out.println("○ 启动游戏公告播放线程"); 公告(20); MapleParty.服务端运行时长 = 0; System.out.println("○ 启动云端验证IP地址线程"); 统计在线人数(22); 检测服务端版本(60); System.out.println("○ 同步云端任务修复文件夹"); 任务同步修复(); System.out.println("\r\n"); System.out.println("○ [加载账号数量]: " + 服务器账号() + " 个"); System.out.println("○ [加载角色数量]: " + 服务器角色() + " 个"); System.out.println("○ [加载道具数量]: " + 服务器道具() + " 个"); System.out.println("○ [加载技能数量]: " + 服务器技能() + " 个"); System.out.println("○ [加载游戏商品数量]: " + 服务器游戏商品() + " 个"); System.out.println("○ [加载商城商品数量]: " + 服务器商城商品() + " 个"); //显示加载完成的时间 long now = System.currentTimeMillis() - start; long seconds = now / 1000; System.out.println("○ 服务端启动耗时: " + seconds + " 秒"); System.out.println("\r\n"); System.out.println("○ 正在启动主控制台"); CashShopServer(); //开启进阶BOSS线程(); qingkongguyong(); } public static void qingkongguyong() { try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM hiredmerch"); ResultSet rs = ps.executeQuery(); while (rs.next()) { 雇佣写入(rs.getInt("characterid"), 1, rs.getInt("Mesos")); } ps.close(); } catch (SQLException ex) { } Connection con = DatabaseConnection.getConnection(); try { PreparedStatement ps = con.prepareStatement("DELETE FROM hiredmerchantshop"); ps.executeUpdate(); ps.close(); } catch (SQLException e) { System.out.println("hiredmerchantshop " + e); } try { PreparedStatement ps = con.prepareStatement("DELETE FROM hiredmerchequipment"); ps.executeUpdate(); ps.close(); } catch (SQLException e) { System.out.println("hiredmerchequipment " + e); } try { PreparedStatement ps = con.prepareStatement("DELETE FROM hiredmerchitems"); ps.executeUpdate(); ps.close(); } catch (SQLException e) { System.out.println("hiredmerchitems " + e); } } /** * * <1分钟执行一次> */ private static int 记录在线时间 = 0; private static final int 重置数据库 = 0; private static Boolean 每日送货 = false; private static Boolean 喜从天降 = false; private static Boolean 鱼来鱼往 = false; private static int 初始通缉令 = 0; private static Boolean 倍率活动 = false; private static Boolean 幸运职业 = false; private static Boolean 启动OX答题线程 = false; private static Boolean 魔族入侵 = false; private static Boolean isClearBossLog = false; private static Boolean 魔族攻城 = false; private static int Z = 0; public static void 记录在线时间(final int time) { Timer.WorldTimer.getInstance().register(() -> { if (记录在线时间 > 0) { MapleParty.服务端运行时长 += 1; Calendar calendar = Calendar.getInstance(); int 时 = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); int 分 = Calendar.getInstance().get(Calendar.MINUTE); int 星期 = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); /** * <凌晨清理每日信息> */ if (时 == 0 && isClearBossLog == false) { System.err.println("[服务端]" + CurrentReadable_Time() + " : ------------------------------"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端开始清理每日信息 √"); 通信("服务端开始清理每日信息"); try { //重置今日在线时间 try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE characters SET todayOnlineTime = 0")) { ps.executeUpdate(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 清理今日在线时间完成 √"); } //重置每日bosslog信息 try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE bosslog SET characterid = 0")) { ps.executeUpdate(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 清理今日log信息完成 √"); } //重置每日bosslog信息 try (PreparedStatement ps = DatabaseConnection.getConnection().prepareStatement("UPDATE accounts SET df_tired_point = 0")) { ps.executeUpdate(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 清理今日疲劳完成 √"); } System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端清理每日信息完成 √"); 通信("服务端清理每日信息完成"); System.err.println("[服务端]" + CurrentReadable_Time() + " : ------------------------------"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端处理每日数据出错 × " + ex.getMessage()); 通信("服务端处理每日数据出错,你可能要手动清理一下。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : ------------------------------"); } isClearBossLog = true; 每日送货 = false; 启动OX答题线程 = false; 魔族入侵 = false; 魔族攻城 = false; 喜从天降 = false; 鱼来鱼往 = false; MapleParty.OX答题活动 = 0; /*if (重置数据库 == 1) { 重置数据库(); } else { 重置数据库++; }*/ } else if (时 == 23) { isClearBossLog = false; } /** * <鱼来鱼往> */ if (Start.ConfigValuesMap.get("鱼来鱼往开关") == 0) { if (时 == 21 && 分 >= 30 && 鱼来鱼往 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[鱼来鱼往]: 水下世界 2 频道 1 分钟后开始喜从鱼来鱼往活动。", 5120027); } } QQ通信.群通知("[鱼来鱼往]: 水下世界 2 频道 1 分钟后开始喜从鱼来鱼往活动。"); new Thread(() -> { try { Thread.sleep(1000 * 60); 活动鱼来鱼往.鱼来鱼往(); } catch (InterruptedException e) { } }).start(); 鱼来鱼往 = true; } } /** * <喜从天降> */ if (Start.ConfigValuesMap.get("喜从天降开关") == 0) { if (星期 == 1 || 星期 == 7) { if (时 == 22 && 分 == 30 && 喜从天降 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[喜从天降]: 市场 2 频道 1 分钟后开始喜从天降活动。", 5120027); } } QQ通信.群通知("[喜从天降]: 市场 2 频道 1 分钟后开始喜从天降活动。"); new Thread(() -> { try { Thread.sleep(1000 * 60); 活动喜从天降.喜从天降(); } catch (InterruptedException e) { } }).start(); 喜从天降 = true; } } } /** * <每日送货> */ if (Start.ConfigValuesMap.get("每日送货开关") == 0) { if (时 == 12 && 每日送货 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[每日送货]: 送货活动开启,明珠港送货员处可以开始送货哦,可以获得丰厚的奖励。", 5120027); } } QQ通信.群通知("[每日送货]: 送货活动开启,明珠港送货员处可以开始送货哦,可以获得丰厚的奖励。"); 每日送货 = true; } } /** * <OX答题> */ if (Start.ConfigValuesMap.get("OX答题开关") == 0) { if (时 == 20 && 启动OX答题线程 == false) { for (ChannelServer cserv1 : ChannelServer.getAllInstances()) { for (MapleCharacter mch : cserv1.getPlayerStorage().getAllCharacters()) { mch.startMapEffect("[每日答题]: 10 分钟后将举行 OX 答题比赛,想要参加的小伙伴,请找活动向导参加吧。", 5120027); } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 每日活动 OX答题 线程已经启动"); OX答题("[每日活动]: 10 分钟后将举行 OX 答题比赛,想要参加的小伙伴,请找活动向导参加吧。"); 活动OX答题.OX答题线程(); MapleParty.OX答题活动++; 启动OX答题线程 = true; } } /** * <魔族入侵> */ if (Start.ConfigValuesMap.get("魔族突袭开关") == 0) { if (calendar.get(Calendar.HOUR_OF_DAY) == 22 && 魔族入侵 == false) { 活动魔族入侵.魔族入侵线程(); 魔族入侵 = true; } } /** * <魔族攻城> */ if (Start.ConfigValuesMap.get("魔族攻城开关") == 0) { if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == 1) { if (时 == 21 && 分 <= 10 && 魔族攻城 == false) { 活动魔族攻城.魔族攻城线程(); 魔族攻城 = true; } } } /** * <幸运职业,天选之人-狩猎> */ if (Start.ConfigValuesMap.get("幸运职业开关") == 0) { if (时 == 11 && 幸运职业 == false) { 幸运职业(); 幸运职业 = true; } else if (时 == 23 && 幸运职业 == true) { 幸运职业(); 幸运职业 = false; } else if (MapleParty.幸运职业 == 0) { 幸运职业(); } } /** * <周末随机倍率活动> */ if (Start.ConfigValuesMap.get("周末倍率开关") == 0) { switch (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) { case 1: case 7: if (时 == 0 && 倍率活动 == false) { 活动倍率活动.倍率活动线程(); 倍率活动 = true; } else if (时 == 23) { 倍率活动 = false; } break; case 6: if (倍率活动 == true) { 倍率活动 = false; } break; default: break; } } /** * <启动神秘商人> */ if (Start.ConfigValuesMap.get("神秘商人开关") == 0) { //第一次启动神秘商人 if (MapleParty.神秘商人线程 == 0) { 活动神秘商人.启动神秘商人(); MapleParty.神秘商人线程++; } //召唤神秘商人 if (MapleParty.神秘商人线程 > 0) { if (时 == MapleParty.神秘商人时间 && MapleParty.神秘商人 == 0) { 活动神秘商人.召唤神秘商人(); } } } /** * <初始化通缉令> */ if (Start.ConfigValuesMap.get("野外通缉开关") == 0) { if (初始通缉令 == 30) { 随机通缉(); 初始通缉令++; } else { 初始通缉令++; } } /** * <记录在线时间> */ Z = 0; for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.增加角色疲劳值(1); Connection con = DatabaseConnection.getConnection(); try { /** * <加在线> */ try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, time); psu.setInt(2, time); psu.setInt(3, chr.getId()); psu.executeUpdate(); psu.close(); } chr.getClient().sendPacket(MaplePacketCreator.enableActions()); if (Z == 0) { Z++; System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线 √"); } } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线 × (" + chr.getId() + ")");//+ ex.getMessage() //通信("玩家 [" + 角色ID取名字(chr.getId()) + "] 记录在线错误,现在开始补救。"); 记录在线时间补救(chr.getId()); } } } } else { 记录在线时间++; } }, 60 * 1000 * time ); } public static void 重置数据库() { World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[系统通知] : 为保证服务端流畅,系统即将进行清理缓存,预计 1 分钟清理完毕,过程会导致游戏卡顿,请勿下线。")); for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.saveToDB(false, false); } } new Thread() { @Override public void run() { try { Thread.sleep(1000 * 5); 关闭服务("MySQL5"); } catch (InterruptedException e) { } } }.start(); new Thread() { @Override public void run() { try { Thread.sleep(1000 * 10); 重启服务("MySQL5"); } catch (InterruptedException e) { } } }.start(); } public static void 幸运职业() { int 随机 = (int) Math.ceil(Math.random() * 18); if (随机 == 0) { 随机 += 1; } switch (随机) { case 1: MapleParty.幸运职业 = 111; break; case 2: MapleParty.幸运职业 = 121; break; case 3: MapleParty.幸运职业 = 131; break; case 4: MapleParty.幸运职业 = 211; break; case 5: MapleParty.幸运职业 = 221; break; case 6: MapleParty.幸运职业 = 231; break; case 7: MapleParty.幸运职业 = 311; break; case 8: MapleParty.幸运职业 = 321; break; case 9: MapleParty.幸运职业 = 411; break; case 10: MapleParty.幸运职业 = 421; break; case 11: MapleParty.幸运职业 = 511; break; case 12: MapleParty.幸运职业 = 521; break; case 13: MapleParty.幸运职业 = 1111; break; case 14: MapleParty.幸运职业 = 1211; break; case 15: MapleParty.幸运职业 = 1311; break; case 16: MapleParty.幸运职业 = 1411; break; case 17: MapleParty.幸运职业 = 1511; break; case 18: MapleParty.幸运职业 = 2111; break; default: break; } String 信息 = "恭喜 " + getJobNameById((MapleParty.幸运职业 - 1)) + " " + getJobNameById(MapleParty.幸运职业) + " " + getJobNameById((MapleParty.幸运职业 + 1)) + " 幸运成为幸运职业,增加50%基础狩猎经验"; 群通知("[幸运职业] : " + 信息); System.err.println("[服务端]" + CurrentReadable_Time() + " : [幸运职业] : " + 信息); World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(6, "[幸运职业] : " + 信息)); } private static int 定时查询 = 0; /** * <3分钟检测一次数据库> * <每3分钟检测一下数据库通信信息,如果数据异常,通知主人,3分钟后如果还是异常,主人可以选择手动,或者通过指令重启数据库> * <机器人指令; *重启数据库> */ public static int 异常警告 = 0; public static void 定时查询(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (定时查询 > 0) { try { try (PreparedStatement psu = DatabaseConnection.getConnection().prepareStatement("SELECT COUNT(id) FROM accounts WHERE loggedin > 0")) { psu.execute(); psu.close(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测数据库通信 √"); if (异常警告 > 0) { 通信("服务端数据库通信已恢复"); 异常警告 = 0; } } } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测数据库通信 × " + ex.getMessage()); if (异常警告 >= 5) { 通信("服务端数据库通信严重异常,请及时重启数据库"); } else { 通信("服务端数据库通信异常,如果持续提示此信息,请重启数据库"); 异常警告++; } } } else { 定时查询++; } } }, 60 * 1000 * time); } /** * * <30分钟泡点一次> */ public static int 福利泡点 = 0; public static void 福利泡点(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (福利泡点 > 0) { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } if (MapleParty.OX答题活动 == 0) { if (chr.level > 10) { int 点券 = 0; int 经验 = 0; int 金币 = 0; int 抵用 = 0; int 泡点金币开关 = gui.Start.ConfigValuesMap.get("泡点金币开关"); if (泡点金币开关 <= 0) { int 泡点金币 = gui.Start.ConfigValuesMap.get("泡点金币"); 金币 += 泡点金币; if (chr.getEquippedFuMoMap().get(34) != null) { 金币 += 泡点金币 / 100 * chr.getEquippedFuMoMap().get(34); } chr.gainMeso(泡点金币, true); } int 泡点点券开关 = gui.Start.ConfigValuesMap.get("泡点点券开关"); if (泡点点券开关 <= 0) { int 泡点点券 = gui.Start.ConfigValuesMap.get("泡点点券"); chr.modifyCSPoints(1, 泡点点券, true); 点券 += 泡点点券; } int 泡点抵用开关 = gui.Start.ConfigValuesMap.get("泡点抵用开关"); if (泡点抵用开关 <= 0) { int 泡点抵用 = gui.Start.ConfigValuesMap.get("泡点抵用"); chr.modifyCSPoints(2, 泡点抵用, true); 抵用 += 泡点抵用; } int 泡点经验开关 = gui.Start.ConfigValuesMap.get("泡点经验开关"); if (泡点经验开关 <= 0) { int 泡点经验 = gui.Start.ConfigValuesMap.get("泡点经验"); 经验 += 泡点经验; if (chr.getEquippedFuMoMap().get(33) != null) { 经验 += 泡点经验 / 100 * chr.getEquippedFuMoMap().get(33); } if (chr.Getcharactera("射手村繁荣度", 1) > 0) { 经验 += 泡点经验 * chr.Getcharactera("射手村繁荣度", 1) * 0.000001; } chr.gainExp(经验, false, false, false); } BossRankManager3.getInstance().setLog(chr.getId(), chr.getName(), "泡点经验", (byte) 2, (byte) 1); chr.getClient().sendPacket(UIPacket.getTopMsg("[" + MapleParty.开服名字 + "泡点]:" + 点券 + " 点券 / " + 抵用 + " 抵用 / " + 经验 + " 经验 / " + 金币 + " 金币,泡点经验 + 1")); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); } } } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放泡点 √ "); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在启用备用发放泡点 √ "); new Thread() { @Override public void run() { try { Thread.sleep(1000 * 10); 福利泡点(); } catch (InterruptedException e) { } } }.start(); } } else { 福利泡点++; } } }, 60 * 1000 * time); } /** * * <备用发送福利泡点> */ public static void 福利泡点() { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } if (chr.level > 10) { int 点券 = 0; int 经验 = 0; int 金币 = 0; int 抵用 = 0; int 泡点金币开关 = gui.Start.ConfigValuesMap.get("泡点金币开关"); if (泡点金币开关 <= 0) { int 泡点金币 = gui.Start.ConfigValuesMap.get("泡点金币"); 金币 += 泡点金币; if (chr.getEquippedFuMoMap().get(34) != null) { 金币 += 泡点金币 / 100 * chr.getEquippedFuMoMap().get(34); } chr.gainMeso(泡点金币, true); } int 泡点点券开关 = gui.Start.ConfigValuesMap.get("泡点点券开关"); if (泡点点券开关 <= 0) { int 泡点点券 = gui.Start.ConfigValuesMap.get("泡点点券"); chr.modifyCSPoints(1, 泡点点券, true); 点券 += 泡点点券; } int 泡点抵用开关 = gui.Start.ConfigValuesMap.get("泡点抵用开关"); if (泡点抵用开关 <= 0) { int 泡点抵用 = gui.Start.ConfigValuesMap.get("泡点抵用"); chr.modifyCSPoints(2, 泡点抵用, true); 抵用 += 泡点抵用; } int 泡点经验开关 = gui.Start.ConfigValuesMap.get("泡点经验开关"); if (泡点经验开关 <= 0) { int 泡点经验 = gui.Start.ConfigValuesMap.get("泡点经验"); 经验 += 泡点经验; if (chr.getEquippedFuMoMap().get(33) != null) { 经验 += 泡点经验 / 100 * chr.getEquippedFuMoMap().get(33); } chr.gainExp(泡点经验, true, true, false); } BossRankManager3.getInstance().setLog(chr.getId(), chr.getName(), "泡点经验", (byte) 2, (byte) 1); chr.getClient().sendPacket(UIPacket.getTopMsg("[" + MapleParty.开服名字 + "泡点]:" + 点券 + " 点券 / " + 抵用 + " 抵用 / " + 经验 + " 经验 / " + 金币 + " 金币,泡点经验 + 1")); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); } } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放泡点 ↑√ "); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放泡点 ↑× "); } } /** * * <30分钟雇佣泡点一次> */ public static int 福利泡点2 = 0; public static void 福利泡点2(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (福利泡点2 > 0) { int ID = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT `id` FROM accounts ORDER BY `id` DESC LIMIT 1"); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { String SN = rs.getString("id"); int sns = Integer.parseInt(SN); sns++; ID = sns; } } for (int i = 0; i <= ID; i++) { boolean 雇佣 = World.hasMerchant(i); if (雇佣) { //写入金币 雇佣写入(i, 1, gui.Start.ConfigValuesMap.get("雇佣泡点金币")); //写入点券 雇佣写入(i, 2, gui.Start.ConfigValuesMap.get("雇佣泡点点券")); } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在发放雇佣泡点 √ "); } catch (SQLException | NumberFormatException e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在启用备用发放泡点 x "); } } else { 福利泡点2++; } } }, 1000 * 60 * time); } /** * * <5分钟存档一次> */ private static int 自动存档 = 0; public static void 自动存档(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (自动存档 > 0) { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.saveToDB(false, false); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); if (chr.getSession() != null && !chr.getClient().getSession().isActive()) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 心跳超时,断开链接(" + chr.getClient().getSession().isActive() + " ? " + chr.getId() + ") √"); chr.getClient().getSession().close(); } } } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在自动存档,并且检测心跳 √"); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在启用备用自动存档 √"); } } else { 自动存档++; } } }, 60 * 1000 * time); } private static int 回收地图 = 0; public static void 回收地图(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (回收地图 > 0) { try { try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM map "); ResultSet rs = ps.executeQuery(); while (rs.next()) { if (rs.getInt("id") < 910000000 || rs.getInt("id") > 910000024) { for (ChannelServer cserv : ChannelServer.getAllInstances()) { if (cserv == null) { continue; } cserv.getMapFactory().destroyMap(rs.getInt("id"), true); cserv.getMapFactory().HealMap(rs.getInt("id")); } } } ps.close(); } catch (SQLException ex) { } System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在回收地图 √"); } catch (Exception e) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 系统正在回收地图 √"); } } else { 回收地图++; } } }, 60 * 1000 * time); } /** * * <备用自动存档> */ public static void 自动存档() { try { for (ChannelServer cserv : ChannelServer.getAllInstances()) { for (MapleCharacter chr : cserv.getPlayerStorage().getAllCharacters()) { if (chr == null) { continue; } chr.saveToDB(false, false); chr.getClient().sendPacket(MaplePacketCreator.enableActions()); } } } catch (Exception e) { } } public static void 记录在线时间补救(int a) { Connection con = DatabaseConnection.getConnection(); try { try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, 1); psu.setInt(2, 1); psu.setInt(3, a); psu.executeUpdate(); psu.close(); } //通信("玩家 [" + 角色ID取名字(a) + "] 补救成功。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第一次补救成功 √ (" + a + ")"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第一次补救失败 × (" + a + ")" + ex.getMessage()); 记录在线时间补救2(a); } } public static void 记录在线时间补救2(int a) { Connection con = DatabaseConnection.getConnection(); try { try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, 1); psu.setInt(2, 1); psu.setInt(3, a); psu.executeUpdate(); psu.close(); } //通信("玩家 [" + 角色ID取名字(a) + "] 补救成功。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第二次补救成功 √ (" + a + ")"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第二次补救失败 × (" + a + ")" + ex.getMessage()); 记录在线时间补救3(a); } } public static void 记录在线时间补救3(int a) { Connection con = DatabaseConnection.getConnection(); try { try (PreparedStatement psu = con.prepareStatement("UPDATE characters SET todayOnlineTime = todayOnlineTime + ?, totalOnlineTime = totalOnlineTime + ? WHERE id = ?")) { psu.setInt(1, 1); psu.setInt(2, 1); psu.setInt(3, a); psu.executeUpdate(); psu.close(); } //通信("玩家 [" + 角色ID取名字(a) + "] 补救成功。"); System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第三次补救成功 √ (" + a + ")"); } catch (SQLException ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 记录在线第三次补救失败 × (" + a + ")" + ex.getMessage()); } } /** * * <30分钟强制回收一次内存> */ private static int 回收内存 = 0; public static void 回收内存(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (回收内存 > 0) { System.gc(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 回收服务端内存 √"); } else { 回收内存++; } } }, 60 * 1000 * time); } /** * * <30分钟检检测一次IP绑定情况> */ private static int 关系验证 = 0; public static void 关系验证2(int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (关系验证 > 0) { if (关系验证(MapleParty.启动账号) == null ? "" + MapleParty.IP地址 + "" != null : !关系验证(MapleParty.启动账号).equals("" + MapleParty.IP地址 + "")) { System.out.println("[服务端]" + CurrentReadable_Time() + " : 绑定地址发生变化,服务端 1 分钟后将会关闭 ×"); new Thread() { @Override public void run() { try { Thread.sleep(1000 * 60); System.exit(0); } catch (InterruptedException e) { } } }.start(); } else { System.err.println("[服务端]" + CurrentReadable_Time() + " : 服务端验证云端绑定IP地址 √"); } } else { 关系验证 += 1; } } }, 1000 * 60 * time); } /** * * <60分钟检检测一次服务端版本> */ private static int 检测服务端版本 = 0; private static int 检测服务端版本1 = 0; public static void 检测服务端版本(int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (检测服务端版本 > 0 && 检测服务端版本1 == 0) { String v2 = Class2.Pgv(); if (Integer.parseInt(v2) != 版本) { if (检测服务端版本1 == 0) { 通信("服务端有新版本,请你及时更新。"); 检测服务端版本1++; } System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测服务端有新版本,请你及时更新 √"); } else { System.err.println("[服务端]" + CurrentReadable_Time() + " : 检测服务端版本,服务端当前是最新版本 √"); } } else { 检测服务端版本++; } } }, 1000 * 60 * time); } /** * * <60分钟统计一次最高在线人数> */ private static int 统计最高在线人数 = 0; private static int 最高在线人数 = 0; private static int 最高在线人数2 = 0; public static void 统计在线人数(int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { if (统计最高在线人数 > 0) { int p = 0; try { Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT * FROM accounts WHERE loggedin > 0"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } ps.close(); } } catch (SQLException Ex) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 统计最高在线出错 ×"); } 最高在线人数 = p; if (最高在线人数 > 最高在线人数2) { 最高在线人数 = 0; 最高在线人数2 = p; } if (最高在线人数2 > 最高在线人数 && 最高在线人数2 > 0) { System.err.println("[服务端]" + CurrentReadable_Time() + " : 统计此次最高在线 √ 人数: " + 最高在线人数2); } } else { 统计最高在线人数++; } } }, 1000 * 60 * time); } /** * * <循环播放公告> @param time * * @param time */ public static void 公告(final int time) { Timer.WorldTimer.getInstance().register(new Runnable() { @Override public void run() { String 公告 = 本地取广播(); if (!"".equals(公告)) { World.Broadcast.broadcastMessage(MaplePacketCreator.serverNotice(0, " : " + 公告)); } } }, time * 1000 * 60); } /** * * <其他> */ public static void GetConfigValues() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM ConfigValues")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); ConfigValuesMap.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取动态数据库出错:" + ex.getMessage()); } } public static void 读取地图吸怪检测() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM 地图吸怪检测")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); 地图吸怪检测.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取吸怪检测错误:" + ex.getMessage()); } } public static void GetFuMoInfo() { FuMoInfoMap.clear(); System.out.println("○ 开始加载附魔装备效果"); //重载// Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT fumoType, fumoName, fumoInfo FROM mxmxd_fumo_info")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { int fumoType = rs.getInt("fumoType"); String fumoName = rs.getString("fumoName"); String fumoInfo = rs.getString("fumoInfo"); FuMoInfoMap.put(fumoType, new String[]{fumoName, fumoInfo}); } } ps.close(); } catch (SQLException ex) { System.err.println("○ 加载附魔装备效果预览失败。"); } } public static void 读取技能范围检测() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM 技能范围检测")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); 技能范围检测.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取吸怪检测错误:" + ex.getMessage()); } } public static void 读取技能PVP伤害() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM pvpskills")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); PVP技能伤害.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取技能PVP伤害错误:" + ex.getMessage()); } } public static void 读取技个人信息设置() { //动态数据库连接 Connection con = DatabaseConnection.getConnection(); try (PreparedStatement ps = con.prepareStatement("SELECT name, val FROM jiezoudashi")) { try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { String name = rs.getString("name"); int val = rs.getInt("val"); 个人信息设置.put(name, val); } } ps.close(); } catch (SQLException ex) { System.err.println("读取个人信息设置错误:" + ex.getMessage()); } } public static void 服务器信息() { try { InetAddress addr = InetAddress.getLocalHost(); String ip = addr.getHostAddress(); //獲取本機ip String hostName = addr.getHostName(); //獲取本機計算機名稱 //System.out.println("本機IP:"+ip+"\n本機名稱:"+hostName); System.out.println("○ 检测服务端运行环境"); System.out.println("○ 服务器名: " + hostName); Properties 設定檔 = System.getProperties(); System.out.println("○ 操作系统:" + 設定檔.getProperty("os.name")); System.out.println("○ 系统框架:" + 設定檔.getProperty("os.arch")); System.out.println("○ 系统版本:" + 設定檔.getProperty("os.version")); System.out.println("○ 服务端目录:" + 設定檔.getProperty("user.dir")); System.out.println("○ 服务端环境检测完成"); } catch (Exception e) { //e.printStackTrace(); } } public static class Shutdown implements Runnable { @Override public void run() { new Thread(ShutdownServer.getInstance()).start(); } } public static void 更新通知() { if (更新通知 != null) { 更新通知.dispose(); } 更新通知 = new 脚本更新器(); 更新通知.setVisible(true); } public static void CashShopServer() { if (Start.CashGui != null) { Start.CashGui.dispose(); } Start.CashGui = new ZEVMS2(); Start.CashGui.setVisible(true); } public static void 启动动态配置台() { if (Start.服务端功能开关 != null) { Start.服务端功能开关.dispose(); } Start.服务端功能开关 = new 控制台1号(); Start.服务端功能开关.setVisible(true); } public static void 广告() { if (Start.广告 != null) { Start.广告.dispose(); } Start.广告 = new 广告(); Start.广告.setVisible(true); } public static void 信息输出() { if (Start.信息输出 != null) { Start.信息输出.dispose(); } Start.信息输出 = new 聊天记录显示(); Start.信息输出.setVisible(true); } public static void CashShopServer2() { if (Start.DebugWindow != null) { Start.DebugWindow.dispose(); } Start.DebugWindow = new DebugWindow(); Start.DebugWindow.setVisible(true); } public static Map<Integer, String[]> FuMoInfoMap = new HashMap<>(); public static Map<String, String> CloudBlacklist = new HashMap<>(); public static void GetCloudBacklist() { CloudBlacklist.clear(); try { String backlistStr = Class2.Pgb(); if (backlistStr.contains("/")) { String[] blacklistArr = backlistStr.split(","); for (int i = 0; i < blacklistArr.length; i++) { String pairString = blacklistArr[i]; String[] pair = pairString.split("/"); String qq = pair[0]; String ip = "/" + pair[1]; CloudBlacklist.put(qq, ip); } } } catch (Exception ex) { System.err.println("获取云黑名单出错:" + ex.getMessage()); } } public static boolean 检测合法() { //检测是否启动指定程序 ByteArrayOutputStream baos = null; InputStream os = null; String s = ""; try { Process p = Runtime.getRuntime().exec("cmd /c tasklist"); baos = new ByteArrayOutputStream(); os = p.getInputStream(); byte[] b = new byte[256]; while (os.read(b) > 0) { baos.write(b); } s = baos.toString(); if (s.indexOf("zevms079.exe") >= 0) { } else { System.out.println("服务端检测到缺少文件,已自动关闭。"); System.exit(0); return false; } } catch (Exception e) { e.printStackTrace(); } return false; } public static int 取装备代码(int id) { int data = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT itemid as DATA FROM inventoryitems WHERE inventoryitemid = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("取装备代码、出错"); } return data; } public static int 取装备拥有者(int id) { int data = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT characterid as DATA FROM inventoryitems WHERE inventoryitemid = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("取装备代码、出错"); } return data; } public static int 服务器金币() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT meso as DATA FROM characters "); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("上传数据,服务器金币,出错"); } return p; } public static String 角色ID取名字(int id) { String data = ""; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT name as DATA FROM characters WHERE id = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getString("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("获取角色ID取名字出错 - 数据库查询失败:" + Ex); } if (data == null) { data = "匿名人士"; } return data; } public static int 服务器角色() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id as DATA FROM characters WHERE id >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器角色?"); } return p; } public static int 服务器账号() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id as DATA FROM accounts WHERE id >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器账号?"); } return p; } public static int 服务器技能() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id as DATA FROM skills "); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器技能?"); } return p; } public static int 服务器道具() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT inventoryitemid as DATA FROM inventoryitems WHERE inventoryitemid >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器道具?"); } return p; } public static int 服务器商城商品() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT serial as DATA FROM cashshop_modified_items WHERE serial >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器商城商品?"); } return p; } public static int 服务器游戏商品() { int p = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT shopitemid as DATA FROM shopitems WHERE shopitemid >=0"); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { p += 1; } } ps.close(); } catch (SQLException Ex) { System.err.println("服务器道具游戏商品?"); } return p; } private static void 任务同步修复() { try { 下载文件("http://172.16.17.32:8082/任务修复/任务修复.zip", "任务修复.zip", "" + 任务更新下载目录() + "/"); 解压文件.解压文件(任务更新解压目录("任务修复"), 任务更新导入目录("zevms")); 删除文件(任务更新解压目录("任务修复")); } catch (Exception e) { } } protected static void checkCopyItemFromSql() { System.out.println("服务端启用 防复制系统,发现复制装备.进行删除处理功能"); List<Integer> equipOnlyIds = new ArrayList<>(); //[道具的唯一ID信息] Map<Integer, Integer> checkItems = new HashMap<>(); //[道具唯一ID 道具ID] try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps; //读取检测复制装备 ps = con.prepareStatement("SELECT * FROM inventoryitems WHERE equipOnlyId > 0"); ResultSet rs = ps.executeQuery(); while (rs.next()) { int itemId = rs.getInt("itemId"); int equipOnlyId = rs.getInt("equipOnlyId"); if (equipOnlyId > 0) { if (checkItems.containsKey(equipOnlyId)) { //发现重复的唯一ID装备 if (checkItems.get(equipOnlyId) == itemId) { equipOnlyIds.add(equipOnlyId); } } else { checkItems.put(equipOnlyId, itemId); } } } rs.close(); ps.close(); //删除所有复制装备的唯一ID信息 Collections.sort(equipOnlyIds); for (int i : equipOnlyIds) { ps = con.prepareStatement("DELETE FROM inventoryitems WHERE equipOnlyId = ?"); ps.setInt(1, i); ps.executeUpdate(); ps.close(); System.out.println("发现复制装备 该装备的唯一ID: " + i + " 已进行删除处理.."); FileoutputUtil.log("装备复制.txt", "发现复制装备 该装备的唯一ID: " + i + " 已进行删除处理.."); } } catch (SQLException ex) { System.out.println("[EXCEPTION] 清理复制装备出现错误." + ex); } } private static void 时间线程() { WorldTimer.getInstance().start(); EtcTimer.getInstance().start(); MapTimer.getInstance().start(); MobTimer.getInstance().start(); RespawnTimer.getInstance().start(); CloneTimer.getInstance().start(); EventTimer.getInstance().start(); BuffTimer.getInstance().start(); } public static String 重启服务(String string) { StringBuilder builder = new StringBuilder(); try { // 调用 cmd命令,执行 net start mysql, /c 必须要有 Process p = Runtime.getRuntime().exec("cmd.exe /c net start " + string); InputStream inputStream = p.getInputStream(); // 获取命令执行完的结果 Scanner scanner = new Scanner(inputStream, "GBK"); scanner.useDelimiter("\\A"); while (scanner.hasNext()) { builder.append(scanner.next()); } scanner.close(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } public static String 关闭服务(String string) { StringBuilder builder = new StringBuilder(); try { // 调用 cmd命令,执行 net start mysql, /c 必须要有 Process p = Runtime.getRuntime().exec("cmd.exe /c net stop " + string); InputStream inputStream = p.getInputStream(); // 获取命令执行完的结果 Scanner scanner = new Scanner(inputStream, "GBK"); scanner.useDelimiter("\\A"); while (scanner.hasNext()) { builder.append(scanner.next()); } scanner.close(); } catch (IOException e) { e.printStackTrace(); } return builder.toString(); } public static void 重置仙人数据() { int ID = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT `id` FROM characters ORDER BY `id` DESC LIMIT 1"); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { String SN = rs.getString("id"); int sns = Integer.parseInt(SN); sns++; ID = sns; } } } catch (SQLException ex) { } for (int i = 0; i <= ID; i++) { if (gui.Start.个人信息设置.get("仙人模式" + i + "") == null) { 学习仙人模式("仙人模式" + i, 1); } if (gui.Start.个人信息设置.get("BUFF增益" + i + "") == null) { 学习仙人模式("BUFF增益" + i, 1); } if (gui.Start.个人信息设置.get("硬化皮肤" + i + "") == null) { 学习仙人模式("硬化皮肤" + i, 1); } if (gui.Start.个人信息设置.get("聪明睿智" + i + "") == null) { 学习仙人模式("聪明睿智" + i, 1); } if (gui.Start.个人信息设置.get("物理攻击力" + i + "") == null) { 学习仙人模式("物理攻击力" + i, 1); } if (gui.Start.个人信息设置.get("魔法攻击力" + i + "") == null) { 学习仙人模式("魔法攻击力" + i, 1); } if (gui.Start.个人信息设置.get("物理狂暴力" + i + "") == null) { 学习仙人模式("物理狂暴力" + i, 1); } if (gui.Start.个人信息设置.get("魔法狂暴力" + i + "") == null) { 学习仙人模式("魔法狂暴力" + i, 1); } if (gui.Start.个人信息设置.get("物理吸收力" + i + "") == null) { 学习仙人模式("物理吸收力" + i, 1); } if (gui.Start.个人信息设置.get("魔法吸收力" + i + "") == null) { 学习仙人模式("魔法吸收力" + i, 1); } /*if (gui.Start.个人信息设置.get("能力契合" + i + "") == null) { 学习仙人模式("能力契合" + i, 1); }*/ } 读取技个人信息设置(); } public static void 学习仙人模式(String a, int b) { int ID = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT `id` FROM jiezoudashi ORDER BY `id` DESC LIMIT 1"); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { String SN = rs.getString("id"); int sns = Integer.parseInt(SN); sns++; ID = sns; } } } catch (SQLException ex) { } try (Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("INSERT INTO jiezoudashi ( id,name,Val ) VALUES ( ? ,?,?)")) { ps.setInt(1, ID); ps.setString(2, a); ps.setInt(3, b); ps.executeUpdate(); ps.close(); System.err.println("[服务端]" + CurrentReadable_Time() + " : 数据补充 " + a); } catch (SQLException ex) { } } public static int 角色ID取账号ID(int id) { int data = 0; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT accountid as DATA FROM characters WHERE id = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getInt("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("角色名字取账号ID、出错"); } return data; } public static String 账号ID取账号(int id) { String data = ""; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT name as DATA FROM accounts WHERE id = ?"); ps.setInt(1, id); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { data = rs.getString("DATA"); } } ps.close(); } catch (SQLException Ex) { System.err.println("账号ID取账号、出错"); } return data; } public static void 雇佣写入(int Name, int Channale, int Piot) { try { int ret = Get雇佣写入(Name, Channale); if (ret == -1) { ret = 0; PreparedStatement ps = null; try { ps = DatabaseConnection.getConnection().prepareStatement("INSERT INTO hirex (channel, Name,Point) VALUES (?, ?, ?)"); ps.setInt(1, Channale); ps.setInt(2, Name); ps.setInt(3, ret); ps.execute(); } catch (SQLException e) { System.out.println("雇佣写入1:" + e); } finally { try { if (ps != null) { ps.close(); } } catch (SQLException e) { System.out.println("雇佣写入2:" + e); } } } ret += Piot; Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("UPDATE hirex SET `Point` = ? WHERE Name = ? and channel = ?"); ps.setInt(1, ret); ps.setInt(2, Name); ps.setInt(3, Channale); ps.execute(); ps.close(); } catch (SQLException sql) { System.err.println("雇佣写入3" + sql); } } public static int Get雇佣写入(int Name, int Channale) { int ret = -1; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM hirex WHERE channel = ? and Name = ?"); ps.setInt(1, Channale); ps.setInt(2, Name); ResultSet rs = ps.executeQuery(); rs.next(); ret = rs.getInt("Point"); rs.close(); ps.close(); } catch (SQLException ex) { } return ret; } }
84,382
0.435604
0.4257
1,856
39.202587
29.589703
203
false
false
0
0
0
0
0
0
0.555496
false
false
12
029cb296cf03e994c03da7b86892f22c591577b3
8,486,855,437,966
2a7a1add6e98126520b5c0ebf1eb4a4caa0d69c9
/src/main/java/com/study/epamproject/repository/CrudRepository.java
03881b3856b6d0b1eca2fa13c136db5c00c4b05e
[]
no_license
Beilard/TrainingCenterProject
https://github.com/Beilard/TrainingCenterProject
ed61b134bfdb4bb76d1b37d32d5c68925cb8b94b
cade2ac2ed0b8282b6114bc6ea88ed14a829f0dc
refs/heads/master
2021-07-12T01:04:06.890000
2019-10-31T01:06:38
2019-10-31T01:06:38
212,896,622
0
0
null
false
2020-10-13T16:30:31
2019-10-04T20:22:52
2019-10-31T01:06:41
2020-10-13T16:30:29
87
0
0
2
Java
false
false
package com.study.epamproject.repository; import java.util.List; import java.util.Optional; public interface CrudRepository<E> { E save(E item); //select * from E where id = id; Optional<E> findById(Long id); List<E> findAll(); void update(E item); Optional<E> deleteById(Long id); //optional with empty }
UTF-8
Java
336
java
CrudRepository.java
Java
[]
null
[]
package com.study.epamproject.repository; import java.util.List; import java.util.Optional; public interface CrudRepository<E> { E save(E item); //select * from E where id = id; Optional<E> findById(Long id); List<E> findAll(); void update(E item); Optional<E> deleteById(Long id); //optional with empty }
336
0.678571
0.678571
17
18.764706
17.80459
58
false
false
0
0
0
0
0
0
0.529412
false
false
12
51e880cf9e91b48dd254ca45b975aaa73ebdd0a9
11,905,649,374,739
ec2826027dccc8d83bf452637e95cc254c55c593
/src/level4/Challenge.java
c13a06e8075daf51169fd64b95925a259859d2ed
[]
no_license
league-iaroc/roombatest-RyanBoyes
https://github.com/league-iaroc/roombatest-RyanBoyes
c49156dd21d64822c7c45aed9c81e6eded7ebbb1
bf62da6aa70ee8919b3eb78d5da253311eda32e2
refs/heads/master
2021-01-20T00:36:28.134000
2017-04-23T18:28:11
2017-04-23T18:28:11
89,158,010
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package level4; import processing.core.PApplet; public class Challenge extends Head { Roomba roomba; int speed = 1000; public static void main(String[] args) { PApplet.main("level4.Processing"); } public Challenge(Roomba roomba) { super(roomba); } /** * complete the MAZE * Hint: use bump sensors */ public void initialize() { } public void loop() { goStraight(50); if (isBumpedRight()){ makeLeftTurn(450); rightBump = false; leftBump = false; } if (isBumpedLeft()){ makeRightTurn(450); leftBump = false; rightBump = false; } } void makeLeftTurn(int sleep){ driveDirect(0,500); sleep(sleep); } void makeRightTurn(int sleep){ driveDirect(500,0); sleep(sleep); } void goStraight(int sleep){ driveDirect(1000,1000); sleep(sleep); } }
UTF-8
Java
855
java
Challenge.java
Java
[]
null
[]
package level4; import processing.core.PApplet; public class Challenge extends Head { Roomba roomba; int speed = 1000; public static void main(String[] args) { PApplet.main("level4.Processing"); } public Challenge(Roomba roomba) { super(roomba); } /** * complete the MAZE * Hint: use bump sensors */ public void initialize() { } public void loop() { goStraight(50); if (isBumpedRight()){ makeLeftTurn(450); rightBump = false; leftBump = false; } if (isBumpedLeft()){ makeRightTurn(450); leftBump = false; rightBump = false; } } void makeLeftTurn(int sleep){ driveDirect(0,500); sleep(sleep); } void makeRightTurn(int sleep){ driveDirect(500,0); sleep(sleep); } void goStraight(int sleep){ driveDirect(1000,1000); sleep(sleep); } }
855
0.623392
0.588304
80
9.6875
11.792576
41
false
false
0
0
0
0
0
0
1.325
false
false
12
525db9fe354eaacf4b414caf781a409b2ee4b50d
22,660,247,513,005
06957a297f9aa4c1c106627654562a84db319fda
/src/main/java/io/jenkins/plugins/sercomm/openwrt/OpenWRTCollectBuilder.java
0421144028f29edc040fc0897f45087de86a9deb
[ "Apache-2.0" ]
permissive
leeshen64/lcmtest
https://github.com/leeshen64/lcmtest
a9f85d876e217696966980244e61a14bfd845c9d
63f50998e20440de72fe1ef89a5701aa24b6a18e
refs/heads/main
2023-01-29T19:01:46.094000
2020-12-09T05:12:42
2020-12-09T05:12:42
311,528,939
0
1
Apache-2.0
false
2020-12-09T05:12:44
2020-11-10T02:59:49
2020-11-10T02:59:54
2020-12-09T05:12:42
4
0
1
0
null
false
false
package io.jenkins.plugins.sercomm.openwrt; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.bind.JavaScriptMethod; import com.sercomm.commons.id.NameRule; import com.sercomm.commons.umei.UMEiError; import com.sercomm.commons.util.DateTime; import com.sercomm.commons.util.XStringUtil; import com.sercomm.demeter.microservices.client.v1.GetDeviceRequest; import com.sercomm.demeter.microservices.client.v1.GetDeviceResult; import com.sercomm.demeter.microservices.client.v1.GetDevicesRequest; import com.sercomm.demeter.microservices.client.v1.GetDevicesResult; import com.sercomm.demeter.microservices.client.v1.GetInstallableAppsRequest; import com.sercomm.demeter.microservices.client.v1.GetInstallableAppsResult; import com.sercomm.demeter.microservices.client.v1.GetInstalledAppRequest; import com.sercomm.demeter.microservices.client.v1.GetInstalledAppResult; import com.sercomm.demeter.microservices.client.v1.PostUbusCommandRequest; import com.sercomm.demeter.microservices.client.v1.PostUbusCommandResult; import com.sercomm.demeter.microservices.client.v1.RESTfulClient; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.AutoCompletionCandidates; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.tasks.SimpleBuildStep; public class OpenWRTCollectBuilder extends Builder implements SimpleBuildStep { private String deviceId; private String appPublisher; private String appName; private String appVersion; private String duration; private String frequency; @DataBoundConstructor public OpenWRTCollectBuilder( String deviceId, String appPublisher, String appName, String appVersion, String duration, String frequency) { this.deviceId = deviceId; this.appPublisher = appPublisher; this.appName = appName; this.appVersion = appVersion; this.duration = duration; this.frequency = frequency; } public String getDeviceId() { return deviceId; } public String getAppPublisher() { return appPublisher; } public String getAppName() { return appName; } public String getAppVersion() { return appVersion; } public String getDuration() { return duration; } public String getFrequency() { return frequency; } @Override public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); final PrintStream logger = listener.getLogger(); // convert to millisecnods final long durationValue = Long.parseLong(this.duration) * 1000L; final long frequencyValue = Long.parseLong(this.frequency) * 1000L; logger.println(LogParserUtil.SYMBOL_COLLECT_PROCEDURE_BPOS); logger.printf("%s - [INFO] ====== Collection Builder ======%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); logger.println(LogParserUtil.SYMBOL_DESCRIBE_BPOS); logger.printf("%s - [INFO] App publisher: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.appPublisher); logger.printf("%s - [INFO] App name: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.appName); logger.printf("%s - [INFO] App version: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.appVersion); logger.printf("%s - [INFO] Duration: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.duration); logger.printf("%s - [INFO] Frequency: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.frequency); logger.printf("%s - [INFO] Endpoint: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), endpoint); logger.println(LogParserUtil.SYMBOL_DESCRIBE_EPOS); try { RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); // 1. check device status and its model name logger.printf("%s - [INFO] checking device status... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(this.deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode()) { logger.printf("failed%n"); throw new InterruptedException("SERVER HTTP " + getDeviceResult.getStatusCode() + ", METHOD: 'getDevice'"); } if(getDeviceResult.hasError()) { logger.printf("failed%n"); UMEiError error = getDeviceResult.getErrors().get(0); throw new InterruptedException("SERVER REPORTED ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } if(0 != getDeviceResult.getData().getState().compareTo("online")) { logger.printf("failed%n"); throw new InterruptedException("DEVICE IS NOT ONLINE"); } logger.printf("ok%n"); // 2. obtaining App list logger.printf("%s - [INFO] obtaining App list... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetInstallableAppsRequest getInstallableAppRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(getDeviceResult.getData().getModel()) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppResult = client.getInstallableApps(getInstallableAppRequest); if(200 != getInstallableAppResult.getStatusCode()) { logger.printf("failed%n"); throw new InterruptedException("SERVER HTTP " + getInstallableAppResult.getStatusCode() + ", METHOD: 'getInstallableApps'"); } if(getInstallableAppResult.hasError()) { logger.printf("failed%n"); UMEiError error = getInstallableAppResult.getErrors().get(0); throw new InterruptedException("SERVER REPORTED ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } logger.printf("ok%n"); // 2-1. checking the specific App to be available or not logger.printf("%s - [INFO] checking specific App... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetInstallableAppsResult.ResultData installableApp = null; GetInstallableAppsResult.ResultData.Version installableVersion = null; for(GetInstallableAppsResult.ResultData app : getInstallableAppResult.getData()) { if(0 != app.getPublisher().compareTo(this.appPublisher)) { continue; } if(0 != app.getAppName().compareTo(this.appName)) { continue; } for(GetInstallableAppsResult.ResultData.Version version : app.getVersions()) { if(0 != version.getVersionName().compareTo(this.appVersion)) { continue; } installableApp = app; installableVersion = version; } } if(null == installableApp || null == installableVersion) { logger.printf("failed%n"); throw new InterruptedException("SPECIFIC APP CANNOT BE FOUND"); } logger.printf("ok%n"); // 3. check if device has installed the specific App logger.printf("%s - [INFO] checking device installed Apps... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetInstalledAppRequest getInstalledAppRequest = new GetInstalledAppRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(this.deviceId) .withAppId(installableApp.getAppId()); GetInstalledAppResult getInstalledAppResult = client.getInstalledApp(getInstalledAppRequest); if(200 != getInstalledAppResult.getStatusCode()) { logger.printf("failed%n"); throw new InterruptedException("SERVER HTTP " + getInstalledAppResult.getStatusCode() + ", METHOD: 'getInstalledApp'"); } logger.printf("ok%n"); if(true == getInstalledAppResult.hasError()) { throw new InterruptedException("SPECIFIC APP HAS NOT BEEN INSTALLED YET"); } logger.println(LogParserUtil.SYMBOL_DETAIL_BPOS); final long beginTime = System.currentTimeMillis(); while(System.currentTimeMillis() - beginTime <= durationValue) { Thread.sleep(frequencyValue); PostUbusCommandRequest request = new PostUbusCommandRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(this.deviceId) .withRequestContents("List", "Services.Management.LCM.ExecutionEnvironments", XStringUtil.BLANK); PostUbusCommandResult result = client.postUbusCommand(request); if(200 != result.getStatusCode()) { throw new InterruptedException("SERVER HTTP " + getInstalledAppResult.getStatusCode() + ", METHOD: 'getInstalledApp'"); } if(true == result.hasError()) { UMEiError error = result.getErrors().get(0); throw new InterruptedException("SERVER REPORTED ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } logger.printf("%s - ==>%s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), result.getData().getResult()); }; logger.println(LogParserUtil.SYMBOL_DETAIL_EPOS); } catch(Throwable t) { logger.printf("%s - [ERROR] %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), t.getMessage()); } logger.println(LogParserUtil.SYMBOL_COLLECT_PROCEDURE_EPOS); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { private static final String PLEASE_SELECT_TEXT = "--- SELECT ---"; private static final ArrayList<ListBoxModel.Option> DEFAULT_DURATION_OPTIONS = new ArrayList<>(); private static final ArrayList<ListBoxModel.Option> DEFAULT_FREQUENCY_OPTIONS = new ArrayList<>(); static { DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("1 minute", "60", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("5 minute", "300", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("10 minutes", "600", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("30 minutes", "1800", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("1 hour", "3600", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("4 hours", "14400", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("8 hours", "28800", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("16 hours", "57600", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("24 hours", "86400", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("48 hours", "172800", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("72 hours", "259200", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("15 seconds", "15", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("30 seconds", "30", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("1 minute", "60", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("5 minutes", "300", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("10 minutes", "600", false)); } private int lastEditorId = 0; @JavaScriptMethod public synchronized String createEditorId() { return String.valueOf(lastEditorId++); } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } public FormValidation doCheckDeviceId( @QueryParameter String value) { if(XStringUtil.isBlank(value)) { return FormValidation.error("DEVICE ID IS BLANK"); } if(!NameRule.isDevice(value)) { return FormValidation.error("INVALID DEVICE ID: '" + value + "'"); } final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); if(XStringUtil.isBlank(endpoint)) { return FormValidation.error("DEMETER ENDPOINT IS NOT CONFIGURED"); } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(value); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode()) { return FormValidation.error("SERVER ACK HTTP " + getDeviceResult.getStatusCode()); } if(true == getDeviceResult.hasError()) { UMEiError error = getDeviceResult.getErrors().get(0); return FormValidation.error("SERVER RESPONSE HAS ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } if(0 != getDeviceResult.getData().getState().compareTo("online")) { return FormValidation.error("DEVICE '" + value + "' IS NOT ONLINE"); } return FormValidation.ok(); } public AutoCompletionCandidates doAutoCompleteDeviceId( @QueryParameter String value) { AutoCompletionCandidates completions = new AutoCompletionCandidates(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDevicesRequest getDeviceRequest = new GetDevicesRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withFrom(0) .withSize(500) .withState("online"); GetDevicesResult getDeviceResult = client.getDevices(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } for(GetDevicesResult.ResultData row : getDeviceResult.getData()) { String deviceId = NameRule.formatDeviceName(row.getSerial(), row.getMac()); if(XStringUtil.isBlank(value) || deviceId.startsWith(value.toLowerCase())) { completions.add(deviceId); } } } while(false); return completions; } public ListBoxModel doFillAppPublisherItems( @QueryParameter String deviceId) { ListBoxModel listBoxModel = new ListBoxModel(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } if(XStringUtil.isBlank(deviceId) || !NameRule.isDevice(deviceId)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } final String model = getDeviceResult.getData().getModel(); GetInstallableAppsRequest getInstallableAppsRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(model) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppsResult = client.getInstallableApps(getInstallableAppsRequest); if(200 != getInstallableAppsResult.getStatusCode() || true == getInstallableAppsResult.hasError()) { break; } if(false == getInstallableAppsResult.getData().isEmpty()) { // add a blank option to encourage users who must select an option listBoxModel.add(PLEASE_SELECT_TEXT); } for(GetInstallableAppsResult.ResultData row : getInstallableAppsResult.getData()) { String publisher = row.getPublisher(); boolean added = false; for(ListBoxModel.Option option : listBoxModel) { if(0 == option.name.compareTo(publisher)) { added = true; break; } } if(false == added) { listBoxModel.add(publisher); } } } while(false); return listBoxModel; } public ListBoxModel doFillAppNameItems( @QueryParameter String deviceId, @QueryParameter String appPublisher) { ListBoxModel listBoxModel = new ListBoxModel(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } if(XStringUtil.isBlank(deviceId) || !NameRule.isDevice(deviceId) || XStringUtil.isBlank(appPublisher) || 0 == appPublisher.compareTo(PLEASE_SELECT_TEXT)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } final String model = getDeviceResult.getData().getModel(); GetInstallableAppsRequest getInstallableAppsRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(model) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppsResult = client.getInstallableApps(getInstallableAppsRequest); if(200 != getInstallableAppsResult.getStatusCode() || true == getInstallableAppsResult.hasError()) { break; } if(false == getInstallableAppsResult.getData().isEmpty()) { // add a blank option to encourage users who must select an option listBoxModel.add(PLEASE_SELECT_TEXT); } for(GetInstallableAppsResult.ResultData row : getInstallableAppsResult.getData()) { String publisher = row.getPublisher(); if(0 != appPublisher.compareTo(publisher)) { continue; } String appName = row.getAppName(); boolean added = false; for(ListBoxModel.Option option : listBoxModel) { if(0 == option.name.compareTo(appName)) { added = true; break; } } if(false == added) { listBoxModel.add(appName); } } } while(false); return listBoxModel; } public ListBoxModel doFillAppVersionItems( @QueryParameter String deviceId, @QueryParameter String appPublisher, @QueryParameter String appName) { ListBoxModel listBoxModel = new ListBoxModel(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } if(XStringUtil.isBlank(deviceId) || !NameRule.isDevice(deviceId) || XStringUtil.isBlank(appPublisher) || 0 == appPublisher.compareTo(PLEASE_SELECT_TEXT) || XStringUtil.isBlank(appName) || 0 == appName.compareTo(PLEASE_SELECT_TEXT)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } final String model = getDeviceResult.getData().getModel(); GetInstallableAppsRequest getInstallableAppsRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(model) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppsResult = client.getInstallableApps(getInstallableAppsRequest); if(200 != getInstallableAppsResult.getStatusCode() || true == getInstallableAppsResult.hasError()) { break; } if(false == getInstallableAppsResult.getData().isEmpty()) { // add a blank option to encourage users who must select an option listBoxModel.add(PLEASE_SELECT_TEXT); } for(GetInstallableAppsResult.ResultData row : getInstallableAppsResult.getData()) { String publisher = row.getPublisher(); if(0 != appPublisher.compareTo(publisher)) { continue; } String name = row.getAppName(); if(0 != appName.compareTo(name)) { continue; } for(GetInstallableAppsResult.ResultData.Version aVersion : row.getVersions()) { listBoxModel.add(aVersion.getVersionName()); } } } while(false); return listBoxModel; } public ListBoxModel doFillDurationItems( @QueryParameter String duration) { ListBoxModel listBoxModel = new ListBoxModel(); for(ListBoxModel.Option option : DEFAULT_DURATION_OPTIONS) { if(XStringUtil.isBlank(duration)) { if(0 == option.value.compareTo("600")) { // default selection listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } else { if(0 == option.value.compareTo(duration)) { // selected listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } } return listBoxModel; } public ListBoxModel doFillFrequencyItems( @QueryParameter String frequency) { ListBoxModel listBoxModel = new ListBoxModel(); for(ListBoxModel.Option option : DEFAULT_FREQUENCY_OPTIONS) { if(XStringUtil.isBlank(frequency)) { if(0 == option.value.compareTo("30")) { // default selection listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } else { if(0 == option.value.compareTo(frequency)) { // selected listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } } return listBoxModel; } @Override public String getDisplayName() { return Messages.DemeterCollectBuilder_DescriptorImpl_DisplayName(); } } }
UTF-8
Java
29,424
java
OpenWRTCollectBuilder.java
Java
[]
null
[]
package io.jenkins.plugins.sercomm.openwrt; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.bind.JavaScriptMethod; import com.sercomm.commons.id.NameRule; import com.sercomm.commons.umei.UMEiError; import com.sercomm.commons.util.DateTime; import com.sercomm.commons.util.XStringUtil; import com.sercomm.demeter.microservices.client.v1.GetDeviceRequest; import com.sercomm.demeter.microservices.client.v1.GetDeviceResult; import com.sercomm.demeter.microservices.client.v1.GetDevicesRequest; import com.sercomm.demeter.microservices.client.v1.GetDevicesResult; import com.sercomm.demeter.microservices.client.v1.GetInstallableAppsRequest; import com.sercomm.demeter.microservices.client.v1.GetInstallableAppsResult; import com.sercomm.demeter.microservices.client.v1.GetInstalledAppRequest; import com.sercomm.demeter.microservices.client.v1.GetInstalledAppResult; import com.sercomm.demeter.microservices.client.v1.PostUbusCommandRequest; import com.sercomm.demeter.microservices.client.v1.PostUbusCommandResult; import com.sercomm.demeter.microservices.client.v1.RESTfulClient; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.AbstractProject; import hudson.model.AutoCompletionCandidates; import hudson.model.Run; import hudson.model.TaskListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.tasks.SimpleBuildStep; public class OpenWRTCollectBuilder extends Builder implements SimpleBuildStep { private String deviceId; private String appPublisher; private String appName; private String appVersion; private String duration; private String frequency; @DataBoundConstructor public OpenWRTCollectBuilder( String deviceId, String appPublisher, String appName, String appVersion, String duration, String frequency) { this.deviceId = deviceId; this.appPublisher = appPublisher; this.appName = appName; this.appVersion = appVersion; this.duration = duration; this.frequency = frequency; } public String getDeviceId() { return deviceId; } public String getAppPublisher() { return appPublisher; } public String getAppName() { return appName; } public String getAppVersion() { return appVersion; } public String getDuration() { return duration; } public String getFrequency() { return frequency; } @Override public void perform(Run<?, ?> run, FilePath workspace, Launcher launcher, TaskListener listener) throws InterruptedException, IOException { final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); final PrintStream logger = listener.getLogger(); // convert to millisecnods final long durationValue = Long.parseLong(this.duration) * 1000L; final long frequencyValue = Long.parseLong(this.frequency) * 1000L; logger.println(LogParserUtil.SYMBOL_COLLECT_PROCEDURE_BPOS); logger.printf("%s - [INFO] ====== Collection Builder ======%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); logger.println(LogParserUtil.SYMBOL_DESCRIBE_BPOS); logger.printf("%s - [INFO] App publisher: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.appPublisher); logger.printf("%s - [INFO] App name: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.appName); logger.printf("%s - [INFO] App version: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.appVersion); logger.printf("%s - [INFO] Duration: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.duration); logger.printf("%s - [INFO] Frequency: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), this.frequency); logger.printf("%s - [INFO] Endpoint: %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), endpoint); logger.println(LogParserUtil.SYMBOL_DESCRIBE_EPOS); try { RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); // 1. check device status and its model name logger.printf("%s - [INFO] checking device status... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(this.deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode()) { logger.printf("failed%n"); throw new InterruptedException("SERVER HTTP " + getDeviceResult.getStatusCode() + ", METHOD: 'getDevice'"); } if(getDeviceResult.hasError()) { logger.printf("failed%n"); UMEiError error = getDeviceResult.getErrors().get(0); throw new InterruptedException("SERVER REPORTED ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } if(0 != getDeviceResult.getData().getState().compareTo("online")) { logger.printf("failed%n"); throw new InterruptedException("DEVICE IS NOT ONLINE"); } logger.printf("ok%n"); // 2. obtaining App list logger.printf("%s - [INFO] obtaining App list... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetInstallableAppsRequest getInstallableAppRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(getDeviceResult.getData().getModel()) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppResult = client.getInstallableApps(getInstallableAppRequest); if(200 != getInstallableAppResult.getStatusCode()) { logger.printf("failed%n"); throw new InterruptedException("SERVER HTTP " + getInstallableAppResult.getStatusCode() + ", METHOD: 'getInstallableApps'"); } if(getInstallableAppResult.hasError()) { logger.printf("failed%n"); UMEiError error = getInstallableAppResult.getErrors().get(0); throw new InterruptedException("SERVER REPORTED ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } logger.printf("ok%n"); // 2-1. checking the specific App to be available or not logger.printf("%s - [INFO] checking specific App... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetInstallableAppsResult.ResultData installableApp = null; GetInstallableAppsResult.ResultData.Version installableVersion = null; for(GetInstallableAppsResult.ResultData app : getInstallableAppResult.getData()) { if(0 != app.getPublisher().compareTo(this.appPublisher)) { continue; } if(0 != app.getAppName().compareTo(this.appName)) { continue; } for(GetInstallableAppsResult.ResultData.Version version : app.getVersions()) { if(0 != version.getVersionName().compareTo(this.appVersion)) { continue; } installableApp = app; installableVersion = version; } } if(null == installableApp || null == installableVersion) { logger.printf("failed%n"); throw new InterruptedException("SPECIFIC APP CANNOT BE FOUND"); } logger.printf("ok%n"); // 3. check if device has installed the specific App logger.printf("%s - [INFO] checking device installed Apps... ", DateTime.now().toString(DateTime.FORMAT_ISO_MS)); GetInstalledAppRequest getInstalledAppRequest = new GetInstalledAppRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(this.deviceId) .withAppId(installableApp.getAppId()); GetInstalledAppResult getInstalledAppResult = client.getInstalledApp(getInstalledAppRequest); if(200 != getInstalledAppResult.getStatusCode()) { logger.printf("failed%n"); throw new InterruptedException("SERVER HTTP " + getInstalledAppResult.getStatusCode() + ", METHOD: 'getInstalledApp'"); } logger.printf("ok%n"); if(true == getInstalledAppResult.hasError()) { throw new InterruptedException("SPECIFIC APP HAS NOT BEEN INSTALLED YET"); } logger.println(LogParserUtil.SYMBOL_DETAIL_BPOS); final long beginTime = System.currentTimeMillis(); while(System.currentTimeMillis() - beginTime <= durationValue) { Thread.sleep(frequencyValue); PostUbusCommandRequest request = new PostUbusCommandRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(this.deviceId) .withRequestContents("List", "Services.Management.LCM.ExecutionEnvironments", XStringUtil.BLANK); PostUbusCommandResult result = client.postUbusCommand(request); if(200 != result.getStatusCode()) { throw new InterruptedException("SERVER HTTP " + getInstalledAppResult.getStatusCode() + ", METHOD: 'getInstalledApp'"); } if(true == result.hasError()) { UMEiError error = result.getErrors().get(0); throw new InterruptedException("SERVER REPORTED ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } logger.printf("%s - ==>%s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), result.getData().getResult()); }; logger.println(LogParserUtil.SYMBOL_DETAIL_EPOS); } catch(Throwable t) { logger.printf("%s - [ERROR] %s%n", DateTime.now().toString(DateTime.FORMAT_ISO_MS), t.getMessage()); } logger.println(LogParserUtil.SYMBOL_COLLECT_PROCEDURE_EPOS); } @Extension public static final class DescriptorImpl extends BuildStepDescriptor<Builder> { private static final String PLEASE_SELECT_TEXT = "--- SELECT ---"; private static final ArrayList<ListBoxModel.Option> DEFAULT_DURATION_OPTIONS = new ArrayList<>(); private static final ArrayList<ListBoxModel.Option> DEFAULT_FREQUENCY_OPTIONS = new ArrayList<>(); static { DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("1 minute", "60", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("5 minute", "300", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("10 minutes", "600", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("30 minutes", "1800", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("1 hour", "3600", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("4 hours", "14400", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("8 hours", "28800", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("16 hours", "57600", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("24 hours", "86400", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("48 hours", "172800", false)); DEFAULT_DURATION_OPTIONS.add(new ListBoxModel.Option("72 hours", "259200", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("15 seconds", "15", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("30 seconds", "30", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("1 minute", "60", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("5 minutes", "300", false)); DEFAULT_FREQUENCY_OPTIONS.add(new ListBoxModel.Option("10 minutes", "600", false)); } private int lastEditorId = 0; @JavaScriptMethod public synchronized String createEditorId() { return String.valueOf(lastEditorId++); } @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } public FormValidation doCheckDeviceId( @QueryParameter String value) { if(XStringUtil.isBlank(value)) { return FormValidation.error("DEVICE ID IS BLANK"); } if(!NameRule.isDevice(value)) { return FormValidation.error("INVALID DEVICE ID: '" + value + "'"); } final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); if(XStringUtil.isBlank(endpoint)) { return FormValidation.error("DEMETER ENDPOINT IS NOT CONFIGURED"); } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(value); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode()) { return FormValidation.error("SERVER ACK HTTP " + getDeviceResult.getStatusCode()); } if(true == getDeviceResult.hasError()) { UMEiError error = getDeviceResult.getErrors().get(0); return FormValidation.error("SERVER RESPONSE HAS ERROR, CODE: " + error.getCode() + ", DETAIL: " + error.getDetail()); } if(0 != getDeviceResult.getData().getState().compareTo("online")) { return FormValidation.error("DEVICE '" + value + "' IS NOT ONLINE"); } return FormValidation.ok(); } public AutoCompletionCandidates doAutoCompleteDeviceId( @QueryParameter String value) { AutoCompletionCandidates completions = new AutoCompletionCandidates(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDevicesRequest getDeviceRequest = new GetDevicesRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withFrom(0) .withSize(500) .withState("online"); GetDevicesResult getDeviceResult = client.getDevices(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } for(GetDevicesResult.ResultData row : getDeviceResult.getData()) { String deviceId = NameRule.formatDeviceName(row.getSerial(), row.getMac()); if(XStringUtil.isBlank(value) || deviceId.startsWith(value.toLowerCase())) { completions.add(deviceId); } } } while(false); return completions; } public ListBoxModel doFillAppPublisherItems( @QueryParameter String deviceId) { ListBoxModel listBoxModel = new ListBoxModel(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } if(XStringUtil.isBlank(deviceId) || !NameRule.isDevice(deviceId)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } final String model = getDeviceResult.getData().getModel(); GetInstallableAppsRequest getInstallableAppsRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(model) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppsResult = client.getInstallableApps(getInstallableAppsRequest); if(200 != getInstallableAppsResult.getStatusCode() || true == getInstallableAppsResult.hasError()) { break; } if(false == getInstallableAppsResult.getData().isEmpty()) { // add a blank option to encourage users who must select an option listBoxModel.add(PLEASE_SELECT_TEXT); } for(GetInstallableAppsResult.ResultData row : getInstallableAppsResult.getData()) { String publisher = row.getPublisher(); boolean added = false; for(ListBoxModel.Option option : listBoxModel) { if(0 == option.name.compareTo(publisher)) { added = true; break; } } if(false == added) { listBoxModel.add(publisher); } } } while(false); return listBoxModel; } public ListBoxModel doFillAppNameItems( @QueryParameter String deviceId, @QueryParameter String appPublisher) { ListBoxModel listBoxModel = new ListBoxModel(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } if(XStringUtil.isBlank(deviceId) || !NameRule.isDevice(deviceId) || XStringUtil.isBlank(appPublisher) || 0 == appPublisher.compareTo(PLEASE_SELECT_TEXT)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } final String model = getDeviceResult.getData().getModel(); GetInstallableAppsRequest getInstallableAppsRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(model) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppsResult = client.getInstallableApps(getInstallableAppsRequest); if(200 != getInstallableAppsResult.getStatusCode() || true == getInstallableAppsResult.hasError()) { break; } if(false == getInstallableAppsResult.getData().isEmpty()) { // add a blank option to encourage users who must select an option listBoxModel.add(PLEASE_SELECT_TEXT); } for(GetInstallableAppsResult.ResultData row : getInstallableAppsResult.getData()) { String publisher = row.getPublisher(); if(0 != appPublisher.compareTo(publisher)) { continue; } String appName = row.getAppName(); boolean added = false; for(ListBoxModel.Option option : listBoxModel) { if(0 == option.name.compareTo(appName)) { added = true; break; } } if(false == added) { listBoxModel.add(appName); } } } while(false); return listBoxModel; } public ListBoxModel doFillAppVersionItems( @QueryParameter String deviceId, @QueryParameter String appPublisher, @QueryParameter String appName) { ListBoxModel listBoxModel = new ListBoxModel(); final String endpoint = OpenWRTPlugin.getDemeterPluginDescriptor().getEndpoint(); do { if(XStringUtil.isBlank(endpoint)) { break; } if(XStringUtil.isBlank(deviceId) || !NameRule.isDevice(deviceId) || XStringUtil.isBlank(appPublisher) || 0 == appPublisher.compareTo(PLEASE_SELECT_TEXT) || XStringUtil.isBlank(appName) || 0 == appName.compareTo(PLEASE_SELECT_TEXT)) { break; } RESTfulClient client = new RESTfulClient.Builder() .enableSSL(true) .endpoint(endpoint).build(); GetDeviceRequest getDeviceRequest = new GetDeviceRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withNodeName(deviceId); GetDeviceResult getDeviceResult = client.getDevice(getDeviceRequest); if(200 != getDeviceResult.getStatusCode() || true == getDeviceResult.hasError()) { break; } final String model = getDeviceResult.getData().getModel(); GetInstallableAppsRequest getInstallableAppsRequest = new GetInstallableAppsRequest() .withOriginatorId(OpenWRTPlugin.ORIGINATOR_ID) .withModel(model) .withFrom(0) .withSize(500); GetInstallableAppsResult getInstallableAppsResult = client.getInstallableApps(getInstallableAppsRequest); if(200 != getInstallableAppsResult.getStatusCode() || true == getInstallableAppsResult.hasError()) { break; } if(false == getInstallableAppsResult.getData().isEmpty()) { // add a blank option to encourage users who must select an option listBoxModel.add(PLEASE_SELECT_TEXT); } for(GetInstallableAppsResult.ResultData row : getInstallableAppsResult.getData()) { String publisher = row.getPublisher(); if(0 != appPublisher.compareTo(publisher)) { continue; } String name = row.getAppName(); if(0 != appName.compareTo(name)) { continue; } for(GetInstallableAppsResult.ResultData.Version aVersion : row.getVersions()) { listBoxModel.add(aVersion.getVersionName()); } } } while(false); return listBoxModel; } public ListBoxModel doFillDurationItems( @QueryParameter String duration) { ListBoxModel listBoxModel = new ListBoxModel(); for(ListBoxModel.Option option : DEFAULT_DURATION_OPTIONS) { if(XStringUtil.isBlank(duration)) { if(0 == option.value.compareTo("600")) { // default selection listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } else { if(0 == option.value.compareTo(duration)) { // selected listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } } return listBoxModel; } public ListBoxModel doFillFrequencyItems( @QueryParameter String frequency) { ListBoxModel listBoxModel = new ListBoxModel(); for(ListBoxModel.Option option : DEFAULT_FREQUENCY_OPTIONS) { if(XStringUtil.isBlank(frequency)) { if(0 == option.value.compareTo("30")) { // default selection listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } else { if(0 == option.value.compareTo(frequency)) { // selected listBoxModel.add(new ListBoxModel.Option(option.name, option.value, true)); } else { listBoxModel.add(option); } } } return listBoxModel; } @Override public String getDisplayName() { return Messages.DemeterCollectBuilder_DescriptorImpl_DisplayName(); } } }
29,424
0.530451
0.523926
729
39.362141
32.448765
159
false
false
0
0
0
0
0
0
0.497942
false
false
12
f14c8198770c0bb89ec380831bf6a503939ac5e7
8,847,632,695,373
43179348e5a49ddec6c6cd6a110ef9bda7fe2fb6
/src/openjava/test/ParserTest.java
94726933f8d2b46b0b44d8e2d25559082125b7c7
[ "Apache-2.0" ]
permissive
Abhiroopks/MuJava-Project
https://github.com/Abhiroopks/MuJava-Project
a058f1a2a499b0b862c38b4d22b6947a7e2aaff1
beb55bb18ef80de55c301878e9fe3830dfbfb886
refs/heads/master
2023-01-28T18:07:49.185000
2020-12-10T18:55:14
2020-12-10T18:55:14
295,043,861
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// // Decompiled by Procyon v0.5.36 // package openjava.test; import openjava.ptree.CompilationUnit; import openjava.tools.parser.ParseException; import openjava.mop.Environment; import openjava.mop.OJSystem; import java.io.FileNotFoundException; import java.io.InputStream; import openjava.tools.parser.Parser; import java.io.FileInputStream; public class ParserTest { public static void main(final String[] args) { System.out.println(System.getProperty("user.dir")); final String file = "src/openjava/test/Flower.java"; Parser parser = null; try { parser = new Parser(new FileInputStream(file)); } catch (FileNotFoundException e3) { System.err.println("File " + file + " not found."); } catch (Exception e) { e.printStackTrace(); } try { OJSystem.initConstants(); final CompilationUnit result = parser.CompilationUnit(OJSystem.env); } catch (ParseException e2) { e2.printStackTrace(); System.out.println(" can't generate parse tree"); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }
UTF-8
Java
1,252
java
ParserTest.java
Java
[]
null
[]
// // Decompiled by Procyon v0.5.36 // package openjava.test; import openjava.ptree.CompilationUnit; import openjava.tools.parser.ParseException; import openjava.mop.Environment; import openjava.mop.OJSystem; import java.io.FileNotFoundException; import java.io.InputStream; import openjava.tools.parser.Parser; import java.io.FileInputStream; public class ParserTest { public static void main(final String[] args) { System.out.println(System.getProperty("user.dir")); final String file = "src/openjava/test/Flower.java"; Parser parser = null; try { parser = new Parser(new FileInputStream(file)); } catch (FileNotFoundException e3) { System.err.println("File " + file + " not found."); } catch (Exception e) { e.printStackTrace(); } try { OJSystem.initConstants(); final CompilationUnit result = parser.CompilationUnit(OJSystem.env); } catch (ParseException e2) { e2.printStackTrace(); System.out.println(" can't generate parse tree"); } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } }
1,252
0.615815
0.610224
44
27.454546
20.037981
80
false
false
0
0
0
0
0
0
0.477273
false
false
12
6bd07fd4d3559355d934c2bff5e03a975fde10e7
8,847,632,692,925
0d6940e6ab910855dbbf190c5f7fcc91a5fc5072
/src/emailbillsender/EmailSender.java
f6b8bb74a43a47f5cfb9f24d63f553090aea0179
[]
no_license
afdzal3/EmailBillSender-daemon
https://github.com/afdzal3/EmailBillSender-daemon
1b8ca220b9731d9b7bb190b8c491211df4de86a1
8e10a70146732fde9a443cb72430b16bb81fad6e
refs/heads/master
2020-12-06T18:18:06.245000
2019-12-04T08:33:21
2019-12-04T08:33:21
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 emailbillsender; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * * @author amer */ public class EmailSender { private Properties prop; private Session ses; private MimeMessage msg; private final String curSys; private final String sender; // all of the attachments private BodyPart pAutopay; private BodyPart pPaynowBM; private BodyPart pPaynowEn; private BodyPart pWherepayBM; private BodyPart pWherepayEn; private BodyPart pFooterFb; private BodyPart pFootLinkdinTmone; private BodyPart pFooterTmBM; private BodyPart pFooterTmEn; private BodyPart pFooterTw; private BodyPart pFooterTwTmone; private BodyPart pFooterWeb; private BodyPart pFooterWebGlobal; private BodyPart pFooterWebTmone; private BodyPart pHeroConsumer; private BodyPart pHeroGlobal; private BodyPart pHeroSme; private BodyPart pHeroTmone; public EmailSender(String host, boolean verbose, String sys, String sendermail) { this.prop = new Properties(); this.prop.put("mail.smtp.host", host); this.curSys = sys.toLowerCase(); this.sender = sendermail; ses = Session.getDefaultInstance(prop); ses.setDebug(verbose); // System.out.println("Mail Session v2 Initialized!"); msg = new MimeMessage(ses); } /** * prepare all the common things * * @throws java.io.UnsupportedEncodingException * @throws javax.mail.MessagingException */ public void init() throws UnsupportedEncodingException, MessagingException { InternetAddress addrFrom = new InternetAddress(sender, "Telekom Malaysia Berhad"); msg.setFrom(addrFrom); msg.setReplyTo(new javax.mail.Address[]{ new javax.mail.internet.InternetAddress("help@tm.com.my") }); // set all of the common attachments pAutopay = new MimeBodyPart(); DataSource fds = new FileDataSource("asset/cta-autopay.png"); pAutopay.setDataHandler(new DataHandler(fds)); pAutopay.setHeader("Content-ID", "<pAutopay>"); pAutopay.setDisposition(MimeBodyPart.INLINE); pPaynowBM = new MimeBodyPart(); fds = new FileDataSource("asset/cta-paynow-bm.jpg"); pPaynowBM.setDataHandler(new DataHandler(fds)); pPaynowBM.setHeader("Content-ID", "<pPaynowBM>"); pPaynowBM.setDisposition(MimeBodyPart.INLINE); pPaynowEn = new MimeBodyPart(); fds = new FileDataSource("asset/cta-paynow-eng.jpg"); pPaynowEn.setDataHandler(new DataHandler(fds)); pPaynowEn.setHeader("Content-ID", "<pPaynowEn>"); pPaynowEn.setDisposition(MimeBodyPart.INLINE); pWherepayBM = new MimeBodyPart(); fds = new FileDataSource("asset/cta-wherecanipaymybill-bm.png"); pWherepayBM.setDataHandler(new DataHandler(fds)); pWherepayBM.setHeader("Content-ID", "<pWherepayBM>"); pWherepayBM.setDisposition(MimeBodyPart.INLINE); pWherepayEn = new MimeBodyPart(); fds = new FileDataSource("asset/cta-wherecanipaymybill-eng.png"); pWherepayEn.setDataHandler(new DataHandler(fds)); pWherepayEn.setHeader("Content-ID", "<pWherepayEn>"); pWherepayEn.setDisposition(MimeBodyPart.INLINE); pFooterFb = new MimeBodyPart(); fds = new FileDataSource("asset/footer_fb.jpg"); pFooterFb.setDataHandler(new DataHandler(fds)); pFooterFb.setHeader("Content-ID", "<pFooterFb>"); pFooterFb.setDisposition(MimeBodyPart.INLINE); pFootLinkdinTmone = new MimeBodyPart(); fds = new FileDataSource("asset/footer_linkedin-tmone.jpg"); pFootLinkdinTmone.setDataHandler(new DataHandler(fds)); pFootLinkdinTmone.setHeader("Content-ID", "<pFootLinkdinTmone>"); pFootLinkdinTmone.setDisposition(MimeBodyPart.INLINE); pFooterTmBM = new MimeBodyPart(); fds = new FileDataSource("asset/footer_tm-bm.jpg"); pFooterTmBM.setDataHandler(new DataHandler(fds)); pFooterTmBM.setHeader("Content-ID", "<pFooterTmBM>"); pFooterTmBM.setDisposition(MimeBodyPart.INLINE); pFooterTmEn = new MimeBodyPart(); fds = new FileDataSource("asset/footer_tm-eng.jpg"); pFooterTmEn.setDataHandler(new DataHandler(fds)); pFooterTmEn.setHeader("Content-ID", "<pFooterTmEn>"); pFooterTmEn.setDisposition(MimeBodyPart.INLINE); pFooterTw = new MimeBodyPart(); fds = new FileDataSource("asset/footer_tw.jpg"); pFooterTw.setDataHandler(new DataHandler(fds)); pFooterTw.setHeader("Content-ID", "<pFooterTw>"); pFooterTw.setDisposition(MimeBodyPart.INLINE); pFooterTwTmone = new MimeBodyPart(); fds = new FileDataSource("asset/footer_twitter-tmone.jpg"); pFooterTwTmone.setDataHandler(new DataHandler(fds)); pFooterTwTmone.setHeader("Content-ID", "<pFooterTwTmone>"); pFooterTwTmone.setDisposition(MimeBodyPart.INLINE); pFooterWeb = new MimeBodyPart(); fds = new FileDataSource("asset/footer_web.jpg"); pFooterWeb.setDataHandler(new DataHandler(fds)); pFooterWeb.setHeader("Content-ID", "<pFooterWeb>"); pFooterWeb.setDisposition(MimeBodyPart.INLINE); pFooterWebGlobal = new MimeBodyPart(); fds = new FileDataSource("asset/footer_web-global.jpg"); pFooterWebGlobal.setDataHandler(new DataHandler(fds)); pFooterWebGlobal.setHeader("Content-ID", "<pFooterWebGlobal>"); pFooterWebGlobal.setDisposition(MimeBodyPart.INLINE); pFooterWebTmone = new MimeBodyPart(); fds = new FileDataSource("asset/footer_web-tmone.jpg"); pFooterWebTmone.setDataHandler(new DataHandler(fds)); pFooterWebTmone.setHeader("Content-ID", "<pFooterWebTmone>"); pFooterWebTmone.setDisposition(MimeBodyPart.INLINE); pHeroConsumer = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-consumer.jpg"); pHeroConsumer.setDataHandler(new DataHandler(fds)); pHeroConsumer.setHeader("Content-ID", "<pHeroConsumer>"); pHeroConsumer.setDisposition(MimeBodyPart.INLINE); pHeroGlobal = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-global.jpg"); pHeroGlobal.setDataHandler(new DataHandler(fds)); pHeroGlobal.setHeader("Content-ID", "<pHeroGlobal>"); pHeroGlobal.setDisposition(MimeBodyPart.INLINE); pHeroSme = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-sme.jpg"); pHeroSme.setDataHandler(new DataHandler(fds)); pHeroSme.setHeader("Content-ID", "<pHeroSme>"); pHeroSme.setDisposition(MimeBodyPart.INLINE); pHeroTmone = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-tmone.jpg"); pHeroTmone.setDataHandler(new DataHandler(fds)); pHeroTmone.setHeader("Content-ID", "<pHeroTmone>"); pHeroTmone.setDisposition(MimeBodyPart.INLINE); } private void setSubject(String bano, Date bdate, String lob, String lang) throws MessagingException { String dateformat = Utilities.dateFormat(bdate, "MM yyyy"); // set the subject if (curSys.equals("icp")) { if (lang.equals("mal")) { msg.setSubject("Bil TM anda (No Akaun: " + bano + ") untuk bulan " + dateformat); } else { // english msg.setSubject("Your TM bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } } else { // nova if (lob.equals("consumer")) { msg.setSubject("Your unifi Home bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } else if (lob.equals("sme")) { msg.setSubject("Your unifi bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } else { // tmone and global msg.setSubject("Your TM bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } } } public String send(String name, String bano, Date enddate, double amount, File pdf, String emailaddr, String ccaddr, String lob, String lang, String currency, double overdue, double cmc, Date duedate ) throws MessagingException { if (emailaddr.trim().isEmpty()) { return "empty email"; } // set the recipient setRecip(emailaddr); setCCRecip(ccaddr); setSubject(bano, enddate, lob, lang); // set the email body if (lang.equals("eng") || curSys.equals("nova")) { if (lob.equals("consumer") || lob.equals("sme")) { buildEmailContentUnifiEn(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else if (lob.equals("global") || lob.equals("wholesale")) { buildEmailContentGlobalEn(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else { // tm one buildEmailContentTMOneEn(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } } else { if (lob.equals("consumer") || lob.equals("sme")) { buildEmailContentUnifiBm(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else if (lob.equals("global") || lob.equals("wholesale")) { buildEmailContentGlobalBm(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else { // tm one buildEmailContentTMOneBm(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } } // send the email Transport.send(msg); return "success"; } /// ---------------------------------------------------------------------- private void setRecip(String recipient) throws MessagingException { if (recipient.contains(",")) { String[] rlist = recipient.split(","); int dsize = rlist.length; InternetAddress[] adrss = new InternetAddress[dsize]; for (int i = 0; i < dsize; i++) { adrss[i] = new InternetAddress(rlist[i]); } msg.setRecipients(Message.RecipientType.TO, adrss); } else { InternetAddress addrTo = new InternetAddress(recipient); msg.setRecipient(Message.RecipientType.TO, addrTo); } } private void setCCRecip(String recipient) throws MessagingException { if (recipient.trim().isEmpty()) { return; } if (recipient.contains(",")) { String[] rlist = recipient.split(","); int dsize = rlist.length; InternetAddress[] adrss = new InternetAddress[dsize]; for (int i = 0; i < dsize; i++) { adrss[i] = new InternetAddress(rlist[i]); } msg.setRecipients(Message.RecipientType.CC, adrss); } else { InternetAddress addrTo = new InternetAddress(recipient); msg.setRecipient(Message.RecipientType.CC, addrTo); } } private void buildEmailContentUnifiEn(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String sLabel = this.curSys.toLowerCase().equals("nova") ? "unifi Home" : "TM"; String otopaybg = lob.toLowerCase().equals("sme") ? "96d8ff" : "f7941d"; String herobanner = lob.toLowerCase().equals("sme") ? "pHeroSme" : "pHeroConsumer"; String overduedisp = "&nbsp;"; String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); if (overdue > 0) { overduedisp = " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:14px;\">PAY IMMEDIATELY</font>\n"; } String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>unifi</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:" + herobanner + "\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Hello " + name + "</font><br /><br />\n" + " Here’s a summary of your latest <b>" + sLabel + " bill</b>.<br />\n" + " A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Bill Date</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Account Number</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Overdue Amount</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Current Charges</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Total Amount Due*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + overduedisp + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pPaynowEn\" alt=\"Pay Now\" width=\"145\" height=\"35\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">*If you have already signed up with our <b>Autopay</b> service, the total amount above will be deducted automatically from your card within the next few days.</font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Disclaimer: Please do not reply to this email.<br />\n" + " For further enquiries or feedback, you can e-mail to <a href=\"mailto:help@tm.com.my\" style=\"text-decoration:underline; color:#272727;\">help@tm.com.my</a>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pAutopay\" alt=\"Auto Pay\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pWherepayEn\" alt=\"Where can i pay my bill\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 25px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWeb\" alt=\"www.unifi.com.my\" width=\"80\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.facebook.com/weareunifi/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterFb\" alt=\"weareunifi\" width=\"71\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"58\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://twitter.com/unifi?lang=en\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTw\" alt=\"@unifi\" width=\"58\" height=\"24\">\n" + " </a>\n" + " </td> \n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"88\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmEn\" alt=\"TM Group\" width=\"180\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); // add the rest of the inlines if (lob.toLowerCase().equals("sme")) { multipart.addBodyPart(pHeroSme); } else { multipart.addBodyPart(pHeroConsumer); } multipart.addBodyPart(pPaynowEn); multipart.addBodyPart(pAutopay); multipart.addBodyPart(pWherepayEn); multipart.addBodyPart(pFooterWeb); multipart.addBodyPart(pFooterFb); multipart.addBodyPart(pFooterTw); multipart.addBodyPart(pFooterTmEn); msg.setContent(multipart); } private void buildEmailContentUnifiBm(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String otopaybg = lob.toLowerCase().equals("sme") ? "96d8ff" : "f7941d"; String herobanner = lob.toLowerCase().equals("sme") ? "pHeroSme" : "pHeroConsumer"; String overduedisp = "&nbsp;"; String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); if (overdue > 0) { overduedisp = " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:14px;\">PAY IMMEDIATELY</font>\n"; } String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>unifi</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:" + herobanner + "\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Hello " + name + "</font><br /><br />\n" + " Berikut adalah ringkasan <b>bil TM</b> terkini anda.<br />\n" + " A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Tarikh Bil</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Nombor Akaun</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Jumlah Caj Tertunggak</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Caj Semasa</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Jumlah Perlu Dibayar*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + overduedisp + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pPaynowBM\" alt=\"Pay Now\" width=\"184\" height=\"35\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">*Jika anda pelanggan <b>Autopay</b> sedia ada, jumlah perlu dibayar akan didebitkan secara automatik melalui kad debit/kredit anda dalam masa beberapa hari dari tarikh bil ini. </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Penafian: Sila jangan balas e-mel ini.<br />\n" + " Untuk pertanyaan lanjut atau maklum balas, sila e-mel kepada <a href=\"mailto:help@tm.com.my\" style=\"text-decoration:underline; color:#272727;\">help@tm.com.my</a>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pAutopay\" alt=\"Auto Pay\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pWherepayBm\" alt=\"Where can i pay my bill\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 25px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWeb\" alt=\"www.unifi.com.my\" width=\"80\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.facebook.com/weareunifi/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterFb\" alt=\"weareunifi\" width=\"71\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"58\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://twitter.com/unifi?lang=en\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTw\" alt=\"@unifi\" width=\"58\" height=\"24\">\n" + " </a>\n" + " </td> \n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"88\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmBM\" alt=\"TM Group\" width=\"198\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); // add the rest of the inlines if (lob.toLowerCase().equals("sme")) { multipart.addBodyPart(pHeroSme); } else { multipart.addBodyPart(pHeroConsumer); } multipart.addBodyPart(pPaynowBM); multipart.addBodyPart(pAutopay); multipart.addBodyPart(pWherepayBM); multipart.addBodyPart(pFooterWeb); multipart.addBodyPart(pFooterFb); multipart.addBodyPart(pFooterTw); multipart.addBodyPart(pFooterTmBM); msg.setContent(multipart); } private void buildEmailContentGlobalEn(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>TM Global bill for " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroGlobal\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Dear valued customer,</font><br /><br />\n" + " Here’s a summary of your latest TM GLOBAL bill. A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Bill Date</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Account Number</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Overdue Amount</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Current Charges</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Total Amount Due*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">\n" + " <b>Note: </b><br>\n" + "1. To avoid your future bills from being automatically sent to junk mail folder, please add our e-mail address " + sender + " to your Address Book and/or the “Approved Sender” list.<br><br>\n" + "2. If there is an overdue amount, kindly make payment promptly to avoid any service interruption. Please disregard this reminder if full payment has already been made<br>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Disclaimer: Please do not reply to this e-mail. For further enquiries or feedback, you may contact your respective TM GLOBAL Account Manager.\n" + " \n" + " \n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"160\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 10px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebGlobal\" alt=\"www.tm.com.my/tmglobal\" height=\"24\">\n" + " </a>\n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"400\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 10px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmEn\" alt=\"TM Group\" width=\"180\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroGlobal); multipart.addBodyPart(pFooterWebGlobal); multipart.addBodyPart(pFooterTmEn); msg.setContent(multipart); } private void buildEmailContentTMOneEn(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>TM ONE bill for " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroTmone\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Dear valued customer,</font><br /><br />\n" + " Here’s a summary of your latest TM ONE bill. A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Bill Date</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Account Number</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Overdue Amount</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Current Charges</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Total Amount Due*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">\n" + " <b>Note: </b><br>\n" + "1. To avoid your future bills from being automatically sent to junk mail folder, please add our e-mail address " + sender + " to your Address Book and/or the “Approved Sender” list.<br><br>\n" + "2. If there is an overdue amount, kindly make payment promptly to avoid any service interruption. Please disregard this reminder if full payment has already been made<br>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Disclaimer: Please do not reply to this e-mail. For further enquiries or feedback, you may contact your respective TM ONE Account Manager.\n" + " \n" + " \n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.tmone.com.my\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebTmone\" alt=\"https://www.tmone.com.my\" width=\"122\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.linkedin.com/company/tm-0ne/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFootLinkdinTmone\" alt=\"https://www.linkedin.com/company/tm-0ne/\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://twitter.com/tm_one\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTwTmone\" alt=\"https://twitter.com/tm_one\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"400\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 10px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmEn\" alt=\"TM Group\" width=\"180\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroTmone); multipart.addBodyPart(pFooterWebTmone); multipart.addBodyPart(pFootLinkdinTmone); multipart.addBodyPart(pFooterTwTmone); multipart.addBodyPart(pFooterTmEn); msg.setContent(multipart); } private void buildEmailContentGlobalBm(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>Bil TM GLOBAL untuk " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroGlobal\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Pelanggan yang dihargai,</font><br /><br />\n" + " Berikut adalah ringkasan bil TM GLOBAL terkini anda. Salinan bil PDF dilampirkan untuk rujukan anda. <br />\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Tarikh Bil</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Nombor Akaun</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Jumlah Caj Tertunggak</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Caj Semasa</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Jumlah Perlu Dibayar*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\"><b>Nota:</b><br>1.Bagi mengelakkan e-mel ini dimasukkan secara automatik ke folder e-mel remeh, sila tambah alamat " + sender + " pada buku alamat anda dan/atau senarai penghantar yang diluluskan. </br><p> 2.Jika terdapat amaun yang tertunggak, sila buat pembayaran segera bagi mengelakkan sebarang gangguan perkhidmatan. Sila abaikan peringatan ini sekiranya pembayaran penuh telah dibuat.</font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Penafian: Sila jangan balas e-mel ini. Untuk pertanyaan lanjut atau maklum balas, sila hubungi Pengurus Akaun TM GLOBAL anda.\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 25px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebGlobal\" alt=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" width=\"135\" height=\"24\">\n" + " </a>\n" + " </td> \n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"700\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmBM\" alt=\"TM Group\" width=\"198\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroGlobal); multipart.addBodyPart(pFooterWebGlobal); multipart.addBodyPart(pFooterTmBM); msg.setContent(multipart); } private void buildEmailContentTMOneBm(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>Bil TM ONE untuk " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroTmone\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Pelanggan yang dihargai,</font><br /><br />\n" + " Berikut adalah ringkasan bil TM ONE terkini anda. Salinan bil PDF dilampirkan untuk rujukan anda. <br />\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Tarikh Bil</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Nombor Akaun</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Jumlah Caj Tertunggak</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Caj Semasa</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Jumlah Perlu Dibayar*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\"><b>Nota:</b><br>1.Bagi mengelakkan e-mel ini dimasukkan secara automatik ke folder e-mel remeh, sila tambah alamat " + sender + " pada buku alamat anda dan/atau senarai penghantar yang diluluskan. </br><p> 2.Jika terdapat amaun yang tertunggak, sila buat pembayaran segera bagi mengelakkan sebarang gangguan perkhidmatan. Sila abaikan peringatan ini sekiranya pembayaran penuh telah dibuat.</font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Penafian: Sila jangan balas e-mel ini. Untuk pertanyaan lanjut atau maklum balas, sila hubungi Pengurus Akaun TM ONE anda.\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.tmone.com.my\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebTmone\" alt=\"https://www.tmone.com.my\" width=\"122\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.linkedin.com/company/tm-0ne/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFootLinkdinTmone\" alt=\"https://www.linkedin.com/company/tm-0ne/\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://twitter.com/tm_one\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTwTmone\" alt=\"https://twitter.com/tm_one\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"700\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmBM\" alt=\"TM Group\" width=\"198\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroTmone); multipart.addBodyPart(pFooterWebTmone); multipart.addBodyPart(pFootLinkdinTmone); multipart.addBodyPart(pFooterTwTmone); multipart.addBodyPart(pFooterTmBM); msg.setContent(multipart); } }
UTF-8
Java
99,154
java
EmailSender.java
Java
[ { "context": "ax.mail.internet.MimeMultipart;\n\n/**\n *\n * @author amer\n */\npublic class EmailSender {\n\n private Properti", "end": 781, "score": 0.9288925528526306, "start": 777, "tag": "USERNAME", "value": "amer" }, { "context": "]{\n new javax.mail.internet.InternetAddress(\"help@tm.com.my\")\n });\n\n // set all of the common attachmen", "end": 2403, "score": 0.999919056892395, "start": 2389, "tag": "EMAIL", "value": "help@tm.com.my" }, { "context": "s or feedback, you can e-mail to <a href=\\\"mailto:help@tm.com.my\\\" style=\\\"text-decoration:underline; color:#27272", "end": 21205, "score": 0.9999224543571472, "start": 21191, "tag": "EMAIL", "value": "help@tm.com.my" }, { "context": "yle=\\\"text-decoration:underline; color:#272727;\\\">help@tm.com.my</a>\\n\"\n + \" </f", "end": 21274, "score": 0.99992436170578, "start": 21260, "tag": "EMAIL", "value": "help@tm.com.my" }, { "context": " <a href=\\\"https://www.facebook.com/weareunifi/\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 24208, "score": 0.9991820454597473, "start": 24198, "tag": "USERNAME", "value": "weareunifi" }, { "context": "if; font-size:14px;\\\" src=\\\"cid:pFooterFb\\\" alt=\\\"weareunifi\\\" width=\\\"71\\\" height=\\\"24\\\">\\n\"\n + \" ", "end": 24399, "score": 0.9856748580932617, "start": 24389, "tag": "USERNAME", "value": "weareunifi" }, { "context": " <a href=\\\"https://twitter.com/unifi?lang=en\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 24723, "score": 0.9963332414627075, "start": 24718, "tag": "USERNAME", "value": "unifi" }, { "context": "if; font-size:14px;\\\" src=\\\"cid:pFooterTw\\\" alt=\\\"@unifi\\\" width=\\\"58\\\" height=\\\"24\\\">\\n\"\n + \" ", "end": 24917, "score": 0.9867798686027527, "start": 24911, "tag": "USERNAME", "value": "@unifi" }, { "context": " maklum balas, sila e-mel kepada <a href=\\\"mailto:help@tm.com.my\\\" style=\\\"text-decoration:underline; color:#27272", "end": 36586, "score": 0.9999312162399292, "start": 36572, "tag": "EMAIL", "value": "help@tm.com.my" }, { "context": "yle=\\\"text-decoration:underline; color:#272727;\\\">help@tm.com.my</a>\\n\"\n + \" </f", "end": 36655, "score": 0.9999319911003113, "start": 36641, "tag": "EMAIL", "value": "help@tm.com.my" }, { "context": " <a href=\\\"https://www.facebook.com/weareunifi/\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 39589, "score": 0.9996252059936523, "start": 39579, "tag": "USERNAME", "value": "weareunifi" }, { "context": "if; font-size:14px;\\\" src=\\\"cid:pFooterFb\\\" alt=\\\"weareunifi\\\" width=\\\"71\\\" height=\\\"24\\\">\\n\"\n + \" ", "end": 39780, "score": 0.9980607032775879, "start": 39770, "tag": "USERNAME", "value": "weareunifi" }, { "context": " <a href=\\\"https://twitter.com/unifi?lang=en\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 40104, "score": 0.9994900226593018, "start": 40099, "tag": "USERNAME", "value": "unifi" }, { "context": "if; font-size:14px;\\\" src=\\\"cid:pFooterTw\\\" alt=\\\"@unifi\\\" width=\\\"58\\\" height=\\\"24\\\">\\n\"\n + \" ", "end": 40298, "score": 0.9995947480201721, "start": 40292, "tag": "USERNAME", "value": "@unifi" }, { "context": " <a href=\\\"https://www.linkedin.com/company/tm-0ne/\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 67620, "score": 0.9995467066764832, "start": 67614, "tag": "USERNAME", "value": "tm-0ne" }, { "context": "dinTmone\\\" alt=\\\"https://www.linkedin.com/company/tm-0ne/\\\" width=\\\"90\\\" height=\\\"auto\\\">\\n\"\n +", "end": 67848, "score": 0.9994101524353027, "start": 67842, "tag": "USERNAME", "value": "tm-0ne" }, { "context": " <a href=\\\"https://twitter.com/tm_one\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 68178, "score": 0.9996740221977234, "start": 68172, "tag": "USERNAME", "value": "tm_one" }, { "context": "=\\\"cid:pFooterTwTmone\\\" alt=\\\"https://twitter.com/tm_one\\\" width=\\\"90\\\" height=\\\"auto\\\">\\n\"\n + ", "end": 68389, "score": 0.999636173248291, "start": 68383, "tag": "USERNAME", "value": "tm_one" }, { "context": " <a href=\\\"https://www.linkedin.com/company/tm-0ne/\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 96676, "score": 0.9994498491287231, "start": 96670, "tag": "USERNAME", "value": "tm-0ne" }, { "context": "dinTmone\\\" alt=\\\"https://www.linkedin.com/company/tm-0ne/\\\" width=\\\"90\\\" height=\\\"auto\\\">\\n\"\n +", "end": 96904, "score": 0.9995035529136658, "start": 96898, "tag": "USERNAME", "value": "tm-0ne" }, { "context": " <a href=\\\"https://twitter.com/tm_one\\\" target=\\\"_blank\\\">\\n\"\n + \" ", "end": 97234, "score": 0.9995579719543457, "start": 97228, "tag": "USERNAME", "value": "tm_one" }, { "context": "=\\\"cid:pFooterTwTmone\\\" alt=\\\"https://twitter.com/tm_one\\\" width=\\\"90\\\" height=\\\"auto\\\">\\n\"\n + ", "end": 97445, "score": 0.9995689392089844, "start": 97439, "tag": "USERNAME", "value": "tm_one" } ]
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 emailbillsender; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * * @author amer */ public class EmailSender { private Properties prop; private Session ses; private MimeMessage msg; private final String curSys; private final String sender; // all of the attachments private BodyPart pAutopay; private BodyPart pPaynowBM; private BodyPart pPaynowEn; private BodyPart pWherepayBM; private BodyPart pWherepayEn; private BodyPart pFooterFb; private BodyPart pFootLinkdinTmone; private BodyPart pFooterTmBM; private BodyPart pFooterTmEn; private BodyPart pFooterTw; private BodyPart pFooterTwTmone; private BodyPart pFooterWeb; private BodyPart pFooterWebGlobal; private BodyPart pFooterWebTmone; private BodyPart pHeroConsumer; private BodyPart pHeroGlobal; private BodyPart pHeroSme; private BodyPart pHeroTmone; public EmailSender(String host, boolean verbose, String sys, String sendermail) { this.prop = new Properties(); this.prop.put("mail.smtp.host", host); this.curSys = sys.toLowerCase(); this.sender = sendermail; ses = Session.getDefaultInstance(prop); ses.setDebug(verbose); // System.out.println("Mail Session v2 Initialized!"); msg = new MimeMessage(ses); } /** * prepare all the common things * * @throws java.io.UnsupportedEncodingException * @throws javax.mail.MessagingException */ public void init() throws UnsupportedEncodingException, MessagingException { InternetAddress addrFrom = new InternetAddress(sender, "Telekom Malaysia Berhad"); msg.setFrom(addrFrom); msg.setReplyTo(new javax.mail.Address[]{ new javax.mail.internet.InternetAddress("<EMAIL>") }); // set all of the common attachments pAutopay = new MimeBodyPart(); DataSource fds = new FileDataSource("asset/cta-autopay.png"); pAutopay.setDataHandler(new DataHandler(fds)); pAutopay.setHeader("Content-ID", "<pAutopay>"); pAutopay.setDisposition(MimeBodyPart.INLINE); pPaynowBM = new MimeBodyPart(); fds = new FileDataSource("asset/cta-paynow-bm.jpg"); pPaynowBM.setDataHandler(new DataHandler(fds)); pPaynowBM.setHeader("Content-ID", "<pPaynowBM>"); pPaynowBM.setDisposition(MimeBodyPart.INLINE); pPaynowEn = new MimeBodyPart(); fds = new FileDataSource("asset/cta-paynow-eng.jpg"); pPaynowEn.setDataHandler(new DataHandler(fds)); pPaynowEn.setHeader("Content-ID", "<pPaynowEn>"); pPaynowEn.setDisposition(MimeBodyPart.INLINE); pWherepayBM = new MimeBodyPart(); fds = new FileDataSource("asset/cta-wherecanipaymybill-bm.png"); pWherepayBM.setDataHandler(new DataHandler(fds)); pWherepayBM.setHeader("Content-ID", "<pWherepayBM>"); pWherepayBM.setDisposition(MimeBodyPart.INLINE); pWherepayEn = new MimeBodyPart(); fds = new FileDataSource("asset/cta-wherecanipaymybill-eng.png"); pWherepayEn.setDataHandler(new DataHandler(fds)); pWherepayEn.setHeader("Content-ID", "<pWherepayEn>"); pWherepayEn.setDisposition(MimeBodyPart.INLINE); pFooterFb = new MimeBodyPart(); fds = new FileDataSource("asset/footer_fb.jpg"); pFooterFb.setDataHandler(new DataHandler(fds)); pFooterFb.setHeader("Content-ID", "<pFooterFb>"); pFooterFb.setDisposition(MimeBodyPart.INLINE); pFootLinkdinTmone = new MimeBodyPart(); fds = new FileDataSource("asset/footer_linkedin-tmone.jpg"); pFootLinkdinTmone.setDataHandler(new DataHandler(fds)); pFootLinkdinTmone.setHeader("Content-ID", "<pFootLinkdinTmone>"); pFootLinkdinTmone.setDisposition(MimeBodyPart.INLINE); pFooterTmBM = new MimeBodyPart(); fds = new FileDataSource("asset/footer_tm-bm.jpg"); pFooterTmBM.setDataHandler(new DataHandler(fds)); pFooterTmBM.setHeader("Content-ID", "<pFooterTmBM>"); pFooterTmBM.setDisposition(MimeBodyPart.INLINE); pFooterTmEn = new MimeBodyPart(); fds = new FileDataSource("asset/footer_tm-eng.jpg"); pFooterTmEn.setDataHandler(new DataHandler(fds)); pFooterTmEn.setHeader("Content-ID", "<pFooterTmEn>"); pFooterTmEn.setDisposition(MimeBodyPart.INLINE); pFooterTw = new MimeBodyPart(); fds = new FileDataSource("asset/footer_tw.jpg"); pFooterTw.setDataHandler(new DataHandler(fds)); pFooterTw.setHeader("Content-ID", "<pFooterTw>"); pFooterTw.setDisposition(MimeBodyPart.INLINE); pFooterTwTmone = new MimeBodyPart(); fds = new FileDataSource("asset/footer_twitter-tmone.jpg"); pFooterTwTmone.setDataHandler(new DataHandler(fds)); pFooterTwTmone.setHeader("Content-ID", "<pFooterTwTmone>"); pFooterTwTmone.setDisposition(MimeBodyPart.INLINE); pFooterWeb = new MimeBodyPart(); fds = new FileDataSource("asset/footer_web.jpg"); pFooterWeb.setDataHandler(new DataHandler(fds)); pFooterWeb.setHeader("Content-ID", "<pFooterWeb>"); pFooterWeb.setDisposition(MimeBodyPart.INLINE); pFooterWebGlobal = new MimeBodyPart(); fds = new FileDataSource("asset/footer_web-global.jpg"); pFooterWebGlobal.setDataHandler(new DataHandler(fds)); pFooterWebGlobal.setHeader("Content-ID", "<pFooterWebGlobal>"); pFooterWebGlobal.setDisposition(MimeBodyPart.INLINE); pFooterWebTmone = new MimeBodyPart(); fds = new FileDataSource("asset/footer_web-tmone.jpg"); pFooterWebTmone.setDataHandler(new DataHandler(fds)); pFooterWebTmone.setHeader("Content-ID", "<pFooterWebTmone>"); pFooterWebTmone.setDisposition(MimeBodyPart.INLINE); pHeroConsumer = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-consumer.jpg"); pHeroConsumer.setDataHandler(new DataHandler(fds)); pHeroConsumer.setHeader("Content-ID", "<pHeroConsumer>"); pHeroConsumer.setDisposition(MimeBodyPart.INLINE); pHeroGlobal = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-global.jpg"); pHeroGlobal.setDataHandler(new DataHandler(fds)); pHeroGlobal.setHeader("Content-ID", "<pHeroGlobal>"); pHeroGlobal.setDisposition(MimeBodyPart.INLINE); pHeroSme = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-sme.jpg"); pHeroSme.setDataHandler(new DataHandler(fds)); pHeroSme.setHeader("Content-ID", "<pHeroSme>"); pHeroSme.setDisposition(MimeBodyPart.INLINE); pHeroTmone = new MimeBodyPart(); fds = new FileDataSource("asset/hero-image-tmone.jpg"); pHeroTmone.setDataHandler(new DataHandler(fds)); pHeroTmone.setHeader("Content-ID", "<pHeroTmone>"); pHeroTmone.setDisposition(MimeBodyPart.INLINE); } private void setSubject(String bano, Date bdate, String lob, String lang) throws MessagingException { String dateformat = Utilities.dateFormat(bdate, "MM yyyy"); // set the subject if (curSys.equals("icp")) { if (lang.equals("mal")) { msg.setSubject("Bil TM anda (No Akaun: " + bano + ") untuk bulan " + dateformat); } else { // english msg.setSubject("Your TM bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } } else { // nova if (lob.equals("consumer")) { msg.setSubject("Your unifi Home bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } else if (lob.equals("sme")) { msg.setSubject("Your unifi bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } else { // tmone and global msg.setSubject("Your TM bill for " + dateformat + " is ready! (Account no: " + bano + ")"); } } } public String send(String name, String bano, Date enddate, double amount, File pdf, String emailaddr, String ccaddr, String lob, String lang, String currency, double overdue, double cmc, Date duedate ) throws MessagingException { if (emailaddr.trim().isEmpty()) { return "empty email"; } // set the recipient setRecip(emailaddr); setCCRecip(ccaddr); setSubject(bano, enddate, lob, lang); // set the email body if (lang.equals("eng") || curSys.equals("nova")) { if (lob.equals("consumer") || lob.equals("sme")) { buildEmailContentUnifiEn(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else if (lob.equals("global") || lob.equals("wholesale")) { buildEmailContentGlobalEn(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else { // tm one buildEmailContentTMOneEn(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } } else { if (lob.equals("consumer") || lob.equals("sme")) { buildEmailContentUnifiBm(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else if (lob.equals("global") || lob.equals("wholesale")) { buildEmailContentGlobalBm(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } else { // tm one buildEmailContentTMOneBm(name, bano, Utilities.dateFormat(enddate, "dd MMM yyyy"), amount, lob, currency, overdue, cmc, Utilities.dateFormat(duedate, "dd MMM yyyy"), pdf); } } // send the email Transport.send(msg); return "success"; } /// ---------------------------------------------------------------------- private void setRecip(String recipient) throws MessagingException { if (recipient.contains(",")) { String[] rlist = recipient.split(","); int dsize = rlist.length; InternetAddress[] adrss = new InternetAddress[dsize]; for (int i = 0; i < dsize; i++) { adrss[i] = new InternetAddress(rlist[i]); } msg.setRecipients(Message.RecipientType.TO, adrss); } else { InternetAddress addrTo = new InternetAddress(recipient); msg.setRecipient(Message.RecipientType.TO, addrTo); } } private void setCCRecip(String recipient) throws MessagingException { if (recipient.trim().isEmpty()) { return; } if (recipient.contains(",")) { String[] rlist = recipient.split(","); int dsize = rlist.length; InternetAddress[] adrss = new InternetAddress[dsize]; for (int i = 0; i < dsize; i++) { adrss[i] = new InternetAddress(rlist[i]); } msg.setRecipients(Message.RecipientType.CC, adrss); } else { InternetAddress addrTo = new InternetAddress(recipient); msg.setRecipient(Message.RecipientType.CC, addrTo); } } private void buildEmailContentUnifiEn(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String sLabel = this.curSys.toLowerCase().equals("nova") ? "unifi Home" : "TM"; String otopaybg = lob.toLowerCase().equals("sme") ? "96d8ff" : "f7941d"; String herobanner = lob.toLowerCase().equals("sme") ? "pHeroSme" : "pHeroConsumer"; String overduedisp = "&nbsp;"; String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); if (overdue > 0) { overduedisp = " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:14px;\">PAY IMMEDIATELY</font>\n"; } String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>unifi</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:" + herobanner + "\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Hello " + name + "</font><br /><br />\n" + " Here’s a summary of your latest <b>" + sLabel + " bill</b>.<br />\n" + " A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Bill Date</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Account Number</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Overdue Amount</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Current Charges</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Total Amount Due*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + overduedisp + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pPaynowEn\" alt=\"Pay Now\" width=\"145\" height=\"35\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">*If you have already signed up with our <b>Autopay</b> service, the total amount above will be deducted automatically from your card within the next few days.</font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Disclaimer: Please do not reply to this email.<br />\n" + " For further enquiries or feedback, you can e-mail to <a href=\"mailto:<EMAIL>\" style=\"text-decoration:underline; color:#272727;\"><EMAIL></a>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pAutopay\" alt=\"Auto Pay\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pWherepayEn\" alt=\"Where can i pay my bill\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 25px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWeb\" alt=\"www.unifi.com.my\" width=\"80\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.facebook.com/weareunifi/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterFb\" alt=\"weareunifi\" width=\"71\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"58\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://twitter.com/unifi?lang=en\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTw\" alt=\"@unifi\" width=\"58\" height=\"24\">\n" + " </a>\n" + " </td> \n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"88\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmEn\" alt=\"TM Group\" width=\"180\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); // add the rest of the inlines if (lob.toLowerCase().equals("sme")) { multipart.addBodyPart(pHeroSme); } else { multipart.addBodyPart(pHeroConsumer); } multipart.addBodyPart(pPaynowEn); multipart.addBodyPart(pAutopay); multipart.addBodyPart(pWherepayEn); multipart.addBodyPart(pFooterWeb); multipart.addBodyPart(pFooterFb); multipart.addBodyPart(pFooterTw); multipart.addBodyPart(pFooterTmEn); msg.setContent(multipart); } private void buildEmailContentUnifiBm(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String otopaybg = lob.toLowerCase().equals("sme") ? "96d8ff" : "f7941d"; String herobanner = lob.toLowerCase().equals("sme") ? "pHeroSme" : "pHeroConsumer"; String overduedisp = "&nbsp;"; String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); if (overdue > 0) { overduedisp = " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:14px;\">PAY IMMEDIATELY</font>\n"; } String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>unifi</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:" + herobanner + "\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Hello " + name + "</font><br /><br />\n" + " Berikut adalah ringkasan <b>bil TM</b> terkini anda.<br />\n" + " A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Tarikh Bil</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Nombor Akaun</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Jumlah Caj Tertunggak</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Caj Semasa</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Jumlah Perlu Dibayar*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + overduedisp + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pPaynowBM\" alt=\"Pay Now\" width=\"184\" height=\"35\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">*Jika anda pelanggan <b>Autopay</b> sedia ada, jumlah perlu dibayar akan didebitkan secara automatik melalui kad debit/kredit anda dalam masa beberapa hari dari tarikh bil ini. </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Penafian: Sila jangan balas e-mel ini.<br />\n" + " Untuk pertanyaan lanjut atau maklum balas, sila e-mel kepada <a href=\"mailto:<EMAIL>\" style=\"text-decoration:underline; color:#272727;\"><EMAIL></a>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#" + otopaybg + "\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pAutopay\" alt=\"Auto Pay\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pWherepayBm\" alt=\"Where can i pay my bill\" width=\"200\" height=\"70\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 25px;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWeb\" alt=\"www.unifi.com.my\" width=\"80\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.facebook.com/weareunifi/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterFb\" alt=\"weareunifi\" width=\"71\" height=\"24\">\n" + " </a>\n" + " </td>\n" + " <td width=\"58\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://twitter.com/unifi?lang=en\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTw\" alt=\"@unifi\" width=\"58\" height=\"24\">\n" + " </a>\n" + " </td> \n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"88\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmBM\" alt=\"TM Group\" width=\"198\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); // add the rest of the inlines if (lob.toLowerCase().equals("sme")) { multipart.addBodyPart(pHeroSme); } else { multipart.addBodyPart(pHeroConsumer); } multipart.addBodyPart(pPaynowBM); multipart.addBodyPart(pAutopay); multipart.addBodyPart(pWherepayBM); multipart.addBodyPart(pFooterWeb); multipart.addBodyPart(pFooterFb); multipart.addBodyPart(pFooterTw); multipart.addBodyPart(pFooterTmBM); msg.setContent(multipart); } private void buildEmailContentGlobalEn(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>TM Global bill for " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroGlobal\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Dear valued customer,</font><br /><br />\n" + " Here’s a summary of your latest TM GLOBAL bill. A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Bill Date</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Account Number</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Overdue Amount</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Current Charges</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Total Amount Due*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">\n" + " <b>Note: </b><br>\n" + "1. To avoid your future bills from being automatically sent to junk mail folder, please add our e-mail address " + sender + " to your Address Book and/or the “Approved Sender” list.<br><br>\n" + "2. If there is an overdue amount, kindly make payment promptly to avoid any service interruption. Please disregard this reminder if full payment has already been made<br>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Disclaimer: Please do not reply to this e-mail. For further enquiries or feedback, you may contact your respective TM GLOBAL Account Manager.\n" + " \n" + " \n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"160\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 10px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebGlobal\" alt=\"www.tm.com.my/tmglobal\" height=\"24\">\n" + " </a>\n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"400\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 10px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmEn\" alt=\"TM Group\" width=\"180\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroGlobal); multipart.addBodyPart(pFooterWebGlobal); multipart.addBodyPart(pFooterTmEn); msg.setContent(multipart); } private void buildEmailContentTMOneEn(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>TM ONE bill for " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroTmone\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Dear valued customer,</font><br /><br />\n" + " Here’s a summary of your latest TM ONE bill. A PDF bill copy is attached for your reference.\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Bill Date</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Account Number</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Overdue Amount</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Current Charges</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Total Amount Due*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:14px;\">Payment Due Date</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\">\n" + " <b>Note: </b><br>\n" + "1. To avoid your future bills from being automatically sent to junk mail folder, please add our e-mail address " + sender + " to your Address Book and/or the “Approved Sender” list.<br><br>\n" + "2. If there is an overdue amount, kindly make payment promptly to avoid any service interruption. Please disregard this reminder if full payment has already been made<br>\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Disclaimer: Please do not reply to this e-mail. For further enquiries or feedback, you may contact your respective TM ONE Account Manager.\n" + " \n" + " \n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.tmone.com.my\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebTmone\" alt=\"https://www.tmone.com.my\" width=\"122\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.linkedin.com/company/tm-0ne/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFootLinkdinTmone\" alt=\"https://www.linkedin.com/company/tm-0ne/\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://twitter.com/tm_one\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTwTmone\" alt=\"https://twitter.com/tm_one\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"400\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 10px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmEn\" alt=\"TM Group\" width=\"180\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroTmone); multipart.addBodyPart(pFooterWebTmone); multipart.addBodyPart(pFootLinkdinTmone); multipart.addBodyPart(pFooterTwTmone); multipart.addBodyPart(pFooterTmEn); msg.setContent(multipart); } private void buildEmailContentGlobalBm(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>Bil TM GLOBAL untuk " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroGlobal\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Pelanggan yang dihargai,</font><br /><br />\n" + " Berikut adalah ringkasan bil TM GLOBAL terkini anda. Salinan bil PDF dilampirkan untuk rujukan anda. <br />\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Tarikh Bil</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Nombor Akaun</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Jumlah Caj Tertunggak</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Caj Semasa</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Jumlah Perlu Dibayar*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\"><b>Nota:</b><br>1.Bagi mengelakkan e-mel ini dimasukkan secara automatik ke folder e-mel remeh, sila tambah alamat " + sender + " pada buku alamat anda dan/atau senarai penghantar yang diluluskan. </br><p> 2.Jika terdapat amaun yang tertunggak, sila buat pembayaran segera bagi mengelakkan sebarang gangguan perkhidmatan. Sila abaikan peringatan ini sekiranya pembayaran penuh telah dibuat.</font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Penafian: Sila jangan balas e-mel ini. Untuk pertanyaan lanjut atau maklum balas, sila hubungi Pengurus Akaun TM GLOBAL anda.\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 25px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebGlobal\" alt=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" width=\"135\" height=\"24\">\n" + " </a>\n" + " </td> \n" + " <td width=\"145\" bgcolor=\"#ffffff\">\n" + " </td>\n" + " <td width=\"700\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmBM\" alt=\"TM Group\" width=\"198\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroGlobal); multipart.addBodyPart(pFooterWebGlobal); multipart.addBodyPart(pFooterTmBM); msg.setContent(multipart); } private void buildEmailContentTMOneBm(String name, String bano, String enddate, double totout, String lob, String currency, double overdue, double cmc, String due_date, File pdf ) throws MessagingException { // set the email body MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String overdueamt = currency + String.format("%.2f", overdue); String cmcamt = currency + String.format("%.2f", cmc); String totdueamt = currency + String.format("%.2f", totout); String mainbody = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + " <head>\n" + " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" + " <title>Bil TM ONE untuk " + name + "</title>\n" + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " </head>\n" + " <body style=\"margin: 0; padding: 0;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" + " <tr>\n" + " <td>\n" + " <!-- Begin Header -->\n" + " <table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td bgcolor=\"#ffffff\" align=\"center\" style=\"font-family:Arial, Helvetica, sans-serif;font-size:9px;color:#464646;padding:8px 0px 4px 0px;\">\n" + " To ensure you receive our emails, save <a style=\"color:#025ba5;\" href=\"mailto:" + sender + "\" target=\"_blank\">&lt;" + sender + "&gt;</a> to your email address book.<br>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " <!-- End Header -->\n" + "\n" + " <table bgcolor=\"#e4e8ee\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse;\">\n" + "\n" + " <!-- Begin Content -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:18px;\" src=\"cid:pHeroTmone\" alt=\"TM\" width=\"600\" height=\"305\">\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 30px 30px 25px 30px; font-size: 17px; color: #272727;\">\n" + " <font style=\"font-size:24px;\">Pelanggan yang dihargai,</font><br /><br />\n" + " Berikut adalah ringkasan bil TM ONE terkini anda. Salinan bil PDF dilampirkan untuk rujukan anda. <br />\n" + " \n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " \n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 20px 20px 20px;\">\n" + " <table bgcolor=\"#ffffff\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td colspan=\"2\" width=\"297\" align=\"center\" style=\"padding:12px 12px 12px 12px; border-right:2px solid #d1d3d7; background-color:#f7941d; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Tarikh Bil</font><br />\n" + " <font style=\"font-size:22px;\">" + enddate + "</font>\n" + " </td>\n" + " <td width=\"223\" align=\"center\" style=\"padding:12px 12px 12px 12px; background-color:#20409a; color:#ffffff;\">\n" + " <font style=\"font-size:14px;\">Nombor Akaun</font><br />\n" + " <font style=\"font-size:22px;\">" + bano + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Jumlah Caj Tertunggak</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + overdueamt + "</font>\n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:15px 15px 15px 15px; border-right:2px solid #d1d3d7;\"\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Caj Semasa</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + cmcamt + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:15px 15px 15px 15px;\">\n" + " <font style=\"color:#20409a; font-size:18px;\">Jumlah Perlu Dibayar*</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + totdueamt + "</font>\n" + " </td>\n" + " </tr>\n" + " <tr>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">&nbsp;\n" + " \n" + " </td>\n" + " <td width=\"148\" align=\"center\" style=\"padding:0px 15px 15px 15px; border-right:2px solid #d1d3d7;\">\n" + " <font style=\"color:#20409a; font-size:13px;\">Sila Bayar Sebelum</font>\n" + " <font style=\"color:#f7941d; font-size:21px;\">" + due_date + "</font>\n" + " </td>\n" + " <td align=\"center\" style=\"padding:0px 0px 10px 0px;\">\n" + " <a href=\"https://www.tm.com.my/tmglobal/Pages/Welcome.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr> \n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 0px 30px 25px 30px; color: #272727;\">\n" + " <font style=\"font-size:12px; font-style:italic;\"><b>Nota:</b><br>1.Bagi mengelakkan e-mel ini dimasukkan secara automatik ke folder e-mel remeh, sila tambah alamat " + sender + " pada buku alamat anda dan/atau senarai penghantar yang diluluskan. </br><p> 2.Jika terdapat amaun yang tertunggak, sila buat pembayaran segera bagi mengelakkan sebarang gangguan perkhidmatan. Sila abaikan peringatan ini sekiranya pembayaran penuh telah dibuat.</font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"left\" style=\"padding: 20px 30px 20px 30px; color: #272727;\">\n" + " <font style=\"font-size:14px;\">\n" + " Penafian: Sila jangan balas e-mel ini. Untuk pertanyaan lanjut atau maklum balas, sila hubungi Pengurus Akaun TM ONE anda.\n" + " </font>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + " <tr>\n" + " <td colspan=\"3\" align=\"center\" style=\"padding: 0px 0px 0px 0px;\" bgcolor=\"#f7941d\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse; font-family:Arial, Helvetica, sans-serif; color: #000000;\">\n" + " <tr>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://unifi.com.my/personal\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " <td align=\"center\" style=\"padding: 0px 0px 20px 0px; color: #272727;\">\n" + " <a href=\"https://community.unifi.com.my/t5/Bill-Payment/Where-can-I-pay-my-unifi-bill/ta-p/8927\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + "\n" + "\n" + " <!-- End Content -->\n" + "\n" + "\n" + " <!-- Begin Footer -->\n" + " <tr>\n" + " <td colspan=\"3\" align=\"left\" bgcolor=\"#ffffff\" style=\"padding: 12px 0px 12px 0px;\">\n" + " <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse;\">\n" + " <tr>\n" + " <td width=\"80\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 8px;\">\n" + " <a href=\"https://www.tmone.com.my\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterWebTmone\" alt=\"https://www.tmone.com.my\" width=\"122\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.linkedin.com/company/tm-0ne/\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFootLinkdinTmone\" alt=\"https://www.linkedin.com/company/tm-0ne/\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"71\" align=\"center\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://twitter.com/tm_one\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTwTmone\" alt=\"https://twitter.com/tm_one\" width=\"90\" height=\"auto\">\n" + " </a>\n" + " </td> \n" + " <td width=\"700\" align=\"right\" bgcolor=\"#ffffff\" style=\"padding: 0px 0px 0px 0px;\">\n" + " <a href=\"https://www.tm.com.my/Pages/Home.aspx\" target=\"_blank\">\n" + " <img style=\"display:block; font-family:Arial, Helvetica, sans-serif; font-size:14px;\" src=\"cid:pFooterTmBM\" alt=\"TM Group\" width=\"198\" height=\"36\">\n" + " </a>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </td>\n" + " </tr>\n" + " <!-- End Footer -->\n" + " \n" + " </table>\n" + " </td>\n" + " </tr>\n" + " </table>\n" + " </body>\n" + "</html>"; messageBodyPart.setContent(mainbody, "text/html"); multipart.addBodyPart(messageBodyPart); // add the pdf attachment BodyPart pPdfAttach = new MimeBodyPart(); DataSource fds = new FileDataSource(pdf); pPdfAttach.setDataHandler(new DataHandler(fds)); pPdfAttach.setFileName(pdf.getName()); multipart.addBodyPart(pPdfAttach); multipart.addBodyPart(pHeroTmone); multipart.addBodyPart(pFooterWebTmone); multipart.addBodyPart(pFootLinkdinTmone); multipart.addBodyPart(pFooterTwTmone); multipart.addBodyPart(pFooterTmBM); msg.setContent(multipart); } }
99,119
0.449471
0.42162
1,550
62.956127
53.202637
487
false
false
0
0
0
0
0
0
0.970968
false
false
12
dba1c0f25fc41a2a763c85865e17c1ce46d46d53
9,783,935,565,480
7627b1fbb32ab9ad8e7b0820eb7b9684c7c30cef
/java/android_apk_workspace/android_2_editview/src/com/example/android_qq/ThirdActivity.java
d8b1cfb016804dcd7fe272397d90b191240ac50d
[]
no_license
AllenWang1985/dst_store
https://github.com/AllenWang1985/dst_store
cd5532998935ea613d328193c8c0fc9a7873a0c1
00f34727b3d2fe95326e69454a4035d9d32967d4
refs/heads/master
2021-01-05T11:29:03.775000
2019-06-04T12:46:44
2019-06-04T12:46:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.android_qq; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ThirdActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.third); final TextView tv = (TextView) findViewById(R.id.textView1); final EditText ev = (EditText) findViewById(R.id.editText1); Button bt = (Button) findViewById(R.id.bt1); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String str = ev.getEditableText().toString(); tv.setText(str); } }); } }
UTF-8
Java
877
java
ThirdActivity.java
Java
[]
null
[]
package com.example.android_qq; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class ThirdActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.third); final TextView tv = (TextView) findViewById(R.id.textView1); final EditText ev = (EditText) findViewById(R.id.editText1); Button bt = (Button) findViewById(R.id.bt1); bt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String str = ev.getEditableText().toString(); tv.setText(str); } }); } }
877
0.741163
0.737742
33
25.575758
19.096296
62
false
false
0
0
0
0
0
0
1.969697
false
false
12
fb3c097e28445a679a892dafabec7f2f34b60d91
30,709,016,171,093
feec8f9bb32e13b2e365a8bc9e201275f8a890fa
/src/main/java/edu/bpl/pwsplugin/acquisitionsequencer/defaultplugin/factories/WaitStepFactory.java
83094a5b61dda9894ecaa92a3c716d18d6ec89a2
[]
no_license
nanthony21/mmPWSPlugin
https://github.com/nanthony21/mmPWSPlugin
3b6e9a743112b10784e1cc0f42fba25d2a8838fb
539efabc26f7b5e77a5b812922f8bca3eb0211d1
refs/heads/master
2023-08-05T17:38:03.778000
2021-11-16T03:20:06
2021-11-16T03:20:06
333,927,667
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.bpl.pwsplugin.acquisitionsequencer.defaultplugin.factories; import edu.bpl.pwsplugin.UI.utils.BuilderJPanel; import edu.bpl.pwsplugin.UI.utils.ImprovedComponents; import edu.bpl.pwsplugin.UI.utils.ImprovedComponents.Spinner; import edu.bpl.pwsplugin.acquisitionsequencer.defaultplugin.factories.WaitStepFactory.WaitStepSettings; import edu.bpl.pwsplugin.acquisitionsequencer.defaultplugin.steps.WaitStep; import edu.bpl.pwsplugin.acquisitionsequencer.factory.StepFactory; import edu.bpl.pwsplugin.acquisitionsequencer.steps.Step; import edu.bpl.pwsplugin.utils.JsonableParam; import javax.swing.JLabel; import javax.swing.SpinnerNumberModel; import net.miginfocom.swing.MigLayout; public class WaitStepFactory implements StepFactory { @Override public BuilderJPanel<?> createUI() { return new WaitStepUI(); } @Override public Class<? extends JsonableParam> getSettings() { return WaitStepSettings.class; } @Override public Step<?> createStep() { return new WaitStep(); } @Override public String getDescription() { return "Simply waits for a given number of seconds."; } @Override public String getName() { return "Wait"; } @Override public String getCategory() { return "Utility"; } public static class WaitStepSettings extends JsonableParam { public double waitTime = 1.; } } class WaitStepUI extends BuilderJPanel<WaitStepSettings> { private final ImprovedComponents.Spinner spinner = new Spinner(new SpinnerNumberModel(1., 0., 1e6, 1.)); public WaitStepUI() { super(new MigLayout(), WaitStepSettings.class); add(new JLabel("Wait time (s):")); add(spinner); } @Override public WaitStepSettings build() throws BuilderPanelException { WaitStepSettings settings = new WaitStepSettings(); settings.waitTime = (double) spinner.getValue(); return settings; } @Override public void populateFields(WaitStepSettings settings) throws BuilderPanelException { spinner.setValue(settings.waitTime); } }
UTF-8
Java
2,090
java
WaitStepFactory.java
Java
[]
null
[]
package edu.bpl.pwsplugin.acquisitionsequencer.defaultplugin.factories; import edu.bpl.pwsplugin.UI.utils.BuilderJPanel; import edu.bpl.pwsplugin.UI.utils.ImprovedComponents; import edu.bpl.pwsplugin.UI.utils.ImprovedComponents.Spinner; import edu.bpl.pwsplugin.acquisitionsequencer.defaultplugin.factories.WaitStepFactory.WaitStepSettings; import edu.bpl.pwsplugin.acquisitionsequencer.defaultplugin.steps.WaitStep; import edu.bpl.pwsplugin.acquisitionsequencer.factory.StepFactory; import edu.bpl.pwsplugin.acquisitionsequencer.steps.Step; import edu.bpl.pwsplugin.utils.JsonableParam; import javax.swing.JLabel; import javax.swing.SpinnerNumberModel; import net.miginfocom.swing.MigLayout; public class WaitStepFactory implements StepFactory { @Override public BuilderJPanel<?> createUI() { return new WaitStepUI(); } @Override public Class<? extends JsonableParam> getSettings() { return WaitStepSettings.class; } @Override public Step<?> createStep() { return new WaitStep(); } @Override public String getDescription() { return "Simply waits for a given number of seconds."; } @Override public String getName() { return "Wait"; } @Override public String getCategory() { return "Utility"; } public static class WaitStepSettings extends JsonableParam { public double waitTime = 1.; } } class WaitStepUI extends BuilderJPanel<WaitStepSettings> { private final ImprovedComponents.Spinner spinner = new Spinner(new SpinnerNumberModel(1., 0., 1e6, 1.)); public WaitStepUI() { super(new MigLayout(), WaitStepSettings.class); add(new JLabel("Wait time (s):")); add(spinner); } @Override public WaitStepSettings build() throws BuilderPanelException { WaitStepSettings settings = new WaitStepSettings(); settings.waitTime = (double) spinner.getValue(); return settings; } @Override public void populateFields(WaitStepSettings settings) throws BuilderPanelException { spinner.setValue(settings.waitTime); } }
2,090
0.737799
0.734928
74
27.229731
27.051775
107
false
false
0
0
0
0
0
0
0.418919
false
false
12
e2780c11c78ec9a13541c2eeb4fadde66b189534
10,926,396,809,971
d71b4e910a18b0d003aee3e51f721dd7cf730c46
/wms-app/wms-java/src/main/java/com/busch/wms/shipment/vo/InboundShipmentVO.java
5f96c1f06f70cf7082ffea10e26dd8aa965aa0e0
[]
no_license
NeverEnoughLights/Test-Repository
https://github.com/NeverEnoughLights/Test-Repository
68230902dbdd88d7734b049d98e4f939be675e17
45b628467f9712586ef15da973f4f42632e24977
refs/heads/Develop
2019-07-02T06:57:43.680000
2017-04-19T15:03:56
2017-04-19T15:03:56
80,837,721
0
0
null
false
2017-04-19T15:25:25
2017-02-03T14:45:57
2017-02-03T14:59:27
2017-04-19T15:25:24
150,598
0
0
0
Java
null
null
/*** COPYRIGHT 2004 BY ANHEUSER-BUSCH. ALL RIGHTS RESERVED. ***/ package com.busch.wms.shipment.vo; import com.busch.wms.basefiles.vo.BaseVO; import com.busch.wms.basefiles.vo.EquipmentVO; import com.busch.wms.order.vo.OrderVO; import com.busch.wms.security.vo.UserProfileVO; import java.util.ArrayList; import java.util.Date; /** * This VO holds the details of a particular Inbound Shipment. This would be used * when the user tries to save a new Inbound Shipment. * @author: Sarat Babu Remote Developer - Infosys * @author: Shrikant_Patel Remote Developer - Infosys * @version: 1.0 */ public class InboundShipmentVO extends BaseVO { /** * Constructor for InboundShipmentVO. */ public InboundShipmentVO() { } /** * Constructor for InboundShipmentVO. * @param user */ public InboundShipmentVO(UserProfileVO user) { super(user); } /** * This variable holds the Ship Mode. */ private String m_strShipMode; /** * This holds the shipment sequence Id. */ private int m_iShipmentSequenceId; /** * This variable holds the Shipment Number. */ private String m_strShipmentNumber; /** * This variable holds the shipment bol seq id */ private int m_iShipmentBOLSeqId; /** * This variable holds the BOL Number. */ private String m_strBOLNumber; /** * This variable holds the Order Number. */ private String m_strOrderNumber; /** * This variable holds the Ship Type. */ private String m_strShipType; /** * This variable holds the Ship From code/number. */ private String m_strShipFrom; /** * This variable holds the Ship From name/description. */ private String m_strShipFromName; /** * This variable holds the business entity sequence id of the * Ship From place */ private int m_iBusinessEntitySequenceId; /** * This variable holds the arraylist of InboundCommodityVO. */ private ArrayList m_arrlstInboundCommodityDetailsVO; /** * In case of Beer Returns or Beer Returns/Trade Returns, this varaible holds the * BRA numbes linked to the shipment. In case of any other shipment types, this * shall be null. */ private ArrayList m_arrlstBeerReturnNumbers; /** * This variable holds information whether shipment is manualy created shipment */ private boolean m_boolIsManual; /** * This contains the equipment number, its seq id, carrier code, whether the * equipment is at door, whether the inbound comm in it is unknown. */ private EquipmentVO m_equipmentVO; /** * This varaible is true - If equipment data is changed. Else false. This is used * when the user is updating the information. Only if it changes then * 1. Linking to shipment * 2. Delinking of old equipment * 3. Check of whether the equipment is at door with inbound commodity 'unknown' * and kicking off the calculate commodity will be done. */ private boolean m_boolEquipChanged; /** * This is used when the user is updating the information. This variable holds * information whether 1. BOL 2. Order #. 3. Ship From location changed. If yes * then it is true else false. Only if this is true we shall again check whether * this is an unique combination. */ private boolean m_boolBOLChanged; /** * This is used when the user is updating the information. It is set to true if * the line item quantity changes. Based on this we shall kick off the calculate * commodity again. */ private boolean m_boolLineItemsChanged; /** * This is used when the user is updating the information. This is set to true if * the BRA numbers change. Based on this it is decided if we have to link the new * BRAs and delink the old BRAs. */ private boolean m_boolBRAChanged; /** * This variable holds if any of the Ship From data changed */ private boolean m_boolShipFromChanged; /** * This variable holds if any of the Order data changed */ private boolean m_boolOrderChanged; /** * This variable holds if any of the Carrier data changed */ private boolean m_boolCarrierChanged; /** * This variable holds if any of the Ship Mode changed */ private boolean m_boolShipModeChanged; /** * This variable holds the Order seq Id */ private int m_iOrderSeqId; /** * Status of the Inbound Shipment. */ private String m_strShipmentStatus; /** * Commodity Code of the Shipment */ private String m_strCommodityCode; /** * Status of the inbound shipment */ private int m_iShpmtStatusCode; /** * Type of the inbound shipment */ private int m_iShpmtType; /** * Holds the task sequence id associated with the shipment */ private long m_lTaskSeqId; /** * Collection of order number/seq ids and order type code for * this shipment */ private OrderVO[] m_arrOrderDetails; /** * Flag to determine whether the BOL combination was validated */ private String m_strInvalidBOLCombination; /** * */ private Date m_dtScheduledTimeStamp; /** * Begin - Modified for defect 6090 by rohit jain on 05 dec 2005 */ /** * Old ShipmentSequence id used to change old shipments status to * cancelled for ASN downloaded shipment through create inbound shipment * link * @return */ private int m_iOldShipmentSequenceId; /** * End - Modified for defect 6090 by rohit jain on 05 dec 2005 */ /** * Begin - Modified for defect 5326 by rohit jain on 17 dec 2005 */ /** * It denotes the estimated arrival time of the shipment * @return */ private Date m_dtEstimaedArrivalTimeStamp; /** * End - Modified for defect 5326 by rohit jain on 17 dec 2005 */ /** * Returns the beerReturnNumbers. * @return ArrayList */ public ArrayList getBeerReturnNumbers() { return m_arrlstBeerReturnNumbers; } /** * Returns the inboundCommodityVO. * @return ArrayList */ public ArrayList getInboundCommodityDetailsVO() { return m_arrlstInboundCommodityDetailsVO; } /** * Returns the bOLChanged. * @return int */ public boolean getBOLChanged() { return m_boolBOLChanged; } /** * Returns the equipChanged. * @return int */ public boolean getEquipChanged() { return m_boolEquipChanged; } /** * Returns the isManual. * @return int */ public boolean getIsManual() { return m_boolIsManual; } /** * Returns the lineItemsChanged. * @return boolean */ public boolean getLineItemsChanged() { return m_boolLineItemsChanged; } /** * Returns the shipFromChanged. * @return int */ public boolean getShipFromChanged() { return m_boolShipFromChanged; } /** * Returns the bRAChanged. * @return int */ public boolean getBRAChanged() { return m_boolBRAChanged; } /** * Returns the Carrier changed * @return boolean */ public boolean getCarrierChanged() { return m_boolCarrierChanged; } /** * Returns the businessEntitySequenceId. * @return int */ public int getBusinessEntitySequenceId() { return m_iBusinessEntitySequenceId; } /** * Returns the orderSeqId. * @return int */ public int getOrderSeqId() { return m_iOrderSeqId; } /** * Returns the shipmentSequenceId. * @return int */ public int getShipmentSequenceId() { return m_iShipmentSequenceId; } /** * Returns the objEquipment. * @return int */ public EquipmentVO getObjEquipment() { return m_equipmentVO; } /** * Returns the orderChanged. * @return int */ public boolean getOrderChanged() { return m_boolOrderChanged; } /** * Returns the shipDataChanged. * @return int */ public boolean getShipModeChanged() { return m_boolShipModeChanged; } /** * Returns the bOLNumber. * @return String */ public String getBOLNumber() { if (m_strBOLNumber != null) { return m_strBOLNumber.trim(); } else { return null; } } /** * Returns the orderNumber. * @return String */ public String getOrderNumber() { if (m_strOrderNumber != null) { return m_strOrderNumber.trim(); } else { return null; } } /** * Returns the shipFrom. * @return String */ public String getShipFrom() { if (m_strShipFrom != null) { return m_strShipFrom.trim(); } else { return null; } } /** * Returns the shipFromName. * @return String */ public String getShipFromName() { if (m_strShipFromName != null) { return m_strShipFromName.trim(); } else { return null; } } /** * Returns the shipmentNumber. * @return String */ public String getShipmentNumber() { if (m_strShipmentNumber != null) { return m_strShipmentNumber.trim(); } else { return null; } } /** * Returns the shipmentStatus. * @return String */ public String getShipmentStatus() { if (m_strShipmentStatus != null) { return m_strShipmentStatus.trim(); } else { return null; } } /** * Returns the shipMode. * @return String */ public String getShipMode() { if (m_strShipMode != null) { return m_strShipMode.trim(); } else { return null; } } /** * Returns the shipType. * @return String */ public String getShipType() { if (m_strShipType != null) { return m_strShipType.trim(); } else { return null; } } /** * Begin - Modified for defect 6090 by rohit jain on 05 dec 2005 */ /** * gets the Old Shipment Sequence Id */ public int getOldShipmentSequenceId() { return m_iOldShipmentSequenceId; } /** * End - Modified for defect 6090 by rohit jain on 05 dec 2005 */ /** * Begin - Modified for defect 5326 by rohit jain on 17 dec 2005 */ /** * gets the Estimated Arrival Time of shipment */ public Date getEstimatedArrivalTimeStamp() { return m_dtEstimaedArrivalTimeStamp; } /** * End - Modified for defect 5326 by rohit jain on 17 dec 2005 */ /** * Sets the beerReturnNumbers. * @param beerReturnNumbers The beerReturnNumbers to set */ public void setBeerReturnNumbers(ArrayList beerReturnNumbers) { m_arrlstBeerReturnNumbers = beerReturnNumbers; } /** * Sets the inboundCommodityVO. * @param inboundCommodityVO The inboundCommodityVO to set */ public void setInboundCommodityVO(ArrayList inboundCommodityDetailsVO) { m_arrlstInboundCommodityDetailsVO = inboundCommodityDetailsVO; } /** * Sets the bOLChanged. * @param bOLChanged The bOLChanged to set */ public void setBOLChanged(boolean bolChanged) { m_boolBOLChanged = bolChanged; } /** * Sets the equipChanged. * @param equipChanged The equipChanged to set */ public void setEquipChanged(boolean equipChanged) { m_boolEquipChanged = equipChanged; } /** * Sets the isManual. * @param isManual The isManual to set */ public void setIsManual(boolean isManual) { m_boolIsManual = isManual; } /** * Sets the lineItemsChanged. * @param lineItemsChanged The lineItemsChanged to set */ public void setLineItemsChanged(boolean lineItemsChanged) { m_boolLineItemsChanged = lineItemsChanged; } /** * Sets the shipFromChanged. * @param shipFromChanged The shipFromChanged to set */ public void setShipFromChanged(boolean shipFromChanged) { m_boolShipFromChanged = shipFromChanged; } /** * Sets the bRAChanged. * @param bRAChanged The bRAChanged to set */ public void setBRAChanged(boolean bRAChanged) { m_boolBRAChanged = bRAChanged; } /** * Sets the Carrier Changed * @param carrierchanged */ public void setCarrierChanged(boolean carrierChanged) { m_boolCarrierChanged = carrierChanged; } /** * Sets the businessEntitySequenceId. * @param businessEntitySequenceId The businessEntitySequenceId to set */ public void setBusinessEntitySequenceId(int businessEntitySequenceId) { m_iBusinessEntitySequenceId = businessEntitySequenceId; } /** * Sets the orderSeqId. * @param orderSeqId The orderSeqId to set */ public void setOrderSeqId(int orderSeqId) { m_iOrderSeqId = orderSeqId; } /** * Sets the shipmentSequenceId. * @param shipmentSequenceId The shipmentSequenceId to set */ public void setShipmentSequenceId(int shipmentSequenceId) { m_iShipmentSequenceId = shipmentSequenceId; } /** * Sets the objEquipment. * @param objEquipment The objEquipment to set */ public void setObjEquipment(EquipmentVO objEquipment) { m_equipmentVO = objEquipment; } /** * Sets the orderChanged. * @param orderChanged The orderChanged to set */ public void setOrderChanged(boolean orderChanged) { m_boolOrderChanged = orderChanged; } /** * Sets the shipDataChanged. * @param shipDataChanged The shipDataChanged to set */ public void setShipModeChanged(boolean shipModeChanged) { m_boolShipModeChanged = shipModeChanged; } /** * Sets the bOLNumber. * @param bOLNumber The bOLNumber to set */ public void setBOLNumber(String bOLNumber) { m_strBOLNumber = (bOLNumber != null) ? bOLNumber.trim() : null; } /** * Sets the orderNumber. * @param orderNumber The orderNumber to set */ public void setOrderNumber(String orderNumber) { m_strOrderNumber = (orderNumber != null) ? orderNumber.trim() : null; } /** * Sets the shipFrom. * @param shipFrom The shipFrom to set */ public void setShipFrom(String shipFrom) { m_strShipFrom = (shipFrom != null) ? shipFrom.trim() : null; } /** * Sets the shipFromName. * @param shipFromName The shipFromName to set */ public void setShipFromName(String shipFromName) { m_strShipFromName = (shipFromName != null) ? shipFromName.trim() : null; } /** * Sets the shipmentNumber. * @param shipmentNumber The shipmentNumber to set */ public void setShipmentNumber(String shipmentNumber) { m_strShipmentNumber = (shipmentNumber != null) ? shipmentNumber.trim() : null; } /** * Sets the shipmentStatus. * @param shipmentStatus The shipmentStatus to set */ public void setShipmentStatus(String shipmentStatus) { m_strShipmentStatus = (shipmentStatus != null) ? shipmentStatus.trim() : null; } /** * Sets the shipMode. * @param shipMode The shipMode to set */ public void setShipMode(String shipMode) { m_strShipMode = (shipMode != null) ? shipMode.trim() : null; } /** * Sets the shipType. * @param shipType The shipType to set */ public void setShipType(String shipType) { m_strShipType = (shipType != null) ? shipType.trim() : null; } /** * Returns the commodityCode. * @return String */ public String getCommodityCode() { if (m_strCommodityCode != null) { return m_strCommodityCode.trim(); } else { return null; } } /** * Sets the commodityCode. * @param commodityCode The commodityCode to set */ public void setCommodityCode(String commodityCode) { m_strCommodityCode = (commodityCode != null) ? commodityCode.trim() : null; } /** * Returns the shipmentBOLSeqId. * @return int */ public int getShipmentBOLSeqId() { return m_iShipmentBOLSeqId; } /** * Sets the shipmentBOLSeqId. * @param shipmentBOLSeqId The shipmentBOLSeqId to set */ public void setShipmentBOLSeqId(int shipmentBOLSeqId) { m_iShipmentBOLSeqId = shipmentBOLSeqId; } /** * Returns the m_iShpmtStatusCode. * @return int */ public int getShpmtStatusCode() { return m_iShpmtStatusCode; } /** * Returns the m_iShpmtType. * @return int */ public int getShpmtType() { return m_iShpmtType; } /** * Sets the m_iShpmtStatusCode. * @param int - The m_iShpmtStatusCode to set */ public void setShpmtStatusCode(int m_iShpmtStatusCode) { this.m_iShpmtStatusCode = m_iShpmtStatusCode; } /** * Sets the m_iShpmtType. * @param int - The m_iShpmtType to set */ public void setShpmtType(int m_iShpmtType) { this.m_iShpmtType = m_iShpmtType; } /** * Returns the orderDetails. * @return OrderVO[] */ public OrderVO[] getOrderDetails() { return m_arrOrderDetails; } /** * Sets the orderDetails. * @param orderDetails The orderDetails to set */ public void setOrderDetails(OrderVO[] orderDetails) { m_arrOrderDetails = orderDetails; } /** * Returns the invalidBOLCombination. * @return String */ public String getInvalidBOLCombination() { return m_strInvalidBOLCombination; } /** * Sets the invalidBOLCombination. * @param invalidBOLCombination The invalidBOLCombination to set */ public void setInvalidBOLCombination(String invalidBOLCombination) { m_strInvalidBOLCombination = invalidBOLCombination; } /** * Returns the m_taskSeqId. * @return long */ public long getTaskSeqId() { return m_lTaskSeqId; } /** * Sets the m_lTaskSeqId. * @param lTaskSeqId The taskSeqId to set */ public void setTaskSeqId(long lTaskSeqId) { m_lTaskSeqId = lTaskSeqId; } /** * Returns the scheduledTimeStamp. * @return Date */ public Date getScheduledTimeStamp() { return m_dtScheduledTimeStamp; } /** * Sets the scheduledTimeStamp. * @param scheduledTimeStamp The scheduledTimeStamp to set */ public void setScheduledTimeStamp(Date dtScheduledTimeStamp) { m_dtScheduledTimeStamp = dtScheduledTimeStamp; } /** * Begin - Modified for defect 6090 by rohit jain on 05 dec 2005 */ /** * Sets the OldshipmentSequenceId. * @param shipmentSequenceId The shipmentSequenceId to set */ public void setOldShipmentSequenceId(int iOldshipmentSequenceId) { m_iOldShipmentSequenceId = iOldshipmentSequenceId; } /** * End - Modified for defect 6090 by rohit jain on 05 dec 2005 */ /** * Begin - Modified for defect 5326 by rohit jain on 17 dec 2005 */ /** * sets the Old Shipment Sequence Id */ public void setEstimatedArrivalTimeStamp(Date dtEstimatedArrivalTimeStamp) { m_dtEstimaedArrivalTimeStamp = dtEstimatedArrivalTimeStamp; } /** * End - Modified for defect 5326 by rohit jain on 17 dec 2005 */ }
UTF-8
Java
17,870
java
InboundShipmentVO.java
Java
[ { "context": " tries to save a new Inbound Shipment.\n * @author: Sarat Babu Remote Developer - Infosys\n * @author: Shrika", "end": 494, "score": 0.9998944997787476, "start": 484, "tag": "NAME", "value": "Sarat Babu" }, { "context": "at Babu Remote Developer - Infosys\n * @author: Shrikant_Patel Remote Developer - Infosys\n * @version: 1.0\n */\n\n", "end": 552, "score": 0.9981778264045715, "start": 538, "tag": "NAME", "value": "Shrikant_Patel" }, { "context": "; \n\t\n\t/**\n\t * Begin - Modified for defect 6090 by rohit jain on 05 dec 2005\n\t */\t\n\t\n\t/**\n\t * Old ShipmentSequ", "end": 5005, "score": 0.999673068523407, "start": 4995, "tag": "NAME", "value": "rohit jain" }, { "context": "eId; \n\n\t/**\n\t * End - Modified for defect 6090 by rohit jain on 05 dec 2005\n\t */\t\n\t\n\t/**\n\t * Begin - Modified", "end": 5301, "score": 0.9997196197509766, "start": 5291, "tag": "NAME", "value": "rohit jain" }, { "context": "/\t\n\t\n\t/**\n\t * Begin - Modified for defect 5326 by rohit jain on 17 dec 2005\n\t */\t\n\t\n\t/**\n\t * It denotes the e", "end": 5381, "score": 0.9995647668838501, "start": 5371, "tag": "NAME", "value": "rohit jain" }, { "context": "Stamp;\n\t/**\n\t * End - Modified for defect 5326 by rohit jain on 17 dec 2005\n\t */\t\t\t\t\n\t\t\n\t/**\n\t * Returns the b", "end": 5585, "score": 0.9997754096984863, "start": 5575, "tag": "NAME", "value": "rohit jain" }, { "context": " \n\n\t/**\n\t * Begin - Modified for defect 6090 by rohit jain on 05 dec 2005\n\t */\t\t\n\t\n\t/** \n\t * gets the Old Sh", "end": 9293, "score": 0.9997923970222473, "start": 9283, "tag": "NAME", "value": "rohit jain" }, { "context": "\n }\n\t/**\n\t * End - Modified for defect 6090 by rohit jain on 05 dec 2005\n\t */\t\t \n\t\n\t/**\n\t * Begin - Modi", "end": 9509, "score": 0.9997313022613525, "start": 9499, "tag": "NAME", "value": "rohit jain" }, { "context": " \n\t\n\t/**\n\t * Begin - Modified for defect 5326 by rohit jain on 17 dec 2005\n\t */\t\n\t\n\t/** \n\t * gets the Estimat", "end": 9593, "score": 0.9997992515563965, "start": 9583, "tag": "NAME", "value": "rohit jain" }, { "context": "p;\n\t}\t\n\t/**\n\t * End - Modified for defect 5326 by rohit jain on 17 dec 2005\n\t */\t\t\t \n\t\n\t/**\n\t * Sets the beerR", "end": 9822, "score": 0.9994593858718872, "start": 9812, "tag": "NAME", "value": "rohit jain" }, { "context": "\t}\n\n\n\t/**\n\t * Begin - Modified for defect 6090 by rohit jain on 05 dec 2005\n\t */\n\t\t\t\n\t/**\n\t * Sets the Oldship", "end": 17184, "score": 0.9998403787612915, "start": 17174, "tag": "NAME", "value": "rohit jain" }, { "context": "Id;\n\t}\n\t/**\n\t * End - Modified for defect 6090 by rohit jain on 05 dec 2005\n\t */\t\n\n\t/**\n\t * Begin - Modified ", "end": 17494, "score": 0.9998477697372437, "start": 17484, "tag": "NAME", "value": "rohit jain" }, { "context": "*/\t\n\n\t/**\n\t * Begin - Modified for defect 5326 by rohit jain on 17 dec 2005\n\t */\t\n\t\n\t/** \n\t * sets the Old Shi", "end": 17573, "score": 0.999847948551178, "start": 17563, "tag": "NAME", "value": "rohit jain" }, { "context": "mp;\n\t}\n\t/**\n\t * End - Modified for defect 5326 by rohit jain on 17 dec 2005\n\t */\t\t\n}", "end": 17846, "score": 0.9990501403808594, "start": 17836, "tag": "NAME", "value": "rohit jain" } ]
null
[]
/*** COPYRIGHT 2004 BY ANHEUSER-BUSCH. ALL RIGHTS RESERVED. ***/ package com.busch.wms.shipment.vo; import com.busch.wms.basefiles.vo.BaseVO; import com.busch.wms.basefiles.vo.EquipmentVO; import com.busch.wms.order.vo.OrderVO; import com.busch.wms.security.vo.UserProfileVO; import java.util.ArrayList; import java.util.Date; /** * This VO holds the details of a particular Inbound Shipment. This would be used * when the user tries to save a new Inbound Shipment. * @author: <NAME> Remote Developer - Infosys * @author: Shrikant_Patel Remote Developer - Infosys * @version: 1.0 */ public class InboundShipmentVO extends BaseVO { /** * Constructor for InboundShipmentVO. */ public InboundShipmentVO() { } /** * Constructor for InboundShipmentVO. * @param user */ public InboundShipmentVO(UserProfileVO user) { super(user); } /** * This variable holds the Ship Mode. */ private String m_strShipMode; /** * This holds the shipment sequence Id. */ private int m_iShipmentSequenceId; /** * This variable holds the Shipment Number. */ private String m_strShipmentNumber; /** * This variable holds the shipment bol seq id */ private int m_iShipmentBOLSeqId; /** * This variable holds the BOL Number. */ private String m_strBOLNumber; /** * This variable holds the Order Number. */ private String m_strOrderNumber; /** * This variable holds the Ship Type. */ private String m_strShipType; /** * This variable holds the Ship From code/number. */ private String m_strShipFrom; /** * This variable holds the Ship From name/description. */ private String m_strShipFromName; /** * This variable holds the business entity sequence id of the * Ship From place */ private int m_iBusinessEntitySequenceId; /** * This variable holds the arraylist of InboundCommodityVO. */ private ArrayList m_arrlstInboundCommodityDetailsVO; /** * In case of Beer Returns or Beer Returns/Trade Returns, this varaible holds the * BRA numbes linked to the shipment. In case of any other shipment types, this * shall be null. */ private ArrayList m_arrlstBeerReturnNumbers; /** * This variable holds information whether shipment is manualy created shipment */ private boolean m_boolIsManual; /** * This contains the equipment number, its seq id, carrier code, whether the * equipment is at door, whether the inbound comm in it is unknown. */ private EquipmentVO m_equipmentVO; /** * This varaible is true - If equipment data is changed. Else false. This is used * when the user is updating the information. Only if it changes then * 1. Linking to shipment * 2. Delinking of old equipment * 3. Check of whether the equipment is at door with inbound commodity 'unknown' * and kicking off the calculate commodity will be done. */ private boolean m_boolEquipChanged; /** * This is used when the user is updating the information. This variable holds * information whether 1. BOL 2. Order #. 3. Ship From location changed. If yes * then it is true else false. Only if this is true we shall again check whether * this is an unique combination. */ private boolean m_boolBOLChanged; /** * This is used when the user is updating the information. It is set to true if * the line item quantity changes. Based on this we shall kick off the calculate * commodity again. */ private boolean m_boolLineItemsChanged; /** * This is used when the user is updating the information. This is set to true if * the BRA numbers change. Based on this it is decided if we have to link the new * BRAs and delink the old BRAs. */ private boolean m_boolBRAChanged; /** * This variable holds if any of the Ship From data changed */ private boolean m_boolShipFromChanged; /** * This variable holds if any of the Order data changed */ private boolean m_boolOrderChanged; /** * This variable holds if any of the Carrier data changed */ private boolean m_boolCarrierChanged; /** * This variable holds if any of the Ship Mode changed */ private boolean m_boolShipModeChanged; /** * This variable holds the Order seq Id */ private int m_iOrderSeqId; /** * Status of the Inbound Shipment. */ private String m_strShipmentStatus; /** * Commodity Code of the Shipment */ private String m_strCommodityCode; /** * Status of the inbound shipment */ private int m_iShpmtStatusCode; /** * Type of the inbound shipment */ private int m_iShpmtType; /** * Holds the task sequence id associated with the shipment */ private long m_lTaskSeqId; /** * Collection of order number/seq ids and order type code for * this shipment */ private OrderVO[] m_arrOrderDetails; /** * Flag to determine whether the BOL combination was validated */ private String m_strInvalidBOLCombination; /** * */ private Date m_dtScheduledTimeStamp; /** * Begin - Modified for defect 6090 by <NAME> on 05 dec 2005 */ /** * Old ShipmentSequence id used to change old shipments status to * cancelled for ASN downloaded shipment through create inbound shipment * link * @return */ private int m_iOldShipmentSequenceId; /** * End - Modified for defect 6090 by <NAME> on 05 dec 2005 */ /** * Begin - Modified for defect 5326 by <NAME> on 17 dec 2005 */ /** * It denotes the estimated arrival time of the shipment * @return */ private Date m_dtEstimaedArrivalTimeStamp; /** * End - Modified for defect 5326 by <NAME> on 17 dec 2005 */ /** * Returns the beerReturnNumbers. * @return ArrayList */ public ArrayList getBeerReturnNumbers() { return m_arrlstBeerReturnNumbers; } /** * Returns the inboundCommodityVO. * @return ArrayList */ public ArrayList getInboundCommodityDetailsVO() { return m_arrlstInboundCommodityDetailsVO; } /** * Returns the bOLChanged. * @return int */ public boolean getBOLChanged() { return m_boolBOLChanged; } /** * Returns the equipChanged. * @return int */ public boolean getEquipChanged() { return m_boolEquipChanged; } /** * Returns the isManual. * @return int */ public boolean getIsManual() { return m_boolIsManual; } /** * Returns the lineItemsChanged. * @return boolean */ public boolean getLineItemsChanged() { return m_boolLineItemsChanged; } /** * Returns the shipFromChanged. * @return int */ public boolean getShipFromChanged() { return m_boolShipFromChanged; } /** * Returns the bRAChanged. * @return int */ public boolean getBRAChanged() { return m_boolBRAChanged; } /** * Returns the Carrier changed * @return boolean */ public boolean getCarrierChanged() { return m_boolCarrierChanged; } /** * Returns the businessEntitySequenceId. * @return int */ public int getBusinessEntitySequenceId() { return m_iBusinessEntitySequenceId; } /** * Returns the orderSeqId. * @return int */ public int getOrderSeqId() { return m_iOrderSeqId; } /** * Returns the shipmentSequenceId. * @return int */ public int getShipmentSequenceId() { return m_iShipmentSequenceId; } /** * Returns the objEquipment. * @return int */ public EquipmentVO getObjEquipment() { return m_equipmentVO; } /** * Returns the orderChanged. * @return int */ public boolean getOrderChanged() { return m_boolOrderChanged; } /** * Returns the shipDataChanged. * @return int */ public boolean getShipModeChanged() { return m_boolShipModeChanged; } /** * Returns the bOLNumber. * @return String */ public String getBOLNumber() { if (m_strBOLNumber != null) { return m_strBOLNumber.trim(); } else { return null; } } /** * Returns the orderNumber. * @return String */ public String getOrderNumber() { if (m_strOrderNumber != null) { return m_strOrderNumber.trim(); } else { return null; } } /** * Returns the shipFrom. * @return String */ public String getShipFrom() { if (m_strShipFrom != null) { return m_strShipFrom.trim(); } else { return null; } } /** * Returns the shipFromName. * @return String */ public String getShipFromName() { if (m_strShipFromName != null) { return m_strShipFromName.trim(); } else { return null; } } /** * Returns the shipmentNumber. * @return String */ public String getShipmentNumber() { if (m_strShipmentNumber != null) { return m_strShipmentNumber.trim(); } else { return null; } } /** * Returns the shipmentStatus. * @return String */ public String getShipmentStatus() { if (m_strShipmentStatus != null) { return m_strShipmentStatus.trim(); } else { return null; } } /** * Returns the shipMode. * @return String */ public String getShipMode() { if (m_strShipMode != null) { return m_strShipMode.trim(); } else { return null; } } /** * Returns the shipType. * @return String */ public String getShipType() { if (m_strShipType != null) { return m_strShipType.trim(); } else { return null; } } /** * Begin - Modified for defect 6090 by <NAME> on 05 dec 2005 */ /** * gets the Old Shipment Sequence Id */ public int getOldShipmentSequenceId() { return m_iOldShipmentSequenceId; } /** * End - Modified for defect 6090 by <NAME> on 05 dec 2005 */ /** * Begin - Modified for defect 5326 by <NAME> on 17 dec 2005 */ /** * gets the Estimated Arrival Time of shipment */ public Date getEstimatedArrivalTimeStamp() { return m_dtEstimaedArrivalTimeStamp; } /** * End - Modified for defect 5326 by <NAME> on 17 dec 2005 */ /** * Sets the beerReturnNumbers. * @param beerReturnNumbers The beerReturnNumbers to set */ public void setBeerReturnNumbers(ArrayList beerReturnNumbers) { m_arrlstBeerReturnNumbers = beerReturnNumbers; } /** * Sets the inboundCommodityVO. * @param inboundCommodityVO The inboundCommodityVO to set */ public void setInboundCommodityVO(ArrayList inboundCommodityDetailsVO) { m_arrlstInboundCommodityDetailsVO = inboundCommodityDetailsVO; } /** * Sets the bOLChanged. * @param bOLChanged The bOLChanged to set */ public void setBOLChanged(boolean bolChanged) { m_boolBOLChanged = bolChanged; } /** * Sets the equipChanged. * @param equipChanged The equipChanged to set */ public void setEquipChanged(boolean equipChanged) { m_boolEquipChanged = equipChanged; } /** * Sets the isManual. * @param isManual The isManual to set */ public void setIsManual(boolean isManual) { m_boolIsManual = isManual; } /** * Sets the lineItemsChanged. * @param lineItemsChanged The lineItemsChanged to set */ public void setLineItemsChanged(boolean lineItemsChanged) { m_boolLineItemsChanged = lineItemsChanged; } /** * Sets the shipFromChanged. * @param shipFromChanged The shipFromChanged to set */ public void setShipFromChanged(boolean shipFromChanged) { m_boolShipFromChanged = shipFromChanged; } /** * Sets the bRAChanged. * @param bRAChanged The bRAChanged to set */ public void setBRAChanged(boolean bRAChanged) { m_boolBRAChanged = bRAChanged; } /** * Sets the Carrier Changed * @param carrierchanged */ public void setCarrierChanged(boolean carrierChanged) { m_boolCarrierChanged = carrierChanged; } /** * Sets the businessEntitySequenceId. * @param businessEntitySequenceId The businessEntitySequenceId to set */ public void setBusinessEntitySequenceId(int businessEntitySequenceId) { m_iBusinessEntitySequenceId = businessEntitySequenceId; } /** * Sets the orderSeqId. * @param orderSeqId The orderSeqId to set */ public void setOrderSeqId(int orderSeqId) { m_iOrderSeqId = orderSeqId; } /** * Sets the shipmentSequenceId. * @param shipmentSequenceId The shipmentSequenceId to set */ public void setShipmentSequenceId(int shipmentSequenceId) { m_iShipmentSequenceId = shipmentSequenceId; } /** * Sets the objEquipment. * @param objEquipment The objEquipment to set */ public void setObjEquipment(EquipmentVO objEquipment) { m_equipmentVO = objEquipment; } /** * Sets the orderChanged. * @param orderChanged The orderChanged to set */ public void setOrderChanged(boolean orderChanged) { m_boolOrderChanged = orderChanged; } /** * Sets the shipDataChanged. * @param shipDataChanged The shipDataChanged to set */ public void setShipModeChanged(boolean shipModeChanged) { m_boolShipModeChanged = shipModeChanged; } /** * Sets the bOLNumber. * @param bOLNumber The bOLNumber to set */ public void setBOLNumber(String bOLNumber) { m_strBOLNumber = (bOLNumber != null) ? bOLNumber.trim() : null; } /** * Sets the orderNumber. * @param orderNumber The orderNumber to set */ public void setOrderNumber(String orderNumber) { m_strOrderNumber = (orderNumber != null) ? orderNumber.trim() : null; } /** * Sets the shipFrom. * @param shipFrom The shipFrom to set */ public void setShipFrom(String shipFrom) { m_strShipFrom = (shipFrom != null) ? shipFrom.trim() : null; } /** * Sets the shipFromName. * @param shipFromName The shipFromName to set */ public void setShipFromName(String shipFromName) { m_strShipFromName = (shipFromName != null) ? shipFromName.trim() : null; } /** * Sets the shipmentNumber. * @param shipmentNumber The shipmentNumber to set */ public void setShipmentNumber(String shipmentNumber) { m_strShipmentNumber = (shipmentNumber != null) ? shipmentNumber.trim() : null; } /** * Sets the shipmentStatus. * @param shipmentStatus The shipmentStatus to set */ public void setShipmentStatus(String shipmentStatus) { m_strShipmentStatus = (shipmentStatus != null) ? shipmentStatus.trim() : null; } /** * Sets the shipMode. * @param shipMode The shipMode to set */ public void setShipMode(String shipMode) { m_strShipMode = (shipMode != null) ? shipMode.trim() : null; } /** * Sets the shipType. * @param shipType The shipType to set */ public void setShipType(String shipType) { m_strShipType = (shipType != null) ? shipType.trim() : null; } /** * Returns the commodityCode. * @return String */ public String getCommodityCode() { if (m_strCommodityCode != null) { return m_strCommodityCode.trim(); } else { return null; } } /** * Sets the commodityCode. * @param commodityCode The commodityCode to set */ public void setCommodityCode(String commodityCode) { m_strCommodityCode = (commodityCode != null) ? commodityCode.trim() : null; } /** * Returns the shipmentBOLSeqId. * @return int */ public int getShipmentBOLSeqId() { return m_iShipmentBOLSeqId; } /** * Sets the shipmentBOLSeqId. * @param shipmentBOLSeqId The shipmentBOLSeqId to set */ public void setShipmentBOLSeqId(int shipmentBOLSeqId) { m_iShipmentBOLSeqId = shipmentBOLSeqId; } /** * Returns the m_iShpmtStatusCode. * @return int */ public int getShpmtStatusCode() { return m_iShpmtStatusCode; } /** * Returns the m_iShpmtType. * @return int */ public int getShpmtType() { return m_iShpmtType; } /** * Sets the m_iShpmtStatusCode. * @param int - The m_iShpmtStatusCode to set */ public void setShpmtStatusCode(int m_iShpmtStatusCode) { this.m_iShpmtStatusCode = m_iShpmtStatusCode; } /** * Sets the m_iShpmtType. * @param int - The m_iShpmtType to set */ public void setShpmtType(int m_iShpmtType) { this.m_iShpmtType = m_iShpmtType; } /** * Returns the orderDetails. * @return OrderVO[] */ public OrderVO[] getOrderDetails() { return m_arrOrderDetails; } /** * Sets the orderDetails. * @param orderDetails The orderDetails to set */ public void setOrderDetails(OrderVO[] orderDetails) { m_arrOrderDetails = orderDetails; } /** * Returns the invalidBOLCombination. * @return String */ public String getInvalidBOLCombination() { return m_strInvalidBOLCombination; } /** * Sets the invalidBOLCombination. * @param invalidBOLCombination The invalidBOLCombination to set */ public void setInvalidBOLCombination(String invalidBOLCombination) { m_strInvalidBOLCombination = invalidBOLCombination; } /** * Returns the m_taskSeqId. * @return long */ public long getTaskSeqId() { return m_lTaskSeqId; } /** * Sets the m_lTaskSeqId. * @param lTaskSeqId The taskSeqId to set */ public void setTaskSeqId(long lTaskSeqId) { m_lTaskSeqId = lTaskSeqId; } /** * Returns the scheduledTimeStamp. * @return Date */ public Date getScheduledTimeStamp() { return m_dtScheduledTimeStamp; } /** * Sets the scheduledTimeStamp. * @param scheduledTimeStamp The scheduledTimeStamp to set */ public void setScheduledTimeStamp(Date dtScheduledTimeStamp) { m_dtScheduledTimeStamp = dtScheduledTimeStamp; } /** * Begin - Modified for defect 6090 by <NAME> on 05 dec 2005 */ /** * Sets the OldshipmentSequenceId. * @param shipmentSequenceId The shipmentSequenceId to set */ public void setOldShipmentSequenceId(int iOldshipmentSequenceId) { m_iOldShipmentSequenceId = iOldshipmentSequenceId; } /** * End - Modified for defect 6090 by <NAME> on 05 dec 2005 */ /** * Begin - Modified for defect 5326 by <NAME> on 17 dec 2005 */ /** * sets the Old Shipment Sequence Id */ public void setEstimatedArrivalTimeStamp(Date dtEstimatedArrivalTimeStamp) { m_dtEstimaedArrivalTimeStamp = dtEstimatedArrivalTimeStamp; } /** * End - Modified for defect 5326 by <NAME> on 17 dec 2005 */ }
17,818
0.68601
0.678623
949
17.831402
20.850338
82
false
false
0
0
0
0
0
0
1.173867
false
false
12
910d9483d05761604d12e67597538057052e9a76
11,957,189,016,309
2e1330438e1f7d2a437aaad3cafcb985843754b9
/yimao/yimao-water/src/main/java/com/yimao/cloud/water/processor/ExportProcessor.java
e56644b5503f0b676abf7e793a76bf78ed62c7e5
[]
no_license
bellmit/self
https://github.com/bellmit/self
b693b43a9d89c0a18d360a43a2ba88adb4b2a6d9
2eb0a199b4f21a4e339f17ebdedcc9f40a5e39ab
refs/heads/master
2022-11-16T04:35:21.503000
2020-07-13T07:15:32
2020-07-13T07:15:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yimao.cloud.water.processor; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.yimao.cloud.base.constant.Constant; import com.yimao.cloud.base.constant.ExportUrlConstant; import com.yimao.cloud.base.constant.RabbitConstant; import com.yimao.cloud.base.enums.ExportRecordStatus; import com.yimao.cloud.base.exception.YimaoException; import com.yimao.cloud.base.properties.DomainProperties; import com.yimao.cloud.base.utils.ExcelUtil; import com.yimao.cloud.base.utils.SFTPUtil; import com.yimao.cloud.base.utils.StringUtil; import com.yimao.cloud.framework.cache.RedisCache; import com.yimao.cloud.pojo.dto.system.ExportRecordDTO; import com.yimao.cloud.pojo.dto.water.WaterDeviceFilterChangeRecordExportDTO; import com.yimao.cloud.pojo.dto.water.WaterDeviceFilterChangeRecordQueryDTO; import com.yimao.cloud.pojo.export.water.DeviceListExport; import com.yimao.cloud.pojo.export.water.DeviceReplaceRecordExport; import com.yimao.cloud.pojo.export.water.FilterReplaceExport; import com.yimao.cloud.pojo.export.water.ManualPadCostExport; import com.yimao.cloud.pojo.query.water.ManualPadCostQuery; import com.yimao.cloud.pojo.query.water.WaterDeviceQuery; import com.yimao.cloud.pojo.query.water.WaterDeviceReplaceRecordQuery; import com.yimao.cloud.water.mapper.ManualPadCostMapper; import com.yimao.cloud.water.mapper.WaterDeviceFilterChangeRecordMapper; import com.yimao.cloud.water.mapper.WaterDeviceMapper; import com.yimao.cloud.water.mapper.WaterDeviceReplaceRecordMapper; import lombok.extern.slf4j.Slf4j; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 描述:导出 * * @Author Zhang Bo * @Date 2019/11/25 */ @Component @Slf4j public class ExportProcessor { private static ExecutorService executor = Executors.newFixedThreadPool(3); private static final DecimalFormat decimalFormat = new DecimalFormat("#0.00"); private static final int pageSize = 500; @Resource private DomainProperties domainProperties; @Resource private RabbitTemplate rabbitTemplate; @Resource private RedisCache redisCache; @Resource private WaterDeviceReplaceRecordMapper waterDeviceReplaceRecordMapper; @Resource private WaterDeviceFilterChangeRecordMapper waterDeviceFilterChangeRecordMapper; @Resource private ManualPadCostMapper manualPadCostMapper; @Resource private WaterDeviceMapper waterDeviceMapper; /** * 导出 */ @RabbitListener(queues = RabbitConstant.EXPORT_ACTION_WATER) @RabbitHandler public void processor(final Map<String, Object> map) { executor.submit(() -> { ExportRecordDTO record = (ExportRecordDTO) map.get("exportRecordDTO"); String url = record.getUrl(); Integer recordId = record.getId(); Integer adminId = record.getAdminId(); // 导出中 record.setStatus(ExportRecordStatus.IN_EXPORT.value); record.setStatusName(ExportRecordStatus.IN_EXPORT.name); rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, 0); SXSSFWorkbook workbook = null; try { String[] titles; String[] beanProperties; // url区分是哪项导出 switch (url) { case "/waterdevice/replacerecord/export": WaterDeviceReplaceRecordQuery query = (WaterDeviceReplaceRecordQuery) map.get("query"); List<DeviceReplaceRecordExport> list = this.waterDeviceReplaceRecordExport(query, adminId, recordId); titles = new String[]{"新SN码", "新ICCID", "新生产批次号", "旧SN码", "旧ICCID", "旧生产批次号", "操作人", "添加时间"}; beanProperties = new String[]{"newSn", "newIccid", "newBatchCode", "oldSn", "oldIccid", "oldBatchCode", "creator", "createTime"}; // 导出成功 this.exportSuccessful(record, titles, beanProperties, list); break; case "/waterdevice/filterReplace/export": titles = new String[]{"SN码", "滤芯名", "省份", "城市", "地区", "更换时间", "设备添加时间"}; beanProperties = new String[]{"sn", "filterName", "province", "city", "region", "createTime", "activatingTime"}; WaterDeviceQuery queryPrams = (WaterDeviceQuery) map.get("query"); workbook = filterReplaceExport(queryPrams, adminId, recordId, titles, beanProperties); // 导出成功 this.uploadExportData(record, workbook); break; case "/padcost/export": ManualPadCostQuery manualPadCostQuery = (ManualPadCostQuery) map.get("query"); List<ManualPadCostExport> manualPadCostExportList = manualPadCostExport(manualPadCostQuery, adminId, recordId); titles = new String[]{"SN码", "余额", "已使用流量", "是否开启", "同步时间", "同步状态", "同步失败原因", "创建时间"}; beanProperties = new String[]{"sn", "balance", "discharge", "open", "syncTime", "syncStatus", "syncFailReason", "createTime"}; // 导出成功 this.exportSuccessful(record, titles, beanProperties, manualPadCostExportList); break; case ExportUrlConstant.EXPORT_FILTERCHANGERECORD_URL: WaterDeviceFilterChangeRecordQueryDTO filterChangeRecordQuery = (WaterDeviceFilterChangeRecordQueryDTO) map .get("query"); List<WaterDeviceFilterChangeRecordExportDTO> changeRecordExportList = waterDeviceFilterChangeRecordExport( filterChangeRecordQuery, adminId, recordId); beanProperties = new String[]{"maintenanceWorkOrderId", "province", "city", "region", "address", "filterName", "consumerName", "consumerPhone", "deviceBatchCode", "deviceModelName", "deviceSncode", "sourceTxt", "effectiveTxt", "createTimeTxt", "activatingTime", "deviceScope", "deviceSimcard"}; titles = new String[]{"维护工单号", "省", "市", "区", "详细地址", "滤芯类型", "客户姓名", "客户电话", "批次码", "设备类型", "SN码", "来源", "是否有效", "更换时间", "设备激活时间", "产品范围", "设备ICCID"}; // 导出成功 this.exportSuccessful(record, titles, beanProperties, changeRecordExportList); break; case "/waterdevice/list/export": titles = new String[]{"SN码", "批次码", "计费方式", "省份", "城市", "地区", "经销商登录名", "经销商姓名", "用户姓名", "用户手机号", "客服姓名", "客服手机号", "型号", "激活时间", "SIM卡号", "最后时间", "是否在线", "金额", "时长", "流量", "版本号", "是否更换计费方式", "当前计费方式", "sim卡运营商", "网络状态"}; beanProperties = new String[]{"sn", "logisticsCode", "costName", "province", "city", "region", "distributorName", "distributorRealName", "deviceUserName", "deviceUserPhone", "engineerName", "engineerPhone", "deviceModel", "snEntryTime", "iccid", "lastOnlineTime", "online", "money", "currentTotalTime", "currentTotalFlow", "version", "costChanged", "costType", "simCompany", "connectionType"}; // 导出成功 WaterDeviceQuery deviceQuery = (WaterDeviceQuery) map.get("query"); workbook = this.waterDeviceListExport(deviceQuery, adminId, recordId, titles, beanProperties); this.uploadExportData(record, workbook); break; } } catch (Exception e) { // 导出失败 record.setStatus(ExportRecordStatus.FAILURE.value); record.setStatusName(ExportRecordStatus.FAILURE.name); if (e instanceof YimaoException) { record.setReason(e.getMessage()); } else { record.setReason("导出失败"); } rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); } }); } /** * 更新导出记录 */ private void exportSuccessful(ExportRecordDTO record, String[] titles, String[] beanProperties, List list) { String path = ExcelUtil.exportToFtp(list, record.getTitle(), titles.length - 1, titles, beanProperties); if (StringUtil.isEmpty(path)) { throw new YimaoException("上传导出数据到FTP服务器发生异常"); } String downloadLink = domainProperties.getImage() + path; // 导出成功 record.setStatus(ExportRecordStatus.SUCCESSFUL.value); record.setStatusName(ExportRecordStatus.SUCCESSFUL.name); record.setDownloadLink(downloadLink); rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); } private SXSSFWorkbook filterReplaceExport(WaterDeviceQuery query, Integer adminId, Integer recordId, String[] titles, String[] beanProperties) { try { DecimalFormat df = new DecimalFormat("#0.00"); int pageNum = 1; Page<FilterReplaceExport> page = null; String title = "滤芯更换导出"; SXSSFWorkbook workbook = null; String activatingTime = ""; boolean isFistBatch; int pages = 0; int size = 5000; List<String> ids = new ArrayList<>(); log.info("============滤芯更换导出开始=============="); boolean flag = true; while (flag) { if (pageNum == 1) { query.setPageSize(null); PageHelper.startPage(pageNum, size); page = waterDeviceMapper.filterReplaceExport(query); isFistBatch = true; pages = page.getPages(); } else { query.setPageSize(size); query.setActivatingTime(activatingTime); page = waterDeviceMapper.filterReplaceExport(query); isFistBatch = false; } if (page == null || page.getResult().isEmpty() || pageNum > pages + 1) { flag = false; break; } workbook = ExcelUtil.generateWorkBook(workbook, distinctFilterReplaceData(page.getResult(), ids), title, titles.length - 1, titles, beanProperties, isFistBatch); if (page != null && !page.getResult().isEmpty() && page.getResult().size() > 0) { activatingTime = page.getResult().get(page.getResult().size() - 1).getActivatingTime(); } if (pageNum < pages) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / pages * 100)); } pageNum++; } log.info("============滤芯更换导出结束=============="); return workbook; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List<ManualPadCostExport> manualPadCostExport(ManualPadCostQuery query, Integer adminId, Integer recordId) { try { DecimalFormat df = new DecimalFormat("#0.00"); List<ManualPadCostExport> list = new ArrayList<>(); int pageNum = 1; Page<ManualPadCostExport> page = null; while (pageNum == 1 || page.getPages() >= pageNum) { PageHelper.startPage(pageNum, pageSize); page = manualPadCostMapper.export(query); list.addAll(page.getResult()); if (pageNum < page.getPages()) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / page.getPages() * 100)); } pageNum++; } log.info("本次导出共查询" + list.size() + "条数据"); return list; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List<DeviceReplaceRecordExport> waterDeviceReplaceRecordExport(WaterDeviceReplaceRecordQuery query, Integer adminId, Integer recordId) { try { DecimalFormat df = new DecimalFormat("#0.00"); List<DeviceReplaceRecordExport> list = new ArrayList<>(); int pageNum = 1; Page<DeviceReplaceRecordExport> page = null; while (pageNum == 1 || page.getPages() >= pageNum) { PageHelper.startPage(pageNum, pageSize); page = waterDeviceReplaceRecordMapper.export(query); list.addAll(page.getResult()); if (pageNum < page.getPages()) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / page.getPages() * 100)); } pageNum++; } log.info("本次导出共查询" + list.size() + "条数据"); return list; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List<WaterDeviceFilterChangeRecordExportDTO> waterDeviceFilterChangeRecordExport( WaterDeviceFilterChangeRecordQueryDTO query, Integer adminId, Integer recordId) { try { DecimalFormat df = new DecimalFormat("#0.00"); List<WaterDeviceFilterChangeRecordExportDTO> list = new ArrayList<>(); int pageNum = 1; Page<WaterDeviceFilterChangeRecordExportDTO> page = null; while (pageNum == 1 || page.getPages() >= pageNum) { PageHelper.startPage(pageNum, pageSize); page = waterDeviceFilterChangeRecordMapper.waterDeviceFilterChangeRecordExport(query); list.addAll(page.getResult()); if (pageNum < page.getPages()) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / page.getPages() * 100)); } pageNum++; } log.info("本次导出共查询" + list.size() + "条数据"); return list; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private SXSSFWorkbook waterDeviceListExport(WaterDeviceQuery deviceQuery, Integer adminId, Integer recordId, String[] titles, String[] beanProperties) { try { int pageNum = 1; int pages = 0; int pageSize = 5000; Page<DeviceListExport> page = null; String createTime = null; String title = "设备列表"; SXSSFWorkbook workbook = null; boolean isFistBatch; List<Long> ids = new ArrayList<>(); while (true) { if (pageNum == 1) { isFistBatch = true; deviceQuery.setPageSize(null); PageHelper.startPage(pageNum, pageSize); page = waterDeviceMapper.waterDeviceListExport(deviceQuery); pages = page.getPages(); } else { isFistBatch = false; deviceQuery.setPageSize(pageSize); deviceQuery.setCreateTime(createTime); page = waterDeviceMapper.waterDeviceListExport(deviceQuery); } if (page == null || page.getResult().isEmpty() || pageNum > pages + 1) { break; } workbook = ExcelUtil.generateWorkBook(workbook, distinctDeviceId(page.getResult(), ids), title, titles.length - 1, titles, beanProperties, isFistBatch); createTime = page.getResult().get(page.getResult().size() - 1).getCreateTime(); if (pageNum < pages) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, decimalFormat.format((double) pageNum / pages * 100)); } pageNum++; } return workbook; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List distinctDeviceId(List<DeviceListExport> result, List<Long> ids) { if (ids.isEmpty()) { for (DeviceListExport device : result) { ids.add(device.getId()); } return result; } List<DeviceListExport> datas = new ArrayList<>(); for (DeviceListExport device : result) { if (!ids.contains(device.getId())) { datas.add(device); } } ids.clear(); for (DeviceListExport device : result) { ids.add(device.getId()); } return datas; } /*** * 上传导出文件并更新导出状态 * * @param record * @param workbook */ private void uploadExportData(ExportRecordDTO record, SXSSFWorkbook workbook) { try { if(workbook==null){ throw new YimaoException("导出的数据不能为空"); } String path = SFTPUtil.upload(workbook, record.getTitle()); if (StringUtil.isEmpty(path)) { throw new YimaoException("上传导出数据到FTP服务器发生异常"); } String downloadLink = domainProperties.getImage() + path; // 导出成功 record.setStatus(ExportRecordStatus.SUCCESSFUL.value); record.setStatusName(ExportRecordStatus.SUCCESSFUL.name); record.setDownloadLink(downloadLink); rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); } catch (Exception e) { throw new YimaoException("导出的数据不能为空"); } } /** * 去重 * * @param result * @return */ private List distinctFilterReplaceData(List<FilterReplaceExport> result, List<String> ids) { if (ids.isEmpty()) { for (FilterReplaceExport filterReplace : result) { ids.add(getkeys(filterReplace)); } return result; } List<FilterReplaceExport> datas = new ArrayList<>(); for (FilterReplaceExport filterReplace : result) { if (!ids.contains(getkeys(filterReplace))) { datas.add(filterReplace); } } ids.clear(); for (FilterReplaceExport filterReplace : result) { ids.add(getkeys(filterReplace)); } return datas; } /**** * * @param filterReplace * @return */ private String getkeys(FilterReplaceExport filterReplace) { StringBuffer sb = new StringBuffer(); return sb.append(filterReplace.getSn()).append("-").append(filterReplace.getFilterName()).append("-") .append(filterReplace.getCreateTime()).toString(); } }
UTF-8
Java
21,147
java
ExportProcessor.java
Java
[ { "context": ".concurrent.Executors;\n\n/**\n * 描述:导出\n *\n * @Author Zhang Bo\n * @Date 2019/11/25\n */\n@Component\n@Slf4j\npublic ", "end": 2116, "score": 0.999455451965332, "start": 2108, "tag": "NAME", "value": "Zhang Bo" } ]
null
[]
package com.yimao.cloud.water.processor; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.yimao.cloud.base.constant.Constant; import com.yimao.cloud.base.constant.ExportUrlConstant; import com.yimao.cloud.base.constant.RabbitConstant; import com.yimao.cloud.base.enums.ExportRecordStatus; import com.yimao.cloud.base.exception.YimaoException; import com.yimao.cloud.base.properties.DomainProperties; import com.yimao.cloud.base.utils.ExcelUtil; import com.yimao.cloud.base.utils.SFTPUtil; import com.yimao.cloud.base.utils.StringUtil; import com.yimao.cloud.framework.cache.RedisCache; import com.yimao.cloud.pojo.dto.system.ExportRecordDTO; import com.yimao.cloud.pojo.dto.water.WaterDeviceFilterChangeRecordExportDTO; import com.yimao.cloud.pojo.dto.water.WaterDeviceFilterChangeRecordQueryDTO; import com.yimao.cloud.pojo.export.water.DeviceListExport; import com.yimao.cloud.pojo.export.water.DeviceReplaceRecordExport; import com.yimao.cloud.pojo.export.water.FilterReplaceExport; import com.yimao.cloud.pojo.export.water.ManualPadCostExport; import com.yimao.cloud.pojo.query.water.ManualPadCostQuery; import com.yimao.cloud.pojo.query.water.WaterDeviceQuery; import com.yimao.cloud.pojo.query.water.WaterDeviceReplaceRecordQuery; import com.yimao.cloud.water.mapper.ManualPadCostMapper; import com.yimao.cloud.water.mapper.WaterDeviceFilterChangeRecordMapper; import com.yimao.cloud.water.mapper.WaterDeviceMapper; import com.yimao.cloud.water.mapper.WaterDeviceReplaceRecordMapper; import lombok.extern.slf4j.Slf4j; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 描述:导出 * * @Author <NAME> * @Date 2019/11/25 */ @Component @Slf4j public class ExportProcessor { private static ExecutorService executor = Executors.newFixedThreadPool(3); private static final DecimalFormat decimalFormat = new DecimalFormat("#0.00"); private static final int pageSize = 500; @Resource private DomainProperties domainProperties; @Resource private RabbitTemplate rabbitTemplate; @Resource private RedisCache redisCache; @Resource private WaterDeviceReplaceRecordMapper waterDeviceReplaceRecordMapper; @Resource private WaterDeviceFilterChangeRecordMapper waterDeviceFilterChangeRecordMapper; @Resource private ManualPadCostMapper manualPadCostMapper; @Resource private WaterDeviceMapper waterDeviceMapper; /** * 导出 */ @RabbitListener(queues = RabbitConstant.EXPORT_ACTION_WATER) @RabbitHandler public void processor(final Map<String, Object> map) { executor.submit(() -> { ExportRecordDTO record = (ExportRecordDTO) map.get("exportRecordDTO"); String url = record.getUrl(); Integer recordId = record.getId(); Integer adminId = record.getAdminId(); // 导出中 record.setStatus(ExportRecordStatus.IN_EXPORT.value); record.setStatusName(ExportRecordStatus.IN_EXPORT.name); rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, 0); SXSSFWorkbook workbook = null; try { String[] titles; String[] beanProperties; // url区分是哪项导出 switch (url) { case "/waterdevice/replacerecord/export": WaterDeviceReplaceRecordQuery query = (WaterDeviceReplaceRecordQuery) map.get("query"); List<DeviceReplaceRecordExport> list = this.waterDeviceReplaceRecordExport(query, adminId, recordId); titles = new String[]{"新SN码", "新ICCID", "新生产批次号", "旧SN码", "旧ICCID", "旧生产批次号", "操作人", "添加时间"}; beanProperties = new String[]{"newSn", "newIccid", "newBatchCode", "oldSn", "oldIccid", "oldBatchCode", "creator", "createTime"}; // 导出成功 this.exportSuccessful(record, titles, beanProperties, list); break; case "/waterdevice/filterReplace/export": titles = new String[]{"SN码", "滤芯名", "省份", "城市", "地区", "更换时间", "设备添加时间"}; beanProperties = new String[]{"sn", "filterName", "province", "city", "region", "createTime", "activatingTime"}; WaterDeviceQuery queryPrams = (WaterDeviceQuery) map.get("query"); workbook = filterReplaceExport(queryPrams, adminId, recordId, titles, beanProperties); // 导出成功 this.uploadExportData(record, workbook); break; case "/padcost/export": ManualPadCostQuery manualPadCostQuery = (ManualPadCostQuery) map.get("query"); List<ManualPadCostExport> manualPadCostExportList = manualPadCostExport(manualPadCostQuery, adminId, recordId); titles = new String[]{"SN码", "余额", "已使用流量", "是否开启", "同步时间", "同步状态", "同步失败原因", "创建时间"}; beanProperties = new String[]{"sn", "balance", "discharge", "open", "syncTime", "syncStatus", "syncFailReason", "createTime"}; // 导出成功 this.exportSuccessful(record, titles, beanProperties, manualPadCostExportList); break; case ExportUrlConstant.EXPORT_FILTERCHANGERECORD_URL: WaterDeviceFilterChangeRecordQueryDTO filterChangeRecordQuery = (WaterDeviceFilterChangeRecordQueryDTO) map .get("query"); List<WaterDeviceFilterChangeRecordExportDTO> changeRecordExportList = waterDeviceFilterChangeRecordExport( filterChangeRecordQuery, adminId, recordId); beanProperties = new String[]{"maintenanceWorkOrderId", "province", "city", "region", "address", "filterName", "consumerName", "consumerPhone", "deviceBatchCode", "deviceModelName", "deviceSncode", "sourceTxt", "effectiveTxt", "createTimeTxt", "activatingTime", "deviceScope", "deviceSimcard"}; titles = new String[]{"维护工单号", "省", "市", "区", "详细地址", "滤芯类型", "客户姓名", "客户电话", "批次码", "设备类型", "SN码", "来源", "是否有效", "更换时间", "设备激活时间", "产品范围", "设备ICCID"}; // 导出成功 this.exportSuccessful(record, titles, beanProperties, changeRecordExportList); break; case "/waterdevice/list/export": titles = new String[]{"SN码", "批次码", "计费方式", "省份", "城市", "地区", "经销商登录名", "经销商姓名", "用户姓名", "用户手机号", "客服姓名", "客服手机号", "型号", "激活时间", "SIM卡号", "最后时间", "是否在线", "金额", "时长", "流量", "版本号", "是否更换计费方式", "当前计费方式", "sim卡运营商", "网络状态"}; beanProperties = new String[]{"sn", "logisticsCode", "costName", "province", "city", "region", "distributorName", "distributorRealName", "deviceUserName", "deviceUserPhone", "engineerName", "engineerPhone", "deviceModel", "snEntryTime", "iccid", "lastOnlineTime", "online", "money", "currentTotalTime", "currentTotalFlow", "version", "costChanged", "costType", "simCompany", "connectionType"}; // 导出成功 WaterDeviceQuery deviceQuery = (WaterDeviceQuery) map.get("query"); workbook = this.waterDeviceListExport(deviceQuery, adminId, recordId, titles, beanProperties); this.uploadExportData(record, workbook); break; } } catch (Exception e) { // 导出失败 record.setStatus(ExportRecordStatus.FAILURE.value); record.setStatusName(ExportRecordStatus.FAILURE.name); if (e instanceof YimaoException) { record.setReason(e.getMessage()); } else { record.setReason("导出失败"); } rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); } }); } /** * 更新导出记录 */ private void exportSuccessful(ExportRecordDTO record, String[] titles, String[] beanProperties, List list) { String path = ExcelUtil.exportToFtp(list, record.getTitle(), titles.length - 1, titles, beanProperties); if (StringUtil.isEmpty(path)) { throw new YimaoException("上传导出数据到FTP服务器发生异常"); } String downloadLink = domainProperties.getImage() + path; // 导出成功 record.setStatus(ExportRecordStatus.SUCCESSFUL.value); record.setStatusName(ExportRecordStatus.SUCCESSFUL.name); record.setDownloadLink(downloadLink); rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); } private SXSSFWorkbook filterReplaceExport(WaterDeviceQuery query, Integer adminId, Integer recordId, String[] titles, String[] beanProperties) { try { DecimalFormat df = new DecimalFormat("#0.00"); int pageNum = 1; Page<FilterReplaceExport> page = null; String title = "滤芯更换导出"; SXSSFWorkbook workbook = null; String activatingTime = ""; boolean isFistBatch; int pages = 0; int size = 5000; List<String> ids = new ArrayList<>(); log.info("============滤芯更换导出开始=============="); boolean flag = true; while (flag) { if (pageNum == 1) { query.setPageSize(null); PageHelper.startPage(pageNum, size); page = waterDeviceMapper.filterReplaceExport(query); isFistBatch = true; pages = page.getPages(); } else { query.setPageSize(size); query.setActivatingTime(activatingTime); page = waterDeviceMapper.filterReplaceExport(query); isFistBatch = false; } if (page == null || page.getResult().isEmpty() || pageNum > pages + 1) { flag = false; break; } workbook = ExcelUtil.generateWorkBook(workbook, distinctFilterReplaceData(page.getResult(), ids), title, titles.length - 1, titles, beanProperties, isFistBatch); if (page != null && !page.getResult().isEmpty() && page.getResult().size() > 0) { activatingTime = page.getResult().get(page.getResult().size() - 1).getActivatingTime(); } if (pageNum < pages) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / pages * 100)); } pageNum++; } log.info("============滤芯更换导出结束=============="); return workbook; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List<ManualPadCostExport> manualPadCostExport(ManualPadCostQuery query, Integer adminId, Integer recordId) { try { DecimalFormat df = new DecimalFormat("#0.00"); List<ManualPadCostExport> list = new ArrayList<>(); int pageNum = 1; Page<ManualPadCostExport> page = null; while (pageNum == 1 || page.getPages() >= pageNum) { PageHelper.startPage(pageNum, pageSize); page = manualPadCostMapper.export(query); list.addAll(page.getResult()); if (pageNum < page.getPages()) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / page.getPages() * 100)); } pageNum++; } log.info("本次导出共查询" + list.size() + "条数据"); return list; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List<DeviceReplaceRecordExport> waterDeviceReplaceRecordExport(WaterDeviceReplaceRecordQuery query, Integer adminId, Integer recordId) { try { DecimalFormat df = new DecimalFormat("#0.00"); List<DeviceReplaceRecordExport> list = new ArrayList<>(); int pageNum = 1; Page<DeviceReplaceRecordExport> page = null; while (pageNum == 1 || page.getPages() >= pageNum) { PageHelper.startPage(pageNum, pageSize); page = waterDeviceReplaceRecordMapper.export(query); list.addAll(page.getResult()); if (pageNum < page.getPages()) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / page.getPages() * 100)); } pageNum++; } log.info("本次导出共查询" + list.size() + "条数据"); return list; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List<WaterDeviceFilterChangeRecordExportDTO> waterDeviceFilterChangeRecordExport( WaterDeviceFilterChangeRecordQueryDTO query, Integer adminId, Integer recordId) { try { DecimalFormat df = new DecimalFormat("#0.00"); List<WaterDeviceFilterChangeRecordExportDTO> list = new ArrayList<>(); int pageNum = 1; Page<WaterDeviceFilterChangeRecordExportDTO> page = null; while (pageNum == 1 || page.getPages() >= pageNum) { PageHelper.startPage(pageNum, pageSize); page = waterDeviceFilterChangeRecordMapper.waterDeviceFilterChangeRecordExport(query); list.addAll(page.getResult()); if (pageNum < page.getPages()) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, df.format((double) pageNum / page.getPages() * 100)); } pageNum++; } log.info("本次导出共查询" + list.size() + "条数据"); return list; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private SXSSFWorkbook waterDeviceListExport(WaterDeviceQuery deviceQuery, Integer adminId, Integer recordId, String[] titles, String[] beanProperties) { try { int pageNum = 1; int pages = 0; int pageSize = 5000; Page<DeviceListExport> page = null; String createTime = null; String title = "设备列表"; SXSSFWorkbook workbook = null; boolean isFistBatch; List<Long> ids = new ArrayList<>(); while (true) { if (pageNum == 1) { isFistBatch = true; deviceQuery.setPageSize(null); PageHelper.startPage(pageNum, pageSize); page = waterDeviceMapper.waterDeviceListExport(deviceQuery); pages = page.getPages(); } else { isFistBatch = false; deviceQuery.setPageSize(pageSize); deviceQuery.setCreateTime(createTime); page = waterDeviceMapper.waterDeviceListExport(deviceQuery); } if (page == null || page.getResult().isEmpty() || pageNum > pages + 1) { break; } workbook = ExcelUtil.generateWorkBook(workbook, distinctDeviceId(page.getResult(), ids), title, titles.length - 1, titles, beanProperties, isFistBatch); createTime = page.getResult().get(page.getResult().size() - 1).getCreateTime(); if (pageNum < pages) { // 设置下载进度 redisCache.set(Constant.EXPORT_PROGRESS + adminId + "_" + recordId, decimalFormat.format((double) pageNum / pages * 100)); } pageNum++; } return workbook; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } private List distinctDeviceId(List<DeviceListExport> result, List<Long> ids) { if (ids.isEmpty()) { for (DeviceListExport device : result) { ids.add(device.getId()); } return result; } List<DeviceListExport> datas = new ArrayList<>(); for (DeviceListExport device : result) { if (!ids.contains(device.getId())) { datas.add(device); } } ids.clear(); for (DeviceListExport device : result) { ids.add(device.getId()); } return datas; } /*** * 上传导出文件并更新导出状态 * * @param record * @param workbook */ private void uploadExportData(ExportRecordDTO record, SXSSFWorkbook workbook) { try { if(workbook==null){ throw new YimaoException("导出的数据不能为空"); } String path = SFTPUtil.upload(workbook, record.getTitle()); if (StringUtil.isEmpty(path)) { throw new YimaoException("上传导出数据到FTP服务器发生异常"); } String downloadLink = domainProperties.getImage() + path; // 导出成功 record.setStatus(ExportRecordStatus.SUCCESSFUL.value); record.setStatusName(ExportRecordStatus.SUCCESSFUL.name); record.setDownloadLink(downloadLink); rabbitTemplate.convertAndSend(RabbitConstant.EXPORT_RECORD, record); } catch (Exception e) { throw new YimaoException("导出的数据不能为空"); } } /** * 去重 * * @param result * @return */ private List distinctFilterReplaceData(List<FilterReplaceExport> result, List<String> ids) { if (ids.isEmpty()) { for (FilterReplaceExport filterReplace : result) { ids.add(getkeys(filterReplace)); } return result; } List<FilterReplaceExport> datas = new ArrayList<>(); for (FilterReplaceExport filterReplace : result) { if (!ids.contains(getkeys(filterReplace))) { datas.add(filterReplace); } } ids.clear(); for (FilterReplaceExport filterReplace : result) { ids.add(getkeys(filterReplace)); } return datas; } /**** * * @param filterReplace * @return */ private String getkeys(FilterReplaceExport filterReplace) { StringBuffer sb = new StringBuffer(); return sb.append(filterReplace.getSn()).append("-").append(filterReplace.getFilterName()).append("-") .append(filterReplace.getCreateTime()).toString(); } }
21,145
0.564161
0.560513
445
44.58427
33.04604
168
false
false
0
0
0
0
0
0
1.008989
false
false
12
86fda414b753364e3e84dabdb0a97b3cf8cc06be
13,563,506,789,626
d1fa28fe015ee60c9b954b8b4a165178024ed488
/src/com/how2java/test/MyBatisTest.java
fb892e4c252cc5e7dbe5b7536f588bc48f3aa655
[]
no_license
xiyuxiaonan/LoginDemo
https://github.com/xiyuxiaonan/LoginDemo
d1e13bfecc64c57249f1c30dfa6abf192e5532eb
7aaf1e2389eb4f451481ac21ee6a28ba0b3fa04e
refs/heads/master
2020-04-26T01:59:45.422000
2019-03-01T02:46:17
2019-03-01T02:46:17
173,221,575
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.how2java.test; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.how2java.mapper.UserMapper; import com.how2java.pojo.Admin; import com.how2java.pojo.User; import com.how2java.service.AdminService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class MyBatisTest { @Autowired private UserMapper userMapper; @Autowired private AdminService adminService; //@Test public void testAdd() { for (int i = 0; i < 100; i++) { User user = new User(); user.setName("new User"); user.setPassword("123456"); userMapper.add(user); } } //@Test public void testSelect() { List<User> us=userMapper.select(); for (User u : us) { System.out.println(u.getName()); } } @Test public void testSelsetAdmin() { Admin ad=adminService.validate_Admin("1"); System.out.println(ad.getPassword()); } }
UTF-8
Java
1,229
java
MyBatisTest.java
Java
[ { "context": "User user = new User();\n user.setName(\"new User\");\n user.setPassword(\"123456\");\n ", "end": 832, "score": 0.9547862410545349, "start": 824, "tag": "USERNAME", "value": "new User" }, { "context": "etName(\"new User\");\n user.setPassword(\"123456\");\n userMapper.add(user);\n }\n \n", "end": 872, "score": 0.9992042183876038, "start": 866, "tag": "PASSWORD", "value": "123456" } ]
null
[]
package com.how2java.test; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.how2java.mapper.UserMapper; import com.how2java.pojo.Admin; import com.how2java.pojo.User; import com.how2java.service.AdminService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class MyBatisTest { @Autowired private UserMapper userMapper; @Autowired private AdminService adminService; //@Test public void testAdd() { for (int i = 0; i < 100; i++) { User user = new User(); user.setName("new User"); user.setPassword("<PASSWORD>"); userMapper.add(user); } } //@Test public void testSelect() { List<User> us=userMapper.select(); for (User u : us) { System.out.println(u.getName()); } } @Test public void testSelsetAdmin() { Admin ad=adminService.validate_Admin("1"); System.out.println(ad.getPassword()); } }
1,233
0.68511
0.66965
47
25.170214
18.483252
71
false
false
0
0
0
0
0
0
0.553191
false
false
12
696015c5aac55c07e93f1e38923c7d2e36885570
17,549,236,434,906
59a0b91ca384945544ad89e0b63c5ca462ce5c91
/app/src/main/java/com/example/gardener/adapters/FavouriteAdapter.java
43f46c45d235e2bf18c31ac0bf7f8854d02ad076
[]
no_license
epetrashko/Gardener
https://github.com/epetrashko/Gardener
e2efbc98abe755a4c3e1fb9c453dd2e7d13a83a4
c854613be74a81f965e4c53d6d5b8c3bd11ba9c1
refs/heads/master
2023-04-28T10:49:23.162000
2021-05-26T14:00:34
2021-05-26T14:00:34
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.gardener.adapters; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.RecyclerView; import com.example.gardener.Const; import com.example.gardener.FavouritePlant; import com.example.gardener.R; import com.example.gardener.fragments.InfoFavouriteFragment; import java.util.ArrayList; public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.FavouriteHolder> { private ArrayList<FavouritePlant> array; private SQLiteDatabase db; private FragmentActivity activity; public FavouriteAdapter(ArrayList<FavouritePlant> array, SQLiteDatabase db, FragmentActivity activity){ this.array = array; this.db = db; this.activity = activity; } @NonNull @Override public FavouriteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new FavouriteHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.plant_card_item, parent, false)); } @Override public void onBindViewHolder(@NonNull final FavouriteHolder holder, final int position) { final FavouritePlant temp = array.get(position); holder.back.setBackgroundResource(temp.img_id); holder.name.setText(temp.name); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int temp_id = array.get(position).id; Cursor fav = db.query(Const.TABLE_PLANT_ITEMS, null, Const.ITEMS_ID + "= '" + temp_id + "'", null, null, null, null); fav.moveToFirst(); Bundle bundle = new Bundle(); bundle.putInt(Const.ITEMS_ID, temp_id); bundle.putInt("image", temp.img_id); if (fav.isAfterLast()){ bundle.putString(Const.ITEMS_COND, "ERROR"); bundle.putString(Const.ITEMS_DESC, "ERROR"); bundle.putString(Const.ITEMS_CARE, "ERROR"); }else{ String desc = fav.getString(1); String cond = fav.getString(2); String care = fav.getString(3); bundle.putString(Const.ITEMS_COND, cond); bundle.putString(Const.ITEMS_DESC, desc); bundle.putString(Const.ITEMS_CARE, care); } InfoFavouriteFragment fragment = new InfoFavouriteFragment(db); fragment.setArguments(bundle); activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit(); } }); } @Override public int getItemCount() { return array.size(); } public class FavouriteHolder extends RecyclerView.ViewHolder { LinearLayout back; TextView name; public FavouriteHolder(@NonNull View itemView) { super(itemView); back = itemView.findViewById(R.id.plant_card_back); name = itemView.findViewById(R.id.plant_name); } } }
UTF-8
Java
3,404
java
FavouriteAdapter.java
Java
[]
null
[]
package com.example.gardener.adapters; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.RecyclerView; import com.example.gardener.Const; import com.example.gardener.FavouritePlant; import com.example.gardener.R; import com.example.gardener.fragments.InfoFavouriteFragment; import java.util.ArrayList; public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.FavouriteHolder> { private ArrayList<FavouritePlant> array; private SQLiteDatabase db; private FragmentActivity activity; public FavouriteAdapter(ArrayList<FavouritePlant> array, SQLiteDatabase db, FragmentActivity activity){ this.array = array; this.db = db; this.activity = activity; } @NonNull @Override public FavouriteHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new FavouriteHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.plant_card_item, parent, false)); } @Override public void onBindViewHolder(@NonNull final FavouriteHolder holder, final int position) { final FavouritePlant temp = array.get(position); holder.back.setBackgroundResource(temp.img_id); holder.name.setText(temp.name); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int temp_id = array.get(position).id; Cursor fav = db.query(Const.TABLE_PLANT_ITEMS, null, Const.ITEMS_ID + "= '" + temp_id + "'", null, null, null, null); fav.moveToFirst(); Bundle bundle = new Bundle(); bundle.putInt(Const.ITEMS_ID, temp_id); bundle.putInt("image", temp.img_id); if (fav.isAfterLast()){ bundle.putString(Const.ITEMS_COND, "ERROR"); bundle.putString(Const.ITEMS_DESC, "ERROR"); bundle.putString(Const.ITEMS_CARE, "ERROR"); }else{ String desc = fav.getString(1); String cond = fav.getString(2); String care = fav.getString(3); bundle.putString(Const.ITEMS_COND, cond); bundle.putString(Const.ITEMS_DESC, desc); bundle.putString(Const.ITEMS_CARE, care); } InfoFavouriteFragment fragment = new InfoFavouriteFragment(db); fragment.setArguments(bundle); activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit(); } }); } @Override public int getItemCount() { return array.size(); } public class FavouriteHolder extends RecyclerView.ViewHolder { LinearLayout back; TextView name; public FavouriteHolder(@NonNull View itemView) { super(itemView); back = itemView.findViewById(R.id.plant_card_back); name = itemView.findViewById(R.id.plant_name); } } }
3,404
0.64953
0.648649
85
39.047058
29.65484
133
false
false
0
0
0
0
0
0
0.858824
false
false
12
f0e7c9895126a3060b1e3762e4d354265c2841f1
4,483,945,922,711
36dfaeb426605db6bbc094f88020510805d1e3ba
/showcase-quartz/src/main/java/samlen/tsoi/showcase/quartz/job/UserJob.java
22f1e81e394ff5d70a5ca63232caaebf2b1ccd7e
[]
no_license
SamlenTsoi/showcase
https://github.com/SamlenTsoi/showcase
213a7bb69cc4a57e7e1f92f8c37a4507e5281fe5
80089e102ff2a667b4bb53e08a975cdf962024be
refs/heads/master
2022-07-01T01:15:57.370000
2020-04-28T08:09:41
2020-04-28T08:09:41
112,805,517
5
3
null
false
2022-06-20T23:31:21
2017-12-02T02:19:30
2021-01-25T08:16:48
2022-06-20T23:31:21
382
4
1
6
Java
false
false
package samlen.tsoi.showcase.quartz.job; import com.google.common.base.Stopwatch; import lombok.extern.slf4j.Slf4j; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * 用户任务 * * @author samlen_tsoi * @date 2018/3/7 */ @Slf4j @Component public class UserJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info("用户定时任务开始"); Stopwatch stopwatch = Stopwatch.createStarted(); //任务执行具体内容忽略 //。。。 stopwatch.stop(); log.info("用户定时任务结束,共花费 :{}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }
UTF-8
Java
850
java
UserJob.java
Java
[ { "context": "il.concurrent.TimeUnit;\n\n/**\n * 用户任务\n *\n * @author samlen_tsoi\n * @date 2018/3/7\n */\n@Slf4j\n@Component\npublic cl", "end": 346, "score": 0.9994942545890808, "start": 335, "tag": "USERNAME", "value": "samlen_tsoi" } ]
null
[]
package samlen.tsoi.showcase.quartz.job; import com.google.common.base.Stopwatch; import lombok.extern.slf4j.Slf4j; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * 用户任务 * * @author samlen_tsoi * @date 2018/3/7 */ @Slf4j @Component public class UserJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { log.info("用户定时任务开始"); Stopwatch stopwatch = Stopwatch.createStarted(); //任务执行具体内容忽略 //。。。 stopwatch.stop(); log.info("用户定时任务结束,共花费 :{}ms", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } }
850
0.72093
0.709302
31
23.967741
23.405931
95
false
false
0
0
0
0
0
0
0.419355
false
false
12
731eb9a6a3fe27e9dc781ce070ab97ac54970e11
6,743,098,680,314
edeb15e4b75a33fae5f24bd2213f09eff503675f
/src/com/arstron/am/Shared/AccountInfo.java
ee309d6b250579cfbb4fc230ca2411c924f60b1c
[]
no_license
RaviPanchal/expense_manager
https://github.com/RaviPanchal/expense_manager
eb4f07c9b294ad32151dd1bf04ec6b89f4330f79
28f08a493926a8acb8f68fb0dc3974f8c70e7301
refs/heads/master
2020-07-20T15:58:57.961000
2014-06-21T06:04:15
2014-06-21T06:04:15
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.arstron.am.Shared; public class AccountInfo { private long id = 0; private String accName = "Select Account", accCurrency = "", dateFormat = ""; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getAccName() { return accName; } public void setAccName(String accName) { this.accName = accName; } public String getAccCurrency() { return accCurrency; } public void setAccCurrency(String accCurrency) { this.accCurrency = accCurrency; } public String getDateFormat() { return dateFormat; } public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } @Override public String toString() { return accName; } }
UTF-8
Java
728
java
AccountInfo.java
Java
[]
null
[]
package com.arstron.am.Shared; public class AccountInfo { private long id = 0; private String accName = "Select Account", accCurrency = "", dateFormat = ""; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getAccName() { return accName; } public void setAccName(String accName) { this.accName = accName; } public String getAccCurrency() { return accCurrency; } public void setAccCurrency(String accCurrency) { this.accCurrency = accCurrency; } public String getDateFormat() { return dateFormat; } public void setDateFormat(String dateFormat) { this.dateFormat = dateFormat; } @Override public String toString() { return accName; } }
728
0.697802
0.696429
44
15.545455
17.42967
78
false
false
0
0
0
0
0
0
1.204545
false
false
12
ef7e99242b49f74dafc38123c11e0f89232563fa
33,423,435,525,253
5c1b99b34424231f6aeff9150404a7ef6dad8165
/Android-DownloadManager-sample/src/info/tongrenlu/android/downloadmanager/sample/DownloadTaskAdapter.java
d5cdac6ca6432a25c15df9452a3234cd8ec5d261
[ "Unlicense" ]
permissive
wdxzs1985/Android-DownloadManager
https://github.com/wdxzs1985/Android-DownloadManager
c17ee5befc2d01765297025600199548cd5990cb
dd173bcdb7b4cde16302a149249fd7a5a7651c75
refs/heads/master
2021-03-12T20:27:32.807000
2014-05-09T09:29:31
2014-05-09T09:29:31
16,571,693
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package info.tongrenlu.android.downloadmanager.sample; import info.tongrenlu.android.downloadmanager.BaseDownloadTaskAdapter; import info.tongrenlu.android.downloadmanager.DownloadListener; import info.tongrenlu.android.downloadmanager.DownloadManager; import info.tongrenlu.android.downloadmanager.DownloadTask; import info.tongrenlu.android.downloadmanager.DownloadTaskInfo; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; public class DownloadTaskAdapter extends BaseDownloadTaskAdapter { public DownloadTaskAdapter(DownloadManager downloadManager) { super(downloadManager); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; ViewHolder holder = null; final Context context = parent.getContext(); if (view == null) { view = View.inflate(context, R.layout.list_item, null); holder = new ViewHolder(); holder.parent = view; holder.icon = (ImageView) view.findViewById(android.R.id.icon); holder.text1 = (TextView) view.findViewById(android.R.id.text1); holder.text2 = (TextView) view.findViewById(android.R.id.text2); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } DownloadTask task = this.getItem(position); holder.bind(task); holder.update(task.getTaskinfo()); return view; } public class ViewHolder implements DownloadListener { public View parent; public ImageView icon; public TextView text1; public TextView text2; public DownloadTask task; public void bind(DownloadTask task) { if (this.task != null) { task.unregisterListener(this); } this.task = task; task.registerListener(this); } public void update(DownloadTaskInfo taskinfo) { this.icon.setImageDrawable(null); this.text1.setText(taskinfo.getFrom()); switch (this.task.getStatus()) { case PENDING: this.text2.setText("PENDING"); break; case RUNNING: if (this.task.isCancelled()) { this.text2.setText("RUNNING && canceled"); } else if (taskinfo.getProgress() < 100) { this.text2.setText(String.format("%d%% (%d / %d)", taskinfo.getProgress(), taskinfo.getRead(), taskinfo.getTotal())); } else if (taskinfo.getProgress() == 100) { String path = taskinfo.getTo(); Drawable background = BitmapDrawable.createFromPath(path); this.icon.setImageDrawable(background); this.text2.setText(""); } break; case FINISHED: if (taskinfo.getProgress() == 100) { String path = taskinfo.getTo(); Drawable background = BitmapDrawable.createFromPath(path); this.icon.setImageDrawable(background); this.text2.setText(""); } else { this.text2.setText("FINISHED && canceled"); } break; default: break; } } @Override public void onDownloadStart(DownloadTaskInfo taskinfo) { this.update(taskinfo); } @Override public void onDownloadCancel(DownloadTaskInfo taskinfo) { this.update(taskinfo); } @Override public void onDownloadFinish(DownloadTaskInfo taskinfo) { this.update(taskinfo); } @Override public void onDownloadProgressUpdate(DownloadTaskInfo taskinfo) { this.update(taskinfo); } } }
UTF-8
Java
4,399
java
DownloadTaskAdapter.java
Java
[]
null
[]
package info.tongrenlu.android.downloadmanager.sample; import info.tongrenlu.android.downloadmanager.BaseDownloadTaskAdapter; import info.tongrenlu.android.downloadmanager.DownloadListener; import info.tongrenlu.android.downloadmanager.DownloadManager; import info.tongrenlu.android.downloadmanager.DownloadTask; import info.tongrenlu.android.downloadmanager.DownloadTaskInfo; import android.content.Context; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; public class DownloadTaskAdapter extends BaseDownloadTaskAdapter { public DownloadTaskAdapter(DownloadManager downloadManager) { super(downloadManager); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; ViewHolder holder = null; final Context context = parent.getContext(); if (view == null) { view = View.inflate(context, R.layout.list_item, null); holder = new ViewHolder(); holder.parent = view; holder.icon = (ImageView) view.findViewById(android.R.id.icon); holder.text1 = (TextView) view.findViewById(android.R.id.text1); holder.text2 = (TextView) view.findViewById(android.R.id.text2); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } DownloadTask task = this.getItem(position); holder.bind(task); holder.update(task.getTaskinfo()); return view; } public class ViewHolder implements DownloadListener { public View parent; public ImageView icon; public TextView text1; public TextView text2; public DownloadTask task; public void bind(DownloadTask task) { if (this.task != null) { task.unregisterListener(this); } this.task = task; task.registerListener(this); } public void update(DownloadTaskInfo taskinfo) { this.icon.setImageDrawable(null); this.text1.setText(taskinfo.getFrom()); switch (this.task.getStatus()) { case PENDING: this.text2.setText("PENDING"); break; case RUNNING: if (this.task.isCancelled()) { this.text2.setText("RUNNING && canceled"); } else if (taskinfo.getProgress() < 100) { this.text2.setText(String.format("%d%% (%d / %d)", taskinfo.getProgress(), taskinfo.getRead(), taskinfo.getTotal())); } else if (taskinfo.getProgress() == 100) { String path = taskinfo.getTo(); Drawable background = BitmapDrawable.createFromPath(path); this.icon.setImageDrawable(background); this.text2.setText(""); } break; case FINISHED: if (taskinfo.getProgress() == 100) { String path = taskinfo.getTo(); Drawable background = BitmapDrawable.createFromPath(path); this.icon.setImageDrawable(background); this.text2.setText(""); } else { this.text2.setText("FINISHED && canceled"); } break; default: break; } } @Override public void onDownloadStart(DownloadTaskInfo taskinfo) { this.update(taskinfo); } @Override public void onDownloadCancel(DownloadTaskInfo taskinfo) { this.update(taskinfo); } @Override public void onDownloadFinish(DownloadTaskInfo taskinfo) { this.update(taskinfo); } @Override public void onDownloadProgressUpdate(DownloadTaskInfo taskinfo) { this.update(taskinfo); } } }
4,399
0.556035
0.551034
119
34.966385
23.661098
78
false
false
0
0
0
0
0
0
0.554622
false
false
12
4f8c2cdc138e8d7b0f508b5f7fde662deb694b7e
25,701,084,328,839
58c00bf811d02379aef98b6da0bdc7ff27728145
/JAVA/src/matera/jooq/tables/pojos/Zona.java
8626377d0e8e1b2525a0afe532e9d6cb295bcdbf
[]
no_license
tinchogava/Matera
https://github.com/tinchogava/Matera
9e39ad2deb5da7f61be6854e54afb49c933fc87a
63b0f60c65af0293d6384837d03116d588996370
refs/heads/master
2021-05-05T22:30:17.306000
2018-01-03T16:06:00
2018-01-03T16:06:00
116,151,161
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * This class is generated by jOOQ */ package matera.jooq.tables.pojos; import java.io.Serializable; import javax.annotation.Generated; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.7.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) @Entity @Table(name = "zona", schema = "matera") public class Zona implements Serializable { private static final long serialVersionUID = -38672312; private Integer idZona; private String nombre; private String habilita; public Zona() {} public Zona(Zona value) { this.idZona = value.idZona; this.nombre = value.nombre; this.habilita = value.habilita; } public Zona( Integer idZona, String nombre, String habilita ) { this.idZona = idZona; this.nombre = nombre; this.habilita = habilita; } @Id @Column(name = "id_zona", unique = true, nullable = false, precision = 10) public Integer getIdZona() { return this.idZona; } public void setIdZona(Integer idZona) { this.idZona = idZona; } @Column(name = "nombre", nullable = false, length = 45) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name = "habilita", nullable = false, length = 1) public String getHabilita() { return this.habilita; } public void setHabilita(String habilita) { this.habilita = habilita; } @Override public String toString() { StringBuilder sb = new StringBuilder("Zona ("); sb.append(idZona); sb.append(", ").append(nombre); sb.append(", ").append(habilita); sb.append(")"); return sb.toString(); } }
UTF-8
Java
1,830
java
Zona.java
Java
[]
null
[]
/** * This class is generated by jOOQ */ package matera.jooq.tables.pojos; import java.io.Serializable; import javax.annotation.Generated; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.7.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) @Entity @Table(name = "zona", schema = "matera") public class Zona implements Serializable { private static final long serialVersionUID = -38672312; private Integer idZona; private String nombre; private String habilita; public Zona() {} public Zona(Zona value) { this.idZona = value.idZona; this.nombre = value.nombre; this.habilita = value.habilita; } public Zona( Integer idZona, String nombre, String habilita ) { this.idZona = idZona; this.nombre = nombre; this.habilita = habilita; } @Id @Column(name = "id_zona", unique = true, nullable = false, precision = 10) public Integer getIdZona() { return this.idZona; } public void setIdZona(Integer idZona) { this.idZona = idZona; } @Column(name = "nombre", nullable = false, length = 45) public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } @Column(name = "habilita", nullable = false, length = 1) public String getHabilita() { return this.habilita; } public void setHabilita(String habilita) { this.habilita = habilita; } @Override public String toString() { StringBuilder sb = new StringBuilder("Zona ("); sb.append(idZona); sb.append(", ").append(nombre); sb.append(", ").append(habilita); sb.append(")"); return sb.toString(); } }
1,830
0.688525
0.679781
94
18.468084
17.226095
75
false
false
0
0
0
0
0
0
1.308511
false
false
12
182870ec33f331292fe626d0980196008d865d8a
10,110,353,048,037
8cc08af9657e76995b539fee6bb19e58ec41e711
/acquire/annotations-persistence/src/main/java/edu/bcm/dldcc/big/clinical/entity/NaLabAnnotation.java
17c19dce47c744a48fd7eb8abbdcf8a616749f96
[]
no_license
colima/Acquire
https://github.com/colima/Acquire
5c0158c2be957721c24d6e7b9eec28617720324f
a86aa8eb16711d76ecae00b792eaf9b159f97374
refs/heads/master
2020-12-01T13:08:12.859000
2014-07-09T17:31:00
2014-07-09T17:31:00
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.bcm.dldcc.big.clinical.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.validation.constraints.DecimalMax; import javax.validation.constraints.DecimalMin; import org.hibernate.envers.Audited; import edu.bcm.dldcc.big.clinical.data.DerivativeType; import edu.bcm.dldcc.big.clinical.data.DnaQuality; /** * Entity implementation class for Entity: NaLabAnnotation * */ @Entity @Table(name="NaAnnotation") @Audited public class NaLabAnnotation implements Serializable { private static final long serialVersionUID = 1L; private DerivativeType type; private DnaQuality quality; private BigDecimal rin; private AliquotAnnotation parent; private String id; private String naLabel; public NaLabAnnotation() { super(); } /** * @return the type */ @Enumerated(EnumType.STRING) public DerivativeType getType() { return this.type; } /** * @param type the type to set */ public void setType(DerivativeType type) { this.type = type; } /** * @return the quality */ @Enumerated(EnumType.STRING) public DnaQuality getQuality() { return this.quality; } /** * @param quality the quality to set */ public void setQuality(DnaQuality quality) { this.quality = quality; } /** * @return the metric */ @DecimalMax(value="10.0") @DecimalMin(value="0.0") public BigDecimal getRin() { return this.rin; } /** * @param metric the metric to set */ public void setRin(BigDecimal metric) { this.rin = metric; } /** * @return the parent */ @ManyToOne public AliquotAnnotation getParent() { return this.parent; } /** * @param parent the parent to set */ public void setParent(AliquotAnnotation parent) { this.parent = parent; } /** * @return the id */ @Id public String getId() { return this.id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } @PrePersist public void generateId() { if(this.getId() == null || this.getId().isEmpty()) { this.setId(UUID.randomUUID().toString()); } } /** * @return the naLabel */ public String getNaLabel() { return this.naLabel; } /** * @param naLabel the naLabel to set */ public void setNaLabel(String naLabel) { this.naLabel = naLabel; } }
UTF-8
Java
2,700
java
NaLabAnnotation.java
Java
[]
null
[]
package edu.bcm.dldcc.big.clinical.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.validation.constraints.DecimalMax; import javax.validation.constraints.DecimalMin; import org.hibernate.envers.Audited; import edu.bcm.dldcc.big.clinical.data.DerivativeType; import edu.bcm.dldcc.big.clinical.data.DnaQuality; /** * Entity implementation class for Entity: NaLabAnnotation * */ @Entity @Table(name="NaAnnotation") @Audited public class NaLabAnnotation implements Serializable { private static final long serialVersionUID = 1L; private DerivativeType type; private DnaQuality quality; private BigDecimal rin; private AliquotAnnotation parent; private String id; private String naLabel; public NaLabAnnotation() { super(); } /** * @return the type */ @Enumerated(EnumType.STRING) public DerivativeType getType() { return this.type; } /** * @param type the type to set */ public void setType(DerivativeType type) { this.type = type; } /** * @return the quality */ @Enumerated(EnumType.STRING) public DnaQuality getQuality() { return this.quality; } /** * @param quality the quality to set */ public void setQuality(DnaQuality quality) { this.quality = quality; } /** * @return the metric */ @DecimalMax(value="10.0") @DecimalMin(value="0.0") public BigDecimal getRin() { return this.rin; } /** * @param metric the metric to set */ public void setRin(BigDecimal metric) { this.rin = metric; } /** * @return the parent */ @ManyToOne public AliquotAnnotation getParent() { return this.parent; } /** * @param parent the parent to set */ public void setParent(AliquotAnnotation parent) { this.parent = parent; } /** * @return the id */ @Id public String getId() { return this.id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } @PrePersist public void generateId() { if(this.getId() == null || this.getId().isEmpty()) { this.setId(UUID.randomUUID().toString()); } } /** * @return the naLabel */ public String getNaLabel() { return this.naLabel; } /** * @param naLabel the naLabel to set */ public void setNaLabel(String naLabel) { this.naLabel = naLabel; } }
2,700
0.657407
0.655185
166
15.26506
15.614392
58
false
false
0
0
0
0
0
0
0.23494
false
false
12
784343666ca2fb0a50d5b815007ece84d18104a7
18,459,769,468,871
c10ddfe01d6e8dce2b901de9f3c2879628e09baf
/src/main/java/com/training/tutorial/rabbitmq/RabbitMQApplication.java
b2ffa61d0f7f152948895e8080a2bd515c601c17
[]
no_license
kevinngth/rabbitMQ
https://github.com/kevinngth/rabbitMQ
12d8129611eced4f25224bcbe8a4b25787a30725
66565f2c8bd257bcf22b527ad0f686d3a8fa70ae
refs/heads/master
2022-04-16T19:14:17.214000
2020-04-15T09:07:59
2020-04-15T09:07:59
255,862,007
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.training.tutorial.rabbitmq; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class RabbitMQApplication { static final String QUEUE_NAME = "queue"; static final String TOPIC_EXCHANGE_NAME = "topic-exchange"; @Bean Queue queue() { // creates an AMQP queue. return new Queue(QUEUE_NAME, false); } @Bean TopicExchange topicExchange() { // creates a topic exchange. return new TopicExchange(TOPIC_EXCHANGE_NAME); // default exchange: messages routed to queue with name specified by routing key if exist // direct exchange: message goes to queue with binding key that matches exactly // topic exchange: messages goes to queues with binding keys containing its routing keys. * replaces exactly 1 word, # replaces 0 or more words and . separates them // fanout exchange: broadcast all received messages to all queues // headers exchange: ignore routing key attribute and uses message headers instead, setting "x-match" to any or all } @Bean Binding binding(Queue queue, TopicExchange topicExchange) { // binds these queue & exchange together, return BindingBuilder.bind(queue).to(topicExchange).with("foo.bar.#"); // defining the behavior that occurs when RabbitTemplate publishes to an exchange. } // the queue is bound with a routing key of foo.bar.#, which means that any messages sent with a routing key that begins with foo.bar. are routed to the queue. @Bean SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames(QUEUE_NAME); container.setMessageListener(listenerAdapter); // registered as a message listener in the container. It listens for messages on the spring-boot queue. return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { // Because the Receiver class is a POJO, it needs to be wrapped in the MessageListenerAdapter, return new MessageListenerAdapter(receiver, "receiveMessage"); // where you specify that it invokes receiveMessage. } public static void main(String[] args) { SpringApplication.run(RabbitMQApplication.class, args); } }
UTF-8
Java
2,700
java
RabbitMQApplication.java
Java
[]
null
[]
package com.training.tutorial.rabbitmq; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class RabbitMQApplication { static final String QUEUE_NAME = "queue"; static final String TOPIC_EXCHANGE_NAME = "topic-exchange"; @Bean Queue queue() { // creates an AMQP queue. return new Queue(QUEUE_NAME, false); } @Bean TopicExchange topicExchange() { // creates a topic exchange. return new TopicExchange(TOPIC_EXCHANGE_NAME); // default exchange: messages routed to queue with name specified by routing key if exist // direct exchange: message goes to queue with binding key that matches exactly // topic exchange: messages goes to queues with binding keys containing its routing keys. * replaces exactly 1 word, # replaces 0 or more words and . separates them // fanout exchange: broadcast all received messages to all queues // headers exchange: ignore routing key attribute and uses message headers instead, setting "x-match" to any or all } @Bean Binding binding(Queue queue, TopicExchange topicExchange) { // binds these queue & exchange together, return BindingBuilder.bind(queue).to(topicExchange).with("foo.bar.#"); // defining the behavior that occurs when RabbitTemplate publishes to an exchange. } // the queue is bound with a routing key of foo.bar.#, which means that any messages sent with a routing key that begins with foo.bar. are routed to the queue. @Bean SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(); container.setConnectionFactory(connectionFactory); container.setQueueNames(QUEUE_NAME); container.setMessageListener(listenerAdapter); // registered as a message listener in the container. It listens for messages on the spring-boot queue. return container; } @Bean MessageListenerAdapter listenerAdapter(Receiver receiver) { // Because the Receiver class is a POJO, it needs to be wrapped in the MessageListenerAdapter, return new MessageListenerAdapter(receiver, "receiveMessage"); // where you specify that it invokes receiveMessage. } public static void main(String[] args) { SpringApplication.run(RabbitMQApplication.class, args); } }
2,700
0.794074
0.793333
55
48.109093
47.889523
166
false
false
0
0
0
0
0
0
1.654545
false
false
12
9900a16658f4f0e5067dae44e45f7da28077b9f3
18,708,877,572,888
b87c766cb15d5169485cd8666469d619a38d83c4
/T03/src/Threads/Server.java
89fe3cf3141ae24402ee15bc970317b938e86adc
[]
no_license
andrewfonseca/ISEL_FSO
https://github.com/andrewfonseca/ISEL_FSO
3a7d2164ea2341b14213b4ffd75bc878ed24d615
124be55f666c7be79f792ee894b71e7197497343
refs/heads/master
2021-01-10T13:46:35.136000
2016-03-03T16:35:27
2016-03-03T16:38:17
43,502,791
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package Threads; //https://www.cs.uic.edu/~troy/spring05/cs450/sockets/socket.html //https://github.com/areong/Socket/tree/master/src/com/areong/socket //https://docs.oracle.com/javase/tutorial/networking/sockets/index.html //http://www.avajava.com/tutorials/lessons/how-do-i-write-a-server-socket-that-can-handle-input-and-output.html //https://gerrydevstory.com/2014/01/28/multithreaded-server-in-java/ //http://cs.lmu.edu/~ray/notes/javanetexamples/ import java.net.*; import java.io.*; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.swing.JTextField; import Robot.MyRobotLego; public class Server extends Thread { private JTextField l; private ArrayList<ClientHandler> clients = new ArrayList<>(); private ServerSocket serverSocket; private final int port = 7755; private Semaphore mutex; public Server(JTextField l) { this.l = l; } @Override public void run() { try { System.out.println("[x] Starting server"); mutex = new Semaphore(1); serverSocket = new ServerSocket(port); while(true) { Socket clientSocket = serverSocket.accept(); clients.add(new ClientHandler(clientSocket, l, mutex)); trimClients(); System.out.println("[x] Clients connected: " + clients.size()); } } catch(IOException e) { System.out.println("[x] Failed to accept new client"); return; } finally { // TODO } } private ClientHandler findClient(String hostname) { for(int i = 0; i < clients.size(); i++) { if(clients.get(i).getHost().toString().equals(hostname)) { return clients.get(i); } } return null; } private boolean killClient(String hostname) { return findClient(hostname).close(); } private void killClient(ClientHandler client) { clients.remove(client); } private void trimClients() { for(int i = 0; i < clients.size(); i++) { if(!clients.get(i).isAlive()) clients.remove(i); } } } class ClientHandler extends Thread { private Socket clientSocket; private PrintWriter out; private BufferedReader in; private Robot.MyRobotLego robot; private JTextField l; private boolean isAlive; private Semaphore mutex; public ClientHandler(Socket clientSocket, JTextField l, Semaphore mutex) { this.clientSocket = clientSocket; this.l = l; this.mutex = mutex; this.isAlive = true; start(); } public String getHost() { return this.clientSocket.getInetAddress().toString(); } @Override public void run() { try { if(!isAlive) return; out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); robot = new MyRobotLego(l, false); String input; while((input = in.readLine()) != null) { int[] c = stringToArraysOfInt(input); if(c[0] == 0) processCommand(c); if(c[0] == 1) processOrder(c); } } catch(IOException | InterruptedException e) { } //finally { close(); } } public boolean close() { try { // TODO: tell the server to remove this client System.out.print("im here"); mutex.release(); out.close(); in.close(); clientSocket.close(); return true; } catch(IOException e) { return false; } } public void shutdown() { close(); isAlive = false; interrupt(); } private boolean processOrder(int[] order) throws InterruptedException { // 1:direction:distance:radius:angle:offsetL:offsetR: if (order.length == 0) return false; if(order[0] != 1) return false; switch(order[1]) { case 8: robot.Reta(order[1]); System.out.println("[x] Robot: Moving forward"); break; case 2: robot.Reta(-order[1]); System.out.println("[x] Robot: Moving backwards"); break; case 6: robot.CurvarDireita(order[3], order[4]); robot.AjustarVMD(order[6]); System.out.println("[x] Robot: Turning left"); break; case 4: robot.CurvarEsquerda(order[3], order[4]); robot.AjustarVME(order[5]); System.out.println("[x] Robot: Turning right"); break; case 5: robot.Parar(true); System.out.println("[x] Robot stop"); break; case 7: robot.AjustarVME(order[5]); break; case 9: robot.AjustarVMD(order[6]); break; } return true; } private void sendCommand(String cmd) { out.println(cmd); out.flush(); } private boolean processCommand(int[] order) throws InterruptedException { // 0:0: -- shutdown // 0:1: -- close // 0:2: -- start // 0:3: -- ping // 0:4: -- pong // 0:5: -- kill if (order.length == 0) return false; if(order[0] != 0) return false; switch(order[1]) { case 0: shutdown(); break; case 1: close(); break; case 2: mutex.acquire(); sendCommand("0:2:"); break; case 3: System.out.println("Client: ping!"); sendCommand("0:4:"); // send pong break; } return false; } public static int[] stringToArraysOfInt(String order) { String[] orders = order.split(":"); int[] intOrders = new int[orders.length]; for(int i = 0; i < orders.length; i++) { intOrders[i] = Integer.parseInt(orders[i]); } return intOrders; } }
UTF-8
Java
5,152
java
Server.java
Java
[ { "context": "package Threads;\n\n//https://www.cs.uic.edu/~troy/spring05/cs450/sockets/socket.html\n//https://g", "end": 45, "score": 0.6553391218185425, "start": 44, "tag": "USERNAME", "value": "t" }, { "context": "05/cs450/sockets/socket.html\n//https://github.com/areong/Socket/tree/master/src/com/areong/socket\n//https:", "end": 111, "score": 0.9993987679481506, "start": 105, "tag": "USERNAME", "value": "areong" } ]
null
[]
package Threads; //https://www.cs.uic.edu/~troy/spring05/cs450/sockets/socket.html //https://github.com/areong/Socket/tree/master/src/com/areong/socket //https://docs.oracle.com/javase/tutorial/networking/sockets/index.html //http://www.avajava.com/tutorials/lessons/how-do-i-write-a-server-socket-that-can-handle-input-and-output.html //https://gerrydevstory.com/2014/01/28/multithreaded-server-in-java/ //http://cs.lmu.edu/~ray/notes/javanetexamples/ import java.net.*; import java.io.*; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.swing.JTextField; import Robot.MyRobotLego; public class Server extends Thread { private JTextField l; private ArrayList<ClientHandler> clients = new ArrayList<>(); private ServerSocket serverSocket; private final int port = 7755; private Semaphore mutex; public Server(JTextField l) { this.l = l; } @Override public void run() { try { System.out.println("[x] Starting server"); mutex = new Semaphore(1); serverSocket = new ServerSocket(port); while(true) { Socket clientSocket = serverSocket.accept(); clients.add(new ClientHandler(clientSocket, l, mutex)); trimClients(); System.out.println("[x] Clients connected: " + clients.size()); } } catch(IOException e) { System.out.println("[x] Failed to accept new client"); return; } finally { // TODO } } private ClientHandler findClient(String hostname) { for(int i = 0; i < clients.size(); i++) { if(clients.get(i).getHost().toString().equals(hostname)) { return clients.get(i); } } return null; } private boolean killClient(String hostname) { return findClient(hostname).close(); } private void killClient(ClientHandler client) { clients.remove(client); } private void trimClients() { for(int i = 0; i < clients.size(); i++) { if(!clients.get(i).isAlive()) clients.remove(i); } } } class ClientHandler extends Thread { private Socket clientSocket; private PrintWriter out; private BufferedReader in; private Robot.MyRobotLego robot; private JTextField l; private boolean isAlive; private Semaphore mutex; public ClientHandler(Socket clientSocket, JTextField l, Semaphore mutex) { this.clientSocket = clientSocket; this.l = l; this.mutex = mutex; this.isAlive = true; start(); } public String getHost() { return this.clientSocket.getInetAddress().toString(); } @Override public void run() { try { if(!isAlive) return; out = new PrintWriter(clientSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); robot = new MyRobotLego(l, false); String input; while((input = in.readLine()) != null) { int[] c = stringToArraysOfInt(input); if(c[0] == 0) processCommand(c); if(c[0] == 1) processOrder(c); } } catch(IOException | InterruptedException e) { } //finally { close(); } } public boolean close() { try { // TODO: tell the server to remove this client System.out.print("im here"); mutex.release(); out.close(); in.close(); clientSocket.close(); return true; } catch(IOException e) { return false; } } public void shutdown() { close(); isAlive = false; interrupt(); } private boolean processOrder(int[] order) throws InterruptedException { // 1:direction:distance:radius:angle:offsetL:offsetR: if (order.length == 0) return false; if(order[0] != 1) return false; switch(order[1]) { case 8: robot.Reta(order[1]); System.out.println("[x] Robot: Moving forward"); break; case 2: robot.Reta(-order[1]); System.out.println("[x] Robot: Moving backwards"); break; case 6: robot.CurvarDireita(order[3], order[4]); robot.AjustarVMD(order[6]); System.out.println("[x] Robot: Turning left"); break; case 4: robot.CurvarEsquerda(order[3], order[4]); robot.AjustarVME(order[5]); System.out.println("[x] Robot: Turning right"); break; case 5: robot.Parar(true); System.out.println("[x] Robot stop"); break; case 7: robot.AjustarVME(order[5]); break; case 9: robot.AjustarVMD(order[6]); break; } return true; } private void sendCommand(String cmd) { out.println(cmd); out.flush(); } private boolean processCommand(int[] order) throws InterruptedException { // 0:0: -- shutdown // 0:1: -- close // 0:2: -- start // 0:3: -- ping // 0:4: -- pong // 0:5: -- kill if (order.length == 0) return false; if(order[0] != 0) return false; switch(order[1]) { case 0: shutdown(); break; case 1: close(); break; case 2: mutex.acquire(); sendCommand("0:2:"); break; case 3: System.out.println("Client: ping!"); sendCommand("0:4:"); // send pong break; } return false; } public static int[] stringToArraysOfInt(String order) { String[] orders = order.split(":"); int[] intOrders = new int[orders.length]; for(int i = 0; i < orders.length; i++) { intOrders[i] = Integer.parseInt(orders[i]); } return intOrders; } }
5,152
0.652174
0.638393
222
22.211712
20.332933
111
false
false
0
0
0
0
0
0
2.355856
false
false
12
e9d4152c3358ed907d67c49907d9d136558b68c1
27,960,237,138,755
9a984dfb52b195c0e6997f5bf58f8b8dc868d015
/JavaCore/src/set/SetClass.java
35bc503ca550411a425a71d0ea621a30d0c5ffc8
[]
no_license
akkhil2012/DsAndAlgo
https://github.com/akkhil2012/DsAndAlgo
2788d8b0068579452a64b52562636b5999ea4117
e3d0fb625d1c06c1c26e58d66dc007b17df71bed
refs/heads/master
2015-09-25T18:06:53.725000
2015-08-18T06:08:00
2015-08-18T06:08:00
40,953,772
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package set; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class SetClass { public static void main(String args[]) { Set st = new HashSet(3);//default load factor: .75//Constructor 1 st.add("first"); st.add("sec"); st.add("third"); HashSet clonedSet = (HashSet) ((HashSet)st).clone();//5. Clone() method ShallowCopy???????? st.remove("first"); // System.out.println("HahsSet after cloning............."+st); // System.out.println("Cloned_HahsSet after cloning............."+clonedSet); // System.out.println("Size of HashSet1 is"+st.size()); st.add("fourth"); // System.out.println("Size of HashSet1 after rehashing is"+st.size()); Set st1 = new TreeSet();//Constructor 2 st1.add("first"); // st1.add("sec"); // st1.add("third"); st1.add(null);//HashSet allows NUll? why st1.add(null); st1.add(null); // System.out.println("Size of HashSet2 is#########"+st1.size()); // st1.add("fourth"); System.out.println("Size of HashSet2 after rehashing is***********"+st1.size()); Iterator it = st1.iterator(); while(it.hasNext()){ System.out.println("The values from HashSet are"+"********"+it.next()); } } }
UTF-8
Java
1,291
java
SetClass.java
Java
[]
null
[]
package set; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class SetClass { public static void main(String args[]) { Set st = new HashSet(3);//default load factor: .75//Constructor 1 st.add("first"); st.add("sec"); st.add("third"); HashSet clonedSet = (HashSet) ((HashSet)st).clone();//5. Clone() method ShallowCopy???????? st.remove("first"); // System.out.println("HahsSet after cloning............."+st); // System.out.println("Cloned_HahsSet after cloning............."+clonedSet); // System.out.println("Size of HashSet1 is"+st.size()); st.add("fourth"); // System.out.println("Size of HashSet1 after rehashing is"+st.size()); Set st1 = new TreeSet();//Constructor 2 st1.add("first"); // st1.add("sec"); // st1.add("third"); st1.add(null);//HashSet allows NUll? why st1.add(null); st1.add(null); // System.out.println("Size of HashSet2 is#########"+st1.size()); // st1.add("fourth"); System.out.println("Size of HashSet2 after rehashing is***********"+st1.size()); Iterator it = st1.iterator(); while(it.hasNext()){ System.out.println("The values from HashSet are"+"********"+it.next()); } } }
1,291
0.595662
0.579396
62
19.758064
24.532852
93
false
false
0
0
0
0
0
0
2.080645
false
false
12
770f32fedfec13b466edd0cb80c01a06d9ce2961
2,559,800,548,221
a391469b25f2a714ee27258ec88c47bca8c92e8e
/Colossus/emotionalpatrick-colossus-f19a4e53c097/minecraft/org/emotionalpatrick/colossus/modules/OpAura.java
41cf593a41f51da2c83e866c6f214ad1e470c182
[]
no_license
cheesepickles90/test
https://github.com/cheesepickles90/test
1408803632f321ac0fe7a3edb5852693ec573636
0513538d90b5b5556fa37e1066b256019adf2e7d
refs/heads/master
2021-01-25T07:08:05.716000
2014-12-29T17:07:54
2014-12-29T17:07:54
28,539,075
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.emotionalpatrick.colossus.modules; import net.minecraft.src.Entity; import net.minecraft.src.EntityLiving; import net.minecraft.src.EntityPlayer; import net.minecraft.src.StringUtils; import org.emotionalpatrick.colossus.main.Colossus; import org.emotionalpatrick.colossus.main.Helper; import org.emotionalpatrick.colossus.main.Wrapper; import org.lwjgl.input.Keyboard; public class OpAura extends Module { private long current; private long last = -1; public float attacksPerSecond = 15F; public OpAura() { super("OpAura", ".opaura", "OP ass aura", "Ramisme", 0xFF0000, Keyboard.KEY_NONE, "Kill Aura"); } @Override public void onTick() { long delay = (long) (1000 / attacksPerSecond); current = System.nanoTime() / 1000000; if (!isEnabled()) { return; } for (Object o : Wrapper.getWorld().loadedEntityList) { Entity e = (Entity) o; if (e == Wrapper.getPlayer()) { continue; } if (((current - last >= delay) || (last == -1)) && isAttackable(e)) { Colossus.getManager().killAura.getBestWeapon(); Wrapper.getPlayer().swingItem(); Wrapper.getMinecraft().playerController.attackEntity(Wrapper.getPlayer(), e); last = System.nanoTime() / 1000000; break; } } } @Override public void onAttackEntity(EntityPlayer par1EntityPlayer, Entity par2Entity) { if (par2Entity instanceof EntityPlayer) { String name = StringUtils.stripControlCodes(par2Entity.getEntityName()); Helper.sendChat("/kill " + name); } } private boolean isAttackable(Entity e) { if (!(e instanceof EntityLiving)) { return false; } EntityLiving eLiving = (EntityLiving) e; return (e.getDistanceToEntity(Wrapper.getPlayer()) <= 6 && eLiving.isEntityAlive() && isPlayer(e)); } private boolean isPlayer(Entity e) { if (!(e instanceof EntityPlayer)) { return false; } EntityPlayer player = (EntityPlayer) e; if (!Helper.isFriend(player.username)) { return true; } return false; } }
UTF-8
Java
1,975
java
OpAura.java
Java
[]
null
[]
package org.emotionalpatrick.colossus.modules; import net.minecraft.src.Entity; import net.minecraft.src.EntityLiving; import net.minecraft.src.EntityPlayer; import net.minecraft.src.StringUtils; import org.emotionalpatrick.colossus.main.Colossus; import org.emotionalpatrick.colossus.main.Helper; import org.emotionalpatrick.colossus.main.Wrapper; import org.lwjgl.input.Keyboard; public class OpAura extends Module { private long current; private long last = -1; public float attacksPerSecond = 15F; public OpAura() { super("OpAura", ".opaura", "OP ass aura", "Ramisme", 0xFF0000, Keyboard.KEY_NONE, "Kill Aura"); } @Override public void onTick() { long delay = (long) (1000 / attacksPerSecond); current = System.nanoTime() / 1000000; if (!isEnabled()) { return; } for (Object o : Wrapper.getWorld().loadedEntityList) { Entity e = (Entity) o; if (e == Wrapper.getPlayer()) { continue; } if (((current - last >= delay) || (last == -1)) && isAttackable(e)) { Colossus.getManager().killAura.getBestWeapon(); Wrapper.getPlayer().swingItem(); Wrapper.getMinecraft().playerController.attackEntity(Wrapper.getPlayer(), e); last = System.nanoTime() / 1000000; break; } } } @Override public void onAttackEntity(EntityPlayer par1EntityPlayer, Entity par2Entity) { if (par2Entity instanceof EntityPlayer) { String name = StringUtils.stripControlCodes(par2Entity.getEntityName()); Helper.sendChat("/kill " + name); } } private boolean isAttackable(Entity e) { if (!(e instanceof EntityLiving)) { return false; } EntityLiving eLiving = (EntityLiving) e; return (e.getDistanceToEntity(Wrapper.getPlayer()) <= 6 && eLiving.isEntityAlive() && isPlayer(e)); } private boolean isPlayer(Entity e) { if (!(e instanceof EntityPlayer)) { return false; } EntityPlayer player = (EntityPlayer) e; if (!Helper.isFriend(player.username)) { return true; } return false; } }
1,975
0.701772
0.68557
72
26.430555
23.317749
97
false
false
0
0
0
0
0
0
2.222222
false
false
12
726283bed4b3f96bcdc52831758b2716a7801d56
10,574,209,522,787
fd37781f148107813e6b2026027cd10e60147be7
/BookMyFurnitures/src/main/java/base/DriverClass.java
43f3f32e3f257ee99adabd0a9e57c5c6a6648111
[]
no_license
ruchi0402/BookMyFurniture
https://github.com/ruchi0402/BookMyFurniture
a1f45b941ab4c4a3ca1394e784925d53a5746062
7cd47dbfc6b07585feeba5500b0e4c1775a42d69
refs/heads/master
2020-12-15T20:06:52.623000
2020-03-07T18:15:12
2020-03-07T18:15:12
235,239,364
0
0
null
false
2020-01-21T04:31:23
2020-01-21T02:24:51
2020-01-21T04:15:29
2020-01-21T04:31:22
0
0
0
0
HTML
false
false
package base; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import util.ReadProperties; // Base class is for driver and browser set up. It extends Read Properties class from which it is getting browser and url data. public class DriverClass { public static WebDriver driver; public ExtentHtmlReporter htmlReporter; public ExtentReports extent; public ExtentTest logger; ReadProperties readconfig = new ReadProperties(); public String browserName = readconfig.getBrowser(); public String url = readconfig.getApplicationURL(); public void instantiateBrowser() { if (browserName.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\src\\main\\resources\\drivers\\chromedriver.exe"); driver = new ChromeDriver(); } else if (browserName.equalsIgnoreCase("FF")) { System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\src\\main\\resources\\drivers\\geckodriver.exe"); driver = new FirefoxDriver(); } driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(CommonConstant.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(CommonConstant.IMPLICIT_WAIT, TimeUnit.SECONDS); driver.get(url); } }
UTF-8
Java
1,607
java
DriverClass.java
Java
[]
null
[]
package base; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import util.ReadProperties; // Base class is for driver and browser set up. It extends Read Properties class from which it is getting browser and url data. public class DriverClass { public static WebDriver driver; public ExtentHtmlReporter htmlReporter; public ExtentReports extent; public ExtentTest logger; ReadProperties readconfig = new ReadProperties(); public String browserName = readconfig.getBrowser(); public String url = readconfig.getApplicationURL(); public void instantiateBrowser() { if (browserName.equalsIgnoreCase("chrome")) { System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\src\\main\\resources\\drivers\\chromedriver.exe"); driver = new ChromeDriver(); } else if (browserName.equalsIgnoreCase("FF")) { System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\src\\main\\resources\\drivers\\geckodriver.exe"); driver = new FirefoxDriver(); } driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().pageLoadTimeout(CommonConstant.PAGE_LOAD_TIMEOUT, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(CommonConstant.IMPLICIT_WAIT, TimeUnit.SECONDS); driver.get(url); } }
1,607
0.774736
0.774736
42
37.261906
29.893509
127
false
false
0
0
0
0
0
0
1.809524
false
false
12
c7ae201a0610a905be940fda1e6e373bb297e74f
24,026,047,090,506
c11704ce582f4ab144eaea2e721db81eb356298f
/src/main/java/com/bjpowernode/crm/datadictionary/service/DicService.java
fa33a321666bc8d1e145b3a5b2215155dec170c8
[]
no_license
hlliu3/CRM
https://github.com/hlliu3/CRM
3123448d9ffcad69916ede771eb14747740a05af
6cac5f17c54ac9b3c9128197717eea1a53c42ba8
refs/heads/master
2022-12-08T17:23:11.405000
2019-06-19T09:36:32
2019-06-19T09:36:32
186,091,393
0
0
null
false
2022-11-15T23:21:01
2019-05-11T05:23:09
2019-06-19T09:37:15
2022-11-15T23:20:59
1,703
0
0
5
JavaScript
false
false
package com.bjpowernode.crm.datadictionary.service; import java.util.Map; /** * DESCRIPTION: * user: * date:2019/5/16 21:29 */ public interface DicService { Map<String,Object> selectDicValueByType(); }
UTF-8
Java
214
java
DicService.java
Java
[]
null
[]
package com.bjpowernode.crm.datadictionary.service; import java.util.Map; /** * DESCRIPTION: * user: * date:2019/5/16 21:29 */ public interface DicService { Map<String,Object> selectDicValueByType(); }
214
0.71028
0.658879
13
15.461538
17.041197
51
false
false
0
0
0
0
0
0
0.307692
false
false
12
56cccbd1b533e501558f46e857944f8d209c36e3
24,764,781,463,644
9c0d65e6f9536a3b08a3aa255d30647bf239696f
/src/main/java/com/buuz135/industrial/plugin/jei/category/LaserDrillOreCategory.java
1c8b57d4f9c1fa2062df5ec7e95bc0faa8179adf
[ "MIT" ]
permissive
NillerMedDild/Industrial-Foregoing
https://github.com/NillerMedDild/Industrial-Foregoing
e5b8f873b8df535631cebac37a5d9049869e2ab2
259b70ac60714786d1f793124bd66284ac08f1e3
refs/heads/1.16
2023-09-02T09:49:25.393000
2021-11-14T15:47:12
2021-11-14T15:47:12
324,833,129
0
0
MIT
true
2021-11-15T06:12:08
2020-12-27T19:25:21
2021-11-07T17:16:35
2021-11-15T06:12:06
7,828
0
0
1
Java
false
false
/* * This file is part of Industrial Foregoing. * * Copyright 2021, Buuz135 * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.buuz135.industrial.plugin.jei.category; import com.buuz135.industrial.recipe.LaserDrillOreRecipe; import com.buuz135.industrial.utils.Reference; import com.hrznstudio.titanium.api.client.AssetTypes; import com.hrznstudio.titanium.client.screen.asset.DefaultAssetProvider; import com.hrznstudio.titanium.util.AssetUtil; import com.mojang.blaze3d.matrix.MatrixStack; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.ingredient.IGuiItemStackGroup; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.category.IRecipeCategory; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.SimpleSound; import net.minecraft.util.RegistryKey; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvents; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.biome.Biome; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class LaserDrillOreCategory implements IRecipeCategory<LaserDrillOreRecipe> { public static final ResourceLocation ID = new ResourceLocation(LaserDrillOreRecipe.SERIALIZER.getRecipeType().toString()); private IGuiHelper guiHelper; public LaserDrillOreCategory(IGuiHelper guiHelper) { this.guiHelper = guiHelper; } @Override public ResourceLocation getUid() { return ID; } @Override public Class<? extends LaserDrillOreRecipe> getRecipeClass() { return LaserDrillOreRecipe.class; } @Override public String getTitle() { return "Laser Drill Items"; } @Override public IDrawable getBackground() { return guiHelper.drawableBuilder(new ResourceLocation(Reference.MOD_ID, "textures/gui/jei.png"), 0, 0, 82, 26).addPadding(0, 60, 35, 35).build(); } @Override public IDrawable getIcon() { return null; } @Override public void setIngredients(LaserDrillOreRecipe laserDrillOreRecipe, IIngredients iIngredients) { iIngredients.setInputs(VanillaTypes.ITEM, Arrays.asList(laserDrillOreRecipe.catalyst.getMatchingStacks())); iIngredients.setOutput(VanillaTypes.ITEM, laserDrillOreRecipe.output.getMatchingStacks()[0]); } @Override public void setRecipe(IRecipeLayout iRecipeLayout, LaserDrillOreRecipe laserDrillOreRecipe, IIngredients iIngredients) { IGuiItemStackGroup guiItemStackGroup = iRecipeLayout.getItemStacks(); guiItemStackGroup.init(0, true, 35, 4); guiItemStackGroup.set(0, iIngredients.getInputs(VanillaTypes.ITEM).get(0)); guiItemStackGroup.init(1, false, 60 + 35, 4); guiItemStackGroup.set(1, iIngredients.getOutputs(VanillaTypes.ITEM).get(0)); } @Override public void draw(LaserDrillOreRecipe recipe, MatrixStack matrixStack, double mouseX, double mouseY) { int recipeWidth = 82 + 35 + 35; if (recipe.pointer > 0) AssetUtil.drawAsset(matrixStack, Minecraft.getInstance().currentScreen, DefaultAssetProvider.DEFAULT_PROVIDER.getAsset(AssetTypes.BUTTON_ARROW_LEFT), 0, 70); if (recipe.pointer < recipe.rarity.length - 1) AssetUtil.drawAsset(matrixStack, Minecraft.getInstance().currentScreen, DefaultAssetProvider.DEFAULT_PROVIDER.getAsset(AssetTypes.BUTTON_ARROW_RIGHT), 137, 70); Minecraft.getInstance().getTextureManager().bindTexture(new ResourceLocation("textures/gui/toasts.png")); Minecraft.getInstance().currentScreen.blit(matrixStack, recipeWidth / 10 * 2, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3, 216, 0, 20, 20, 256, 256); Minecraft.getInstance().currentScreen.blit(matrixStack, recipeWidth / 10 * 7, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3, 216, 0, 20, 20, 256, 256); Minecraft.getInstance().getTextureManager().bindTexture(new ResourceLocation("forge", "textures/gui/icons.png")); Minecraft.getInstance().currentScreen.blit(matrixStack, recipeWidth / 10 * 7 + 1, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 + 3, 0, 16, 16, 16); String minY = new TranslationTextComponent("text.industrialforegoing.miny").getString() + " " + recipe.rarity[recipe.pointer].depth_min; String maxY = new TranslationTextComponent("text.industrialforegoing.maxy").getString() + " " + recipe.rarity[recipe.pointer].depth_max; String wight = new TranslationTextComponent("text.industrialforegoing.weight").getString() + " " + recipe.rarity[recipe.pointer].weight; String biomes = new TranslationTextComponent("text.industrialforegoing.biomes").getString(); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + minY, recipeWidth / 10, 30, 0); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + wight, recipeWidth / 10, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2), 0); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + maxY, recipeWidth / 10 * 6, 30, 0); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + "" + TextFormatting.UNDERLINE + biomes, recipeWidth / 2 - Minecraft.getInstance().fontRenderer.getStringWidth(biomes) / 2, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 2, 0); } @Override public List<ITextComponent> getTooltipStrings(LaserDrillOreRecipe recipe, double mouseX, double mouseY) { if (mouseX > 0 && mouseX < 15 && mouseY > 70 && mouseY < 85 && recipe.pointer > 0) { // Inside the back button return Collections.singletonList(new TranslationTextComponent("text.industrialforegoing.button.jei.prev_rarity")); } if (mouseX > 137 && mouseX < (137 + 15) && mouseY > 70 && mouseY < 85 && recipe.pointer < recipe.rarity.length - 1) { //Inside the next button return Collections.singletonList(new TranslationTextComponent("text.industrialforegoing.button.jei.next_rarity")); } if (mouseX > 13 * 2 && mouseX < 13 * 2 + 20 && mouseY > 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 && mouseY < 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 + 20) { //Inside the whitelisted biomes List<ITextComponent> biomes = new ArrayList<>(); biomes.add(new TranslationTextComponent("text.industrialforegoing.tooltip.whitelisted_biomes").mergeStyle(TextFormatting.UNDERLINE).mergeStyle(TextFormatting.GOLD)); if (recipe.rarity[recipe.pointer].whitelist.length == 0) biomes.add(new StringTextComponent("- Any")); else { for (RegistryKey<Biome> registryKey : recipe.rarity[recipe.pointer].whitelist) { biomes.add(new StringTextComponent("- ").append(new TranslationTextComponent("biome." + registryKey.getLocation().getNamespace() + "." + registryKey.getLocation().getPath()))); } } return biomes; } if (mouseX > 13 * 8 && mouseX < 13 * 8 + 20 && mouseY > 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 && mouseY < 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 + 20) { //Inside the whitelisted biomes List<ITextComponent> biomes = new ArrayList<>(); biomes.add(new TranslationTextComponent("text.industrialforegoing.tooltip.blacklisted_biomes").mergeStyle(TextFormatting.UNDERLINE).mergeStyle(TextFormatting.GOLD)); if (recipe.rarity[recipe.pointer].blacklist.length == 0) biomes.add(new StringTextComponent("- None")); else { for (RegistryKey<Biome> registryKey : recipe.rarity[recipe.pointer].blacklist) { biomes.add(new StringTextComponent("- ").append(new TranslationTextComponent("biome." + registryKey.getLocation().getNamespace() + "." + registryKey.getLocation().getPath()))); } } return biomes; } return Collections.emptyList(); } @Override public boolean handleClick(LaserDrillOreRecipe recipe, double mouseX, double mouseY, int mouseButton) { if (mouseX > 0 && mouseX < 15 && mouseY > 70 && mouseY < 85 && recipe.pointer > 0) { --recipe.pointer; Minecraft.getInstance().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); return true; } if (mouseX > 137 && mouseX < (137 + 15) && mouseY > 70 && mouseY < 85 && recipe.pointer < recipe.rarity.length - 1) { ++recipe.pointer; Minecraft.getInstance().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); return true; } return false; } }
UTF-8
Java
10,223
java
LaserDrillOreCategory.java
Java
[ { "context": "art of Industrial Foregoing.\n *\n * Copyright 2021, Buuz135\n *\n * Permission is hereby granted, free of charg", "end": 78, "score": 0.999699592590332, "start": 71, "tag": "USERNAME", "value": "Buuz135" } ]
null
[]
/* * This file is part of Industrial Foregoing. * * Copyright 2021, Buuz135 * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.buuz135.industrial.plugin.jei.category; import com.buuz135.industrial.recipe.LaserDrillOreRecipe; import com.buuz135.industrial.utils.Reference; import com.hrznstudio.titanium.api.client.AssetTypes; import com.hrznstudio.titanium.client.screen.asset.DefaultAssetProvider; import com.hrznstudio.titanium.util.AssetUtil; import com.mojang.blaze3d.matrix.MatrixStack; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.ingredient.IGuiItemStackGroup; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.category.IRecipeCategory; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.SimpleSound; import net.minecraft.util.RegistryKey; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvents; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.biome.Biome; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class LaserDrillOreCategory implements IRecipeCategory<LaserDrillOreRecipe> { public static final ResourceLocation ID = new ResourceLocation(LaserDrillOreRecipe.SERIALIZER.getRecipeType().toString()); private IGuiHelper guiHelper; public LaserDrillOreCategory(IGuiHelper guiHelper) { this.guiHelper = guiHelper; } @Override public ResourceLocation getUid() { return ID; } @Override public Class<? extends LaserDrillOreRecipe> getRecipeClass() { return LaserDrillOreRecipe.class; } @Override public String getTitle() { return "Laser Drill Items"; } @Override public IDrawable getBackground() { return guiHelper.drawableBuilder(new ResourceLocation(Reference.MOD_ID, "textures/gui/jei.png"), 0, 0, 82, 26).addPadding(0, 60, 35, 35).build(); } @Override public IDrawable getIcon() { return null; } @Override public void setIngredients(LaserDrillOreRecipe laserDrillOreRecipe, IIngredients iIngredients) { iIngredients.setInputs(VanillaTypes.ITEM, Arrays.asList(laserDrillOreRecipe.catalyst.getMatchingStacks())); iIngredients.setOutput(VanillaTypes.ITEM, laserDrillOreRecipe.output.getMatchingStacks()[0]); } @Override public void setRecipe(IRecipeLayout iRecipeLayout, LaserDrillOreRecipe laserDrillOreRecipe, IIngredients iIngredients) { IGuiItemStackGroup guiItemStackGroup = iRecipeLayout.getItemStacks(); guiItemStackGroup.init(0, true, 35, 4); guiItemStackGroup.set(0, iIngredients.getInputs(VanillaTypes.ITEM).get(0)); guiItemStackGroup.init(1, false, 60 + 35, 4); guiItemStackGroup.set(1, iIngredients.getOutputs(VanillaTypes.ITEM).get(0)); } @Override public void draw(LaserDrillOreRecipe recipe, MatrixStack matrixStack, double mouseX, double mouseY) { int recipeWidth = 82 + 35 + 35; if (recipe.pointer > 0) AssetUtil.drawAsset(matrixStack, Minecraft.getInstance().currentScreen, DefaultAssetProvider.DEFAULT_PROVIDER.getAsset(AssetTypes.BUTTON_ARROW_LEFT), 0, 70); if (recipe.pointer < recipe.rarity.length - 1) AssetUtil.drawAsset(matrixStack, Minecraft.getInstance().currentScreen, DefaultAssetProvider.DEFAULT_PROVIDER.getAsset(AssetTypes.BUTTON_ARROW_RIGHT), 137, 70); Minecraft.getInstance().getTextureManager().bindTexture(new ResourceLocation("textures/gui/toasts.png")); Minecraft.getInstance().currentScreen.blit(matrixStack, recipeWidth / 10 * 2, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3, 216, 0, 20, 20, 256, 256); Minecraft.getInstance().currentScreen.blit(matrixStack, recipeWidth / 10 * 7, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3, 216, 0, 20, 20, 256, 256); Minecraft.getInstance().getTextureManager().bindTexture(new ResourceLocation("forge", "textures/gui/icons.png")); Minecraft.getInstance().currentScreen.blit(matrixStack, recipeWidth / 10 * 7 + 1, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 + 3, 0, 16, 16, 16); String minY = new TranslationTextComponent("text.industrialforegoing.miny").getString() + " " + recipe.rarity[recipe.pointer].depth_min; String maxY = new TranslationTextComponent("text.industrialforegoing.maxy").getString() + " " + recipe.rarity[recipe.pointer].depth_max; String wight = new TranslationTextComponent("text.industrialforegoing.weight").getString() + " " + recipe.rarity[recipe.pointer].weight; String biomes = new TranslationTextComponent("text.industrialforegoing.biomes").getString(); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + minY, recipeWidth / 10, 30, 0); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + wight, recipeWidth / 10, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2), 0); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + maxY, recipeWidth / 10 * 6, 30, 0); Minecraft.getInstance().fontRenderer.drawString(matrixStack, TextFormatting.DARK_GRAY + "" + TextFormatting.UNDERLINE + biomes, recipeWidth / 2 - Minecraft.getInstance().fontRenderer.getStringWidth(biomes) / 2, 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 2, 0); } @Override public List<ITextComponent> getTooltipStrings(LaserDrillOreRecipe recipe, double mouseX, double mouseY) { if (mouseX > 0 && mouseX < 15 && mouseY > 70 && mouseY < 85 && recipe.pointer > 0) { // Inside the back button return Collections.singletonList(new TranslationTextComponent("text.industrialforegoing.button.jei.prev_rarity")); } if (mouseX > 137 && mouseX < (137 + 15) && mouseY > 70 && mouseY < 85 && recipe.pointer < recipe.rarity.length - 1) { //Inside the next button return Collections.singletonList(new TranslationTextComponent("text.industrialforegoing.button.jei.next_rarity")); } if (mouseX > 13 * 2 && mouseX < 13 * 2 + 20 && mouseY > 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 && mouseY < 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 + 20) { //Inside the whitelisted biomes List<ITextComponent> biomes = new ArrayList<>(); biomes.add(new TranslationTextComponent("text.industrialforegoing.tooltip.whitelisted_biomes").mergeStyle(TextFormatting.UNDERLINE).mergeStyle(TextFormatting.GOLD)); if (recipe.rarity[recipe.pointer].whitelist.length == 0) biomes.add(new StringTextComponent("- Any")); else { for (RegistryKey<Biome> registryKey : recipe.rarity[recipe.pointer].whitelist) { biomes.add(new StringTextComponent("- ").append(new TranslationTextComponent("biome." + registryKey.getLocation().getNamespace() + "." + registryKey.getLocation().getPath()))); } } return biomes; } if (mouseX > 13 * 8 && mouseX < 13 * 8 + 20 && mouseY > 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 && mouseY < 30 + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 2) * 3 + 20) { //Inside the whitelisted biomes List<ITextComponent> biomes = new ArrayList<>(); biomes.add(new TranslationTextComponent("text.industrialforegoing.tooltip.blacklisted_biomes").mergeStyle(TextFormatting.UNDERLINE).mergeStyle(TextFormatting.GOLD)); if (recipe.rarity[recipe.pointer].blacklist.length == 0) biomes.add(new StringTextComponent("- None")); else { for (RegistryKey<Biome> registryKey : recipe.rarity[recipe.pointer].blacklist) { biomes.add(new StringTextComponent("- ").append(new TranslationTextComponent("biome." + registryKey.getLocation().getNamespace() + "." + registryKey.getLocation().getPath()))); } } return biomes; } return Collections.emptyList(); } @Override public boolean handleClick(LaserDrillOreRecipe recipe, double mouseX, double mouseY, int mouseButton) { if (mouseX > 0 && mouseX < 15 && mouseY > 70 && mouseY < 85 && recipe.pointer > 0) { --recipe.pointer; Minecraft.getInstance().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); return true; } if (mouseX > 137 && mouseX < (137 + 15) && mouseY > 70 && mouseY < 85 && recipe.pointer < recipe.rarity.length - 1) { ++recipe.pointer; Minecraft.getInstance().getSoundHandler().play(SimpleSound.master(SoundEvents.UI_BUTTON_CLICK, 1.0F)); return true; } return false; } }
10,223
0.712707
0.690502
174
57.752872
58.026272
287
false
false
0
0
0
0
0
0
1.034483
false
false
12
c05403109f7734f0eb59b540f146a844864e3df0
23,235,773,108,176
540e31b9546ab543b9ffbea9288b55b8406907dd
/src/main/java/com/springboot/pojo/User.java
50692dcf7376a1a3bec63858cac31b14b962a745
[]
no_license
tangshiwei/springboot-shiro
https://github.com/tangshiwei/springboot-shiro
6d780fce1ffc01071d44d318eacc99858286196f
fe06eb8a19259df9326759af5c7286331047c210
refs/heads/master
2022-12-21T15:03:15.818000
2020-09-04T02:38:52
2020-09-04T02:38:52
292,731,131
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.springboot.pojo; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class User implements Serializable{ private Integer id; private String userName; private String password; private Date createTime; private String status; }
UTF-8
Java
280
java
User.java
Java
[ { "context": "erializable{\n\n\tprivate Integer id;\n\tprivate String userName;\n\tprivate String password;\n\tprivate Date createTi", "end": 199, "score": 0.9986097812652588, "start": 191, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.springboot.pojo; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class User implements Serializable{ private Integer id; private String userName; private String password; private Date createTime; private String status; }
280
0.789286
0.789286
17
15.470589
13.146763
42
false
false
0
0
0
0
0
0
0.823529
false
false
12
203a956426a29727281726f38482ad24aa0e6220
1,975,684,994,397
028b573522bb1f788e1e4591496ef3a5f0c90b4a
/src/LeetCode/Sliding_Window/P424_Longest_Repeating_Character_Replacement/Solution.java
8b6ba1da25d6555df7989b4fa0ffee4abc9b50a2
[]
no_license
chopincode/Cracking-Interviews
https://github.com/chopincode/Cracking-Interviews
4b496e782745db9ab08c0115d45f998d77cadac9
bd7e7dadea1cfa50f91eccbc592f7775629ac21f
refs/heads/master
2022-04-10T22:24:12.023000
2020-02-05T16:41:11
2020-02-05T16:41:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LeetCode.Sliding_Window.P424_Longest_Repeating_Character_Replacement; public class Solution { public int characterReplacement(String s, int k) { int max = 0; int maxLength = 0; int[] dict = new int[256]; int left = 0, right = 0; while (right < s.length()) { dict[s.charAt(right)]++; maxLength = Math.max(maxLength, dict[s.charAt(right)]); while((right - left + 1 - maxLength > k)) { dict[s.charAt(left)]--; left++; } max = Math.max(max, right - left + 1); right++; } return max; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.characterReplacement("AABABBA", 1)); } }
UTF-8
Java
830
java
Solution.java
Java
[]
null
[]
package LeetCode.Sliding_Window.P424_Longest_Repeating_Character_Replacement; public class Solution { public int characterReplacement(String s, int k) { int max = 0; int maxLength = 0; int[] dict = new int[256]; int left = 0, right = 0; while (right < s.length()) { dict[s.charAt(right)]++; maxLength = Math.max(maxLength, dict[s.charAt(right)]); while((right - left + 1 - maxLength > k)) { dict[s.charAt(left)]--; left++; } max = Math.max(max, right - left + 1); right++; } return max; } public static void main(String[] args) { Solution solution = new Solution(); System.out.println(solution.characterReplacement("AABABBA", 1)); } }
830
0.531325
0.515663
27
29.74074
22.306938
77
false
false
0
0
0
0
0
0
0.703704
false
false
12
4817e70fdc4f704bee7b60927c9543c994b83999
8,675,833,968,139
5e2a2f4f63f31a84bc8cd73bfef0d6b0318c0b48
/sdk/Sklep/src/MouseHandler.java
860b4f5e1796c2f93de220d69ad73510729c2c14
[]
no_license
blazejziel/Java
https://github.com/blazejziel/Java
23582dccdb563de77e4e233ffc808f579653bea6
14eb4cd80c17c9e5a96f76a5029bdc1c5d5fc7ee
refs/heads/master
2020-04-04T03:51:22.828000
2019-11-25T16:43:26
2019-11-25T16:43:26
155,684,097
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.event.*; import javax.swing.JOptionPane; public class MouseHandler implements ActionListener{ private Produkt p; public void actionPerformed(ActionEvent e) { Produkt p1=new Produkt(Okno.getPr(), Okno.cen); System.out.println("wpisane: "+Produkt.nazwa); System.out.println("Produkt: "+p1.getName()); JOptionPane.showMessageDialog(null, "Klick!"+Okno.pr+" miało być pr..."); } }
WINDOWS-1250
Java
409
java
MouseHandler.java
Java
[]
null
[]
import java.awt.event.*; import javax.swing.JOptionPane; public class MouseHandler implements ActionListener{ private Produkt p; public void actionPerformed(ActionEvent e) { Produkt p1=new Produkt(Okno.getPr(), Okno.cen); System.out.println("wpisane: "+Produkt.nazwa); System.out.println("Produkt: "+p1.getName()); JOptionPane.showMessageDialog(null, "Klick!"+Okno.pr+" miało być pr..."); } }
409
0.734644
0.72973
14
28.071428
24.111242
75
false
false
0
0
0
0
0
0
1.428571
false
false
12
e8054d34a89eb5749def6d7ea9bf626d915ee399
18,176,301,629,108
57734297bb85411931bb11744f1b8ec4a98aa702
/HighScores/src/scores/part2/TestHighScore2.java
ac165da8920eb2ade0b988269daf9c119def7328
[]
no_license
LaureMarchal/HighScores
https://github.com/LaureMarchal/HighScores
0bf84b20f1464e67b1b90c45666cc449515c09db
50dab5f992443507955bf9a7d74b75fb511e6077
refs/heads/master
2016-09-12T23:21:49.794000
2016-05-20T19:08:58
2016-05-20T19:08:58
57,046,365
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package scores.part2; import java.util.Random; import java.util.Scanner; import scores.BestPlayer; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * Contains a main which asks the user to enter his name and return a random score * Then reads a file with scores and return just names with scores * Print the ten best players. * * @author Laure Marchal and Theo Gauchoux * */ public class TestHighScore2 { public static void main(String[] args) { // Part 1 - 1 System.out.println("Ecrivez votre nom d'utilisateur svp : "); Scanner scanner = new Scanner(System.in); String username = scanner.nextLine(); scanner.close(); // Part 1 - 2 String fileContents = ""; BufferedReader br; try { br = new BufferedReader(new FileReader("data/scoreSamples.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = br.readLine(); } fileContents = sb.toString(); br.close(); } catch (IOException e) { e.printStackTrace(); } String[] scores = fileContents.split("\n"); // Part 1 - 3 Random randomizer = new Random(); int chosenScore = randomizer.nextInt(scores.length); // Part 1 - 4 System.out.println("The player called " + username + " has " + scores[chosenScore] + " points."); // Get and print the scores from ThingSpeak System.out.println("print the list of scores : "); HighScore2 highScore = new HighScore2(); String[] results = highScore.getScores(); // Part 2 BestPlayer[] toplayer = highScore.tenBestScores(results); for(BestPlayer player : toplayer) { if (player != null){ System.out.println(player); } } } }
UTF-8
Java
1,755
java
TestHighScore2.java
Java
[ { "context": "ores\n * Print the ten best players.\n * \n * @author Laure Marchal and Theo Gauchoux\n *\n */\npublic class TestHighSco", "end": 402, "score": 0.9998819231987, "start": 389, "tag": "NAME", "value": "Laure Marchal" }, { "context": "ten best players.\n * \n * @author Laure Marchal and Theo Gauchoux\n *\n */\npublic class TestHighScore2 {\n\n\tpublic sta", "end": 420, "score": 0.9998723864555359, "start": 407, "tag": "NAME", "value": "Theo Gauchoux" } ]
null
[]
package scores.part2; import java.util.Random; import java.util.Scanner; import scores.BestPlayer; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; /** * Contains a main which asks the user to enter his name and return a random score * Then reads a file with scores and return just names with scores * Print the ten best players. * * @author <NAME> and <NAME> * */ public class TestHighScore2 { public static void main(String[] args) { // Part 1 - 1 System.out.println("Ecrivez votre nom d'utilisateur svp : "); Scanner scanner = new Scanner(System.in); String username = scanner.nextLine(); scanner.close(); // Part 1 - 2 String fileContents = ""; BufferedReader br; try { br = new BufferedReader(new FileReader("data/scoreSamples.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = br.readLine(); } fileContents = sb.toString(); br.close(); } catch (IOException e) { e.printStackTrace(); } String[] scores = fileContents.split("\n"); // Part 1 - 3 Random randomizer = new Random(); int chosenScore = randomizer.nextInt(scores.length); // Part 1 - 4 System.out.println("The player called " + username + " has " + scores[chosenScore] + " points."); // Get and print the scores from ThingSpeak System.out.println("print the list of scores : "); HighScore2 highScore = new HighScore2(); String[] results = highScore.getScores(); // Part 2 BestPlayer[] toplayer = highScore.tenBestScores(results); for(BestPlayer player : toplayer) { if (player != null){ System.out.println(player); } } } }
1,741
0.671795
0.664387
71
23.718309
21.684799
99
false
false
0
0
0
0
0
0
1.929577
false
false
12
96014e6ec51c8977e8cfcb2974e24838717833f1
26,955,214,794,482
2844b02875d1c843727ea97377955a6a1d55ab83
/src/cn/sunn/forensiclion/domain/CaseInfor.java
0cbffb18ef298b98c5214a593f261b7c8c9bde1d
[]
no_license
queer1/ForensicLion
https://github.com/queer1/ForensicLion
91121cc7cf3d268b8f69cf86a11d6699cfb4e228
6aa97032b3d639ffa92e191da189237269a9b21c
refs/heads/master
2021-01-20T19:49:49.332000
2013-05-05T06:18:21
2013-05-05T06:18:21
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.sunn.forensiclion.domain; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * CaseInfor entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "case_infor", catalog = "ForensicLion") public class CaseInfor implements java.io.Serializable { // Fields private long id; private String caseId; private String identifyMajor; private Date entrustDate; private String identifyRequest; private String entrusterAddress; private String reportGetway; private String receiverName; private String receiverAddress; private String receiverCode; private String receiverEmail; private String entruster; private String entrusterRelation; private String entrusterNum; private String linkman; private String linkmanTel; private String linkmanFax; private String identifySender; private String insuranceUnit; private String insuranceLinkman; private String insuranceTel; private String insuranceEmail; private Date caseDate; private String caseClass; private Integer caseIdentifyTimes; private String caseProgress; private String caseRemark; private String status; private Set<CaseCheckInfor> caseCheckInfors = new HashSet<CaseCheckInfor>(0); private Set<CaseFile> caseFiles = new HashSet<CaseFile>(0); private Set<CaseIdentifiedInfo> caseIdentifiedInfos = new HashSet<CaseIdentifiedInfo>( 0); private Set<CaseCharge> caseCharges = new HashSet<CaseCharge>(0); private Set<CaseInternalStatistics> caseInternalStatisticses = new HashSet<CaseInternalStatistics>( 0); // Constructors /** default constructor */ public CaseInfor() { } /** minimal constructor */ public CaseInfor(String caseId) { this.caseId = caseId; } /** full constructor */ public CaseInfor(String caseId, String identifyMajor, Date entrustDate, String identifyRequest, String entrusterAddress, String reportGetway, String receiverName, String receiverAddress, String receiverCode, String receiverEmail, String entruster, String entrusterRelation, String entrusterNum, String linkman, String linkmanTel, String linkmanFax, String identifySender, String insuranceUnit, String insuranceLinkman, String insuranceTel, String insuranceEmail, Date caseDate, String caseClass, Integer caseIdentifyTimes, String caseProgress, String caseRemark, String status, Set<CaseCheckInfor> caseCheckInfors, Set<CaseFile> caseFiles, Set<CaseIdentifiedInfo> caseIdentifiedInfos, Set<CaseCharge> caseCharges, Set<CaseInternalStatistics> caseInternalStatisticses) { this.caseId = caseId; this.identifyMajor = identifyMajor; this.entrustDate = entrustDate; this.identifyRequest = identifyRequest; this.entrusterAddress = entrusterAddress; this.reportGetway = reportGetway; this.receiverName = receiverName; this.receiverAddress = receiverAddress; this.receiverCode = receiverCode; this.receiverEmail = receiverEmail; this.entruster = entruster; this.entrusterRelation = entrusterRelation; this.entrusterNum = entrusterNum; this.linkman = linkman; this.linkmanTel = linkmanTel; this.linkmanFax = linkmanFax; this.identifySender = identifySender; this.insuranceUnit = insuranceUnit; this.insuranceLinkman = insuranceLinkman; this.insuranceTel = insuranceTel; this.insuranceEmail = insuranceEmail; this.caseDate = caseDate; this.caseClass = caseClass; this.caseIdentifyTimes = caseIdentifyTimes; this.caseProgress = caseProgress; this.caseRemark = caseRemark; this.status = status; this.caseCheckInfors = caseCheckInfors; this.caseFiles = caseFiles; this.caseIdentifiedInfos = caseIdentifiedInfos; this.caseCharges = caseCharges; this.caseInternalStatisticses = caseInternalStatisticses; } // Property accessors @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public long getId() { return this.id; } public void setId(long id) { this.id = id; } @Column(name = "case_id", nullable = false, length = 10) public String getCaseId() { return this.caseId; } public void setCaseId(String caseId) { this.caseId = caseId; } @Column(name = "identify_major", length = 60) public String getIdentifyMajor() { return this.identifyMajor; } public void setIdentifyMajor(String identifyMajor) { this.identifyMajor = identifyMajor; } @Temporal(TemporalType.DATE) @Column(name = "entrust_date", length = 10) public Date getEntrustDate() { return this.entrustDate; } public void setEntrustDate(Date entrustDate) { this.entrustDate = entrustDate; } @Column(name = "identify_request", length = 300) public String getIdentifyRequest() { return this.identifyRequest; } public void setIdentifyRequest(String identifyRequest) { this.identifyRequest = identifyRequest; } @Column(name = "entruster_address", length = 300) public String getEntrusterAddress() { return this.entrusterAddress; } public void setEntrusterAddress(String entrusterAddress) { this.entrusterAddress = entrusterAddress; } @Column(name = "report_getway", length = 30) public String getReportGetway() { return this.reportGetway; } public void setReportGetway(String reportGetway) { this.reportGetway = reportGetway; } @Column(name = "receiver_name", length = 20) public String getReceiverName() { return this.receiverName; } public void setReceiverName(String receiverName) { this.receiverName = receiverName; } @Column(name = "receiver_address", length = 300) public String getReceiverAddress() { return this.receiverAddress; } public void setReceiverAddress(String receiverAddress) { this.receiverAddress = receiverAddress; } @Column(name = "receiver_code", length = 10) public String getReceiverCode() { return this.receiverCode; } public void setReceiverCode(String receiverCode) { this.receiverCode = receiverCode; } @Column(name = "receiver_email", length = 50) public String getReceiverEmail() { return this.receiverEmail; } public void setReceiverEmail(String receiverEmail) { this.receiverEmail = receiverEmail; } @Column(name = "entruster", length = 100) public String getEntruster() { return this.entruster; } public void setEntruster(String entruster) { this.entruster = entruster; } @Column(name = "entruster_relation", length = 100) public String getEntrusterRelation() { return this.entrusterRelation; } public void setEntrusterRelation(String entrusterRelation) { this.entrusterRelation = entrusterRelation; } @Column(name = "entruster_num", length = 30) public String getEntrusterNum() { return this.entrusterNum; } public void setEntrusterNum(String entrusterNum) { this.entrusterNum = entrusterNum; } @Column(name = "linkman", length = 30) public String getLinkman() { return this.linkman; } public void setLinkman(String linkman) { this.linkman = linkman; } @Column(name = "linkman_tel", length = 30) public String getLinkmanTel() { return this.linkmanTel; } public void setLinkmanTel(String linkmanTel) { this.linkmanTel = linkmanTel; } @Column(name = "linkman_fax", length = 30) public String getLinkmanFax() { return this.linkmanFax; } public void setLinkmanFax(String linkmanFax) { this.linkmanFax = linkmanFax; } @Column(name = "identify_sender", length = 30) public String getIdentifySender() { return this.identifySender; } public void setIdentifySender(String identifySender) { this.identifySender = identifySender; } @Column(name = "insurance_unit", length = 100) public String getInsuranceUnit() { return this.insuranceUnit; } public void setInsuranceUnit(String insuranceUnit) { this.insuranceUnit = insuranceUnit; } @Column(name = "insurance_linkman", length = 30) public String getInsuranceLinkman() { return this.insuranceLinkman; } public void setInsuranceLinkman(String insuranceLinkman) { this.insuranceLinkman = insuranceLinkman; } @Column(name = "insurance_tel", length = 30) public String getInsuranceTel() { return this.insuranceTel; } public void setInsuranceTel(String insuranceTel) { this.insuranceTel = insuranceTel; } @Column(name = "insurance_email", length = 50) public String getInsuranceEmail() { return this.insuranceEmail; } public void setInsuranceEmail(String insuranceEmail) { this.insuranceEmail = insuranceEmail; } @Temporal(TemporalType.DATE) @Column(name = "case_date", length = 10) public Date getCaseDate() { return this.caseDate; } public void setCaseDate(Date caseDate) { this.caseDate = caseDate; } @Column(name = "case_class", length = 100) public String getCaseClass() { return this.caseClass; } public void setCaseClass(String caseClass) { this.caseClass = caseClass; } @Column(name = "case_identify_times") public Integer getCaseIdentifyTimes() { return this.caseIdentifyTimes; } public void setCaseIdentifyTimes(Integer caseIdentifyTimes) { this.caseIdentifyTimes = caseIdentifyTimes; } @Column(name = "case_progress", length = 100) public String getCaseProgress() { return this.caseProgress; } public void setCaseProgress(String caseProgress) { this.caseProgress = caseProgress; } @Column(name = "case_remark", length = 3000) public String getCaseRemark() { return this.caseRemark; } public void setCaseRemark(String caseRemark) { this.caseRemark = caseRemark; } @Column(name = "status", length = 100) public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseCheckInfor> getCaseCheckInfors() { return this.caseCheckInfors; } public void setCaseCheckInfors(Set<CaseCheckInfor> caseCheckInfors) { this.caseCheckInfors = caseCheckInfors; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseFile> getCaseFiles() { return this.caseFiles; } public void setCaseFiles(Set<CaseFile> caseFiles) { this.caseFiles = caseFiles; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseIdentifiedInfo> getCaseIdentifiedInfos() { return this.caseIdentifiedInfos; } public void setCaseIdentifiedInfos( Set<CaseIdentifiedInfo> caseIdentifiedInfos) { this.caseIdentifiedInfos = caseIdentifiedInfos; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseCharge> getCaseCharges() { return this.caseCharges; } public void setCaseCharges(Set<CaseCharge> caseCharges) { this.caseCharges = caseCharges; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseInternalStatistics> getCaseInternalStatisticses() { return this.caseInternalStatisticses; } public void setCaseInternalStatisticses( Set<CaseInternalStatistics> caseInternalStatisticses) { this.caseInternalStatisticses = caseInternalStatisticses; } }
UTF-8
Java
11,405
java
CaseInfor.java
Java
[]
null
[]
package cn.sunn.forensiclion.domain; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * CaseInfor entity. @author MyEclipse Persistence Tools */ @Entity @Table(name = "case_infor", catalog = "ForensicLion") public class CaseInfor implements java.io.Serializable { // Fields private long id; private String caseId; private String identifyMajor; private Date entrustDate; private String identifyRequest; private String entrusterAddress; private String reportGetway; private String receiverName; private String receiverAddress; private String receiverCode; private String receiverEmail; private String entruster; private String entrusterRelation; private String entrusterNum; private String linkman; private String linkmanTel; private String linkmanFax; private String identifySender; private String insuranceUnit; private String insuranceLinkman; private String insuranceTel; private String insuranceEmail; private Date caseDate; private String caseClass; private Integer caseIdentifyTimes; private String caseProgress; private String caseRemark; private String status; private Set<CaseCheckInfor> caseCheckInfors = new HashSet<CaseCheckInfor>(0); private Set<CaseFile> caseFiles = new HashSet<CaseFile>(0); private Set<CaseIdentifiedInfo> caseIdentifiedInfos = new HashSet<CaseIdentifiedInfo>( 0); private Set<CaseCharge> caseCharges = new HashSet<CaseCharge>(0); private Set<CaseInternalStatistics> caseInternalStatisticses = new HashSet<CaseInternalStatistics>( 0); // Constructors /** default constructor */ public CaseInfor() { } /** minimal constructor */ public CaseInfor(String caseId) { this.caseId = caseId; } /** full constructor */ public CaseInfor(String caseId, String identifyMajor, Date entrustDate, String identifyRequest, String entrusterAddress, String reportGetway, String receiverName, String receiverAddress, String receiverCode, String receiverEmail, String entruster, String entrusterRelation, String entrusterNum, String linkman, String linkmanTel, String linkmanFax, String identifySender, String insuranceUnit, String insuranceLinkman, String insuranceTel, String insuranceEmail, Date caseDate, String caseClass, Integer caseIdentifyTimes, String caseProgress, String caseRemark, String status, Set<CaseCheckInfor> caseCheckInfors, Set<CaseFile> caseFiles, Set<CaseIdentifiedInfo> caseIdentifiedInfos, Set<CaseCharge> caseCharges, Set<CaseInternalStatistics> caseInternalStatisticses) { this.caseId = caseId; this.identifyMajor = identifyMajor; this.entrustDate = entrustDate; this.identifyRequest = identifyRequest; this.entrusterAddress = entrusterAddress; this.reportGetway = reportGetway; this.receiverName = receiverName; this.receiverAddress = receiverAddress; this.receiverCode = receiverCode; this.receiverEmail = receiverEmail; this.entruster = entruster; this.entrusterRelation = entrusterRelation; this.entrusterNum = entrusterNum; this.linkman = linkman; this.linkmanTel = linkmanTel; this.linkmanFax = linkmanFax; this.identifySender = identifySender; this.insuranceUnit = insuranceUnit; this.insuranceLinkman = insuranceLinkman; this.insuranceTel = insuranceTel; this.insuranceEmail = insuranceEmail; this.caseDate = caseDate; this.caseClass = caseClass; this.caseIdentifyTimes = caseIdentifyTimes; this.caseProgress = caseProgress; this.caseRemark = caseRemark; this.status = status; this.caseCheckInfors = caseCheckInfors; this.caseFiles = caseFiles; this.caseIdentifiedInfos = caseIdentifiedInfos; this.caseCharges = caseCharges; this.caseInternalStatisticses = caseInternalStatisticses; } // Property accessors @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public long getId() { return this.id; } public void setId(long id) { this.id = id; } @Column(name = "case_id", nullable = false, length = 10) public String getCaseId() { return this.caseId; } public void setCaseId(String caseId) { this.caseId = caseId; } @Column(name = "identify_major", length = 60) public String getIdentifyMajor() { return this.identifyMajor; } public void setIdentifyMajor(String identifyMajor) { this.identifyMajor = identifyMajor; } @Temporal(TemporalType.DATE) @Column(name = "entrust_date", length = 10) public Date getEntrustDate() { return this.entrustDate; } public void setEntrustDate(Date entrustDate) { this.entrustDate = entrustDate; } @Column(name = "identify_request", length = 300) public String getIdentifyRequest() { return this.identifyRequest; } public void setIdentifyRequest(String identifyRequest) { this.identifyRequest = identifyRequest; } @Column(name = "entruster_address", length = 300) public String getEntrusterAddress() { return this.entrusterAddress; } public void setEntrusterAddress(String entrusterAddress) { this.entrusterAddress = entrusterAddress; } @Column(name = "report_getway", length = 30) public String getReportGetway() { return this.reportGetway; } public void setReportGetway(String reportGetway) { this.reportGetway = reportGetway; } @Column(name = "receiver_name", length = 20) public String getReceiverName() { return this.receiverName; } public void setReceiverName(String receiverName) { this.receiverName = receiverName; } @Column(name = "receiver_address", length = 300) public String getReceiverAddress() { return this.receiverAddress; } public void setReceiverAddress(String receiverAddress) { this.receiverAddress = receiverAddress; } @Column(name = "receiver_code", length = 10) public String getReceiverCode() { return this.receiverCode; } public void setReceiverCode(String receiverCode) { this.receiverCode = receiverCode; } @Column(name = "receiver_email", length = 50) public String getReceiverEmail() { return this.receiverEmail; } public void setReceiverEmail(String receiverEmail) { this.receiverEmail = receiverEmail; } @Column(name = "entruster", length = 100) public String getEntruster() { return this.entruster; } public void setEntruster(String entruster) { this.entruster = entruster; } @Column(name = "entruster_relation", length = 100) public String getEntrusterRelation() { return this.entrusterRelation; } public void setEntrusterRelation(String entrusterRelation) { this.entrusterRelation = entrusterRelation; } @Column(name = "entruster_num", length = 30) public String getEntrusterNum() { return this.entrusterNum; } public void setEntrusterNum(String entrusterNum) { this.entrusterNum = entrusterNum; } @Column(name = "linkman", length = 30) public String getLinkman() { return this.linkman; } public void setLinkman(String linkman) { this.linkman = linkman; } @Column(name = "linkman_tel", length = 30) public String getLinkmanTel() { return this.linkmanTel; } public void setLinkmanTel(String linkmanTel) { this.linkmanTel = linkmanTel; } @Column(name = "linkman_fax", length = 30) public String getLinkmanFax() { return this.linkmanFax; } public void setLinkmanFax(String linkmanFax) { this.linkmanFax = linkmanFax; } @Column(name = "identify_sender", length = 30) public String getIdentifySender() { return this.identifySender; } public void setIdentifySender(String identifySender) { this.identifySender = identifySender; } @Column(name = "insurance_unit", length = 100) public String getInsuranceUnit() { return this.insuranceUnit; } public void setInsuranceUnit(String insuranceUnit) { this.insuranceUnit = insuranceUnit; } @Column(name = "insurance_linkman", length = 30) public String getInsuranceLinkman() { return this.insuranceLinkman; } public void setInsuranceLinkman(String insuranceLinkman) { this.insuranceLinkman = insuranceLinkman; } @Column(name = "insurance_tel", length = 30) public String getInsuranceTel() { return this.insuranceTel; } public void setInsuranceTel(String insuranceTel) { this.insuranceTel = insuranceTel; } @Column(name = "insurance_email", length = 50) public String getInsuranceEmail() { return this.insuranceEmail; } public void setInsuranceEmail(String insuranceEmail) { this.insuranceEmail = insuranceEmail; } @Temporal(TemporalType.DATE) @Column(name = "case_date", length = 10) public Date getCaseDate() { return this.caseDate; } public void setCaseDate(Date caseDate) { this.caseDate = caseDate; } @Column(name = "case_class", length = 100) public String getCaseClass() { return this.caseClass; } public void setCaseClass(String caseClass) { this.caseClass = caseClass; } @Column(name = "case_identify_times") public Integer getCaseIdentifyTimes() { return this.caseIdentifyTimes; } public void setCaseIdentifyTimes(Integer caseIdentifyTimes) { this.caseIdentifyTimes = caseIdentifyTimes; } @Column(name = "case_progress", length = 100) public String getCaseProgress() { return this.caseProgress; } public void setCaseProgress(String caseProgress) { this.caseProgress = caseProgress; } @Column(name = "case_remark", length = 3000) public String getCaseRemark() { return this.caseRemark; } public void setCaseRemark(String caseRemark) { this.caseRemark = caseRemark; } @Column(name = "status", length = 100) public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseCheckInfor> getCaseCheckInfors() { return this.caseCheckInfors; } public void setCaseCheckInfors(Set<CaseCheckInfor> caseCheckInfors) { this.caseCheckInfors = caseCheckInfors; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseFile> getCaseFiles() { return this.caseFiles; } public void setCaseFiles(Set<CaseFile> caseFiles) { this.caseFiles = caseFiles; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseIdentifiedInfo> getCaseIdentifiedInfos() { return this.caseIdentifiedInfos; } public void setCaseIdentifiedInfos( Set<CaseIdentifiedInfo> caseIdentifiedInfos) { this.caseIdentifiedInfos = caseIdentifiedInfos; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseCharge> getCaseCharges() { return this.caseCharges; } public void setCaseCharges(Set<CaseCharge> caseCharges) { this.caseCharges = caseCharges; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "caseInfor") public Set<CaseInternalStatistics> getCaseInternalStatisticses() { return this.caseInternalStatisticses; } public void setCaseInternalStatisticses( Set<CaseInternalStatistics> caseInternalStatisticses) { this.caseInternalStatisticses = caseInternalStatisticses; } }
11,405
0.760368
0.754406
420
26.157143
21.484081
100
false
false
0
0
0
0
0
0
1.621429
false
false
12
d3e8149c62f2716d269b55ade1ab5be669719485
36,825,049,605,785
e274ca3f32563b764d3b1e0ab52b695454eae131
/Source Code (Hao Zheng 594644)/src/Tile.java
2a7aef9c8e72716f77a74f27bdeb0451ba8e9783
[]
no_license
zhenghao35791/Multi-Player-and-Multi-Server-Online-Game
https://github.com/zhenghao35791/Multi-Player-and-Multi-Server-Online-Game
f1445d33fcea244ba308cdda5ca01c31460f8cdb
af0958fded718a64942dd3bef3bfd3fbe0d9b586
refs/heads/master
2021-01-25T08:54:27.050000
2014-12-27T03:24:25
2014-12-27T03:24:25
28,527,473
4
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import java.util.HashMap; import java.util.List; import java.util.Map; /** * basic information of Tile * * @author hao * */ public class Tile extends Wall { int TileID = 1; public static final int WALL_X = 0; private int WIDTH = 50; private int HEIGHT = 50; public static int WALL_Y = 0; private String style; private TankClient tc; public boolean live = true; private int x, y; public int getX() { return x; } public void setX(int x) { this.x = x; } public Tile() { super(); } public Tile(int x, int y, String style, TankClient tc, int TileID) { super(x, y, style, tc); this.x = x; this.y = y; this.style = style; this.tc = tc; this.TileID = TileID; } public boolean getLive() { return live; } public void setLive(boolean live) { this.live = live; } String wallStyle = null; int step = 0; private static Toolkit tk = Toolkit.getDefaultToolkit(); private static Image[] wallImgs = null; private static Map<String, Image> imgs = new HashMap<String, Image>(); static {//import images that need wallImgs = new Image[] { tk.getImage(Wall.class.getClassLoader().getResource( "images/tile1.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile2.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile3.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile4.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile5.png")), }; imgs.put("tile1", wallImgs[0]); imgs.put("tile2", wallImgs[1]); imgs.put("tile3", wallImgs[2]); imgs.put("tile4", wallImgs[3]); imgs.put("tile5", wallImgs[4]); } boolean init = false; /* * draw all the walls due to different styles * @see Wall#draw(java.awt.Graphics, int, int) */ public void draw(Graphics g, int offsetX, int offsetY) { if (!this.live) { tc.tiles.remove(this); return; } if (!init) { for (int i = 0; i < wallImgs.length; i++) g.drawImage(wallImgs[i], -100, -100, null); init = true; } wallStyle = style; g.drawImage(imgs.get(wallStyle), this.x + offsetX, this.y + offsetY, null); if (("tile1".equals(style)) || ("tile2".equals(style)) || ("tile3".equals(style)) || ("tile4".equals(style)) || ("tile5".equals(style))) { this.coolidesWithMissiles(tc.missiles); this.collidesWithTank(tc.myTank); this.collidesWithTanks(tc.tanks); } } public Rectangle getRect() { return new Rectangle(x, y, WIDTH, HEIGHT); } /** * if missile hit a wall collision detection happens * @param missile * @return */ public boolean collidesWithMissile(Missile missile) { for (int i = 0; i < tc.tiles.size(); i++) { Tile tile = tc.tiles.get(i); if (tile.live && missile.isMissileLive() && tile.getRect().intersects(missile.getRect())) { tile.live = false; Explosion e = new Explosion(x, y, tc); tc.explosions.add(e); missile.setMissileLive(false); MissileDeadMessage missileDeadMessage = new MissileDeadMessage(//send missile dead message missile.tankID, missile.missileID); tc.ngc.send(missileDeadMessage); TILE_DEAD_MESSAGE tileDeadMessage = new TILE_DEAD_MESSAGE(// send tile dead message tile.TileID); tc.ngc.send(tileDeadMessage); return true; } } return false; } /** * whether missile hit the wall * * @param missiles * list to pu the missiles * @return boolaen hit or not */ public boolean coolidesWithMissiles(List<Missile> missiles) { for (int i = 0; i < missiles.size(); i++) { Missile missile = missiles.get(i); if (collidesWithMissile(missile)) return true; } return false; } public boolean collidesWithTank(Tank tank) { if (this.live && tank.TankLive() && this.getRect().intersects(tank.getRect())) { tank.stay(); return true; } return false; } public boolean collidesWithTanks(List<Tank> tanks) { for (int i = 0; i < tanks.size(); i++) { Tank tank = tanks.get(i); if (collidesWithTank(tank)) return true; } return false; } public String getStyle() { return style; } /** * if missile hit this(Wall), missile live is false * * @param m * because need to use variables in Missile * @return */ }
UTF-8
Java
4,383
java
Tile.java
Java
[ { "context": ";\n\n/**\n * basic information of Tile\n * \n * @author hao\n * \n */\npublic class Tile extends Wall {\n\tint Til", "end": 224, "score": 0.9712544083595276, "start": 221, "tag": "USERNAME", "value": "hao" } ]
null
[]
import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import java.util.HashMap; import java.util.List; import java.util.Map; /** * basic information of Tile * * @author hao * */ public class Tile extends Wall { int TileID = 1; public static final int WALL_X = 0; private int WIDTH = 50; private int HEIGHT = 50; public static int WALL_Y = 0; private String style; private TankClient tc; public boolean live = true; private int x, y; public int getX() { return x; } public void setX(int x) { this.x = x; } public Tile() { super(); } public Tile(int x, int y, String style, TankClient tc, int TileID) { super(x, y, style, tc); this.x = x; this.y = y; this.style = style; this.tc = tc; this.TileID = TileID; } public boolean getLive() { return live; } public void setLive(boolean live) { this.live = live; } String wallStyle = null; int step = 0; private static Toolkit tk = Toolkit.getDefaultToolkit(); private static Image[] wallImgs = null; private static Map<String, Image> imgs = new HashMap<String, Image>(); static {//import images that need wallImgs = new Image[] { tk.getImage(Wall.class.getClassLoader().getResource( "images/tile1.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile2.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile3.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile4.png")), tk.getImage(Wall.class.getClassLoader().getResource( "images/tile5.png")), }; imgs.put("tile1", wallImgs[0]); imgs.put("tile2", wallImgs[1]); imgs.put("tile3", wallImgs[2]); imgs.put("tile4", wallImgs[3]); imgs.put("tile5", wallImgs[4]); } boolean init = false; /* * draw all the walls due to different styles * @see Wall#draw(java.awt.Graphics, int, int) */ public void draw(Graphics g, int offsetX, int offsetY) { if (!this.live) { tc.tiles.remove(this); return; } if (!init) { for (int i = 0; i < wallImgs.length; i++) g.drawImage(wallImgs[i], -100, -100, null); init = true; } wallStyle = style; g.drawImage(imgs.get(wallStyle), this.x + offsetX, this.y + offsetY, null); if (("tile1".equals(style)) || ("tile2".equals(style)) || ("tile3".equals(style)) || ("tile4".equals(style)) || ("tile5".equals(style))) { this.coolidesWithMissiles(tc.missiles); this.collidesWithTank(tc.myTank); this.collidesWithTanks(tc.tanks); } } public Rectangle getRect() { return new Rectangle(x, y, WIDTH, HEIGHT); } /** * if missile hit a wall collision detection happens * @param missile * @return */ public boolean collidesWithMissile(Missile missile) { for (int i = 0; i < tc.tiles.size(); i++) { Tile tile = tc.tiles.get(i); if (tile.live && missile.isMissileLive() && tile.getRect().intersects(missile.getRect())) { tile.live = false; Explosion e = new Explosion(x, y, tc); tc.explosions.add(e); missile.setMissileLive(false); MissileDeadMessage missileDeadMessage = new MissileDeadMessage(//send missile dead message missile.tankID, missile.missileID); tc.ngc.send(missileDeadMessage); TILE_DEAD_MESSAGE tileDeadMessage = new TILE_DEAD_MESSAGE(// send tile dead message tile.TileID); tc.ngc.send(tileDeadMessage); return true; } } return false; } /** * whether missile hit the wall * * @param missiles * list to pu the missiles * @return boolaen hit or not */ public boolean coolidesWithMissiles(List<Missile> missiles) { for (int i = 0; i < missiles.size(); i++) { Missile missile = missiles.get(i); if (collidesWithMissile(missile)) return true; } return false; } public boolean collidesWithTank(Tank tank) { if (this.live && tank.TankLive() && this.getRect().intersects(tank.getRect())) { tank.stay(); return true; } return false; } public boolean collidesWithTanks(List<Tank> tanks) { for (int i = 0; i < tanks.size(); i++) { Tank tank = tanks.get(i); if (collidesWithTank(tank)) return true; } return false; } public String getStyle() { return style; } /** * if missile hit this(Wall), missile live is false * * @param m * because need to use variables in Missile * @return */ }
4,383
0.648414
0.639744
182
23.082418
19.573441
94
false
false
0
0
0
0
0
0
2.450549
false
false
12
be1f1a2910f749259a7b73d50e55451dff428865
13,108,240,247,033
264fcaa66358c5286451810ea0f9624ee571aa1d
/app/src/main/java/irishrail/sample/com/irishrailrealtime/data/request/GetStationsRequest.java
7aab49516f3eb7962fccce324f24dba2b68112c7
[]
no_license
evobrien/Samples
https://github.com/evobrien/Samples
4f83592a5a49ae888389578edd7bbe48d8d081ab
3848a13326109e02fa41f44332519769b06c3904
refs/heads/master
2016-08-11T06:53:19.715000
2016-01-11T11:02:22
2016-01-11T11:02:22
49,420,233
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package irishrail.sample.com.irishrailrealtime.data.request; import android.content.Context; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import irishrail.sample.com.irishrailrealtime.data.model.Stations; /** * Created by evano on 10/01/2016. */ public class GetStationsRequest extends BaseRequest<Stations> { protected String url="http://api.irishrail.ie/realtime/realtime.asmx/getAllStationsXML"; public GetStationsRequest(Context ctx, Response.Listener<Stations> responseListener, Response.ErrorListener errorListener) { super(ctx, responseListener, errorListener); } @Override public void execute() { XmlRequest request=new XmlRequest( Request.Method.GET, getUrl(), Stations.class, null, this.mResponseListener, this.mErrorListener); request.setTag(this.getClass().getName()); request.setShouldCache(false); request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestManager.getInstance().add(request); } private String getUrl(){ return this.url; } }
UTF-8
Java
1,417
java
GetStationsRequest.java
Java
[ { "context": "ilrealtime.data.model.Stations;\n\n/**\n * Created by evano on 10/01/2016.\n */\npublic class GetStationsReques", "end": 304, "score": 0.9965016841888428, "start": 299, "tag": "USERNAME", "value": "evano" } ]
null
[]
package irishrail.sample.com.irishrailrealtime.data.request; import android.content.Context; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import irishrail.sample.com.irishrailrealtime.data.model.Stations; /** * Created by evano on 10/01/2016. */ public class GetStationsRequest extends BaseRequest<Stations> { protected String url="http://api.irishrail.ie/realtime/realtime.asmx/getAllStationsXML"; public GetStationsRequest(Context ctx, Response.Listener<Stations> responseListener, Response.ErrorListener errorListener) { super(ctx, responseListener, errorListener); } @Override public void execute() { XmlRequest request=new XmlRequest( Request.Method.GET, getUrl(), Stations.class, null, this.mResponseListener, this.mErrorListener); request.setTag(this.getClass().getName()); request.setShouldCache(false); request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); RequestManager.getInstance().add(request); } private String getUrl(){ return this.url; } }
1,417
0.648553
0.642908
48
28.520834
25.655563
92
false
false
0
0
0
0
0
0
0.520833
false
false
3
0f7208150a1c335995d810ac0686105abb6173f5
29,867,202,602,796
a6b982ab5890c9ccd3049270e679ffcbba101cae
/src/main/java/com/ats/hrmgt/model/AssetCategory.java
000101eeb509d09629947bec19bd3804d50e1d50
[]
no_license
Aaryatech/HrEsayWebApiPune
https://github.com/Aaryatech/HrEsayWebApiPune
67d623b4bae75e4ae5e89985039de6194cfd66bb
f58236e95b42662b416857393324b0f55b431e01
refs/heads/master
2021-08-07T05:29:43.167000
2021-08-04T09:58:46
2021-08-04T09:58:46
243,730,457
0
0
null
false
2020-02-28T10:00:15
2020-02-28T09:56:36
2020-02-28T09:59:55
2020-02-28T10:00:14
0
0
0
1
Java
false
false
package com.ats.hrmgt.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "m_asset_category") public class AssetCategory { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int assetCatId; private String catName; private String catRemark; private int returnNotifctnDays; private int amcNotifctnDays; private int serviceNotifctnDays; private int serviceCycleDays; private int delStatus; private int makerUserId; private String updateDatetime; private int exInt1; private String exVar1; public int getAssetCatId() { return assetCatId; } public void setAssetCatId(int assetCatId) { this.assetCatId = assetCatId; } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } public String getCatRemark() { return catRemark; } public void setCatRemark(String catRemark) { this.catRemark = catRemark; } public int getReturnNotifctnDays() { return returnNotifctnDays; } public void setReturnNotifctnDays(int returnNotifctnDays) { this.returnNotifctnDays = returnNotifctnDays; } public int getAmcNotifctnDays() { return amcNotifctnDays; } public void setAmcNotifctnDays(int amcNotifctnDays) { this.amcNotifctnDays = amcNotifctnDays; } public int getServiceNotifctnDays() { return serviceNotifctnDays; } public void setServiceNotifctnDays(int serviceNotifctnDays) { this.serviceNotifctnDays = serviceNotifctnDays; } public int getServiceCycleDays() { return serviceCycleDays; } public void setServiceCycleDays(int serviceCycleDays) { this.serviceCycleDays = serviceCycleDays; } public int getDelStatus() { return delStatus; } public void setDelStatus(int delStatus) { this.delStatus = delStatus; } public int getMakerUserId() { return makerUserId; } public void setMakerUserId(int makerUserId) { this.makerUserId = makerUserId; } public String getUpdateDatetime() { return updateDatetime; } public void setUpdateDatetime(String updateDatetime) { this.updateDatetime = updateDatetime; } public int getExInt1() { return exInt1; } public void setExInt1(int exInt1) { this.exInt1 = exInt1; } public String getExVar1() { return exVar1; } public void setExVar1(String exVar1) { this.exVar1 = exVar1; } @Override public String toString() { return "AssetCategory [assetCatId=" + assetCatId + ", catName=" + catName + ", catRemark=" + catRemark + ", returnNotifctnDays=" + returnNotifctnDays + ", amcNotifctnDays=" + amcNotifctnDays + ", serviceNotifctnDays=" + serviceNotifctnDays + ", serviceCycleDays=" + serviceCycleDays + ", delStatus=" + delStatus + ", makerUserId=" + makerUserId + ", updateDatetime=" + updateDatetime + ", exInt1=" + exInt1 + ", exVar1=" + exVar1 + "]"; } }
UTF-8
Java
2,920
java
AssetCategory.java
Java
[]
null
[]
package com.ats.hrmgt.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "m_asset_category") public class AssetCategory { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int assetCatId; private String catName; private String catRemark; private int returnNotifctnDays; private int amcNotifctnDays; private int serviceNotifctnDays; private int serviceCycleDays; private int delStatus; private int makerUserId; private String updateDatetime; private int exInt1; private String exVar1; public int getAssetCatId() { return assetCatId; } public void setAssetCatId(int assetCatId) { this.assetCatId = assetCatId; } public String getCatName() { return catName; } public void setCatName(String catName) { this.catName = catName; } public String getCatRemark() { return catRemark; } public void setCatRemark(String catRemark) { this.catRemark = catRemark; } public int getReturnNotifctnDays() { return returnNotifctnDays; } public void setReturnNotifctnDays(int returnNotifctnDays) { this.returnNotifctnDays = returnNotifctnDays; } public int getAmcNotifctnDays() { return amcNotifctnDays; } public void setAmcNotifctnDays(int amcNotifctnDays) { this.amcNotifctnDays = amcNotifctnDays; } public int getServiceNotifctnDays() { return serviceNotifctnDays; } public void setServiceNotifctnDays(int serviceNotifctnDays) { this.serviceNotifctnDays = serviceNotifctnDays; } public int getServiceCycleDays() { return serviceCycleDays; } public void setServiceCycleDays(int serviceCycleDays) { this.serviceCycleDays = serviceCycleDays; } public int getDelStatus() { return delStatus; } public void setDelStatus(int delStatus) { this.delStatus = delStatus; } public int getMakerUserId() { return makerUserId; } public void setMakerUserId(int makerUserId) { this.makerUserId = makerUserId; } public String getUpdateDatetime() { return updateDatetime; } public void setUpdateDatetime(String updateDatetime) { this.updateDatetime = updateDatetime; } public int getExInt1() { return exInt1; } public void setExInt1(int exInt1) { this.exInt1 = exInt1; } public String getExVar1() { return exVar1; } public void setExVar1(String exVar1) { this.exVar1 = exVar1; } @Override public String toString() { return "AssetCategory [assetCatId=" + assetCatId + ", catName=" + catName + ", catRemark=" + catRemark + ", returnNotifctnDays=" + returnNotifctnDays + ", amcNotifctnDays=" + amcNotifctnDays + ", serviceNotifctnDays=" + serviceNotifctnDays + ", serviceCycleDays=" + serviceCycleDays + ", delStatus=" + delStatus + ", makerUserId=" + makerUserId + ", updateDatetime=" + updateDatetime + ", exInt1=" + exInt1 + ", exVar1=" + exVar1 + "]"; } }
2,920
0.749315
0.743151
109
25.78899
21.896786
104
false
false
0
0
0
0
0
0
1.715596
false
false
3
ec6f4f895895c4bad7fc4dd3d9d043d0594456d6
18,854,906,467,876
9389f7ec2992a8eba5b1ed2b19b8216b4067e224
/service/src/main/java/org/openo/drivermgr/dao/inf/IDriverManagerDao.java
aa26b1e897a164c5feb017f56978b7efd6101723
[]
no_license
openov2/common-services-driver-mgr
https://github.com/openov2/common-services-driver-mgr
fb3a8d31d90b91ef44f27c08becf693bdb011517
29cbfaec5786bc5d83e787b53fcb6abce4b72a16
refs/heads/master
2021-05-06T05:42:05.569000
2017-03-22T03:53:15
2017-03-22T03:53:23
115,205,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2016 Huawei Technologies Co., Ltd. * * 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.openo.drivermgr.dao.inf; import java.util.List; import org.openo.drivermgr.entity.DriverInstance; import org.openo.drivermgr.entity.DriverService; /** * DAO Layer for the Driver Manager Service. * <br/> * * @author * @version */ public interface IDriverManagerDao { /** * saving the driver instance object to the DB using the mybaties. * <br/> * * @param dirverInstance * @since */ void saveDriverInstance(DriverInstance dirverInstance); /** * saving the driver service object to the DB using the mybaties. * <br/> * * @param driverService * @since */ void saveDriverService(DriverService driverService); /** * delete the driver instance object from the DB * <br/> * * @param instanceId * @since */ void deleteDriverInstance(String instanceId); /** * delete the driver service by instanceid * <br/> * * @param instanceId * @since */ void deleteDriverService(String instanceId); /** * get the driver instance object by the instanceId. * <br/> * * @param instanceId * @return * @since */ DriverInstance getDriverByInstanceId(String instanceId); /** * get the driver service object by the serviceUrl * <br/> * * @param serviceUrl * @return * @since */ List<DriverService> getDriverServiceByUrl(String serviceUrl); /** * get all driver instance. * <br/> * * @return * @since */ List<DriverInstance> getAllDriverInstance(); }
UTF-8
Java
2,273
java
IDriverManagerDao.java
Java
[]
null
[]
/* * Copyright 2016 Huawei Technologies Co., Ltd. * * 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.openo.drivermgr.dao.inf; import java.util.List; import org.openo.drivermgr.entity.DriverInstance; import org.openo.drivermgr.entity.DriverService; /** * DAO Layer for the Driver Manager Service. * <br/> * * @author * @version */ public interface IDriverManagerDao { /** * saving the driver instance object to the DB using the mybaties. * <br/> * * @param dirverInstance * @since */ void saveDriverInstance(DriverInstance dirverInstance); /** * saving the driver service object to the DB using the mybaties. * <br/> * * @param driverService * @since */ void saveDriverService(DriverService driverService); /** * delete the driver instance object from the DB * <br/> * * @param instanceId * @since */ void deleteDriverInstance(String instanceId); /** * delete the driver service by instanceid * <br/> * * @param instanceId * @since */ void deleteDriverService(String instanceId); /** * get the driver instance object by the instanceId. * <br/> * * @param instanceId * @return * @since */ DriverInstance getDriverByInstanceId(String instanceId); /** * get the driver service object by the serviceUrl * <br/> * * @param serviceUrl * @return * @since */ List<DriverService> getDriverServiceByUrl(String serviceUrl); /** * get all driver instance. * <br/> * * @return * @since */ List<DriverInstance> getAllDriverInstance(); }
2,273
0.626925
0.623405
98
22.193878
22.489298
75
false
false
0
0
0
0
0
0
0.173469
false
false
3
ca8cf0f065cc60be60c2946f6ef0e5a26d37c652
30,313,879,179,252
1366953d30c8441a4061ab36ede4f1630540b75b
/app/src/main/java/br/com/sistemasecia/consultaprodutos/ListaProdutosActivity.java
2f7a9ce44e34e35cdbe14b882aa6d2ce55589fa0
[]
no_license
GBMeinchein/ListaProdutosAndroid
https://github.com/GBMeinchein/ListaProdutosAndroid
3121a901e50af72875710738ca756f4db23725c2
9fcbdef177ed73a050edf69882502f4a512d7645
refs/heads/master
2016-09-06T16:29:27.276000
2015-04-24T17:16:26
2015-04-24T17:16:26
34,458,286
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.sistemasecia.consultaprodutos; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Filter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * Created by maq8 on 18/03/2015. */ //Classe da lista dos produtos public class ListaProdutosActivity extends Activity { AdaptadorProdutos<Produto> adaptador = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button btLimpa = (Button) findViewById(R.id.btLimpa); final EditText etFiltraProduto = (EditText) findViewById(R.id.etProduto); final DbHelper dbHelper = new DbHelper(this); ArrayList<Produto> itens = new ArrayList<Produto>(); final ListView lista = (ListView) findViewById(R.id.lvListaProdutos); //array itens recebe todos os produtos do banco de dados itens = dbHelper.selectTodosProdutosArray(); //adaptador, da calsse AdaptadorProdutos que vai receber a lista de itens, //para depois passar seus dados para o listview adaptador = new AdaptadorProdutos<Produto>(itens); //seta para o lista(listview da tela) o adapter com a lista de produtos lista.setAdapter(adaptador); btLimpa.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etFiltraProduto.setText(""); } }); etFiltraProduto.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //sempre filtra o adaptador quando o texto do filtro é mudado adaptador.getFilter().filter(s.toString()); } @Override public void afterTextChanged(Editable s) { } }); } //classe adaptador adaptador produtos para customizar o adapter, para deixar com duas linhas class AdaptadorProdutos<T> extends ArrayAdapter { String prefix1, prefix2, prefix3 = "", prefix4 = "", prefix5 = ""; String prefixAux; int tamanho; String valor, valorSemUltimaVirgula, primeiroCaracter; //Itens de exibição / filtrados private List<Produto> itens_exibicao; //Essa lista contem todos os itens. private List<Produto> itens; //Utilizado no getView para carregar e construir um item. private LayoutInflater layoutInflater; //private ArrayList<T> mOriginalValues = (ArrayList<T>) listaProdutos; AdaptadorProdutos(Context context, int resource) { super(context, resource, 0, new ArrayList<T>()); } public AdaptadorProdutos(List<Produto> itens) { super(ListaProdutosActivity.this, R.layout.activity_lista, itens); this.itens_exibicao = itens; this.itens = itens; } public AdaptadorProdutos(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId, new ArrayList<T>()); } public AdaptadorProdutos(Context context, int resource, List<Produto> itens) { super(context, resource, 0, Arrays.asList(itens)); this.itens = itens; this.itens_exibicao = itens; layoutInflater = LayoutInflater.from(context); } public AdaptadorProdutos(Context context, int resource, int textViewResourceId, T[] objects) { super(context, resource, textViewResourceId, Arrays.asList(objects)); } public View getView(int arg0, View arg1, ViewGroup arg2) { View linha = arg1; ArmazenadorProdutos armazenador = null; if (linha == null) { LayoutInflater inflater = getLayoutInflater(); linha = inflater.inflate(R.layout.activity_lista, arg2, false); armazenador = new ArmazenadorProdutos(linha); linha.setTag(armazenador); } else { armazenador = (ArmazenadorProdutos) linha.getTag(); } armazenador.popularFormulario(itens_exibicao.get(arg0)); return linha; } @Override public int getCount() { return itens_exibicao.size(); } @Override public Object getItem(int arg0) { return itens_exibicao.get(arg0); } public Filter getFilter() { Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence filtro) { FilterResults results = new FilterResults(); //se não foi realizado nenhum filtro insere todos os itens. if (filtro == null || filtro.length() == 0) { results.count = itens.size(); results.values = itens; } else { prefixAux = filtro.toString(); tamanho = prefixAux.length(); valor = prefixAux.substring(tamanho - 1, tamanho); primeiroCaracter = prefixAux.substring(0, 1); valorSemUltimaVirgula = prefixAux.substring(0, tamanho - 1); int numeroDeVirgulas = 0; boolean segundaVirgula = false; filtro = filtro.toString().toLowerCase(); if (filtro.toString().contains(",") && primeiroCaracter.equals(",") == false && (valor.equals(",") == false || valorSemUltimaVirgula.contains(","))) { //cria um array para armazenar os objetos filtrados. List<Produto> itens_filtrados = new ArrayList<Produto>(); for(int x = 0, y = 1; y < tamanho; x++, y++){ if(prefixAux.substring(x, y).equals(",")){ numeroDeVirgulas = numeroDeVirgulas + 1; } } if(numeroDeVirgulas < 4) { //Toast.makeText(getContext(), String.valueOf(numeroDeVirgulas)+String.valueOf(tamanho), Toast.LENGTH_SHORT).show(); Scanner scan = new Scanner(filtro.toString()).useDelimiter(","); while (scan.hasNext()) { prefix1 = scan.next(); prefix2 = scan.next(); if (numeroDeVirgulas > 1) { segundaVirgula = true; prefix3 = scan.next(); } if (numeroDeVirgulas > 2) { prefix4 = scan.next(); } if (numeroDeVirgulas > 3) { prefix5 = scan.next(); } // Toast.makeText(getContext(),prefix1 + prefix2, Toast.LENGTH_SHORT).show(); } scan.close(); }else{ Toast.makeText(getContext(), "Não é possível utilizar mais de quatro vírgulas para o filtro!", Toast.LENGTH_SHORT).show(); } //percorre toda lista verificando se contem a palavra do filtro na descricao do objeto. for (int i = 0; i < itens.size() - 1; i++) { Produto data = itens.get(i); filtro = filtro.toString().toLowerCase(); String condicao = data.getDescricao().toLowerCase(); if (condicao.contains(prefix1) && condicao.contains(prefix2) && (condicao.contains(prefix3) || numeroDeVirgulas <= 1) && (condicao.contains(prefix4) || numeroDeVirgulas <= 2) && (condicao.contains(prefix5) || numeroDeVirgulas <= 3)) { //se conter adiciona na lista de itens filtrados. itens_filtrados.add(data); } } // Define o resultado do filtro na variavel FilterResults results.count = itens_filtrados.size(); results.values = itens_filtrados; }else if (segundaVirgula == false){ //cria um array para armazenar os objetos filtrados. List<Produto> itens_filtrados = new ArrayList<Produto>(); String filtroAux = filtro.toString(); if(valor.equals(",")){ filtro = filtroAux.substring(0, tamanho-1); } //percorre toda lista verificando se contem a palavra do filtro na descricao do objeto. for (int i = 0; i < itens.size() - 1; i++) { Produto data = itens.get(i); filtro = filtro.toString().toLowerCase(); String condicao = data.getDescricao().toLowerCase(); if (condicao.contains(filtro)) { //se conter adiciona na lista de itens filtrados. itens_filtrados.add(data); } } // Define o resultado do filtro na variavel FilterResults results.count = itens_filtrados.size(); results.values = itens_filtrados; } } return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, Filter.FilterResults results) { itens_exibicao = (List<Produto>) results.values; // Valores filtrados. notifyDataSetChanged(); // Notifica a lista de alteração } }; return filter; } } //classe que com as duas linhas do listview e recebe a descriçao e os demais dados static class ArmazenadorProdutos { private TextView nome; private TextView codigo; ArmazenadorProdutos(View linha) { nome = (TextView) linha.findViewById(R.id.descricao); codigo = (TextView) linha.findViewById(R.id.detalhes); } void popularFormulario(Produto r) { nome.setText(r.getDescricao()); codigo.setText(r.toString()); } } }
UTF-8
Java
11,878
java
ListaProdutosActivity.java
Java
[ { "context": "List;\nimport java.util.Scanner;\n\n/**\n * Created by maq8 on 18/03/2015.\n */\n//Classe da lista dos produtos", "end": 774, "score": 0.9996137022972107, "start": 770, "tag": "USERNAME", "value": "maq8" } ]
null
[]
package br.com.sistemasecia.consultaprodutos; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Filter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * Created by maq8 on 18/03/2015. */ //Classe da lista dos produtos public class ListaProdutosActivity extends Activity { AdaptadorProdutos<Produto> adaptador = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button btLimpa = (Button) findViewById(R.id.btLimpa); final EditText etFiltraProduto = (EditText) findViewById(R.id.etProduto); final DbHelper dbHelper = new DbHelper(this); ArrayList<Produto> itens = new ArrayList<Produto>(); final ListView lista = (ListView) findViewById(R.id.lvListaProdutos); //array itens recebe todos os produtos do banco de dados itens = dbHelper.selectTodosProdutosArray(); //adaptador, da calsse AdaptadorProdutos que vai receber a lista de itens, //para depois passar seus dados para o listview adaptador = new AdaptadorProdutos<Produto>(itens); //seta para o lista(listview da tela) o adapter com a lista de produtos lista.setAdapter(adaptador); btLimpa.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { etFiltraProduto.setText(""); } }); etFiltraProduto.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { //sempre filtra o adaptador quando o texto do filtro é mudado adaptador.getFilter().filter(s.toString()); } @Override public void afterTextChanged(Editable s) { } }); } //classe adaptador adaptador produtos para customizar o adapter, para deixar com duas linhas class AdaptadorProdutos<T> extends ArrayAdapter { String prefix1, prefix2, prefix3 = "", prefix4 = "", prefix5 = ""; String prefixAux; int tamanho; String valor, valorSemUltimaVirgula, primeiroCaracter; //Itens de exibição / filtrados private List<Produto> itens_exibicao; //Essa lista contem todos os itens. private List<Produto> itens; //Utilizado no getView para carregar e construir um item. private LayoutInflater layoutInflater; //private ArrayList<T> mOriginalValues = (ArrayList<T>) listaProdutos; AdaptadorProdutos(Context context, int resource) { super(context, resource, 0, new ArrayList<T>()); } public AdaptadorProdutos(List<Produto> itens) { super(ListaProdutosActivity.this, R.layout.activity_lista, itens); this.itens_exibicao = itens; this.itens = itens; } public AdaptadorProdutos(Context context, int resource, int textViewResourceId) { super(context, resource, textViewResourceId, new ArrayList<T>()); } public AdaptadorProdutos(Context context, int resource, List<Produto> itens) { super(context, resource, 0, Arrays.asList(itens)); this.itens = itens; this.itens_exibicao = itens; layoutInflater = LayoutInflater.from(context); } public AdaptadorProdutos(Context context, int resource, int textViewResourceId, T[] objects) { super(context, resource, textViewResourceId, Arrays.asList(objects)); } public View getView(int arg0, View arg1, ViewGroup arg2) { View linha = arg1; ArmazenadorProdutos armazenador = null; if (linha == null) { LayoutInflater inflater = getLayoutInflater(); linha = inflater.inflate(R.layout.activity_lista, arg2, false); armazenador = new ArmazenadorProdutos(linha); linha.setTag(armazenador); } else { armazenador = (ArmazenadorProdutos) linha.getTag(); } armazenador.popularFormulario(itens_exibicao.get(arg0)); return linha; } @Override public int getCount() { return itens_exibicao.size(); } @Override public Object getItem(int arg0) { return itens_exibicao.get(arg0); } public Filter getFilter() { Filter filter = new Filter() { @Override protected FilterResults performFiltering(CharSequence filtro) { FilterResults results = new FilterResults(); //se não foi realizado nenhum filtro insere todos os itens. if (filtro == null || filtro.length() == 0) { results.count = itens.size(); results.values = itens; } else { prefixAux = filtro.toString(); tamanho = prefixAux.length(); valor = prefixAux.substring(tamanho - 1, tamanho); primeiroCaracter = prefixAux.substring(0, 1); valorSemUltimaVirgula = prefixAux.substring(0, tamanho - 1); int numeroDeVirgulas = 0; boolean segundaVirgula = false; filtro = filtro.toString().toLowerCase(); if (filtro.toString().contains(",") && primeiroCaracter.equals(",") == false && (valor.equals(",") == false || valorSemUltimaVirgula.contains(","))) { //cria um array para armazenar os objetos filtrados. List<Produto> itens_filtrados = new ArrayList<Produto>(); for(int x = 0, y = 1; y < tamanho; x++, y++){ if(prefixAux.substring(x, y).equals(",")){ numeroDeVirgulas = numeroDeVirgulas + 1; } } if(numeroDeVirgulas < 4) { //Toast.makeText(getContext(), String.valueOf(numeroDeVirgulas)+String.valueOf(tamanho), Toast.LENGTH_SHORT).show(); Scanner scan = new Scanner(filtro.toString()).useDelimiter(","); while (scan.hasNext()) { prefix1 = scan.next(); prefix2 = scan.next(); if (numeroDeVirgulas > 1) { segundaVirgula = true; prefix3 = scan.next(); } if (numeroDeVirgulas > 2) { prefix4 = scan.next(); } if (numeroDeVirgulas > 3) { prefix5 = scan.next(); } // Toast.makeText(getContext(),prefix1 + prefix2, Toast.LENGTH_SHORT).show(); } scan.close(); }else{ Toast.makeText(getContext(), "Não é possível utilizar mais de quatro vírgulas para o filtro!", Toast.LENGTH_SHORT).show(); } //percorre toda lista verificando se contem a palavra do filtro na descricao do objeto. for (int i = 0; i < itens.size() - 1; i++) { Produto data = itens.get(i); filtro = filtro.toString().toLowerCase(); String condicao = data.getDescricao().toLowerCase(); if (condicao.contains(prefix1) && condicao.contains(prefix2) && (condicao.contains(prefix3) || numeroDeVirgulas <= 1) && (condicao.contains(prefix4) || numeroDeVirgulas <= 2) && (condicao.contains(prefix5) || numeroDeVirgulas <= 3)) { //se conter adiciona na lista de itens filtrados. itens_filtrados.add(data); } } // Define o resultado do filtro na variavel FilterResults results.count = itens_filtrados.size(); results.values = itens_filtrados; }else if (segundaVirgula == false){ //cria um array para armazenar os objetos filtrados. List<Produto> itens_filtrados = new ArrayList<Produto>(); String filtroAux = filtro.toString(); if(valor.equals(",")){ filtro = filtroAux.substring(0, tamanho-1); } //percorre toda lista verificando se contem a palavra do filtro na descricao do objeto. for (int i = 0; i < itens.size() - 1; i++) { Produto data = itens.get(i); filtro = filtro.toString().toLowerCase(); String condicao = data.getDescricao().toLowerCase(); if (condicao.contains(filtro)) { //se conter adiciona na lista de itens filtrados. itens_filtrados.add(data); } } // Define o resultado do filtro na variavel FilterResults results.count = itens_filtrados.size(); results.values = itens_filtrados; } } return results; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, Filter.FilterResults results) { itens_exibicao = (List<Produto>) results.values; // Valores filtrados. notifyDataSetChanged(); // Notifica a lista de alteração } }; return filter; } } //classe que com as duas linhas do listview e recebe a descriçao e os demais dados static class ArmazenadorProdutos { private TextView nome; private TextView codigo; ArmazenadorProdutos(View linha) { nome = (TextView) linha.findViewById(R.id.descricao); codigo = (TextView) linha.findViewById(R.id.detalhes); } void popularFormulario(Produto r) { nome.setText(r.getDescricao()); codigo.setText(r.toString()); } } }
11,878
0.529199
0.524227
278
41.679855
34.431274
266
false
false
0
0
0
0
0
0
0.705036
false
false
3
9bc0d2f80444f35b59f6ef2ee64a793be866845a
30,313,879,178,350
49b0d49023f3f57209c8e027f71723e4c5da7f5b
/src/gr/uom/jcaliper/metrics/ep/EPCalculator.java
8bb259462ac8538af2894c3d6691049449ae1e54
[]
no_license
teohaik/jcaliper
https://github.com/teohaik/jcaliper
ff27dc0b7e4f38132e5cc12e035735c41b0ba5b7
9c59e760980b6672022c7f81caeda198224e8174
refs/heads/master
2021-01-10T02:28:27.050000
2020-03-15T18:03:56
2020-03-15T18:03:56
50,365,388
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package gr.uom.jcaliper.metrics.ep; import gr.uom.jcaliper.metrics.Metric; import gr.uom.jcaliper.metrics.MetricCalculator; import gr.uom.jcaliper.preferences.Preferences; import gr.uom.jcaliper.system.CratEntity; import gr.uom.jcaliper.system.EntitySet; import gr.uom.jcaliper.system.HashedClass; import gr.uom.jcaliper.system.IEntityPool; /** * Data structures designed to speed up Entity Placement calculation * * @author Panagiotis Kouros */ public abstract class EPCalculator extends MetricCalculator { protected final IEntityPool entities; protected final int nEntities; protected EntitySet internalRelatives; protected EntitySet externalRelatives; protected EntitySet welcome = new EntitySet(); protected EPCalculator(HashedClass prototype, Metric metric) { super(prototype, metric); entities = metric.getCraCase(); nEntities = metric.getCraCase().getTotalEntities(); initializeRelatives(); } // Implemented methods @Override protected void calculateClassEvaluation() { evaluation = calculateClassEvaluation(this, internalRelatives, externalRelatives); } @Override protected void calculateMoveGains() { initializeWelcome(); for (int entId : exitCandidates()) exitGain.put(entId, exitGainOf(entId)); for (int entId : entryCandidates()) entryGain.put(entId, entryGainOf(entId)); } // Abstract methods protected abstract void initializeWelcome(); protected abstract double calculateClassEvaluation(EntitySet theClass, EntitySet intRelatives, EntitySet extRelatives); // EntitySets: Relatives and Welcome private final void initializeRelatives() { EntitySet relatives = new EntitySet(); for (int entityId : this) { CratEntity entity = entities.getEntity(entityId); relatives.addAll(entity.getRelatives()); } internalRelatives = intersection(relatives); externalRelatives = relatives.difference(internalRelatives); } // Entities candidate to be moved private final EntitySet exitCandidates() { EntitySet candidates = new EntitySet(); for (int entId : this) if (entities.getEntity(entId).isMovable()) candidates.add(entId); return candidates; } private final EntitySet entryCandidates() { EntitySet candidates = new EntitySet(); for (int entId : welcome) if (entities.getEntity(entId).isMovable()) candidates.add(entId); return candidates; } // Concrete calculation methods protected final double innerDistancesTotal(EntitySet theClass, EntitySet intRelatives) { int classSize = theClass.size() - 1; // exclude the measured entity double innerSimilaritiesTotal = 0.0; for (int entId : intRelatives) innerSimilaritiesTotal += similarity(entId, theClass, classSize); double innerDistancesTotal = theClass.size() - innerSimilaritiesTotal; if (PRINT_DEBUG_INFO) System.out.format("\t\tInnerDistance = (%d-%8.6f)/%d = %8.6f\n", theClass.size(), innerSimilaritiesTotal, theClass.size(), innerDistancesTotal / theClass.size()); return innerDistancesTotal; } protected final double outerDistancesTotal(EntitySet theClass, EntitySet extRelatives, int nExternal) { int classSize = theClass.size(); // the full class size double outerSimilaritiesTotal = 0.0; for (int entId : extRelatives) outerSimilaritiesTotal += similarity(entId, theClass, classSize); double outerDistancesTotal = nExternal - outerSimilaritiesTotal; if (outerDistancesTotal < 1e-10) // if is 0 outerDistancesTotal = 1.0 / nEntities; // set it to any too small number if (PRINT_DEBUG_INFO) System.out.format("\t\tOuterDistance = (%d-%8.6f)/%d = %8.6f\n", nExternal, outerSimilaritiesTotal, nExternal, outerDistancesTotal / nExternal); return outerDistancesTotal; } protected final double similarity(int entId, EntitySet theClass, int classSize) { EntitySet entitySet = entities.getEntity(entId).getEntitySet(); int intersectionSize = theClass.intersection(entitySet).size(); if (intersectionSize == 0) return 0.0; int unionSize = (classSize + entitySet.size()) - intersectionSize; double similarity = ((double) intersectionSize) / unionSize; if (PRINT_DEBUG_INFO) System.out.format("\t\t\tsim(%d,%s) = %d/%d = %8.6f\t\tS(%d)=%s\n", entId, theClass, intersectionSize, unionSize, similarity, entId, entitySet); return similarity; } private final double exitGainOf(int moving) { if (PRINT_DEBUG_INFO) System.out.format("\t\tcalculating exit gain of %d...\n", moving); // Construct the resulting new class EntitySet newClass = without(moving); long hash = newClass.calculateHash(); // Try to get a known class evaluation Double newEvaluation = metric.getStoredValue(hash); // If not available, calculate and store it if (newEvaluation == null) { EntitySet newIntRelatives = internalRelatives.without(moving); EntitySet newExtRelatives = externalRelatives.plus(moving); newEvaluation = calculateClassEvaluation(newClass, newIntRelatives, newExtRelatives); metric.storeValue(hash, newEvaluation); } if (PRINT_DEBUG_INFO) System.out.format("\t\texit gain of %d = %8.6f\n", moving, newEvaluation - evaluation); return (newEvaluation - evaluation); } private final double entryGainOf(int moving) { if (PRINT_DEBUG_INFO) System.out.format("\t\tcalculating entry gain of %d...\n", moving); // Construct the resulting new class EntitySet newClass = plus(moving); long hash = newClass.calculateHash(); // Try to get a known class evaluation Double newEvaluation = metric.getStoredValue(hash); // If not available, calculate and store it if (newEvaluation == null) { EntitySet entityRelatives = entities.getEntity(moving).getRelatives(); EntitySet newIntRelatives = entityRelatives.intersection(newClass); newIntRelatives.addAll(internalRelatives); newIntRelatives.add(moving); EntitySet newExtRelatives = entityRelatives.difference(newClass); newExtRelatives.addAll(externalRelatives); newExtRelatives.remove(moving); newEvaluation = calculateClassEvaluation(newClass, newIntRelatives, newExtRelatives); metric.storeValue(hash, newEvaluation); } if (PRINT_DEBUG_INFO) System.out.format("\t\tentry gain of %d = %8.6f\n", moving, newEvaluation - evaluation); return (newEvaluation - evaluation); } // Don't modify next line. Change the static value in class Preferences private static final boolean PRINT_DEBUG_INFO = Preferences.PRINT_DEBUG_INFO; private static final long serialVersionUID = 1L; }
UTF-8
Java
6,454
java
EPCalculator.java
Java
[ { "context": "eed up Entity Placement calculation\n * \n * @author Panagiotis Kouros\n */\npublic abstract class EPCalculator extends Me", "end": 448, "score": 0.9998680949211121, "start": 431, "tag": "NAME", "value": "Panagiotis Kouros" } ]
null
[]
package gr.uom.jcaliper.metrics.ep; import gr.uom.jcaliper.metrics.Metric; import gr.uom.jcaliper.metrics.MetricCalculator; import gr.uom.jcaliper.preferences.Preferences; import gr.uom.jcaliper.system.CratEntity; import gr.uom.jcaliper.system.EntitySet; import gr.uom.jcaliper.system.HashedClass; import gr.uom.jcaliper.system.IEntityPool; /** * Data structures designed to speed up Entity Placement calculation * * @author <NAME> */ public abstract class EPCalculator extends MetricCalculator { protected final IEntityPool entities; protected final int nEntities; protected EntitySet internalRelatives; protected EntitySet externalRelatives; protected EntitySet welcome = new EntitySet(); protected EPCalculator(HashedClass prototype, Metric metric) { super(prototype, metric); entities = metric.getCraCase(); nEntities = metric.getCraCase().getTotalEntities(); initializeRelatives(); } // Implemented methods @Override protected void calculateClassEvaluation() { evaluation = calculateClassEvaluation(this, internalRelatives, externalRelatives); } @Override protected void calculateMoveGains() { initializeWelcome(); for (int entId : exitCandidates()) exitGain.put(entId, exitGainOf(entId)); for (int entId : entryCandidates()) entryGain.put(entId, entryGainOf(entId)); } // Abstract methods protected abstract void initializeWelcome(); protected abstract double calculateClassEvaluation(EntitySet theClass, EntitySet intRelatives, EntitySet extRelatives); // EntitySets: Relatives and Welcome private final void initializeRelatives() { EntitySet relatives = new EntitySet(); for (int entityId : this) { CratEntity entity = entities.getEntity(entityId); relatives.addAll(entity.getRelatives()); } internalRelatives = intersection(relatives); externalRelatives = relatives.difference(internalRelatives); } // Entities candidate to be moved private final EntitySet exitCandidates() { EntitySet candidates = new EntitySet(); for (int entId : this) if (entities.getEntity(entId).isMovable()) candidates.add(entId); return candidates; } private final EntitySet entryCandidates() { EntitySet candidates = new EntitySet(); for (int entId : welcome) if (entities.getEntity(entId).isMovable()) candidates.add(entId); return candidates; } // Concrete calculation methods protected final double innerDistancesTotal(EntitySet theClass, EntitySet intRelatives) { int classSize = theClass.size() - 1; // exclude the measured entity double innerSimilaritiesTotal = 0.0; for (int entId : intRelatives) innerSimilaritiesTotal += similarity(entId, theClass, classSize); double innerDistancesTotal = theClass.size() - innerSimilaritiesTotal; if (PRINT_DEBUG_INFO) System.out.format("\t\tInnerDistance = (%d-%8.6f)/%d = %8.6f\n", theClass.size(), innerSimilaritiesTotal, theClass.size(), innerDistancesTotal / theClass.size()); return innerDistancesTotal; } protected final double outerDistancesTotal(EntitySet theClass, EntitySet extRelatives, int nExternal) { int classSize = theClass.size(); // the full class size double outerSimilaritiesTotal = 0.0; for (int entId : extRelatives) outerSimilaritiesTotal += similarity(entId, theClass, classSize); double outerDistancesTotal = nExternal - outerSimilaritiesTotal; if (outerDistancesTotal < 1e-10) // if is 0 outerDistancesTotal = 1.0 / nEntities; // set it to any too small number if (PRINT_DEBUG_INFO) System.out.format("\t\tOuterDistance = (%d-%8.6f)/%d = %8.6f\n", nExternal, outerSimilaritiesTotal, nExternal, outerDistancesTotal / nExternal); return outerDistancesTotal; } protected final double similarity(int entId, EntitySet theClass, int classSize) { EntitySet entitySet = entities.getEntity(entId).getEntitySet(); int intersectionSize = theClass.intersection(entitySet).size(); if (intersectionSize == 0) return 0.0; int unionSize = (classSize + entitySet.size()) - intersectionSize; double similarity = ((double) intersectionSize) / unionSize; if (PRINT_DEBUG_INFO) System.out.format("\t\t\tsim(%d,%s) = %d/%d = %8.6f\t\tS(%d)=%s\n", entId, theClass, intersectionSize, unionSize, similarity, entId, entitySet); return similarity; } private final double exitGainOf(int moving) { if (PRINT_DEBUG_INFO) System.out.format("\t\tcalculating exit gain of %d...\n", moving); // Construct the resulting new class EntitySet newClass = without(moving); long hash = newClass.calculateHash(); // Try to get a known class evaluation Double newEvaluation = metric.getStoredValue(hash); // If not available, calculate and store it if (newEvaluation == null) { EntitySet newIntRelatives = internalRelatives.without(moving); EntitySet newExtRelatives = externalRelatives.plus(moving); newEvaluation = calculateClassEvaluation(newClass, newIntRelatives, newExtRelatives); metric.storeValue(hash, newEvaluation); } if (PRINT_DEBUG_INFO) System.out.format("\t\texit gain of %d = %8.6f\n", moving, newEvaluation - evaluation); return (newEvaluation - evaluation); } private final double entryGainOf(int moving) { if (PRINT_DEBUG_INFO) System.out.format("\t\tcalculating entry gain of %d...\n", moving); // Construct the resulting new class EntitySet newClass = plus(moving); long hash = newClass.calculateHash(); // Try to get a known class evaluation Double newEvaluation = metric.getStoredValue(hash); // If not available, calculate and store it if (newEvaluation == null) { EntitySet entityRelatives = entities.getEntity(moving).getRelatives(); EntitySet newIntRelatives = entityRelatives.intersection(newClass); newIntRelatives.addAll(internalRelatives); newIntRelatives.add(moving); EntitySet newExtRelatives = entityRelatives.difference(newClass); newExtRelatives.addAll(externalRelatives); newExtRelatives.remove(moving); newEvaluation = calculateClassEvaluation(newClass, newIntRelatives, newExtRelatives); metric.storeValue(hash, newEvaluation); } if (PRINT_DEBUG_INFO) System.out.format("\t\tentry gain of %d = %8.6f\n", moving, newEvaluation - evaluation); return (newEvaluation - evaluation); } // Don't modify next line. Change the static value in class Preferences private static final boolean PRINT_DEBUG_INFO = Preferences.PRINT_DEBUG_INFO; private static final long serialVersionUID = 1L; }
6,443
0.751162
0.746669
177
35.463276
26.263334
95
false
false
0
0
0
0
0
0
2.305085
false
false
3
2ffca196e4d0642dbeb099cd4c75b4fd3cf6a761
22,728,966,979,941
1dacc2b67b52d398bbe157e090984dd8554e37a8
/src/main/java/com/demo/share/headfirst/singleton/DoubleCheckSingleton.java
45d29f6a6aeee42f1924e737a68a8208089fc7fe
[]
no_license
yanghua0311/java-share
https://github.com/yanghua0311/java-share
329ec6dfb54b36b65acdd3c4678460ae3b0f77b6
aa341c90cd14e7241078018d8f5d483ecdccb8fd
refs/heads/master
2021-06-30T08:18:39.899000
2019-05-15T14:16:29
2019-05-15T14:16:29
146,375,454
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.demo.share.headfirst.singleton; /** * Created by youngwa on 2019/04/01. 21:43 */ public class DoubleCheckSingleton { private DoubleCheckSingleton(){ } private volatile static DoubleCheckSingleton singleton; public static DoubleCheckSingleton getInstance() { if (singleton == null) { synchronized(DoubleCheckSingleton.class) { //如果不为volatile保证happen-before原则,极度并发繁忙的情况下,cpu无法及时刷新前一个线程new的对象给予当前线程。 if (singleton == null) { singleton =new DoubleCheckSingleton(); } } } return singleton; } }
UTF-8
Java
724
java
DoubleCheckSingleton.java
Java
[ { "context": "demo.share.headfirst.singleton;\n\n/**\n * Created by youngwa on 2019/04/01. 21:43\n */\npublic class DoubleCheck", "end": 70, "score": 0.9995227456092834, "start": 63, "tag": "USERNAME", "value": "youngwa" } ]
null
[]
package com.demo.share.headfirst.singleton; /** * Created by youngwa on 2019/04/01. 21:43 */ public class DoubleCheckSingleton { private DoubleCheckSingleton(){ } private volatile static DoubleCheckSingleton singleton; public static DoubleCheckSingleton getInstance() { if (singleton == null) { synchronized(DoubleCheckSingleton.class) { //如果不为volatile保证happen-before原则,极度并发繁忙的情况下,cpu无法及时刷新前一个线程new的对象给予当前线程。 if (singleton == null) { singleton =new DoubleCheckSingleton(); } } } return singleton; } }
724
0.616822
0.598131
23
26.913044
24.077616
86
false
false
0
0
0
0
0
0
0.173913
false
false
3
610df2cba0d7c53fd2315cc076be9b8f163dca26
10,866,267,318,013
395528490e6dfc8fd3ff1785742b7eb3329f2b56
/framework/src/main/java/com/jossv/framework/dao/DaoFactoryImpl.java
2e2d86fe45d165f54403f41310e0d8b408249e4a
[]
no_license
userya/jossv
https://github.com/userya/jossv
eaff5e7d7582d2175f5ae602c16853d199ad0e0b
10c878ebbf10ece63ec3b98cef04322af17a76a0
refs/heads/master
2021-01-10T02:04:21.360000
2015-11-17T05:11:25
2015-11-17T05:11:25
46,174,198
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jossv.framework.dao; import java.util.Map; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.ConcurrentReferenceHashMap; import com.alibaba.druid.pool.DruidDataSource; import com.jossv.framework.dao.generator.ddl.SchemaGenerator; import com.jossv.framework.dao.model.DefineAble; public class DaoFactoryImpl implements DaoFactory { private EntityFactory entityFactory; private JdbcTemplate jdbcTemplate; private SchemaGenerator schemaGenerator; @SuppressWarnings("rawtypes") private Map<String, CommonDAO> daoMap = new ConcurrentReferenceHashMap<String, CommonDAO>(); public DaoFactoryImpl(EntityFactory entityFactory, DruidDataSource dataSource) { super(); this.entityFactory = entityFactory; this.jdbcTemplate = new JdbcTemplate(dataSource); schemaGenerator = new SchemaGenerator(); schemaGenerator.setUrl(dataSource.getUrl()); schemaGenerator.setUsername(dataSource.getUsername()); schemaGenerator.setPassword(dataSource.getPassword()); schemaGenerator.setDriver(dataSource.getDriverClassName()); schemaGenerator.setDialect("org.hibernate.dialect.MySQLDialect");// TODO } public <T> CommonDAO<T> getDAO(Class<T> clazz) { return getDAO(clazz, clazz.getName()); } @SuppressWarnings("unchecked") public <T> CommonDAO<T> getDAO(Class<T> clazz, String id) { if (!daoMap.containsKey(id)) { DefineAble da = null; if (entityFactory.contain(id)) { da = entityFactory.getEntity(id); } else { da = entityFactory.getTableFactory().getTable(id); } if (da != null) { CommonDAOImpl<T> dao = new CommonDAOImpl<T>(jdbcTemplate, entityFactory, da, clazz); daoMap.put(id, dao); } else { throw new RuntimeException("can not found id with :" + id); } } return daoMap.get(id); } public void remove(String id) { if (daoMap.containsKey(id)) { daoMap.remove(id); } } public SchemaGenerator getSchemaGenerator() { return schemaGenerator; } }
UTF-8
Java
1,970
java
DaoFactoryImpl.java
Java
[]
null
[]
package com.jossv.framework.dao; import java.util.Map; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.ConcurrentReferenceHashMap; import com.alibaba.druid.pool.DruidDataSource; import com.jossv.framework.dao.generator.ddl.SchemaGenerator; import com.jossv.framework.dao.model.DefineAble; public class DaoFactoryImpl implements DaoFactory { private EntityFactory entityFactory; private JdbcTemplate jdbcTemplate; private SchemaGenerator schemaGenerator; @SuppressWarnings("rawtypes") private Map<String, CommonDAO> daoMap = new ConcurrentReferenceHashMap<String, CommonDAO>(); public DaoFactoryImpl(EntityFactory entityFactory, DruidDataSource dataSource) { super(); this.entityFactory = entityFactory; this.jdbcTemplate = new JdbcTemplate(dataSource); schemaGenerator = new SchemaGenerator(); schemaGenerator.setUrl(dataSource.getUrl()); schemaGenerator.setUsername(dataSource.getUsername()); schemaGenerator.setPassword(dataSource.getPassword()); schemaGenerator.setDriver(dataSource.getDriverClassName()); schemaGenerator.setDialect("org.hibernate.dialect.MySQLDialect");// TODO } public <T> CommonDAO<T> getDAO(Class<T> clazz) { return getDAO(clazz, clazz.getName()); } @SuppressWarnings("unchecked") public <T> CommonDAO<T> getDAO(Class<T> clazz, String id) { if (!daoMap.containsKey(id)) { DefineAble da = null; if (entityFactory.contain(id)) { da = entityFactory.getEntity(id); } else { da = entityFactory.getTableFactory().getTable(id); } if (da != null) { CommonDAOImpl<T> dao = new CommonDAOImpl<T>(jdbcTemplate, entityFactory, da, clazz); daoMap.put(id, dao); } else { throw new RuntimeException("can not found id with :" + id); } } return daoMap.get(id); } public void remove(String id) { if (daoMap.containsKey(id)) { daoMap.remove(id); } } public SchemaGenerator getSchemaGenerator() { return schemaGenerator; } }
1,970
0.749239
0.749239
69
27.550724
25.262411
93
false
false
0
0
0
0
0
0
1.898551
false
false
3
606a851c3e303a7adb6c33fc0c833b864596131f
721,554,533,578
1aaa410bd2a140db46d72bb0b9948750bb8f0466
/L2J_Mobius_5.0_Salvation/dist/game/data/scripts/handlers/effecthandlers/AddHate.java
48d69968c5b685195bdc8311dbb6fccef5175c42
[]
no_license
destrodevianne/l2j_mobius
https://github.com/destrodevianne/l2j_mobius
36b3cf27456b3d658082ed94e68f4c61df5552cf
87016b911214b0b20148bc52b0764e0054725d33
refs/heads/master
2020-09-27T04:43:45.033000
2020-04-27T21:58:53
2020-04-27T21:58:53
226,417,180
2
4
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * This file is part of the L2J Mobius project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package handlers.effecthandlers; import org.l2jmobius.gameserver.model.StatSet; import org.l2jmobius.gameserver.model.actor.Attackable; import org.l2jmobius.gameserver.model.actor.Creature; import org.l2jmobius.gameserver.model.effects.AbstractEffect; import org.l2jmobius.gameserver.model.items.instance.ItemInstance; import org.l2jmobius.gameserver.model.skills.Skill; /** * Add Hate effect implementation. * @author Adry_85 */ public class AddHate extends AbstractEffect { private final double _power; private final boolean _affectSummoner; public AddHate(StatSet params) { _power = params.getDouble("power", 0); _affectSummoner = params.getBoolean("affectSummoner", false); } @Override public boolean isInstant() { return true; } @Override public void instant(Creature effector, Creature effected, Skill skill, ItemInstance item) { if (_affectSummoner && (effector.getSummoner() != null)) { effector = effector.getSummoner(); } if (!effected.isAttackable()) { return; } final double val = _power; if (val > 0) { ((Attackable) effected).addDamageHate(effector, 0, (int) val); effected.setRunning(); } else if (val < 0) { ((Attackable) effected).reduceHate(effector, (int) -val); } } }
UTF-8
Java
1,970
java
AddHate.java
Java
[ { "context": "\n/**\n * Add Hate effect implementation.\n * @author Adry_85\n */\npublic class AddHate extends AbstractEffect\n{", "end": 1135, "score": 0.9995372891426086, "start": 1128, "tag": "USERNAME", "value": "Adry_85" } ]
null
[]
/* * This file is part of the L2J Mobius project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package handlers.effecthandlers; import org.l2jmobius.gameserver.model.StatSet; import org.l2jmobius.gameserver.model.actor.Attackable; import org.l2jmobius.gameserver.model.actor.Creature; import org.l2jmobius.gameserver.model.effects.AbstractEffect; import org.l2jmobius.gameserver.model.items.instance.ItemInstance; import org.l2jmobius.gameserver.model.skills.Skill; /** * Add Hate effect implementation. * @author Adry_85 */ public class AddHate extends AbstractEffect { private final double _power; private final boolean _affectSummoner; public AddHate(StatSet params) { _power = params.getDouble("power", 0); _affectSummoner = params.getBoolean("affectSummoner", false); } @Override public boolean isInstant() { return true; } @Override public void instant(Creature effector, Creature effected, Skill skill, ItemInstance item) { if (_affectSummoner && (effector.getSummoner() != null)) { effector = effector.getSummoner(); } if (!effected.isAttackable()) { return; } final double val = _power; if (val > 0) { ((Attackable) effected).addDamageHate(effector, 0, (int) val); effected.setRunning(); } else if (val < 0) { ((Attackable) effected).reduceHate(effector, (int) -val); } } }
1,970
0.727411
0.720305
71
26.746479
26.270918
90
true
false
0
0
0
0
0
0
1.380282
false
false
3
4ff02a363a084e8c1f5935b57685978b4bfbc36c
6,296,422,071,613
da95d7c49917245c4f0623979436de9bfeb54e3b
/src/com/googlecode/lazyrecords/sql/grammars/SqlGrammar.java
8f2aa600e75c74da2f94e7e9d427bada49ee8b68
[]
no_license
igneco/lazyrecords
https://github.com/igneco/lazyrecords
d6cbf8168957de9d2445f9a11cd25c70f5972248
b7cd011541e672f2ccecfffe8b690f91d31a6a75
refs/heads/master
2021-01-11T21:24:23.415000
2016-03-30T05:33:53
2016-03-30T05:33:53
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.googlecode.lazyrecords.sql.grammars; import com.googlecode.lazyrecords.Aggregate; import com.googlecode.lazyrecords.AliasedKeyword; import com.googlecode.lazyrecords.CompositeKeyword; import com.googlecode.lazyrecords.Definition; import com.googlecode.lazyrecords.Join; import com.googlecode.lazyrecords.Joiner; import com.googlecode.lazyrecords.Keyword; import com.googlecode.lazyrecords.Record; import com.googlecode.lazyrecords.RecordTo; import com.googlecode.lazyrecords.sql.expressions.*; import com.googlecode.totallylazy.functions.Function1; import com.googlecode.totallylazy.Option; import com.googlecode.totallylazy.Pair; import com.googlecode.totallylazy.predicates.Predicate; import com.googlecode.totallylazy.Sequence; import java.util.Comparator; public interface SqlGrammar { SelectExpression selectExpression(Option<SetQuantifier> setQuantifier, Sequence<? extends Keyword<?>> selectList, Definition fromClause, Option<Predicate<? super Record>> whereClause, Option<Comparator<? super Record>> orderByClause, Option<Sequence<? extends Keyword<?>>> groupByClause, Option<Integer> offsetClause, Option<Integer> fetchClause); SelectList selectList(Sequence<? extends Keyword<?>> select); FromClause fromClause(Definition definition); WhereClause whereClause(Predicate<? super Record> where); OrderByClause orderByClause(Comparator<? super Record> orderBy); OffsetClause offsetClause(int number); FetchClause fetchClause(int number); GroupByClause groupByClause(Sequence<? extends Keyword<?>> columns); DerivedColumn derivedColumn(Function1<? super Record, ?> callable); ValueExpression valueExpression(Function1<? super Record, ?> callable); ValueExpression concat(Sequence<? extends Keyword<?>> keywords); Expression insertStatement(Definition definition, Record record); Expression updateStatement(Definition definition, Predicate<? super Record> predicate, Record record); Expression deleteStatement(Definition definition, Option<? extends Predicate<? super Record>> predicate); Expression createTable(Definition definition); Expression dropTable(Definition definition); AsClause asClause(String alias); ValueExpression valueExpression(Keyword<?> keyword); ValueExpression valueExpression(AliasedKeyword aliasedKeyword); ValueExpression valueExpression(Aggregate aggregate); ValueExpression valueExpression(CompositeKeyword<?> composite); JoinSpecification joinSpecification(Joiner joiner); JoinType joinType(Join join); ExpressionBuilder join(ExpressionBuilder primary, ExpressionBuilder secondary, JoinType type, JoinSpecification specification); ExpressionBuilder join(ExpressionBuilder builder, Join join); class functions { public static Function1<Predicate<? super Record>, WhereClause> whereClause(final SqlGrammar grammar) { return grammar::whereClause; } public static RecordTo<Expression> insertStatement(final SqlGrammar grammar, final Definition definition) { return new RecordTo<Expression>() { public Expression call(Record record) throws Exception { return grammar.insertStatement(definition, record); } }; } public static Function1<Pair<? extends Predicate<? super Record>, Record>, Expression> updateStatement(final SqlGrammar grammar, final Definition definition) { return recordPair -> grammar.updateStatement(definition, recordPair.first(), recordPair.second()); } public static Function1<Keyword<?>, DerivedColumn> derivedColumn(final SqlGrammar grammar) { return grammar::derivedColumn; } public static Function1<? super Comparator<? super Record>,OrderByClause> orderByClause(final SqlGrammar grammar) { return grammar::orderByClause; } public static Function1<? super Sequence<? extends Keyword<?>>,GroupByClause> groupByClause(final SqlGrammar grammar) { return grammar::groupByClause; } } }
UTF-8
Java
4,386
java
SqlGrammar.java
Java
[]
null
[]
package com.googlecode.lazyrecords.sql.grammars; import com.googlecode.lazyrecords.Aggregate; import com.googlecode.lazyrecords.AliasedKeyword; import com.googlecode.lazyrecords.CompositeKeyword; import com.googlecode.lazyrecords.Definition; import com.googlecode.lazyrecords.Join; import com.googlecode.lazyrecords.Joiner; import com.googlecode.lazyrecords.Keyword; import com.googlecode.lazyrecords.Record; import com.googlecode.lazyrecords.RecordTo; import com.googlecode.lazyrecords.sql.expressions.*; import com.googlecode.totallylazy.functions.Function1; import com.googlecode.totallylazy.Option; import com.googlecode.totallylazy.Pair; import com.googlecode.totallylazy.predicates.Predicate; import com.googlecode.totallylazy.Sequence; import java.util.Comparator; public interface SqlGrammar { SelectExpression selectExpression(Option<SetQuantifier> setQuantifier, Sequence<? extends Keyword<?>> selectList, Definition fromClause, Option<Predicate<? super Record>> whereClause, Option<Comparator<? super Record>> orderByClause, Option<Sequence<? extends Keyword<?>>> groupByClause, Option<Integer> offsetClause, Option<Integer> fetchClause); SelectList selectList(Sequence<? extends Keyword<?>> select); FromClause fromClause(Definition definition); WhereClause whereClause(Predicate<? super Record> where); OrderByClause orderByClause(Comparator<? super Record> orderBy); OffsetClause offsetClause(int number); FetchClause fetchClause(int number); GroupByClause groupByClause(Sequence<? extends Keyword<?>> columns); DerivedColumn derivedColumn(Function1<? super Record, ?> callable); ValueExpression valueExpression(Function1<? super Record, ?> callable); ValueExpression concat(Sequence<? extends Keyword<?>> keywords); Expression insertStatement(Definition definition, Record record); Expression updateStatement(Definition definition, Predicate<? super Record> predicate, Record record); Expression deleteStatement(Definition definition, Option<? extends Predicate<? super Record>> predicate); Expression createTable(Definition definition); Expression dropTable(Definition definition); AsClause asClause(String alias); ValueExpression valueExpression(Keyword<?> keyword); ValueExpression valueExpression(AliasedKeyword aliasedKeyword); ValueExpression valueExpression(Aggregate aggregate); ValueExpression valueExpression(CompositeKeyword<?> composite); JoinSpecification joinSpecification(Joiner joiner); JoinType joinType(Join join); ExpressionBuilder join(ExpressionBuilder primary, ExpressionBuilder secondary, JoinType type, JoinSpecification specification); ExpressionBuilder join(ExpressionBuilder builder, Join join); class functions { public static Function1<Predicate<? super Record>, WhereClause> whereClause(final SqlGrammar grammar) { return grammar::whereClause; } public static RecordTo<Expression> insertStatement(final SqlGrammar grammar, final Definition definition) { return new RecordTo<Expression>() { public Expression call(Record record) throws Exception { return grammar.insertStatement(definition, record); } }; } public static Function1<Pair<? extends Predicate<? super Record>, Record>, Expression> updateStatement(final SqlGrammar grammar, final Definition definition) { return recordPair -> grammar.updateStatement(definition, recordPair.first(), recordPair.second()); } public static Function1<Keyword<?>, DerivedColumn> derivedColumn(final SqlGrammar grammar) { return grammar::derivedColumn; } public static Function1<? super Comparator<? super Record>,OrderByClause> orderByClause(final SqlGrammar grammar) { return grammar::orderByClause; } public static Function1<? super Sequence<? extends Keyword<?>>,GroupByClause> groupByClause(final SqlGrammar grammar) { return grammar::groupByClause; } } }
4,386
0.708846
0.707022
111
38.513512
37.848171
167
false
false
0
0
0
0
0
0
0.693694
false
false
3
ff84ab46a0e5ff3dfd43690e88076deac925b706
22,960,895,178,417
2d952d1aa07015492e1ca24c2ac5e677d3a438c1
/src/schoolWork/ScoreSheet.java
08c855d35f7400e57f6b0839ad4da085899670e0
[]
no_license
TBeardJR/Yahtzee-Project
https://github.com/TBeardJR/Yahtzee-Project
3b683944452bf1313e72cb70ad11b10a257ef7a1
972f231cdcfce830eaf4b23cc453d41cee03ac17
refs/heads/master
2021-01-25T05:57:57.314000
2014-09-21T15:24:22
2014-09-21T15:24:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package schoolWork; import javax.swing.*; import javax.swing.UIManager.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ScoreSheet { { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { { // If Nimbus is not available, you can set the GUI to another // look and feel. } } } JFrame scoreSheetFrame; JPanel upperScoreSheetPanel, lowerScoreSheetPanel, buttonPanel; JButton nextRoundButton, finishButton, nextPlayersTurnButton; public static final int OPTION_YES = 0; public static final int OPTION_NO = 1; public int optionResponse = OPTION_NO; public Object[] options = { "Yes", "No" }; //Table data //Upper Section JTable upperSectionScoreSheet; JScrollPane upperScrollPane; String[] upperSectionColumnNames = {"UpperSection", "How to Score", "Game #1" , "Game #2", "Game #3", "Game #4"}; Object[][] upperSectionGrid = { {"Aces = 1", "Count and add only one","","","",""}, {"Twos = 2", "Count and add only two","","","",""}, {"Threes = 3", "Count and add only three","","","",""}, {"Fours = 4", "Count and add only four","","","",""}, {"Fives = 5", "Count and add only five","","","",""}, {"Sixes = 6", "Count and add only one","","","",""}, {"TOTAL SCORE", "---->","","","",""}, {"BONUS", "If score is 63 or more","","","",""}, {"UPPER TOTAL", "---->","","","",""} }; //Lower Section JTable lowerSectionScoreSheet; JScrollPane lowerScrollPane; String[] lowerSectionColumnNames = {"LowerSection", "", "" , "", "", ""}; Object[][] lowerSectionGrid = { {"3 of a Kind", "Add Total of all dice","","","",""}, {"4 of a Kind", "Add Total of all dice","","","",""}, {"Full House", "Score 25","","","",""}, {"Sm. Straight", "Score 30","","","",""}, {"Lg. Straight", "Score 40","","","",""}, {"YAHTZEE", "Score 50","","","",""}, {"Chance", "Score total of all 5 dice","","","",""}, {"YAHTZEE BONUS", "Check for each bonus","","","",""}, {"LOWER TOTAL", "---->","","","",""}, {"GRAND TOTAL", "---->","","","",""} }; public ScoreSheet() { scoreSheetFrame = new JFrame("Yahtzee Score Sheet"); scoreSheetFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); upperScoreSheetPanel = new JPanel(); lowerScoreSheetPanel = new JPanel(); buttonPanel = new JPanel(); scoreSheetFrame.setLayout(new BorderLayout() ); //upper score sheet scoreSheetFrame.add(upperScoreSheetPanel); scoreSheetFrame.add(upperScoreSheetPanel, BorderLayout.NORTH); upperSectionScoreSheet = new JTable(upperSectionGrid, upperSectionColumnNames); upperScoreSheetPanel.setLayout(new BorderLayout()); upperScoreSheetPanel.add(upperSectionScoreSheet.getTableHeader(), BorderLayout.PAGE_START); upperScoreSheetPanel.add(upperSectionScoreSheet, BorderLayout.NORTH); upperSectionScoreSheet.setEnabled(false); upperScrollPane = new JScrollPane(upperSectionScoreSheet); upperSectionScoreSheet.setFillsViewportHeight(true); upperScoreSheetPanel.add(upperSectionScoreSheet); DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment( DefaultTableCellRenderer.CENTER ); for(int x = 0 ; x < upperSectionColumnNames.length; x++){ upperSectionScoreSheet.getColumnModel().getColumn(x).setCellRenderer( centerRenderer ); } //lower score sheet scoreSheetFrame.add(lowerScoreSheetPanel); scoreSheetFrame.add(lowerScoreSheetPanel, BorderLayout.CENTER); lowerSectionScoreSheet = new JTable(lowerSectionGrid, lowerSectionColumnNames); lowerScoreSheetPanel.setLayout(new BorderLayout()); lowerScoreSheetPanel.add(lowerSectionScoreSheet.getTableHeader(), BorderLayout.PAGE_START); lowerScoreSheetPanel.add(lowerSectionScoreSheet, BorderLayout.CENTER); lowerSectionScoreSheet.setEnabled(false); lowerScrollPane = new JScrollPane(lowerSectionScoreSheet); lowerSectionScoreSheet.setFillsViewportHeight(true); lowerScoreSheetPanel.add(lowerSectionScoreSheet); scoreSheetFrame.add(buttonPanel, BorderLayout.SOUTH); nextPlayersTurnButton = new JButton(); buttonPanel.add(nextPlayersTurnButton); nextRoundButton = new JButton("Next Round"); buttonPanel.add(nextRoundButton); nextRoundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scoreSheetFrame.setVisible(false); } }); finishButton = new JButton("Finish"); buttonPanel.add(finishButton); centerRenderer.setHorizontalAlignment( DefaultTableCellRenderer.CENTER ); for(int x = 0 ; x < lowerSectionColumnNames.length; x++){ lowerSectionScoreSheet.getColumnModel().getColumn(x).setCellRenderer( centerRenderer ); } scoreSheetFrame.setSize(860, 415); //scoreSheetFrame.pack(); scoreSheetFrame.setVisible(false); } public void updateUpperScoreSheet(int updateScoreEvent, int score, int game) { upperSectionGrid[updateScoreEvent][game] = score; upperScoreSheetPanel.revalidate(); upperScoreSheetPanel.repaint(); } public void updateLowerScoreSheet(int updateScoreEvent, int score, int game) { lowerSectionGrid[updateScoreEvent][game] = score; lowerScoreSheetPanel.revalidate(); lowerScoreSheetPanel.repaint(); } public void promptPlayerForNewGame() { optionResponse = JOptionPane.showOptionDialog(scoreSheetFrame, "Do you want to play again?", "Game Finished", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); } public static void main(String[] args) { new ScoreSheet(); } }
UTF-8
Java
5,757
java
ScoreSheet.java
Java
[]
null
[]
package schoolWork; import javax.swing.*; import javax.swing.UIManager.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ScoreSheet { { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { { // If Nimbus is not available, you can set the GUI to another // look and feel. } } } JFrame scoreSheetFrame; JPanel upperScoreSheetPanel, lowerScoreSheetPanel, buttonPanel; JButton nextRoundButton, finishButton, nextPlayersTurnButton; public static final int OPTION_YES = 0; public static final int OPTION_NO = 1; public int optionResponse = OPTION_NO; public Object[] options = { "Yes", "No" }; //Table data //Upper Section JTable upperSectionScoreSheet; JScrollPane upperScrollPane; String[] upperSectionColumnNames = {"UpperSection", "How to Score", "Game #1" , "Game #2", "Game #3", "Game #4"}; Object[][] upperSectionGrid = { {"Aces = 1", "Count and add only one","","","",""}, {"Twos = 2", "Count and add only two","","","",""}, {"Threes = 3", "Count and add only three","","","",""}, {"Fours = 4", "Count and add only four","","","",""}, {"Fives = 5", "Count and add only five","","","",""}, {"Sixes = 6", "Count and add only one","","","",""}, {"TOTAL SCORE", "---->","","","",""}, {"BONUS", "If score is 63 or more","","","",""}, {"UPPER TOTAL", "---->","","","",""} }; //Lower Section JTable lowerSectionScoreSheet; JScrollPane lowerScrollPane; String[] lowerSectionColumnNames = {"LowerSection", "", "" , "", "", ""}; Object[][] lowerSectionGrid = { {"3 of a Kind", "Add Total of all dice","","","",""}, {"4 of a Kind", "Add Total of all dice","","","",""}, {"Full House", "Score 25","","","",""}, {"Sm. Straight", "Score 30","","","",""}, {"Lg. Straight", "Score 40","","","",""}, {"YAHTZEE", "Score 50","","","",""}, {"Chance", "Score total of all 5 dice","","","",""}, {"YAHTZEE BONUS", "Check for each bonus","","","",""}, {"LOWER TOTAL", "---->","","","",""}, {"GRAND TOTAL", "---->","","","",""} }; public ScoreSheet() { scoreSheetFrame = new JFrame("Yahtzee Score Sheet"); scoreSheetFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); upperScoreSheetPanel = new JPanel(); lowerScoreSheetPanel = new JPanel(); buttonPanel = new JPanel(); scoreSheetFrame.setLayout(new BorderLayout() ); //upper score sheet scoreSheetFrame.add(upperScoreSheetPanel); scoreSheetFrame.add(upperScoreSheetPanel, BorderLayout.NORTH); upperSectionScoreSheet = new JTable(upperSectionGrid, upperSectionColumnNames); upperScoreSheetPanel.setLayout(new BorderLayout()); upperScoreSheetPanel.add(upperSectionScoreSheet.getTableHeader(), BorderLayout.PAGE_START); upperScoreSheetPanel.add(upperSectionScoreSheet, BorderLayout.NORTH); upperSectionScoreSheet.setEnabled(false); upperScrollPane = new JScrollPane(upperSectionScoreSheet); upperSectionScoreSheet.setFillsViewportHeight(true); upperScoreSheetPanel.add(upperSectionScoreSheet); DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(); centerRenderer.setHorizontalAlignment( DefaultTableCellRenderer.CENTER ); for(int x = 0 ; x < upperSectionColumnNames.length; x++){ upperSectionScoreSheet.getColumnModel().getColumn(x).setCellRenderer( centerRenderer ); } //lower score sheet scoreSheetFrame.add(lowerScoreSheetPanel); scoreSheetFrame.add(lowerScoreSheetPanel, BorderLayout.CENTER); lowerSectionScoreSheet = new JTable(lowerSectionGrid, lowerSectionColumnNames); lowerScoreSheetPanel.setLayout(new BorderLayout()); lowerScoreSheetPanel.add(lowerSectionScoreSheet.getTableHeader(), BorderLayout.PAGE_START); lowerScoreSheetPanel.add(lowerSectionScoreSheet, BorderLayout.CENTER); lowerSectionScoreSheet.setEnabled(false); lowerScrollPane = new JScrollPane(lowerSectionScoreSheet); lowerSectionScoreSheet.setFillsViewportHeight(true); lowerScoreSheetPanel.add(lowerSectionScoreSheet); scoreSheetFrame.add(buttonPanel, BorderLayout.SOUTH); nextPlayersTurnButton = new JButton(); buttonPanel.add(nextPlayersTurnButton); nextRoundButton = new JButton("Next Round"); buttonPanel.add(nextRoundButton); nextRoundButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scoreSheetFrame.setVisible(false); } }); finishButton = new JButton("Finish"); buttonPanel.add(finishButton); centerRenderer.setHorizontalAlignment( DefaultTableCellRenderer.CENTER ); for(int x = 0 ; x < lowerSectionColumnNames.length; x++){ lowerSectionScoreSheet.getColumnModel().getColumn(x).setCellRenderer( centerRenderer ); } scoreSheetFrame.setSize(860, 415); //scoreSheetFrame.pack(); scoreSheetFrame.setVisible(false); } public void updateUpperScoreSheet(int updateScoreEvent, int score, int game) { upperSectionGrid[updateScoreEvent][game] = score; upperScoreSheetPanel.revalidate(); upperScoreSheetPanel.repaint(); } public void updateLowerScoreSheet(int updateScoreEvent, int score, int game) { lowerSectionGrid[updateScoreEvent][game] = score; lowerScoreSheetPanel.revalidate(); lowerScoreSheetPanel.repaint(); } public void promptPlayerForNewGame() { optionResponse = JOptionPane.showOptionDialog(scoreSheetFrame, "Do you want to play again?", "Game Finished", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); } public static void main(String[] args) { new ScoreSheet(); } }
5,757
0.69828
0.692375
157
35.668789
28.362617
183
false
false
0
0
0
0
0
0
3.33121
false
false
3
68e5b68131fb2a5bc0859c9ef547b7f2cafadfda
309,237,661,486
660e139843d71c9252ed8d39e2a7fd9522ca2811
/aswb/tests/unittests/com/google/idea/blaze/android/run/deployinfo/BlazeApkDeployInfoProtoHelperTest.java
c481e2742dbfda67b7292512c7ce6adccf654b22
[ "Apache-2.0" ]
permissive
wix-playground/intellij
https://github.com/wix-playground/intellij
aa48c19b1947cd134b834704be5f84199ca58dbd
33e4707514788bc66bf8e58a67d1b178af4cec2a
refs/heads/wix-master
2023-09-03T01:09:45.650000
2023-08-28T10:48:04
2023-08-28T10:48:04
147,094,500
10
7
Apache-2.0
true
2023-08-28T10:48:06
2018-09-02T14:52:00
2022-06-06T08:39:57
2023-08-28T10:48:05
165,127
9
3
3
Java
false
false
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.android.run.deployinfo; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass.AndroidDeployInfo; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass.Artifact; import com.google.idea.blaze.android.manifest.ManifestParser.ParsedManifest; import com.google.idea.blaze.android.manifest.ParsedManifestService; import com.google.idea.blaze.base.BlazeTestCase; import com.google.idea.blaze.base.command.buildresult.BuildResultHelper; import com.google.idea.blaze.base.model.primitives.Label; import java.io.File; import java.util.function.Predicate; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; /** * Unit tests for {@link BlazeApkDeployInfoProtoHelper}. * * <p>{@link BlazeApkDeployInfoProtoHelper#readDeployInfoProtoForTarget(Label, BuildResultHelper, * Predicate)} requires a integration test to test properly and is handled by {@link * com.google.idea.blaze.android.google3.run.deployinfo.BlazeApkDeployInfoTest}. */ @RunWith(JUnit4.class) public class BlazeApkDeployInfoProtoHelperTest extends BlazeTestCase { private final ParsedManifestService mockParsedManifestService = Mockito.mock(ParsedManifestService.class); /** * Registers a mocked {@link ParsedManifestService} to return predetermined matching parsed * manifests and for verifying that manifest refreshes are called correctly. */ @Override protected void initTest(Container applicationServices, Container projectServices) { projectServices.register(ParsedManifestService.class, mockParsedManifestService); } @Test public void readDeployInfoForNormalBuild_onlyMainManifest() throws Exception { // setup AndroidDeployInfo deployInfoProto = AndroidDeployInfo.newBuilder() .setMergedManifest(makeArtifact("path/to/manifest")) .addApksToDeploy(makeArtifact("path/to/apk")) .build(); File mainApk = new File("execution_root/path/to/apk"); File mainManifestFile = new File("execution_root/path/to/manifest"); ParsedManifest parsedMainManifest = new ParsedManifest("main", null, null); when(mockParsedManifestService.getParsedManifest(mainManifestFile)) .thenReturn(parsedMainManifest); // perform BlazeAndroidDeployInfo deployInfo = new BlazeApkDeployInfoProtoHelper() .extractDeployInfoAndInvalidateManifests( getProject(), new File("execution_root"), deployInfoProto); // verify assertThat(deployInfo.getApksToDeploy()).containsExactly(mainApk); assertThat(deployInfo.getMergedManifest()).isEqualTo(parsedMainManifest); assertThat(deployInfo.getTestTargetMergedManifest()).isNull(); verify(mockParsedManifestService, times(1)).invalidateCachedManifest(mainManifestFile); } @Test public void readDeployInfoForNormalBuild_withTestTargetManifest() throws Exception { // setup AndroidDeployInfo deployInfoProto = AndroidDeployInfo.newBuilder() .setMergedManifest(makeArtifact("path/to/manifest")) .addAdditionalMergedManifests(makeArtifact("path/to/testtarget/manifest")) .addApksToDeploy(makeArtifact("path/to/apk")) .addApksToDeploy(makeArtifact("path/to/testtarget/apk")) .build(); File mainApk = new File("execution_root/path/to/apk"); File testApk = new File("execution_root/path/to/testtarget/apk"); File mainManifest = new File("execution_root/path/to/manifest"); File testTargetManifest = new File("execution_root/path/to/testtarget/manifest"); ParsedManifest parsedMainManifest = new ParsedManifest("main", null, null); ParsedManifest parsedTestManifest = new ParsedManifest("testtarget", null, null); when(mockParsedManifestService.getParsedManifest(mainManifest)).thenReturn(parsedMainManifest); when(mockParsedManifestService.getParsedManifest(testTargetManifest)) .thenReturn(parsedTestManifest); // perform BlazeAndroidDeployInfo deployInfo = new BlazeApkDeployInfoProtoHelper() .extractDeployInfoAndInvalidateManifests( getProject(), new File("execution_root"), deployInfoProto); // verify assertThat(deployInfo.getApksToDeploy()).containsExactly(mainApk, testApk).inOrder(); assertThat(deployInfo.getMergedManifest()).isEqualTo(parsedMainManifest); assertThat(deployInfo.getTestTargetMergedManifest()).isEqualTo(parsedTestManifest); ArgumentCaptor<File> expectedArgs = ArgumentCaptor.forClass(File.class); verify(mockParsedManifestService, times(2)).invalidateCachedManifest(expectedArgs.capture()); assertThat(expectedArgs.getAllValues()) .containsExactly(mainManifest, testTargetManifest) .inOrder(); } private static Artifact makeArtifact(String execRootPath) { return AndroidDeployInfoOuterClass.Artifact.newBuilder().setExecRootPath(execRootPath).build(); } }
UTF-8
Java
5,947
java
BlazeApkDeployInfoProtoHelperTest.java
Java
[]
null
[]
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.android.run.deployinfo; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass.AndroidDeployInfo; import com.google.devtools.build.lib.rules.android.deployinfo.AndroidDeployInfoOuterClass.Artifact; import com.google.idea.blaze.android.manifest.ManifestParser.ParsedManifest; import com.google.idea.blaze.android.manifest.ParsedManifestService; import com.google.idea.blaze.base.BlazeTestCase; import com.google.idea.blaze.base.command.buildresult.BuildResultHelper; import com.google.idea.blaze.base.model.primitives.Label; import java.io.File; import java.util.function.Predicate; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; /** * Unit tests for {@link BlazeApkDeployInfoProtoHelper}. * * <p>{@link BlazeApkDeployInfoProtoHelper#readDeployInfoProtoForTarget(Label, BuildResultHelper, * Predicate)} requires a integration test to test properly and is handled by {@link * com.google.idea.blaze.android.google3.run.deployinfo.BlazeApkDeployInfoTest}. */ @RunWith(JUnit4.class) public class BlazeApkDeployInfoProtoHelperTest extends BlazeTestCase { private final ParsedManifestService mockParsedManifestService = Mockito.mock(ParsedManifestService.class); /** * Registers a mocked {@link ParsedManifestService} to return predetermined matching parsed * manifests and for verifying that manifest refreshes are called correctly. */ @Override protected void initTest(Container applicationServices, Container projectServices) { projectServices.register(ParsedManifestService.class, mockParsedManifestService); } @Test public void readDeployInfoForNormalBuild_onlyMainManifest() throws Exception { // setup AndroidDeployInfo deployInfoProto = AndroidDeployInfo.newBuilder() .setMergedManifest(makeArtifact("path/to/manifest")) .addApksToDeploy(makeArtifact("path/to/apk")) .build(); File mainApk = new File("execution_root/path/to/apk"); File mainManifestFile = new File("execution_root/path/to/manifest"); ParsedManifest parsedMainManifest = new ParsedManifest("main", null, null); when(mockParsedManifestService.getParsedManifest(mainManifestFile)) .thenReturn(parsedMainManifest); // perform BlazeAndroidDeployInfo deployInfo = new BlazeApkDeployInfoProtoHelper() .extractDeployInfoAndInvalidateManifests( getProject(), new File("execution_root"), deployInfoProto); // verify assertThat(deployInfo.getApksToDeploy()).containsExactly(mainApk); assertThat(deployInfo.getMergedManifest()).isEqualTo(parsedMainManifest); assertThat(deployInfo.getTestTargetMergedManifest()).isNull(); verify(mockParsedManifestService, times(1)).invalidateCachedManifest(mainManifestFile); } @Test public void readDeployInfoForNormalBuild_withTestTargetManifest() throws Exception { // setup AndroidDeployInfo deployInfoProto = AndroidDeployInfo.newBuilder() .setMergedManifest(makeArtifact("path/to/manifest")) .addAdditionalMergedManifests(makeArtifact("path/to/testtarget/manifest")) .addApksToDeploy(makeArtifact("path/to/apk")) .addApksToDeploy(makeArtifact("path/to/testtarget/apk")) .build(); File mainApk = new File("execution_root/path/to/apk"); File testApk = new File("execution_root/path/to/testtarget/apk"); File mainManifest = new File("execution_root/path/to/manifest"); File testTargetManifest = new File("execution_root/path/to/testtarget/manifest"); ParsedManifest parsedMainManifest = new ParsedManifest("main", null, null); ParsedManifest parsedTestManifest = new ParsedManifest("testtarget", null, null); when(mockParsedManifestService.getParsedManifest(mainManifest)).thenReturn(parsedMainManifest); when(mockParsedManifestService.getParsedManifest(testTargetManifest)) .thenReturn(parsedTestManifest); // perform BlazeAndroidDeployInfo deployInfo = new BlazeApkDeployInfoProtoHelper() .extractDeployInfoAndInvalidateManifests( getProject(), new File("execution_root"), deployInfoProto); // verify assertThat(deployInfo.getApksToDeploy()).containsExactly(mainApk, testApk).inOrder(); assertThat(deployInfo.getMergedManifest()).isEqualTo(parsedMainManifest); assertThat(deployInfo.getTestTargetMergedManifest()).isEqualTo(parsedTestManifest); ArgumentCaptor<File> expectedArgs = ArgumentCaptor.forClass(File.class); verify(mockParsedManifestService, times(2)).invalidateCachedManifest(expectedArgs.capture()); assertThat(expectedArgs.getAllValues()) .containsExactly(mainManifest, testTargetManifest) .inOrder(); } private static Artifact makeArtifact(String execRootPath) { return AndroidDeployInfoOuterClass.Artifact.newBuilder().setExecRootPath(execRootPath).build(); } }
5,947
0.766941
0.764755
130
44.746155
32.180096
108
false
false
0
0
0
0
0
0
0.553846
false
false
3
cb6c29e075585b595d054ade02ffdd07afa55a24
20,100,446,958,574
387119cf6e424f3d49e3a8dffa39e39f339155f7
/MonitorEnergiaModem/src/sme/modem/gsm/GSMModem.java
531a0b6c8d4390209e66054107844bac9b50b644
[]
no_license
adolfoluna/MonitorEnergia
https://github.com/adolfoluna/MonitorEnergia
55b0759535d3f5b42fb727da0070cbae248de380
e2123c301406364a5bd60ca2e22ca6dda47fb6f5
refs/heads/master
2023-01-13T16:45:35.691000
2020-11-20T20:42:57
2020-11-20T20:42:57
208,151,704
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sme.modem.gsm; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import sme.modem.media.comm.MediaComm; import sme.modem.media.comm.MediaCommDataListener; public class GSMModem implements MediaCommDataListener, GSMModemBufferListener, WaitTimeOutListener { private static final Log log = LogFactory.getLog(GSMModem.class); private MediaComm mediaComm; private GSMModemBuffer buffer = new GSMModemBuffer(); private TimerWaitable responseWaiter = new TimerWait(); private TimerWaitAsync eventWaiter = new TimerWaitAsync(); private GSMModemCommandResponse respuesta; private GSMModemEventListener glistener; private static final long eventTimeOut = 15_000; public GSMModem() { eventWaiter.setWaitTimeOutListener(this); buffer.setGSMModemBufferListener(this); } public GSMModemCommandResponse sendCommand(String command,long timeOut) { return sendCommand(command.getBytes(), timeOut); }; synchronized public GSMModemCommandResponse sendCommand(byte []command,long timeOut) { String aux = new String(command).replace("\r\n","\\n"); if( mediaComm == null ) { log.error("error intentando enviar comando sin medio de comunicacion disponibe comando:"+aux); return null; } //si hay un evento pendiente esperar que el evento se complete while(eventWaiter.isWaiting()) { try { Thread.sleep(1_000); } catch (InterruptedException ex) { ex.printStackTrace(); } } //inicializar respuesta apuntando a un nuevo Objeto respuesta = new GSMModemCommandResponse(); //por defecto asumir que se agoto el tiempo de espera respuesta.setTimeOutReached(true); //escribir al puerto serial if( mediaComm.write(command) ) log.info("tx:"+aux); else { log.error("error, no se pudo enviar comando '"+aux); return null; } //comenzar a esperar por la respuesta responseWaiter.startWait(timeOut); if( respuesta.isTimeOutReached() ) log.error("error, tiempo de espera agotado comando:"+aux); if( !respuesta.isResponseComplete() ) log.error("error, respuesta incompleta comando:"+aux); if( respuesta.getResponse() != null ) log.info("rx:"+respuesta.getResponse().replace("\r\n", "\\n")); return respuesta; } public MediaComm getMediaComm() { return mediaComm; } public void setMediaComm(MediaComm mediaComm) { //borrar el listener del medio de comunicacion anteior if( this.mediaComm != null ) this.mediaComm.setMediaCommDataListener(null); //guardar la referencia del medio de comunicacion this.mediaComm = mediaComm; //escuchar cuando llegue info al medio de comunicacion mediaComm.setMediaCommDataListener(this); } @Override public void onMediaCommDataRecived(byte[] data, int length) { //si no se esta esperando respuesta ni evento, empezar a esperar evento if( !responseWaiter.isWaiting() && !eventWaiter.isWaiting() ) eventWaiter.startWait(eventTimeOut); //agregar a buffer la respuesta que llego del medio de comunicacion buffer.write(data,responseWaiter.isWaiting()); } @Override public void gsmModemBufferResponse(String response) { if( respuesta != null ) { respuesta.setResponse(response); respuesta.setResponseComplete(true); respuesta.setTimeOutReached(false); } else log.error("error, no existe objeto respuesta para ser asignado"); //dejar de esperar a respuesta de comando responseWaiter.stopWait(); } @Override public void gsmModemBufferEvent(String event) { //dejar de esperar por el evento eventWaiter.stopWait(); //indicar evento en log log.info("evento:"+event.replace("\r", "\\r").replace("\n", "\\n")); //disparar evento de que llego un evento al modem if( glistener != null ) glistener.gsmModemEvent(event); } public void stop() { eventWaiter.stop(); } //ocurre cuando la espera de un evento hace timeout @Override public void waitTimedOut() { if( respuesta != null ) log.error("error, tiempo de espera agotado para recibir evento, rx:"+respuesta.getResponse().replace("\r\n", "\\n")); else log.error("error, tiempo de espera agotado para recibir evento, rx:null"); } public void setGSMModemEventListener(GSMModemEventListener listener) { this.glistener = listener; } }
UTF-8
Java
4,363
java
GSMModem.java
Java
[]
null
[]
package sme.modem.gsm; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import sme.modem.media.comm.MediaComm; import sme.modem.media.comm.MediaCommDataListener; public class GSMModem implements MediaCommDataListener, GSMModemBufferListener, WaitTimeOutListener { private static final Log log = LogFactory.getLog(GSMModem.class); private MediaComm mediaComm; private GSMModemBuffer buffer = new GSMModemBuffer(); private TimerWaitable responseWaiter = new TimerWait(); private TimerWaitAsync eventWaiter = new TimerWaitAsync(); private GSMModemCommandResponse respuesta; private GSMModemEventListener glistener; private static final long eventTimeOut = 15_000; public GSMModem() { eventWaiter.setWaitTimeOutListener(this); buffer.setGSMModemBufferListener(this); } public GSMModemCommandResponse sendCommand(String command,long timeOut) { return sendCommand(command.getBytes(), timeOut); }; synchronized public GSMModemCommandResponse sendCommand(byte []command,long timeOut) { String aux = new String(command).replace("\r\n","\\n"); if( mediaComm == null ) { log.error("error intentando enviar comando sin medio de comunicacion disponibe comando:"+aux); return null; } //si hay un evento pendiente esperar que el evento se complete while(eventWaiter.isWaiting()) { try { Thread.sleep(1_000); } catch (InterruptedException ex) { ex.printStackTrace(); } } //inicializar respuesta apuntando a un nuevo Objeto respuesta = new GSMModemCommandResponse(); //por defecto asumir que se agoto el tiempo de espera respuesta.setTimeOutReached(true); //escribir al puerto serial if( mediaComm.write(command) ) log.info("tx:"+aux); else { log.error("error, no se pudo enviar comando '"+aux); return null; } //comenzar a esperar por la respuesta responseWaiter.startWait(timeOut); if( respuesta.isTimeOutReached() ) log.error("error, tiempo de espera agotado comando:"+aux); if( !respuesta.isResponseComplete() ) log.error("error, respuesta incompleta comando:"+aux); if( respuesta.getResponse() != null ) log.info("rx:"+respuesta.getResponse().replace("\r\n", "\\n")); return respuesta; } public MediaComm getMediaComm() { return mediaComm; } public void setMediaComm(MediaComm mediaComm) { //borrar el listener del medio de comunicacion anteior if( this.mediaComm != null ) this.mediaComm.setMediaCommDataListener(null); //guardar la referencia del medio de comunicacion this.mediaComm = mediaComm; //escuchar cuando llegue info al medio de comunicacion mediaComm.setMediaCommDataListener(this); } @Override public void onMediaCommDataRecived(byte[] data, int length) { //si no se esta esperando respuesta ni evento, empezar a esperar evento if( !responseWaiter.isWaiting() && !eventWaiter.isWaiting() ) eventWaiter.startWait(eventTimeOut); //agregar a buffer la respuesta que llego del medio de comunicacion buffer.write(data,responseWaiter.isWaiting()); } @Override public void gsmModemBufferResponse(String response) { if( respuesta != null ) { respuesta.setResponse(response); respuesta.setResponseComplete(true); respuesta.setTimeOutReached(false); } else log.error("error, no existe objeto respuesta para ser asignado"); //dejar de esperar a respuesta de comando responseWaiter.stopWait(); } @Override public void gsmModemBufferEvent(String event) { //dejar de esperar por el evento eventWaiter.stopWait(); //indicar evento en log log.info("evento:"+event.replace("\r", "\\r").replace("\n", "\\n")); //disparar evento de que llego un evento al modem if( glistener != null ) glistener.gsmModemEvent(event); } public void stop() { eventWaiter.stop(); } //ocurre cuando la espera de un evento hace timeout @Override public void waitTimedOut() { if( respuesta != null ) log.error("error, tiempo de espera agotado para recibir evento, rx:"+respuesta.getResponse().replace("\r\n", "\\n")); else log.error("error, tiempo de espera agotado para recibir evento, rx:null"); } public void setGSMModemEventListener(GSMModemEventListener listener) { this.glistener = listener; } }
4,363
0.715333
0.713271
154
27.331169
26.821938
126
false
false
0
0
0
0
0
0
2.01948
false
false
3
59163543bdd3dbbc03220345ef95daeb61353c21
11,081,015,639,504
75fe8a934012ce8b37e3d6a5c09febc3260fc7ed
/majiang/javaCode/jing/game/net/handler/SCGameAction.java
4e800b2380eaa0c9eac54a9cef1f701fcf072f4a
[]
no_license
thinkido/exampleAs3
https://github.com/thinkido/exampleAs3
36ad39ad24696bb81ba8985f2c5ac8a67e2b84dd
55a127b1a1f8e48f04f973a4df8596df4478c154
refs/heads/master
2016-09-11T00:48:14.220000
2016-02-20T07:14:25
2016-02-20T07:14:25
14,101,421
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jing.game.net.handler; import game.view.scene.gamescene.GameScene; import game.view.scene.gamescene.windows.PlayerActionWindow; import java.util.Vector; import jing.consts.CardPlace; import jing.consts.EffectType; import jing.consts.PlayerAction; import jing.game.view.Mahjong; import jing.game.view.Player; import jing.game.vo.CombinVO; import protocol.sc_game_action; import protocol.sccomplex_tile; public class SCGameAction { public SCGameAction(sc_game_action pb) { // GDC.trace(pb.toString()); PlayerActionWindow.close(); GameScene.cur.info.setRemainTiles(pb.getTiles_remain()); GameScene.cur.pDown.clearJiaoTip(); GameScene.cur.jiaoTip(null); int action = pb.getId(); if(PlayerAction.LACK == action) { lack(pb); } else if(PlayerAction.CHU == action) { chu(pb); } else if(PlayerAction.PENG == action) { peng(pb); } else if(PlayerAction.MING_GANG == action) { mingGang(pb); } else if(PlayerAction.AN_GANG == action) { anGang(pb); } else if(PlayerAction.HU == action) { hu(pb); } else if(PlayerAction.GUO == action) { guo(pb); } else if(PlayerAction.CHI_LEFT == action) { chiLeft(pb); } else if(PlayerAction.CHI_MIDDLE == action) { chiMiddle(pb); } else if(PlayerAction.CHI_RIGHT == action) { chiRight(pb); } } private void lack(sc_game_action pb) { } private void chu(sc_game_action pb) { syncPlayerCards(pb); Player player = GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()); int count = player.cardCount(CardPlace.ON_TABLE); Mahjong mj = player.getCard(CardPlace.ON_TABLE, count - 1); GameScene.cur.setLastChu(mj); } private void peng(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.PENG); } private void mingGang(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.GANG); } private void anGang(sc_game_action pb) { syncPlayerCards(pb); Player player = GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()); GameScene.cur.info.showEffect(player.dir(), EffectType.GANG); } private void hu(sc_game_action pb) { boolean isZimo = pb.getAct_seat_index() == pb.getActed_seat_index() ? true : false; Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); if(false == isZimo) { player.removeLastOnTable(); } syncPlayerCards(pb); GameScene.cur.info.setHu(GameScene.cur.getDirBySeat(pb.getAct_seat_index()), true); GameScene.cur.info.showEffect(GameScene.cur.getDirBySeat(pb.getAct_seat_index()), EffectType.HU); } private void guo(sc_game_action pb) { } private void chiLeft(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.CHI); } private void chiMiddle(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.CHI); } private void chiRight(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.CHI); } private void syncPlayerCards(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()); Vector vecComplex = pb.getAct_complex_seq(); CombinVO[] cbs = new CombinVO[vecComplex.size()]; for(int index = 0; index < vecComplex.size(); ++index) { sccomplex_tile tile = (sccomplex_tile)vecComplex.elementAt(index); cbs[index] = new CombinVO(tile.getType(), tile.getId()); } Vector vecWan = pb.getAct_hand_seq().getWan(); Vector vecTong = pb.getAct_hand_seq().getTong(); Vector vecTiao = pb.getAct_hand_seq().getTiao(); Vector vecLack = pb.getAct_hand_seq().getLack(); Vector vecZi = pb.getAct_hand_seq().getZi(); // Vector vecHua = pb.getAct_hand_seq().getHua(); int[] inHandCards = new int[vecWan.size() + vecTong.size() + vecTiao.size() + vecLack.size() + vecZi.size()]; int cardIndex = 0; for(int index = 0; index < vecWan.size(); ++index) { int card_value = ((Integer)vecWan.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecTong.size(); ++index) { int card_value = ((Integer)vecTong.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecTiao.size(); ++index) { int card_value = ((Integer)vecTiao.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecLack.size(); ++index) { int card_value = ((Integer)vecLack.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecZi.size(); ++index) { int card_value = ((Integer)vecZi.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } boolean hasMo = (pb.getAct_hand_seq().getMo().size() > 0); boolean hasHu = (pb.getAct_hu_seq().size() > 0); int newInHand = -1; if(hasMo) { newInHand = ((Integer)pb.getAct_hand_seq().getMo().elementAt(0)).intValue(); } else if(hasHu) { newInHand = ((Integer)pb.getAct_hu_seq().elementAt(0)).intValue(); } int[] onTableCards = new int[pb.getAct_chued_seq().size()]; for(int index = 0; index < pb.getAct_chued_seq().size(); index++) { int card = ((Integer)pb.getAct_chued_seq().elementAt(index)).intValue(); onTableCards[index] = card; } player.setInHand(inHandCards); player.setNewInHand(newInHand); player.setInHandTable(cbs); player.setOnTable(onTableCards); } }
UTF-8
Java
6,497
java
SCGameAction.java
Java
[]
null
[]
package jing.game.net.handler; import game.view.scene.gamescene.GameScene; import game.view.scene.gamescene.windows.PlayerActionWindow; import java.util.Vector; import jing.consts.CardPlace; import jing.consts.EffectType; import jing.consts.PlayerAction; import jing.game.view.Mahjong; import jing.game.view.Player; import jing.game.vo.CombinVO; import protocol.sc_game_action; import protocol.sccomplex_tile; public class SCGameAction { public SCGameAction(sc_game_action pb) { // GDC.trace(pb.toString()); PlayerActionWindow.close(); GameScene.cur.info.setRemainTiles(pb.getTiles_remain()); GameScene.cur.pDown.clearJiaoTip(); GameScene.cur.jiaoTip(null); int action = pb.getId(); if(PlayerAction.LACK == action) { lack(pb); } else if(PlayerAction.CHU == action) { chu(pb); } else if(PlayerAction.PENG == action) { peng(pb); } else if(PlayerAction.MING_GANG == action) { mingGang(pb); } else if(PlayerAction.AN_GANG == action) { anGang(pb); } else if(PlayerAction.HU == action) { hu(pb); } else if(PlayerAction.GUO == action) { guo(pb); } else if(PlayerAction.CHI_LEFT == action) { chiLeft(pb); } else if(PlayerAction.CHI_MIDDLE == action) { chiMiddle(pb); } else if(PlayerAction.CHI_RIGHT == action) { chiRight(pb); } } private void lack(sc_game_action pb) { } private void chu(sc_game_action pb) { syncPlayerCards(pb); Player player = GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()); int count = player.cardCount(CardPlace.ON_TABLE); Mahjong mj = player.getCard(CardPlace.ON_TABLE, count - 1); GameScene.cur.setLastChu(mj); } private void peng(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.PENG); } private void mingGang(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.GANG); } private void anGang(sc_game_action pb) { syncPlayerCards(pb); Player player = GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()); GameScene.cur.info.showEffect(player.dir(), EffectType.GANG); } private void hu(sc_game_action pb) { boolean isZimo = pb.getAct_seat_index() == pb.getActed_seat_index() ? true : false; Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); if(false == isZimo) { player.removeLastOnTable(); } syncPlayerCards(pb); GameScene.cur.info.setHu(GameScene.cur.getDirBySeat(pb.getAct_seat_index()), true); GameScene.cur.info.showEffect(GameScene.cur.getDirBySeat(pb.getAct_seat_index()), EffectType.HU); } private void guo(sc_game_action pb) { } private void chiLeft(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.CHI); } private void chiMiddle(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.CHI); } private void chiRight(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getActed_seat_index()); player.removeLastOnTable(); syncPlayerCards(pb); GameScene.cur.info.showEffect(GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()).dir(), EffectType.CHI); } private void syncPlayerCards(sc_game_action pb) { Player player = GameScene.cur.getPlayerBySeat(pb.getAct_seat_index()); Vector vecComplex = pb.getAct_complex_seq(); CombinVO[] cbs = new CombinVO[vecComplex.size()]; for(int index = 0; index < vecComplex.size(); ++index) { sccomplex_tile tile = (sccomplex_tile)vecComplex.elementAt(index); cbs[index] = new CombinVO(tile.getType(), tile.getId()); } Vector vecWan = pb.getAct_hand_seq().getWan(); Vector vecTong = pb.getAct_hand_seq().getTong(); Vector vecTiao = pb.getAct_hand_seq().getTiao(); Vector vecLack = pb.getAct_hand_seq().getLack(); Vector vecZi = pb.getAct_hand_seq().getZi(); // Vector vecHua = pb.getAct_hand_seq().getHua(); int[] inHandCards = new int[vecWan.size() + vecTong.size() + vecTiao.size() + vecLack.size() + vecZi.size()]; int cardIndex = 0; for(int index = 0; index < vecWan.size(); ++index) { int card_value = ((Integer)vecWan.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecTong.size(); ++index) { int card_value = ((Integer)vecTong.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecTiao.size(); ++index) { int card_value = ((Integer)vecTiao.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecLack.size(); ++index) { int card_value = ((Integer)vecLack.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } for(int index = 0; index < vecZi.size(); ++index) { int card_value = ((Integer)vecZi.elementAt(index)).intValue(); inHandCards[cardIndex++] = card_value; } boolean hasMo = (pb.getAct_hand_seq().getMo().size() > 0); boolean hasHu = (pb.getAct_hu_seq().size() > 0); int newInHand = -1; if(hasMo) { newInHand = ((Integer)pb.getAct_hand_seq().getMo().elementAt(0)).intValue(); } else if(hasHu) { newInHand = ((Integer)pb.getAct_hu_seq().elementAt(0)).intValue(); } int[] onTableCards = new int[pb.getAct_chued_seq().size()]; for(int index = 0; index < pb.getAct_chued_seq().size(); index++) { int card = ((Integer)pb.getAct_chued_seq().elementAt(index)).intValue(); onTableCards[index] = card; } player.setInHand(inHandCards); player.setNewInHand(newInHand); player.setInHandTable(cbs); player.setOnTable(onTableCards); } }
6,497
0.668155
0.666
233
25.875536
27.864431
111
false
false
0
0
0
0
0
0
2.034335
false
false
3
27cbeedd2575fd275e5ed52bba20175604500674
30,837,865,200,510
9098c5ad8da3a14c7778d66384a11d8eaa2f1671
/src/com/main/view/StartUp.java
a4aba6a4ee8551e7362a3169cd831828e33b2857
[]
no_license
lizhi21707/NetworkController
https://github.com/lizhi21707/NetworkController
192d21e69d43dae7091177200c792130ea0baa21
10a03179d5cc158ce3f993d8f4fe91494d855879
refs/heads/master
2021-05-30T10:51:38.040000
2015-12-10T11:32:24
2015-12-10T11:32:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.main.view; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.main.provider.DataProvider; import com.main.view.util.SWTResourceManager; public class StartUp { protected Shell shell; private String IP; private String PORT; private Text textIP; private Text textPort; private Label lblInputIpAnd; public StartUp() { open(); } /** * Open the window. */ public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Create contents of the window. */ protected void createContents() { shell = new Shell(); shell.setSize(450, 166); shell.setText("SWT Application"); Group grpConnect = new Group(shell, SWT.NONE); grpConnect.setText("Connect"); grpConnect.setBounds(10, 10, 414, 108); textIP = new Text(grpConnect, SWT.BORDER); textIP.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); textIP.setBounds(26, 47, 130, 29); textPort = new Text(grpConnect, SWT.BORDER); textPort.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); textPort.setBounds(168, 47, 85, 29); Button btnNewButton = new Button(grpConnect, SWT.NONE); btnNewButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { IP = textIP.getText(); PORT = textPort.getText(); if(!IP.equals("") && !PORT.equals("")){ connectToRemote(IP, PORT); }else { lblInputIpAnd.setVisible(true); } } }); btnNewButton.setBounds(292, 37, 93, 41); btnNewButton.setText("New Button"); lblInputIpAnd = new Label(grpConnect, SWT.NONE); lblInputIpAnd.setTouchEnabled(true); lblInputIpAnd.setBounds(36, 83, 146, 15); lblInputIpAnd.setText("Input IP and PORT"); lblInputIpAnd.setVisible(false); } protected void connectToRemote(String iP2, String pORT2) { // TODO Auto-generated method stub try { if (InetAddress.getByName(IP).isReachable(5000)) { DataProvider.setIP(IP); DataProvider.setPORT(PORT); new MainFrame(); shell.setVisible(false); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
UTF-8
Java
2,889
java
StartUp.java
Java
[]
null
[]
package com.main.view; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.main.provider.DataProvider; import com.main.view.util.SWTResourceManager; public class StartUp { protected Shell shell; private String IP; private String PORT; private Text textIP; private Text textPort; private Label lblInputIpAnd; public StartUp() { open(); } /** * Open the window. */ public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Create contents of the window. */ protected void createContents() { shell = new Shell(); shell.setSize(450, 166); shell.setText("SWT Application"); Group grpConnect = new Group(shell, SWT.NONE); grpConnect.setText("Connect"); grpConnect.setBounds(10, 10, 414, 108); textIP = new Text(grpConnect, SWT.BORDER); textIP.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); textIP.setBounds(26, 47, 130, 29); textPort = new Text(grpConnect, SWT.BORDER); textPort.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); textPort.setBounds(168, 47, 85, 29); Button btnNewButton = new Button(grpConnect, SWT.NONE); btnNewButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { IP = textIP.getText(); PORT = textPort.getText(); if(!IP.equals("") && !PORT.equals("")){ connectToRemote(IP, PORT); }else { lblInputIpAnd.setVisible(true); } } }); btnNewButton.setBounds(292, 37, 93, 41); btnNewButton.setText("New Button"); lblInputIpAnd = new Label(grpConnect, SWT.NONE); lblInputIpAnd.setTouchEnabled(true); lblInputIpAnd.setBounds(36, 83, 146, 15); lblInputIpAnd.setText("Input IP and PORT"); lblInputIpAnd.setVisible(false); } protected void connectToRemote(String iP2, String pORT2) { // TODO Auto-generated method stub try { if (InetAddress.getByName(IP).isReachable(5000)) { DataProvider.setIP(IP); DataProvider.setPORT(PORT); new MainFrame(); shell.setVisible(false); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
2,889
0.682243
0.660782
108
24.75
18.109301
75
false
false
0
0
0
0
0
0
2.388889
false
false
3
82a183ddd9afa4dcf85e323b021a1932283f2258
18,279,380,848,649
2ae3fb80c43b47bb6411f2225095205e832c67cc
/src/main/java/com/app/MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb/controller/CustomerAccountController.java
866cab2707cc941b7fce867ff005c6afc802db6f
[ "MIT" ]
permissive
ruisunon/Crud-With-SpringBoot-Security-MongoTemplate-And-Mongodb
https://github.com/ruisunon/Crud-With-SpringBoot-Security-MongoTemplate-And-Mongodb
78f66d4ad04d1a769674b1b9b5d345f859721069
a963057aef9dce16791e67f8030298b1ca9a60af
refs/heads/master
2020-04-23T10:18:09.313000
2019-02-01T14:12:31
2019-02-01T14:12:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.controller; import java.util.List; import java.util.UUID; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.dao.ICustomerAccountDAO; import com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.modal.AccountDTO; import com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.modal.CustomerDTO; @Controller public class CustomerAccountController { private Logger logger = Logger.getLogger(CustomerAccountController.class); @Autowired private ICustomerAccountDAO customerAccountDAO; @RequestMapping(value = "/welcome-customer-account", method = RequestMethod.GET) public ModelAndView showAddCustomerAccountPage() { logger.debug("****Going To Enter On Add CustomerAccount Page****"); logger.debug(""); logger.debug(""); ModelAndView model = new ModelAndView(); model.setViewName("addCustomerAccount"); return model; } @RequestMapping(value = "/add-customer-account", method = RequestMethod.POST) public ModelAndView callSaveCustomerAccountDetails(@RequestParam("customerFirstName") String customerFirstName, @RequestParam("customerLastName") String customerLastName, @RequestParam("customerAddress") String customerAddress, @RequestParam("accountType") String accountType, @RequestParam("accountStatus") String accountStatus, @ModelAttribute() CustomerDTO customerDTO, @ModelAttribute() AccountDTO accountDTO) throws Exception { logger.debug("****Going To Start CallSaveCustomerAccountDetails Method****"); // for AccountDTO accountDTO.setAccountNumber(UUID.randomUUID().toString()); accountDTO.setAccountType(accountType); accountDTO.setAccountStatus(accountStatus); // for CustomerDTO customerDTO.setCustomerFirstName(customerFirstName); customerDTO.setCustomerLastName(customerLastName); customerDTO.setCustomerAddress(customerAddress); customerDTO.setCustomerAccount(accountDTO); customerAccountDAO.saveCustomerAccountDetails(customerDTO); if(customerAccountDAO != null) { logger.debug(customerFirstName.concat(customerLastName)+" Is Save Successfully"); } else { logger.debug("Unable To Save "+customerFirstName.concat(customerLastName)); } logger.debug("****Going To End CallSaveCustomerAccountDetails Method****"); logger.debug(""); logger.debug(""); return new ModelAndView("redirect:/fetch-customer-account"); } @RequestMapping(value = "/fetch-customer-account", method = RequestMethod.GET) public ModelAndView callGetAllCustomersAccountDetails() throws Exception { logger.debug("****Going To Start CallGetAllCustomersAccountDetails Method****"); ModelAndView model = new ModelAndView("fetch-customer-account"); List<CustomerDTO> customersAccountList = customerAccountDAO.getAllCustomersAccountDetails(); if(customersAccountList != null && customersAccountList.size() > 0) { model.addObject("customersAccountList", customersAccountList); logger.debug("You Have Successfully Fetch All CustomersAccount Details List"); } else { logger.debug("Unable To Fetch All CustomersAccount Details List"); } logger.debug("****Going To End CallGetAllCustomersAccountDetails Method****"); logger.debug(""); logger.debug(""); return model; } @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/edit-customer-account/{customerId}", method = RequestMethod.GET) public ModelAndView callGetCustomerAccountDetailsById(@PathVariable("customerId") String customerId) throws Exception { logger.debug("****Going To Start CallGetCustomerAccountDetailsById Method****"); ModelAndView model = new ModelAndView(); CustomerDTO editCustomerAccount = customerAccountDAO.getCustomerAccountDetailsById(customerId); if(editCustomerAccount != null) { model.addObject("values", editCustomerAccount); logger.debug("You Have Successfully Edit Customer Id "+customerId); } else { logger.debug("Unable To Edit Customer Id "+customerId); } model.setViewName("updateCustomerAccount"); logger.debug("****Going To End CallGetCustomerAccountDetailsById Method****"); logger.debug(""); logger.debug(""); return model; } @RequestMapping(value = "/update-customer-account", method = RequestMethod.POST) public ModelAndView callUpdateCustomerAccountDetails(@RequestParam("customerFirstName") String customerFirstName, @RequestParam("customerLastName") String customerLastName, @RequestParam("customerAddress") String customerAddress, @RequestParam("accountNumber") String accountNumber, @RequestParam("accountType") String accountType, @RequestParam("accountStatus") String accountStatus, @ModelAttribute() CustomerDTO customerDTO, @ModelAttribute() AccountDTO accountDTO) throws Exception { logger.debug("****Going To Start CallUpdateCustomerAccountDetails Method****"); // for AccountDTO accountDTO.setAccountNumber(accountNumber); accountDTO.setAccountType(accountType); accountDTO.setAccountStatus(accountStatus); // for CustomerDTO customerDTO.setCustomerFirstName(customerFirstName); customerDTO.setCustomerLastName(customerLastName); customerDTO.setCustomerAddress(customerAddress); customerDTO.setCustomerAccount(accountDTO); customerAccountDAO.updateCustomerAccountDetails(customerDTO); if(customerAccountDAO != null) { logger.debug(customerFirstName.concat(customerLastName)+" Is Updated Successfully"); } else { logger.debug("Unable To Update "+customerFirstName.concat(customerLastName)); } logger.debug("****Going To End CallUpdateCustomerAccountDetails Method****"); logger.debug(""); logger.debug(""); return new ModelAndView("redirect:/fetch-customer-account"); } @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/delete-customer-account/{customerId}", method = RequestMethod.GET) public ModelAndView callDeleteCustomerAccountDetails(@PathVariable("customerId") String customerId) throws Exception { logger.debug("****Going To Start CallDeleteCustomerAccountDetails Method****"); customerAccountDAO.deleteCustomerAccountDetails(customerId); if(customerAccountDAO != null) { logger.debug("You Have Successfully Delete Customer Id "+customerId); } else { logger.debug("Unable To Delete Customer Id "+customerId); } logger.debug("****Going To End CallDeleteCustomerAccountDetails Method****"); logger.debug(""); logger.debug(""); return new ModelAndView("redirect:/fetch-customer-account"); } }
UTF-8
Java
7,238
java
CustomerAccountController.java
Java
[ { "context": "rFirstName);\n \tcustomerDTO.setCustomerLastName(customerLastName);\n \tcustomerDTO.setCustomerAddress(cus", "end": 2543, "score": 0.7463892698287964, "start": 2535, "tag": "NAME", "value": "customer" }, { "context": "rFirstName);\n \tcustomerDTO.setCustomerLastName(customerLastName);\n \tcustomerDTO.setCustomerAddress(cus", "end": 5865, "score": 0.5600422620773315, "start": 5857, "tag": "NAME", "value": "customer" } ]
null
[]
package com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.controller; import java.util.List; import java.util.UUID; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.dao.ICustomerAccountDAO; import com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.modal.AccountDTO; import com.app.MavenSpringBootMvcAopSecurityCrudWithLog4jMongoTemplateAndMongodb.modal.CustomerDTO; @Controller public class CustomerAccountController { private Logger logger = Logger.getLogger(CustomerAccountController.class); @Autowired private ICustomerAccountDAO customerAccountDAO; @RequestMapping(value = "/welcome-customer-account", method = RequestMethod.GET) public ModelAndView showAddCustomerAccountPage() { logger.debug("****Going To Enter On Add CustomerAccount Page****"); logger.debug(""); logger.debug(""); ModelAndView model = new ModelAndView(); model.setViewName("addCustomerAccount"); return model; } @RequestMapping(value = "/add-customer-account", method = RequestMethod.POST) public ModelAndView callSaveCustomerAccountDetails(@RequestParam("customerFirstName") String customerFirstName, @RequestParam("customerLastName") String customerLastName, @RequestParam("customerAddress") String customerAddress, @RequestParam("accountType") String accountType, @RequestParam("accountStatus") String accountStatus, @ModelAttribute() CustomerDTO customerDTO, @ModelAttribute() AccountDTO accountDTO) throws Exception { logger.debug("****Going To Start CallSaveCustomerAccountDetails Method****"); // for AccountDTO accountDTO.setAccountNumber(UUID.randomUUID().toString()); accountDTO.setAccountType(accountType); accountDTO.setAccountStatus(accountStatus); // for CustomerDTO customerDTO.setCustomerFirstName(customerFirstName); customerDTO.setCustomerLastName(customerLastName); customerDTO.setCustomerAddress(customerAddress); customerDTO.setCustomerAccount(accountDTO); customerAccountDAO.saveCustomerAccountDetails(customerDTO); if(customerAccountDAO != null) { logger.debug(customerFirstName.concat(customerLastName)+" Is Save Successfully"); } else { logger.debug("Unable To Save "+customerFirstName.concat(customerLastName)); } logger.debug("****Going To End CallSaveCustomerAccountDetails Method****"); logger.debug(""); logger.debug(""); return new ModelAndView("redirect:/fetch-customer-account"); } @RequestMapping(value = "/fetch-customer-account", method = RequestMethod.GET) public ModelAndView callGetAllCustomersAccountDetails() throws Exception { logger.debug("****Going To Start CallGetAllCustomersAccountDetails Method****"); ModelAndView model = new ModelAndView("fetch-customer-account"); List<CustomerDTO> customersAccountList = customerAccountDAO.getAllCustomersAccountDetails(); if(customersAccountList != null && customersAccountList.size() > 0) { model.addObject("customersAccountList", customersAccountList); logger.debug("You Have Successfully Fetch All CustomersAccount Details List"); } else { logger.debug("Unable To Fetch All CustomersAccount Details List"); } logger.debug("****Going To End CallGetAllCustomersAccountDetails Method****"); logger.debug(""); logger.debug(""); return model; } @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/edit-customer-account/{customerId}", method = RequestMethod.GET) public ModelAndView callGetCustomerAccountDetailsById(@PathVariable("customerId") String customerId) throws Exception { logger.debug("****Going To Start CallGetCustomerAccountDetailsById Method****"); ModelAndView model = new ModelAndView(); CustomerDTO editCustomerAccount = customerAccountDAO.getCustomerAccountDetailsById(customerId); if(editCustomerAccount != null) { model.addObject("values", editCustomerAccount); logger.debug("You Have Successfully Edit Customer Id "+customerId); } else { logger.debug("Unable To Edit Customer Id "+customerId); } model.setViewName("updateCustomerAccount"); logger.debug("****Going To End CallGetCustomerAccountDetailsById Method****"); logger.debug(""); logger.debug(""); return model; } @RequestMapping(value = "/update-customer-account", method = RequestMethod.POST) public ModelAndView callUpdateCustomerAccountDetails(@RequestParam("customerFirstName") String customerFirstName, @RequestParam("customerLastName") String customerLastName, @RequestParam("customerAddress") String customerAddress, @RequestParam("accountNumber") String accountNumber, @RequestParam("accountType") String accountType, @RequestParam("accountStatus") String accountStatus, @ModelAttribute() CustomerDTO customerDTO, @ModelAttribute() AccountDTO accountDTO) throws Exception { logger.debug("****Going To Start CallUpdateCustomerAccountDetails Method****"); // for AccountDTO accountDTO.setAccountNumber(accountNumber); accountDTO.setAccountType(accountType); accountDTO.setAccountStatus(accountStatus); // for CustomerDTO customerDTO.setCustomerFirstName(customerFirstName); customerDTO.setCustomerLastName(customerLastName); customerDTO.setCustomerAddress(customerAddress); customerDTO.setCustomerAccount(accountDTO); customerAccountDAO.updateCustomerAccountDetails(customerDTO); if(customerAccountDAO != null) { logger.debug(customerFirstName.concat(customerLastName)+" Is Updated Successfully"); } else { logger.debug("Unable To Update "+customerFirstName.concat(customerLastName)); } logger.debug("****Going To End CallUpdateCustomerAccountDetails Method****"); logger.debug(""); logger.debug(""); return new ModelAndView("redirect:/fetch-customer-account"); } @PreAuthorize("hasRole('ADMIN')") @RequestMapping(value = "/delete-customer-account/{customerId}", method = RequestMethod.GET) public ModelAndView callDeleteCustomerAccountDetails(@PathVariable("customerId") String customerId) throws Exception { logger.debug("****Going To Start CallDeleteCustomerAccountDetails Method****"); customerAccountDAO.deleteCustomerAccountDetails(customerId); if(customerAccountDAO != null) { logger.debug("You Have Successfully Delete Customer Id "+customerId); } else { logger.debug("Unable To Delete Customer Id "+customerId); } logger.debug("****Going To End CallDeleteCustomerAccountDetails Method****"); logger.debug(""); logger.debug(""); return new ModelAndView("redirect:/fetch-customer-account"); } }
7,238
0.769826
0.768997
154
46
31.385744
120
false
false
0
0
0
0
65
0.035922
1.987013
false
false
3
aff881680fb416b2e797fad4db83d51f2d439a12
26,456,998,543,987
b174ccd42d1eef9899f87f7a6938845ac3bd7dbf
/qingk-statistics-database/src/main/java/com/allook/statistics/database/framework/DatabaseContextHolder.java
74552c140970142aa125f89047d1542d9a5cf741
[]
no_license
dedebao/qingk-statistics
https://github.com/dedebao/qingk-statistics
5668634ed8bccabb863fd5f9099f55ef379b7880
6194d0bee127cdbff0ea3ffdcdd6c7468f0f8ded
refs/heads/master
2020-04-01T03:34:05.425000
2018-10-13T10:11:21
2018-10-13T10:11:21
152,827,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.allook.statistics.database.framework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @ClassName: DatabaseContextHolder * @Description:数据源选择器 * @author: pengyu * @date: 2018年9月21日 下午4:31:43 */ public class DatabaseContextHolder { public static final Logger log = LoggerFactory.getLogger(DatabaseContextHolder.class); private static final ThreadLocal<DatasourceType> contextHolder = new ThreadLocal<>(); // 设置数据源名 public static void setDB(DatasourceType dbType) { log.info("选择数据源:{}", dbType); contextHolder.set(dbType); } // 获取数据源名 public static DatasourceType getDB() { return contextHolder.get(); } // 清除数据源名 public static void clearDB() { contextHolder.remove(); } }
UTF-8
Java
874
java
DatabaseContextHolder.java
Java
[ { "context": "eContextHolder \n * @Description:数据源选择器\n * @author: pengyu\n * @date: 2018年9月21日 下午4:31:43 \n */\n\npublic clas", "end": 205, "score": 0.9963793754577637, "start": 199, "tag": "USERNAME", "value": "pengyu" } ]
null
[]
/** * */ package com.allook.statistics.database.framework; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @ClassName: DatabaseContextHolder * @Description:数据源选择器 * @author: pengyu * @date: 2018年9月21日 下午4:31:43 */ public class DatabaseContextHolder { public static final Logger log = LoggerFactory.getLogger(DatabaseContextHolder.class); private static final ThreadLocal<DatasourceType> contextHolder = new ThreadLocal<>(); // 设置数据源名 public static void setDB(DatasourceType dbType) { log.info("选择数据源:{}", dbType); contextHolder.set(dbType); } // 获取数据源名 public static DatasourceType getDB() { return contextHolder.get(); } // 清除数据源名 public static void clearDB() { contextHolder.remove(); } }
874
0.669975
0.652605
39
19.666666
22.607389
89
false
false
0
0
0
0
0
0
0.307692
false
false
3
ecaca18170545931ca631301dae3dd646c881690
4,896,262,741,417
4072fef5725d1592fb5e47e0d57bf8445043293f
/src/test/java/mwang/parkinglot/AppMultithreadingUseCaseTest.java
037d1d643443973bb5433c2f76b89336c33e9780
[]
no_license
michaelgithub2013/parking-lot
https://github.com/michaelgithub2013/parking-lot
254998b8254092bf52575b911b2d40a36a4b4eb2
1f261381ab839bac9d4642489fe8b550fc43d379
refs/heads/master
2021-01-10T06:28:38.539000
2016-02-24T22:54:01
2016-02-24T22:54:01
52,468,075
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mwang.parkinglot; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Phaser; import java.util.concurrent.TimeoutException; import junit.framework.TestCase; import mwang.parkinglot.test.util.PhaserCar; /** * * @author mwang * * Description of the Multithreading use case * * It demonstrates concurrent access of resource, thread execution, * thread lock and result gathering. * * Prepare: * * A parking lot is constructed with 2 entries, 2 exits and 3 parking * spaces. Each entry or exit allows multiple cars passing at same time. * Once parking lot is full, cars are not allowed to enter * * A car behaves like this: Wait until a group signal is ready, enter * the parking lot, stay inside for a while, pay bill, leave and save * journey. * * Test case: * * Send the car group to the parking lot. Once a car * is back, print its journey and send it to the parking lot again. * Repeat this three times. * * Result: * * Running the case, We expect to see the 4 cars group went to the 3 * spaces parking lot three times. In each time, they started at the * same time. There is always one car blocked. When coming back, first * car got its journey printed first. * * */ public class AppMultithreadingUseCaseTest extends TestCase { private ParkingLot parkingLot; @Override public void setUp() throws Exception { super.setUp(); String[] entries = { "South Entry", "North Entry" }; String[] exits = { "Under Ground Exit", "Ground Exit" }; int spaceNumber = 3; parkingLot = new ParkingLotImpl(entries, exits, spaceNumber); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testPhaserCar() throws InterruptedException, ExecutionException, TimeoutException { List<Callable<PhaserCar>> cars = new ArrayList<>(); int carNumberInGroup = 4; Phaser phaser = new Phaser(carNumberInGroup); for (int i = 0; i < carNumberInGroup; i++) cars.add(new PhaserCar("car_" + (i + 1), parkingLot, "North Entry", "Ground Exit", phaser)); Executor executor = Executors.newFixedThreadPool(9); CompletionService<PhaserCar> completionService = new ExecutorCompletionService<PhaserCar>(executor); // send the cars System.out.println("*** start ***"); for (Callable<PhaserCar> car : cars) completionService.submit(car); // gather result int received = 0; while (received < carNumberInGroup * 3) { received++; // blocks if none available Future<PhaserCar> resultFuture = completionService.take(); PhaserCar aCar = resultFuture.get(); System.out.println(aCar.getLastJourney()); completionService.submit(aCar); } } }
UTF-8
Java
3,258
java
AppMultithreadingUseCaseTest.java
Java
[ { "context": "nglot.test.util.PhaserCar;\r\n\r\n/**\r\n * \r\n * @author mwang\r\n * \r\n * Description of the Multithreadin", "end": 584, "score": 0.9995615482330322, "start": 579, "tag": "USERNAME", "value": "mwang" } ]
null
[]
package mwang.parkinglot; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Phaser; import java.util.concurrent.TimeoutException; import junit.framework.TestCase; import mwang.parkinglot.test.util.PhaserCar; /** * * @author mwang * * Description of the Multithreading use case * * It demonstrates concurrent access of resource, thread execution, * thread lock and result gathering. * * Prepare: * * A parking lot is constructed with 2 entries, 2 exits and 3 parking * spaces. Each entry or exit allows multiple cars passing at same time. * Once parking lot is full, cars are not allowed to enter * * A car behaves like this: Wait until a group signal is ready, enter * the parking lot, stay inside for a while, pay bill, leave and save * journey. * * Test case: * * Send the car group to the parking lot. Once a car * is back, print its journey and send it to the parking lot again. * Repeat this three times. * * Result: * * Running the case, We expect to see the 4 cars group went to the 3 * spaces parking lot three times. In each time, they started at the * same time. There is always one car blocked. When coming back, first * car got its journey printed first. * * */ public class AppMultithreadingUseCaseTest extends TestCase { private ParkingLot parkingLot; @Override public void setUp() throws Exception { super.setUp(); String[] entries = { "South Entry", "North Entry" }; String[] exits = { "Under Ground Exit", "Ground Exit" }; int spaceNumber = 3; parkingLot = new ParkingLotImpl(entries, exits, spaceNumber); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testPhaserCar() throws InterruptedException, ExecutionException, TimeoutException { List<Callable<PhaserCar>> cars = new ArrayList<>(); int carNumberInGroup = 4; Phaser phaser = new Phaser(carNumberInGroup); for (int i = 0; i < carNumberInGroup; i++) cars.add(new PhaserCar("car_" + (i + 1), parkingLot, "North Entry", "Ground Exit", phaser)); Executor executor = Executors.newFixedThreadPool(9); CompletionService<PhaserCar> completionService = new ExecutorCompletionService<PhaserCar>(executor); // send the cars System.out.println("*** start ***"); for (Callable<PhaserCar> car : cars) completionService.submit(car); // gather result int received = 0; while (received < carNumberInGroup * 3) { received++; // blocks if none available Future<PhaserCar> resultFuture = completionService.take(); PhaserCar aCar = resultFuture.get(); System.out.println(aCar.getLastJourney()); completionService.submit(aCar); } } }
3,258
0.669429
0.665746
100
30.58
27.099882
102
false
false
0
0
0
0
0
0
1.3
false
false
3
b1bfb44fc801fa4de1af29b190bf86b2976f02b2
14,851,996,940,105
f7e7fbab5e86cf94a7c1b0e9287593710d360afb
/example/src/main/java/com/felhr/serialportexample/Activity/WorkerActivity.java
5993b445c2619684351706f2f6aa3f31c7a403d8
[ "MIT" ]
permissive
dongtrieuqn12/VendingMachine
https://github.com/dongtrieuqn12/VendingMachine
7a41328bcdd9c6ee71af1a098b273efb0ec9d316
574e1058311eb33cdf1ff15dd53a59bc70da5562
refs/heads/master
2020-03-29T16:35:23.254000
2018-09-24T14:57:17
2018-09-24T14:57:17
150,119,908
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.felhr.serialportexample.Activity; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by Ho Dong Trieu on 08/29/2018 */ public class WorkerActivity extends AsyncTask<WorkerActivity.WorkerParams, Void, String> { static class WorkerParams { final MainActivity activity; String result; WorkerParams(MainActivity activity, String result) { this.result = result; this.activity = activity; } } StringBuilder stringBuilder; HttpURLConnection connection = null; String targetURL; String urlParameters; public WorkerActivity(String urlParameters) { this.urlParameters = urlParameters; } @Override protected String doInBackground(WorkerParams... workerParams) { try { URL url = new URL("https://id.kiotviet.vn/connect/token"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setUseCaches(false); connection.setDoOutput(true); //send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //get response InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return String.valueOf(stringBuilder); } }
UTF-8
Java
2,397
java
WorkerActivity.java
Java
[ { "context": "Exception;\nimport java.net.URL;\n\n/**\n * Created by Ho Dong Trieu on 08/29/2018\n */\npublic class WorkerActivity ext", "end": 358, "score": 0.9998669028282166, "start": 345, "tag": "NAME", "value": "Ho Dong Trieu" } ]
null
[]
package com.felhr.serialportexample.Activity; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by <NAME> on 08/29/2018 */ public class WorkerActivity extends AsyncTask<WorkerActivity.WorkerParams, Void, String> { static class WorkerParams { final MainActivity activity; String result; WorkerParams(MainActivity activity, String result) { this.result = result; this.activity = activity; } } StringBuilder stringBuilder; HttpURLConnection connection = null; String targetURL; String urlParameters; public WorkerActivity(String urlParameters) { this.urlParameters = urlParameters; } @Override protected String doInBackground(WorkerParams... workerParams) { try { URL url = new URL("https://id.kiotviet.vn/connect/token"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setUseCaches(false); connection.setDoOutput(true); //send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //get response InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; stringBuilder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line + "\n"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return String.valueOf(stringBuilder); } }
2,390
0.635795
0.632457
77
30.129869
24.407978
95
false
false
0
0
0
0
0
0
0.558442
false
false
3
e283bb4434191eb49fabd039c79d478c3c9e6d00
27,401,891,351,812
f8708f063e9d77aff4d7d30a691559bdae82601d
/src/EstadosFinancieros/EResultados.java
74c76f4bd0f142a2e392486cf9d17d9d93d5e5ca
[]
no_license
brenNavas/Contables
https://github.com/brenNavas/Contables
f6af7d31b1fbcaf53813eec9ce51fa515454b8d2
e9399d2617dd2bffdd39c65e11671674011a4c3f
refs/heads/master
2021-08-22T08:44:54.931000
2017-11-29T19:54:56
2017-11-29T19:54:56
112,520,342
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 EstadosFinancieros; import Logica.Conexion; import com.itextpdf.text.BadElementException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author Yeseliz */ public class EResultados extends javax.swing.JInternalFrame { private Conexion mysql = new Conexion(); private Connection cn = mysql.conectar(); private String sentenciaSql = ""; public static Double utilidadReinvertida; /** * Creates new form EResultados */ public EResultados() { initComponents(); resultado(); fecha1.setText(fechaActual()); fecha2.setText(fechaActual()); } public void consulta() { } private void resultado() { try { //Ventas netas String sql1 = "SELECT sum(monto)FROM nuevatransaccion WHERE tipo='Venta'"; PreparedStatement statement1 = null; statement1 = this.cn.prepareStatement(sql1); ResultSet resultado1 = statement1.executeQuery(); String sql2 = "SELECT sum(monto) FROM nuevatransaccion WHERE tipo='Devolucion'"; PreparedStatement statement2 = null; statement2 = this.cn.prepareStatement(sql2); ResultSet resultado2 = statement2.executeQuery(); String sql3 = "SELECT sum(monto) from nuevatransaccion where tipo='Credito'"; PreparedStatement statement3 = null; statement3 = this.cn.prepareStatement(sql3); ResultSet resultado3 = statement3.executeQuery(); //Costo de lo vendido String sql4 = "SELECT sum(monto) from nuevatransaccion WHERE tipo='Compra'"; PreparedStatement statement4 = null; statement4 = this.cn.prepareStatement(sql4); ResultSet resultado4 = statement4.executeQuery(); //Gastos de operacion String sql5= "SELECT saldoDeudor from cuenta WHERE codigoCuenta='41'"; PreparedStatement statement5 = null; statement5 = this.cn.prepareStatement(sql5); ResultSet resultado5 = statement5.executeQuery(); //Gastos financieros String sql6="SELECT saldoDeudor from cuenta WHERE codigoCuenta='417'"; PreparedStatement statement6 = null; statement6 = this.cn.prepareStatement(sql6); ResultSet resultado6 = statement6.executeQuery(); //Otros ingresos String sql7="SELECT saldoAcreedor from cuenta WHERE codigoCuenta='520'"; PreparedStatement statement7 = null; statement7 = this.cn.prepareStatement(sql7); ResultSet resultado7 = statement7.executeQuery(); //Impuestos String sql8="SELECT saldoDeudor from cuenta WHERE codigoCuenta='415010'"; PreparedStatement statement8 = null; statement8 = this.cn.prepareStatement(sql8); ResultSet resultado8 = statement8.executeQuery(); while (resultado1.next() && resultado2.next() && resultado3.next() && resultado4.next() && resultado5.next() && resultado6.next() && resultado7.next() && resultado8.next()) { //Utilidad bruta String ventasAlContado = resultado1.getString("sum(monto)"); String ventasAlCredito = resultado2.getString("sum(monto)"); String rebajas = resultado3.getString("sum(monto)"); Double vContado = Double.parseDouble(ventasAlContado); Double vCredito = Double.parseDouble(ventasAlCredito); Double rebajaVenta = Double.parseDouble(rebajas); Double ventasNeta = vContado + vCredito - rebajaVenta; txtVentasNetas.setText(String.valueOf(ventasNeta)); String costoDeLovendido = resultado4.getString("sum(monto)"); //Calculo Double CostoVendido = Double.parseDouble(costoDeLovendido); txtCostoVendido.setText(String.valueOf(CostoVendido)); Double UtilidadBruta = ventasNeta - CostoVendido; //Resultado txtUtilidadBruta.setText(String.valueOf(UtilidadBruta)); //Utilidad de operacion String gastoOperacion= resultado5.getString("SaldoDeudor"); //Calculo Double gastoOp= Double.parseDouble(gastoOperacion); txtGastosO.setText(String.valueOf(gastoOp)); Double UtilidadOperacion= UtilidadBruta-gastoOp; txtUtilidadO.setText(String.valueOf(UtilidadOperacion)); //Utilidad antes de otros ingreso String gastoFin= resultado6.getString("SaldoDeudor"); //Calculo Double gastoFinanciero= Double.parseDouble(gastoFin); txtGastosFinancieros.setText(String.valueOf(gastoFinanciero)); Double UtilidadAntesDeOtroIngresos= UtilidadOperacion-gastoFinanciero; txtUtilidadAI.setText(String.valueOf(UtilidadAntesDeOtroIngresos)); //Utilidad antes de impuesto String OtroIngreso= resultado7.getString("saldoAcreedor"); //Calculo Double OtrosIngresosNetos= Double.parseDouble(OtroIngreso); txtOtrosIngresosNetos.setText(String.valueOf(OtrosIngresosNetos)); Double UtilidadAntesDeImpuesto=UtilidadAntesDeOtroIngresos+OtrosIngresosNetos; txtUAI.setText(String.valueOf(UtilidadAntesDeImpuesto)); //Utilidad neta String imp= resultado8.getString("saldoDeudor"); Double impuestos= Double.parseDouble(imp); txtImpuestos.setText(String.valueOf(impuestos)); Double UtilidadNeta=UtilidadAntesDeImpuesto-impuestos; txtUtilidadNeta.setText(String.valueOf(UtilidadNeta)); //Para Estado de capital UtilidadNeta=utilidadReinvertida; } } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error al recuperar las cuentas de la base de datos"); ex.printStackTrace(); } } public static String fechaActual(){ Date fecha = new Date(); SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy"); return formatoFecha.format(fecha); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); fecha1 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); fecha2 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); jLabel11 = new javax.swing.JLabel(); jSeparator3 = new javax.swing.JSeparator(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jSeparator4 = new javax.swing.JSeparator(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jSeparator5 = new javax.swing.JSeparator(); jLabel16 = new javax.swing.JLabel(); txtVentasNetas = new javax.swing.JTextField(); txtGastosO = new javax.swing.JTextField(); txtCostoVendido = new javax.swing.JTextField(); txtUtilidadBruta = new javax.swing.JTextField(); txtUtilidadO = new javax.swing.JTextField(); txtGastosFinancieros = new javax.swing.JTextField(); txtUtilidadAI = new javax.swing.JTextField(); txtOtrosIngresosNetos = new javax.swing.JTextField(); txtUAI = new javax.swing.JTextField(); txtImpuestos = new javax.swing.JTextField(); txtUtilidadNeta = new javax.swing.JTextField(); ImprimirPDF = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setIconifiable(true); setFrameIcon(null); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(51, 51, 51)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 102), 7)); jPanel1.setForeground(new java.awt.Color(204, 204, 204)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setForeground(new java.awt.Color(204, 204, 204)); jLabel2.setText("ESTADO DE RESULTADOS"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(211, 39, -1, -1)); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("TAPICERIA BELEN"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(242, 18, -1, -1)); fecha1.setBackground(new java.awt.Color(51, 51, 51)); fecha1.setForeground(new java.awt.Color(255, 255, 255)); fecha1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fecha1ActionPerformed(evt); } }); jPanel1.add(fecha1, new org.netbeans.lib.awtextra.AbsoluteConstraints(231, 65, 66, -1)); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setForeground(new java.awt.Color(204, 204, 204)); jLabel3.setText("Del"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(202, 67, -1, -1)); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setForeground(new java.awt.Color(204, 204, 204)); jLabel5.setText("al"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(301, 67, -1, -1)); fecha2.setBackground(new java.awt.Color(51, 51, 51)); fecha2.setForeground(new java.awt.Color(255, 255, 255)); fecha2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fecha2ActionPerformed(evt); } }); jPanel1.add(fecha2, new org.netbeans.lib.awtextra.AbsoluteConstraints(321, 65, 66, -1)); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(204, 204, 204)); jLabel6.setText("- Costo de lo vendido"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(133, 181, -1, -1)); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(204, 204, 204)); jLabel7.setText("Ventas Netas"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(188, 155, -1, -1)); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel8.setForeground(new java.awt.Color(204, 204, 204)); jLabel8.setText("= Utilidad Bruta"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(171, 214, -1, -1)); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel9.setForeground(new java.awt.Color(204, 204, 204)); jLabel9.setText("- Gastos de Operación"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(128, 240, -1, -1)); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(204, 204, 204)); jLabel10.setText("= Utilidad de operación"); jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(124, 285, -1, -1)); jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 206, 229, -1)); jPanel1.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 266, 229, 10)); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel11.setForeground(new java.awt.Color(204, 204, 204)); jLabel11.setText("- Impuestos"); jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(198, 436, -1, -1)); jPanel1.add(jSeparator3, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 333, 232, 7)); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel12.setForeground(new java.awt.Color(204, 204, 204)); jLabel12.setText("= Utilidad antes de otros ingresos"); jPanel1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 346, -1, -1)); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel13.setForeground(new java.awt.Color(204, 204, 204)); jLabel13.setText("+ Otros ingresos netos"); jPanel1.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(124, 372, -1, -1)); jPanel1.add(jSeparator4, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 462, 232, 7)); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel14.setForeground(new java.awt.Color(204, 204, 204)); jLabel14.setText("= Utilidad antes de impuestos"); jPanel1.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(79, 410, -1, -1)); jLabel15.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel15.setForeground(new java.awt.Color(204, 204, 204)); jLabel15.setText("- Gastos Financieros"); jPanel1.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(145, 307, -1, -1)); jPanel1.add(jSeparator5, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 398, 227, -1)); jLabel16.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel16.setForeground(new java.awt.Color(204, 204, 204)); jLabel16.setText("= Utilidad Neta"); jPanel1.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 475, -1, -1)); txtVentasNetas.setBackground(new java.awt.Color(153, 153, 153)); txtVentasNetas.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtVentasNetas, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 155, 75, -1)); txtGastosO.setBackground(new java.awt.Color(153, 153, 153)); txtGastosO.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtGastosO, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 240, 75, -1)); txtCostoVendido.setBackground(new java.awt.Color(153, 153, 153)); txtCostoVendido.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtCostoVendido, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 181, 75, -1)); txtUtilidadBruta.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadBruta.setForeground(new java.awt.Color(255, 255, 255)); txtUtilidadBruta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUtilidadBrutaActionPerformed(evt); } }); jPanel1.add(txtUtilidadBruta, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 214, 75, -1)); txtUtilidadO.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadO.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtUtilidadO, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 282, 75, -1)); txtGastosFinancieros.setBackground(new java.awt.Color(153, 153, 153)); txtGastosFinancieros.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtGastosFinancieros, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 307, 75, -1)); txtUtilidadAI.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadAI.setForeground(new java.awt.Color(255, 255, 255)); txtUtilidadAI.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUtilidadAIActionPerformed(evt); } }); jPanel1.add(txtUtilidadAI, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 346, 75, -1)); txtOtrosIngresosNetos.setBackground(new java.awt.Color(153, 153, 153)); txtOtrosIngresosNetos.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtOtrosIngresosNetos, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 372, 75, -1)); txtUAI.setBackground(new java.awt.Color(153, 153, 153)); txtUAI.setForeground(new java.awt.Color(255, 255, 255)); txtUAI.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUAIActionPerformed(evt); } }); jPanel1.add(txtUAI, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 410, 75, -1)); txtImpuestos.setBackground(new java.awt.Color(153, 153, 153)); txtImpuestos.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtImpuestos, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 436, 75, -1)); txtUtilidadNeta.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadNeta.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtUtilidadNeta, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 475, 75, -1)); ImprimirPDF.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/imprimir.png"))); // NOI18N jPanel1.add(ImprimirPDF, new org.netbeans.lib.awtextra.AbsoluteConstraints(917, 30, 90, -1)); jButton2.setText("Guargar Reporte"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 50, -1, -1)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 50, 580, 550)); jLabel1.setForeground(new java.awt.Color(204, 204, 204)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/fondo.jpg"))); // NOI18N getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 680, 640)); pack(); }// </editor-fold>//GEN-END:initComponents private void fecha1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecha1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_fecha1ActionPerformed private void fecha2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecha2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_fecha2ActionPerformed private void txtUtilidadBrutaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUtilidadBrutaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUtilidadBrutaActionPerformed private void txtUAIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUAIActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUAIActionPerformed private void txtUtilidadAIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUtilidadAIActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUtilidadAIActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed String f1=null; //String a=null, b=null, c=null; JFileChooser dlg = new JFileChooser(); int option = dlg.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION){ File f= dlg.getSelectedFile(); f1 =f.toString(); } try { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(f1+".pdf")); } catch (FileNotFoundException fileNotFoundException) { System.out.println("(No se encontró el fichero para generar el pdf)" + fileNotFoundException); } document.open(); Image image = Image.getInstance("src\\Imagenes\\LOGO1.png"); document.add(image); document.addTitle("Reporte Pdf"); document.addSubject("iText"); String tex=jLabel4.getText(); String tex1=jLabel2.getText(); String tex3=jLabel3.getText()+" "+fecha1.getText()+" "+jLabel5.getText()+" "+fecha2.getText(); try{ Paragraph p = new Paragraph(tex); Paragraph p2 = new Paragraph(tex1); Paragraph p3 = new Paragraph(tex3); p.setAlignment(Element.ALIGN_CENTER); p2.setAlignment(Element.ALIGN_CENTER); p3.setAlignment(Element.ALIGN_CENTER); document.add(p); document.add(p2); document.add(p3); document.add(new Paragraph (" ")); JOptionPane.showMessageDialog(null, "Documento creado"); } catch(Exception e){ JOptionPane.showMessageDialog(null, "error"+ e); } String [][] reporte = {{jLabel7.getText(), txtVentasNetas.getText()}, {jLabel6.getText(), txtCostoVendido.getText()}, {jLabel8.getText(), txtUtilidadBruta.getText()}, {jLabel9.getText(), txtGastosO.getText()}, {jLabel10.getText(), txtUtilidadO.getText()}, {jLabel15.getText(), txtGastosFinancieros.getText()}, {jLabel12.getText(), txtUtilidadAI.getText()}, {jLabel13.getText(), txtOtrosIngresosNetos.getText()}, {jLabel14.getText(), txtUAI.getText()}, {jLabel11.getText(), txtImpuestos.getText()}, {jLabel16.getText(), txtUtilidadNeta.getText()}}; Integer numColumns = 2; Integer numRows=11; PdfPTable table = new PdfPTable(2); // Now we fill the PDF table // Ahora llenamos la tabla del PDF PdfPCell columnHeader; String[] c= {" "," "}; // Fill table rows (rellenamos las filas de la tabla). for (int column = 0; column <2; column++) { columnHeader = new PdfPCell(new Phrase(c[column].toString())); //columnHeader = new PdfPCell(new Phrase("COL " + column)); columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(columnHeader); } table.setHeaderRows(1); // Fill table rows (rellenamos las filas de la tabla). for (int row = 0; row < numRows; row++) { for (int column = 0; column < 2; column++) { table.addCell(reporte[row][column]); } } document.add(table); document.close(); System.out.println("Se ha generado tu hoja PDF!"); } catch (DocumentException documentException) { System.out.println("Se ha producido un error al generar un documento" + documentException); } catch (IOException ex) { Logger.getLogger(EResultados.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EResultados().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ImprimirPDF; private javax.swing.JTextField fecha1; private javax.swing.JTextField fecha2; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JTextField txtCostoVendido; private javax.swing.JTextField txtGastosFinancieros; private javax.swing.JTextField txtGastosO; private javax.swing.JTextField txtImpuestos; private javax.swing.JTextField txtOtrosIngresosNetos; private javax.swing.JTextField txtUAI; private javax.swing.JTextField txtUtilidadAI; private javax.swing.JTextField txtUtilidadBruta; private javax.swing.JTextField txtUtilidadNeta; private javax.swing.JTextField txtUtilidadO; private javax.swing.JTextField txtVentasNetas; // End of variables declaration//GEN-END:variables }
UTF-8
Java
29,143
java
EResultados.java
Java
[ { "context": "import javax.swing.JOptionPane;\n\n/**\n *\n * @author Yeseliz\n */\npublic class EResultados extends javax.swing.", "end": 1071, "score": 0.936806857585907, "start": 1064, "tag": "USERNAME", "value": "Yeseliz" }, { "context": "t.Color(255, 255, 255));\n jLabel4.setText(\"TAPICERIA BELEN\");\n jPanel1.add(jLabel4, new org.netbeans.", "end": 10712, "score": 0.9998615980148315, "start": 10697, "tag": "NAME", "value": "TAPICERIA BELEN" } ]
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 EstadosFinancieros; import Logica.Conexion; import com.itextpdf.text.BadElementException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /** * * @author Yeseliz */ public class EResultados extends javax.swing.JInternalFrame { private Conexion mysql = new Conexion(); private Connection cn = mysql.conectar(); private String sentenciaSql = ""; public static Double utilidadReinvertida; /** * Creates new form EResultados */ public EResultados() { initComponents(); resultado(); fecha1.setText(fechaActual()); fecha2.setText(fechaActual()); } public void consulta() { } private void resultado() { try { //Ventas netas String sql1 = "SELECT sum(monto)FROM nuevatransaccion WHERE tipo='Venta'"; PreparedStatement statement1 = null; statement1 = this.cn.prepareStatement(sql1); ResultSet resultado1 = statement1.executeQuery(); String sql2 = "SELECT sum(monto) FROM nuevatransaccion WHERE tipo='Devolucion'"; PreparedStatement statement2 = null; statement2 = this.cn.prepareStatement(sql2); ResultSet resultado2 = statement2.executeQuery(); String sql3 = "SELECT sum(monto) from nuevatransaccion where tipo='Credito'"; PreparedStatement statement3 = null; statement3 = this.cn.prepareStatement(sql3); ResultSet resultado3 = statement3.executeQuery(); //Costo de lo vendido String sql4 = "SELECT sum(monto) from nuevatransaccion WHERE tipo='Compra'"; PreparedStatement statement4 = null; statement4 = this.cn.prepareStatement(sql4); ResultSet resultado4 = statement4.executeQuery(); //Gastos de operacion String sql5= "SELECT saldoDeudor from cuenta WHERE codigoCuenta='41'"; PreparedStatement statement5 = null; statement5 = this.cn.prepareStatement(sql5); ResultSet resultado5 = statement5.executeQuery(); //Gastos financieros String sql6="SELECT saldoDeudor from cuenta WHERE codigoCuenta='417'"; PreparedStatement statement6 = null; statement6 = this.cn.prepareStatement(sql6); ResultSet resultado6 = statement6.executeQuery(); //Otros ingresos String sql7="SELECT saldoAcreedor from cuenta WHERE codigoCuenta='520'"; PreparedStatement statement7 = null; statement7 = this.cn.prepareStatement(sql7); ResultSet resultado7 = statement7.executeQuery(); //Impuestos String sql8="SELECT saldoDeudor from cuenta WHERE codigoCuenta='415010'"; PreparedStatement statement8 = null; statement8 = this.cn.prepareStatement(sql8); ResultSet resultado8 = statement8.executeQuery(); while (resultado1.next() && resultado2.next() && resultado3.next() && resultado4.next() && resultado5.next() && resultado6.next() && resultado7.next() && resultado8.next()) { //Utilidad bruta String ventasAlContado = resultado1.getString("sum(monto)"); String ventasAlCredito = resultado2.getString("sum(monto)"); String rebajas = resultado3.getString("sum(monto)"); Double vContado = Double.parseDouble(ventasAlContado); Double vCredito = Double.parseDouble(ventasAlCredito); Double rebajaVenta = Double.parseDouble(rebajas); Double ventasNeta = vContado + vCredito - rebajaVenta; txtVentasNetas.setText(String.valueOf(ventasNeta)); String costoDeLovendido = resultado4.getString("sum(monto)"); //Calculo Double CostoVendido = Double.parseDouble(costoDeLovendido); txtCostoVendido.setText(String.valueOf(CostoVendido)); Double UtilidadBruta = ventasNeta - CostoVendido; //Resultado txtUtilidadBruta.setText(String.valueOf(UtilidadBruta)); //Utilidad de operacion String gastoOperacion= resultado5.getString("SaldoDeudor"); //Calculo Double gastoOp= Double.parseDouble(gastoOperacion); txtGastosO.setText(String.valueOf(gastoOp)); Double UtilidadOperacion= UtilidadBruta-gastoOp; txtUtilidadO.setText(String.valueOf(UtilidadOperacion)); //Utilidad antes de otros ingreso String gastoFin= resultado6.getString("SaldoDeudor"); //Calculo Double gastoFinanciero= Double.parseDouble(gastoFin); txtGastosFinancieros.setText(String.valueOf(gastoFinanciero)); Double UtilidadAntesDeOtroIngresos= UtilidadOperacion-gastoFinanciero; txtUtilidadAI.setText(String.valueOf(UtilidadAntesDeOtroIngresos)); //Utilidad antes de impuesto String OtroIngreso= resultado7.getString("saldoAcreedor"); //Calculo Double OtrosIngresosNetos= Double.parseDouble(OtroIngreso); txtOtrosIngresosNetos.setText(String.valueOf(OtrosIngresosNetos)); Double UtilidadAntesDeImpuesto=UtilidadAntesDeOtroIngresos+OtrosIngresosNetos; txtUAI.setText(String.valueOf(UtilidadAntesDeImpuesto)); //Utilidad neta String imp= resultado8.getString("saldoDeudor"); Double impuestos= Double.parseDouble(imp); txtImpuestos.setText(String.valueOf(impuestos)); Double UtilidadNeta=UtilidadAntesDeImpuesto-impuestos; txtUtilidadNeta.setText(String.valueOf(UtilidadNeta)); //Para Estado de capital UtilidadNeta=utilidadReinvertida; } } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Error al recuperar las cuentas de la base de datos"); ex.printStackTrace(); } } public static String fechaActual(){ Date fecha = new Date(); SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy"); return formatoFecha.format(fecha); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); fecha1 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); fecha2 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); jLabel11 = new javax.swing.JLabel(); jSeparator3 = new javax.swing.JSeparator(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jSeparator4 = new javax.swing.JSeparator(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jSeparator5 = new javax.swing.JSeparator(); jLabel16 = new javax.swing.JLabel(); txtVentasNetas = new javax.swing.JTextField(); txtGastosO = new javax.swing.JTextField(); txtCostoVendido = new javax.swing.JTextField(); txtUtilidadBruta = new javax.swing.JTextField(); txtUtilidadO = new javax.swing.JTextField(); txtGastosFinancieros = new javax.swing.JTextField(); txtUtilidadAI = new javax.swing.JTextField(); txtOtrosIngresosNetos = new javax.swing.JTextField(); txtUAI = new javax.swing.JTextField(); txtImpuestos = new javax.swing.JTextField(); txtUtilidadNeta = new javax.swing.JTextField(); ImprimirPDF = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setClosable(true); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setIconifiable(true); setFrameIcon(null); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(51, 51, 51)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 102), 7)); jPanel1.setForeground(new java.awt.Color(204, 204, 204)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setForeground(new java.awt.Color(204, 204, 204)); jLabel2.setText("ESTADO DE RESULTADOS"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(211, 39, -1, -1)); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("<NAME>"); jPanel1.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(242, 18, -1, -1)); fecha1.setBackground(new java.awt.Color(51, 51, 51)); fecha1.setForeground(new java.awt.Color(255, 255, 255)); fecha1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fecha1ActionPerformed(evt); } }); jPanel1.add(fecha1, new org.netbeans.lib.awtextra.AbsoluteConstraints(231, 65, 66, -1)); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setForeground(new java.awt.Color(204, 204, 204)); jLabel3.setText("Del"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(202, 67, -1, -1)); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setForeground(new java.awt.Color(204, 204, 204)); jLabel5.setText("al"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(301, 67, -1, -1)); fecha2.setBackground(new java.awt.Color(51, 51, 51)); fecha2.setForeground(new java.awt.Color(255, 255, 255)); fecha2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fecha2ActionPerformed(evt); } }); jPanel1.add(fecha2, new org.netbeans.lib.awtextra.AbsoluteConstraints(321, 65, 66, -1)); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel6.setForeground(new java.awt.Color(204, 204, 204)); jLabel6.setText("- Costo de lo vendido"); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(133, 181, -1, -1)); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel7.setForeground(new java.awt.Color(204, 204, 204)); jLabel7.setText("Ventas Netas"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(188, 155, -1, -1)); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel8.setForeground(new java.awt.Color(204, 204, 204)); jLabel8.setText("= Utilidad Bruta"); jPanel1.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(171, 214, -1, -1)); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel9.setForeground(new java.awt.Color(204, 204, 204)); jLabel9.setText("- Gastos de Operación"); jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(128, 240, -1, -1)); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel10.setForeground(new java.awt.Color(204, 204, 204)); jLabel10.setText("= Utilidad de operación"); jPanel1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(124, 285, -1, -1)); jPanel1.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 206, 229, -1)); jPanel1.add(jSeparator2, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 266, 229, 10)); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel11.setForeground(new java.awt.Color(204, 204, 204)); jLabel11.setText("- Impuestos"); jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(198, 436, -1, -1)); jPanel1.add(jSeparator3, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 333, 232, 7)); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel12.setForeground(new java.awt.Color(204, 204, 204)); jLabel12.setText("= Utilidad antes de otros ingresos"); jPanel1.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 346, -1, -1)); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel13.setForeground(new java.awt.Color(204, 204, 204)); jLabel13.setText("+ Otros ingresos netos"); jPanel1.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(124, 372, -1, -1)); jPanel1.add(jSeparator4, new org.netbeans.lib.awtextra.AbsoluteConstraints(51, 462, 232, 7)); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel14.setForeground(new java.awt.Color(204, 204, 204)); jLabel14.setText("= Utilidad antes de impuestos"); jPanel1.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(79, 410, -1, -1)); jLabel15.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel15.setForeground(new java.awt.Color(204, 204, 204)); jLabel15.setText("- Gastos Financieros"); jPanel1.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(145, 307, -1, -1)); jPanel1.add(jSeparator5, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 398, 227, -1)); jLabel16.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel16.setForeground(new java.awt.Color(204, 204, 204)); jLabel16.setText("= Utilidad Neta"); jPanel1.add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 475, -1, -1)); txtVentasNetas.setBackground(new java.awt.Color(153, 153, 153)); txtVentasNetas.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtVentasNetas, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 155, 75, -1)); txtGastosO.setBackground(new java.awt.Color(153, 153, 153)); txtGastosO.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtGastosO, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 240, 75, -1)); txtCostoVendido.setBackground(new java.awt.Color(153, 153, 153)); txtCostoVendido.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtCostoVendido, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 181, 75, -1)); txtUtilidadBruta.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadBruta.setForeground(new java.awt.Color(255, 255, 255)); txtUtilidadBruta.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUtilidadBrutaActionPerformed(evt); } }); jPanel1.add(txtUtilidadBruta, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 214, 75, -1)); txtUtilidadO.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadO.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtUtilidadO, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 282, 75, -1)); txtGastosFinancieros.setBackground(new java.awt.Color(153, 153, 153)); txtGastosFinancieros.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtGastosFinancieros, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 307, 75, -1)); txtUtilidadAI.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadAI.setForeground(new java.awt.Color(255, 255, 255)); txtUtilidadAI.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUtilidadAIActionPerformed(evt); } }); jPanel1.add(txtUtilidadAI, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 346, 75, -1)); txtOtrosIngresosNetos.setBackground(new java.awt.Color(153, 153, 153)); txtOtrosIngresosNetos.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtOtrosIngresosNetos, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 372, 75, -1)); txtUAI.setBackground(new java.awt.Color(153, 153, 153)); txtUAI.setForeground(new java.awt.Color(255, 255, 255)); txtUAI.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtUAIActionPerformed(evt); } }); jPanel1.add(txtUAI, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 410, 75, -1)); txtImpuestos.setBackground(new java.awt.Color(153, 153, 153)); txtImpuestos.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtImpuestos, new org.netbeans.lib.awtextra.AbsoluteConstraints(339, 436, 75, -1)); txtUtilidadNeta.setBackground(new java.awt.Color(153, 153, 153)); txtUtilidadNeta.setForeground(new java.awt.Color(255, 255, 255)); jPanel1.add(txtUtilidadNeta, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 475, 75, -1)); ImprimirPDF.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/imprimir.png"))); // NOI18N jPanel1.add(ImprimirPDF, new org.netbeans.lib.awtextra.AbsoluteConstraints(917, 30, 90, -1)); jButton2.setText("Guargar Reporte"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 50, -1, -1)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 50, 580, 550)); jLabel1.setForeground(new java.awt.Color(204, 204, 204)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/fondo.jpg"))); // NOI18N getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 680, 640)); pack(); }// </editor-fold>//GEN-END:initComponents private void fecha1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecha1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_fecha1ActionPerformed private void fecha2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecha2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_fecha2ActionPerformed private void txtUtilidadBrutaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUtilidadBrutaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUtilidadBrutaActionPerformed private void txtUAIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUAIActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUAIActionPerformed private void txtUtilidadAIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUtilidadAIActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtUtilidadAIActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed String f1=null; //String a=null, b=null, c=null; JFileChooser dlg = new JFileChooser(); int option = dlg.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION){ File f= dlg.getSelectedFile(); f1 =f.toString(); } try { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(f1+".pdf")); } catch (FileNotFoundException fileNotFoundException) { System.out.println("(No se encontró el fichero para generar el pdf)" + fileNotFoundException); } document.open(); Image image = Image.getInstance("src\\Imagenes\\LOGO1.png"); document.add(image); document.addTitle("Reporte Pdf"); document.addSubject("iText"); String tex=jLabel4.getText(); String tex1=jLabel2.getText(); String tex3=jLabel3.getText()+" "+fecha1.getText()+" "+jLabel5.getText()+" "+fecha2.getText(); try{ Paragraph p = new Paragraph(tex); Paragraph p2 = new Paragraph(tex1); Paragraph p3 = new Paragraph(tex3); p.setAlignment(Element.ALIGN_CENTER); p2.setAlignment(Element.ALIGN_CENTER); p3.setAlignment(Element.ALIGN_CENTER); document.add(p); document.add(p2); document.add(p3); document.add(new Paragraph (" ")); JOptionPane.showMessageDialog(null, "Documento creado"); } catch(Exception e){ JOptionPane.showMessageDialog(null, "error"+ e); } String [][] reporte = {{jLabel7.getText(), txtVentasNetas.getText()}, {jLabel6.getText(), txtCostoVendido.getText()}, {jLabel8.getText(), txtUtilidadBruta.getText()}, {jLabel9.getText(), txtGastosO.getText()}, {jLabel10.getText(), txtUtilidadO.getText()}, {jLabel15.getText(), txtGastosFinancieros.getText()}, {jLabel12.getText(), txtUtilidadAI.getText()}, {jLabel13.getText(), txtOtrosIngresosNetos.getText()}, {jLabel14.getText(), txtUAI.getText()}, {jLabel11.getText(), txtImpuestos.getText()}, {jLabel16.getText(), txtUtilidadNeta.getText()}}; Integer numColumns = 2; Integer numRows=11; PdfPTable table = new PdfPTable(2); // Now we fill the PDF table // Ahora llenamos la tabla del PDF PdfPCell columnHeader; String[] c= {" "," "}; // Fill table rows (rellenamos las filas de la tabla). for (int column = 0; column <2; column++) { columnHeader = new PdfPCell(new Phrase(c[column].toString())); //columnHeader = new PdfPCell(new Phrase("COL " + column)); columnHeader.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(columnHeader); } table.setHeaderRows(1); // Fill table rows (rellenamos las filas de la tabla). for (int row = 0; row < numRows; row++) { for (int column = 0; column < 2; column++) { table.addCell(reporte[row][column]); } } document.add(table); document.close(); System.out.println("Se ha generado tu hoja PDF!"); } catch (DocumentException documentException) { System.out.println("Se ha producido un error al generar un documento" + documentException); } catch (IOException ex) { Logger.getLogger(EResultados.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(EResultados.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new EResultados().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ImprimirPDF; private javax.swing.JTextField fecha1; private javax.swing.JTextField fecha2; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JSeparator jSeparator5; private javax.swing.JTextField txtCostoVendido; private javax.swing.JTextField txtGastosFinancieros; private javax.swing.JTextField txtGastosO; private javax.swing.JTextField txtImpuestos; private javax.swing.JTextField txtOtrosIngresosNetos; private javax.swing.JTextField txtUAI; private javax.swing.JTextField txtUtilidadAI; private javax.swing.JTextField txtUtilidadBruta; private javax.swing.JTextField txtUtilidadNeta; private javax.swing.JTextField txtUtilidadO; private javax.swing.JTextField txtVentasNetas; // End of variables declaration//GEN-END:variables }
29,134
0.646603
0.607721
606
47.085808
30.900553
186
false
false
0
0
0
0
70
0.002402
1.128713
false
false
3
27914a0f058393b105ca144b906bc51dc9f3c48c
1,194,000,909,753
d892807a3ee9828151773ad59eb3917d9c2cf206
/app/src/main/java/com/example/designmaterials/fragments/LinksFragment.java
0ebc2bb08b51f2b574b764a10a13db609764fa3f
[]
no_license
AbelSAnderson/DesignMaterials
https://github.com/AbelSAnderson/DesignMaterials
a4a286bd4bb08cd1aea4ef304b693d6a7edb0ed5
0ee9825922f2e7532d16cb321c974a93b543e5ab
refs/heads/master
2022-03-06T18:20:04.322000
2019-12-02T14:59:48
2019-12-02T14:59:48
217,394,840
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.designmaterials.fragments; import android.Manifest; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import android.preference.PreferenceManager; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.designmaterials.R; import org.json.JSONObject; import java.util.HashMap; /** * A simple {@link Fragment} subclass. */ public class LinksFragment extends Fragment { public static final int PERMISSION_TEXT = 1; public static final int PERMISSION_CALL_PHONE = 2; public LinksFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_links, container, false); view.findViewById(R.id.textButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.SEND_SMS)) { final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setTitle(getString(R.string.smsPermissionTitle)).setMessage(getString(R.string.smsPermissionMessage)).create(); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.permissionAlertDialogButtonText), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { alertDialog.dismiss(); ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.SEND_SMS}, PERMISSION_TEXT); } }); alertDialog.show(); } else { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.SEND_SMS}, PERMISSION_TEXT); } } else { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto: 0000000000")); intent.putExtra("sms_body", getString(R.string.smsIntentMessage)); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getActivity(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } } }); view.findViewById(R.id.phoneButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CALL_PHONE)) { final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setTitle(getString(R.string.phonePermissionTitle)).setMessage(getString(R.string.phonePermissionMessage)).create(); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.permissionAlertDialogButtonText), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { alertDialog.dismiss(); ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_CALL_PHONE); } }); alertDialog.show(); } else { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_CALL_PHONE); } } else { Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel: 0000000000")); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getActivity(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } } }); view.findViewById(R.id.tweeterButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = "https://twitter.com/intent/tweet?text="+getString(R.string.share_text)+"&url="+getString(R.string.share_url); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); view.findViewById(R.id.facebookButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = "https://www.facebook.com/sharer/sharer.php?u="+getString(R.string.share_url)+"&m="+getString(R.string.share_text); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); view.findViewById(R.id.emailButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); boolean pixelChoice = sharedPrefs.getBoolean("pixelChoice", false); boolean rgbChoice = sharedPrefs.getBoolean("rgbChoice", false); boolean jsonValue = sharedPrefs.getBoolean("jsonValue", false); int thePrimaryColor = sharedPreferences.getInt("primaryColor", 123); int thePrimaryColorDark = sharedPreferences.getInt("primaryColorDark", 123); int thePrimaryColorLight = sharedPreferences.getInt("primaryColorLight", 123); int theSecondaryColor = sharedPreferences.getInt("secondaryColor", 123); int theSecondaryColorDark = sharedPreferences.getInt("secondaryColorDark", 123); int theSecondaryColorLight = sharedPreferences.getInt("secondaryColorLight", 123); String headingFontName = sharedPreferences.getString("headingFontName", "opensans"); String bodyFontName = sharedPreferences.getString("bodyFontName", "opensans"); String buttonFontName = sharedPreferences.getString("buttonFontName", "opensans"); String headingFontWeight = sharedPreferences.getString("headingFontWeight", ""); String bodyFontWeight = sharedPreferences.getString("bodyFontWeight", ""); String buttonFontWeight = sharedPreferences.getString("buttonFontWeight", ""); int headingsFontsize = sharedPreferences.getInt("headingFontSize", 22); int bodyFontsize = sharedPreferences.getInt("bodyFontSize", 22); int buttonFontsize = sharedPreferences.getInt("buttonFontSize", 22); String headingFontSizeStr = ""; String bodyFontSizeStr = ""; String buttonFontSizeStr = ""; String headingFontWeightStr = ""; String bodyFontWeightStr = ""; String buttonFontWeightStr = ""; String primaryColorStr = ""; String primaryColorLightStr = ""; String primaryColorDarkStr = ""; String secondaryColorStr = ""; String secondaryColorLightStr = ""; String secondaryColorDarkStr = ""; String message=""; switch (headingFontWeight) { case "": headingFontWeightStr = "regular"; break; case "b": headingFontWeightStr = "bold"; break; case "l": headingFontWeightStr = "light"; break; } switch (bodyFontWeight) { case "": bodyFontWeightStr = "regular"; break; case "b": bodyFontWeightStr = "bold"; break; case "l": bodyFontWeightStr = "light"; break; } switch (buttonFontWeight) { case "": buttonFontWeightStr = "regular"; break; case "b": buttonFontWeightStr = "bold"; break; case "l": buttonFontWeightStr = "light"; break; } if (pixelChoice) { Resources r = getResources(); headingFontSizeStr = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, headingsFontsize, r.getDisplayMetrics()) + "px"; bodyFontSizeStr = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, bodyFontsize, r.getDisplayMetrics()) + "px"; buttonFontSizeStr = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, buttonFontsize, r.getDisplayMetrics()) + "px"; } else { headingFontSizeStr = headingsFontsize + "dp"; bodyFontSizeStr = bodyFontsize + "dp"; buttonFontSizeStr = buttonFontsize + "dp"; } if (rgbChoice) { primaryColorStr = "(R:" + Color.red(thePrimaryColor) + ", G:" + Color.green(thePrimaryColor) + ", B:" + Color.blue(thePrimaryColor) + ")"; primaryColorLightStr = "(R:" + Color.red(thePrimaryColorLight) + ", G:" + Color.green(thePrimaryColorLight) + ", B:" + Color.blue(thePrimaryColorLight) + ")"; primaryColorDarkStr = "(R:" + Color.red(thePrimaryColorDark) + ", G:" + Color.green(thePrimaryColorDark) + ", B:" + Color.blue(thePrimaryColorDark) + ")"; secondaryColorStr = "(R:" + Color.red(theSecondaryColor) + ", G:" + Color.green(theSecondaryColor) + ", B:" + Color.blue(theSecondaryColor) + ")"; secondaryColorLightStr = "(R:" + Color.red(theSecondaryColorLight) + ", G:" + Color.green(theSecondaryColorLight) + ", B:" + Color.blue(theSecondaryColorLight) + ")"; secondaryColorDarkStr = "(R:" + Color.red(theSecondaryColorDark) + ", G:" + Color.green(theSecondaryColorDark) + ", B:" + Color.blue(theSecondaryColorDark) + ")"; } else { primaryColorStr = String.format("#%06X", (0xFFFFFF & thePrimaryColor)); primaryColorLightStr = String.format("#%06X", (0xFFFFFF & thePrimaryColorLight)); primaryColorDarkStr = String.format("#%06X", (0xFFFFFF & thePrimaryColorDark)); secondaryColorStr = String.format("#%06X", (0xFFFFFF & theSecondaryColor)); secondaryColorLightStr = String.format("#%06X", (0xFFFFFF & theSecondaryColorLight)); secondaryColorDarkStr = String.format("#%06X", (0xFFFFFF & theSecondaryColorDark)); } if(jsonValue){ HashMap<String,String> allStyle=new HashMap<>(); allStyle.put("PrimaryColor",primaryColorStr); allStyle.put("PrimaryColorLight",primaryColorLightStr); allStyle.put("PrimaryColorDark",primaryColorDarkStr); allStyle.put("SecondaryColor",secondaryColorStr); allStyle.put("SecondaryColorDark",secondaryColorDarkStr); allStyle.put("SecondaryColorLight",secondaryColorLightStr); allStyle.put("HeadingFontName",headingFontName); allStyle.put("BodyFontName",bodyFontName); allStyle.put("ButtonFontName",buttonFontName); allStyle.put("HeadingFontWeight",headingFontWeightStr); allStyle.put("BodyFontWeight",bodyFontWeightStr); allStyle.put("ButtonFontWeight",buttonFontWeightStr); allStyle.put("HeadingFontSize",headingFontSizeStr); allStyle.put("BodyFontSize",bodyFontSizeStr); allStyle.put("ButtonFontSize",buttonFontSizeStr); JSONObject jsonObject=new JSONObject(allStyle); message = getString(R.string.emailIntentMessageStart) +getString(R.string.emailIntentMessageJson)+"\n\n"+ jsonObject+"\n\n"+ getString(R.string.emailIntentMessageEnd) + "\n from " + getString(R.string.nav_header_subtitle); }else{ message = getString(R.string.emailIntentMessageStart) + getString(R.string.emailIntentPrimaryColor) +" "+ primaryColorStr + getString(R.string.emailIntentPrimaryColorLight) + " " + primaryColorLightStr + getString(R.string.emailIntentPrimaryColorDark) + " " + primaryColorDarkStr + "\n" + getString(R.string.emailIntentSecondaryColor) + " " + secondaryColorStr + getString(R.string.emailIntentSecondaryColorLight) + " " + secondaryColorLightStr + getString(R.string.emailIntentSecondaryColorDark) + secondaryColorDarkStr + " " + "\n" + getString(R.string.emailIntentHeadingFontName) + " " + headingFontName + getString(R.string.emailIntentBodyFontName) + " " + bodyFontName + getString(R.string.emailIntentButtonFontName) + " " + buttonFontName + "\n" + getString(R.string.emailIntentHeadingFontWeight) + " " + headingFontWeightStr + getString(R.string.emailIntentButtonFontName) + " " + buttonFontWeightStr + getString(R.string.emailIntentBodyFontName) + " " + bodyFontWeightStr + "\n" + getString(R.string.emailIntentHeadingFontSize) + " " + headingFontSizeStr + getString(R.string.emailIntentBodyFontSize) + " " + bodyFontSizeStr + getString(R.string.emailIntentButtonFontSize) + " " + buttonFontSizeStr + getString(R.string.emailIntentMessageEnd) + "\n from " + getString(R.string.nav_header_subtitle); } Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.emailIntentSubject)); intent.putExtra(Intent.EXTRA_TEXT, message); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getContext(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } }); view.findViewById(R.id.mapButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=37.4088695,-122.0773546(Google Headquarters)")); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getContext(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } }); return view; } }
UTF-8
Java
17,060
java
LinksFragment.java
Java
[]
null
[]
package com.example.designmaterials.fragments; import android.Manifest; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import android.preference.PreferenceManager; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.designmaterials.R; import org.json.JSONObject; import java.util.HashMap; /** * A simple {@link Fragment} subclass. */ public class LinksFragment extends Fragment { public static final int PERMISSION_TEXT = 1; public static final int PERMISSION_CALL_PHONE = 2; public LinksFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_links, container, false); view.findViewById(R.id.textButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.SEND_SMS)) { final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setTitle(getString(R.string.smsPermissionTitle)).setMessage(getString(R.string.smsPermissionMessage)).create(); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.permissionAlertDialogButtonText), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { alertDialog.dismiss(); ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.SEND_SMS}, PERMISSION_TEXT); } }); alertDialog.show(); } else { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.SEND_SMS}, PERMISSION_TEXT); } } else { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto: 0000000000")); intent.putExtra("sms_body", getString(R.string.smsIntentMessage)); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getActivity(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } } }); view.findViewById(R.id.phoneButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CALL_PHONE)) { final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).setTitle(getString(R.string.phonePermissionTitle)).setMessage(getString(R.string.phonePermissionMessage)).create(); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, getString(R.string.permissionAlertDialogButtonText), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { alertDialog.dismiss(); ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_CALL_PHONE); } }); alertDialog.show(); } else { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_CALL_PHONE); } } else { Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel: 0000000000")); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getActivity(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } } }); view.findViewById(R.id.tweeterButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = "https://twitter.com/intent/tweet?text="+getString(R.string.share_text)+"&url="+getString(R.string.share_url); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); view.findViewById(R.id.facebookButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String url = "https://www.facebook.com/sharer/sharer.php?u="+getString(R.string.share_url)+"&m="+getString(R.string.share_text); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); view.findViewById(R.id.emailButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); boolean pixelChoice = sharedPrefs.getBoolean("pixelChoice", false); boolean rgbChoice = sharedPrefs.getBoolean("rgbChoice", false); boolean jsonValue = sharedPrefs.getBoolean("jsonValue", false); int thePrimaryColor = sharedPreferences.getInt("primaryColor", 123); int thePrimaryColorDark = sharedPreferences.getInt("primaryColorDark", 123); int thePrimaryColorLight = sharedPreferences.getInt("primaryColorLight", 123); int theSecondaryColor = sharedPreferences.getInt("secondaryColor", 123); int theSecondaryColorDark = sharedPreferences.getInt("secondaryColorDark", 123); int theSecondaryColorLight = sharedPreferences.getInt("secondaryColorLight", 123); String headingFontName = sharedPreferences.getString("headingFontName", "opensans"); String bodyFontName = sharedPreferences.getString("bodyFontName", "opensans"); String buttonFontName = sharedPreferences.getString("buttonFontName", "opensans"); String headingFontWeight = sharedPreferences.getString("headingFontWeight", ""); String bodyFontWeight = sharedPreferences.getString("bodyFontWeight", ""); String buttonFontWeight = sharedPreferences.getString("buttonFontWeight", ""); int headingsFontsize = sharedPreferences.getInt("headingFontSize", 22); int bodyFontsize = sharedPreferences.getInt("bodyFontSize", 22); int buttonFontsize = sharedPreferences.getInt("buttonFontSize", 22); String headingFontSizeStr = ""; String bodyFontSizeStr = ""; String buttonFontSizeStr = ""; String headingFontWeightStr = ""; String bodyFontWeightStr = ""; String buttonFontWeightStr = ""; String primaryColorStr = ""; String primaryColorLightStr = ""; String primaryColorDarkStr = ""; String secondaryColorStr = ""; String secondaryColorLightStr = ""; String secondaryColorDarkStr = ""; String message=""; switch (headingFontWeight) { case "": headingFontWeightStr = "regular"; break; case "b": headingFontWeightStr = "bold"; break; case "l": headingFontWeightStr = "light"; break; } switch (bodyFontWeight) { case "": bodyFontWeightStr = "regular"; break; case "b": bodyFontWeightStr = "bold"; break; case "l": bodyFontWeightStr = "light"; break; } switch (buttonFontWeight) { case "": buttonFontWeightStr = "regular"; break; case "b": buttonFontWeightStr = "bold"; break; case "l": buttonFontWeightStr = "light"; break; } if (pixelChoice) { Resources r = getResources(); headingFontSizeStr = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, headingsFontsize, r.getDisplayMetrics()) + "px"; bodyFontSizeStr = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, bodyFontsize, r.getDisplayMetrics()) + "px"; buttonFontSizeStr = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, buttonFontsize, r.getDisplayMetrics()) + "px"; } else { headingFontSizeStr = headingsFontsize + "dp"; bodyFontSizeStr = bodyFontsize + "dp"; buttonFontSizeStr = buttonFontsize + "dp"; } if (rgbChoice) { primaryColorStr = "(R:" + Color.red(thePrimaryColor) + ", G:" + Color.green(thePrimaryColor) + ", B:" + Color.blue(thePrimaryColor) + ")"; primaryColorLightStr = "(R:" + Color.red(thePrimaryColorLight) + ", G:" + Color.green(thePrimaryColorLight) + ", B:" + Color.blue(thePrimaryColorLight) + ")"; primaryColorDarkStr = "(R:" + Color.red(thePrimaryColorDark) + ", G:" + Color.green(thePrimaryColorDark) + ", B:" + Color.blue(thePrimaryColorDark) + ")"; secondaryColorStr = "(R:" + Color.red(theSecondaryColor) + ", G:" + Color.green(theSecondaryColor) + ", B:" + Color.blue(theSecondaryColor) + ")"; secondaryColorLightStr = "(R:" + Color.red(theSecondaryColorLight) + ", G:" + Color.green(theSecondaryColorLight) + ", B:" + Color.blue(theSecondaryColorLight) + ")"; secondaryColorDarkStr = "(R:" + Color.red(theSecondaryColorDark) + ", G:" + Color.green(theSecondaryColorDark) + ", B:" + Color.blue(theSecondaryColorDark) + ")"; } else { primaryColorStr = String.format("#%06X", (0xFFFFFF & thePrimaryColor)); primaryColorLightStr = String.format("#%06X", (0xFFFFFF & thePrimaryColorLight)); primaryColorDarkStr = String.format("#%06X", (0xFFFFFF & thePrimaryColorDark)); secondaryColorStr = String.format("#%06X", (0xFFFFFF & theSecondaryColor)); secondaryColorLightStr = String.format("#%06X", (0xFFFFFF & theSecondaryColorLight)); secondaryColorDarkStr = String.format("#%06X", (0xFFFFFF & theSecondaryColorDark)); } if(jsonValue){ HashMap<String,String> allStyle=new HashMap<>(); allStyle.put("PrimaryColor",primaryColorStr); allStyle.put("PrimaryColorLight",primaryColorLightStr); allStyle.put("PrimaryColorDark",primaryColorDarkStr); allStyle.put("SecondaryColor",secondaryColorStr); allStyle.put("SecondaryColorDark",secondaryColorDarkStr); allStyle.put("SecondaryColorLight",secondaryColorLightStr); allStyle.put("HeadingFontName",headingFontName); allStyle.put("BodyFontName",bodyFontName); allStyle.put("ButtonFontName",buttonFontName); allStyle.put("HeadingFontWeight",headingFontWeightStr); allStyle.put("BodyFontWeight",bodyFontWeightStr); allStyle.put("ButtonFontWeight",buttonFontWeightStr); allStyle.put("HeadingFontSize",headingFontSizeStr); allStyle.put("BodyFontSize",bodyFontSizeStr); allStyle.put("ButtonFontSize",buttonFontSizeStr); JSONObject jsonObject=new JSONObject(allStyle); message = getString(R.string.emailIntentMessageStart) +getString(R.string.emailIntentMessageJson)+"\n\n"+ jsonObject+"\n\n"+ getString(R.string.emailIntentMessageEnd) + "\n from " + getString(R.string.nav_header_subtitle); }else{ message = getString(R.string.emailIntentMessageStart) + getString(R.string.emailIntentPrimaryColor) +" "+ primaryColorStr + getString(R.string.emailIntentPrimaryColorLight) + " " + primaryColorLightStr + getString(R.string.emailIntentPrimaryColorDark) + " " + primaryColorDarkStr + "\n" + getString(R.string.emailIntentSecondaryColor) + " " + secondaryColorStr + getString(R.string.emailIntentSecondaryColorLight) + " " + secondaryColorLightStr + getString(R.string.emailIntentSecondaryColorDark) + secondaryColorDarkStr + " " + "\n" + getString(R.string.emailIntentHeadingFontName) + " " + headingFontName + getString(R.string.emailIntentBodyFontName) + " " + bodyFontName + getString(R.string.emailIntentButtonFontName) + " " + buttonFontName + "\n" + getString(R.string.emailIntentHeadingFontWeight) + " " + headingFontWeightStr + getString(R.string.emailIntentButtonFontName) + " " + buttonFontWeightStr + getString(R.string.emailIntentBodyFontName) + " " + bodyFontWeightStr + "\n" + getString(R.string.emailIntentHeadingFontSize) + " " + headingFontSizeStr + getString(R.string.emailIntentBodyFontSize) + " " + bodyFontSizeStr + getString(R.string.emailIntentButtonFontSize) + " " + buttonFontSizeStr + getString(R.string.emailIntentMessageEnd) + "\n from " + getString(R.string.nav_header_subtitle); } Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:")); intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.emailIntentSubject)); intent.putExtra(Intent.EXTRA_TEXT, message); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getContext(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } }); view.findViewById(R.id.mapButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=37.4088695,-122.0773546(Google Headquarters)")); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(getContext(), getString(R.string.errorNoSoftware), Toast.LENGTH_SHORT).show(); } } }); return view; } }
17,060
0.578429
0.573447
299
56.0602
44.494743
209
false
false
0
0
0
0
0
0
0.852843
false
false
3
03180ac3dc36058d03b545c9bcad1ffb932f6d84
15,118,284,905,025
c4d3065de45d291331ae3afc0237085d9f53d3e9
/src/com/pc/busniess/oaAddressBook/po/OaInfoAddressBookPo.java
eb9fad7398b1f223c7b85da6cfccdb90aa1f96ca
[]
no_license
dandingol03/sdrpoms
https://github.com/dandingol03/sdrpoms
edf86ab1327fa4bd2f8824234e7aaba83236e6c5
7619c66a88c0ce7a71b596168fce6ebfa568d6b6
refs/heads/master
2020-03-28T16:56:02.137000
2018-09-14T05:56:26
2018-09-14T05:56:26
148,742,208
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pc.busniess.oaAddressBook.po; import com.pc.bsp.user.po.User; /** * pc端通讯录基本字段信息 * @author c.xk * @version 1.0 * @since 1.0 */ public class OaInfoAddressBookPo extends User{ /** * */ private static final long serialVersionUID = 1L; private String id; //ID private String unitName; //单位名称 private String name; //姓名 private String userId; private String adress ; //地址 private String postalcode; //邮编 private String remark; //备注 public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUnitName() { return unitName; } public void setUnitName(String unitName) { this.unitName = unitName; } public String getAdress() { return adress; } public void setAdress(String adress) { this.adress = adress; } public String getPostalcode() { return postalcode; } public void setPostalcode(String postalcode) { this.postalcode = postalcode; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
UTF-8
Java
1,358
java
OaInfoAddressBookPo.java
Java
[ { "context": "sp.user.po.User;\n\n\n/**\n * pc端通讯录基本字段信息\n * @author c.xk\n * @version 1.0\n * @since 1.0\n */\n\npublic class", "end": 113, "score": 0.9996173977851868, "start": 109, "tag": "USERNAME", "value": "c.xk" } ]
null
[]
package com.pc.busniess.oaAddressBook.po; import com.pc.bsp.user.po.User; /** * pc端通讯录基本字段信息 * @author c.xk * @version 1.0 * @since 1.0 */ public class OaInfoAddressBookPo extends User{ /** * */ private static final long serialVersionUID = 1L; private String id; //ID private String unitName; //单位名称 private String name; //姓名 private String userId; private String adress ; //地址 private String postalcode; //邮编 private String remark; //备注 public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUnitName() { return unitName; } public void setUnitName(String unitName) { this.unitName = unitName; } public String getAdress() { return adress; } public void setAdress(String adress) { this.adress = adress; } public String getPostalcode() { return postalcode; } public void setPostalcode(String postalcode) { this.postalcode = postalcode; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
1,358
0.672755
0.66895
71
17.507042
14.819927
49
false
false
0
0
0
0
0
0
1.43662
false
false
3
b0951663a83ecdfa02ee8aa789a5230ff64080f2
26,757,646,306,255
aa904bfae2c8718e3a0e4880bb499115ed77f74e
/app/src/main/java/com/cabbage/useraccountprototype/LoginActivity.java
03a40fa496ba840b2101a9762f5b514ef46b238f
[]
no_license
liaowng/UserAccountPrototype-A
https://github.com/liaowng/UserAccountPrototype-A
1540e39889353753d0692b0c829ec78246df9bef
89db9f48b2984eb1d04043d15216376709e0ff0e
refs/heads/master
2021-06-15T19:54:09.261000
2017-04-24T03:52:36
2017-04-24T03:52:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cabbage.useraccountprototype; import android.app.Activity; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class LoginActivity extends AppCompatActivity { @BindView(R.id.app_bar) AppBarLayout mAppBarLayout; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.et_phone_number) EditText etPhoneNumber; @OnClick(R.id.btn_forget_password) void forgetPasswordOnClick() { } public static int getStatusBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); setUpAppBar(); // setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true); etPhoneNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { // TODO: done on click } return false; } }); } private void setUpAppBar() { if (mAppBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mAppBarLayout.setPadding(0, getStatusBarHeight(this), 0, 0); } setSupportActionBar(mToolbar); if (getSupportActionBar() == null) throw new AssertionError("Can not find toolbar"); getSupportActionBar().setTitle(""); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true); // getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_24dp); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); // TODO: Show popup to ask user to confirm aborting } public static void setWindowFlag(Activity activity, final int bits, boolean on) { Window win = activity.getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } }
UTF-8
Java
3,469
java
LoginActivity.java
Java
[]
null
[]
package com.cabbage.useraccountprototype; import android.app.Activity; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class LoginActivity extends AppCompatActivity { @BindView(R.id.app_bar) AppBarLayout mAppBarLayout; @BindView(R.id.toolbar) Toolbar mToolbar; @BindView(R.id.et_phone_number) EditText etPhoneNumber; @OnClick(R.id.btn_forget_password) void forgetPasswordOnClick() { } public static int getStatusBarHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); setUpAppBar(); // setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true); etPhoneNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { // TODO: done on click } return false; } }); } private void setUpAppBar() { if (mAppBarLayout != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mAppBarLayout.setPadding(0, getStatusBarHeight(this), 0, 0); } setSupportActionBar(mToolbar); if (getSupportActionBar() == null) throw new AssertionError("Can not find toolbar"); getSupportActionBar().setTitle(""); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true); // getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close_24dp); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); // TODO: Show popup to ask user to confirm aborting } public static void setWindowFlag(Activity activity, final int bits, boolean on) { Window win = activity.getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } }
3,469
0.66561
0.663015
101
33.346535
26.501797
103
false
false
0
0
0
0
0
0
0.633663
false
false
3
743eed26af80c95bdb94b62f84f85aa8331e005d
2,800,318,680,159
9eb1cda86843995e0424d0dfa36db9ff0738b0d1
/src/com/wingsoft/fdwz/dao/StioDao.java
f149e81807a8b8c617adadf8c62b9ac1754ed8b6
[]
no_license
superspeedone/webservice
https://github.com/superspeedone/webservice
c27abdc7085404301d5e348b056bd680ede4791e
0375b374758ec10e56be75e9bdf9b697e1e32c35
refs/heads/master
2016-08-09T04:33:47.075000
2016-03-07T00:59:23
2016-03-07T00:59:23
53,284,296
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wingsoft.fdwz.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.wingsoft.fdwz.pojo.db.Stio; import com.wingsoft.fdwz.util.Config; import com.wingsoft.fdwz.util.JdbcDao; import com.wingsoft.fdwz.util.Tools; public class StioDao extends JdbcDao { private Logger logger = LogManager.getLogger(StioDao.class.getName()); public List<Stio> getStio(String fromDate, String toDate) { this.logger.entry(new Object[] { fromDate , toDate}); List<Stio> stioList = new ArrayList<Stio>(); Stio stio = null; super.getConnection(Config.getInstance().getResourceName()); ResultSet rs = null; int RowNums = 0; try { rs = super.executeQuery("select io_no,io_date,io_prjcode,unitname,sourceoffunds," + "chargeman,viaman,provider,campus,storename,amount,io_prjcode_new from v_stio_push" + " where io_date >= to_date(\'"+fromDate+" 00:00:00\','yyyy-mm-dd hh24:mi:ss') " + "and io_date <= to_date(\'"+toDate+" 23:59:59\','yyyy-mm-dd hh24:mi:ss')"); while (rs.next()) { stio = new Stio(); stio.setIo_no(Tools.trim(rs.getString("io_no"))); stio.setIo_date(rs.getDate("io_date")); stio.setIo_prjcode(Tools.trim(rs.getString("io_prjcode"))); stio.setUnitname((Tools.trim(rs.getString("unitname")))); stio.setChargeman(Tools.trim(rs.getString("chargeman"))); stio.setViaman(Tools.trim(rs.getString("viaman"))); stio.setProvider(Tools.trim(rs.getString("provider"))); stio.setCampus(Tools.trim(rs.getString("campus"))); stio.setStorename(Tools.trim(rs.getString("storename"))); stio.setIo_prjcode_new(Tools.trim(rs.getString("io_prjcode_new"))); stio.setAmount(rs.getDouble("amount")); stio.setSourceoffunds(""); stioList.add(stio); RowNums++; } this.logger.info("共查询到"+RowNums+"条数据"); } catch (SQLException e) { this.logger.catching(e); super.close(rs, true, true); } finally { super.close(rs, true, true); } return ((List<Stio>) this.logger.exit(stioList)); } }
UTF-8
Java
2,146
java
StioDao.java
Java
[]
null
[]
package com.wingsoft.fdwz.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.wingsoft.fdwz.pojo.db.Stio; import com.wingsoft.fdwz.util.Config; import com.wingsoft.fdwz.util.JdbcDao; import com.wingsoft.fdwz.util.Tools; public class StioDao extends JdbcDao { private Logger logger = LogManager.getLogger(StioDao.class.getName()); public List<Stio> getStio(String fromDate, String toDate) { this.logger.entry(new Object[] { fromDate , toDate}); List<Stio> stioList = new ArrayList<Stio>(); Stio stio = null; super.getConnection(Config.getInstance().getResourceName()); ResultSet rs = null; int RowNums = 0; try { rs = super.executeQuery("select io_no,io_date,io_prjcode,unitname,sourceoffunds," + "chargeman,viaman,provider,campus,storename,amount,io_prjcode_new from v_stio_push" + " where io_date >= to_date(\'"+fromDate+" 00:00:00\','yyyy-mm-dd hh24:mi:ss') " + "and io_date <= to_date(\'"+toDate+" 23:59:59\','yyyy-mm-dd hh24:mi:ss')"); while (rs.next()) { stio = new Stio(); stio.setIo_no(Tools.trim(rs.getString("io_no"))); stio.setIo_date(rs.getDate("io_date")); stio.setIo_prjcode(Tools.trim(rs.getString("io_prjcode"))); stio.setUnitname((Tools.trim(rs.getString("unitname")))); stio.setChargeman(Tools.trim(rs.getString("chargeman"))); stio.setViaman(Tools.trim(rs.getString("viaman"))); stio.setProvider(Tools.trim(rs.getString("provider"))); stio.setCampus(Tools.trim(rs.getString("campus"))); stio.setStorename(Tools.trim(rs.getString("storename"))); stio.setIo_prjcode_new(Tools.trim(rs.getString("io_prjcode_new"))); stio.setAmount(rs.getDouble("amount")); stio.setSourceoffunds(""); stioList.add(stio); RowNums++; } this.logger.info("共查询到"+RowNums+"条数据"); } catch (SQLException e) { this.logger.catching(e); super.close(rs, true, true); } finally { super.close(rs, true, true); } return ((List<Stio>) this.logger.exit(stioList)); } }
2,146
0.695591
0.686679
58
35.758621
24.479626
90
false
false
0
0
0
0
0
0
3.086207
false
false
3
bf49497c246fe0c55165ec0d003a843850198388
6,786,048,378,531
ccfe23d2eaa4356bebc4117e937277975c43e576
/ioc/src/main/java/vip/simplify/ioc/resolver/IAnnotationResolver.java
5c8578c2768e6cfecca095fcebce41fe639877d5
[]
no_license
wlzsoft/simplify-framework
https://github.com/wlzsoft/simplify-framework
bb87c7a5345a83fb43300f5af2f8b039f5f89f99
d7cf334fa1492d6f00f04badef10470a3a07ad5e
refs/heads/master
2020-03-19T20:06:37.553000
2017-12-21T01:47:08
2018-06-11T07:23:11
136,888,509
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vip.simplify.ioc.resolver; import java.util.List; /** * <p><b>Title:</b><i>解析器</i></p> * <p>Desc: 解析各种注解信息 * 注意后续其他模块都需要以spi插件机制集成到框架中</p> * <p>source folder:{@docRoot}</p> * <p>Copyright:Copyright(c)2014</p> * <p>Company:meizu</p> * <p>Create Date:2016年1月6日 上午11:19:57</p> * <p>Modified By:luchuangye-</p> * <p>Modified Date:2016年1月6日 上午11:19:57</p> * @author <a href="mailto:luchuangye@meizu.com" >luchuangye</a> * @version Version 0.1 * @param <R> 指定解析数据的类型 */ public interface IAnnotationResolver<R extends Object> { /** * * 方法用途: 解析注解<br> * 操作步骤: TODO<br> * @param resolveList 解析的数据列表 */ void resolve(List<R> resolveList); /** * 方法用途: 解析执行bean实例,并进行依赖注入<br> * 操作步骤: TODO<br> * @param beanName */ default void resolveBeanObj(String beanName) { } }
UTF-8
Java
1,001
java
IAnnotationResolver.java
Java
[ { "context": "e Date:2016年1月6日 上午11:19:57</p>\n * <p>Modified By:luchuangye-</p>\n * <p>Modified Date:2016年1月6日 上午11:19:57</p>\n", "end": 329, "score": 0.9840325713157654, "start": 319, "tag": "USERNAME", "value": "luchuangye" }, { "context": "16年1月6日 上午11:19:57</p>\n * @author <a href=\"mailto:luchuangye@meizu.com\" >luchuangye</a>\n * @version Version 0.1\n * @para", "end": 427, "score": 0.9999282360076904, "start": 407, "tag": "EMAIL", "value": "luchuangye@meizu.com" }, { "context": " * @author <a href=\"mailto:luchuangye@meizu.com\" >luchuangye</a>\n * @version Version 0.1\n * @param <R> 指定解析数据的", "end": 440, "score": 0.9968515634536743, "start": 430, "tag": "USERNAME", "value": "luchuangye" } ]
null
[]
package vip.simplify.ioc.resolver; import java.util.List; /** * <p><b>Title:</b><i>解析器</i></p> * <p>Desc: 解析各种注解信息 * 注意后续其他模块都需要以spi插件机制集成到框架中</p> * <p>source folder:{@docRoot}</p> * <p>Copyright:Copyright(c)2014</p> * <p>Company:meizu</p> * <p>Create Date:2016年1月6日 上午11:19:57</p> * <p>Modified By:luchuangye-</p> * <p>Modified Date:2016年1月6日 上午11:19:57</p> * @author <a href="mailto:<EMAIL>" >luchuangye</a> * @version Version 0.1 * @param <R> 指定解析数据的类型 */ public interface IAnnotationResolver<R extends Object> { /** * * 方法用途: 解析注解<br> * 操作步骤: TODO<br> * @param resolveList 解析的数据列表 */ void resolve(List<R> resolveList); /** * 方法用途: 解析执行bean实例,并进行依赖注入<br> * 操作步骤: TODO<br> * @param beanName */ default void resolveBeanObj(String beanName) { } }
988
0.640491
0.603681
37
21.027027
17.535273
64
false
false
0
0
0
0
0
0
0.540541
false
false
3
902524f84416592ae309f95a168a8dfe4dec7967
2,027,224,614,991
b17918304d4669b5fb0207969fb854437e00d308
/FIONA2/sop/sop.ear/sop.war/deployed/SYSTEM/ReportingMgmt_ServerEngineConfig/1/src/sop/webflow/rt/java/code/SYSTEM___ReportingMgmt_ServerEngineConfig___1.java
120d73f74171acc8c13cce6dabc89656b6a5954a
[]
no_license
ecqweijun/fiona2
https://github.com/ecqweijun/fiona2
c4ced03755e92f35a017e724534030f4d89cbfae
42289f3961d825fdaf900ff8b4c7b517a93276b0
refs/heads/master
2018-04-20T05:27:47.479000
2017-05-11T08:48:30
2017-05-11T08:51:49
90,717,187
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Generated by SIT * * Feel free to add methods or comments. The content of this * file will be kept as-is when committed. * * Extending this class is not recommended , since the class- * name will change together with the version. Calling methods * from external code is not recommended as well , for similar * reasons. */ package sop.webflow.rt.java.code; import sop.reporting.action.ServerEngineController; import sop.reporting.util.ReportConsts; import sop.reporting.util.ReportUtil; import sop.web.smc.SmcUtil; import sop.webflow.rt.api.BaseProcessClass; public class SYSTEM___ReportingMgmt_ServerEngineConfig___1 extends BaseProcessClass { public void getServerEngineList_OnStepProcess_1() throws Exception { // getServerEngineList->OnStepProcess ServerEngineController.prepareViewServerEngineList(request); } public void searchServerEngineList_OnStepProcess_0() throws Exception { // searchServerEngineList->OnStepProcess ServerEngineController.searchServerEngineList(request); } public void createServerEngine_OnStepProcess_1() throws Exception { // createServerEngine->OnStepProcess ServerEngineController.createServerEngine(request); } public void createServerEngine_OnStepProcess_0() throws Exception { // prepareCreateServerEngine->OnStepProcess ServerEngineController.prepareCreateServerEngine(request); } public void deleteServerEngines_OnStepProcess_0() throws Exception { // deleteServerEngines->OnStepProcess ServerEngineController.deleteServerEngine(request); } public void prepareViewServerEngines_OnStepProcess_0() throws Exception { // prepareViewServerEngines->OnStepProcess ServerEngineController.viewServerEngine(request); } public void prepareEditServerEngines_OnStepProcess_0() throws Exception { // prepareEditServerEngines->OnStepProcess ServerEngineController.prepareEditServerEngineByType(request); } public void saveServerEngines_OnStepProcess_0() throws Exception { // saveServerEngines->OnStepProcess ServerEngineController.saveServerEngineByType(request); } public void sortServerEngines_OnStepProcess_0() throws Exception { // sortServerEngines->OnStepProcess ServerEngineController.doSorting(request); } public void preparePaging_OnStepProcess_0() throws Exception { // preparePaging->OnStepProcess ServerEngineController.doPaging(request); } public void clearCache_OnStepProcess_0() throws Exception { // clearCache->OnStepProcess session.removeAttribute(ReportConsts.SETYPE_RD_ATTR); } public void exportAll_OnStepProcess_0() throws Exception { // exportAll->OnStepProcess ServerEngineController.doExportAll(request, response); } public void export_OnStepProcess_0() throws Exception { // export->OnStepProcess ServerEngineController.doExport(request, response); } public void import_OnStepProcess_0() throws Exception { // import->OnStepProcess ReportUtil.handleMultipartRequest(request); ServerEngineController.doImport(request); } public void step1_OnStepProcess_0() throws Exception { // Step1->OnStepProcess SmcUtil.clearSearchStatusFromSession("searchPanelStatus"); } public void step2_OnStepProcess_0() throws Exception { // Step2->OnStepProcess SmcUtil.saveSearchStatusToSession("searchPanelStatus"); } }
UTF-8
Java
3,408
java
SYSTEM___ReportingMgmt_ServerEngineConfig___1.java
Java
[]
null
[]
/** * Generated by SIT * * Feel free to add methods or comments. The content of this * file will be kept as-is when committed. * * Extending this class is not recommended , since the class- * name will change together with the version. Calling methods * from external code is not recommended as well , for similar * reasons. */ package sop.webflow.rt.java.code; import sop.reporting.action.ServerEngineController; import sop.reporting.util.ReportConsts; import sop.reporting.util.ReportUtil; import sop.web.smc.SmcUtil; import sop.webflow.rt.api.BaseProcessClass; public class SYSTEM___ReportingMgmt_ServerEngineConfig___1 extends BaseProcessClass { public void getServerEngineList_OnStepProcess_1() throws Exception { // getServerEngineList->OnStepProcess ServerEngineController.prepareViewServerEngineList(request); } public void searchServerEngineList_OnStepProcess_0() throws Exception { // searchServerEngineList->OnStepProcess ServerEngineController.searchServerEngineList(request); } public void createServerEngine_OnStepProcess_1() throws Exception { // createServerEngine->OnStepProcess ServerEngineController.createServerEngine(request); } public void createServerEngine_OnStepProcess_0() throws Exception { // prepareCreateServerEngine->OnStepProcess ServerEngineController.prepareCreateServerEngine(request); } public void deleteServerEngines_OnStepProcess_0() throws Exception { // deleteServerEngines->OnStepProcess ServerEngineController.deleteServerEngine(request); } public void prepareViewServerEngines_OnStepProcess_0() throws Exception { // prepareViewServerEngines->OnStepProcess ServerEngineController.viewServerEngine(request); } public void prepareEditServerEngines_OnStepProcess_0() throws Exception { // prepareEditServerEngines->OnStepProcess ServerEngineController.prepareEditServerEngineByType(request); } public void saveServerEngines_OnStepProcess_0() throws Exception { // saveServerEngines->OnStepProcess ServerEngineController.saveServerEngineByType(request); } public void sortServerEngines_OnStepProcess_0() throws Exception { // sortServerEngines->OnStepProcess ServerEngineController.doSorting(request); } public void preparePaging_OnStepProcess_0() throws Exception { // preparePaging->OnStepProcess ServerEngineController.doPaging(request); } public void clearCache_OnStepProcess_0() throws Exception { // clearCache->OnStepProcess session.removeAttribute(ReportConsts.SETYPE_RD_ATTR); } public void exportAll_OnStepProcess_0() throws Exception { // exportAll->OnStepProcess ServerEngineController.doExportAll(request, response); } public void export_OnStepProcess_0() throws Exception { // export->OnStepProcess ServerEngineController.doExport(request, response); } public void import_OnStepProcess_0() throws Exception { // import->OnStepProcess ReportUtil.handleMultipartRequest(request); ServerEngineController.doImport(request); } public void step1_OnStepProcess_0() throws Exception { // Step1->OnStepProcess SmcUtil.clearSearchStatusFromSession("searchPanelStatus"); } public void step2_OnStepProcess_0() throws Exception { // Step2->OnStepProcess SmcUtil.saveSearchStatusToSession("searchPanelStatus"); } }
3,408
0.767606
0.761444
104
30.76923
26.697462
85
false
false
0
0
0
0
0
0
1.365385
false
false
3
542e33f748ce27cacccf2680f28e340f9ecedf3b
30,614,526,891,068
3803a0e10cee02d2e6e9e305f217f472ba285f87
/artemis-fluid/artemis-fluid-core/src/main/java/com/artemis/generator/strategy/e/ComponentGroupStrategy.java
0649a07fa5099c1430a95ecb46f188e8e0fa3bbe
[ "Apache-2.0", "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
junkdog/artemis-odb
https://github.com/junkdog/artemis-odb
b4090a8a8cc71cd211a97eec0d8bdae910d5424e
51628b3d316a2db1c1a7218572d03c56f2c98b0c
refs/heads/develop
2023-08-11T05:03:40.989000
2021-07-20T10:29:27
2021-07-20T10:29:27
6,331,476
774
164
BSD-2-Clause
false
2023-04-14T23:11:52
2012-10-22T08:09:23
2023-04-03T13:19:18
2023-04-14T23:11:51
3,681
737
103
35
Java
false
false
package com.artemis.generator.strategy.e; import com.artemis.generator.common.BuilderModelStrategy; import com.artemis.generator.model.FluidTypes; import com.artemis.generator.model.artemis.ArtemisModel; import com.artemis.generator.model.type.MethodDescriptor; import com.artemis.generator.model.type.ParameterizedTypeImpl; import com.artemis.generator.model.type.TypeModel; import com.artemis.generator.util.MethodBuilder; import com.artemis.utils.ImmutableBag; /** * Adds methods to access entities groups, and find entities by group. * * @author Daan van Yperen */ public class ComponentGroupStrategy implements BuilderModelStrategy { private MethodDescriptor createGroupSetter() { return new MethodBuilder(FluidTypes.E_TYPE, "group") .parameter(String.class, "group") .debugNotes("default group setter") .statement("World w = mappers.getWorld()") .statement("w.getSystem(com.artemis.managers.GroupManager.class).add(w.getEntity(entityId), group)") .returnFluid() .build(); } private MethodDescriptor createGroupsSetter() { return new MethodBuilder(FluidTypes.E_TYPE, "groups") .varArgs(true) .parameter(String[].class, "groups") .debugNotes("default groups setter") .statement("for (int i = 0; groups.length > i; i++) { group(groups[i]); }") .returnFluid() .build(); } private MethodDescriptor createGroupRemover() { return new MethodBuilder(FluidTypes.E_TYPE, "removeGroup") .parameter(String.class, "group") .debugNotes("default group remover") .statement("World w = mappers.getWorld()") .statement("w.getSystem(com.artemis.managers.GroupManager.class).remove(w.getEntity(entityId), group)") .returnFluid() .build(); } private MethodDescriptor createGroupsRemover() { return new MethodBuilder(FluidTypes.E_TYPE, "removeGroups") .varArgs(true) .parameter(String[].class, "groups") .debugNotes("default groups remover") .statement("for (int i = 0; groups.length > i; i++) { removeGroup(groups[i]); }") .returnFluid() .build(); } private MethodDescriptor createAllGroupRemover() { return new MethodBuilder(FluidTypes.E_TYPE, "removeGroups") .debugNotes("default groups remover") .statement("World w = mappers.getWorld()") .statement("w.getSystem(com.artemis.managers.GroupManager.class).removeFromAllGroups(w.getEntity(entityId))") .returnFluid() .build(); } private MethodDescriptor createGroupsGetter() { return new MethodBuilder(new ParameterizedTypeImpl(ImmutableBag.class, String.class), "groups") .debugNotes("default groups getter") .statement("World w = mappers.getWorld()") .statement("return w.getSystem(com.artemis.managers.GroupManager.class).getGroups(w.getEntity(entityId))") .build(); } private MethodDescriptor createIsInGroup() { return new MethodBuilder(boolean.class, "isInGroup") .parameter(String.class, "group") .debugNotes("default group setter") .statement("World w = mappers.getWorld()") .statement("return w.getSystem(com.artemis.managers.GroupManager.class).isInGroup(w.getEntity(entityId), group)") .build(); } /** * static EBag E::withGroup(groupName) */ private MethodDescriptor createStaticWithGroup() { return new MethodBuilder(FluidTypes.EBAG_TYPE, "withGroup") .setStatic(true) .parameter(String.class, "groupName") .javaDoc("Get entities in group..\n@return {@code EBag} of entities in group. Returns empty bag if group contains no entities.") .statement("if(_processingMapper==null) throw new RuntimeException(\"SuperMapper system must be registered before any systems using E().\");") .statement("return new EBag((com.artemis.utils.IntBag)_processingMapper.getWorld().getSystem(com.artemis.managers.GroupManager.class).getEntityIds(groupName))") .build(); } @Override public void apply(ArtemisModel artemisModel, TypeModel model) { model.add(createGroupSetter()); model.add(createGroupsSetter()); model.add(createGroupRemover()); model.add(createGroupsRemover()); model.add(createAllGroupRemover()); model.add(createGroupsGetter()); model.add(createIsInGroup()); model.add(createStaticWithGroup()); } }
UTF-8
Java
5,367
java
ComponentGroupStrategy.java
Java
[ { "context": " groups, and find entities by group.\n *\n * @author Daan van Yperen\n */\npublic class ComponentGroupStrategy implement", "end": 570, "score": 0.9998693466186523, "start": 555, "tag": "NAME", "value": "Daan van Yperen" } ]
null
[]
package com.artemis.generator.strategy.e; import com.artemis.generator.common.BuilderModelStrategy; import com.artemis.generator.model.FluidTypes; import com.artemis.generator.model.artemis.ArtemisModel; import com.artemis.generator.model.type.MethodDescriptor; import com.artemis.generator.model.type.ParameterizedTypeImpl; import com.artemis.generator.model.type.TypeModel; import com.artemis.generator.util.MethodBuilder; import com.artemis.utils.ImmutableBag; /** * Adds methods to access entities groups, and find entities by group. * * @author <NAME> */ public class ComponentGroupStrategy implements BuilderModelStrategy { private MethodDescriptor createGroupSetter() { return new MethodBuilder(FluidTypes.E_TYPE, "group") .parameter(String.class, "group") .debugNotes("default group setter") .statement("World w = mappers.getWorld()") .statement("w.getSystem(com.artemis.managers.GroupManager.class).add(w.getEntity(entityId), group)") .returnFluid() .build(); } private MethodDescriptor createGroupsSetter() { return new MethodBuilder(FluidTypes.E_TYPE, "groups") .varArgs(true) .parameter(String[].class, "groups") .debugNotes("default groups setter") .statement("for (int i = 0; groups.length > i; i++) { group(groups[i]); }") .returnFluid() .build(); } private MethodDescriptor createGroupRemover() { return new MethodBuilder(FluidTypes.E_TYPE, "removeGroup") .parameter(String.class, "group") .debugNotes("default group remover") .statement("World w = mappers.getWorld()") .statement("w.getSystem(com.artemis.managers.GroupManager.class).remove(w.getEntity(entityId), group)") .returnFluid() .build(); } private MethodDescriptor createGroupsRemover() { return new MethodBuilder(FluidTypes.E_TYPE, "removeGroups") .varArgs(true) .parameter(String[].class, "groups") .debugNotes("default groups remover") .statement("for (int i = 0; groups.length > i; i++) { removeGroup(groups[i]); }") .returnFluid() .build(); } private MethodDescriptor createAllGroupRemover() { return new MethodBuilder(FluidTypes.E_TYPE, "removeGroups") .debugNotes("default groups remover") .statement("World w = mappers.getWorld()") .statement("w.getSystem(com.artemis.managers.GroupManager.class).removeFromAllGroups(w.getEntity(entityId))") .returnFluid() .build(); } private MethodDescriptor createGroupsGetter() { return new MethodBuilder(new ParameterizedTypeImpl(ImmutableBag.class, String.class), "groups") .debugNotes("default groups getter") .statement("World w = mappers.getWorld()") .statement("return w.getSystem(com.artemis.managers.GroupManager.class).getGroups(w.getEntity(entityId))") .build(); } private MethodDescriptor createIsInGroup() { return new MethodBuilder(boolean.class, "isInGroup") .parameter(String.class, "group") .debugNotes("default group setter") .statement("World w = mappers.getWorld()") .statement("return w.getSystem(com.artemis.managers.GroupManager.class).isInGroup(w.getEntity(entityId), group)") .build(); } /** * static EBag E::withGroup(groupName) */ private MethodDescriptor createStaticWithGroup() { return new MethodBuilder(FluidTypes.EBAG_TYPE, "withGroup") .setStatic(true) .parameter(String.class, "groupName") .javaDoc("Get entities in group..\n@return {@code EBag} of entities in group. Returns empty bag if group contains no entities.") .statement("if(_processingMapper==null) throw new RuntimeException(\"SuperMapper system must be registered before any systems using E().\");") .statement("return new EBag((com.artemis.utils.IntBag)_processingMapper.getWorld().getSystem(com.artemis.managers.GroupManager.class).getEntityIds(groupName))") .build(); } @Override public void apply(ArtemisModel artemisModel, TypeModel model) { model.add(createGroupSetter()); model.add(createGroupsSetter()); model.add(createGroupRemover()); model.add(createGroupsRemover()); model.add(createAllGroupRemover()); model.add(createGroupsGetter()); model.add(createIsInGroup()); model.add(createStaticWithGroup()); } }
5,358
0.572573
0.5722
123
42.634148
37.34856
184
false
false
0
0
0
0
0
0
0.422764
false
false
3
35eebd7f2286183e0d9382eec64529ccc10149b7
24,043,226,925,534
a511f0c6d89ca2b8275a2ab912541818c7f15b42
/MY ASSIGNMENT/UserLoginProject/src/com/yash/training/controller/WelcomeServlet.java
bde183a1f1f5d235450fbd924c4c0dd937a40766
[]
no_license
SomeshGautam91/MY-Assignment
https://github.com/SomeshGautam91/MY-Assignment
7e9ae33534e8ab015691392c6843d7e80dc54432
6d2824867ac8b271b00b73e9a81a7d004883dc85
refs/heads/master
2020-12-24T20:42:18.668000
2016-04-18T07:45:01
2016-04-18T07:45:01
56,481,749
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yash.training.controller; import java.io.IOException; import java.io.PrintWriter; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yash.training.db.ConnectionProvider; import java.sql.*; @WebServlet("/WU") public class WelcomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger =LoggerFactory.getLogger(WelcomeServlet.class); public WelcomeServlet() { super(); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("userid"); String password=request.getParameter("password"); String sql="Select password from UserInfo where UserId='"+username+"'"; ConnectionProvider cp=new ConnectionProvider(); try { Connection con=cp.connect(); } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter out= response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>"); out.println("Welcome User"); out.println("</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>"); out.println("Welcome "+username); out.println("</h1>"); out.println("</body>"); out.println("</html>"); } }
UTF-8
Java
1,601
java
WelcomeServlet.java
Java
[]
null
[]
package com.yash.training.controller; import java.io.IOException; import java.io.PrintWriter; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import com.yash.training.db.ConnectionProvider; import java.sql.*; @WebServlet("/WU") public class WelcomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger =LoggerFactory.getLogger(WelcomeServlet.class); public WelcomeServlet() { super(); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("userid"); String password=request.getParameter("password"); String sql="Select password from UserInfo where UserId='"+username+"'"; ConnectionProvider cp=new ConnectionProvider(); try { Connection con=cp.connect(); } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter out= response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>"); out.println("Welcome User"); out.println("</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>"); out.println("Welcome "+username); out.println("</h1>"); out.println("</body>"); out.println("</html>"); } }
1,601
0.723923
0.7208
58
26.603449
23.148649
120
false
false
0
0
0
0
0
0
1.534483
false
false
3
cf54084f15a6e78f4fee8cbf83ba59c1fee6d6f7
10,522,669,936,983
095606f03c514b4664df2e07fe00b4f83cecef50
/bamboo-specs/src/main/java/com/streacs/java/PlanSpec.java
be810e0b7de984d3f3905c6f22abcb06873e317e
[ "MIT" ]
permissive
streacs/docker_atlassian_confluence
https://github.com/streacs/docker_atlassian_confluence
78eafa3c0ddc5a833c10e133f46ff073f12c6374
baf992b28c669874b8990b1bc22d1b79bde45e27
refs/heads/master
2021-10-18T04:36:58.149000
2019-02-13T21:53:14
2019-02-13T21:53:14
115,925,133
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.streacs.java; import com.atlassian.bamboo.specs.api.BambooSpec; import com.atlassian.bamboo.specs.api.builders.plan.Plan; import com.atlassian.bamboo.specs.api.builders.plan.PlanIdentifier; import com.atlassian.bamboo.specs.api.builders.plan.branches.BranchCleanup; import com.atlassian.bamboo.specs.api.builders.plan.branches.PlanBranchManagement; import com.atlassian.bamboo.specs.api.builders.project.Project; import com.atlassian.bamboo.specs.api.builders.repository.VcsRepositoryIdentifier; import com.atlassian.bamboo.specs.api.builders.requirement.Requirement; import com.atlassian.bamboo.specs.builders.task.CheckoutItem; import com.atlassian.bamboo.specs.builders.task.VcsCheckoutTask; import com.atlassian.bamboo.specs.builders.trigger.BitbucketServerTrigger; import com.atlassian.bamboo.specs.model.task.ScriptTaskProperties; import com.atlassian.bamboo.specs.util.BambooServer; import com.atlassian.bamboo.specs.api.builders.plan.Stage; import com.atlassian.bamboo.specs.api.builders.plan.Job; import com.atlassian.bamboo.specs.builders.task.ScriptTask; import com.atlassian.bamboo.specs.builders.trigger.ScheduledTrigger; import com.atlassian.bamboo.specs.api.builders.permission.Permissions; import com.atlassian.bamboo.specs.api.builders.permission.PermissionType; import com.atlassian.bamboo.specs.api.builders.permission.PlanPermissions; import java.time.LocalTime; import java.util.concurrent.TimeUnit; /** * Plan configuration for Bamboo. * Learn more on: <a href="https://confluence.atlassian.com/display/BAMBOO/Bamboo+Specs">https://confluence.atlassian.com/display/BAMBOO/Bamboo+Specs</a> */ @BambooSpec public class PlanSpec { /** * Run main to publish plan on Bamboo */ public static void main(final String[] args) throws Exception { //By default credentials are read from the '.credentials' file. BambooServer bambooServer = new BambooServer("https://build.streacs.com"); Plan plan = new PlanSpec().createPlan(); bambooServer.publish(plan); PlanPermissions planPermission = new PlanSpec().createPlanPermission(plan.getIdentifier()); bambooServer.publish(planPermission); } PlanPermissions createPlanPermission(PlanIdentifier planIdentifier) { Permissions permission = new Permissions() .userPermissions("sysadmin", PermissionType.ADMIN, PermissionType.CLONE, PermissionType.EDIT) .groupPermissions("crowd-administrators", PermissionType.ADMIN) .loggedInUserPermissions(PermissionType.VIEW) .anonymousUserPermissionView(); return new PlanPermissions(planIdentifier.getProjectKey(), planIdentifier.getPlanKey()).permissions(permission); } Project project() { return new Project() .name("Docker Containers") .key("DCK"); } Plan createPlan() { return new Plan( project(), "STREACS Atlassian Confluence", "EF74EC") .enabled(true) .noPluginConfigurations() .noNotifications() .linkedRepositories("DCK - STREACS Atlassian Confluence (master)") .planBranchManagement(new PlanBranchManagement() .createForVcsBranchMatching("^feature/.*|^release/.*|^develop") .triggerBuildsLikeParentPlan() .delete(new BranchCleanup() .whenInactiveInRepositoryAfterDays(7))) .description("Plan created from (https://scm.streacs.com/projects/DCK/repos/streacs_atlassian_confluence)") .triggers( new ScheduledTrigger() .description("Nightly Build") .enabled(true) .scheduleOnceDaily(LocalTime.of(00, 00)), new BitbucketServerTrigger() .name("Bitbucket Server repository triggered") .description("Commit Trigger") ) .stages( new Stage("STAGE_01").jobs( new Job("Default Job", "B497EA") .requirements(new Requirement("system.docker.executable")) .tasks( checkoutTask() ) .tasks( buildTask() ) .tasks( testTask() ) .tasks( deployTask() ) .tasks( removeTask() ) ) ); } VcsCheckoutTask checkoutTask() { return new VcsCheckoutTask() .description("Checkout Repository") .checkoutItems(new CheckoutItem() .repository(new VcsRepositoryIdentifier() .name("DCK - STREACS Atlassian Confluence (master)") ) ); } ScriptTask buildTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("build"); } ScriptTask testTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("test"); } ScriptTask deployTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("deploy"); } ScriptTask removeTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("remove"); } }
UTF-8
Java
6,019
java
PlanSpec.java
Java
[]
null
[]
package com.streacs.java; import com.atlassian.bamboo.specs.api.BambooSpec; import com.atlassian.bamboo.specs.api.builders.plan.Plan; import com.atlassian.bamboo.specs.api.builders.plan.PlanIdentifier; import com.atlassian.bamboo.specs.api.builders.plan.branches.BranchCleanup; import com.atlassian.bamboo.specs.api.builders.plan.branches.PlanBranchManagement; import com.atlassian.bamboo.specs.api.builders.project.Project; import com.atlassian.bamboo.specs.api.builders.repository.VcsRepositoryIdentifier; import com.atlassian.bamboo.specs.api.builders.requirement.Requirement; import com.atlassian.bamboo.specs.builders.task.CheckoutItem; import com.atlassian.bamboo.specs.builders.task.VcsCheckoutTask; import com.atlassian.bamboo.specs.builders.trigger.BitbucketServerTrigger; import com.atlassian.bamboo.specs.model.task.ScriptTaskProperties; import com.atlassian.bamboo.specs.util.BambooServer; import com.atlassian.bamboo.specs.api.builders.plan.Stage; import com.atlassian.bamboo.specs.api.builders.plan.Job; import com.atlassian.bamboo.specs.builders.task.ScriptTask; import com.atlassian.bamboo.specs.builders.trigger.ScheduledTrigger; import com.atlassian.bamboo.specs.api.builders.permission.Permissions; import com.atlassian.bamboo.specs.api.builders.permission.PermissionType; import com.atlassian.bamboo.specs.api.builders.permission.PlanPermissions; import java.time.LocalTime; import java.util.concurrent.TimeUnit; /** * Plan configuration for Bamboo. * Learn more on: <a href="https://confluence.atlassian.com/display/BAMBOO/Bamboo+Specs">https://confluence.atlassian.com/display/BAMBOO/Bamboo+Specs</a> */ @BambooSpec public class PlanSpec { /** * Run main to publish plan on Bamboo */ public static void main(final String[] args) throws Exception { //By default credentials are read from the '.credentials' file. BambooServer bambooServer = new BambooServer("https://build.streacs.com"); Plan plan = new PlanSpec().createPlan(); bambooServer.publish(plan); PlanPermissions planPermission = new PlanSpec().createPlanPermission(plan.getIdentifier()); bambooServer.publish(planPermission); } PlanPermissions createPlanPermission(PlanIdentifier planIdentifier) { Permissions permission = new Permissions() .userPermissions("sysadmin", PermissionType.ADMIN, PermissionType.CLONE, PermissionType.EDIT) .groupPermissions("crowd-administrators", PermissionType.ADMIN) .loggedInUserPermissions(PermissionType.VIEW) .anonymousUserPermissionView(); return new PlanPermissions(planIdentifier.getProjectKey(), planIdentifier.getPlanKey()).permissions(permission); } Project project() { return new Project() .name("Docker Containers") .key("DCK"); } Plan createPlan() { return new Plan( project(), "STREACS Atlassian Confluence", "EF74EC") .enabled(true) .noPluginConfigurations() .noNotifications() .linkedRepositories("DCK - STREACS Atlassian Confluence (master)") .planBranchManagement(new PlanBranchManagement() .createForVcsBranchMatching("^feature/.*|^release/.*|^develop") .triggerBuildsLikeParentPlan() .delete(new BranchCleanup() .whenInactiveInRepositoryAfterDays(7))) .description("Plan created from (https://scm.streacs.com/projects/DCK/repos/streacs_atlassian_confluence)") .triggers( new ScheduledTrigger() .description("Nightly Build") .enabled(true) .scheduleOnceDaily(LocalTime.of(00, 00)), new BitbucketServerTrigger() .name("Bitbucket Server repository triggered") .description("Commit Trigger") ) .stages( new Stage("STAGE_01").jobs( new Job("Default Job", "B497EA") .requirements(new Requirement("system.docker.executable")) .tasks( checkoutTask() ) .tasks( buildTask() ) .tasks( testTask() ) .tasks( deployTask() ) .tasks( removeTask() ) ) ); } VcsCheckoutTask checkoutTask() { return new VcsCheckoutTask() .description("Checkout Repository") .checkoutItems(new CheckoutItem() .repository(new VcsRepositoryIdentifier() .name("DCK - STREACS Atlassian Confluence (master)") ) ); } ScriptTask buildTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("build"); } ScriptTask testTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("test"); } ScriptTask deployTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("deploy"); } ScriptTask removeTask() { return new ScriptTask() .description("Build Docker container") .location(ScriptTaskProperties.Location.FILE) .fileFromPath("Buildfile") .argument("remove"); } }
6,019
0.619704
0.617711
151
38.86755
27.729937
153
false
false
0
0
0
0
0
0
0.324503
false
false
3
1294a73d2e7d69c79e83f585d5b08ea35b4f77eb
28,166,395,538,708
4c6acb9aabf359f37b5f62d3d3db7ca64e251992
/src/main/java/com/blastfurnace/otr/data/series/repository/SeriesAliasRepository.java
eebaeebf50610d9b369ece3ed77ea1609624e05b
[]
no_license
Blastfurnace1/series
https://github.com/Blastfurnace1/series
3cf16350d9b1754ef9fd4647fb94934cee54b058
110213ccd9adbcc6a712ed7e092c3ba035916f16
refs/heads/master
2020-03-21T23:21:00.787000
2018-07-06T14:58:02
2018-07-06T14:58:02
139,182,214
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.blastfurnace.otr.data.series.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.blastfurnace.otr.data.series.model.SeriesAlias; public interface SeriesAliasRepository extends CrudRepository<SeriesAlias, Long> { public List<SeriesAlias> findBySeriesId(Long seriesId); }
UTF-8
Java
359
java
SeriesAliasRepository.java
Java
[]
null
[]
package com.blastfurnace.otr.data.series.repository; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.blastfurnace.otr.data.series.model.SeriesAlias; public interface SeriesAliasRepository extends CrudRepository<SeriesAlias, Long> { public List<SeriesAlias> findBySeriesId(Long seriesId); }
359
0.791086
0.791086
13
25.307692
29.678753
82
false
false
0
0
0
0
0
0
0.538462
false
false
3
ab327a022d391b2cc018adc9e9335afe1dab99a2
7,885,560,013,302
64ea061a936e5d81ac458c528fce9590abb6322d
/com/syntax/class22/Main.java
f16754e2a112850c46c15390a7df180e64907b93
[]
no_license
cyberi007/JavaBatch7
https://github.com/cyberi007/JavaBatch7
363c847d519211ec342897a2334542f22383a80c
257378610190824a2ca4e971c84c66f312e7f4e4
refs/heads/master
2022-11-24T12:55:17.844000
2020-07-28T19:51:50
2020-07-28T19:51:50
283,315,023
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.syntax.class22; public class Main { public static void Apple() { System.out.println("static method without parameter"); } public static void Apple(int a) { System.out.println("static method with int parameter"); } public static void main(String[] args) { Apple(); Apple(10); } }
UTF-8
Java
347
java
Main.java
Java
[]
null
[]
package com.syntax.class22; public class Main { public static void Apple() { System.out.println("static method without parameter"); } public static void Apple(int a) { System.out.println("static method with int parameter"); } public static void main(String[] args) { Apple(); Apple(10); } }
347
0.616715
0.605187
28
11.392858
17.259241
59
false
false
0
0
0
0
0
0
1.214286
false
false
3
212a987958ad531a6343fb6adb2e418a215b3798
13,907,104,171,619
22bbddbd75402fd3ae5195dea9650b6cb06c277c
/Desenvolvimento/SGS-TI-common/src/common/entity/PessoaFisica.java
ac3dc2bc25e66be0ca8daffd73037e7fb8140fe5
[]
no_license
LuisEduardoER/sgs-ti
https://github.com/LuisEduardoER/sgs-ti
fbf4e0edaf1bab625dc2865b65f23f7792d74388
175c20c5aaa4c19b835332f8fc4b54aff15c5d55
refs/heads/master
2021-01-10T16:56:53.071000
2010-11-16T22:42:31
2010-11-16T22:42:31
44,364,188
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package common.entity; import java.util.Date; import java.util.List; public class PessoaFisica extends Cliente { private static final long serialVersionUID = 1L; private String nome; private String sexo; private Date dataNascimento; private long CPF; /** * Construtor. * * @param endereco * @param porte * @param usuarios * @param nome * @param sexo * @param dataNascimento * @param CPF */ public PessoaFisica(String endereco, Porte porte, List<Usuario> usuarios, String nome, String sexo, Date dataNascimento, long CPF) { super(endereco, porte, null, nome); this.nome = nome; this.sexo = sexo; this.dataNascimento = dataNascimento; this.CPF = CPF; } /* * GETTERs AND SETTERs */ public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSexo() { return sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public Date getDataNascimento() { return dataNascimento; } public void setDataNascimento(Date dataNascimento) { this.dataNascimento = dataNascimento; } public long getCPF() { return CPF; } public void setCPF(long cPF) { CPF = cPF; } }
UTF-8
Java
1,259
java
PessoaFisica.java
Java
[]
null
[]
package common.entity; import java.util.Date; import java.util.List; public class PessoaFisica extends Cliente { private static final long serialVersionUID = 1L; private String nome; private String sexo; private Date dataNascimento; private long CPF; /** * Construtor. * * @param endereco * @param porte * @param usuarios * @param nome * @param sexo * @param dataNascimento * @param CPF */ public PessoaFisica(String endereco, Porte porte, List<Usuario> usuarios, String nome, String sexo, Date dataNascimento, long CPF) { super(endereco, porte, null, nome); this.nome = nome; this.sexo = sexo; this.dataNascimento = dataNascimento; this.CPF = CPF; } /* * GETTERs AND SETTERs */ public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getSexo() { return sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public Date getDataNascimento() { return dataNascimento; } public void setDataNascimento(Date dataNascimento) { this.dataNascimento = dataNascimento; } public long getCPF() { return CPF; } public void setCPF(long cPF) { CPF = cPF; } }
1,259
0.655282
0.654488
63
17.984127
16.078669
74
false
false
0
0
0
0
0
0
1.587302
false
false
3
aa07118cc63cd091c30123494fa78abefb56c207
13,907,104,174,145
8eeadc680368fb7644941bcc27c36e76d5378968
/src/main/java/cs545_project/online_market/domain/User.java
44d833df5666850208e72ed0a1863f2270351ac4
[]
no_license
emanSorour107/cs545project
https://github.com/emanSorour107/cs545project
f510e98626c8f19b36cd5898fe89b7872ea78f8f
4fdf695a0f2fe1b025c93624b181bc4fd29c06ff
refs/heads/master
2022-11-21T03:44:36.173000
2020-07-15T00:19:04
2020-07-15T00:19:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cs545_project.online_market.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.Where; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Entity @Table @Data @AllArgsConstructor @NoArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") private Long id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email; @Column(name = "username") private String username; @Column(name = "password") private String password; //set status for user 0: in-active user - 1: active user @Column(name = "active") private int active; @Enumerated(EnumType.STRING) @Column(name = "seller_status") private SellerStatus sellerStatus; @Enumerated(EnumType.STRING) private UserRole role; @OneToMany(mappedBy = "user") @Where(clause="ADDRESS_TYPE='shipping'") private List<ShippingAddress> shippingAddresses = new ArrayList<>(); @OneToMany(mappedBy = "user") @Where(clause="ADDRESS_TYPE='billing'") private List<BillingAddress> billingAddresses = new ArrayList<>(); @OneToMany(mappedBy = "seller") private List<Product> products = new ArrayList<>(); @ManyToMany(cascade = CascadeType.ALL) @JoinTable( name = "buyer_following", joinColumns = {@JoinColumn(name = "buyer_id")}, inverseJoinColumns = {@JoinColumn(name = "seller_id")}, uniqueConstraints = {@UniqueConstraint(columnNames = {"buyer_id", "seller_id"})} ) private List<User> followingSellers = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "buyer") private List<Order> orders = new ArrayList<>(); @OneToMany(mappedBy = "user") private List<Card> cards = new ArrayList<>(); /** * Store Buyer points. This points will be updated every time Buyer make/cancel/return Order */ @Column(nullable = true, columnDefinition="int(1) default '0'") private double points; public double getAvailablePointsCredit() { return points/100; } public void addProduct(Product product) { this.products.add(product); } public void addFollowSeller(User seller) { this.followingSellers.add(seller); } public void removeFollowSeller(User seller) { this.followingSellers.remove(seller); } public void addOrder(Order order) { this.orders.add(order); } public void removeProduct(Product product) { this.products.remove(product); } public void addShippingAddress(ShippingAddress address) { this.shippingAddresses.add(address); } public void addBillingAddress(BillingAddress address) { this.billingAddresses.add(address); } public void followSeller(User seller) { this.followingSellers.add(seller); } public void unFollowSeller(User seller) { this.followingSellers.remove(seller); } public String getFullName() { return firstName + " " + lastName; } @Override public String toString() { return "User{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", active=" + active + ", role=" + role + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && active == user.active && Objects.equals(firstName, user.firstName) && Objects.equals(lastName, user.lastName) && Objects.equals(email, user.email) && Objects.equals(username, user.username) && Objects.equals(password, user.password) && role == user.role; } @Override public int hashCode() { return Objects.hash(id, firstName, lastName, email, username, password, active, role); } }
UTF-8
Java
3,942
java
User.java
Java
[ { "context": "\"email\")\n\tprivate String email;\n\n\t@Column(name = \"username\")\n\tprivate String username;\n\n\t@Column(name = \"pas", "end": 652, "score": 0.9993059635162354, "start": 644, "tag": "USERNAME", "value": "username" }, { "context": "ame\")\n\tprivate String username;\n\n\t@Column(name = \"password\")\n\tprivate String password;\n\n\t//set status for us", "end": 707, "score": 0.9977366924285889, "start": 699, "tag": "PASSWORD", "value": "password" }, { "context": "urn \"User{\" +\n\t\t\t\"id=\" + id +\n\t\t\t\", firstName='\" + firstName + '\\'' +\n\t\t\t\", lastName='\" + lastName + '\\'' +\n\t\t", "end": 3128, "score": 0.819283664226532, "start": 3119, "tag": "NAME", "value": "firstName" }, { "context": "stName='\" + firstName + '\\'' +\n\t\t\t\", lastName='\" + lastName + '\\'' +\n\t\t\t\", email='\" + email + '\\'' +\n\t\t\t\", us", "end": 3166, "score": 0.8365944027900696, "start": 3158, "tag": "NAME", "value": "lastName" }, { "context": "\t\t\", email='\" + email + '\\'' +\n\t\t\t\", username='\" + username + '\\'' +\n\t\t\t\", password='\" + password + '\\'' +\n\t\t", "end": 3236, "score": 0.9927041530609131, "start": 3228, "tag": "USERNAME", "value": "username" }, { "context": "sername='\" + username + '\\'' +\n\t\t\t\", password='\" + password + '\\'' +\n\t\t\t\", active=\" + active +\n\t\t\t\", role=\" +", "end": 3274, "score": 0.9989604353904724, "start": 3266, "tag": "PASSWORD", "value": "password" }, { "context": ", user.email) &&\n\t\t\tObjects.equals(username, user.username) &&\n\t\t\tObjects.equals(password, user.password) &&", "end": 3734, "score": 0.7876010537147522, "start": 3726, "tag": "USERNAME", "value": "username" }, { "context": "ame, user.username) &&\n\t\t\tObjects.equals(password, user.password) &&\n\t\t\trole == user.role;\n\t}\n\n\t@Override\n\tpublic ", "end": 3780, "score": 0.9869957566261292, "start": 3767, "tag": "PASSWORD", "value": "user.password" } ]
null
[]
package cs545_project.online_market.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.Where; import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.Objects; @Entity @Table @Data @AllArgsConstructor @NoArgsConstructor public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") private Long id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "email") private String email; @Column(name = "username") private String username; @Column(name = "<PASSWORD>") private String password; //set status for user 0: in-active user - 1: active user @Column(name = "active") private int active; @Enumerated(EnumType.STRING) @Column(name = "seller_status") private SellerStatus sellerStatus; @Enumerated(EnumType.STRING) private UserRole role; @OneToMany(mappedBy = "user") @Where(clause="ADDRESS_TYPE='shipping'") private List<ShippingAddress> shippingAddresses = new ArrayList<>(); @OneToMany(mappedBy = "user") @Where(clause="ADDRESS_TYPE='billing'") private List<BillingAddress> billingAddresses = new ArrayList<>(); @OneToMany(mappedBy = "seller") private List<Product> products = new ArrayList<>(); @ManyToMany(cascade = CascadeType.ALL) @JoinTable( name = "buyer_following", joinColumns = {@JoinColumn(name = "buyer_id")}, inverseJoinColumns = {@JoinColumn(name = "seller_id")}, uniqueConstraints = {@UniqueConstraint(columnNames = {"buyer_id", "seller_id"})} ) private List<User> followingSellers = new ArrayList<>(); @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "buyer") private List<Order> orders = new ArrayList<>(); @OneToMany(mappedBy = "user") private List<Card> cards = new ArrayList<>(); /** * Store Buyer points. This points will be updated every time Buyer make/cancel/return Order */ @Column(nullable = true, columnDefinition="int(1) default '0'") private double points; public double getAvailablePointsCredit() { return points/100; } public void addProduct(Product product) { this.products.add(product); } public void addFollowSeller(User seller) { this.followingSellers.add(seller); } public void removeFollowSeller(User seller) { this.followingSellers.remove(seller); } public void addOrder(Order order) { this.orders.add(order); } public void removeProduct(Product product) { this.products.remove(product); } public void addShippingAddress(ShippingAddress address) { this.shippingAddresses.add(address); } public void addBillingAddress(BillingAddress address) { this.billingAddresses.add(address); } public void followSeller(User seller) { this.followingSellers.add(seller); } public void unFollowSeller(User seller) { this.followingSellers.remove(seller); } public String getFullName() { return firstName + " " + lastName; } @Override public String toString() { return "User{" + "id=" + id + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", username='" + username + '\'' + ", password='" + <PASSWORD> + '\'' + ", active=" + active + ", role=" + role + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return id == user.id && active == user.active && Objects.equals(firstName, user.firstName) && Objects.equals(lastName, user.lastName) && Objects.equals(email, user.email) && Objects.equals(username, user.username) && Objects.equals(password, <PASSWORD>) && role == user.role; } @Override public int hashCode() { return Objects.hash(id, firstName, lastName, email, username, password, active, role); } }
3,943
0.698884
0.696347
160
23.63125
20.982321
93
false
false
0
0
0
0
0
0
1.4625
false
false
3
e47387765f8f2019917b4ce76e731df0f7772e19
4,750,233,834,802
e66fee69f1d7129a0b346013cf65704cfe33efe4
/문제집/Print_1529.java
e8cb5e8580967f1292436c4d3245350996f1a3d5
[]
no_license
dudrbs703/codeup
https://github.com/dudrbs703/codeup
97b4f173370b37818cf8bc50da50495f82cd822a
c0b9cea6c3db965787ad680e02b04971be476f7d
refs/heads/master
2023-02-27T17:09:55.704000
2021-02-08T02:04:45
2021-02-08T02:04:45
188,873,178
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Print_1529 */ public class Print_1529 { public static void main(String[] args) { f(); } public static void f() { System.out.println("**"); } }
UTF-8
Java
188
java
Print_1529.java
Java
[]
null
[]
/** * Print_1529 */ public class Print_1529 { public static void main(String[] args) { f(); } public static void f() { System.out.println("**"); } }
188
0.494681
0.452128
14
12.5
13.484118
44
false
false
0
0
0
0
0
0
0.142857
false
false
3
8c3fea337548b9e4447887e662db7e68cc9b7424
21,191,368,660,116
9b12893ea9fc5433cd79d56688508174b1c5503a
/biz/cloud-biz-api-extend/src/main/java/com/midea/cloud/srm/model/suppliercooperate/invoice/entity/OnlineInvoice.java
1d17768f55df536f13e0f81dd8f93f38a95df56d
[]
no_license
bellmit/cloud-srm
https://github.com/bellmit/cloud-srm
8af35dd98a0d78e3d418558f7dccf51c2ad4d22f
524e80e76f800005e013dda8d89ebd2c1e19a966
refs/heads/master
2023-07-02T15:32:52.138000
2021-08-08T17:31:04
2021-08-08T17:31:04
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.midea.cloud.srm.model.suppliercooperate.invoice.entity; import java.math.BigDecimal; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; import java.time.LocalDate; import com.midea.cloud.srm.model.common.BaseEntity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <pre> * 网上开票表 模型 * </pre> * * @author chensl26@meiCloud.com * @version 1.00.00 * * <pre> * 修改记录 * 修改后版本: * 修改人: * 修改日期: 2020-08-31 16:47:48 * 修改内容: * </pre> */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("ceea_sc_online_invoice") public class OnlineInvoice extends BaseEntity { private static final long serialVersionUID = 1L; /** * 主键,网上开票ID */ @TableId("ONLINE_INVOICE_ID") private Long onlineInvoiceId; /** * 业务实体ID */ @TableField("ORG_ID") private Long orgId; /** * 业务实体编码 */ @TableField("ORG_CODE") private String orgCode; /** * 业务实体名称 */ @TableField("ORG_NAME") private String orgName; /** * 供应商ID */ @TableField("VENDOR_ID") private Long vendorId; /** * 供应商编码 */ @TableField("VENDOR_CODE") private String vendorCode; /** * 供应商名称 */ @TableField("VENDOR_NAME") private String vendorName; /** * erp供应商编码 */ @TableField("ERP_VENDOR_CODE") private String erpVendorCode; /** * 成本类型名称 */ @TableField("COST_TYPE_NAME") private String costTypeName; /** * 成本类型编码 */ @TableField("COST_TYPE_CODE") private String costTypeCode; /** * 网上发票号 */ @TableField("ONLINE_INVOICE_NUM") private String onlineInvoiceNum; /** * 税务发票号 */ @TableField("TAX_INVOICE_NUM") private String taxInvoiceNum; /** * 费控发票号(备用,暂不使用) */ @TableField("FSSC_NO") private String fsscNo; /** * 币种ID */ @TableField("CURRENCY_ID") private Long currencyId; /** * 币种编码 */ @TableField("CURRENCY_CODE") private String currencyCode; /** * 币种名称 */ @TableField("CURRENCY_NAME") private String currencyName; /** * 汇率 */ @TableField("EXCHANGE_RATE") private BigDecimal exchangeRate; /** * 发票日期 */ @TableField("INVOICE_DATE") private LocalDate invoiceDate; /** * 实际发票金额(含税) */ @TableField("ACTUAL_INVOICE_AMOUNT_Y") private BigDecimal actualInvoiceAmountY; /** * 发票税额 */ @TableField("INVOICE_TAX") private BigDecimal invoiceTax; /** * 发票净额(不含税) */ @TableField("ACTUAL_INVOICE_AMOUNT_N") private BigDecimal actualInvoiceAmountN; /** * 含税总额(系统) */ @TableField("TAX_TOTAL_AMOUNT") private BigDecimal taxTotalAmount; /** * 税额(系统) */ @TableField("TOTAL_TAX") private BigDecimal totalTax; /** * 付款账期编码 */ @TableField("PAY_ACCOUNT_PERIOD_CODE") private String payAccountPeriodCode; /** * 付款账期名称(费控需要传) */ @TableField("PAY_ACCOUNT_PERIOD_NAME") private String payAccountPeriodName; /** * 付款方式 */ @TableField("PAY_METHOD") private String payMethod; /** * 应付账款到期日 */ @TableField("ACCOUNT_PAYABLE_DEALINE") private LocalDate accountPayableDealine; /** * 业务类型 */ @TableField("BUSINESS_TYPE") private String businessType; /** * 是否纸质附件 */ @TableField("IF_PAPER_ATTACH") private String ifPaperAttach; /** * 审批人ID */ @TableField("APPROVER_ID") private Long approverId; /** * 审批人名称 */ @TableField("APPROVER_NICKNAME") private String approverNickname; /** * 审批人登录账号 */ @TableField("APPROVER_USERNAME") private String approverUsername; /** * 审批人员工工号 */ @TableField("APPROVER_EMP_NO") private String approverEmpNo; /** * 审批部门编码 */ @TableField("APPROVER_DEPTID") private String approverDeptid; /** * 审批部门 */ @TableField("APPROVER_DEPT") private String approverDept; /** * 合同编号 */ @TableField("CONTRACT_CODE") private String contractCode; /** * 发票状态 */ @TableField("INVOICE_STATUS") private String invoiceStatus; /** * 摘要 */ @TableField("COMMENT") private String comment; /** * 起草人意见 */ @TableField("DRAFTER_VIEW") private String drafterView; /** * 生效日期(YYYY-MM-DD) */ @TableField("START_DATE") private LocalDate startDate; /** * 失效日期(YYYY-MM-DD) */ @TableField("END_DATE") private LocalDate endDate; /** * 创建人ID */ @TableField(value = "CREATED_ID", fill = FieldFill.INSERT) private Long createdId; /** * 创建人 */ @TableField(value = "CREATED_BY", fill = FieldFill.INSERT) private String createdBy; /** * 创建时间 */ @TableField(value = "CREATION_DATE", fill = FieldFill.INSERT) private Date creationDate; /** * 创建人IP */ @TableField(value = "CREATED_BY_IP", fill = FieldFill.INSERT) private String createdByIp; /** * 最后更新人ID */ @TableField(value = "LAST_UPDATED_ID", fill = FieldFill.INSERT_UPDATE) private Long lastUpdatedId; /** * 最后更新人 */ @TableField(value = "LAST_UPDATED_BY", fill = FieldFill.INSERT_UPDATE) private String lastUpdatedBy; /** * 最后更新时间 */ @TableField(value = "LAST_UPDATE_DATE", fill = FieldFill.INSERT_UPDATE) private Date lastUpdateDate; /** * 最后更新人IP */ @TableField(value = "LAST_UPDATED_BY_IP", fill = FieldFill.INSERT_UPDATE) private String lastUpdatedByIp; /** * 租户ID */ @TableField("TENANT_ID") private String tenantId; /** * 版本号 */ @TableField("VERSION") private Long version; /** * 网上开票类型:VENDOR_INVOICE,//供应商端开具 BUYER_INVOICE;//采购商端开具 */ @TableField("ONLINE_INVOICE_TYPE") private String onlineInvoiceType; /** * 已付款金额 */ @TableField("PAID_AMOUNT") private BigDecimal paidAmount; /** * 未付款金额 */ @TableField("UN_PAID_AMOUNT") private BigDecimal unPaidAmount; /** * 本次付款金额 */ @TableField("PAYING_AMOUNT") private BigDecimal payingAmount; /** * 导入状态 */ @TableField("IMPORT_STATUS") private String importStatus; /** * 项目编号 */ @TableField(exist = false) private String projectCode; /** * 项目名称 */ @TableField(exist = false) private String projectName; /** * 费控单号 */ @TableField("BOE_NO") private String boeNo; /** * 费控打印URL */ @TableField("PRINT_URL") private String printUrl; /** * 是否核销预付的虚拟发票,是传Y,否传N */ @TableField("VIRTUAL_INVOICE") private String virtualInvoice; /** * 是否服务类 */ @TableField("IS_SERVICE") private String isService; /** * 纸质张数 */ @TableField("BPCOUNT") private Integer bpcount; /** * erp instid */ @TableField("INSTID") private String instid; /** * 预算告警忽略标识 */ @TableField("BUDGET_IGNORE") private String budgetIgnore; }
UTF-8
Java
8,278
java
OnlineInvoice.java
Java
[ { "context": ";\n\n/**\n* <pre>\n * 网上开票表 模型\n * </pre>\n*\n* @author chensl26@meiCloud.com\n* @version 1.00.00\n*\n* <pre>\n * 修改记录\n * 修改后版本:", "end": 577, "score": 0.9999200701713562, "start": 556, "tag": "EMAIL", "value": "chensl26@meiCloud.com" } ]
null
[]
package com.midea.cloud.srm.model.suppliercooperate.invoice.entity; import java.math.BigDecimal; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; import java.time.LocalDate; import com.midea.cloud.srm.model.common.BaseEntity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <pre> * 网上开票表 模型 * </pre> * * @author <EMAIL> * @version 1.00.00 * * <pre> * 修改记录 * 修改后版本: * 修改人: * 修改日期: 2020-08-31 16:47:48 * 修改内容: * </pre> */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("ceea_sc_online_invoice") public class OnlineInvoice extends BaseEntity { private static final long serialVersionUID = 1L; /** * 主键,网上开票ID */ @TableId("ONLINE_INVOICE_ID") private Long onlineInvoiceId; /** * 业务实体ID */ @TableField("ORG_ID") private Long orgId; /** * 业务实体编码 */ @TableField("ORG_CODE") private String orgCode; /** * 业务实体名称 */ @TableField("ORG_NAME") private String orgName; /** * 供应商ID */ @TableField("VENDOR_ID") private Long vendorId; /** * 供应商编码 */ @TableField("VENDOR_CODE") private String vendorCode; /** * 供应商名称 */ @TableField("VENDOR_NAME") private String vendorName; /** * erp供应商编码 */ @TableField("ERP_VENDOR_CODE") private String erpVendorCode; /** * 成本类型名称 */ @TableField("COST_TYPE_NAME") private String costTypeName; /** * 成本类型编码 */ @TableField("COST_TYPE_CODE") private String costTypeCode; /** * 网上发票号 */ @TableField("ONLINE_INVOICE_NUM") private String onlineInvoiceNum; /** * 税务发票号 */ @TableField("TAX_INVOICE_NUM") private String taxInvoiceNum; /** * 费控发票号(备用,暂不使用) */ @TableField("FSSC_NO") private String fsscNo; /** * 币种ID */ @TableField("CURRENCY_ID") private Long currencyId; /** * 币种编码 */ @TableField("CURRENCY_CODE") private String currencyCode; /** * 币种名称 */ @TableField("CURRENCY_NAME") private String currencyName; /** * 汇率 */ @TableField("EXCHANGE_RATE") private BigDecimal exchangeRate; /** * 发票日期 */ @TableField("INVOICE_DATE") private LocalDate invoiceDate; /** * 实际发票金额(含税) */ @TableField("ACTUAL_INVOICE_AMOUNT_Y") private BigDecimal actualInvoiceAmountY; /** * 发票税额 */ @TableField("INVOICE_TAX") private BigDecimal invoiceTax; /** * 发票净额(不含税) */ @TableField("ACTUAL_INVOICE_AMOUNT_N") private BigDecimal actualInvoiceAmountN; /** * 含税总额(系统) */ @TableField("TAX_TOTAL_AMOUNT") private BigDecimal taxTotalAmount; /** * 税额(系统) */ @TableField("TOTAL_TAX") private BigDecimal totalTax; /** * 付款账期编码 */ @TableField("PAY_ACCOUNT_PERIOD_CODE") private String payAccountPeriodCode; /** * 付款账期名称(费控需要传) */ @TableField("PAY_ACCOUNT_PERIOD_NAME") private String payAccountPeriodName; /** * 付款方式 */ @TableField("PAY_METHOD") private String payMethod; /** * 应付账款到期日 */ @TableField("ACCOUNT_PAYABLE_DEALINE") private LocalDate accountPayableDealine; /** * 业务类型 */ @TableField("BUSINESS_TYPE") private String businessType; /** * 是否纸质附件 */ @TableField("IF_PAPER_ATTACH") private String ifPaperAttach; /** * 审批人ID */ @TableField("APPROVER_ID") private Long approverId; /** * 审批人名称 */ @TableField("APPROVER_NICKNAME") private String approverNickname; /** * 审批人登录账号 */ @TableField("APPROVER_USERNAME") private String approverUsername; /** * 审批人员工工号 */ @TableField("APPROVER_EMP_NO") private String approverEmpNo; /** * 审批部门编码 */ @TableField("APPROVER_DEPTID") private String approverDeptid; /** * 审批部门 */ @TableField("APPROVER_DEPT") private String approverDept; /** * 合同编号 */ @TableField("CONTRACT_CODE") private String contractCode; /** * 发票状态 */ @TableField("INVOICE_STATUS") private String invoiceStatus; /** * 摘要 */ @TableField("COMMENT") private String comment; /** * 起草人意见 */ @TableField("DRAFTER_VIEW") private String drafterView; /** * 生效日期(YYYY-MM-DD) */ @TableField("START_DATE") private LocalDate startDate; /** * 失效日期(YYYY-MM-DD) */ @TableField("END_DATE") private LocalDate endDate; /** * 创建人ID */ @TableField(value = "CREATED_ID", fill = FieldFill.INSERT) private Long createdId; /** * 创建人 */ @TableField(value = "CREATED_BY", fill = FieldFill.INSERT) private String createdBy; /** * 创建时间 */ @TableField(value = "CREATION_DATE", fill = FieldFill.INSERT) private Date creationDate; /** * 创建人IP */ @TableField(value = "CREATED_BY_IP", fill = FieldFill.INSERT) private String createdByIp; /** * 最后更新人ID */ @TableField(value = "LAST_UPDATED_ID", fill = FieldFill.INSERT_UPDATE) private Long lastUpdatedId; /** * 最后更新人 */ @TableField(value = "LAST_UPDATED_BY", fill = FieldFill.INSERT_UPDATE) private String lastUpdatedBy; /** * 最后更新时间 */ @TableField(value = "LAST_UPDATE_DATE", fill = FieldFill.INSERT_UPDATE) private Date lastUpdateDate; /** * 最后更新人IP */ @TableField(value = "LAST_UPDATED_BY_IP", fill = FieldFill.INSERT_UPDATE) private String lastUpdatedByIp; /** * 租户ID */ @TableField("TENANT_ID") private String tenantId; /** * 版本号 */ @TableField("VERSION") private Long version; /** * 网上开票类型:VENDOR_INVOICE,//供应商端开具 BUYER_INVOICE;//采购商端开具 */ @TableField("ONLINE_INVOICE_TYPE") private String onlineInvoiceType; /** * 已付款金额 */ @TableField("PAID_AMOUNT") private BigDecimal paidAmount; /** * 未付款金额 */ @TableField("UN_PAID_AMOUNT") private BigDecimal unPaidAmount; /** * 本次付款金额 */ @TableField("PAYING_AMOUNT") private BigDecimal payingAmount; /** * 导入状态 */ @TableField("IMPORT_STATUS") private String importStatus; /** * 项目编号 */ @TableField(exist = false) private String projectCode; /** * 项目名称 */ @TableField(exist = false) private String projectName; /** * 费控单号 */ @TableField("BOE_NO") private String boeNo; /** * 费控打印URL */ @TableField("PRINT_URL") private String printUrl; /** * 是否核销预付的虚拟发票,是传Y,否传N */ @TableField("VIRTUAL_INVOICE") private String virtualInvoice; /** * 是否服务类 */ @TableField("IS_SERVICE") private String isService; /** * 纸质张数 */ @TableField("BPCOUNT") private Integer bpcount; /** * erp instid */ @TableField("INSTID") private String instid; /** * 预算告警忽略标识 */ @TableField("BUDGET_IGNORE") private String budgetIgnore; }
8,264
0.574815
0.571902
428
16.644859
15.483788
77
false
false
0
0
0
0
0
0
0.214953
false
false
3
beb545649c9c22e5279a1f09e3d6a88a0bdc40f5
31,894,427,172,146
a76682ce1034baf7ebc62fcf6f843dffce05fcc4
/Exampl/src/Sampl/ex.java
e28b389df59345c16a99744f7d3abf7b0d4b3854
[]
no_license
practice512/SampleRepo
https://github.com/practice512/SampleRepo
a51ad825da25f7b6628cd7efa371dadad460825b
4e9953027c9cceed6c31794aeb1ea8f9ae81def9
refs/heads/master
2021-01-01T19:12:07.291000
2017-07-27T13:02:11
2017-07-27T13:02:11
98,533,019
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Sampl; public class ex { public int b=10; } //public class privateex { // // public static void main(String[] args) // { // ex e =new ex(); // System.out.println(e.b); // } // //}
UTF-8
Java
198
java
ex.java
Java
[]
null
[]
package Sampl; public class ex { public int b=10; } //public class privateex { // // public static void main(String[] args) // { // ex e =new ex(); // System.out.println(e.b); // } // //}
198
0.570707
0.560606
16
11.375
12.159744
41
false
false
0
0
0
0
0
0
0.8125
false
false
3