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
sequence | 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
unknown | revision_date
unknown | committer_date
unknown | 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
unknown | gha_created_at
unknown | gha_updated_at
unknown | gha_pushed_at
unknown | 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
sequence | 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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f2e6bc184d019285c00a57319c67b5359d8cd712 | 12,541,304,557,074 | ad6d2194d0114dc07fb739f7dbdc7205c71581a4 | /src/sample/logic/CoreLogic.java | b276e5c6cae2176b2683557eca637e9695fe4522 | [] | no_license | Rkoks/FirstJavaFX | https://github.com/Rkoks/FirstJavaFX | 0a47dda6ce181994be38115eb46d1c2e62d67bd2 | 98874a74202eae0462f77fac0fa9f0244dbc1d75 | refs/heads/master | "2023-06-20T00:00:50.857000" | "2021-07-19T10:47:58" | "2021-07-19T10:47:58" | 387,430,169 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sample.logic;
import javafx.animation.AnimationTimer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class CoreLogic {
public static String resultFilePath;
public static Team selectedTeam = null;
public static Comparator<Team> teamComparator = new TeamComparatorByResults();
public static ObservableList<Team> teams = FXCollections.observableArrayList();
public static ObservableList<Team> sortedTeams = FXCollections.observableArrayList();
public static ScrollBarManger vBar;
public static AnimationTimer animationTimer = new AnimationTimer() {
@Override
public void handle(long l) {
vBar.animateScrollBar(l);
}
};
public static void addTeam(String newTeamName) {
if (newTeamName != null && newTeamName != "") {//проверка на пустоту
Team newTeam = new Team(newTeamName);
if (CoreLogic.teams.contains(newTeam)) { //проверка на дублирование команды
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Добавление команды");
alert.setHeaderText(null);
alert.setContentText("Команда с таким названием уже существует. Попробуйте ввести другое название!");
alert.showAndWait();
} else {
CoreLogic.teams.add(newTeam);
CoreLogic.teams.sort(new TeamComparatorByName());
}
}
}
public static void clearTextField(TextField pointField, TextField minutesField, TextField secondsField,
TextField millisField) {
pointField.clear();
minutesField.clear();
secondsField.clear();
millisField.clear();
}
public static void saveResults() {
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(resultFilePath));
List<Team> teamsToFile = new ArrayList<>(teams);
objectOutputStream.writeObject(teamsToFile);
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void loadResults(){
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(resultFilePath));
List<Team> teamsFromFile = (ArrayList<Team>) objectInputStream.readObject();
teams.clear();
teams.addAll(teamsFromFile);
refreshResultTable();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void setChangeCirclesBar(ComboBox<Integer> comboBar, Team team) {
comboBar.getItems().clear();
Integer circleCount = team.getMainCirclesCount();
if (team.isAdditionalCircleDone()) {
circleCount++;
}
ObservableList<Integer> circles = FXCollections.observableArrayList();
for (int i = 1; i < circleCount + 1; i++) {
circles.add(i);
}
comboBar.getItems().addAll(circles);
}
public static void setResultToFields(Integer selectedCircle, TextField pointField, TextField minutesField,
TextField secondsField, TextField millisField) {
Integer time;
switch (selectedCircle) {
case 1:
pointField.setText(selectedTeam.getFirstCirclePoints().toString());
time = selectedTeam.getFirstCircleTime();
minutesField.setText(time / 60000 % 60 + "");
secondsField.setText(time / 1000 % 60+"");
millisField.setText(time % 1000+"");
break;
case 2:
pointField.setText(selectedTeam.getSecondCirclePoints().toString());
time = selectedTeam.getSecondCircleTime();
minutesField.setText(time / 60000 % 60+"");
secondsField.setText(time / 1000 % 60+"");
millisField.setText(time % 1000+"");
break;
case 3:
pointField.setText(selectedTeam.getAdditionalCirclePoints().toString());
time = selectedTeam.getAdditionalCircleTime();
minutesField.setText(time / 60000 % 60+"");
secondsField.setText(time / 1000 % 60+"");
millisField.setText(time % 1000+"");
break;
}
}
public static void refreshResultTable() {
sortedTeams.clear();
sortedTeams.addAll(teams);
FXCollections.sort(sortedTeams, teamComparator);
StartInits.resultTableView.refresh();
}
}
| UTF-8 | Java | 4,268 | java | CoreLogic.java | Java | [] | null | [] | package sample.logic;
import javafx.animation.AnimationTimer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class CoreLogic {
public static String resultFilePath;
public static Team selectedTeam = null;
public static Comparator<Team> teamComparator = new TeamComparatorByResults();
public static ObservableList<Team> teams = FXCollections.observableArrayList();
public static ObservableList<Team> sortedTeams = FXCollections.observableArrayList();
public static ScrollBarManger vBar;
public static AnimationTimer animationTimer = new AnimationTimer() {
@Override
public void handle(long l) {
vBar.animateScrollBar(l);
}
};
public static void addTeam(String newTeamName) {
if (newTeamName != null && newTeamName != "") {//проверка на пустоту
Team newTeam = new Team(newTeamName);
if (CoreLogic.teams.contains(newTeam)) { //проверка на дублирование команды
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Добавление команды");
alert.setHeaderText(null);
alert.setContentText("Команда с таким названием уже существует. Попробуйте ввести другое название!");
alert.showAndWait();
} else {
CoreLogic.teams.add(newTeam);
CoreLogic.teams.sort(new TeamComparatorByName());
}
}
}
public static void clearTextField(TextField pointField, TextField minutesField, TextField secondsField,
TextField millisField) {
pointField.clear();
minutesField.clear();
secondsField.clear();
millisField.clear();
}
public static void saveResults() {
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(resultFilePath));
List<Team> teamsToFile = new ArrayList<>(teams);
objectOutputStream.writeObject(teamsToFile);
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void loadResults(){
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(resultFilePath));
List<Team> teamsFromFile = (ArrayList<Team>) objectInputStream.readObject();
teams.clear();
teams.addAll(teamsFromFile);
refreshResultTable();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void setChangeCirclesBar(ComboBox<Integer> comboBar, Team team) {
comboBar.getItems().clear();
Integer circleCount = team.getMainCirclesCount();
if (team.isAdditionalCircleDone()) {
circleCount++;
}
ObservableList<Integer> circles = FXCollections.observableArrayList();
for (int i = 1; i < circleCount + 1; i++) {
circles.add(i);
}
comboBar.getItems().addAll(circles);
}
public static void setResultToFields(Integer selectedCircle, TextField pointField, TextField minutesField,
TextField secondsField, TextField millisField) {
Integer time;
switch (selectedCircle) {
case 1:
pointField.setText(selectedTeam.getFirstCirclePoints().toString());
time = selectedTeam.getFirstCircleTime();
minutesField.setText(time / 60000 % 60 + "");
secondsField.setText(time / 1000 % 60+"");
millisField.setText(time % 1000+"");
break;
case 2:
pointField.setText(selectedTeam.getSecondCirclePoints().toString());
time = selectedTeam.getSecondCircleTime();
minutesField.setText(time / 60000 % 60+"");
secondsField.setText(time / 1000 % 60+"");
millisField.setText(time % 1000+"");
break;
case 3:
pointField.setText(selectedTeam.getAdditionalCirclePoints().toString());
time = selectedTeam.getAdditionalCircleTime();
minutesField.setText(time / 60000 % 60+"");
secondsField.setText(time / 1000 % 60+"");
millisField.setText(time % 1000+"");
break;
}
}
public static void refreshResultTable() {
sortedTeams.clear();
sortedTeams.addAll(teams);
FXCollections.sort(sortedTeams, teamComparator);
StartInits.resultTableView.refresh();
}
}
| 4,268 | 0.735749 | 0.722222 | 126 | 31.857143 | 26.994919 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.650794 | false | false | 8 |
7312c4471e8de552c046cbfbc699a9e24600ca06 | 2,448,131,374,454 | 1850ec23fd3b6ab9b2b1e666336ed19f3a16275b | /gateway-core/src/main/java/com/zs/gateway/bean/entity/SysDO.java | 8a4bcd35daefd30904a5b15c796c5b4cb4fe4671 | [] | no_license | langjiangit/FastGateway | https://github.com/langjiangit/FastGateway | f06606eba099cbcf291606979feed83df58040c4 | 61795278b851b0a2e00409d83ba36d19953d76ec | refs/heads/master | "2022-12-27T16:50:44.090000" | "2020-06-17T08:17:20" | "2020-06-17T08:17:20" | 308,545,069 | 0 | 1 | null | true | "2020-10-30T06:34:06" | "2020-10-30T06:34:06" | "2020-09-18T08:38:34" | "2020-10-13T22:46:25" | 142 | 0 | 0 | 0 | null | false | false | /*
* Author github: https://github.com/zs-neo
* Author Email: 2931622851@qq.com
*/
package com.zs.gateway.bean.entity;
import lombok.Data;
import java.util.Date;
/**
* 内部服务
*
* @author zhousheng
* @version 1.0
* @since 2020/6/12 22:00
*/
@Data
public class SysDO {
/**
* 主键id
*/
private Long id;
/**
* 系统名称
*/
private String name;
/**
* 系统描述
*/
private String desc;
/**
* 创建时间
*/
private Date createdTime;
/**
* 修改时间
*/
private Date modifiedTime;
}
| UTF-8 | Java | 537 | java | SysDO.java | Java | [
{
"context": "/*\n * Author github: https://github.com/zs-neo\n * Author Email: 2931622851@qq.com\n */\npackage co",
"end": 46,
"score": 0.9996051788330078,
"start": 40,
"tag": "USERNAME",
"value": "zs-neo"
},
{
"context": "ithub: https://github.com/zs-neo\n * Author Email: 2931622851@qq.com\n */\npackage com.zs.gateway.bean.entity;\n\nimport l",
"end": 81,
"score": 0.9997950196266174,
"start": 64,
"tag": "EMAIL",
"value": "2931622851@qq.com"
},
{
"context": "\nimport java.util.Date;\n\n/**\n * 内部服务\n *\n * @author zhousheng\n * @version 1.0\n * @since 2020/6/12 22:00\n */\n@Da",
"end": 203,
"score": 0.999668300151825,
"start": 194,
"tag": "USERNAME",
"value": "zhousheng"
}
] | null | [] | /*
* Author github: https://github.com/zs-neo
* Author Email: <EMAIL>
*/
package com.zs.gateway.bean.entity;
import lombok.Data;
import java.util.Date;
/**
* 内部服务
*
* @author zhousheng
* @version 1.0
* @since 2020/6/12 22:00
*/
@Data
public class SysDO {
/**
* 主键id
*/
private Long id;
/**
* 系统名称
*/
private String name;
/**
* 系统描述
*/
private String desc;
/**
* 创建时间
*/
private Date createdTime;
/**
* 修改时间
*/
private Date modifiedTime;
}
| 527 | 0.600406 | 0.553753 | 41 | 11.02439 | 10.942171 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.707317 | false | false | 8 |
4603173d384cb4732db4c0e120f3ab42d8de3719 | 22,454,089,052,676 | 90162f6e575911257c806a8fa980928bf5d185ed | /src/test/java/com/hasi/GetStockProfit/Application/GetStockProfitServiceTest.java | ebfb3f5c0e8c8719d498dc1dcc6c8b3c521d42a7 | [] | no_license | hasihime/GetStiockProfit | https://github.com/hasihime/GetStiockProfit | 19d3549a6593e62ac05428d51bee3857a0ef0281 | aafeda3569ab906ca299775a80b306da8ab7e06d | refs/heads/develop | "2023-02-13T04:00:56.420000" | "2021-01-14T12:08:53" | "2021-01-14T12:08:53" | 318,052,688 | 0 | 0 | null | false | "2021-01-14T12:00:47" | "2020-12-03T02:34:37" | "2021-01-05T10:40:20" | "2021-01-14T12:00:46" | 198 | 0 | 0 | 0 | Java | false | false | package com.hasi.GetStockProfit.Application;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hasi.GetStockProfit.Domain.Request.KakaoSkillRequest;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.Component;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.KakaoSkillSimpleTextResponse;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.SimpleText;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.SkillTemplate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
@SpringBootTest
class GetStockProfitServiceTest {
@Autowired
private GetStockProfitService getStockProfitService;
@Test
@DisplayName("kakaoSkill 입력값이 옳은 경우")
public void CorrectSkill() {
KakaoSkillRequest skillRequest = new KakaoSkillRequest();
skillRequest.makeUserRequest();
skillRequest.makeUtterance("correct input");
//when
boolean actual = getStockProfitService.CheckSkillRequest(skillRequest);
//then
Assertions.assertTrue(actual);
Assertions.assertEquals(skillRequest.getUtterance(), "correct input");
}
@Test
@DisplayName("kakaoSkill 입력값이 없는 경우")
public void NullSkill() {
KakaoSkillRequest skillRequest = new KakaoSkillRequest();
skillRequest.makeUserRequest();
//when
boolean actual = getStockProfitService.CheckSkillRequest(skillRequest);
//then
Assertions.assertFalse(actual);
Assertions.assertNull(skillRequest.getUtterance());
}
@Test
@DisplayName("kakaoSkill Response 전송")
public void SendSkillResponse() throws JsonProcessingException {
KakaoSkillSimpleTextResponse expected = new KakaoSkillSimpleTextResponse();
SimpleText ExpectedSimpleText = new SimpleText("Expected");
expected.setVersion("2.0");
Component outputs = new Component(ExpectedSimpleText);
SkillTemplate template = new SkillTemplate(new ArrayList<Component>());
template.getOutputs().add(outputs);
expected.setTemplate(template);
ObjectMapper mapper = new ObjectMapper();
String expectedJson = mapper.writeValueAsString(expected);
//when
KakaoSkillSimpleTextResponse skillResponse = new KakaoSkillSimpleTextResponse();
SimpleText simpleText = new SimpleText("Expected");
String actualJson = getStockProfitService.MakeKakaoResponse(skillResponse, simpleText);
//then
Assertions.assertEquals(expectedJson, actualJson);
}
} | UTF-8 | Java | 2,884 | java | GetStockProfitServiceTest.java | Java | [] | null | [] | package com.hasi.GetStockProfit.Application;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hasi.GetStockProfit.Domain.Request.KakaoSkillRequest;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.Component;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.KakaoSkillSimpleTextResponse;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.SimpleText;
import com.hasi.GetStockProfit.Domain.Response.KakaoSkillSimpleText.SkillTemplate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.ArrayList;
@SpringBootTest
class GetStockProfitServiceTest {
@Autowired
private GetStockProfitService getStockProfitService;
@Test
@DisplayName("kakaoSkill 입력값이 옳은 경우")
public void CorrectSkill() {
KakaoSkillRequest skillRequest = new KakaoSkillRequest();
skillRequest.makeUserRequest();
skillRequest.makeUtterance("correct input");
//when
boolean actual = getStockProfitService.CheckSkillRequest(skillRequest);
//then
Assertions.assertTrue(actual);
Assertions.assertEquals(skillRequest.getUtterance(), "correct input");
}
@Test
@DisplayName("kakaoSkill 입력값이 없는 경우")
public void NullSkill() {
KakaoSkillRequest skillRequest = new KakaoSkillRequest();
skillRequest.makeUserRequest();
//when
boolean actual = getStockProfitService.CheckSkillRequest(skillRequest);
//then
Assertions.assertFalse(actual);
Assertions.assertNull(skillRequest.getUtterance());
}
@Test
@DisplayName("kakaoSkill Response 전송")
public void SendSkillResponse() throws JsonProcessingException {
KakaoSkillSimpleTextResponse expected = new KakaoSkillSimpleTextResponse();
SimpleText ExpectedSimpleText = new SimpleText("Expected");
expected.setVersion("2.0");
Component outputs = new Component(ExpectedSimpleText);
SkillTemplate template = new SkillTemplate(new ArrayList<Component>());
template.getOutputs().add(outputs);
expected.setTemplate(template);
ObjectMapper mapper = new ObjectMapper();
String expectedJson = mapper.writeValueAsString(expected);
//when
KakaoSkillSimpleTextResponse skillResponse = new KakaoSkillSimpleTextResponse();
SimpleText simpleText = new SimpleText("Expected");
String actualJson = getStockProfitService.MakeKakaoResponse(skillResponse, simpleText);
//then
Assertions.assertEquals(expectedJson, actualJson);
}
} | 2,884 | 0.748244 | 0.747542 | 79 | 35.06329 | 29.624802 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.531646 | false | false | 8 |
357333de404612cd55166c7fddbd235a8598bcfc | 24,223,615,564,241 | 7c2c6fe27190233212bab0a325afd727010436e2 | /JavaFXProject/team3/SmartHomePanel/src/smarthomepanel/control/LightController.java | 2a09f10b763e2db152754b8bfbdf2d23f26693a6 | [] | no_license | blueskii/TestRepository | https://github.com/blueskii/TestRepository | 506239fdf1b7283bd25bd5b41dc6761f16792874 | da4d113755bdf1cc08e963cc2c8439b4541686af | refs/heads/master | "2018-04-05T10:22:47.653000" | "2017-07-10T02:55:34" | "2017-07-10T02:55:34" | 89,182,161 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package smarthomepanel.control;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.util.Duration;
public class LightController implements Initializable {
@FXML
private ImageView imgRoom1;
@FXML
private ImageView imgRoom2;
@FXML
private ImageView imgMain;
@FXML
private ImageView imgBig;
@FXML
private ImageView imgKitchen;
@FXML
private Button btnMain;
@FXML
private Button btnBig;
@FXML
private Button btnKitchen;
@FXML
private Button btnRoom1;
@FXML
private Button btnRoom2;
@FXML
private Button btnAllOff;
@FXML
private Button btnAllOn;
@FXML
private Button btnBack;
@FXML
private AnchorPane lightControl;
@FXML
private Button btnHome;
Image switch_off = new Image(getClass().getResource("images/icons/control/light_off2.png").toString());
Image switch_on = new Image(getClass().getResource("images/icons/control/light_on.png").toString());
public static String Main = "OFF";
public static String Big = "OFF";
public static String Room1 = "OFF";
public static String Room2 = "OFF";
public static String Kitchen = "OFF";
@FXML
private Region regionKitchen;
@FXML
private Region regionBig;
@FXML
private Region regionMain;
@FXML
private Region regionRoom2;
@FXML
private Region regionRoom1;
@FXML
private Region regionBig2;
@FXML
private Region regionMain2;
@Override
public void initialize(URL url, ResourceBundle rb) {
setting();
btnMain.setOnAction(e -> handleBtnMain(e));
btnBig.setOnAction(e -> handleBtnBig(e));
btnKitchen.setOnAction(e -> handleBtnKitchen(e));
btnRoom1.setOnAction(e -> handleBtnRoom1(e));
btnRoom2.setOnAction(e -> handleBtnRoom2(e));
btnAllOff.setOnAction(e -> handleBtnAllOff(e));
btnAllOn.setOnAction(e -> handleBtnAllOn(e));
btnBack.setOnAction(e -> handleBtnBack(e));
btnHome.setOnAction(e -> handleBtnHome(e));
}
private void setting() {
if (Main.equals("OFF")) {
imgMain.setImage(switch_off);
btnSetting(imgMain, regionMain, btnMain);
} else {
imgMain.setImage(switch_on);
btnSetting(imgMain, regionMain, btnMain);
}
if (Big.equals("OFF")) {
imgBig.setImage(switch_off);
btnSetting(imgBig, regionBig, btnBig);
} else {
imgBig.setImage(switch_on);
btnSetting(imgBig, regionBig, btnBig);
}
if (Room1.equals("OFF")) {
imgRoom1.setImage(switch_off);
btnSetting(imgRoom1, regionRoom1, btnRoom1);
} else {
imgRoom1.setImage(switch_on);
btnSetting(imgRoom1, regionRoom1, btnRoom1);
}
if (Room2.equals("OFF")) {
imgRoom2.setImage(switch_off);
btnSetting(imgRoom2, regionRoom2, btnRoom2);
} else {
imgRoom2.setImage(switch_on);
btnSetting(imgRoom2, regionRoom2, btnRoom2);
}
if (Kitchen.equals("OFF")) {
imgKitchen.setImage(switch_off);
btnSetting(imgKitchen, regionKitchen, btnKitchen);
} else {
imgKitchen.setImage(switch_on);
btnSetting(imgKitchen, regionKitchen, btnKitchen);
}
}
private void handleBtnMain(ActionEvent e) {
btnSetting(imgMain, regionMain, btnMain);
if (Main.equals("ON")) {
Main = "OFF";
} else {
Main = "ON";
}
}
private void handleBtnBig(ActionEvent e) {
btnSetting(imgBig, regionBig, btnBig);
if (Big.equals("ON")) {
Big = "OFF";
} else {
Big = "ON";
}
}
private void handleBtnRoom1(ActionEvent e) {
btnSetting(imgRoom1, regionRoom1, btnRoom1);
if (Room1.equals("ON")) {
Room1 = "OFF";
} else {
Room1 = "ON";
}
}
private void handleBtnRoom2(ActionEvent e) {
btnSetting(imgRoom2, regionRoom2, btnRoom2);
if (Room2.equals("ON")) {
Room2 = "OFF";
} else {
Room2 = "ON";
}
}
private void handleBtnKitchen(ActionEvent e) {
btnSetting(imgKitchen, regionKitchen, btnKitchen);
if (Kitchen.equals("ON")) {
Kitchen = "OFF";
} else {
Kitchen = "ON";
}
}
private void handleBtnBack(ActionEvent e) {
StackPane rootPane = (StackPane) btnBack.getScene().getRoot();
lightControl.setOpacity(1);
KeyValue keyValue = new KeyValue(lightControl.opacityProperty(), 0);
KeyFrame keyFrame = new KeyFrame(Duration.millis(500),
event -> rootPane.getChildren().remove(lightControl),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
}
private void handleBtnHome(ActionEvent e) {
StackPane rootPane = (StackPane) btnBack.getScene().getRoot();
rootPane.getChildren().remove(1);
lightControl.setOpacity(1);
KeyValue keyValue = new KeyValue(lightControl.opacityProperty(), 0);
KeyFrame keyFrame = new KeyFrame(Duration.millis(500),
event -> rootPane.getChildren().remove(lightControl),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
}
private void handleBtnAllOff(ActionEvent e) {
if (imgMain.getImage() == switch_on) {
handleBtnMain(e);
}
if (imgBig.getImage() == switch_on) {
handleBtnBig(e);
}
if (imgRoom1.getImage() == switch_on) {
handleBtnRoom1(e);
}
if (imgRoom2.getImage() == switch_on) {
handleBtnRoom2(e);
}
if (imgKitchen.getImage() == switch_on) {
handleBtnKitchen(e);
}
}
private void handleBtnAllOn(ActionEvent e) {
if (imgMain.getImage() == switch_off) {
handleBtnMain(e);
}
if (imgBig.getImage() == switch_off) {
handleBtnBig(e);
}
if (imgRoom1.getImage() == switch_off) {
handleBtnRoom1(e);
}
if (imgRoom2.getImage() == switch_off) {
handleBtnRoom2(e);
}
if (imgKitchen.getImage() == switch_off) {
handleBtnKitchen(e);
}
}
//ON, OFF에 따라 전구 이미지, 방 그림자, 글씨 색 설정
private void btnSetting(ImageView imageView, Region region, Button button) {
if (imageView.getImage() == switch_on) {
imageView.setImage(switch_off);
lightOff(region, button);
if(region==regionMain){
lightOff(regionMain2, button);
}
else if(region==regionBig){
lightOff(regionBig2, button);
}
} else {
imageView.setImage(switch_on);
lightOn(region, button);
if(region==regionMain){
lightOn(regionMain2, button);
}
else if(region==regionBig){
lightOn(regionBig2, button);
}
}
}
//방 어두워지고 환해지는거 설정
private void lightOn(Region region, Button button) {
region.setOpacity(0.7);
KeyValue keyValue = new KeyValue(region.opacityProperty(), 0);
KeyFrame keyFrame = new KeyFrame(Duration.millis(1000),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
button.setTextFill(Color.BLACK);
}
private void lightOff(Region region, Button button) {
region.setOpacity(0);
KeyValue keyValue = new KeyValue(region.opacityProperty(), 0.7);
KeyFrame keyFrame = new KeyFrame(Duration.millis(1000),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
button.setTextFill(Color.WHITE);
}
}
| UTF-8 | Java | 8,738 | java | LightController.java | Java | [] | null | [] | package smarthomepanel.control;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.util.Duration;
public class LightController implements Initializable {
@FXML
private ImageView imgRoom1;
@FXML
private ImageView imgRoom2;
@FXML
private ImageView imgMain;
@FXML
private ImageView imgBig;
@FXML
private ImageView imgKitchen;
@FXML
private Button btnMain;
@FXML
private Button btnBig;
@FXML
private Button btnKitchen;
@FXML
private Button btnRoom1;
@FXML
private Button btnRoom2;
@FXML
private Button btnAllOff;
@FXML
private Button btnAllOn;
@FXML
private Button btnBack;
@FXML
private AnchorPane lightControl;
@FXML
private Button btnHome;
Image switch_off = new Image(getClass().getResource("images/icons/control/light_off2.png").toString());
Image switch_on = new Image(getClass().getResource("images/icons/control/light_on.png").toString());
public static String Main = "OFF";
public static String Big = "OFF";
public static String Room1 = "OFF";
public static String Room2 = "OFF";
public static String Kitchen = "OFF";
@FXML
private Region regionKitchen;
@FXML
private Region regionBig;
@FXML
private Region regionMain;
@FXML
private Region regionRoom2;
@FXML
private Region regionRoom1;
@FXML
private Region regionBig2;
@FXML
private Region regionMain2;
@Override
public void initialize(URL url, ResourceBundle rb) {
setting();
btnMain.setOnAction(e -> handleBtnMain(e));
btnBig.setOnAction(e -> handleBtnBig(e));
btnKitchen.setOnAction(e -> handleBtnKitchen(e));
btnRoom1.setOnAction(e -> handleBtnRoom1(e));
btnRoom2.setOnAction(e -> handleBtnRoom2(e));
btnAllOff.setOnAction(e -> handleBtnAllOff(e));
btnAllOn.setOnAction(e -> handleBtnAllOn(e));
btnBack.setOnAction(e -> handleBtnBack(e));
btnHome.setOnAction(e -> handleBtnHome(e));
}
private void setting() {
if (Main.equals("OFF")) {
imgMain.setImage(switch_off);
btnSetting(imgMain, regionMain, btnMain);
} else {
imgMain.setImage(switch_on);
btnSetting(imgMain, regionMain, btnMain);
}
if (Big.equals("OFF")) {
imgBig.setImage(switch_off);
btnSetting(imgBig, regionBig, btnBig);
} else {
imgBig.setImage(switch_on);
btnSetting(imgBig, regionBig, btnBig);
}
if (Room1.equals("OFF")) {
imgRoom1.setImage(switch_off);
btnSetting(imgRoom1, regionRoom1, btnRoom1);
} else {
imgRoom1.setImage(switch_on);
btnSetting(imgRoom1, regionRoom1, btnRoom1);
}
if (Room2.equals("OFF")) {
imgRoom2.setImage(switch_off);
btnSetting(imgRoom2, regionRoom2, btnRoom2);
} else {
imgRoom2.setImage(switch_on);
btnSetting(imgRoom2, regionRoom2, btnRoom2);
}
if (Kitchen.equals("OFF")) {
imgKitchen.setImage(switch_off);
btnSetting(imgKitchen, regionKitchen, btnKitchen);
} else {
imgKitchen.setImage(switch_on);
btnSetting(imgKitchen, regionKitchen, btnKitchen);
}
}
private void handleBtnMain(ActionEvent e) {
btnSetting(imgMain, regionMain, btnMain);
if (Main.equals("ON")) {
Main = "OFF";
} else {
Main = "ON";
}
}
private void handleBtnBig(ActionEvent e) {
btnSetting(imgBig, regionBig, btnBig);
if (Big.equals("ON")) {
Big = "OFF";
} else {
Big = "ON";
}
}
private void handleBtnRoom1(ActionEvent e) {
btnSetting(imgRoom1, regionRoom1, btnRoom1);
if (Room1.equals("ON")) {
Room1 = "OFF";
} else {
Room1 = "ON";
}
}
private void handleBtnRoom2(ActionEvent e) {
btnSetting(imgRoom2, regionRoom2, btnRoom2);
if (Room2.equals("ON")) {
Room2 = "OFF";
} else {
Room2 = "ON";
}
}
private void handleBtnKitchen(ActionEvent e) {
btnSetting(imgKitchen, regionKitchen, btnKitchen);
if (Kitchen.equals("ON")) {
Kitchen = "OFF";
} else {
Kitchen = "ON";
}
}
private void handleBtnBack(ActionEvent e) {
StackPane rootPane = (StackPane) btnBack.getScene().getRoot();
lightControl.setOpacity(1);
KeyValue keyValue = new KeyValue(lightControl.opacityProperty(), 0);
KeyFrame keyFrame = new KeyFrame(Duration.millis(500),
event -> rootPane.getChildren().remove(lightControl),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
}
private void handleBtnHome(ActionEvent e) {
StackPane rootPane = (StackPane) btnBack.getScene().getRoot();
rootPane.getChildren().remove(1);
lightControl.setOpacity(1);
KeyValue keyValue = new KeyValue(lightControl.opacityProperty(), 0);
KeyFrame keyFrame = new KeyFrame(Duration.millis(500),
event -> rootPane.getChildren().remove(lightControl),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
}
private void handleBtnAllOff(ActionEvent e) {
if (imgMain.getImage() == switch_on) {
handleBtnMain(e);
}
if (imgBig.getImage() == switch_on) {
handleBtnBig(e);
}
if (imgRoom1.getImage() == switch_on) {
handleBtnRoom1(e);
}
if (imgRoom2.getImage() == switch_on) {
handleBtnRoom2(e);
}
if (imgKitchen.getImage() == switch_on) {
handleBtnKitchen(e);
}
}
private void handleBtnAllOn(ActionEvent e) {
if (imgMain.getImage() == switch_off) {
handleBtnMain(e);
}
if (imgBig.getImage() == switch_off) {
handleBtnBig(e);
}
if (imgRoom1.getImage() == switch_off) {
handleBtnRoom1(e);
}
if (imgRoom2.getImage() == switch_off) {
handleBtnRoom2(e);
}
if (imgKitchen.getImage() == switch_off) {
handleBtnKitchen(e);
}
}
//ON, OFF에 따라 전구 이미지, 방 그림자, 글씨 색 설정
private void btnSetting(ImageView imageView, Region region, Button button) {
if (imageView.getImage() == switch_on) {
imageView.setImage(switch_off);
lightOff(region, button);
if(region==regionMain){
lightOff(regionMain2, button);
}
else if(region==regionBig){
lightOff(regionBig2, button);
}
} else {
imageView.setImage(switch_on);
lightOn(region, button);
if(region==regionMain){
lightOn(regionMain2, button);
}
else if(region==regionBig){
lightOn(regionBig2, button);
}
}
}
//방 어두워지고 환해지는거 설정
private void lightOn(Region region, Button button) {
region.setOpacity(0.7);
KeyValue keyValue = new KeyValue(region.opacityProperty(), 0);
KeyFrame keyFrame = new KeyFrame(Duration.millis(1000),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
button.setTextFill(Color.BLACK);
}
private void lightOff(Region region, Button button) {
region.setOpacity(0);
KeyValue keyValue = new KeyValue(region.opacityProperty(), 0.7);
KeyFrame keyFrame = new KeyFrame(Duration.millis(1000),
keyValue
);
Timeline timeLine = new Timeline();
timeLine.getKeyFrames().add(keyFrame);
timeLine.play();
button.setTextFill(Color.WHITE);
}
}
| 8,738 | 0.586771 | 0.577092 | 285 | 29.449123 | 19.983021 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673684 | false | false | 8 |
8bc0b693d8a85ac6ef55a7203da8c2a749f88be3 | 39,101,382,281,112 | 6c3de5b4746a31aff53114d17b8ab9d56ca9c8a0 | /src/main/java/models/Pedido.java | 6e39c6770e319f0becc2da782b3a98a388badf7d | [] | no_license | Fortes-dev/CRUDcomandasHibernate | https://github.com/Fortes-dev/CRUDcomandasHibernate | 5aa13aab5d5dcbefcb197621e569cd6885a47f69 | 33ce5c13a39930da030c646b7e4f94988ad5d39a | refs/heads/master | "2023-09-06T01:49:41.449000" | "2021-11-08T17:52:48" | "2021-11-08T17:52:48" | 425,938,909 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package models;
import java.sql.Date;
import java.io.Serializable;
import java.util.List;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author medin Modelo de la tabla pedidos
*/
@Entity
@Table(name = "pedidos")
public class Pedido implements Serializable {
/**
* Atributos que coinciden con las columnas de la tabla pedidos
*/
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
@JoinColumn(name="fecha")
private Date fecha;
@JoinColumn(name="precio")
private double precio;
@JoinColumn(name="pendiente")
private String pendiente;
@JoinColumn(name="recogido")
private String recogido;
@ManyToOne
@JoinColumn(name="product_id")
private Producto producto;
/**
* Constructor con parámetros
*
* @param id
* @param fecha
* @param precio
* @param pendiente
* @param recogido
*/
public Pedido(Long id, Date fecha, double precio, String pendiente, String recogido) {
this.id = id;
this.fecha = fecha;
this.precio = precio;
this.pendiente = pendiente;
this.recogido = recogido;
}
/**
* Constructor vacio
*/
public Pedido() {
}
/**
* Getters y setters de los campos/atributos
*
* @return
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Producto getProducto() {
return producto;
}
public void setProducto(Producto producto) {
this.producto = producto;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public String isPendiente() {
return pendiente;
}
public void setPendiente(String pendiente) {
this.pendiente = pendiente;
}
public String isRecogido() {
return recogido;
}
public void setRecogido(String recogido) {
this.recogido = recogido;
}
/**
* Método toString para mostar un pedido por consola.
*
* @return
*/
@Override
public String toString() {
return "Pedido{" + "id=" + id + ", fecha=" + fecha + ", precio=" + precio + ", pendiente=" + pendiente + ", recogido=" + recogido + '}';
}
}
| UTF-8 | Java | 2,915 | java | Pedido.java | Java | [
{
"context": "import javax.persistence.Table;\n\n/**\n *\n * @author medin Modelo de la tabla pedidos\n */\n@Entity\n@Table(nam",
"end": 601,
"score": 0.9319003820419312,
"start": 596,
"tag": "USERNAME",
"value": "medin"
}
] | 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 models;
import java.sql.Date;
import java.io.Serializable;
import java.util.List;
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.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author medin Modelo de la tabla pedidos
*/
@Entity
@Table(name = "pedidos")
public class Pedido implements Serializable {
/**
* Atributos que coinciden con las columnas de la tabla pedidos
*/
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
@JoinColumn(name="fecha")
private Date fecha;
@JoinColumn(name="precio")
private double precio;
@JoinColumn(name="pendiente")
private String pendiente;
@JoinColumn(name="recogido")
private String recogido;
@ManyToOne
@JoinColumn(name="product_id")
private Producto producto;
/**
* Constructor con parámetros
*
* @param id
* @param fecha
* @param precio
* @param pendiente
* @param recogido
*/
public Pedido(Long id, Date fecha, double precio, String pendiente, String recogido) {
this.id = id;
this.fecha = fecha;
this.precio = precio;
this.pendiente = pendiente;
this.recogido = recogido;
}
/**
* Constructor vacio
*/
public Pedido() {
}
/**
* Getters y setters de los campos/atributos
*
* @return
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Producto getProducto() {
return producto;
}
public void setProducto(Producto producto) {
this.producto = producto;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public String isPendiente() {
return pendiente;
}
public void setPendiente(String pendiente) {
this.pendiente = pendiente;
}
public String isRecogido() {
return recogido;
}
public void setRecogido(String recogido) {
this.recogido = recogido;
}
/**
* Método toString para mostar un pedido por consola.
*
* @return
*/
@Override
public String toString() {
return "Pedido{" + "id=" + id + ", fecha=" + fecha + ", precio=" + precio + ", pendiente=" + pendiente + ", recogido=" + recogido + '}';
}
}
| 2,915 | 0.619636 | 0.619636 | 134 | 20.738806 | 20.620209 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.350746 | false | false | 8 |
bd05a571bc9d9ac984052c1ffa24566cc9a9c11b | 36,507,222,061,765 | 74389446c1a1453df3e5f26b7c52eb0eb0aef214 | /src/controller/configuracion/tickets/FxTicketController.java | 1ef32259ba1f8ee46c3629662f8b0f9c2a600b66 | [
"Apache-2.0"
] | permissive | luismy10/SysSoftIntegra | https://github.com/luismy10/SysSoftIntegra | f0721aa513a6ec88c45ded48f83079a9e5e5598f | b51bed4f94e270be2c8b454aa6bcccda363489c7 | refs/heads/master | "2022-11-25T11:10:56.959000" | "2022-11-18T17:43:44" | "2022-11-18T17:43:44" | 201,481,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controller.configuracion.tickets;
import controller.configuracion.impresoras.FxImprimirController;
import controller.menus.FxPrincipalController;
import controller.tools.FilesRouters;
import controller.tools.ImageViewTicket;
import controller.tools.Json;
import controller.tools.Session;
import controller.tools.TextFieldTicket;
import controller.tools.Tools;
import controller.tools.WindowStage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ResourceBundle;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import model.ImageADO;
import model.ImagenTB;
import model.TicketADO;
import model.TicketTB;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class FxTicketController implements Initializable {
@FXML
private VBox vbWindow;
@FXML
private VBox vbContenedor;
@FXML
private AnchorPane apEncabezado;
@FXML
private AnchorPane apDetalleCabecera;
@FXML
private AnchorPane apPie;
@FXML
private TextField txtAnchoColumna;
@FXML
private ComboBox<Pos> cbAlignment;
@FXML
private CheckBox cbMultilinea;
@FXML
private CheckBox cbEditable;
@FXML
private TextField txtVariable;
@FXML
private Label lblNombre;
@FXML
private Label lblColumnas;
@FXML
private Label formatoTicket;
@FXML
private CheckBox cbPredeterminado;
@FXML
private ComboBox<String> cbFuente;
@FXML
private ComboBox<Float> cbSize;
@FXML
private TextField txtAncho;
@FXML
private TextField txtAlto;
private FxPrincipalController fxPrincipalController;
private TextFieldTicket tfAnterior;
private TextFieldTicket tfReference;
private File selectFile;
private HBox hboxAnterior;
private HBox hboxReference;
private short sheetWidth;
private double pointWidth;
private int idTicket;
private int tipoTicket;
private String ruta;
@Override
public void initialize(URL url, ResourceBundle rb) {
pointWidth = 8.10;
sheetWidth = 0;
cbAlignment.getItems().add(Pos.CENTER_LEFT);
cbAlignment.getItems().add(Pos.CENTER);
cbAlignment.getItems().add(Pos.CENTER_RIGHT);
cbFuente.getItems().addAll("Consola", "Roboto Regular", "Roboto Bold");
cbSize.getItems().addAll(10.5f, 12.5f, 14.5f, 16.5f, 18.5f, 20.5f, 22.5f, 24.5f);
}
public void loadTicket(int idTicket, int tipoTicket, String nombre, String ruta, boolean predeterminado) {
if (ruta != null) {
this.idTicket = idTicket;
this.tipoTicket = tipoTicket;
this.ruta = ruta;
hboxReference = null;
JSONObject jSONObject = Json.obtenerObjetoJSON(ruta);
apEncabezado.getChildren().clear();
apDetalleCabecera.getChildren().clear();
apPie.getChildren().clear();
lblNombre.setText(nombre);
formatoTicket.setText(tipoTicket + "");
cbPredeterminado.setSelected(predeterminado);
cbPredeterminado.setText(predeterminado ? "SI" : "NO");
ArrayList<ImagenTB> imagenTBs = ImageADO.ListaImagePorIdRelacionado(idTicket);
sheetWidth = jSONObject.get("column") != null ? Short.parseShort(jSONObject.get("column").toString()) : (short) 40;
lblColumnas.setText("" + sheetWidth);
vbContenedor.setPrefWidth(sheetWidth * pointWidth);
if (jSONObject.get("cabecera") != null) {
JSONObject cabeceraObjects = Json.obtenerObjetoJSON(jSONObject.get("cabecera").toString());
for (int i = 0; i < cabeceraObjects.size(); i++) {
HBox box = generateElement(apEncabezado, "cb");
JSONObject objectObtener = Json.obtenerObjetoJSON(cabeceraObjects.get("cb_" + (i + 1)).toString());
if (objectObtener.get("text") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("text").toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
} else if (objectObtener.get("list") != null) {
JSONArray array = Json.obtenerArrayJSON(objectObtener.get("list").toString());
Iterator it = array.iterator();
while (it.hasNext()) {
JSONObject object = Json.obtenerObjetoJSON(it.next().toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
}
} else if (objectObtener.get("image") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("image").toString());
ImageViewTicket imageView = addElementImageView("", Short.parseShort(object.get("width").toString()), Double.parseDouble(object.get("fitwidth").toString()), Double.parseDouble(object.get("fitheight").toString()), false, object.get("type").toString());
imageView.setId(String.valueOf(object.get("value").toString()));
box.setPrefWidth(imageView.getColumnWidth() * pointWidth);
box.setPrefHeight(imageView.getFitHeight());
box.setAlignment(getAlignment(object.get("align").toString()));
box.getChildren().add(imageView);
}
}
}
if (jSONObject.get("detalle") != null) {
JSONObject detalleObjects = Json.obtenerObjetoJSON(jSONObject.get("detalle").toString());
for (int i = 0; i < detalleObjects.size(); i++) {
HBox box = generateElement(apDetalleCabecera, "dr");
JSONObject objectObtener = Json.obtenerObjetoJSON(detalleObjects.get("dr_" + (i + 1)).toString());
if (objectObtener.get("text") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("text").toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
} else if (objectObtener.get("list") != null) {
JSONArray array = Json.obtenerArrayJSON(objectObtener.get("list").toString());
Iterator it = array.iterator();
while (it.hasNext()) {
JSONObject object = Json.obtenerObjetoJSON(it.next().toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
}
} else if (objectObtener.get("image") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("image").toString());
ImageViewTicket imageView = addElementImageView("", Short.parseShort(object.get("width").toString()), Double.parseDouble(object.get("fitwidth").toString()), Double.parseDouble(object.get("fitheight").toString()), false, object.get("type").toString());
imageView.setId(String.valueOf(object.get("value").toString()));
box.setPrefWidth(imageView.getColumnWidth() * pointWidth);
box.setPrefHeight(imageView.getFitHeight());
box.setAlignment(getAlignment(object.get("align").toString()));
box.getChildren().add(imageView);
}
}
}
if (jSONObject.get("pie") != null) {
JSONObject pieObjects = Json.obtenerObjetoJSON(jSONObject.get("pie").toString());
for (int i = 0; i < pieObjects.size(); i++) {
HBox box = generateElement(apPie, "cp");
JSONObject objectObtener = Json.obtenerObjetoJSON(pieObjects.get("cp_" + (i + 1)).toString());
if (objectObtener.get("text") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("text").toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
} else if (objectObtener.get("list") != null) {
JSONArray array = Json.obtenerArrayJSON(objectObtener.get("list").toString());
Iterator it = array.iterator();
while (it.hasNext()) {
JSONObject object = Json.obtenerObjetoJSON(it.next().toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
}
} else if (objectObtener.get("image") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("image").toString());
ImageViewTicket imageView = addElementImageView("", Short.parseShort(object.get("width").toString()), Double.parseDouble(object.get("fitwidth").toString()), Double.parseDouble(object.get("fitheight").toString()), false, object.get("type").toString());
imageView.setId(String.valueOf(object.get("value").toString()));
box.setPrefWidth(imageView.getColumnWidth() * pointWidth);
box.setPrefHeight(imageView.getFitHeight());
box.setAlignment(getAlignment(object.get("align").toString()));
box.getChildren().add(imageView);
}
}
}
for (int i = 0; i < imagenTBs.size(); i++) {
for (int m = 0; m < apEncabezado.getChildren().size(); m++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(m);
if (hBox.getChildren().size() == 1) {
Object object = hBox.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket imageViewTicket = (ImageViewTicket) hBox.getChildren().get(0);
if (imagenTBs.get(i).getIdSubRelacion().equalsIgnoreCase(imageViewTicket.getId())) {
imageViewTicket.setUrl(imagenTBs.get(i).getImagen());
imageViewTicket.setImage(new Image(new ByteArrayInputStream(imagenTBs.get(i).getImagen())));
}
}
}
}
}
for (int i = 0; i < imagenTBs.size(); i++) {
for (int m = 0; m < apDetalleCabecera.getChildren().size(); m++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(m);
if (hBox.getChildren().size() == 1) {
Object object = hBox.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket imageViewTicket = (ImageViewTicket) hBox.getChildren().get(0);
if (imagenTBs.get(i).getIdSubRelacion().equalsIgnoreCase(imageViewTicket.getId())) {
imageViewTicket.setUrl(imagenTBs.get(i).getImagen());
imageViewTicket.setImage(new Image(new ByteArrayInputStream(imagenTBs.get(i).getImagen())));
}
}
}
}
}
for (int i = 0; i < imagenTBs.size(); i++) {
for (int m = 0; m < apPie.getChildren().size(); m++) {
HBox hBox = (HBox) apPie.getChildren().get(m);
if (hBox.getChildren().size() == 1) {
Object object = hBox.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket imageViewTicket = (ImageViewTicket) hBox.getChildren().get(0);
if (imagenTBs.get(i).getIdSubRelacion().equalsIgnoreCase(imageViewTicket.getId())) {
imageViewTicket.setUrl(imagenTBs.get(i).getImagen());
imageViewTicket.setImage(new Image(new ByteArrayInputStream(imagenTBs.get(i).getImagen())));
}
}
}
}
}
}
}
private void saveTicket() {
try {
int valideteUno = 0;
int valideteDos = 0;
int valideteTree = 0;
for (int i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteUno++;
}
}
for (int i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteDos++;
}
}
for (int i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteTree++;
}
}
if (valideteUno > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en la cabecera sin contenido");
} else if (valideteDos > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el detalle sin contenido");
} else if (valideteTree > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el pie sin contenido");
} else {
if (!apEncabezado.getChildren().isEmpty() && !apDetalleCabecera.getChildren().isEmpty() && !apPie.getChildren().isEmpty()) {
JSONObject sampleObject = new JSONObject();
sampleObject.put("column", sheetWidth);
JSONObject cabecera = new JSONObject();
for (int i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
JSONObject cb = new JSONObject();
if (hBox.getChildren().size() > 1) {
JSONArray kids = new JSONArray();
for (int v = 0; v < hBox.getChildren().size(); v++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(v);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
kids.add(cbkid);
}
cb.put("list", kids);
} else {
Object object = hBox.getChildren().get(0);
if (object instanceof TextFieldTicket) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
cb.put("text", cbkid);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", viewTicket.getId());
cbkid.put("width", viewTicket.getColumnWidth());
cbkid.put("align", hBox.getAlignment().toString());
cbkid.put("variable", "");
cbkid.put("fitwidth", viewTicket.getFitWidth());
cbkid.put("fitheight", viewTicket.getFitHeight());
cbkid.put("type", viewTicket.getType());
cb.put("image", cbkid);
}
}
cabecera.put("cb_" + (i + 1), cb);
}
JSONObject detalle = new JSONObject();
for (int i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
JSONObject cb = new JSONObject();
if (hBox.getChildren().size() > 1) {
JSONArray kids = new JSONArray();
for (int v = 0; v < hBox.getChildren().size(); v++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(v);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
kids.add(cbkid);
}
cb.put("list", kids);
} else {
Object object = hBox.getChildren().get(0);
if (object instanceof TextFieldTicket) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
cb.put("text", cbkid);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", viewTicket.getId());
cbkid.put("width", viewTicket.getColumnWidth());
cbkid.put("align", hBox.getAlignment().toString());
cbkid.put("variable", "");
cbkid.put("fitwidth", viewTicket.getFitWidth());
cbkid.put("fitheight", viewTicket.getFitHeight());
cbkid.put("type", viewTicket.getType());
cb.put("image", cbkid);
}
}
detalle.put("dr_" + (i + 1), cb);
}
JSONObject pie = new JSONObject();
for (int i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
JSONObject cb = new JSONObject();
if (hBox.getChildren().size() > 1) {
JSONArray kids = new JSONArray();
for (int v = 0; v < hBox.getChildren().size(); v++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(v);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
kids.add(cbkid);
}
cb.put("list", kids);
} else {
Object object = hBox.getChildren().get(0);
if (object instanceof TextFieldTicket) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
cb.put("text", cbkid);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", viewTicket.getId());
cbkid.put("width", viewTicket.getColumnWidth());
cbkid.put("align", hBox.getAlignment().toString());
cbkid.put("variable", "");
cbkid.put("fitwidth", viewTicket.getFitWidth());
cbkid.put("fitheight", viewTicket.getFitHeight());
cbkid.put("type", viewTicket.getType());
cb.put("image", cbkid);
}
}
pie.put("cp_" + (i + 1), cb);
}
sampleObject.put("cabecera", cabecera);
sampleObject.put("detalle", detalle);
sampleObject.put("pie", pie);
Files.write(Paths.get("./archivos/ticketventa.json"), sampleObject.toJSONString().getBytes());
TicketTB ticketTB = new TicketTB();
ticketTB.setId(idTicket);
ticketTB.setNombreTicket(lblNombre.getText().trim().toUpperCase());
ticketTB.setRuta(sampleObject.toJSONString());
ticketTB.setTipo(tipoTicket);
ticketTB.setPredeterminado(cbPredeterminado.isSelected());
ticketTB.setApCabecera(apEncabezado);
ticketTB.setApDetalle(apDetalleCabecera);
ticketTB.setApPie(apPie);
String result = TicketADO.CrudTicket(ticketTB);
if (result.equalsIgnoreCase("duplicate")) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El nombre del formato ya existe, intente con otro.");
} else if (result.equalsIgnoreCase("updated")) {
Tools.AlertMessageInformation(vbWindow, "Ticket", "Se actualizo correctamente el formato.");
if (cbPredeterminado.isSelected()) {
switch (tipoTicket) {
case 1:
Session.TICKET_VENTA_ID = idTicket;
Session.TICKET_VENTA_RUTA = sampleObject.toJSONString();
break;
case 2:
Session.TICKET_COMPRA_ID = idTicket;
Session.TICKET_COMPRA_RUTA = sampleObject.toJSONString();
break;
case 5:
Session.TICKET_CORTE_CAJA_ID = idTicket;
Session.TICKET_CORTE_CAJA_RUTA = sampleObject.toJSONString();
break;
case 7:
Session.TICKET_PRE_VENTA_ID = idTicket;
Session.TICKET_PRE_VENTA_RUTA = sampleObject.toJSONString();
break;
case 8:
Session.TICKET_COTIZACION_ID = idTicket;
Session.TICKET_COTIZACION_RUTA = sampleObject.toJSONString();
break;
case 9:
Session.TICKET_CUENTA_POR_COBRAR_ID = idTicket;
Session.TICKET_CUENTA_POR_COBRAR_RUTA = sampleObject.toJSONString();
break;
case 10:
Session.TICKET_CUENTA_POR_PAGAR_ID = idTicket;
Session.TICKET_CUENTA_POR_PAGAR_RUTA = sampleObject.toJSONString();
break;
case 11:
Session.TICKET_GUIA_REMISION_ID = idTicket;
Session.TICKET_GUIA_REMISION_RUTA = sampleObject.toJSONString();
break;
case 12:
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_ID = idTicket;
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_RUTA = sampleObject.toJSONString();
break;
case 13:
Session.TICKET_PEDIDO_ID = idTicket;
Session.TICKET_PEDIDO_RUTA = sampleObject.toJSONString();
break;
case 14:
Session.TICKET_ORDEN_COMPRA_ID = idTicket;
Session.TICKET_ORDEN_COMPRA_RUTA = sampleObject.toJSONString();
break;
case 15:
Session.TICKET_NOTA_CREDITO_ID = idTicket;
Session.TICKET_NOTA_CREDITO_RUTA = sampleObject.toJSONString();
break;
default:
break;
}
}
clearPane();
} else if (result.equalsIgnoreCase("registered")) {
Tools.AlertMessageInformation(vbWindow, "Ticket", "Se guardo correctamente el formato, recuerda siempre poner en predeterminado el ticket, si lo va utilizar frecuentemente.");
clearPane();
} else {
Tools.AlertMessageError(vbWindow, "Ticket", result);
}
} else {
if (apEncabezado.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El encabezado está vacío.");
} else if (apDetalleCabecera.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El detalle cabecera está vacío.");
} else if (apPie.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El pie está vacío.");
}
}
}
} catch (IOException ex) {
Tools.AlertMessageError(vbWindow, "Ticket", "No se pudo guardar la hoja con problemas de formato.");
System.out.println(ex.getLocalizedMessage());
System.out.println(ex);
}
}
private HBox generateElement(AnchorPane contenedor, String id) {
if (contenedor.getChildren().isEmpty()) {
return addElement(contenedor, id + "1", true);
} else {
HBox hBox = (HBox) contenedor.getChildren().get(contenedor.getChildren().size() - 1);
String idGenerate = hBox.getId();
String codigo = idGenerate.substring(2);
int valor = Integer.parseInt(codigo) + 1;
String newCodigo = id + valor;
return addElement(contenedor, newCodigo, true);
}
}
private HBox addElement(AnchorPane contenedor, String id, boolean useLayout) {
double layoutY = 0;
if (useLayout) {
for (int i = 0; i < contenedor.getChildren().size(); i++) {
layoutY += ((HBox) contenedor.getChildren().get(i)).getPrefHeight();
}
}
ImageView imgRemove = new ImageView(new Image("/view/image/remove-item.png"));
imgRemove.setFitWidth(20);
imgRemove.setFitHeight(20);
ImageView imgMoveDown = new ImageView(new Image("/view/image/movedown.png"));
imgMoveDown.setFitWidth(20);
imgMoveDown.setFitHeight(20);
ImageView imgMoveUp = new ImageView(new Image("/view/image/moveup.png"));
imgMoveUp.setFitWidth(20);
imgMoveUp.setFitHeight(20);
ImageView imgText = new ImageView(new Image("/view/image/text.png"));
imgText.setFitWidth(20);
imgText.setFitHeight(20);
ImageView imgTextVariable = new ImageView(new Image("/view/image/text-variable.png"));
imgTextVariable.setFitWidth(20);
imgTextVariable.setFitHeight(20);
ImageView imgTextLines = new ImageView(new Image("/view/image/text-lines.png"));
imgTextLines.setFitWidth(20);
imgTextLines.setFitHeight(20);
ImageView imgUnaLinea = new ImageView(new Image("/view/image/linea.png"));
imgUnaLinea.setFitWidth(20);
imgUnaLinea.setFitHeight(20);
ImageView imgDobleLinea = new ImageView(new Image("/view/image/doble-linea.png"));
imgDobleLinea.setFitWidth(20);
imgDobleLinea.setFitHeight(20);
ImageView imgImage = new ImageView(new Image("/view/image/photo.png"));
imgImage.setFitWidth(20);
imgImage.setFitHeight(20);
HBox hBox = new HBox();
hBox.setId(id);
hBox.setLayoutX(0);
hBox.setLayoutY(layoutY);
hBox.setPrefWidth(sheetWidth * pointWidth);
//font size 12.5px
hBox.setPrefHeight(30);
hBox.setStyle("-fx-padding:0 20 0 0;-fx-border-width: 1 1 1 1;-fx-border-color: #0066ff;;-fx-background-color: white;");
hBox.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> {
hboxAnterior = hboxReference;
if (hboxAnterior != null) {
hboxAnterior.setStyle("-fx-padding:0 20 0 0;-fx-border-width: 1 1 1 1;-fx-border-color: #0066ff;-fx-background-color: white;");
}
hBox.setStyle("-fx-padding:0 20 0 0;-fx-border-width: 1 1 1 1;-fx-border-color: #0066ff;-fx-background-color: rgb(250, 198, 203);");
hboxReference = hBox;
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
txtAncho.setText(Tools.roundingValue(viewTicket.getFitWidth(), 0));
txtAlto.setText(Tools.roundingValue(viewTicket.getFitHeight(), 0));
}
}
});
ContextMenu contextMenu = new ContextMenu();
MenuItem remove = new MenuItem("Remover Renglón");
remove.setGraphic(imgRemove);
remove.setOnAction(e -> {
for (int b = 0; b < contenedor.getChildren().size(); b++) {
if (contenedor.getChildren().get(b).getId().equalsIgnoreCase(hBox.getId())) {
contenedor.getChildren().remove(b);
double yPosBefero = 0;
for (int p = 0; p < contenedor.getChildren().size(); p++) {
HBox hb = (HBox) contenedor.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
contenedor.layout();
break;
}
}
int valor = 0;
for (int n = 0; n < contenedor.getChildren().size(); n++) {
HBox boxn = (HBox) contenedor.getChildren().get(n);
if (boxn.getChildren().size() == 1) {
Object object = boxn.getChildren().get(0);
if (object instanceof ImageViewTicket) {
valor++;
ImageViewTicket imageViewTicket = (ImageViewTicket) boxn.getChildren().get(0);
imageViewTicket.setId(boxn.getParent().equals(apEncabezado) ? "imc" + valor
: boxn.getParent().equals(apDetalleCabecera) ? "imd" + valor : boxn.getParent().equals(apPie) ? "imp" + valor : "");
}
}
}
});
MenuItem text = new MenuItem("Agregar Texto");
text.setGraphic(imgText);
text.setOnAction(e -> {
TextFieldTicket field = addElementTextField("iu", "Escriba", false, (short) 0, (short) 7, Pos.CENTER_LEFT, true, "", "Consola", 12.5f);
hBox.getChildren().add(field);
});
MenuItem textVariable = new MenuItem("Agregar Variable");
textVariable.setGraphic(imgTextVariable);
textVariable.setOnAction(e -> {
windowTextVar(hBox);
});
MenuItem textMultilinea = new MenuItem("Agregar Texto Multilínea");
textMultilinea.setGraphic(imgTextLines);
textMultilinea.setOnAction(e -> {
windowTextMultilinea(hBox);
});
MenuItem textUnaLinea = new MenuItem("Agregar Línea");
textUnaLinea.setGraphic(imgUnaLinea);
textUnaLinea.setOnAction(e -> {
String value = "";
for (int i = 0; i < sheetWidth; i++) {
value += "-";
}
TextFieldTicket field = addElementTextField("iu", value, false, (short) 0, sheetWidth, Pos.CENTER_LEFT, false, "", "Consola", 12.5f);
hBox.getChildren().add(field);
});
MenuItem textDosLineas = new MenuItem("Agregar Doble Línea");
textDosLineas.setGraphic(imgDobleLinea);
textDosLineas.setOnAction(e -> {
String value = "";
for (int i = 0; i < sheetWidth; i++) {
value += "=";
}
TextFieldTicket field = addElementTextField("iu", value, false, (short) 0, sheetWidth, Pos.CENTER_LEFT, false, "", "Consola", 12.5f);
hBox.getChildren().add(field);
});
MenuItem moveUp = new MenuItem("Subir elemento");
moveUp.setGraphic(imgMoveUp);
moveUp.setOnAction(e -> {
moveUpHBox(contenedor);
});
MenuItem moveDown = new MenuItem("Bajar elemento");
moveDown.setGraphic(imgMoveDown);
moveDown.setOnAction(e -> {
moveDownHBox(contenedor);
});
MenuItem addImage = new MenuItem("Agregar imagen");
addImage.setGraphic(imgImage);
addImage.setOnAction(e -> {
if (hBox.getChildren().isEmpty()) {
int currentTotal = 0;
for (int n = 0; n < contenedor.getChildren().size(); n++) {
HBox boxn = (HBox) contenedor.getChildren().get(n);
if (boxn.getChildren().size() == 1) {
if (boxn.getChildren().get(0) instanceof ImageViewTicket) {
currentTotal++;
}
}
}
String newCodigo = "";
if (contenedor.equals(apEncabezado)) {
int valor = currentTotal + 1;
newCodigo = "imc" + valor;
} else if (contenedor.equals(apDetalleCabecera)) {
int valor = currentTotal + 1;
newCodigo = "imd" + valor;
} else if (contenedor.equals(apPie)) {
int valor = currentTotal + 1;
newCodigo = "imp" + valor;
}
ImageViewTicket imageView = addElementImageView("/view/image/no-image.png", sheetWidth, 100, 86, true, "image");
imageView.setId(newCodigo);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.setPrefHeight(imageView.getFitHeight());
hBox.getChildren().add(imageView);
double yPosBefero = 0;
for (int p = 0; p < contenedor.getChildren().size(); p++) {
HBox hb = (HBox) contenedor.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
contenedor.layout();
}
});
MenuItem addQr = new MenuItem("Agregar QR");
addQr.setGraphic(imgImage);
addQr.setOnAction(e -> {
if (hBox.getChildren().isEmpty()) {
int currentTotal = 0;
for (int n = 0; n < contenedor.getChildren().size(); n++) {
HBox boxn = (HBox) contenedor.getChildren().get(n);
if (boxn.getChildren().size() == 1) {
if (boxn.getChildren().get(0) instanceof ImageViewTicket) {
currentTotal++;
}
}
}
String newCodigo = "";
if (contenedor.equals(apEncabezado)) {
int valor = currentTotal + 1;
newCodigo = "imc" + valor;
} else if (contenedor.equals(apDetalleCabecera)) {
int valor = currentTotal + 1;
newCodigo = "imd" + valor;
} else if (contenedor.equals(apPie)) {
int valor = currentTotal + 1;
newCodigo = "imp" + valor;
}
// try {
// BufferedImage qrImage = com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage(new com.google.zxing.qrcode.QRCodeWriter().encode("",com.google.zxing.BarcodeFormat.QR_CODE, 300, 300));
// } catch (WriterException ex) {
// Logger.getLogger(FxTicketController.class.getName()).log(Level.SEVERE, null, ex);
// }
ImageViewTicket imageView = addElementImageView("/view/image/qr.png", sheetWidth, 100, 86, true, "qr");
imageView.setId(newCodigo);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.setPrefHeight(imageView.getFitHeight());
hBox.getChildren().add(imageView);
double yPosBefero = 0;
for (int p = 0; p < contenedor.getChildren().size(); p++) {
HBox hb = (HBox) contenedor.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
contenedor.layout();
}
});
contextMenu.getItems().addAll(text, textVariable, textMultilinea, textUnaLinea, textDosLineas, remove, moveUp, moveDown, addImage, addQr);
hBox.setOnContextMenuRequested((ContextMenuEvent event) -> {
contextMenu.show(hBox, event.getSceneX(), event.getSceneY());
short widthContent = 0;
for (int i = 0; i < hBox.getChildren().size(); i++) {
Object object = hBox.getChildren().get(i);
if (object instanceof TextFieldTicket) {
widthContent += ((TextFieldTicket) hBox.getChildren().get(i)).getColumnWidth();
} else if (object instanceof ImageViewTicket) {
widthContent += ((ImageViewTicket) hBox.getChildren().get(i)).getColumnWidth();
}
}
text.setDisable((widthContent + 13) > sheetWidth);
textUnaLinea.setDisable((widthContent + 13) > sheetWidth);
textDosLineas.setDisable((widthContent + 13) > sheetWidth);
addImage.setDisable(!hBox.getChildren().isEmpty());
addQr.setDisable(!hBox.getChildren().isEmpty());
});
if (useLayout) {
contenedor.getChildren().add(hBox);
}
return hBox;
}
public TextFieldTicket addElementTextField(String id, String titulo, boolean multilinea, short lines, short widthColumn, Pos align, boolean editable, String variable, String font, float size) {
TextFieldTicket field = new TextFieldTicket(titulo, id);
field.setMultilineas(multilinea);
field.setLines(lines);
field.setColumnWidth(widthColumn);
field.setVariable(variable);
field.setEditable(editable);
field.setPreferredSize((double) widthColumn * pointWidth, 30);
field.setAlignment(align);
field.setFontColor(editable ? "black" : "#d62c0a");
field.setFontName(font);
field.setFontSize(size);
field.setFontBackground("white");
field.getStyleClass().add("text-field-ticket");
field.setStyle("-fx-background-color:" + field.getFontBackground() + " ;-fx-text-fill:" + field.getFontColor() + ";-fx-font-family:" + (field.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : field.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
field.addEventHandler(MouseEvent.MOUSE_PRESSED, m -> {
tfAnterior = tfReference;
if (tfAnterior != null) {
tfAnterior.setStyle("-fx-background-color: white;-fx-text-fill:" + tfAnterior.getFontColor() + ";-fx-font-family:" + (tfAnterior.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfAnterior.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfAnterior.getFontSize() + ";");
}
tfReference = field;
tfReference.setFontBackground("#cecece");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
txtAnchoColumna.setText(tfReference.getColumnWidth() + "");
cbAlignment.getItems().forEach(c -> {
if (c.equals(tfReference.getAlignment())) {
cbAlignment.getSelectionModel().select(c);
}
});
//HBox hBox = (HBox) tfReference.getParent();
//cbFuente.setDisable(hBox.getChildren().size() > 1);
cbFuente.getSelectionModel().select(tfReference.getFontName());
//cbSize.setDisable(hBox.getChildren().size() > 1);
cbSize.getSelectionModel().select(tfReference.getFontSize());
cbMultilinea.setSelected(tfReference.isMultilineas());
cbMultilinea.setText(tfReference.isMultilineas() ? "Si" : "No");
cbEditable.setSelected(tfReference.isEditable());
cbEditable.setText(tfReference.isEditable() ? "Si" : "No");
txtVariable.setText(tfReference.getVariable());
});
field.lengthProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
if (!field.isMultilineas()) {
if (newValue.intValue() > oldValue.intValue()) {
if (field.getText().length() >= field.getColumnWidth()) {
field.setText(field.getText().substring(0, field.getColumnWidth()));
}
}
}
});
ImageView imgRemove = new ImageView(new Image("/view/image/remove-item.png"));
imgRemove.setFitWidth(20);
imgRemove.setFitHeight(20);
ImageView imgAdaptParentWidth = new ImageView(new Image("/view/image/width-parent.png"));
imgAdaptParentWidth.setFitWidth(20);
imgAdaptParentWidth.setFitHeight(20);
ImageView imgTextLeft = new ImageView(new Image("/view/image/text-left.png"));
imgTextLeft.setFitWidth(20);
imgTextLeft.setFitHeight(20);
ImageView imgTextCenter = new ImageView(new Image("/view/image/text-center.png"));
imgTextCenter.setFitWidth(20);
imgTextCenter.setFitHeight(20);
ImageView imgTextRight = new ImageView(new Image("/view/image/text-right.png"));
imgTextRight.setFitWidth(20);
imgTextRight.setFitHeight(20);
ContextMenu contextMenu = new ContextMenu();
MenuItem remove = new MenuItem("Remover Campo de Texto");
remove.setGraphic(imgRemove);
remove.setOnAction(e -> {
((HBox) field.getParent()).getChildren().remove(field);
});
MenuItem textAdaptWidth = new MenuItem("Adaptar el Ancho del Padre");
textAdaptWidth.setGraphic(imgAdaptParentWidth);
textAdaptWidth.setOnAction(e -> {
field.setColumnWidth(sheetWidth);
field.setPreferredSize(((double) field.getColumnWidth() * pointWidth), field.getPrefHeight());
});
MenuItem textLeft = new MenuItem("Alineación Izquierda");
textLeft.setGraphic(imgTextLeft);
textLeft.setOnAction(e -> {
if (!field.getText().isEmpty()) {
field.setAlignment(Pos.CENTER_LEFT);
}
});
MenuItem textCenter = new MenuItem("Alineación Central");
textCenter.setGraphic(imgTextCenter);
textCenter.setOnAction(e -> {
if (!field.getText().isEmpty()) {
field.setAlignment(Pos.CENTER);
}
});
MenuItem textRight = new MenuItem("Alineación Derecha");
textRight.setGraphic(imgTextRight);
textRight.setOnAction(e -> {
if (!field.getText().isEmpty()) {
field.setAlignment(Pos.CENTER_RIGHT);
}
});
contextMenu.getItems().addAll(remove, textAdaptWidth, new SeparatorMenuItem(), textLeft, textCenter, textRight);
field.setContextMenu(contextMenu);
field.setOnContextMenuRequested((event) -> {
if (((HBox) field.getParent()).getChildren().size() > 1) {
textAdaptWidth.setDisable(true);
}
if (field.isMultilineas()) {
textLeft.setDisable(true);
textCenter.setDisable(true);
textRight.setDisable(true);
}
});
return field;
}
private ImageViewTicket addElementImageView(String path, short widthColumn, double width, double height, boolean newImage, String type) {
ImageViewTicket imageView = new ImageViewTicket();
imageView.setColumnWidth(widthColumn);
imageView.setFitWidth(width);
imageView.setFitHeight(height);
imageView.setSmooth(true);
imageView.setType(type);
if (newImage) {
imageView.setImage(new Image(path));
imageView.setUrl(Tools.getImageBytes(imageView.getImage(), Tools.getFileExtension(new File(path))));
}
return imageView;
}
private void actionAnchoColumnas() {
if (tfReference != null) {
if (Tools.isNumeric(txtAnchoColumna.getText())) {
int widthContent = 0;
for (int i = 0; i < ((HBox) tfReference.getParent()).getChildren().size(); i++) {
TextFieldTicket fieldTicket = ((TextFieldTicket) ((HBox) tfReference.getParent()).getChildren().get(i));
if (fieldTicket != tfReference) {
widthContent += fieldTicket.getColumnWidth();
}
}
if ((widthContent + Integer.parseInt(txtAnchoColumna.getText())) > sheetWidth) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "No puede sobrepasar al ancho de la hoja.");
} else {
if (!tfReference.isMultilineas() && tfReference.isEditable()) {
if (tfReference.getText().length() < Integer.parseInt(txtAnchoColumna.getText())) {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
} else {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
tfReference.setText(tfReference.getText().substring(0, tfReference.getColumnWidth()));
}
} else {
if (tfReference.getText().length() < Integer.parseInt(txtAnchoColumna.getText())) {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
} else {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
}
}
}
}
}
}
public void clearPane() {
idTicket = 0;
tipoTicket = 0;
ruta = "";
apEncabezado.getChildren().clear();
apDetalleCabecera.getChildren().clear();
apPie.getChildren().clear();
txtAnchoColumna.setText("");
cbAlignment.getSelectionModel().select(null);
cbFuente.getSelectionModel().select(null);
cbSize.getSelectionModel().select(null);
cbMultilinea.setSelected(false);
cbEditable.setSelected(false);
txtVariable.setText("");
lblNombre.setText("--");
formatoTicket.setText("--");
lblColumnas.setText("0");
sheetWidth = 0;
lblColumnas.setText(sheetWidth + "");
cbPredeterminado.setSelected(false);
cbPredeterminado.setText("NO");
vbContenedor.setPrefWidth(Control.USE_COMPUTED_SIZE);
}
private Pos getAlignment(String align) {
switch (align) {
case "CENTER":
return Pos.CENTER;
case "CENTER_LEFT":
return Pos.CENTER_LEFT;
case "CENTER_RIGHT":
return Pos.CENTER_RIGHT;
default:
return Pos.CENTER_LEFT;
}
}
private void searchTicket() {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_BUSQUEDA);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketBusquedaController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.loadComponents(0, true);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Seleccionar formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void nuevoTicket() {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_PROCESO);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketProcesoController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Nuevo formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void editarTicket() {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_PROCESO);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketProcesoController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.editarTicket(tipoTicket, lblNombre.getText(), sheetWidth);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Editar formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void windowTextMultilinea(HBox hBox) {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_MULTILINEA);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketMultilineaController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.setLoadComponent(hBox, sheetWidth);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Agregar texto multilinea", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void windowTextVar(HBox hBox) {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_VARIABLE);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketVariableController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.setLoadComponent(hBox, sheetWidth);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Agregar variable", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void openWindowImpresora() {
try {
int valideteUno = 0;
int valideteDos = 0;
int valideteTree = 0;
for (int i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteUno++;
}
}
for (int i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteDos++;
}
}
for (int i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteTree++;
}
}
if (valideteUno > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en la cabecera sin contenido");
} else if (valideteDos > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el detalle sin contenido");
} else if (valideteTree > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el pie sin contenido");
} else {
if (!apEncabezado.getChildren().isEmpty() && !apDetalleCabecera.getChildren().isEmpty() && !apPie.getChildren().isEmpty()) {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_IMPRIMIR);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxImprimirController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Imprimir Prueba", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} else {
if (apEncabezado.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El encabezado está vacío.");
} else if (apDetalleCabecera.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El detalle cabecera está vacío.");
} else if (apPie.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El pie está vacío.");
}
}
}
} catch (IOException ex) {
}
}
public void editarTicket(boolean editable, int tipoTicket, String nombre, short widthPage) {
if (editable) {
this.tipoTicket = tipoTicket;
lblNombre.setText(nombre);
sheetWidth = widthPage;
lblColumnas.setText("" + sheetWidth);
vbContenedor.setPrefWidth(sheetWidth * pointWidth);
formatoTicket.setText(tipoTicket + "");
for (short i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
hBox.setPrefWidth(sheetWidth * pointWidth);
short newwidth = (short) (sheetWidth / hBox.getChildren().size());
for (short j = 0; j < hBox.getChildren().size(); j++) {
Object object = hBox.getChildren().get(j);
if (object instanceof TextFieldTicket) {
TextFieldTicket fieldTicket = (TextFieldTicket) hBox.getChildren().get(j);
fieldTicket.setColumnWidth(newwidth);
fieldTicket.setPreferredSize(newwidth * pointWidth, fieldTicket.getPrefHeight());
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(j);
viewTicket.setColumnWidth(newwidth);
}
}
}
for (short i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
hBox.setPrefWidth(sheetWidth * pointWidth);
short newwidth = (short) (sheetWidth / hBox.getChildren().size());
for (short j = 0; j < hBox.getChildren().size(); j++) {
Object object = hBox.getChildren().get(j);
if (object instanceof TextFieldTicket) {
TextFieldTicket fieldTicket = (TextFieldTicket) hBox.getChildren().get(j);
fieldTicket.setColumnWidth(newwidth);
fieldTicket.setPreferredSize(newwidth * pointWidth, fieldTicket.getPrefHeight());
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(j);
viewTicket.setColumnWidth(newwidth);
}
}
}
for (short i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
hBox.setPrefWidth(sheetWidth * pointWidth);
short newwidth = (short) (sheetWidth / hBox.getChildren().size());
for (short j = 0; j < hBox.getChildren().size(); j++) {
Object object = hBox.getChildren().get(j);
if (object instanceof TextFieldTicket) {
TextFieldTicket fieldTicket = (TextFieldTicket) hBox.getChildren().get(j);
fieldTicket.setColumnWidth(newwidth);
fieldTicket.setPreferredSize(newwidth * pointWidth, fieldTicket.getPrefHeight());
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(j);
viewTicket.setColumnWidth(newwidth);
}
}
}
} else {
clearPane();
lblNombre.setText(nombre);
sheetWidth = widthPage;
lblColumnas.setText("" + sheetWidth);
vbContenedor.setPrefWidth(sheetWidth * pointWidth);
this.tipoTicket = tipoTicket;
formatoTicket.setText(tipoTicket + "");
cbPredeterminado.setSelected(false);
cbPredeterminado.setText("NO");
}
}
private void moveUpHBox(AnchorPane anchorPane) {
for (int i = 0; i < anchorPane.getChildren().size(); i++) {
if (((HBox) anchorPane.getChildren().get(i)).equals(hboxReference)) {
if (i == 0) {
break;
}
String style = hboxReference.getStyle();
HBox previous = (HBox) anchorPane.getChildren().get(i - 1);
HBox oldHbox = addElement(anchorPane, previous.getId(), false);
oldHbox.setLayoutY(previous.getLayoutY());
oldHbox.setPrefHeight(hboxReference.getPrefHeight());
for (int r = 0; r < hboxReference.getChildren().size(); r++) {
Object object = hboxReference.getChildren().get(r);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) hboxReference.getChildren().get(r);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
oldHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) hboxReference.getChildren().get(r);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setId(ivAnterior.getId());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
oldHbox.setAlignment(hboxReference.getAlignment());
oldHbox.getChildren().add(imageTicket);
}
}
HBox newHbox = addElement(anchorPane, hboxReference.getId(), false);
newHbox.setLayoutY(oldHbox.getLayoutY() + oldHbox.getPrefHeight());
newHbox.setPrefHeight(previous.getPrefHeight());
for (int a = 0; a < previous.getChildren().size(); a++) {
Object object = previous.getChildren().get(a);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) previous.getChildren().get(a);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
newHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) previous.getChildren().get(a);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setId(ivAnterior.getId());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
newHbox.setAlignment(hboxReference.getAlignment());
newHbox.getChildren().add(imageTicket);
}
}
anchorPane.getChildren().set(i - 1, oldHbox);
anchorPane.getChildren().set(i, newHbox);
oldHbox.setStyle(style);
hboxReference = oldHbox;
break;
}
}
anchorPane.layout();
}
private void moveDownHBox(AnchorPane anchorPane) {
for (int i = 0; i < anchorPane.getChildren().size(); i++) {
if (((HBox) anchorPane.getChildren().get(i)).equals(hboxReference)) {
if (anchorPane.getChildren().size() == (i + 1)) {
break;
}
String style = hboxReference.getStyle();
HBox later = (HBox) anchorPane.getChildren().get(i + 1);
HBox newHbox = addElement(anchorPane, hboxReference.getId(), false);
newHbox.setLayoutY(hboxReference.getLayoutY());
newHbox.setPrefHeight(later.getPrefHeight());
for (int a = 0; a < later.getChildren().size(); a++) {
Object object = later.getChildren().get(a);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) later.getChildren().get(a);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
newHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) later.getChildren().get(a);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
newHbox.setAlignment(hboxReference.getAlignment());
newHbox.getChildren().add(imageTicket);
}
}
HBox oldHbox = addElement(anchorPane, later.getId(), false);
oldHbox.setLayoutY(newHbox.getLayoutY() + newHbox.getPrefHeight());
oldHbox.setPrefHeight(hboxReference.getPrefHeight());
for (int r = 0; r < hboxReference.getChildren().size(); r++) {
Object object = hboxReference.getChildren().get(r);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) hboxReference.getChildren().get(r);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
oldHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) hboxReference.getChildren().get(r);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
oldHbox.setAlignment(hboxReference.getAlignment());
oldHbox.getChildren().add(imageTicket);
}
}
anchorPane.getChildren().set(i, newHbox);
anchorPane.getChildren().set(i + 1, oldHbox);
oldHbox.setStyle(style);
hboxReference = oldHbox;
break;
}
}
anchorPane.layout();
}
public void leftElementHBox() {
if (hboxReference != null) {
hboxReference.setAlignment(Pos.CENTER_LEFT);
}
}
private void centerElementHBox() {
if (hboxReference != null) {
hboxReference.setAlignment(Pos.CENTER);
}
}
private void rightElementHBox() {
if (hboxReference != null) {
hboxReference.setAlignment(Pos.CENTER_RIGHT);
}
}
private void loadSelectImage() {
if (hboxReference != null) {
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Importar una imagen");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Elija una imagen", "*.png", "*.jpg", "*.jpeg", "*.gif"));
selectFile = fileChooser.showOpenDialog(vbWindow.getScene().getWindow());
if (selectFile != null) {
selectFile = new File(selectFile.getAbsolutePath());
if (selectFile.getName().endsWith("png") || selectFile.getName().endsWith("jpg") || selectFile.getName().endsWith("jpeg") || selectFile.getName().endsWith("gif")) {
viewTicket.setImage(new Image(selectFile.toURI().toString()));
viewTicket.setSmooth(true);
viewTicket.setPreserveRatio(false);
viewTicket.setUrl(Tools.getImageBytes(selectFile));
//imageBytes = null;
} else {
Tools.AlertMessageWarning(vbWindow, "Mi Empresa", "No seleccionó un formato correcto de imagen.");
}
}
}
}
}
}
private void onEventPredeterminado() {
if (idTicket > 0) {
short option = Tools.AlertMessageConfirmation(vbWindow, "Ticket", "¿Está seguro de hacer prederteminado este modelo de ticket?");
if (option == 1) {
String result = TicketADO.ChangeDefaultState(idTicket, tipoTicket);
if (result.equalsIgnoreCase("updated")) {
Tools.AlertMessageInformation(vbWindow, "Ticket", "Se realizó los cambios correctamente.");
cbPredeterminado.setSelected(true);
cbPredeterminado.setText("SI");
switch (tipoTicket) {
case 1:
Session.TICKET_VENTA_ID = idTicket;
Session.TICKET_VENTA_RUTA = ruta;
break;
case 2:
Session.TICKET_COMPRA_ID = idTicket;
Session.TICKET_COMPRA_RUTA = ruta;
break;
case 5:
Session.TICKET_CORTE_CAJA_ID = idTicket;
Session.TICKET_CORTE_CAJA_RUTA = ruta;
break;
case 7:
Session.TICKET_PRE_VENTA_ID = idTicket;
Session.TICKET_PRE_VENTA_RUTA = ruta;
break;
case 8:
Session.TICKET_COTIZACION_ID = idTicket;
Session.TICKET_COTIZACION_RUTA = ruta;
break;
case 9:
Session.TICKET_CUENTA_POR_COBRAR_ID = idTicket;
Session.TICKET_CUENTA_POR_COBRAR_RUTA = ruta;
break;
case 10:
Session.TICKET_CUENTA_POR_PAGAR_ID = idTicket;
Session.TICKET_CUENTA_POR_PAGAR_RUTA = ruta;
break;
case 11:
Session.TICKET_GUIA_REMISION_ID = idTicket;
Session.TICKET_GUIA_REMISION_RUTA = ruta;
break;
case 12:
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_ID = idTicket;
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_RUTA = ruta;
break;
case 13:
Session.TICKET_PEDIDO_ID = idTicket;
Session.TICKET_PEDIDO_RUTA = ruta;
break;
case 14:
Session.TICKET_ORDEN_COMPRA_ID = idTicket;
Session.TICKET_ORDEN_COMPRA_RUTA = ruta;
break;
case 15:
Session.TICKET_NOTA_CREDITO_ID = idTicket;
Session.TICKET_NOTA_CREDITO_RUTA = ruta;
break;
default:
break;
}
} else {
Tools.AlertMessageError(vbWindow, "Ticket", result);
}
}
} else {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El modelo del ticket está en proceso de creación, busque en la lista para hacerlo prederteminado.");
}
}
private void onEventEliminar() {
if (idTicket != 0) {
short value = Tools.AlertMessageConfirmation(vbWindow, "Ticket", "¿Está seguro de continuar?");
if (value == 1) {
String result = TicketADO.DeleteTicket(idTicket);
if (result.equalsIgnoreCase("deleted")) {
Tools.AlertMessageConfirmation(vbWindow, "Ticket", "Se elemino correctamente el ticket.");
switch (tipoTicket) {
case 1:
Session.TICKET_VENTA_ID = 0;
Session.TICKET_VENTA_RUTA = "";
break;
case 2:
Session.TICKET_COMPRA_ID = 0;
Session.TICKET_COMPRA_RUTA = "";
break;
case 5:
Session.TICKET_CORTE_CAJA_ID = 0;
Session.TICKET_CORTE_CAJA_RUTA = "";
break;
case 7:
Session.TICKET_PRE_VENTA_ID = 0;
Session.TICKET_PRE_VENTA_RUTA = "";
break;
case 8:
Session.TICKET_COTIZACION_ID = 0;
Session.TICKET_COTIZACION_RUTA = "";
break;
case 9:
Session.TICKET_CUENTA_POR_COBRAR_ID = 0;
Session.TICKET_CUENTA_POR_COBRAR_RUTA = "";
break;
case 10:
Session.TICKET_CUENTA_POR_PAGAR_ID = 0;
Session.TICKET_CUENTA_POR_PAGAR_RUTA = "";
break;
case 11:
Session.TICKET_GUIA_REMISION_ID = 0;
Session.TICKET_GUIA_REMISION_RUTA = "";
break;
case 12:
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_ID = 0;
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_RUTA = "";
break;
case 13:
Session.TICKET_PEDIDO_ID = 0;
Session.TICKET_PEDIDO_RUTA = "";
break;
case 14:
Session.TICKET_ORDEN_COMPRA_ID = 0;
Session.TICKET_ORDEN_COMPRA_RUTA = "";
break;
case 15:
Session.TICKET_NOTA_CREDITO_ID = 0;
Session.TICKET_NOTA_CREDITO_RUTA = "";
break;
default:
break;
}
clearPane();
} else if (result.equalsIgnoreCase("predeterminated")) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El ticket es predeterminado, no puede eliminar por el momento.");
} else {
Tools.AlertMessageError(vbWindow, "Ticket", result);
}
}
}
}
private void onEventClonar() {
if (idTicket == 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "No se puede clonar un ticket recien creado.");
return;
}
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_CLONAR);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketClonarController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Clonar formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.setOnShowing(w -> controller.loadComponents(idTicket));
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
@FXML
private void onKeyPressNuevo(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
nuevoTicket();
}
}
@FXML
private void onActionNuevo(ActionEvent event) {
nuevoTicket();
}
@FXML
private void onKeyPressEditar(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
editarTicket();
}
}
@FXML
private void onActionEditar(ActionEvent event) {
editarTicket();
}
@FXML
private void onKeyPressedSave(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
saveTicket();
}
}
@FXML
private void onActionSave(ActionEvent event) {
saveTicket();
}
@FXML
private void onKeyPressedClonar(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
onEventClonar();
}
}
@FXML
private void onActionClonar(ActionEvent event) {
onEventClonar();
}
@FXML
private void onActionEliminar(ActionEvent event) {
onEventEliminar();
}
@FXML
private void onKeyPressedEliminar(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
onEventEliminar();
}
}
@FXML
private void onKeyPressedPrint(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
openWindowImpresora();
}
}
@FXML
private void onActionPrint(ActionEvent event) {
openWindowImpresora();
}
@FXML
private void onMouseClickedEncabezadoAdd(MouseEvent event) {
generateElement(apEncabezado, "cb");
}
@FXML
private void onMouseClickedDetalleCabeceraAdd(MouseEvent event) {
generateElement(apDetalleCabecera, "dr");
}
@FXML
private void onMouseClickedPieAdd(MouseEvent event) {
generateElement(apPie, "cp");
}
@FXML
private void onActionAnchoColumna(ActionEvent event) {
actionAnchoColumnas();
}
@FXML
private void onKeyTypedAnchoColumna(KeyEvent event) {
char c = event.getCharacter().charAt(0);
if ((c < '0' || c > '9') && (c != '\b')) {
event.consume();
}
}
@FXML
private void onKeyPressedSearch(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
searchTicket();
}
}
@FXML
private void onActionSearch(ActionEvent event) {
searchTicket();
}
@FXML
private void onActionMultilinea(ActionEvent event) {
if (tfReference != null) {
if (!cbMultilinea.isSelected()) {
tfReference.setMultilineas(false);
tfReference.setLines((short) 0);
} else {
tfReference.setMultilineas(true);
tfReference.setLines((short) 1);
}
}
}
@FXML
private void onKeyPressedClear(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
clearPane();
}
}
@FXML
private void onActionClear(ActionEvent event) {
clearPane();
}
@FXML
private void onKeyPressedImage(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
loadSelectImage();
}
}
@FXML
private void onActionImage(ActionEvent event) {
loadSelectImage();
}
@FXML
private void onKeyPressedMoveUp(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
if (hboxReference != null) {
moveUpHBox((AnchorPane) hboxReference.getParent());
}
}
}
@FXML
private void onActionMoveUp(ActionEvent event) {
if (hboxReference != null) {
moveUpHBox((AnchorPane) hboxReference.getParent());
}
}
@FXML
private void onKeyPressedMoveDown(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
if (hboxReference != null) {
moveDownHBox((AnchorPane) hboxReference.getParent());
}
}
}
@FXML
private void onActionMoveDown(ActionEvent event) {
if (hboxReference != null) {
moveDownHBox((AnchorPane) hboxReference.getParent());
}
}
@FXML
private void onKeyPressedLeft(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
leftElementHBox();
}
}
@FXML
private void onActionLeft(ActionEvent event) {
leftElementHBox();
}
@FXML
private void onKeyPressedCenter(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
centerElementHBox();
}
}
@FXML
private void onActionCenter(ActionEvent event) {
centerElementHBox();
}
@FXML
private void onKeyPressedRight(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
rightElementHBox();
}
}
@FXML
private void onActionRight(ActionEvent event) {
rightElementHBox();
}
@FXML
private void onKeyPressedPredeterminado(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
onEventPredeterminado();
}
}
@FXML
private void onActionPredeterminado(ActionEvent event) {
onEventPredeterminado();
}
@FXML
private void onActionFuente(ActionEvent event) {
if (cbFuente.getSelectionModel().getSelectedIndex() >= 0) {
if (tfReference != null) {
switch (cbFuente.getSelectionModel().getSelectedIndex()) {
case 0:
tfReference.setFontName("Consola");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
break;
case 1:
tfReference.setFontName("Roboto Regular");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
break;
default:
tfReference.setFontName("Roboto Bold");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
break;
}
HBox hBox = (HBox) tfReference.getParent();
for (int i = 0; i < hBox.getChildren().size(); i++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(i);
field.setFontName(tfReference.getFontName());
field.setStyle("-fx-background-color: " + field.getFontBackground() + ";-fx-text-fill:" + field.getFontColor() + ";-fx-font-family:" + (field.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : field.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
}
}
}
}
@FXML
private void onSize(ActionEvent event) {
if (cbFuente.getSelectionModel().getSelectedIndex() >= 0) {
if (tfReference != null) {
tfReference.setFontSize(cbSize.getSelectionModel().getSelectedItem());
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
HBox hBox = (HBox) tfReference.getParent();
for (int i = 0; i < hBox.getChildren().size(); i++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(i);
field.setFontSize(cbSize.getSelectionModel().getSelectedItem());
field.setStyle("-fx-background-color: " + field.getFontBackground() + ";-fx-text-fill:" + field.getFontColor() + ";-fx-font-family:" + (field.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : field.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
}
}
}
}
@FXML
private void onActionAncho(ActionEvent event) {
if (hboxReference != null) {
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
double oldWidth = viewTicket.getFitWidth();
viewTicket.setFitWidth(Tools.isNumeric(txtAncho.getText().trim()) && Double.parseDouble(txtAncho.getText().trim()) > 0 ? Double.parseDouble(txtAncho.getText()) : oldWidth);
}
}
}
}
@FXML
private void onKeyTypedAncho(KeyEvent event) {
char c = event.getCharacter().charAt(0);
if ((c < '0' || c > '9') && (c != '\b')) {
event.consume();
}
}
@FXML
private void onActionAlto(ActionEvent event) {
if (hboxReference != null) {
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
double oldHeight = viewTicket.getFitHeight();
viewTicket.setFitHeight(Tools.isNumeric(txtAlto.getText().trim()) && Double.parseDouble(txtAlto.getText().trim()) > 0 ? Double.parseDouble(txtAlto.getText()) : oldHeight);
hboxReference.setPrefHeight(viewTicket.getFitHeight());
double yPosBefero = 0;
AnchorPane apDady = (AnchorPane) hboxReference.getParent();
for (int p = 0; p < apDady.getChildren().size(); p++) {
HBox hb = (HBox) apDady.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
apDady.layout();
}
}
}
}
@FXML
private void onKeyTypedAlto(KeyEvent event) {
char c = event.getCharacter().charAt(0);
if ((c < '0' || c > '9') && (c != '\b')) {
event.consume();
}
}
public AnchorPane getHbEncabezado() {
return apEncabezado;
}
public AnchorPane getHbDetalleCabecera() {
return apDetalleCabecera;
}
public AnchorPane getHbPie() {
return apPie;
}
public short getSheetWidth() {
return sheetWidth;
}
public void setContent(FxPrincipalController fxPrincipalController) {
this.fxPrincipalController = fxPrincipalController;
}
}
| UTF-8 | Java | 100,906 | java | FxTicketController.java | Java | [] | null | [] | package controller.configuracion.tickets;
import controller.configuracion.impresoras.FxImprimirController;
import controller.menus.FxPrincipalController;
import controller.tools.FilesRouters;
import controller.tools.ImageViewTicket;
import controller.tools.Json;
import controller.tools.Session;
import controller.tools.TextFieldTicket;
import controller.tools.Tools;
import controller.tools.WindowStage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ResourceBundle;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import model.ImageADO;
import model.ImagenTB;
import model.TicketADO;
import model.TicketTB;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class FxTicketController implements Initializable {
@FXML
private VBox vbWindow;
@FXML
private VBox vbContenedor;
@FXML
private AnchorPane apEncabezado;
@FXML
private AnchorPane apDetalleCabecera;
@FXML
private AnchorPane apPie;
@FXML
private TextField txtAnchoColumna;
@FXML
private ComboBox<Pos> cbAlignment;
@FXML
private CheckBox cbMultilinea;
@FXML
private CheckBox cbEditable;
@FXML
private TextField txtVariable;
@FXML
private Label lblNombre;
@FXML
private Label lblColumnas;
@FXML
private Label formatoTicket;
@FXML
private CheckBox cbPredeterminado;
@FXML
private ComboBox<String> cbFuente;
@FXML
private ComboBox<Float> cbSize;
@FXML
private TextField txtAncho;
@FXML
private TextField txtAlto;
private FxPrincipalController fxPrincipalController;
private TextFieldTicket tfAnterior;
private TextFieldTicket tfReference;
private File selectFile;
private HBox hboxAnterior;
private HBox hboxReference;
private short sheetWidth;
private double pointWidth;
private int idTicket;
private int tipoTicket;
private String ruta;
@Override
public void initialize(URL url, ResourceBundle rb) {
pointWidth = 8.10;
sheetWidth = 0;
cbAlignment.getItems().add(Pos.CENTER_LEFT);
cbAlignment.getItems().add(Pos.CENTER);
cbAlignment.getItems().add(Pos.CENTER_RIGHT);
cbFuente.getItems().addAll("Consola", "Roboto Regular", "Roboto Bold");
cbSize.getItems().addAll(10.5f, 12.5f, 14.5f, 16.5f, 18.5f, 20.5f, 22.5f, 24.5f);
}
public void loadTicket(int idTicket, int tipoTicket, String nombre, String ruta, boolean predeterminado) {
if (ruta != null) {
this.idTicket = idTicket;
this.tipoTicket = tipoTicket;
this.ruta = ruta;
hboxReference = null;
JSONObject jSONObject = Json.obtenerObjetoJSON(ruta);
apEncabezado.getChildren().clear();
apDetalleCabecera.getChildren().clear();
apPie.getChildren().clear();
lblNombre.setText(nombre);
formatoTicket.setText(tipoTicket + "");
cbPredeterminado.setSelected(predeterminado);
cbPredeterminado.setText(predeterminado ? "SI" : "NO");
ArrayList<ImagenTB> imagenTBs = ImageADO.ListaImagePorIdRelacionado(idTicket);
sheetWidth = jSONObject.get("column") != null ? Short.parseShort(jSONObject.get("column").toString()) : (short) 40;
lblColumnas.setText("" + sheetWidth);
vbContenedor.setPrefWidth(sheetWidth * pointWidth);
if (jSONObject.get("cabecera") != null) {
JSONObject cabeceraObjects = Json.obtenerObjetoJSON(jSONObject.get("cabecera").toString());
for (int i = 0; i < cabeceraObjects.size(); i++) {
HBox box = generateElement(apEncabezado, "cb");
JSONObject objectObtener = Json.obtenerObjetoJSON(cabeceraObjects.get("cb_" + (i + 1)).toString());
if (objectObtener.get("text") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("text").toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
} else if (objectObtener.get("list") != null) {
JSONArray array = Json.obtenerArrayJSON(objectObtener.get("list").toString());
Iterator it = array.iterator();
while (it.hasNext()) {
JSONObject object = Json.obtenerObjetoJSON(it.next().toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
}
} else if (objectObtener.get("image") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("image").toString());
ImageViewTicket imageView = addElementImageView("", Short.parseShort(object.get("width").toString()), Double.parseDouble(object.get("fitwidth").toString()), Double.parseDouble(object.get("fitheight").toString()), false, object.get("type").toString());
imageView.setId(String.valueOf(object.get("value").toString()));
box.setPrefWidth(imageView.getColumnWidth() * pointWidth);
box.setPrefHeight(imageView.getFitHeight());
box.setAlignment(getAlignment(object.get("align").toString()));
box.getChildren().add(imageView);
}
}
}
if (jSONObject.get("detalle") != null) {
JSONObject detalleObjects = Json.obtenerObjetoJSON(jSONObject.get("detalle").toString());
for (int i = 0; i < detalleObjects.size(); i++) {
HBox box = generateElement(apDetalleCabecera, "dr");
JSONObject objectObtener = Json.obtenerObjetoJSON(detalleObjects.get("dr_" + (i + 1)).toString());
if (objectObtener.get("text") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("text").toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
} else if (objectObtener.get("list") != null) {
JSONArray array = Json.obtenerArrayJSON(objectObtener.get("list").toString());
Iterator it = array.iterator();
while (it.hasNext()) {
JSONObject object = Json.obtenerObjetoJSON(it.next().toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
}
} else if (objectObtener.get("image") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("image").toString());
ImageViewTicket imageView = addElementImageView("", Short.parseShort(object.get("width").toString()), Double.parseDouble(object.get("fitwidth").toString()), Double.parseDouble(object.get("fitheight").toString()), false, object.get("type").toString());
imageView.setId(String.valueOf(object.get("value").toString()));
box.setPrefWidth(imageView.getColumnWidth() * pointWidth);
box.setPrefHeight(imageView.getFitHeight());
box.setAlignment(getAlignment(object.get("align").toString()));
box.getChildren().add(imageView);
}
}
}
if (jSONObject.get("pie") != null) {
JSONObject pieObjects = Json.obtenerObjetoJSON(jSONObject.get("pie").toString());
for (int i = 0; i < pieObjects.size(); i++) {
HBox box = generateElement(apPie, "cp");
JSONObject objectObtener = Json.obtenerObjetoJSON(pieObjects.get("cp_" + (i + 1)).toString());
if (objectObtener.get("text") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("text").toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
} else if (objectObtener.get("list") != null) {
JSONArray array = Json.obtenerArrayJSON(objectObtener.get("list").toString());
Iterator it = array.iterator();
while (it.hasNext()) {
JSONObject object = Json.obtenerObjetoJSON(it.next().toString());
TextFieldTicket field = addElementTextField("iu", object.get("value").toString(), Boolean.valueOf(object.get("multiline").toString()), Short.parseShort(object.get("lines").toString()), Short.parseShort(object.get("width").toString()), getAlignment(object.get("align").toString()), Boolean.parseBoolean(object.get("editable").toString()), String.valueOf(object.get("variable").toString()), String.valueOf(object.get("font").toString()), Float.valueOf(object.get("size").toString()));
box.getChildren().add(field);
}
} else if (objectObtener.get("image") != null) {
JSONObject object = Json.obtenerObjetoJSON(objectObtener.get("image").toString());
ImageViewTicket imageView = addElementImageView("", Short.parseShort(object.get("width").toString()), Double.parseDouble(object.get("fitwidth").toString()), Double.parseDouble(object.get("fitheight").toString()), false, object.get("type").toString());
imageView.setId(String.valueOf(object.get("value").toString()));
box.setPrefWidth(imageView.getColumnWidth() * pointWidth);
box.setPrefHeight(imageView.getFitHeight());
box.setAlignment(getAlignment(object.get("align").toString()));
box.getChildren().add(imageView);
}
}
}
for (int i = 0; i < imagenTBs.size(); i++) {
for (int m = 0; m < apEncabezado.getChildren().size(); m++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(m);
if (hBox.getChildren().size() == 1) {
Object object = hBox.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket imageViewTicket = (ImageViewTicket) hBox.getChildren().get(0);
if (imagenTBs.get(i).getIdSubRelacion().equalsIgnoreCase(imageViewTicket.getId())) {
imageViewTicket.setUrl(imagenTBs.get(i).getImagen());
imageViewTicket.setImage(new Image(new ByteArrayInputStream(imagenTBs.get(i).getImagen())));
}
}
}
}
}
for (int i = 0; i < imagenTBs.size(); i++) {
for (int m = 0; m < apDetalleCabecera.getChildren().size(); m++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(m);
if (hBox.getChildren().size() == 1) {
Object object = hBox.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket imageViewTicket = (ImageViewTicket) hBox.getChildren().get(0);
if (imagenTBs.get(i).getIdSubRelacion().equalsIgnoreCase(imageViewTicket.getId())) {
imageViewTicket.setUrl(imagenTBs.get(i).getImagen());
imageViewTicket.setImage(new Image(new ByteArrayInputStream(imagenTBs.get(i).getImagen())));
}
}
}
}
}
for (int i = 0; i < imagenTBs.size(); i++) {
for (int m = 0; m < apPie.getChildren().size(); m++) {
HBox hBox = (HBox) apPie.getChildren().get(m);
if (hBox.getChildren().size() == 1) {
Object object = hBox.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket imageViewTicket = (ImageViewTicket) hBox.getChildren().get(0);
if (imagenTBs.get(i).getIdSubRelacion().equalsIgnoreCase(imageViewTicket.getId())) {
imageViewTicket.setUrl(imagenTBs.get(i).getImagen());
imageViewTicket.setImage(new Image(new ByteArrayInputStream(imagenTBs.get(i).getImagen())));
}
}
}
}
}
}
}
private void saveTicket() {
try {
int valideteUno = 0;
int valideteDos = 0;
int valideteTree = 0;
for (int i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteUno++;
}
}
for (int i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteDos++;
}
}
for (int i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteTree++;
}
}
if (valideteUno > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en la cabecera sin contenido");
} else if (valideteDos > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el detalle sin contenido");
} else if (valideteTree > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el pie sin contenido");
} else {
if (!apEncabezado.getChildren().isEmpty() && !apDetalleCabecera.getChildren().isEmpty() && !apPie.getChildren().isEmpty()) {
JSONObject sampleObject = new JSONObject();
sampleObject.put("column", sheetWidth);
JSONObject cabecera = new JSONObject();
for (int i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
JSONObject cb = new JSONObject();
if (hBox.getChildren().size() > 1) {
JSONArray kids = new JSONArray();
for (int v = 0; v < hBox.getChildren().size(); v++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(v);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
kids.add(cbkid);
}
cb.put("list", kids);
} else {
Object object = hBox.getChildren().get(0);
if (object instanceof TextFieldTicket) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
cb.put("text", cbkid);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", viewTicket.getId());
cbkid.put("width", viewTicket.getColumnWidth());
cbkid.put("align", hBox.getAlignment().toString());
cbkid.put("variable", "");
cbkid.put("fitwidth", viewTicket.getFitWidth());
cbkid.put("fitheight", viewTicket.getFitHeight());
cbkid.put("type", viewTicket.getType());
cb.put("image", cbkid);
}
}
cabecera.put("cb_" + (i + 1), cb);
}
JSONObject detalle = new JSONObject();
for (int i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
JSONObject cb = new JSONObject();
if (hBox.getChildren().size() > 1) {
JSONArray kids = new JSONArray();
for (int v = 0; v < hBox.getChildren().size(); v++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(v);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
kids.add(cbkid);
}
cb.put("list", kids);
} else {
Object object = hBox.getChildren().get(0);
if (object instanceof TextFieldTicket) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
cb.put("text", cbkid);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", viewTicket.getId());
cbkid.put("width", viewTicket.getColumnWidth());
cbkid.put("align", hBox.getAlignment().toString());
cbkid.put("variable", "");
cbkid.put("fitwidth", viewTicket.getFitWidth());
cbkid.put("fitheight", viewTicket.getFitHeight());
cbkid.put("type", viewTicket.getType());
cb.put("image", cbkid);
}
}
detalle.put("dr_" + (i + 1), cb);
}
JSONObject pie = new JSONObject();
for (int i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
JSONObject cb = new JSONObject();
if (hBox.getChildren().size() > 1) {
JSONArray kids = new JSONArray();
for (int v = 0; v < hBox.getChildren().size(); v++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(v);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
kids.add(cbkid);
}
cb.put("list", kids);
} else {
Object object = hBox.getChildren().get(0);
if (object instanceof TextFieldTicket) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", field.getText());
cbkid.put("width", field.getColumnWidth());
cbkid.put("align", field.getAlignment().toString());
cbkid.put("multiline", field.isMultilineas());
cbkid.put("lines", field.getLines());
cbkid.put("editable", field.isEditable());
cbkid.put("variable", field.getVariable());
cbkid.put("font", field.getFontName());
cbkid.put("size", field.getFontSize());
cb.put("text", cbkid);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(0);
JSONObject cbkid = new JSONObject();
cbkid.put("value", viewTicket.getId());
cbkid.put("width", viewTicket.getColumnWidth());
cbkid.put("align", hBox.getAlignment().toString());
cbkid.put("variable", "");
cbkid.put("fitwidth", viewTicket.getFitWidth());
cbkid.put("fitheight", viewTicket.getFitHeight());
cbkid.put("type", viewTicket.getType());
cb.put("image", cbkid);
}
}
pie.put("cp_" + (i + 1), cb);
}
sampleObject.put("cabecera", cabecera);
sampleObject.put("detalle", detalle);
sampleObject.put("pie", pie);
Files.write(Paths.get("./archivos/ticketventa.json"), sampleObject.toJSONString().getBytes());
TicketTB ticketTB = new TicketTB();
ticketTB.setId(idTicket);
ticketTB.setNombreTicket(lblNombre.getText().trim().toUpperCase());
ticketTB.setRuta(sampleObject.toJSONString());
ticketTB.setTipo(tipoTicket);
ticketTB.setPredeterminado(cbPredeterminado.isSelected());
ticketTB.setApCabecera(apEncabezado);
ticketTB.setApDetalle(apDetalleCabecera);
ticketTB.setApPie(apPie);
String result = TicketADO.CrudTicket(ticketTB);
if (result.equalsIgnoreCase("duplicate")) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El nombre del formato ya existe, intente con otro.");
} else if (result.equalsIgnoreCase("updated")) {
Tools.AlertMessageInformation(vbWindow, "Ticket", "Se actualizo correctamente el formato.");
if (cbPredeterminado.isSelected()) {
switch (tipoTicket) {
case 1:
Session.TICKET_VENTA_ID = idTicket;
Session.TICKET_VENTA_RUTA = sampleObject.toJSONString();
break;
case 2:
Session.TICKET_COMPRA_ID = idTicket;
Session.TICKET_COMPRA_RUTA = sampleObject.toJSONString();
break;
case 5:
Session.TICKET_CORTE_CAJA_ID = idTicket;
Session.TICKET_CORTE_CAJA_RUTA = sampleObject.toJSONString();
break;
case 7:
Session.TICKET_PRE_VENTA_ID = idTicket;
Session.TICKET_PRE_VENTA_RUTA = sampleObject.toJSONString();
break;
case 8:
Session.TICKET_COTIZACION_ID = idTicket;
Session.TICKET_COTIZACION_RUTA = sampleObject.toJSONString();
break;
case 9:
Session.TICKET_CUENTA_POR_COBRAR_ID = idTicket;
Session.TICKET_CUENTA_POR_COBRAR_RUTA = sampleObject.toJSONString();
break;
case 10:
Session.TICKET_CUENTA_POR_PAGAR_ID = idTicket;
Session.TICKET_CUENTA_POR_PAGAR_RUTA = sampleObject.toJSONString();
break;
case 11:
Session.TICKET_GUIA_REMISION_ID = idTicket;
Session.TICKET_GUIA_REMISION_RUTA = sampleObject.toJSONString();
break;
case 12:
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_ID = idTicket;
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_RUTA = sampleObject.toJSONString();
break;
case 13:
Session.TICKET_PEDIDO_ID = idTicket;
Session.TICKET_PEDIDO_RUTA = sampleObject.toJSONString();
break;
case 14:
Session.TICKET_ORDEN_COMPRA_ID = idTicket;
Session.TICKET_ORDEN_COMPRA_RUTA = sampleObject.toJSONString();
break;
case 15:
Session.TICKET_NOTA_CREDITO_ID = idTicket;
Session.TICKET_NOTA_CREDITO_RUTA = sampleObject.toJSONString();
break;
default:
break;
}
}
clearPane();
} else if (result.equalsIgnoreCase("registered")) {
Tools.AlertMessageInformation(vbWindow, "Ticket", "Se guardo correctamente el formato, recuerda siempre poner en predeterminado el ticket, si lo va utilizar frecuentemente.");
clearPane();
} else {
Tools.AlertMessageError(vbWindow, "Ticket", result);
}
} else {
if (apEncabezado.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El encabezado está vacío.");
} else if (apDetalleCabecera.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El detalle cabecera está vacío.");
} else if (apPie.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El pie está vacío.");
}
}
}
} catch (IOException ex) {
Tools.AlertMessageError(vbWindow, "Ticket", "No se pudo guardar la hoja con problemas de formato.");
System.out.println(ex.getLocalizedMessage());
System.out.println(ex);
}
}
private HBox generateElement(AnchorPane contenedor, String id) {
if (contenedor.getChildren().isEmpty()) {
return addElement(contenedor, id + "1", true);
} else {
HBox hBox = (HBox) contenedor.getChildren().get(contenedor.getChildren().size() - 1);
String idGenerate = hBox.getId();
String codigo = idGenerate.substring(2);
int valor = Integer.parseInt(codigo) + 1;
String newCodigo = id + valor;
return addElement(contenedor, newCodigo, true);
}
}
private HBox addElement(AnchorPane contenedor, String id, boolean useLayout) {
double layoutY = 0;
if (useLayout) {
for (int i = 0; i < contenedor.getChildren().size(); i++) {
layoutY += ((HBox) contenedor.getChildren().get(i)).getPrefHeight();
}
}
ImageView imgRemove = new ImageView(new Image("/view/image/remove-item.png"));
imgRemove.setFitWidth(20);
imgRemove.setFitHeight(20);
ImageView imgMoveDown = new ImageView(new Image("/view/image/movedown.png"));
imgMoveDown.setFitWidth(20);
imgMoveDown.setFitHeight(20);
ImageView imgMoveUp = new ImageView(new Image("/view/image/moveup.png"));
imgMoveUp.setFitWidth(20);
imgMoveUp.setFitHeight(20);
ImageView imgText = new ImageView(new Image("/view/image/text.png"));
imgText.setFitWidth(20);
imgText.setFitHeight(20);
ImageView imgTextVariable = new ImageView(new Image("/view/image/text-variable.png"));
imgTextVariable.setFitWidth(20);
imgTextVariable.setFitHeight(20);
ImageView imgTextLines = new ImageView(new Image("/view/image/text-lines.png"));
imgTextLines.setFitWidth(20);
imgTextLines.setFitHeight(20);
ImageView imgUnaLinea = new ImageView(new Image("/view/image/linea.png"));
imgUnaLinea.setFitWidth(20);
imgUnaLinea.setFitHeight(20);
ImageView imgDobleLinea = new ImageView(new Image("/view/image/doble-linea.png"));
imgDobleLinea.setFitWidth(20);
imgDobleLinea.setFitHeight(20);
ImageView imgImage = new ImageView(new Image("/view/image/photo.png"));
imgImage.setFitWidth(20);
imgImage.setFitHeight(20);
HBox hBox = new HBox();
hBox.setId(id);
hBox.setLayoutX(0);
hBox.setLayoutY(layoutY);
hBox.setPrefWidth(sheetWidth * pointWidth);
//font size 12.5px
hBox.setPrefHeight(30);
hBox.setStyle("-fx-padding:0 20 0 0;-fx-border-width: 1 1 1 1;-fx-border-color: #0066ff;;-fx-background-color: white;");
hBox.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> {
hboxAnterior = hboxReference;
if (hboxAnterior != null) {
hboxAnterior.setStyle("-fx-padding:0 20 0 0;-fx-border-width: 1 1 1 1;-fx-border-color: #0066ff;-fx-background-color: white;");
}
hBox.setStyle("-fx-padding:0 20 0 0;-fx-border-width: 1 1 1 1;-fx-border-color: #0066ff;-fx-background-color: rgb(250, 198, 203);");
hboxReference = hBox;
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
txtAncho.setText(Tools.roundingValue(viewTicket.getFitWidth(), 0));
txtAlto.setText(Tools.roundingValue(viewTicket.getFitHeight(), 0));
}
}
});
ContextMenu contextMenu = new ContextMenu();
MenuItem remove = new MenuItem("Remover Renglón");
remove.setGraphic(imgRemove);
remove.setOnAction(e -> {
for (int b = 0; b < contenedor.getChildren().size(); b++) {
if (contenedor.getChildren().get(b).getId().equalsIgnoreCase(hBox.getId())) {
contenedor.getChildren().remove(b);
double yPosBefero = 0;
for (int p = 0; p < contenedor.getChildren().size(); p++) {
HBox hb = (HBox) contenedor.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
contenedor.layout();
break;
}
}
int valor = 0;
for (int n = 0; n < contenedor.getChildren().size(); n++) {
HBox boxn = (HBox) contenedor.getChildren().get(n);
if (boxn.getChildren().size() == 1) {
Object object = boxn.getChildren().get(0);
if (object instanceof ImageViewTicket) {
valor++;
ImageViewTicket imageViewTicket = (ImageViewTicket) boxn.getChildren().get(0);
imageViewTicket.setId(boxn.getParent().equals(apEncabezado) ? "imc" + valor
: boxn.getParent().equals(apDetalleCabecera) ? "imd" + valor : boxn.getParent().equals(apPie) ? "imp" + valor : "");
}
}
}
});
MenuItem text = new MenuItem("Agregar Texto");
text.setGraphic(imgText);
text.setOnAction(e -> {
TextFieldTicket field = addElementTextField("iu", "Escriba", false, (short) 0, (short) 7, Pos.CENTER_LEFT, true, "", "Consola", 12.5f);
hBox.getChildren().add(field);
});
MenuItem textVariable = new MenuItem("Agregar Variable");
textVariable.setGraphic(imgTextVariable);
textVariable.setOnAction(e -> {
windowTextVar(hBox);
});
MenuItem textMultilinea = new MenuItem("Agregar Texto Multilínea");
textMultilinea.setGraphic(imgTextLines);
textMultilinea.setOnAction(e -> {
windowTextMultilinea(hBox);
});
MenuItem textUnaLinea = new MenuItem("Agregar Línea");
textUnaLinea.setGraphic(imgUnaLinea);
textUnaLinea.setOnAction(e -> {
String value = "";
for (int i = 0; i < sheetWidth; i++) {
value += "-";
}
TextFieldTicket field = addElementTextField("iu", value, false, (short) 0, sheetWidth, Pos.CENTER_LEFT, false, "", "Consola", 12.5f);
hBox.getChildren().add(field);
});
MenuItem textDosLineas = new MenuItem("Agregar Doble Línea");
textDosLineas.setGraphic(imgDobleLinea);
textDosLineas.setOnAction(e -> {
String value = "";
for (int i = 0; i < sheetWidth; i++) {
value += "=";
}
TextFieldTicket field = addElementTextField("iu", value, false, (short) 0, sheetWidth, Pos.CENTER_LEFT, false, "", "Consola", 12.5f);
hBox.getChildren().add(field);
});
MenuItem moveUp = new MenuItem("Subir elemento");
moveUp.setGraphic(imgMoveUp);
moveUp.setOnAction(e -> {
moveUpHBox(contenedor);
});
MenuItem moveDown = new MenuItem("Bajar elemento");
moveDown.setGraphic(imgMoveDown);
moveDown.setOnAction(e -> {
moveDownHBox(contenedor);
});
MenuItem addImage = new MenuItem("Agregar imagen");
addImage.setGraphic(imgImage);
addImage.setOnAction(e -> {
if (hBox.getChildren().isEmpty()) {
int currentTotal = 0;
for (int n = 0; n < contenedor.getChildren().size(); n++) {
HBox boxn = (HBox) contenedor.getChildren().get(n);
if (boxn.getChildren().size() == 1) {
if (boxn.getChildren().get(0) instanceof ImageViewTicket) {
currentTotal++;
}
}
}
String newCodigo = "";
if (contenedor.equals(apEncabezado)) {
int valor = currentTotal + 1;
newCodigo = "imc" + valor;
} else if (contenedor.equals(apDetalleCabecera)) {
int valor = currentTotal + 1;
newCodigo = "imd" + valor;
} else if (contenedor.equals(apPie)) {
int valor = currentTotal + 1;
newCodigo = "imp" + valor;
}
ImageViewTicket imageView = addElementImageView("/view/image/no-image.png", sheetWidth, 100, 86, true, "image");
imageView.setId(newCodigo);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.setPrefHeight(imageView.getFitHeight());
hBox.getChildren().add(imageView);
double yPosBefero = 0;
for (int p = 0; p < contenedor.getChildren().size(); p++) {
HBox hb = (HBox) contenedor.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
contenedor.layout();
}
});
MenuItem addQr = new MenuItem("Agregar QR");
addQr.setGraphic(imgImage);
addQr.setOnAction(e -> {
if (hBox.getChildren().isEmpty()) {
int currentTotal = 0;
for (int n = 0; n < contenedor.getChildren().size(); n++) {
HBox boxn = (HBox) contenedor.getChildren().get(n);
if (boxn.getChildren().size() == 1) {
if (boxn.getChildren().get(0) instanceof ImageViewTicket) {
currentTotal++;
}
}
}
String newCodigo = "";
if (contenedor.equals(apEncabezado)) {
int valor = currentTotal + 1;
newCodigo = "imc" + valor;
} else if (contenedor.equals(apDetalleCabecera)) {
int valor = currentTotal + 1;
newCodigo = "imd" + valor;
} else if (contenedor.equals(apPie)) {
int valor = currentTotal + 1;
newCodigo = "imp" + valor;
}
// try {
// BufferedImage qrImage = com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage(new com.google.zxing.qrcode.QRCodeWriter().encode("",com.google.zxing.BarcodeFormat.QR_CODE, 300, 300));
// } catch (WriterException ex) {
// Logger.getLogger(FxTicketController.class.getName()).log(Level.SEVERE, null, ex);
// }
ImageViewTicket imageView = addElementImageView("/view/image/qr.png", sheetWidth, 100, 86, true, "qr");
imageView.setId(newCodigo);
hBox.setAlignment(Pos.CENTER_LEFT);
hBox.setPrefHeight(imageView.getFitHeight());
hBox.getChildren().add(imageView);
double yPosBefero = 0;
for (int p = 0; p < contenedor.getChildren().size(); p++) {
HBox hb = (HBox) contenedor.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
contenedor.layout();
}
});
contextMenu.getItems().addAll(text, textVariable, textMultilinea, textUnaLinea, textDosLineas, remove, moveUp, moveDown, addImage, addQr);
hBox.setOnContextMenuRequested((ContextMenuEvent event) -> {
contextMenu.show(hBox, event.getSceneX(), event.getSceneY());
short widthContent = 0;
for (int i = 0; i < hBox.getChildren().size(); i++) {
Object object = hBox.getChildren().get(i);
if (object instanceof TextFieldTicket) {
widthContent += ((TextFieldTicket) hBox.getChildren().get(i)).getColumnWidth();
} else if (object instanceof ImageViewTicket) {
widthContent += ((ImageViewTicket) hBox.getChildren().get(i)).getColumnWidth();
}
}
text.setDisable((widthContent + 13) > sheetWidth);
textUnaLinea.setDisable((widthContent + 13) > sheetWidth);
textDosLineas.setDisable((widthContent + 13) > sheetWidth);
addImage.setDisable(!hBox.getChildren().isEmpty());
addQr.setDisable(!hBox.getChildren().isEmpty());
});
if (useLayout) {
contenedor.getChildren().add(hBox);
}
return hBox;
}
public TextFieldTicket addElementTextField(String id, String titulo, boolean multilinea, short lines, short widthColumn, Pos align, boolean editable, String variable, String font, float size) {
TextFieldTicket field = new TextFieldTicket(titulo, id);
field.setMultilineas(multilinea);
field.setLines(lines);
field.setColumnWidth(widthColumn);
field.setVariable(variable);
field.setEditable(editable);
field.setPreferredSize((double) widthColumn * pointWidth, 30);
field.setAlignment(align);
field.setFontColor(editable ? "black" : "#d62c0a");
field.setFontName(font);
field.setFontSize(size);
field.setFontBackground("white");
field.getStyleClass().add("text-field-ticket");
field.setStyle("-fx-background-color:" + field.getFontBackground() + " ;-fx-text-fill:" + field.getFontColor() + ";-fx-font-family:" + (field.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : field.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
field.addEventHandler(MouseEvent.MOUSE_PRESSED, m -> {
tfAnterior = tfReference;
if (tfAnterior != null) {
tfAnterior.setStyle("-fx-background-color: white;-fx-text-fill:" + tfAnterior.getFontColor() + ";-fx-font-family:" + (tfAnterior.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfAnterior.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfAnterior.getFontSize() + ";");
}
tfReference = field;
tfReference.setFontBackground("#cecece");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
txtAnchoColumna.setText(tfReference.getColumnWidth() + "");
cbAlignment.getItems().forEach(c -> {
if (c.equals(tfReference.getAlignment())) {
cbAlignment.getSelectionModel().select(c);
}
});
//HBox hBox = (HBox) tfReference.getParent();
//cbFuente.setDisable(hBox.getChildren().size() > 1);
cbFuente.getSelectionModel().select(tfReference.getFontName());
//cbSize.setDisable(hBox.getChildren().size() > 1);
cbSize.getSelectionModel().select(tfReference.getFontSize());
cbMultilinea.setSelected(tfReference.isMultilineas());
cbMultilinea.setText(tfReference.isMultilineas() ? "Si" : "No");
cbEditable.setSelected(tfReference.isEditable());
cbEditable.setText(tfReference.isEditable() ? "Si" : "No");
txtVariable.setText(tfReference.getVariable());
});
field.lengthProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
if (!field.isMultilineas()) {
if (newValue.intValue() > oldValue.intValue()) {
if (field.getText().length() >= field.getColumnWidth()) {
field.setText(field.getText().substring(0, field.getColumnWidth()));
}
}
}
});
ImageView imgRemove = new ImageView(new Image("/view/image/remove-item.png"));
imgRemove.setFitWidth(20);
imgRemove.setFitHeight(20);
ImageView imgAdaptParentWidth = new ImageView(new Image("/view/image/width-parent.png"));
imgAdaptParentWidth.setFitWidth(20);
imgAdaptParentWidth.setFitHeight(20);
ImageView imgTextLeft = new ImageView(new Image("/view/image/text-left.png"));
imgTextLeft.setFitWidth(20);
imgTextLeft.setFitHeight(20);
ImageView imgTextCenter = new ImageView(new Image("/view/image/text-center.png"));
imgTextCenter.setFitWidth(20);
imgTextCenter.setFitHeight(20);
ImageView imgTextRight = new ImageView(new Image("/view/image/text-right.png"));
imgTextRight.setFitWidth(20);
imgTextRight.setFitHeight(20);
ContextMenu contextMenu = new ContextMenu();
MenuItem remove = new MenuItem("Remover Campo de Texto");
remove.setGraphic(imgRemove);
remove.setOnAction(e -> {
((HBox) field.getParent()).getChildren().remove(field);
});
MenuItem textAdaptWidth = new MenuItem("Adaptar el Ancho del Padre");
textAdaptWidth.setGraphic(imgAdaptParentWidth);
textAdaptWidth.setOnAction(e -> {
field.setColumnWidth(sheetWidth);
field.setPreferredSize(((double) field.getColumnWidth() * pointWidth), field.getPrefHeight());
});
MenuItem textLeft = new MenuItem("Alineación Izquierda");
textLeft.setGraphic(imgTextLeft);
textLeft.setOnAction(e -> {
if (!field.getText().isEmpty()) {
field.setAlignment(Pos.CENTER_LEFT);
}
});
MenuItem textCenter = new MenuItem("Alineación Central");
textCenter.setGraphic(imgTextCenter);
textCenter.setOnAction(e -> {
if (!field.getText().isEmpty()) {
field.setAlignment(Pos.CENTER);
}
});
MenuItem textRight = new MenuItem("Alineación Derecha");
textRight.setGraphic(imgTextRight);
textRight.setOnAction(e -> {
if (!field.getText().isEmpty()) {
field.setAlignment(Pos.CENTER_RIGHT);
}
});
contextMenu.getItems().addAll(remove, textAdaptWidth, new SeparatorMenuItem(), textLeft, textCenter, textRight);
field.setContextMenu(contextMenu);
field.setOnContextMenuRequested((event) -> {
if (((HBox) field.getParent()).getChildren().size() > 1) {
textAdaptWidth.setDisable(true);
}
if (field.isMultilineas()) {
textLeft.setDisable(true);
textCenter.setDisable(true);
textRight.setDisable(true);
}
});
return field;
}
private ImageViewTicket addElementImageView(String path, short widthColumn, double width, double height, boolean newImage, String type) {
ImageViewTicket imageView = new ImageViewTicket();
imageView.setColumnWidth(widthColumn);
imageView.setFitWidth(width);
imageView.setFitHeight(height);
imageView.setSmooth(true);
imageView.setType(type);
if (newImage) {
imageView.setImage(new Image(path));
imageView.setUrl(Tools.getImageBytes(imageView.getImage(), Tools.getFileExtension(new File(path))));
}
return imageView;
}
private void actionAnchoColumnas() {
if (tfReference != null) {
if (Tools.isNumeric(txtAnchoColumna.getText())) {
int widthContent = 0;
for (int i = 0; i < ((HBox) tfReference.getParent()).getChildren().size(); i++) {
TextFieldTicket fieldTicket = ((TextFieldTicket) ((HBox) tfReference.getParent()).getChildren().get(i));
if (fieldTicket != tfReference) {
widthContent += fieldTicket.getColumnWidth();
}
}
if ((widthContent + Integer.parseInt(txtAnchoColumna.getText())) > sheetWidth) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "No puede sobrepasar al ancho de la hoja.");
} else {
if (!tfReference.isMultilineas() && tfReference.isEditable()) {
if (tfReference.getText().length() < Integer.parseInt(txtAnchoColumna.getText())) {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
} else {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
tfReference.setText(tfReference.getText().substring(0, tfReference.getColumnWidth()));
}
} else {
if (tfReference.getText().length() < Integer.parseInt(txtAnchoColumna.getText())) {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
} else {
tfReference.setColumnWidth(Short.parseShort(txtAnchoColumna.getText()));
tfReference.setPreferredSize(((double) tfReference.getColumnWidth() * pointWidth), tfReference.getPrefHeight());
}
}
}
}
}
}
public void clearPane() {
idTicket = 0;
tipoTicket = 0;
ruta = "";
apEncabezado.getChildren().clear();
apDetalleCabecera.getChildren().clear();
apPie.getChildren().clear();
txtAnchoColumna.setText("");
cbAlignment.getSelectionModel().select(null);
cbFuente.getSelectionModel().select(null);
cbSize.getSelectionModel().select(null);
cbMultilinea.setSelected(false);
cbEditable.setSelected(false);
txtVariable.setText("");
lblNombre.setText("--");
formatoTicket.setText("--");
lblColumnas.setText("0");
sheetWidth = 0;
lblColumnas.setText(sheetWidth + "");
cbPredeterminado.setSelected(false);
cbPredeterminado.setText("NO");
vbContenedor.setPrefWidth(Control.USE_COMPUTED_SIZE);
}
private Pos getAlignment(String align) {
switch (align) {
case "CENTER":
return Pos.CENTER;
case "CENTER_LEFT":
return Pos.CENTER_LEFT;
case "CENTER_RIGHT":
return Pos.CENTER_RIGHT;
default:
return Pos.CENTER_LEFT;
}
}
private void searchTicket() {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_BUSQUEDA);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketBusquedaController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.loadComponents(0, true);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Seleccionar formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void nuevoTicket() {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_PROCESO);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketProcesoController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Nuevo formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void editarTicket() {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_PROCESO);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketProcesoController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.editarTicket(tipoTicket, lblNombre.getText(), sheetWidth);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Editar formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void windowTextMultilinea(HBox hBox) {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_MULTILINEA);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketMultilineaController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.setLoadComponent(hBox, sheetWidth);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Agregar texto multilinea", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void windowTextVar(HBox hBox) {
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_VARIABLE);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketVariableController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
controller.setLoadComponent(hBox, sheetWidth);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Agregar variable", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
private void openWindowImpresora() {
try {
int valideteUno = 0;
int valideteDos = 0;
int valideteTree = 0;
for (int i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteUno++;
}
}
for (int i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteDos++;
}
}
for (int i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
if (hBox.getChildren().isEmpty()) {
valideteTree++;
}
}
if (valideteUno > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en la cabecera sin contenido");
} else if (valideteDos > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el detalle sin contenido");
} else if (valideteTree > 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "Hay una fila en el pie sin contenido");
} else {
if (!apEncabezado.getChildren().isEmpty() && !apDetalleCabecera.getChildren().isEmpty() && !apPie.getChildren().isEmpty()) {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_IMPRIMIR);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxImprimirController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Imprimir Prueba", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.show();
} else {
if (apEncabezado.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El encabezado está vacío.");
} else if (apDetalleCabecera.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El detalle cabecera está vacío.");
} else if (apPie.getChildren().isEmpty()) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El pie está vacío.");
}
}
}
} catch (IOException ex) {
}
}
public void editarTicket(boolean editable, int tipoTicket, String nombre, short widthPage) {
if (editable) {
this.tipoTicket = tipoTicket;
lblNombre.setText(nombre);
sheetWidth = widthPage;
lblColumnas.setText("" + sheetWidth);
vbContenedor.setPrefWidth(sheetWidth * pointWidth);
formatoTicket.setText(tipoTicket + "");
for (short i = 0; i < apEncabezado.getChildren().size(); i++) {
HBox hBox = (HBox) apEncabezado.getChildren().get(i);
hBox.setPrefWidth(sheetWidth * pointWidth);
short newwidth = (short) (sheetWidth / hBox.getChildren().size());
for (short j = 0; j < hBox.getChildren().size(); j++) {
Object object = hBox.getChildren().get(j);
if (object instanceof TextFieldTicket) {
TextFieldTicket fieldTicket = (TextFieldTicket) hBox.getChildren().get(j);
fieldTicket.setColumnWidth(newwidth);
fieldTicket.setPreferredSize(newwidth * pointWidth, fieldTicket.getPrefHeight());
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(j);
viewTicket.setColumnWidth(newwidth);
}
}
}
for (short i = 0; i < apDetalleCabecera.getChildren().size(); i++) {
HBox hBox = (HBox) apDetalleCabecera.getChildren().get(i);
hBox.setPrefWidth(sheetWidth * pointWidth);
short newwidth = (short) (sheetWidth / hBox.getChildren().size());
for (short j = 0; j < hBox.getChildren().size(); j++) {
Object object = hBox.getChildren().get(j);
if (object instanceof TextFieldTicket) {
TextFieldTicket fieldTicket = (TextFieldTicket) hBox.getChildren().get(j);
fieldTicket.setColumnWidth(newwidth);
fieldTicket.setPreferredSize(newwidth * pointWidth, fieldTicket.getPrefHeight());
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(j);
viewTicket.setColumnWidth(newwidth);
}
}
}
for (short i = 0; i < apPie.getChildren().size(); i++) {
HBox hBox = (HBox) apPie.getChildren().get(i);
hBox.setPrefWidth(sheetWidth * pointWidth);
short newwidth = (short) (sheetWidth / hBox.getChildren().size());
for (short j = 0; j < hBox.getChildren().size(); j++) {
Object object = hBox.getChildren().get(j);
if (object instanceof TextFieldTicket) {
TextFieldTicket fieldTicket = (TextFieldTicket) hBox.getChildren().get(j);
fieldTicket.setColumnWidth(newwidth);
fieldTicket.setPreferredSize(newwidth * pointWidth, fieldTicket.getPrefHeight());
} else if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hBox.getChildren().get(j);
viewTicket.setColumnWidth(newwidth);
}
}
}
} else {
clearPane();
lblNombre.setText(nombre);
sheetWidth = widthPage;
lblColumnas.setText("" + sheetWidth);
vbContenedor.setPrefWidth(sheetWidth * pointWidth);
this.tipoTicket = tipoTicket;
formatoTicket.setText(tipoTicket + "");
cbPredeterminado.setSelected(false);
cbPredeterminado.setText("NO");
}
}
private void moveUpHBox(AnchorPane anchorPane) {
for (int i = 0; i < anchorPane.getChildren().size(); i++) {
if (((HBox) anchorPane.getChildren().get(i)).equals(hboxReference)) {
if (i == 0) {
break;
}
String style = hboxReference.getStyle();
HBox previous = (HBox) anchorPane.getChildren().get(i - 1);
HBox oldHbox = addElement(anchorPane, previous.getId(), false);
oldHbox.setLayoutY(previous.getLayoutY());
oldHbox.setPrefHeight(hboxReference.getPrefHeight());
for (int r = 0; r < hboxReference.getChildren().size(); r++) {
Object object = hboxReference.getChildren().get(r);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) hboxReference.getChildren().get(r);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
oldHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) hboxReference.getChildren().get(r);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setId(ivAnterior.getId());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
oldHbox.setAlignment(hboxReference.getAlignment());
oldHbox.getChildren().add(imageTicket);
}
}
HBox newHbox = addElement(anchorPane, hboxReference.getId(), false);
newHbox.setLayoutY(oldHbox.getLayoutY() + oldHbox.getPrefHeight());
newHbox.setPrefHeight(previous.getPrefHeight());
for (int a = 0; a < previous.getChildren().size(); a++) {
Object object = previous.getChildren().get(a);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) previous.getChildren().get(a);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
newHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) previous.getChildren().get(a);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setId(ivAnterior.getId());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
newHbox.setAlignment(hboxReference.getAlignment());
newHbox.getChildren().add(imageTicket);
}
}
anchorPane.getChildren().set(i - 1, oldHbox);
anchorPane.getChildren().set(i, newHbox);
oldHbox.setStyle(style);
hboxReference = oldHbox;
break;
}
}
anchorPane.layout();
}
private void moveDownHBox(AnchorPane anchorPane) {
for (int i = 0; i < anchorPane.getChildren().size(); i++) {
if (((HBox) anchorPane.getChildren().get(i)).equals(hboxReference)) {
if (anchorPane.getChildren().size() == (i + 1)) {
break;
}
String style = hboxReference.getStyle();
HBox later = (HBox) anchorPane.getChildren().get(i + 1);
HBox newHbox = addElement(anchorPane, hboxReference.getId(), false);
newHbox.setLayoutY(hboxReference.getLayoutY());
newHbox.setPrefHeight(later.getPrefHeight());
for (int a = 0; a < later.getChildren().size(); a++) {
Object object = later.getChildren().get(a);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) later.getChildren().get(a);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
newHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) later.getChildren().get(a);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
newHbox.setAlignment(hboxReference.getAlignment());
newHbox.getChildren().add(imageTicket);
}
}
HBox oldHbox = addElement(anchorPane, later.getId(), false);
oldHbox.setLayoutY(newHbox.getLayoutY() + newHbox.getPrefHeight());
oldHbox.setPrefHeight(hboxReference.getPrefHeight());
for (int r = 0; r < hboxReference.getChildren().size(); r++) {
Object object = hboxReference.getChildren().get(r);
if (object instanceof TextFieldTicket) {
TextFieldTicket tftAnterior = (TextFieldTicket) hboxReference.getChildren().get(r);
TextFieldTicket fieldTicket = addElementTextField(tftAnterior.getId(), tftAnterior.getText(), tftAnterior.isMultilineas(), tftAnterior.getLines(), tftAnterior.getColumnWidth(), tftAnterior.getAlignment(), tftAnterior.isEditable(), tftAnterior.getVariable(), tftAnterior.getFontName(), tftAnterior.getFontSize());
oldHbox.getChildren().add(fieldTicket);
} else if (object instanceof ImageViewTicket) {
ImageViewTicket ivAnterior = (ImageViewTicket) hboxReference.getChildren().get(r);
ImageViewTicket imageTicket = addElementImageView("", ivAnterior.getColumnWidth(), ivAnterior.getFitWidth(), ivAnterior.getFitHeight(), false, ivAnterior.getType());
imageTicket.setImage(new Image(new ByteArrayInputStream(ivAnterior.getUrl())));
imageTicket.setUrl(ivAnterior.getUrl());
oldHbox.setAlignment(hboxReference.getAlignment());
oldHbox.getChildren().add(imageTicket);
}
}
anchorPane.getChildren().set(i, newHbox);
anchorPane.getChildren().set(i + 1, oldHbox);
oldHbox.setStyle(style);
hboxReference = oldHbox;
break;
}
}
anchorPane.layout();
}
public void leftElementHBox() {
if (hboxReference != null) {
hboxReference.setAlignment(Pos.CENTER_LEFT);
}
}
private void centerElementHBox() {
if (hboxReference != null) {
hboxReference.setAlignment(Pos.CENTER);
}
}
private void rightElementHBox() {
if (hboxReference != null) {
hboxReference.setAlignment(Pos.CENTER_RIGHT);
}
}
private void loadSelectImage() {
if (hboxReference != null) {
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Importar una imagen");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Elija una imagen", "*.png", "*.jpg", "*.jpeg", "*.gif"));
selectFile = fileChooser.showOpenDialog(vbWindow.getScene().getWindow());
if (selectFile != null) {
selectFile = new File(selectFile.getAbsolutePath());
if (selectFile.getName().endsWith("png") || selectFile.getName().endsWith("jpg") || selectFile.getName().endsWith("jpeg") || selectFile.getName().endsWith("gif")) {
viewTicket.setImage(new Image(selectFile.toURI().toString()));
viewTicket.setSmooth(true);
viewTicket.setPreserveRatio(false);
viewTicket.setUrl(Tools.getImageBytes(selectFile));
//imageBytes = null;
} else {
Tools.AlertMessageWarning(vbWindow, "Mi Empresa", "No seleccionó un formato correcto de imagen.");
}
}
}
}
}
}
private void onEventPredeterminado() {
if (idTicket > 0) {
short option = Tools.AlertMessageConfirmation(vbWindow, "Ticket", "¿Está seguro de hacer prederteminado este modelo de ticket?");
if (option == 1) {
String result = TicketADO.ChangeDefaultState(idTicket, tipoTicket);
if (result.equalsIgnoreCase("updated")) {
Tools.AlertMessageInformation(vbWindow, "Ticket", "Se realizó los cambios correctamente.");
cbPredeterminado.setSelected(true);
cbPredeterminado.setText("SI");
switch (tipoTicket) {
case 1:
Session.TICKET_VENTA_ID = idTicket;
Session.TICKET_VENTA_RUTA = ruta;
break;
case 2:
Session.TICKET_COMPRA_ID = idTicket;
Session.TICKET_COMPRA_RUTA = ruta;
break;
case 5:
Session.TICKET_CORTE_CAJA_ID = idTicket;
Session.TICKET_CORTE_CAJA_RUTA = ruta;
break;
case 7:
Session.TICKET_PRE_VENTA_ID = idTicket;
Session.TICKET_PRE_VENTA_RUTA = ruta;
break;
case 8:
Session.TICKET_COTIZACION_ID = idTicket;
Session.TICKET_COTIZACION_RUTA = ruta;
break;
case 9:
Session.TICKET_CUENTA_POR_COBRAR_ID = idTicket;
Session.TICKET_CUENTA_POR_COBRAR_RUTA = ruta;
break;
case 10:
Session.TICKET_CUENTA_POR_PAGAR_ID = idTicket;
Session.TICKET_CUENTA_POR_PAGAR_RUTA = ruta;
break;
case 11:
Session.TICKET_GUIA_REMISION_ID = idTicket;
Session.TICKET_GUIA_REMISION_RUTA = ruta;
break;
case 12:
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_ID = idTicket;
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_RUTA = ruta;
break;
case 13:
Session.TICKET_PEDIDO_ID = idTicket;
Session.TICKET_PEDIDO_RUTA = ruta;
break;
case 14:
Session.TICKET_ORDEN_COMPRA_ID = idTicket;
Session.TICKET_ORDEN_COMPRA_RUTA = ruta;
break;
case 15:
Session.TICKET_NOTA_CREDITO_ID = idTicket;
Session.TICKET_NOTA_CREDITO_RUTA = ruta;
break;
default:
break;
}
} else {
Tools.AlertMessageError(vbWindow, "Ticket", result);
}
}
} else {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El modelo del ticket está en proceso de creación, busque en la lista para hacerlo prederteminado.");
}
}
private void onEventEliminar() {
if (idTicket != 0) {
short value = Tools.AlertMessageConfirmation(vbWindow, "Ticket", "¿Está seguro de continuar?");
if (value == 1) {
String result = TicketADO.DeleteTicket(idTicket);
if (result.equalsIgnoreCase("deleted")) {
Tools.AlertMessageConfirmation(vbWindow, "Ticket", "Se elemino correctamente el ticket.");
switch (tipoTicket) {
case 1:
Session.TICKET_VENTA_ID = 0;
Session.TICKET_VENTA_RUTA = "";
break;
case 2:
Session.TICKET_COMPRA_ID = 0;
Session.TICKET_COMPRA_RUTA = "";
break;
case 5:
Session.TICKET_CORTE_CAJA_ID = 0;
Session.TICKET_CORTE_CAJA_RUTA = "";
break;
case 7:
Session.TICKET_PRE_VENTA_ID = 0;
Session.TICKET_PRE_VENTA_RUTA = "";
break;
case 8:
Session.TICKET_COTIZACION_ID = 0;
Session.TICKET_COTIZACION_RUTA = "";
break;
case 9:
Session.TICKET_CUENTA_POR_COBRAR_ID = 0;
Session.TICKET_CUENTA_POR_COBRAR_RUTA = "";
break;
case 10:
Session.TICKET_CUENTA_POR_PAGAR_ID = 0;
Session.TICKET_CUENTA_POR_PAGAR_RUTA = "";
break;
case 11:
Session.TICKET_GUIA_REMISION_ID = 0;
Session.TICKET_GUIA_REMISION_RUTA = "";
break;
case 12:
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_ID = 0;
Session.TICKET_HISTORIAL_SALIDA_PRODUCTOS_RUTA = "";
break;
case 13:
Session.TICKET_PEDIDO_ID = 0;
Session.TICKET_PEDIDO_RUTA = "";
break;
case 14:
Session.TICKET_ORDEN_COMPRA_ID = 0;
Session.TICKET_ORDEN_COMPRA_RUTA = "";
break;
case 15:
Session.TICKET_NOTA_CREDITO_ID = 0;
Session.TICKET_NOTA_CREDITO_RUTA = "";
break;
default:
break;
}
clearPane();
} else if (result.equalsIgnoreCase("predeterminated")) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "El ticket es predeterminado, no puede eliminar por el momento.");
} else {
Tools.AlertMessageError(vbWindow, "Ticket", result);
}
}
}
}
private void onEventClonar() {
if (idTicket == 0) {
Tools.AlertMessageWarning(vbWindow, "Ticket", "No se puede clonar un ticket recien creado.");
return;
}
try {
fxPrincipalController.openFondoModal();
URL url = getClass().getResource(FilesRouters.FX_TICKET_CLONAR);
FXMLLoader fXMLLoader = WindowStage.LoaderWindow(url);
Parent parent = fXMLLoader.load(url.openStream());
//Controlller here
FxTicketClonarController controller = fXMLLoader.getController();
controller.setInitTicketController(this);
//
Stage stage = WindowStage.StageLoaderModal(parent, "Clonar formato", vbWindow.getScene().getWindow());
stage.setResizable(false);
stage.sizeToScene();
stage.setOnHiding(w -> fxPrincipalController.closeFondoModal());
stage.setOnShowing(w -> controller.loadComponents(idTicket));
stage.show();
} catch (IOException ex) {
System.out.println(ex.getLocalizedMessage());
}
}
@FXML
private void onKeyPressNuevo(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
nuevoTicket();
}
}
@FXML
private void onActionNuevo(ActionEvent event) {
nuevoTicket();
}
@FXML
private void onKeyPressEditar(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
editarTicket();
}
}
@FXML
private void onActionEditar(ActionEvent event) {
editarTicket();
}
@FXML
private void onKeyPressedSave(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
saveTicket();
}
}
@FXML
private void onActionSave(ActionEvent event) {
saveTicket();
}
@FXML
private void onKeyPressedClonar(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
onEventClonar();
}
}
@FXML
private void onActionClonar(ActionEvent event) {
onEventClonar();
}
@FXML
private void onActionEliminar(ActionEvent event) {
onEventEliminar();
}
@FXML
private void onKeyPressedEliminar(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
onEventEliminar();
}
}
@FXML
private void onKeyPressedPrint(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
openWindowImpresora();
}
}
@FXML
private void onActionPrint(ActionEvent event) {
openWindowImpresora();
}
@FXML
private void onMouseClickedEncabezadoAdd(MouseEvent event) {
generateElement(apEncabezado, "cb");
}
@FXML
private void onMouseClickedDetalleCabeceraAdd(MouseEvent event) {
generateElement(apDetalleCabecera, "dr");
}
@FXML
private void onMouseClickedPieAdd(MouseEvent event) {
generateElement(apPie, "cp");
}
@FXML
private void onActionAnchoColumna(ActionEvent event) {
actionAnchoColumnas();
}
@FXML
private void onKeyTypedAnchoColumna(KeyEvent event) {
char c = event.getCharacter().charAt(0);
if ((c < '0' || c > '9') && (c != '\b')) {
event.consume();
}
}
@FXML
private void onKeyPressedSearch(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
searchTicket();
}
}
@FXML
private void onActionSearch(ActionEvent event) {
searchTicket();
}
@FXML
private void onActionMultilinea(ActionEvent event) {
if (tfReference != null) {
if (!cbMultilinea.isSelected()) {
tfReference.setMultilineas(false);
tfReference.setLines((short) 0);
} else {
tfReference.setMultilineas(true);
tfReference.setLines((short) 1);
}
}
}
@FXML
private void onKeyPressedClear(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
clearPane();
}
}
@FXML
private void onActionClear(ActionEvent event) {
clearPane();
}
@FXML
private void onKeyPressedImage(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
loadSelectImage();
}
}
@FXML
private void onActionImage(ActionEvent event) {
loadSelectImage();
}
@FXML
private void onKeyPressedMoveUp(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
if (hboxReference != null) {
moveUpHBox((AnchorPane) hboxReference.getParent());
}
}
}
@FXML
private void onActionMoveUp(ActionEvent event) {
if (hboxReference != null) {
moveUpHBox((AnchorPane) hboxReference.getParent());
}
}
@FXML
private void onKeyPressedMoveDown(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
if (hboxReference != null) {
moveDownHBox((AnchorPane) hboxReference.getParent());
}
}
}
@FXML
private void onActionMoveDown(ActionEvent event) {
if (hboxReference != null) {
moveDownHBox((AnchorPane) hboxReference.getParent());
}
}
@FXML
private void onKeyPressedLeft(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
leftElementHBox();
}
}
@FXML
private void onActionLeft(ActionEvent event) {
leftElementHBox();
}
@FXML
private void onKeyPressedCenter(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
centerElementHBox();
}
}
@FXML
private void onActionCenter(ActionEvent event) {
centerElementHBox();
}
@FXML
private void onKeyPressedRight(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
rightElementHBox();
}
}
@FXML
private void onActionRight(ActionEvent event) {
rightElementHBox();
}
@FXML
private void onKeyPressedPredeterminado(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
onEventPredeterminado();
}
}
@FXML
private void onActionPredeterminado(ActionEvent event) {
onEventPredeterminado();
}
@FXML
private void onActionFuente(ActionEvent event) {
if (cbFuente.getSelectionModel().getSelectedIndex() >= 0) {
if (tfReference != null) {
switch (cbFuente.getSelectionModel().getSelectedIndex()) {
case 0:
tfReference.setFontName("Consola");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
break;
case 1:
tfReference.setFontName("Roboto Regular");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
break;
default:
tfReference.setFontName("Roboto Bold");
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
break;
}
HBox hBox = (HBox) tfReference.getParent();
for (int i = 0; i < hBox.getChildren().size(); i++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(i);
field.setFontName(tfReference.getFontName());
field.setStyle("-fx-background-color: " + field.getFontBackground() + ";-fx-text-fill:" + field.getFontColor() + ";-fx-font-family:" + (field.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : field.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
}
}
}
}
@FXML
private void onSize(ActionEvent event) {
if (cbFuente.getSelectionModel().getSelectedIndex() >= 0) {
if (tfReference != null) {
tfReference.setFontSize(cbSize.getSelectionModel().getSelectedItem());
tfReference.setStyle("-fx-background-color: " + tfReference.getFontBackground() + ";-fx-text-fill:" + tfReference.getFontColor() + ";-fx-font-family:" + (tfReference.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : tfReference.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + tfReference.getFontSize() + ";");
HBox hBox = (HBox) tfReference.getParent();
for (int i = 0; i < hBox.getChildren().size(); i++) {
TextFieldTicket field = (TextFieldTicket) hBox.getChildren().get(i);
field.setFontSize(cbSize.getSelectionModel().getSelectedItem());
field.setStyle("-fx-background-color: " + field.getFontBackground() + ";-fx-text-fill:" + field.getFontColor() + ";-fx-font-family:" + (field.getFontName().equalsIgnoreCase("Consola") ? "Monospace" : field.getFontName().equalsIgnoreCase("Roboto Regular") ? "Roboto" : "Roboto Bold") + ";-fx-font-size:" + field.getFontSize() + ";");
}
}
}
}
@FXML
private void onActionAncho(ActionEvent event) {
if (hboxReference != null) {
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
double oldWidth = viewTicket.getFitWidth();
viewTicket.setFitWidth(Tools.isNumeric(txtAncho.getText().trim()) && Double.parseDouble(txtAncho.getText().trim()) > 0 ? Double.parseDouble(txtAncho.getText()) : oldWidth);
}
}
}
}
@FXML
private void onKeyTypedAncho(KeyEvent event) {
char c = event.getCharacter().charAt(0);
if ((c < '0' || c > '9') && (c != '\b')) {
event.consume();
}
}
@FXML
private void onActionAlto(ActionEvent event) {
if (hboxReference != null) {
if (hboxReference.getChildren().size() == 1) {
Object object = hboxReference.getChildren().get(0);
if (object instanceof ImageViewTicket) {
ImageViewTicket viewTicket = (ImageViewTicket) hboxReference.getChildren().get(0);
double oldHeight = viewTicket.getFitHeight();
viewTicket.setFitHeight(Tools.isNumeric(txtAlto.getText().trim()) && Double.parseDouble(txtAlto.getText().trim()) > 0 ? Double.parseDouble(txtAlto.getText()) : oldHeight);
hboxReference.setPrefHeight(viewTicket.getFitHeight());
double yPosBefero = 0;
AnchorPane apDady = (AnchorPane) hboxReference.getParent();
for (int p = 0; p < apDady.getChildren().size(); p++) {
HBox hb = (HBox) apDady.getChildren().get(p);
if (p == 0) {
double heightNow = hb.getPrefHeight();
hb.setLayoutY(p * heightNow);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
} else {
hb.setLayoutY(yPosBefero);
yPosBefero = hb.getLayoutY() + hb.getPrefHeight();
}
}
apDady.layout();
}
}
}
}
@FXML
private void onKeyTypedAlto(KeyEvent event) {
char c = event.getCharacter().charAt(0);
if ((c < '0' || c > '9') && (c != '\b')) {
event.consume();
}
}
public AnchorPane getHbEncabezado() {
return apEncabezado;
}
public AnchorPane getHbDetalleCabecera() {
return apDetalleCabecera;
}
public AnchorPane getHbPie() {
return apPie;
}
public short getSheetWidth() {
return sheetWidth;
}
public void setContent(FxPrincipalController fxPrincipalController) {
this.fxPrincipalController = fxPrincipalController;
}
}
| 100,906 | 0.53359 | 0.529456 | 2,030 | 48.694088 | 48.959435 | 510 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.825616 | false | false | 8 |
65add21f181611e73d22d768f61fb88471b98b1c | 39,676,907,888,507 | 290f10f2878ee1ca8880e5e58815d07c4dbedc54 | /Pronto/app/src/main/java/com/redeyesoftware/pronto/BluetoothActivity.java | eed8cd99085771c5621cbf018df3cda23eea4304 | [] | no_license | brenton311/se101-final-project | https://github.com/brenton311/se101-final-project | a956029181a641b36dd9253fc4b1ebc3dc24c6b1 | 354abdcd926934dfaa3f48fd999c9c582c62e302 | refs/heads/master | "2021-01-19T21:54:45.665000" | "2018-09-20T02:39:30" | "2018-09-20T02:39:30" | 72,122,386 | 0 | 0 | null | false | "2016-11-18T19:58:00" | "2016-10-27T15:33:12" | "2016-11-18T19:52:48" | "2016-11-18T19:58:00" | 156 | 0 | 0 | 0 | Python | null | null | package com.redeyesoftware.pronto;
/**
* Created by George on 20/11/2016.
*/
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BluetoothActivity extends AppCompatActivity {
private static BluetoothActivity me;
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
me = this;
try {
findBT();
openBT();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void refresh() {
SharedPreferences prefs = getSharedPreferences("PrefsFile", MODE_PRIVATE);
String token = prefs.getString("accessToken", "ERROR: DID NOT READ");
NetworkingUtility.getComments("/inbox/feed/", token, true, 30, 20, "1150546131643551","", "fillTiva", new String[]{
"author_id", "msg_id", "text", "likes", "bookmarks"
});
}
public static void sendCommentsToTiva() {
try {
JSONArray jsonCommentArray = new JSONArray();
for (int i = 0; i < NetworkingUtility.comments.length; i++) {
jsonCommentArray.put(createJSONforComment(i));
}
me.sendData(jsonCommentArray.toString());
} catch (Exception ex) {
me.showMessage("Bluetooth Connection Failed");
}
}
private static JSONObject createJSONforComment(int index) {
boolean iLiked = NetworkingUtility.comments[index][3].indexOf(LoginActivity.getId()) != -1;
boolean iBookmarked = NetworkingUtility.comments[index][4].indexOf(LoginActivity.getId()) != -1;
JSONObject comment = new JSONObject();
try {
comment.put("author_id", NetworkingUtility.comments[index][0]);
comment.put("msg_id", NetworkingUtility.comments[index][1]);
comment.put("text", NetworkingUtility.comments[index][2]);
comment.put("i_liked", iLiked);
comment.put("i_bookmarked", iBookmarked);
} catch (JSONException e) {
e.printStackTrace();
}
return comment;
}
void findBT() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
showMessage("This device does not support Bluetooth");
}
//Todo: fix the bug with bluetooth disabled
if(!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for(BluetoothDevice device : pairedDevices) {
if(device.getName().equals("HC-05")) {
mmDevice = device;
showMessage("Pronto Receiver Found");
break;
}
}
}
}
void openBT() throws IOException {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
refresh();
showMessage("Bluetooth Connection Opened");
}
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++) {
byte b = packetBytes[i];
if(b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
Log.d("Debug:", "Message received from bluetooth: " + data);
//note need to not include last chat when getting token because \n is included at end of data
SharedPreferences prefs = getSharedPreferences("PrefsFile", MODE_PRIVATE);
String token = prefs.getString("accessToken", "ERROR: DID NOT READ");
if (data.substring(0,4).equals("LIKE")) {
NetworkingUtility.post("/msg/like/", new String[]{"access_token","msg_id"}, new String[]{token,data.substring(5,data.length()-1)});
} else if (data.substring(0,4).equals("BKMK")) {
NetworkingUtility.getComments("/inbox/feed/", token, true, 1, 1, "1150546131643551",data.substring(5,data.length()-1), "updateBookmarkFromBluetooth", new String[]{
"author_id", "msg_id", "text", "timestamp", "likes", "bookmarks", "attachments"
});
NetworkingUtility.post("/msg/bookmark/", new String[]{"access_token","msg_id"}, new String[]{token,data.substring(5,data.length()-1)});
} else if (data.substring(0,4).equals("DISL")) {
NetworkingUtility.post("/msg/dislike/", new String[]{"access_token", "msg_id"}, new String[]{token,data.substring(5,data.length()-1)});
}
handler.post(new Runnable() {
public void run() {
showMessage(data);
}
});
}
else {
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData(String msg) throws Exception {
msg += "\n";
mmOutputStream.write(msg.getBytes());
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
}
private void showMessage(String theMsg) {
// Toast msg = Toast.makeText(getBaseContext(), theMsg, (Toast.LENGTH_SHORT));
// msg.show();
}
@Override
protected void onDestroy() {
super.onDestroy();
MainPage.updateFragments();
try {
sendData("CMD:Finished");
} catch (Exception ex) {
me.showMessage("Bluetooth Connection Failed");
}
try {
closeBT();
}
catch (IOException ex) { }
}
public static void updateBookmarkFromBluetooth() {
ArrayList<SerializableBookmark> bookmarkList = new ArrayList<SerializableBookmark>();
File bookmarksFile = new File(me.getFilesDir().getPath().toString() + "/SavedProntoBookmarks.txt");
if (bookmarksFile.exists()) {
Log.d("Debug", "comment found file");
try {
FileInputStream fileIn = new FileInputStream(bookmarksFile);
ObjectInputStream in = new ObjectInputStream(fileIn);
bookmarkList = (ArrayList<SerializableBookmark>) in.readObject();
//Log.i("palval", "dir.exists()");
in.close();
fileIn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("Debug", "comment did not find file");
try {
bookmarksFile.createNewFile(); // if file already exists will do nothing
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String date = TimeStampConverter.getDate(Long.parseLong(NetworkingUtility.comments[0][3]));
boolean iLiked = NetworkingUtility.comments[0][4].indexOf(LoginActivity.getId()) != -1;
boolean iBookmarked = NetworkingUtility.comments[0][5].indexOf(LoginActivity.getId()) != -1;
int numLikes = NetworkingUtility.comments[0][4].length() - NetworkingUtility.comments[0][4].replace(",", "").length();
int numBookmarks = NetworkingUtility.comments[0][5].length() - NetworkingUtility.comments[0][5].replace(",", "").length();
if (numLikes>0) numLikes++;
if (numBookmarks>0) numBookmarks++;
if (numLikes==0 && NetworkingUtility.comments[0][4].length()>4) numLikes=1;
if (numBookmarks==0 && NetworkingUtility.comments[0][5].length()>4) numBookmarks=1;
if (iBookmarked) {//delete
for (int i=0; i<bookmarkList.size();i++) {
if(bookmarkList.get(i).getMessageID().equals(NetworkingUtility.comments[0][1])) {
bookmarkList.remove(i);
}
}
} else {//create
SerializableBookmark newBookmark = new SerializableBookmark(NetworkingUtility.comments[0][1], NetworkingUtility.comments[0][2], NetworkingUtility.comments[0][0], date, numLikes, iLiked, numBookmarks+1, NetworkingUtility.comments[0][6]);
bookmarkList.add(newBookmark);
}
try {
FileOutputStream fileOut = new FileOutputStream(bookmarksFile);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(bookmarkList);//this is only possible becuase SerializableBookmark implements Serializable
out.close();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("Debug", "Bookmark successfully added/deleted");
}
} | UTF-8 | Java | 12,427 | java | BluetoothActivity.java | Java | [
{
"context": "kage com.redeyesoftware.pronto;\n\n/**\n * Created by George on 20/11/2016.\n */\n\nimport android.app.Activity;\n",
"end": 60,
"score": 0.9991168975830078,
"start": 54,
"tag": "NAME",
"value": "George"
}
] | null | [] | package com.redeyesoftware.pronto;
/**
* Created by George on 20/11/2016.
*/
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BluetoothActivity extends AppCompatActivity {
private static BluetoothActivity me;
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
me = this;
try {
findBT();
openBT();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void refresh() {
SharedPreferences prefs = getSharedPreferences("PrefsFile", MODE_PRIVATE);
String token = prefs.getString("accessToken", "ERROR: DID NOT READ");
NetworkingUtility.getComments("/inbox/feed/", token, true, 30, 20, "1150546131643551","", "fillTiva", new String[]{
"author_id", "msg_id", "text", "likes", "bookmarks"
});
}
public static void sendCommentsToTiva() {
try {
JSONArray jsonCommentArray = new JSONArray();
for (int i = 0; i < NetworkingUtility.comments.length; i++) {
jsonCommentArray.put(createJSONforComment(i));
}
me.sendData(jsonCommentArray.toString());
} catch (Exception ex) {
me.showMessage("Bluetooth Connection Failed");
}
}
private static JSONObject createJSONforComment(int index) {
boolean iLiked = NetworkingUtility.comments[index][3].indexOf(LoginActivity.getId()) != -1;
boolean iBookmarked = NetworkingUtility.comments[index][4].indexOf(LoginActivity.getId()) != -1;
JSONObject comment = new JSONObject();
try {
comment.put("author_id", NetworkingUtility.comments[index][0]);
comment.put("msg_id", NetworkingUtility.comments[index][1]);
comment.put("text", NetworkingUtility.comments[index][2]);
comment.put("i_liked", iLiked);
comment.put("i_bookmarked", iBookmarked);
} catch (JSONException e) {
e.printStackTrace();
}
return comment;
}
void findBT() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null) {
showMessage("This device does not support Bluetooth");
}
//Todo: fix the bug with bluetooth disabled
if(!mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0) {
for(BluetoothDevice device : pairedDevices) {
if(device.getName().equals("HC-05")) {
mmDevice = device;
showMessage("Pronto Receiver Found");
break;
}
}
}
}
void openBT() throws IOException {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard //SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
refresh();
showMessage("Bluetooth Connection Opened");
}
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++) {
byte b = packetBytes[i];
if(b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
Log.d("Debug:", "Message received from bluetooth: " + data);
//note need to not include last chat when getting token because \n is included at end of data
SharedPreferences prefs = getSharedPreferences("PrefsFile", MODE_PRIVATE);
String token = prefs.getString("accessToken", "ERROR: DID NOT READ");
if (data.substring(0,4).equals("LIKE")) {
NetworkingUtility.post("/msg/like/", new String[]{"access_token","msg_id"}, new String[]{token,data.substring(5,data.length()-1)});
} else if (data.substring(0,4).equals("BKMK")) {
NetworkingUtility.getComments("/inbox/feed/", token, true, 1, 1, "1150546131643551",data.substring(5,data.length()-1), "updateBookmarkFromBluetooth", new String[]{
"author_id", "msg_id", "text", "timestamp", "likes", "bookmarks", "attachments"
});
NetworkingUtility.post("/msg/bookmark/", new String[]{"access_token","msg_id"}, new String[]{token,data.substring(5,data.length()-1)});
} else if (data.substring(0,4).equals("DISL")) {
NetworkingUtility.post("/msg/dislike/", new String[]{"access_token", "msg_id"}, new String[]{token,data.substring(5,data.length()-1)});
}
handler.post(new Runnable() {
public void run() {
showMessage(data);
}
});
}
else {
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData(String msg) throws Exception {
msg += "\n";
mmOutputStream.write(msg.getBytes());
}
void closeBT() throws IOException {
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
}
private void showMessage(String theMsg) {
// Toast msg = Toast.makeText(getBaseContext(), theMsg, (Toast.LENGTH_SHORT));
// msg.show();
}
@Override
protected void onDestroy() {
super.onDestroy();
MainPage.updateFragments();
try {
sendData("CMD:Finished");
} catch (Exception ex) {
me.showMessage("Bluetooth Connection Failed");
}
try {
closeBT();
}
catch (IOException ex) { }
}
public static void updateBookmarkFromBluetooth() {
ArrayList<SerializableBookmark> bookmarkList = new ArrayList<SerializableBookmark>();
File bookmarksFile = new File(me.getFilesDir().getPath().toString() + "/SavedProntoBookmarks.txt");
if (bookmarksFile.exists()) {
Log.d("Debug", "comment found file");
try {
FileInputStream fileIn = new FileInputStream(bookmarksFile);
ObjectInputStream in = new ObjectInputStream(fileIn);
bookmarkList = (ArrayList<SerializableBookmark>) in.readObject();
//Log.i("palval", "dir.exists()");
in.close();
fileIn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d("Debug", "comment did not find file");
try {
bookmarksFile.createNewFile(); // if file already exists will do nothing
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String date = TimeStampConverter.getDate(Long.parseLong(NetworkingUtility.comments[0][3]));
boolean iLiked = NetworkingUtility.comments[0][4].indexOf(LoginActivity.getId()) != -1;
boolean iBookmarked = NetworkingUtility.comments[0][5].indexOf(LoginActivity.getId()) != -1;
int numLikes = NetworkingUtility.comments[0][4].length() - NetworkingUtility.comments[0][4].replace(",", "").length();
int numBookmarks = NetworkingUtility.comments[0][5].length() - NetworkingUtility.comments[0][5].replace(",", "").length();
if (numLikes>0) numLikes++;
if (numBookmarks>0) numBookmarks++;
if (numLikes==0 && NetworkingUtility.comments[0][4].length()>4) numLikes=1;
if (numBookmarks==0 && NetworkingUtility.comments[0][5].length()>4) numBookmarks=1;
if (iBookmarked) {//delete
for (int i=0; i<bookmarkList.size();i++) {
if(bookmarkList.get(i).getMessageID().equals(NetworkingUtility.comments[0][1])) {
bookmarkList.remove(i);
}
}
} else {//create
SerializableBookmark newBookmark = new SerializableBookmark(NetworkingUtility.comments[0][1], NetworkingUtility.comments[0][2], NetworkingUtility.comments[0][0], date, numLikes, iLiked, numBookmarks+1, NetworkingUtility.comments[0][6]);
bookmarkList.add(newBookmark);
}
try {
FileOutputStream fileOut = new FileOutputStream(bookmarksFile);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(bookmarkList);//this is only possible becuase SerializableBookmark implements Serializable
out.close();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("Debug", "Bookmark successfully added/deleted");
}
} | 12,427 | 0.565382 | 0.55307 | 306 | 39.61438 | 35.700024 | 248 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.794118 | false | false | 8 |
1f9961cdfa719ebbaad0553895e8a24e35a414cf | 7,550,552,506,691 | 59181cfbcc040e2f3c5c9d6e6318a648fc3b25a8 | /src/gr/teic/ie/oop2/paint/MyBoundedShape.java | c8d2f37d505bd518d653f4f62b5a7cdef464be9d | [] | no_license | mernabobakr/finalprojecectOOP | https://github.com/mernabobakr/finalprojecectOOP | a60807b75d6def2457f53aeed1c1fa45508e4d97 | 949a99bea16c5e945c3f2f85e5bdeb315e5efe38 | refs/heads/master | "2020-12-12T13:57:46.639000" | "2020-05-17T01:42:40" | "2020-05-17T01:42:40" | 234,143,952 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gr.teic.ie.oop2.paint;
import java.awt.Color;
import java.awt.Graphics;
abstract class MyBoundedShape implements MyShape {
private int x1, y1, x2, y2; //coordinates of shape
private Color color; // color of shape
private boolean fill; //boolean variable that determines whether the shape is filled or not
public MyBoundedShape() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
color = Color.RED;
fill = false;
}
public MyBoundedShape(int x1, int y1, int x2, int y2, Color color, boolean fill) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
this.fill = fill;
}
//Mutator methods
/**
* set fill
*/
public void setFill(boolean fill) {
this.fill = fill;
}
/**
* Mutator method for x1
*/
public void setX1(int x1) {
this.x1 = x1;
}
/**
* Mutator method for y1
*/
public void setY1(int y1) {
this.y1 = y1;
}
/**
* Mutator method for x2
*/
public void setX2(int x2) {
this.x2 = x2;
}
/**
* Mutator method for y2
*/
public void setY2(int y2) {
this.y2 = y2;
}
/**
* Mutator method for color
*/
public void setColor(Color color) {
this.color = color;
}
/**
* Mutator method for text
*/
/**
* Accessor method for x1
*/
public int getX1() {
return x1;
}
/**
* Accessor method for y1
*/
public int getY1() {
return y1;
}
/**
* Accessor method for x2
*/
public int getX2() {
return x2;
}
/**
* Accessor method for y2
*/
public int getY2() {
return y2;
}
/**
* Accessor method for color
*/
public Color getColor() {
return color;
}
/**
* Accessor method for text
*/
/**
* gets the upper left x
*/
public int getUpperLeftX() {
return Math.min(getX1(), getX2());
}
/**
* gets the upper left y
*/
public int getUpperLeftY() {
return Math.min(getY1(), getY2());
}
/**
* gets width
*/
public int getWidth() {
return Math.abs(getX1() - getX2());
}
//Accessor methods
/**
* gets height
*/
public int getHeight() {
return Math.abs(getY1() - getY2());
}
/**
* return fill
*/
public boolean getFill() {
return fill;
}
/**
* Abstract method for drawing the shape that must be overriden
*/
abstract public void draw(Graphics g);
} // end class MyBoundedShape
| UTF-8 | Java | 2,749 | java | MyBoundedShape.java | Java | [] | null | [] | package gr.teic.ie.oop2.paint;
import java.awt.Color;
import java.awt.Graphics;
abstract class MyBoundedShape implements MyShape {
private int x1, y1, x2, y2; //coordinates of shape
private Color color; // color of shape
private boolean fill; //boolean variable that determines whether the shape is filled or not
public MyBoundedShape() {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
color = Color.RED;
fill = false;
}
public MyBoundedShape(int x1, int y1, int x2, int y2, Color color, boolean fill) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
this.fill = fill;
}
//Mutator methods
/**
* set fill
*/
public void setFill(boolean fill) {
this.fill = fill;
}
/**
* Mutator method for x1
*/
public void setX1(int x1) {
this.x1 = x1;
}
/**
* Mutator method for y1
*/
public void setY1(int y1) {
this.y1 = y1;
}
/**
* Mutator method for x2
*/
public void setX2(int x2) {
this.x2 = x2;
}
/**
* Mutator method for y2
*/
public void setY2(int y2) {
this.y2 = y2;
}
/**
* Mutator method for color
*/
public void setColor(Color color) {
this.color = color;
}
/**
* Mutator method for text
*/
/**
* Accessor method for x1
*/
public int getX1() {
return x1;
}
/**
* Accessor method for y1
*/
public int getY1() {
return y1;
}
/**
* Accessor method for x2
*/
public int getX2() {
return x2;
}
/**
* Accessor method for y2
*/
public int getY2() {
return y2;
}
/**
* Accessor method for color
*/
public Color getColor() {
return color;
}
/**
* Accessor method for text
*/
/**
* gets the upper left x
*/
public int getUpperLeftX() {
return Math.min(getX1(), getX2());
}
/**
* gets the upper left y
*/
public int getUpperLeftY() {
return Math.min(getY1(), getY2());
}
/**
* gets width
*/
public int getWidth() {
return Math.abs(getX1() - getX2());
}
//Accessor methods
/**
* gets height
*/
public int getHeight() {
return Math.abs(getY1() - getY2());
}
/**
* return fill
*/
public boolean getFill() {
return fill;
}
/**
* Abstract method for drawing the shape that must be overriden
*/
abstract public void draw(Graphics g);
} // end class MyBoundedShape
| 2,749 | 0.497636 | 0.473991 | 159 | 16.289309 | 15.820672 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.283019 | false | false | 8 |
d4ce22b975dbb4d0b36f06eee27100a6ad00e761 | 15,453,292,346,233 | eb560ae74925e9b04e0ef4ce0e638ef8d22130f4 | /src/main/java/com/diverhome/controller/employee/EmployeeController.java | ba9ad72fde13eea0d7551dbbd09e4aea3096b9b2 | [] | no_license | ananchao/diverhomemanage | https://github.com/ananchao/diverhomemanage | f2e61d37ab84f73bbee21a7f82250e9b12de52fc | 2a5c6ded655a03541f833a11a8a1f9472c7a43fd | refs/heads/master | "2021-01-20T01:04:34.817000" | "2017-04-24T09:18:39" | "2017-04-24T09:18:39" | 89,219,752 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.diverhome.controller.employee;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.diverhome.controller.base.BaseController;
import com.diverhome.entity.PageData;
import com.diverhome.entity.ResponseEntity;
import com.diverhome.entity.TbEmployee;
import com.diverhome.service.employee.EmployeeCoachService;
import com.diverhome.util.Constant;
import com.diverhome.util.StringUtil;
/**
* ***************************************************************
* <p>Filename: EmployeeController.java
* <p>Description:
* <p>
* <p>Copyright: Copyright (c)2016
* <p>Company: njits
* <p>Create at: 2017年4月4日 下午8:28:56
* <p>
* <p>Modification History:
* <p>Date Author Version Description
* <p>------------------------------------------------------------------
* <p>2017年4月4日 anchao 1.0 first Version
* <p>------------------------------------------------------------------
********************************************************************
*/
@Controller
@RequestMapping("/manage")
public class EmployeeController extends BaseController {
@Autowired
private EmployeeCoachService employeeCoachService;
/**
*
* @Title: getEmployeeList
* @Description: 根据类型查询员工信息
* @return
* @throws
*/
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity getEmployeeList() {
ResponseEntity responseEntity = new ResponseEntity();
try {
PageData pd = this.getPageData();
// 员工类型 0 潜水教练 1 其他员工
String type = StringUtil.nvl(pd.getString("type"), "0", 2);
ArrayList<TbEmployee> employeeList = employeeCoachService.getEmployeeList(type);
responseEntity.setStatus(Constant.SUCCESS);
responseEntity.setData(employeeList);
} catch (Exception e) {
//设置返回信息
responseEntity.setStatus(Constant.BUSINESS_ERROR);
responseEntity.setMessage(Constant.EXCEPTION_MSG_GETEMPLOYEECOACHLIST);
logger.error(e.getMessage(), e);
}
return responseEntity;
}
}
| UTF-8 | Java | 2,430 | java | EmployeeController.java | Java | [] | null | [] | package com.diverhome.controller.employee;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.diverhome.controller.base.BaseController;
import com.diverhome.entity.PageData;
import com.diverhome.entity.ResponseEntity;
import com.diverhome.entity.TbEmployee;
import com.diverhome.service.employee.EmployeeCoachService;
import com.diverhome.util.Constant;
import com.diverhome.util.StringUtil;
/**
* ***************************************************************
* <p>Filename: EmployeeController.java
* <p>Description:
* <p>
* <p>Copyright: Copyright (c)2016
* <p>Company: njits
* <p>Create at: 2017年4月4日 下午8:28:56
* <p>
* <p>Modification History:
* <p>Date Author Version Description
* <p>------------------------------------------------------------------
* <p>2017年4月4日 anchao 1.0 first Version
* <p>------------------------------------------------------------------
********************************************************************
*/
@Controller
@RequestMapping("/manage")
public class EmployeeController extends BaseController {
@Autowired
private EmployeeCoachService employeeCoachService;
/**
*
* @Title: getEmployeeList
* @Description: 根据类型查询员工信息
* @return
* @throws
*/
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity getEmployeeList() {
ResponseEntity responseEntity = new ResponseEntity();
try {
PageData pd = this.getPageData();
// 员工类型 0 潜水教练 1 其他员工
String type = StringUtil.nvl(pd.getString("type"), "0", 2);
ArrayList<TbEmployee> employeeList = employeeCoachService.getEmployeeList(type);
responseEntity.setStatus(Constant.SUCCESS);
responseEntity.setData(employeeList);
} catch (Exception e) {
//设置返回信息
responseEntity.setStatus(Constant.BUSINESS_ERROR);
responseEntity.setMessage(Constant.EXCEPTION_MSG_GETEMPLOYEECOACHLIST);
logger.error(e.getMessage(), e);
}
return responseEntity;
}
}
| 2,430 | 0.638677 | 0.627226 | 68 | 32.676472 | 24.02293 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.220588 | false | false | 8 |
f29e5c641d96a4fd0b9745cd3fe9ac5aed0ee05d | 5,720,896,462,701 | 23d946bb0da006f45cfa224669dc210ff9cfc99a | /src/test/java/com/barchart/missive/value/TestValueMissive.java | 439785660a6d783007c4e7aca463ec5a26716689 | [
"BSD-3-Clause"
] | permissive | GLitchfield/barchart-missive-1 | https://github.com/GLitchfield/barchart-missive-1 | 702493edc5169d8bae972a3689c31e175e694092 | d3ab607cf6140cc5c63f4bf201199395494d7e67 | refs/heads/master | "2021-01-15T10:30:52.903000" | "2015-10-13T20:57:05" | "2015-10-13T20:57:05" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.barchart.missive.value;
import static org.junit.Assert.*;
import static com.barchart.missive.value.TestSpec.*;
import org.junit.Test;
public class TestValueMissive {
@Test
public void test() {
final ExampleMissive examp = ValueMissive.build(ExampleMissive.class);
examp.set(INT_1, 1);
examp.set(INT_2, 2);
examp.set(INT_3, 3);
examp.set(LONG_1, 4l);
examp.set(LONG_2, 5l);
examp.set(LONG_3, 6l);
assertTrue(examp.get(INT_1) == 1);
assertTrue(examp.get(INT_2) == 2);
assertTrue(examp.get(INT_3) == 3);
assertTrue(examp.get(LONG_1) == 4);
assertTrue(examp.get(LONG_2) == 5);
assertTrue(examp.get(LONG_3) == 6);
final ExampleMissive thatMiss = ValueMissive.build(ExampleMissive.class);
thatMiss.set(INT_1, 3);
thatMiss.set(INT_2, 2);
thatMiss.set(INT_3, 1);
final Functor<ExampleMissive, ExampleMissive> exAdd = examp.addInts();
exAdd.run(thatMiss);
assertTrue(examp.get(INT_1) == 4);
assertTrue(examp.get(INT_2) == 4);
assertTrue(examp.get(INT_3) == 4);
}
}
| UTF-8 | Java | 1,057 | java | TestValueMissive.java | Java | [] | null | [] | package com.barchart.missive.value;
import static org.junit.Assert.*;
import static com.barchart.missive.value.TestSpec.*;
import org.junit.Test;
public class TestValueMissive {
@Test
public void test() {
final ExampleMissive examp = ValueMissive.build(ExampleMissive.class);
examp.set(INT_1, 1);
examp.set(INT_2, 2);
examp.set(INT_3, 3);
examp.set(LONG_1, 4l);
examp.set(LONG_2, 5l);
examp.set(LONG_3, 6l);
assertTrue(examp.get(INT_1) == 1);
assertTrue(examp.get(INT_2) == 2);
assertTrue(examp.get(INT_3) == 3);
assertTrue(examp.get(LONG_1) == 4);
assertTrue(examp.get(LONG_2) == 5);
assertTrue(examp.get(LONG_3) == 6);
final ExampleMissive thatMiss = ValueMissive.build(ExampleMissive.class);
thatMiss.set(INT_1, 3);
thatMiss.set(INT_2, 2);
thatMiss.set(INT_3, 1);
final Functor<ExampleMissive, ExampleMissive> exAdd = examp.addInts();
exAdd.run(thatMiss);
assertTrue(examp.get(INT_1) == 4);
assertTrue(examp.get(INT_2) == 4);
assertTrue(examp.get(INT_3) == 4);
}
}
| 1,057 | 0.662252 | 0.628193 | 49 | 20.571428 | 20.034664 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.183673 | false | false | 8 |
01520336093703edc64acb1f231a1c187f1d0156 | 32,598,801,788,433 | ddc60af1649b97d53e515bdebd68d08b8a029267 | /src/WarmUp9_1.java | 535d7dcd3649c00c8a2c5474103515e2f5115088 | [] | no_license | kchung1068/WarmUp9_1 | https://github.com/kchung1068/WarmUp9_1 | 7246799d2c5ab487a60f33827faac039a2b646da | 5b37c3f1abe1ab08e98a015c5d7ab49fbe89bb91 | refs/heads/master | "2023-02-25T12:49:45.957000" | "2021-01-28T21:02:41" | "2021-01-28T21:02:41" | 333,924,719 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Write the class RightTriangle. The fields of the class
* are integers which represent the sides of the triangle.
* Name the fields a,b and c where a and b are the legs of
* the triangle and c is the hypotenuse. Each of the fields
* should be private since it makes no sense for the side
* lengths to be negative. Write three constructors. The first
* is a default (no argument) constructor in which each field
* is initialized to an appropriate value. Second, write an
* argument constructor which receives all three sides of
* the triangle in order. Again, make sure they are appropriate
* values. The third, write a copy constructor. Then write the
* setters and getters for each field.
*/
public class WarmUp9_1 {
public static void main(String args[]){
RightTriangle r = new RightTriangle();
RightTriangle s = new RightTriangle(3,4,5);
RightTriangle t = new RightTriangle(s);
t.setA(5);
System.out.println( "A = " + t.getA() );
t.setB(12);
System.out.println( "B = " + t.getB() );
t.setC(13);
System.out.println( "C = " + t.getC() );
}
}
| UTF-8 | Java | 1,088 | java | WarmUp9_1.java | Java | [] | null | [] | /* Write the class RightTriangle. The fields of the class
* are integers which represent the sides of the triangle.
* Name the fields a,b and c where a and b are the legs of
* the triangle and c is the hypotenuse. Each of the fields
* should be private since it makes no sense for the side
* lengths to be negative. Write three constructors. The first
* is a default (no argument) constructor in which each field
* is initialized to an appropriate value. Second, write an
* argument constructor which receives all three sides of
* the triangle in order. Again, make sure they are appropriate
* values. The third, write a copy constructor. Then write the
* setters and getters for each field.
*/
public class WarmUp9_1 {
public static void main(String args[]){
RightTriangle r = new RightTriangle();
RightTriangle s = new RightTriangle(3,4,5);
RightTriangle t = new RightTriangle(s);
t.setA(5);
System.out.println( "A = " + t.getA() );
t.setB(12);
System.out.println( "B = " + t.getB() );
t.setC(13);
System.out.println( "C = " + t.getC() );
}
}
| 1,088 | 0.702206 | 0.693015 | 29 | 36.517242 | 22.824097 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.448276 | false | false | 8 |
4eb51e1ff78bebbbea203d8ae5e7e5b0b4df9943 | 13,984,413,583,576 | 82521aef3b7bb4655d369cd7631a6c57b7ff8dd6 | /src/main/java/com/xiaohao/cms/model/AdminExample.java | b4acbd723b8065daa4dffe99b98cc7c69a6f270a | [] | no_license | amdiaosi/try-ssi | https://github.com/amdiaosi/try-ssi | 1742ef6d8302b8d77c3247af38286589825a8793 | a43070072b1833b8f7f6388da6a7622ebb3a2319 | refs/heads/master | "2020-05-31T07:26:37.502000" | "2014-10-14T07:25:59" | "2014-10-14T07:25:59" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiaohao.cms.model;
import java.util.ArrayList;
import java.util.List;
public class AdminExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public AdminExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andUserIsNull() {
addCriterion("user is null");
return (Criteria) this;
}
public Criteria andUserIsNotNull() {
addCriterion("user is not null");
return (Criteria) this;
}
public Criteria andUserEqualTo(String value) {
addCriterion("user =", value, "user");
return (Criteria) this;
}
public Criteria andUserNotEqualTo(String value) {
addCriterion("user <>", value, "user");
return (Criteria) this;
}
public Criteria andUserGreaterThan(String value) {
addCriterion("user >", value, "user");
return (Criteria) this;
}
public Criteria andUserGreaterThanOrEqualTo(String value) {
addCriterion("user >=", value, "user");
return (Criteria) this;
}
public Criteria andUserLessThan(String value) {
addCriterion("user <", value, "user");
return (Criteria) this;
}
public Criteria andUserLessThanOrEqualTo(String value) {
addCriterion("user <=", value, "user");
return (Criteria) this;
}
public Criteria andUserLike(String value) {
addCriterion("user like", value, "user");
return (Criteria) this;
}
public Criteria andUserNotLike(String value) {
addCriterion("user not like", value, "user");
return (Criteria) this;
}
public Criteria andUserIn(List<String> values) {
addCriterion("user in", values, "user");
return (Criteria) this;
}
public Criteria andUserNotIn(List<String> values) {
addCriterion("user not in", values, "user");
return (Criteria) this;
}
public Criteria andUserBetween(String value1, String value2) {
addCriterion("user between", value1, value2, "user");
return (Criteria) this;
}
public Criteria andUserNotBetween(String value1, String value2) {
addCriterion("user not between", value1, value2, "user");
return (Criteria) this;
}
public Criteria andPswIsNull() {
addCriterion("psw is null");
return (Criteria) this;
}
public Criteria andPswIsNotNull() {
addCriterion("psw is not null");
return (Criteria) this;
}
public Criteria andPswEqualTo(String value) {
addCriterion("psw =", value, "psw");
return (Criteria) this;
}
public Criteria andPswNotEqualTo(String value) {
addCriterion("psw <>", value, "psw");
return (Criteria) this;
}
public Criteria andPswGreaterThan(String value) {
addCriterion("psw >", value, "psw");
return (Criteria) this;
}
public Criteria andPswGreaterThanOrEqualTo(String value) {
addCriterion("psw >=", value, "psw");
return (Criteria) this;
}
public Criteria andPswLessThan(String value) {
addCriterion("psw <", value, "psw");
return (Criteria) this;
}
public Criteria andPswLessThanOrEqualTo(String value) {
addCriterion("psw <=", value, "psw");
return (Criteria) this;
}
public Criteria andPswLike(String value) {
addCriterion("psw like", value, "psw");
return (Criteria) this;
}
public Criteria andPswNotLike(String value) {
addCriterion("psw not like", value, "psw");
return (Criteria) this;
}
public Criteria andPswIn(List<String> values) {
addCriterion("psw in", values, "psw");
return (Criteria) this;
}
public Criteria andPswNotIn(List<String> values) {
addCriterion("psw not in", values, "psw");
return (Criteria) this;
}
public Criteria andPswBetween(String value1, String value2) {
addCriterion("psw between", value1, value2, "psw");
return (Criteria) this;
}
public Criteria andPswNotBetween(String value1, String value2) {
addCriterion("psw not between", value1, value2, "psw");
return (Criteria) this;
}
public Criteria andIsAdminIsNull() {
addCriterion("isAdmin is null");
return (Criteria) this;
}
public Criteria andIsAdminIsNotNull() {
addCriterion("isAdmin is not null");
return (Criteria) this;
}
public Criteria andIsAdminEqualTo(Boolean value) {
addCriterion("isAdmin =", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminNotEqualTo(Boolean value) {
addCriterion("isAdmin <>", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminGreaterThan(Boolean value) {
addCriterion("isAdmin >", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminGreaterThanOrEqualTo(Boolean value) {
addCriterion("isAdmin >=", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminLessThan(Boolean value) {
addCriterion("isAdmin <", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminLessThanOrEqualTo(Boolean value) {
addCriterion("isAdmin <=", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminIn(List<Boolean> values) {
addCriterion("isAdmin in", values, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminNotIn(List<Boolean> values) {
addCriterion("isAdmin not in", values, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminBetween(Boolean value1, Boolean value2) {
addCriterion("isAdmin between", value1, value2, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminNotBetween(Boolean value1, Boolean value2) {
addCriterion("isAdmin not between", value1, value2, "isAdmin");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_admin
*
* @mbggenerated do_not_delete_during_merge Fri Sep 26 10:04:36 CST 2014
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | UTF-8 | Java | 16,628 | java | AdminExample.java | Java | [] | null | [] | package com.xiaohao.cms.model;
import java.util.ArrayList;
import java.util.List;
public class AdminExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public AdminExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andUserIsNull() {
addCriterion("user is null");
return (Criteria) this;
}
public Criteria andUserIsNotNull() {
addCriterion("user is not null");
return (Criteria) this;
}
public Criteria andUserEqualTo(String value) {
addCriterion("user =", value, "user");
return (Criteria) this;
}
public Criteria andUserNotEqualTo(String value) {
addCriterion("user <>", value, "user");
return (Criteria) this;
}
public Criteria andUserGreaterThan(String value) {
addCriterion("user >", value, "user");
return (Criteria) this;
}
public Criteria andUserGreaterThanOrEqualTo(String value) {
addCriterion("user >=", value, "user");
return (Criteria) this;
}
public Criteria andUserLessThan(String value) {
addCriterion("user <", value, "user");
return (Criteria) this;
}
public Criteria andUserLessThanOrEqualTo(String value) {
addCriterion("user <=", value, "user");
return (Criteria) this;
}
public Criteria andUserLike(String value) {
addCriterion("user like", value, "user");
return (Criteria) this;
}
public Criteria andUserNotLike(String value) {
addCriterion("user not like", value, "user");
return (Criteria) this;
}
public Criteria andUserIn(List<String> values) {
addCriterion("user in", values, "user");
return (Criteria) this;
}
public Criteria andUserNotIn(List<String> values) {
addCriterion("user not in", values, "user");
return (Criteria) this;
}
public Criteria andUserBetween(String value1, String value2) {
addCriterion("user between", value1, value2, "user");
return (Criteria) this;
}
public Criteria andUserNotBetween(String value1, String value2) {
addCriterion("user not between", value1, value2, "user");
return (Criteria) this;
}
public Criteria andPswIsNull() {
addCriterion("psw is null");
return (Criteria) this;
}
public Criteria andPswIsNotNull() {
addCriterion("psw is not null");
return (Criteria) this;
}
public Criteria andPswEqualTo(String value) {
addCriterion("psw =", value, "psw");
return (Criteria) this;
}
public Criteria andPswNotEqualTo(String value) {
addCriterion("psw <>", value, "psw");
return (Criteria) this;
}
public Criteria andPswGreaterThan(String value) {
addCriterion("psw >", value, "psw");
return (Criteria) this;
}
public Criteria andPswGreaterThanOrEqualTo(String value) {
addCriterion("psw >=", value, "psw");
return (Criteria) this;
}
public Criteria andPswLessThan(String value) {
addCriterion("psw <", value, "psw");
return (Criteria) this;
}
public Criteria andPswLessThanOrEqualTo(String value) {
addCriterion("psw <=", value, "psw");
return (Criteria) this;
}
public Criteria andPswLike(String value) {
addCriterion("psw like", value, "psw");
return (Criteria) this;
}
public Criteria andPswNotLike(String value) {
addCriterion("psw not like", value, "psw");
return (Criteria) this;
}
public Criteria andPswIn(List<String> values) {
addCriterion("psw in", values, "psw");
return (Criteria) this;
}
public Criteria andPswNotIn(List<String> values) {
addCriterion("psw not in", values, "psw");
return (Criteria) this;
}
public Criteria andPswBetween(String value1, String value2) {
addCriterion("psw between", value1, value2, "psw");
return (Criteria) this;
}
public Criteria andPswNotBetween(String value1, String value2) {
addCriterion("psw not between", value1, value2, "psw");
return (Criteria) this;
}
public Criteria andIsAdminIsNull() {
addCriterion("isAdmin is null");
return (Criteria) this;
}
public Criteria andIsAdminIsNotNull() {
addCriterion("isAdmin is not null");
return (Criteria) this;
}
public Criteria andIsAdminEqualTo(Boolean value) {
addCriterion("isAdmin =", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminNotEqualTo(Boolean value) {
addCriterion("isAdmin <>", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminGreaterThan(Boolean value) {
addCriterion("isAdmin >", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminGreaterThanOrEqualTo(Boolean value) {
addCriterion("isAdmin >=", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminLessThan(Boolean value) {
addCriterion("isAdmin <", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminLessThanOrEqualTo(Boolean value) {
addCriterion("isAdmin <=", value, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminIn(List<Boolean> values) {
addCriterion("isAdmin in", values, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminNotIn(List<Boolean> values) {
addCriterion("isAdmin not in", values, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminBetween(Boolean value1, Boolean value2) {
addCriterion("isAdmin between", value1, value2, "isAdmin");
return (Criteria) this;
}
public Criteria andIsAdminNotBetween(Boolean value1, Boolean value2) {
addCriterion("isAdmin not between", value1, value2, "isAdmin");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_admin
*
* @mbggenerated do_not_delete_during_merge Fri Sep 26 10:04:36 CST 2014
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_admin
*
* @mbggenerated Fri Sep 26 10:04:36 CST 2014
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | 16,628 | 0.57325 | 0.558576 | 562 | 28.588968 | 23.566973 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.537367 | false | false | 8 |
f0a96a255b9a0bf9cf515fdcc3e58a1e8e990621 | 33,973,191,312,619 | 5f7d55b0d9a590627f61240b9cba8ca0059495e1 | /src/main/java/seedu/address/storage/ingredient/JsonSerializableIngredientBook.java | e1a604903fc21f87ef7bf88076f826bcc28d4c08 | [
"MIT"
] | permissive | AY2021S2-CS2103T-W15-3/JJIMY | https://github.com/AY2021S2-CS2103T-W15-3/JJIMY | dbb2bbef959d752a0d91bbd28c4bb4d3cf8e1c62 | 5aba63792990453f1d7a416cd275d27b5fbda918 | refs/heads/master | "2023-04-03T16:47:05.001000" | "2021-04-16T09:52:43" | "2021-04-16T09:52:43" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package seedu.address.storage.ingredient;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.ReadOnlyBook;
import seedu.address.model.ingredient.Ingredient;
import seedu.address.model.ingredient.IngredientBook;
/**
* An immutable IngredientBook that is serializable to JSON format.
*/
@JsonRootName(value = "ingredientbook")
public class JsonSerializableIngredientBook {
public static final String MESSAGE_DUPLICATE_DISH = "Ingredient list contains duplicate ingredients.";
private final List<Ingredient> ingredients = new ArrayList<>();
/**
* Constructs a {@code JsonSerializableIngredientBook} with the given persons.
*/
@JsonCreator
public JsonSerializableIngredientBook(@JsonProperty("ingredients") List<Ingredient> ingredients) {
this.ingredients.addAll(ingredients);
}
/**
* Converts a given {@code ReadOnlyBook<Ingredient>} into this class for Jackson use.
*
* @param source future changes to this will not affect the created {@code JsonSerializableIngredientBook}.
*/
public JsonSerializableIngredientBook(ReadOnlyBook<Ingredient> source) {
ingredients.addAll(source.getItemList());
}
/**
* Converts this ingredient book into the model's {@code IngredientBook} object.
* @throws IllegalValueException if there were any data constraints violated.
*/
public IngredientBook toModelType() throws IllegalValueException {
IngredientBook ingredientBook = new IngredientBook();
ingredientBook.setIngredients(ingredients);
return ingredientBook;
}
}
| UTF-8 | Java | 1,843 | java | JsonSerializableIngredientBook.java | Java | [] | null | [] | package seedu.address.storage.ingredient;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.ReadOnlyBook;
import seedu.address.model.ingredient.Ingredient;
import seedu.address.model.ingredient.IngredientBook;
/**
* An immutable IngredientBook that is serializable to JSON format.
*/
@JsonRootName(value = "ingredientbook")
public class JsonSerializableIngredientBook {
public static final String MESSAGE_DUPLICATE_DISH = "Ingredient list contains duplicate ingredients.";
private final List<Ingredient> ingredients = new ArrayList<>();
/**
* Constructs a {@code JsonSerializableIngredientBook} with the given persons.
*/
@JsonCreator
public JsonSerializableIngredientBook(@JsonProperty("ingredients") List<Ingredient> ingredients) {
this.ingredients.addAll(ingredients);
}
/**
* Converts a given {@code ReadOnlyBook<Ingredient>} into this class for Jackson use.
*
* @param source future changes to this will not affect the created {@code JsonSerializableIngredientBook}.
*/
public JsonSerializableIngredientBook(ReadOnlyBook<Ingredient> source) {
ingredients.addAll(source.getItemList());
}
/**
* Converts this ingredient book into the model's {@code IngredientBook} object.
* @throws IllegalValueException if there were any data constraints violated.
*/
public IngredientBook toModelType() throws IllegalValueException {
IngredientBook ingredientBook = new IngredientBook();
ingredientBook.setIngredients(ingredients);
return ingredientBook;
}
}
| 1,843 | 0.754205 | 0.754205 | 50 | 35.860001 | 33.263802 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.34 | false | false | 8 |
eb0804bc7bf45746f7f34528d50594326b3429c2 | 27,599,459,862,798 | 62a27567c0a357f1d923a0d0b41b852cd461b125 | /app/src/main/java/com/example/tugas_sqllite/RecyclerViewAdapter.java | d918722c46102dd6b501d078156dd325adf5328f | [] | no_license | redcountry15/tugas_pwpbb | https://github.com/redcountry15/tugas_pwpbb | e380121f9fdafa014379933af9e9453b1f535bfe | 1d63fbf7f6a23170d1885c73794b431c7bb9b622 | refs/heads/master | "2020-07-25T19:02:48.146000" | "2019-09-14T11:54:12" | "2019-09-14T11:54:12" | 208,394,172 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.tugas_sqllite;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
List<Siswa> infoSiswa;
Context context;
onSiswaClickListener listener;
public RecyclerViewAdapter(Context context, List<Siswa>info, onSiswaClickListener listener){
this.context=context;
this.infoSiswa = info;
this.listener = listener;
}
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model_recycler,parent,false);
ViewHolder View = new ViewHolder(view);
return View;
}
public interface onSiswaClickListener{
void onSiswaClick(Siswa siswa);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Siswa siswa = infoSiswa.get(position);
holder.textNamaSiswa.setText(siswa.getNama());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onSiswaClick(siswa);
}
});
}
@Override
public int getItemCount() {
return infoSiswa.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textNamaSiswa;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textNamaSiswa = itemView.findViewById(R.id.NamaSiswa);
}
}
}
| UTF-8 | Java | 1,824 | java | RecyclerViewAdapter.java | Java | [] | null | [] | package com.example.tugas_sqllite;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
List<Siswa> infoSiswa;
Context context;
onSiswaClickListener listener;
public RecyclerViewAdapter(Context context, List<Siswa>info, onSiswaClickListener listener){
this.context=context;
this.infoSiswa = info;
this.listener = listener;
}
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.model_recycler,parent,false);
ViewHolder View = new ViewHolder(view);
return View;
}
public interface onSiswaClickListener{
void onSiswaClick(Siswa siswa);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final Siswa siswa = infoSiswa.get(position);
holder.textNamaSiswa.setText(siswa.getNama());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
listener.onSiswaClick(siswa);
}
});
}
@Override
public int getItemCount() {
return infoSiswa.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textNamaSiswa;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textNamaSiswa = itemView.findViewById(R.id.NamaSiswa);
}
}
}
| 1,824 | 0.697917 | 0.697917 | 62 | 28.419355 | 26.365635 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 8 |
1a98212f992e12d05ab5932ef7da71767e18d8b9 | 3,582,002,734,638 | 8cf58313435ccb0c34ab427b243145e776e6a32c | /actividad-01/src/main/java/pe/isil/jugadores/Players.java | 85b69d9ca9c404f06a0266766d3038f66115fe58 | [] | no_license | josue240294/efe | https://github.com/josue240294/efe | ee034ec77ef588b40c7c87ae26e00853d2eda061 | 04733b4d0bde2f72da62dae45ff95adf97daf827 | refs/heads/master | "2022-07-04T17:55:23.141000" | "2020-05-21T22:21:09" | "2020-05-21T22:21:09" | 265,964,318 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pe.isil.jugadores;
public interface Players {
void send();
}
| UTF-8 | Java | 75 | java | Players.java | Java | [] | null | [] | package pe.isil.jugadores;
public interface Players {
void send();
}
| 75 | 0.693333 | 0.693333 | 6 | 11.5 | 11.65833 | 26 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 8 |
00788c6067c389756f1ea2b99953146a2fefc5a9 | 25,056,839,256,852 | 9419b3be2f079f8a66f8e06fac0076328f613fbb | /backend/src/main/java/br/com/ota/backend/model/Land.java | cf07eaa4e704794bc1ce70cc14d4b1a490bf4d7e | [] | no_license | olivanaires/land-manager | https://github.com/olivanaires/land-manager | ab1e0e7043d0899be31f58cf2249e13117468d56 | 37fe85736be636c0d2ae00e30f27d08e3060b1f6 | refs/heads/master | "2023-01-06T09:45:50.700000" | "2020-10-30T20:37:36" | "2020-10-30T20:37:36" | 306,991,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.ota.backend.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "lands")
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Land extends BaseEntity {
private float area;
private float backdimension;
private String backintersection;
private String block;
private float frontdimension;
private String frontintersection;
private float lefdimension;
private String leftintersection;
private String number;
private float rightdimension;
private String rightintersection;
private String situation;
@ManyToOne
@JoinColumn(name = "landlocation_id", referencedColumnName = "id")
private LandLocation landLocation;
}
| UTF-8 | Java | 924 | java | Land.java | Java | [] | null | [] | package br.com.ota.backend.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "lands")
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Land extends BaseEntity {
private float area;
private float backdimension;
private String backintersection;
private String block;
private float frontdimension;
private String frontintersection;
private float lefdimension;
private String leftintersection;
private String number;
private float rightdimension;
private String rightintersection;
private String situation;
@ManyToOne
@JoinColumn(name = "landlocation_id", referencedColumnName = "id")
private LandLocation landLocation;
}
| 924 | 0.764069 | 0.764069 | 47 | 18.659575 | 17.23835 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.468085 | false | false | 8 |
b662ca9ec2c4d2f560ee635a7e1d5bfadbe8e140 | 16,320,875,791,939 | 507ce8dbc7662933d314f524b15cac971b9741d9 | /src/main/java/br/com/marcoscastelini/controller/ControllerConfiguracao.java | 0bde29dd540e22f3a11acb8dd28529ac82e7c9ae | [] | no_license | marcos-castelini/etiqueta-zebra | https://github.com/marcos-castelini/etiqueta-zebra | 096e5c407b4754c8a4fe7dfde9f89c6606db99b5 | d0dede11a6aceb38754774dbd642a9f132c7c0e5 | refs/heads/master | "2023-06-01T23:58:38.980000" | "2021-06-16T17:39:27" | "2021-06-16T17:39:27" | 358,954,102 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.marcoscastelini.controller;
import br.com.marcoscastelini.util.Configuracao;
import br.com.marcoscastelini.util.Impressora;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javax.print.PrintService;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class ControllerConfiguracao implements Initializable {
@FXML
private TextField txtNomeEstabelecimento;
@FXML
private TextArea txtExames, txtConvenios;
@FXML
private ComboBox<Integer> cmbQtdePadrao;
@FXML
private ComboBox<PrintService> cmbImpressora;
@Override
public void initialize(URL location, ResourceBundle resources) {
for (int i = 1; i <= 16; i++)
cmbQtdePadrao.getItems().add(i);
txtNomeEstabelecimento.setText(Configuracao.getProperties().getProperty("nome_estabelecimento"));
txtExames.setText(Configuracao.getProperties().getProperty("exames"));
txtConvenios.setText(Configuracao.getProperties().getProperty("convenios"));
cmbQtdePadrao.getSelectionModel().select(Integer.parseInt(Configuracao.getProperties().getProperty("qtde_etiquetas")) - 1);
Impressora.selecionarImpressora(cmbImpressora);
}
@FXML
public void onSalvar(ActionEvent event) {
Configuracao.getProperties().setProperty("nome_estabelecimento", txtNomeEstabelecimento.getText());
Configuracao.getProperties().setProperty("exames", txtExames.getText());
Configuracao.getProperties().setProperty("convenios", txtConvenios.getText());
Configuracao.getProperties().setProperty("qtde_etiquetas", cmbQtdePadrao.getSelectionModel().getSelectedItem().toString());
Configuracao.getProperties().setProperty("impressora", cmbImpressora.getSelectionModel().getSelectedItem().getName());
Configuracao.save();
Alert alert = new Alert(Alert.AlertType.INFORMATION, "Configurações salvas, a aplicação será reiniciada.", ButtonType.OK);
alert.showAndWait().ifPresent(buttonType -> {
if (buttonType == ButtonType.OK)
try {
Configuracao.reiniciarAplicacao();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
| UTF-8 | Java | 2,361 | java | ControllerConfiguracao.java | Java | [] | null | [] | package br.com.marcoscastelini.controller;
import br.com.marcoscastelini.util.Configuracao;
import br.com.marcoscastelini.util.Impressora;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javax.print.PrintService;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class ControllerConfiguracao implements Initializable {
@FXML
private TextField txtNomeEstabelecimento;
@FXML
private TextArea txtExames, txtConvenios;
@FXML
private ComboBox<Integer> cmbQtdePadrao;
@FXML
private ComboBox<PrintService> cmbImpressora;
@Override
public void initialize(URL location, ResourceBundle resources) {
for (int i = 1; i <= 16; i++)
cmbQtdePadrao.getItems().add(i);
txtNomeEstabelecimento.setText(Configuracao.getProperties().getProperty("nome_estabelecimento"));
txtExames.setText(Configuracao.getProperties().getProperty("exames"));
txtConvenios.setText(Configuracao.getProperties().getProperty("convenios"));
cmbQtdePadrao.getSelectionModel().select(Integer.parseInt(Configuracao.getProperties().getProperty("qtde_etiquetas")) - 1);
Impressora.selecionarImpressora(cmbImpressora);
}
@FXML
public void onSalvar(ActionEvent event) {
Configuracao.getProperties().setProperty("nome_estabelecimento", txtNomeEstabelecimento.getText());
Configuracao.getProperties().setProperty("exames", txtExames.getText());
Configuracao.getProperties().setProperty("convenios", txtConvenios.getText());
Configuracao.getProperties().setProperty("qtde_etiquetas", cmbQtdePadrao.getSelectionModel().getSelectedItem().toString());
Configuracao.getProperties().setProperty("impressora", cmbImpressora.getSelectionModel().getSelectedItem().getName());
Configuracao.save();
Alert alert = new Alert(Alert.AlertType.INFORMATION, "Configurações salvas, a aplicação será reiniciada.", ButtonType.OK);
alert.showAndWait().ifPresent(buttonType -> {
if (buttonType == ButtonType.OK)
try {
Configuracao.reiniciarAplicacao();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
| 2,361 | 0.70798 | 0.706282 | 60 | 38.266666 | 36.517059 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.716667 | false | false | 8 |
d8b3e399a35d0f5469e46b02a47d91534a4188dc | 5,128,190,955,962 | 14968110db73b6b0a345fff7e7efa91cf6546890 | /certificationCenter/src/main/java/by/training/certificationCenter/bean/Document.java | efe416608f32c1e1c6fffa18c167588b8ccc9cd2 | [] | no_license | chakurmaksim/TrainingRepository | https://github.com/chakurmaksim/TrainingRepository | b629a9387af2ba4a2888eb61ad61215611efbf3a | 61fd1dac19fd54e351ad99d557378b7bc744941d | refs/heads/master | "2023-05-11T04:47:18.625000" | "2022-03-09T11:41:46" | "2022-03-09T11:41:46" | 194,842,879 | 0 | 0 | null | false | "2023-05-09T18:36:31" | "2019-07-02T10:35:01" | "2022-03-09T11:41:05" | "2023-05-09T18:36:27" | 1,215 | 0 | 0 | 18 | Java | false | false | package by.training.certificationCenter.bean;
import java.io.InputStream;
import java.util.Objects;
public class Document extends CertificationEntity {
/**
* Real path to the directory where the file is located.
*/
private String uploadFilePath;
/**
* File name.
*/
private String fileName;
/**
* Link to the InputStream.
*/
private InputStream inputStream;
/**
* Link to the application to which this product belongs.
*/
private Application application;
public Document(final int newId) {
super(newId);
}
public String getUploadFilePath() {
return uploadFilePath;
}
public void setUploadFilePath(String uploadFilePath) {
this.uploadFilePath = uploadFilePath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public Application getApplication() {
return application;
}
public void setApplication(Application newApplication) {
this.application = newApplication;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Document document = (Document) o;
return id == document.id
&& Objects.equals(uploadFilePath, document.uploadFilePath)
&& Objects.equals(fileName, document.fileName);
}
@Override
public int hashCode() {
return Objects.hash(id, uploadFilePath, fileName);
}
@Override
public String toString() {
return "Document{"
+ " id=" + id
+ ", uploadFilePath='" + uploadFilePath + '\''
+ ", fileName='" + fileName + '\''
+ '}';
}
}
| UTF-8 | Java | 2,087 | java | Document.java | Java | [] | null | [] | package by.training.certificationCenter.bean;
import java.io.InputStream;
import java.util.Objects;
public class Document extends CertificationEntity {
/**
* Real path to the directory where the file is located.
*/
private String uploadFilePath;
/**
* File name.
*/
private String fileName;
/**
* Link to the InputStream.
*/
private InputStream inputStream;
/**
* Link to the application to which this product belongs.
*/
private Application application;
public Document(final int newId) {
super(newId);
}
public String getUploadFilePath() {
return uploadFilePath;
}
public void setUploadFilePath(String uploadFilePath) {
this.uploadFilePath = uploadFilePath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public Application getApplication() {
return application;
}
public void setApplication(Application newApplication) {
this.application = newApplication;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Document document = (Document) o;
return id == document.id
&& Objects.equals(uploadFilePath, document.uploadFilePath)
&& Objects.equals(fileName, document.fileName);
}
@Override
public int hashCode() {
return Objects.hash(id, uploadFilePath, fileName);
}
@Override
public String toString() {
return "Document{"
+ " id=" + id
+ ", uploadFilePath='" + uploadFilePath + '\''
+ ", fileName='" + fileName + '\''
+ '}';
}
}
| 2,087 | 0.598946 | 0.598946 | 84 | 23.845238 | 20.795773 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369048 | false | false | 8 |
73c51bb1682c4deaada078cb95fcd7177b3ab899 | 21,071,109,608,745 | 019351eb9567fefa8c9c15588899b52edbb68616 | /Multi-thread/src/cn/shyshetxwh/v2/v21/HasSelfPrivateNum2.java | 78207d56c14febfc57b197ca657b0cdf47b6ea78 | [] | no_license | shyshetxwh/selfstudy | https://github.com/shyshetxwh/selfstudy | 3220bbdee656f659a8890053d12e7a792bc67ad6 | 9b536e83243214a9ea37ff46a48b72d5d242ef2b | refs/heads/master | "2023-04-02T09:52:44.067000" | "2021-04-02T13:33:46" | "2021-04-02T13:33:46" | 352,621,879 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.shyshetxwh.v2.v21;
/**
* FileName: HasSelfPrivateNum2
* Author: Administrator+shyshetxwh
* Date: 2021/1/3 0003 16:54
*/
class Thread3 extends Thread {
private HasSelfPrivateNum2 numRef;
public Thread3(HasSelfPrivateNum2 numRef) {
this.numRef = numRef;
}
@Override
public void run() {
numRef.addI("a");
}
}
class Thread4 extends Thread {
private HasSelfPrivateNum2 numRef;
public Thread4(HasSelfPrivateNum2 numRef) {
this.numRef = numRef;
}
@Override
public void run() {
numRef.addI("b");
}
}
public class HasSelfPrivateNum2 {
private int num = 0;
public void addI(String username) {
try {
if (username.equals("a")) {
num = 100;
System.out.println("a set over");
Thread.sleep(2000);
} else {
num = 200;
System.out.println("b set over");
}
System.out.println(username + " num=" + num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HasSelfPrivateNum2 num2 = new HasSelfPrivateNum2();
new Thread3(num2).start();
new Thread4(num2).start();
}
}
| UTF-8 | Java | 1,314 | java | HasSelfPrivateNum2.java | Java | [
{
"context": "\n\n/**\n * FileName: HasSelfPrivateNum2\n * Author: Administrator+shyshetxwh\n * Date: 2021/1/3 0003 16:54\n */\n\nclass Threa",
"end": 104,
"score": 0.9994935393333435,
"start": 80,
"tag": "USERNAME",
"value": "Administrator+shyshetxwh"
}
] | null | [] | package cn.shyshetxwh.v2.v21;
/**
* FileName: HasSelfPrivateNum2
* Author: Administrator+shyshetxwh
* Date: 2021/1/3 0003 16:54
*/
class Thread3 extends Thread {
private HasSelfPrivateNum2 numRef;
public Thread3(HasSelfPrivateNum2 numRef) {
this.numRef = numRef;
}
@Override
public void run() {
numRef.addI("a");
}
}
class Thread4 extends Thread {
private HasSelfPrivateNum2 numRef;
public Thread4(HasSelfPrivateNum2 numRef) {
this.numRef = numRef;
}
@Override
public void run() {
numRef.addI("b");
}
}
public class HasSelfPrivateNum2 {
private int num = 0;
public void addI(String username) {
try {
if (username.equals("a")) {
num = 100;
System.out.println("a set over");
Thread.sleep(2000);
} else {
num = 200;
System.out.println("b set over");
}
System.out.println(username + " num=" + num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HasSelfPrivateNum2 num2 = new HasSelfPrivateNum2();
new Thread3(num2).start();
new Thread4(num2).start();
}
}
| 1,314 | 0.557078 | 0.522831 | 59 | 21.271187 | 17.357489 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.305085 | false | false | 8 |
ee38284e54b7307ef443fc8f2e634d2ebe3853ca | 16,303,695,921,229 | ad6ae27290fbc0ed4f4c65278d8526cf2c98e940 | /app/src/main/java/com/example/alirzaycefaydal/ecommerceserviceside/ViewHolder/MenuViewHolder.java | e98a9a9bdd05c778728a9d1e6aa51283af3099a6 | [] | no_license | alirzaycefydli/EcommerceServerSide | https://github.com/alirzaycefydli/EcommerceServerSide | 079d57111c411d203432e7f3e8c0a47a5586b4de | 191dd7217d4183c0181f69ebdbbf1317322e73ac | refs/heads/master | "2020-04-15T12:58:49.073000" | "2019-01-08T19:31:09" | "2019-01-08T19:31:09" | 164,696,571 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.alirzaycefaydal.ecommerceserviceside.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.alirzaycefaydal.ecommerceserviceside.HomeActivity;
import com.example.alirzaycefaydal.ecommerceserviceside.Interface.ItemClickListener;
import com.example.alirzaycefaydal.ecommerceserviceside.R;
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnCreateContextMenuListener{
public TextView txtMenuName;
public ImageView imageView;
private ItemClickListener listener;
public MenuViewHolder (View view){
super(view);
txtMenuName=view.findViewById(R.id.menu_name);
imageView=view.findViewById(R.id.menu_image);
view.setOnCreateContextMenuListener(this);
view.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener listener){
this.listener=listener;
}
@Override
public void onClick(View v) {
listener.onClick(v,getAdapterPosition(),false);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select an action");
menu.add(0,0,getAdapterPosition(),HomeActivity.UPDATE);
menu.add(0,1,getAdapterPosition(),HomeActivity.DELETE);
}
}
| UTF-8 | Java | 1,476 | java | MenuViewHolder.java | Java | [
{
"context": "package com.example.alirzaycefaydal.ecommerceserviceside.ViewHolder;\n\nimport and",
"end": 30,
"score": 0.8419733047485352,
"start": 20,
"tag": "USERNAME",
"value": "alirzaycef"
},
{
"context": "package com.example.alirzaycefaydal.ecommerceserviceside.ViewHolder;\n\nimport android.",
"end": 35,
"score": 0.505955696105957,
"start": 32,
"tag": "USERNAME",
"value": "dal"
},
{
"context": "port android.widget.TextView;\n\nimport com.example.alirzaycefaydal.ecommerceserviceside.HomeActivity;\nimport com.exa",
"end": 276,
"score": 0.9701887965202332,
"start": 261,
"tag": "USERNAME",
"value": "alirzaycefaydal"
},
{
"context": "merceserviceside.HomeActivity;\nimport com.example.alirzaycefaydal.ecommerceserviceside.Interface.ItemClickListener;",
"end": 346,
"score": 0.9449896812438965,
"start": 331,
"tag": "USERNAME",
"value": "alirzaycefaydal"
},
{
"context": "e.Interface.ItemClickListener;\nimport com.example.alirzaycefaydal.ecommerceserviceside.R;\n\npublic class MenuViewHol",
"end": 431,
"score": 0.9005535840988159,
"start": 416,
"tag": "USERNAME",
"value": "alirzaycefaydal"
}
] | null | [] | package com.example.alirzaycefaydal.ecommerceserviceside.ViewHolder;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.alirzaycefaydal.ecommerceserviceside.HomeActivity;
import com.example.alirzaycefaydal.ecommerceserviceside.Interface.ItemClickListener;
import com.example.alirzaycefaydal.ecommerceserviceside.R;
public class MenuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnCreateContextMenuListener{
public TextView txtMenuName;
public ImageView imageView;
private ItemClickListener listener;
public MenuViewHolder (View view){
super(view);
txtMenuName=view.findViewById(R.id.menu_name);
imageView=view.findViewById(R.id.menu_image);
view.setOnCreateContextMenuListener(this);
view.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener listener){
this.listener=listener;
}
@Override
public void onClick(View v) {
listener.onClick(v,getAdapterPosition(),false);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select an action");
menu.add(0,0,getAdapterPosition(),HomeActivity.UPDATE);
menu.add(0,1,getAdapterPosition(),HomeActivity.DELETE);
}
}
| 1,476 | 0.762873 | 0.759485 | 45 | 31.799999 | 30.138643 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.733333 | false | false | 8 |
37e4dab8f877cc034ef10669d9b2c8647ebe3163 | 16,303,695,917,839 | 5169a4c4d0e4bd84eff3a65fd9926df01437d098 | /API/src/com/javalec/base/Random_01.java | c5ad33aade929fead9285f0e6b90dba2198f8dc0 | [] | no_license | ds-hur/Java_study | https://github.com/ds-hur/Java_study | 8ec55592e197459f90931570bd36ba67fabfc876 | 431fa5e689c302d52491b74cffb9c3e031da0b45 | refs/heads/main | "2023-07-22T23:30:00.847000" | "2021-09-09T08:51:08" | "2021-09-09T08:51:08" | 404,649,650 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javalec.base;
import java.util.Random;
public class Random_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random random = new Random();
for (int j = 1; j<=6; j++) {
int i = random.nextInt(46); // 11 전까지의 난수
System.out.println(i);
}
}
}
| UTF-8 | Java | 319 | java | Random_01.java | Java | [] | null | [] | package com.javalec.base;
import java.util.Random;
public class Random_01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random random = new Random();
for (int j = 1; j<=6; j++) {
int i = random.nextInt(46); // 11 전까지의 난수
System.out.println(i);
}
}
}
| 319 | 0.628664 | 0.602606 | 18 | 16.055555 | 15.914606 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.444444 | false | false | 8 |
1180322d08cc356a709547c557923d39d9d215bc | 26,740,466,430,443 | de9281058db8c2071447ca2565b1c6d1c3502e11 | /src/main/java/org/liber/api/daoImpl/BookshelfDAOImpl.java | 51a5a9d44161ef3d520d37d12b63f4d857ae1217 | [] | no_license | PrashantM89/LiberAPI | https://github.com/PrashantM89/LiberAPI | 493f12ffb4af6044507c787f6f7c07ac299a8cf5 | adaa8bb9d14d5093d75c9e50ca0268346dd46144 | refs/heads/master | "2022-12-28T21:13:15.066000" | "2019-06-09T20:24:56" | "2019-06-09T20:24:56" | 191,051,335 | 0 | 0 | null | false | "2022-12-16T10:42:14" | "2019-06-09T20:17:24" | "2019-06-09T20:25:41" | "2022-12-16T10:42:11" | 25 | 0 | 0 | 5 | Java | false | false | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.liber.api.daoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.liber.api.dao.BookshelfDAO;
import org.liber.api.model.BookEntity;
import org.liber.api.model.TransactionEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
*
* @author prashant
*/
public class BookshelfDAOImpl implements BookshelfDAO{
private JdbcTemplate jdbcTemplate;
public BookshelfDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public List<BookEntity> getAllBooks() {
String sql="SELECT * FROM bookshelf where b_delete='N'";
List<BookEntity> books = jdbcTemplate.query(sql, new RowMapper<BookEntity>() {
@Override
public BookEntity mapRow(ResultSet rs, int i) throws SQLException {
BookEntity b = new BookEntity();
b.setTitle(rs.getString("b_title"));
b.setAuthor(rs.getString("b_author"));
b.setCoverImgUrl(rs.getString("b_cover"));
b.setDescription(rs.getString("b_desc"));
b.setGenre(rs.getString("b_genre"));
b.setRating(rs.getString("b_rating"));
b.setUser(rs.getString("u_id"));
b.setAvailable(rs.getString("b_available"));
b.setReader(rs.getString("b_reader"));
b.setDor(rs.getString("b_dor"));
b.setDelete(rs.getString("b_delete"));
return b;
}
});
return books;
}
@Override
public void insertBook(BookEntity b, String u_id) {
String sql = "INSERT INTO bookshelf (b_title, b_author, b_cover, b_desc,b_genre,b_rating,u_id,b_available, b_reader,b_delete)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
jdbcTemplate.update(sql, b.getTitle(),b.getAuthor(),b.getCoverImgUrl(),b.getDescription(),b.getGenre(),b.getRating(), u_id,b.getAvailable(),b.getReader(),b.getDelete());
}
@Override
public void updateBookshelfAvailability(String isAvailable, TransactionEntity t) {
int count = jdbcTemplate.update("UPDATE bookshelf set b_available = ? ,b_reader = ?, b_dor = ? where b_title = ? AND u_id = ?", new Object[] {isAvailable,t.getTxUser(),t.getTxReturnDate() ,t.getTxBook(), t.getTxBookOwner()});
}
@Override
public void updateBookshelfToDeleteBook(BookEntity b) {
int count = jdbcTemplate.update("UPDATE bookshelf set b_available = ? ,b_delete = ? where b_title = ? AND u_id = ?", new Object[] {"N",b.getDelete(),b.getTitle(),b.getUser()});
}
}
| UTF-8 | Java | 2,916 | java | BookshelfDAOImpl.java | Java | [
{
"context": "gframework.jdbc.core.RowMapper;\n\n/**\n *\n * @author prashant\n */\npublic class BookshelfDAOImpl implements Book",
"end": 576,
"score": 0.9972620010375977,
"start": 568,
"tag": "USERNAME",
"value": "prashant"
}
] | 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 org.liber.api.daoImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.liber.api.dao.BookshelfDAO;
import org.liber.api.model.BookEntity;
import org.liber.api.model.TransactionEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
/**
*
* @author prashant
*/
public class BookshelfDAOImpl implements BookshelfDAO{
private JdbcTemplate jdbcTemplate;
public BookshelfDAOImpl(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public List<BookEntity> getAllBooks() {
String sql="SELECT * FROM bookshelf where b_delete='N'";
List<BookEntity> books = jdbcTemplate.query(sql, new RowMapper<BookEntity>() {
@Override
public BookEntity mapRow(ResultSet rs, int i) throws SQLException {
BookEntity b = new BookEntity();
b.setTitle(rs.getString("b_title"));
b.setAuthor(rs.getString("b_author"));
b.setCoverImgUrl(rs.getString("b_cover"));
b.setDescription(rs.getString("b_desc"));
b.setGenre(rs.getString("b_genre"));
b.setRating(rs.getString("b_rating"));
b.setUser(rs.getString("u_id"));
b.setAvailable(rs.getString("b_available"));
b.setReader(rs.getString("b_reader"));
b.setDor(rs.getString("b_dor"));
b.setDelete(rs.getString("b_delete"));
return b;
}
});
return books;
}
@Override
public void insertBook(BookEntity b, String u_id) {
String sql = "INSERT INTO bookshelf (b_title, b_author, b_cover, b_desc,b_genre,b_rating,u_id,b_available, b_reader,b_delete)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
jdbcTemplate.update(sql, b.getTitle(),b.getAuthor(),b.getCoverImgUrl(),b.getDescription(),b.getGenre(),b.getRating(), u_id,b.getAvailable(),b.getReader(),b.getDelete());
}
@Override
public void updateBookshelfAvailability(String isAvailable, TransactionEntity t) {
int count = jdbcTemplate.update("UPDATE bookshelf set b_available = ? ,b_reader = ?, b_dor = ? where b_title = ? AND u_id = ?", new Object[] {isAvailable,t.getTxUser(),t.getTxReturnDate() ,t.getTxBook(), t.getTxBookOwner()});
}
@Override
public void updateBookshelfToDeleteBook(BookEntity b) {
int count = jdbcTemplate.update("UPDATE bookshelf set b_available = ? ,b_delete = ? where b_title = ? AND u_id = ?", new Object[] {"N",b.getDelete(),b.getTitle(),b.getUser()});
}
}
| 2,916 | 0.630315 | 0.630315 | 73 | 38.945206 | 44.950474 | 252 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.191781 | false | false | 8 |
611054fc9dbaec0127cac113c2601ee5959caebe | 8,504,035,273,613 | f4ce00825a64e375184cf9f89d6eded655566053 | /source2/com/duokan/reader/ui/personal/cz.java | 65e4890235f6e6bc68b814e12d57fdce312c5585 | [] | no_license | yezhuen/hackmanysee | https://github.com/yezhuen/hackmanysee | 97865ebabb00bda60f6325731e8b9a66eb4547c0 | a9255e3eb70bf59e091b574b30417fca45e8d901 | refs/heads/master | "2016-08-05T11:01:40.100000" | "2014-01-15T18:26:51" | "2014-01-15T18:26:51" | 15,881,265 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) lnc
package com.duokan.reader.ui.personal;
import com.duokan.reader.domain.cloud.push.DkCloudPushManager;
// Referenced classes of package com.duokan.reader.ui.personal:
// cx
class cz
implements Runnable
{
cz(cx cx)
{
a = cx;
super();
}
public void run()
{
DkCloudPushManager.a().b();
}
final cx a;
}
| UTF-8 | Java | 526 | java | cz.java | Java | [
{
"context": "// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.\n// Jad home page: http://www.kpdus.com/jad.html\n",
"end": 61,
"score": 0.9996399879455566,
"start": 45,
"tag": "NAME",
"value": "Pavel Kouznetsov"
}
] | null | [] | // Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) lnc
package com.duokan.reader.ui.personal;
import com.duokan.reader.domain.cloud.push.DkCloudPushManager;
// Referenced classes of package com.duokan.reader.ui.personal:
// cx
class cz
implements Runnable
{
cz(cx cx)
{
a = cx;
super();
}
public void run()
{
DkCloudPushManager.a().b();
}
final cx a;
}
| 516 | 0.631179 | 0.61597 | 28 | 17.785715 | 20.449165 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.214286 | false | false | 8 |
bdd06b3132789f9b8aa734ccee447229d9b71978 | 33,621,004,000,222 | 194e44209e5494bc78378963e15cbfc8ba944373 | /src/main/java/thebetweenlands/common/block/misc/BlockSulfurTorch.java | 1e99d8a30a02d879bb9d1523a645bae33effe651 | [] | no_license | Angry-Pixel/The-Betweenlands | https://github.com/Angry-Pixel/The-Betweenlands | cf8b8f4b8ac58b047dfbb19911426b81c7f31733 | eafac1c217cdf304d477b025708e0dadf82b6953 | refs/heads/1.12-fixes | "2023-09-01T07:57:27.962000" | "2023-04-07T19:02:05" | "2023-04-07T19:02:05" | 30,657,636 | 237 | 125 | null | false | "2023-09-04T07:18:36" | "2015-02-11T16:34:13" | "2023-08-29T19:10:12" | "2023-09-04T07:18:35" | 975,776 | 218 | 68 | 207 | Java | false | false | package thebetweenlands.common.block.misc;
import java.util.Random;
import net.minecraft.block.BlockTorch;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import thebetweenlands.client.render.particle.BLParticles;
import thebetweenlands.client.tab.BLCreativeTabs;
import thebetweenlands.common.registries.BlockRegistry;
public class BlockSulfurTorch extends BlockTorch {
public BlockSulfurTorch() {
this.setCreativeTab(BLCreativeTabs.BLOCKS);
this.setSoundType(SoundType.WOOD);
this.setLightLevel(0.9375F);
this.setTickRandomly(true);
}
@Override
public void randomTick(World worldIn, BlockPos pos, IBlockState state, Random random) {
if(!worldIn.isRemote && worldIn.isRainingAt(pos)) {
worldIn.setBlockState(pos, BlockRegistry.SULFUR_TORCH_EXTINGUISHED.getDefaultState().withProperty(FACING, worldIn.getBlockState(pos).getValue(FACING)));
}
}
@Override
@SideOnly(Side.CLIENT)
public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) {
EnumFacing enumfacing = (EnumFacing)state.getValue(FACING);
double px = (double)pos.getX() + 0.5D;
double py = (double)pos.getY() + 0.7D;
double pz = (double)pos.getZ() + 0.5D;
if (enumfacing.getAxis().isHorizontal()) {
EnumFacing enumfacing1 = enumfacing.getOpposite();
BLParticles.SULFUR_TORCH.spawn(world, px + 0.27D * (double)enumfacing1.getXOffset(), py + 0.22D, pz + 0.27D * (double)enumfacing1.getZOffset());
} else {
BLParticles.SULFUR_TORCH.spawn(world, px, py, pz);
}
}
}
| UTF-8 | Java | 1,750 | java | BlockSulfurTorch.java | Java | [] | null | [] | package thebetweenlands.common.block.misc;
import java.util.Random;
import net.minecraft.block.BlockTorch;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import thebetweenlands.client.render.particle.BLParticles;
import thebetweenlands.client.tab.BLCreativeTabs;
import thebetweenlands.common.registries.BlockRegistry;
public class BlockSulfurTorch extends BlockTorch {
public BlockSulfurTorch() {
this.setCreativeTab(BLCreativeTabs.BLOCKS);
this.setSoundType(SoundType.WOOD);
this.setLightLevel(0.9375F);
this.setTickRandomly(true);
}
@Override
public void randomTick(World worldIn, BlockPos pos, IBlockState state, Random random) {
if(!worldIn.isRemote && worldIn.isRainingAt(pos)) {
worldIn.setBlockState(pos, BlockRegistry.SULFUR_TORCH_EXTINGUISHED.getDefaultState().withProperty(FACING, worldIn.getBlockState(pos).getValue(FACING)));
}
}
@Override
@SideOnly(Side.CLIENT)
public void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) {
EnumFacing enumfacing = (EnumFacing)state.getValue(FACING);
double px = (double)pos.getX() + 0.5D;
double py = (double)pos.getY() + 0.7D;
double pz = (double)pos.getZ() + 0.5D;
if (enumfacing.getAxis().isHorizontal()) {
EnumFacing enumfacing1 = enumfacing.getOpposite();
BLParticles.SULFUR_TORCH.spawn(world, px + 0.27D * (double)enumfacing1.getXOffset(), py + 0.22D, pz + 0.27D * (double)enumfacing1.getZOffset());
} else {
BLParticles.SULFUR_TORCH.spawn(world, px, py, pz);
}
}
}
| 1,750 | 0.771429 | 0.758286 | 47 | 36.234043 | 33.480518 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.829787 | false | false | 8 |
05cbef3cdda9d0dc6453bba415e53222b288702d | 15,736,760,187,895 | f9d4e86a2cf7e552bb7e8f9895e4cc31ca05f4a5 | /app/src/main/java/abdullah/elamien/bloodbank/ui/App.java | bb9490f0b20787480fc798a12c5552801fe9a146 | [
"MIT"
] | permissive | mohammedragabmohammedborik/BloodBank | https://github.com/mohammedragabmohammedborik/BloodBank | a5d7099e776cf456257261170cff718b77306895 | 4c4d22ba8ec85a90b9bed2515cecc13266af1491 | refs/heads/master | "2020-06-12T22:20:34.560000" | "2019-06-27T16:01:56" | "2019-06-27T16:01:56" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package abdullah.elamien.bloodbank.ui;
import android.app.Application;
import abdullah.elamien.bloodbank.di.components.AppComponent;
import abdullah.elamien.bloodbank.di.components.DaggerAppComponent;
import abdullah.elamien.bloodbank.di.modules.PreferenceUtilsModule;
/**
* Created by AbdullahAtta on 6/19/2019.
*/
public class App extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerAppComponent.builder().preferenceUtilsModule(new PreferenceUtilsModule(getApplicationContext())).build();
}
public AppComponent getAppComponent() {
return mAppComponent;
}
}
| UTF-8 | Java | 695 | java | App.java | Java | [
{
"context": ".modules.PreferenceUtilsModule;\n\n/**\n * Created by AbdullahAtta on 6/19/2019.\n */\npublic class App extends Applic",
"end": 302,
"score": 0.9468691945075989,
"start": 290,
"tag": "NAME",
"value": "AbdullahAtta"
}
] | null | [] | package abdullah.elamien.bloodbank.ui;
import android.app.Application;
import abdullah.elamien.bloodbank.di.components.AppComponent;
import abdullah.elamien.bloodbank.di.components.DaggerAppComponent;
import abdullah.elamien.bloodbank.di.modules.PreferenceUtilsModule;
/**
* Created by AbdullahAtta on 6/19/2019.
*/
public class App extends Application {
private AppComponent mAppComponent;
@Override
public void onCreate() {
super.onCreate();
mAppComponent = DaggerAppComponent.builder().preferenceUtilsModule(new PreferenceUtilsModule(getApplicationContext())).build();
}
public AppComponent getAppComponent() {
return mAppComponent;
}
}
| 695 | 0.759712 | 0.74964 | 24 | 27.958334 | 31.272297 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 8 |
49a8be2120134570ef83a40aaef1add8ed6462d0 | 1,494,648,658,094 | 8f6a158b16b0a61e7787f948b6e259ec94bdc24e | /plugin/src/main/java/net/dzikoysk/funnyguilds/event/guild/GuildRenameEvent.java | 114590064ac3b79b98db95a80f7f1b5134415380 | [
"Apache-2.0"
] | permissive | FunnyGuilds/FunnyGuilds | https://github.com/FunnyGuilds/FunnyGuilds | fba2139c761b68b0b0219c8867978cf4f93ed03c | 9410d90956768d1dc827828fc97a48688a78b466 | refs/heads/5.x | "2023-08-16T22:40:07.291000" | "2023-08-07T09:51:17" | "2023-08-07T09:51:17" | 24,366,589 | 300 | 257 | Apache-2.0 | false | "2023-09-01T09:44:30" | "2014-09-23T10:18:52" | "2023-07-20T19:14:47" | "2023-09-01T09:44:30" | 5,372 | 177 | 97 | 54 | Java | false | false | package net.dzikoysk.funnyguilds.event.guild;
import net.dzikoysk.funnyguilds.guild.Guild;
import net.dzikoysk.funnyguilds.user.User;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class GuildRenameEvent extends GuildEvent {
private static final HandlerList handlers = new HandlerList();
private final String oldName;
private final String newName;
@Override
public @NotNull HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public GuildRenameEvent(EventCause eventCause, User doer, Guild guild, String oldName, String newName) {
super(eventCause, doer, guild);
this.oldName = oldName;
this.newName = newName;
}
public String getOldName() {
return this.oldName;
}
public String getNewName() {
return this.newName;
}
@Override
public String getDefaultCancelMessage() {
return "[FunnyGuilds] Guild renaming has been cancelled by the server!";
}
}
| UTF-8 | Java | 1,086 | java | GuildRenameEvent.java | Java | [] | null | [] | package net.dzikoysk.funnyguilds.event.guild;
import net.dzikoysk.funnyguilds.guild.Guild;
import net.dzikoysk.funnyguilds.user.User;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
public class GuildRenameEvent extends GuildEvent {
private static final HandlerList handlers = new HandlerList();
private final String oldName;
private final String newName;
@Override
public @NotNull HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
public GuildRenameEvent(EventCause eventCause, User doer, Guild guild, String oldName, String newName) {
super(eventCause, doer, guild);
this.oldName = oldName;
this.newName = newName;
}
public String getOldName() {
return this.oldName;
}
public String getNewName() {
return this.newName;
}
@Override
public String getDefaultCancelMessage() {
return "[FunnyGuilds] Guild renaming has been cancelled by the server!";
}
}
| 1,086 | 0.697053 | 0.697053 | 42 | 24.857143 | 24.439985 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 8 |
489d8028dcb73338d70ba5fb7c80d2dec3733e57 | 18,554,258,721,729 | 2780889aed3bfa13e18c11094ccfa3d8de44e268 | /src/com/darcy/main/cleancode_v1_0_3/BinaryTree/P28_BalancedBinaryTree.java | 1c36e3e25f027101d88615e12ed9ce5d8201475f | [] | no_license | MyDarcy/LearningJava | https://github.com/MyDarcy/LearningJava | 7d2b968fdd969c21130fe67c2283bc3040d2a7ad | d60f6d23b5e3d8de3bed4de340bad58a0610d9e0 | refs/heads/master | "2021-01-19T03:09:36.345000" | "2019-05-27T01:44:39" | "2019-05-27T01:44:39" | 87,307,602 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.darcy.main.cleancode_v1_0_3.BinaryTree;
/**
* Author by darcy
* Date on 17-9-3 下午1:14.
* Description:
*
* 判定给定的二叉树是否是平衡树.
*
* Given a binary tree, determine if it is height-balanced.
* For this problem, a height-balanced binary tree is defined as a binary tree in which the
* depth of the two subtrees of every node never differs by more than 1.
*
*/
public class P28_BalancedBinaryTree {
static class TreeNode {
Integer val;
TreeNode left;
TreeNode right;
public TreeNode(Integer val) {
this.val = val;
}
public TreeNode(Integer val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
public TreeNode() {
}
}
/**
*
* 暴力方法.
* 每一个节点都需要判定其高度.
*
* O(n^2)的时间复杂度, O(1)的空间复杂度.
*
* @param root
* @return
*/
public static boolean bruteSolution(TreeNode root) {
if (root == null) {
return true;
}
return Math.abs(depth(root.left) - depth(root.right)) <= 1
&& bruteSolution(root.left)
&& bruteSolution(root.right);
}
// 求以root为根节点的最大深度.
public static int depth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(depth(root.left), depth(root.right)) + 1;
}
/**
* 跟上面应该是一样的意思.
* @param root
* @return
*/
public static boolean solution2(TreeNode root) {
if (root == null) {
return true;
}
int left = depth2(root.left);
int right = depth2(root.right);
return Math.abs(left - right) <= 1 && solution2(root.left) && solution2(root.right);
}
private static int depth2(TreeNode root) {
if (root == null) {
return 0;
}
int left = depth2(root.left);
int right = depth2(root.right);
return Math.max(left, right);
}
/**
* @param root
* @return
*/
public static boolean solution3(TreeNode root) {
return maxDepth(root) != -1;
}
private static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int L = maxDepth(root.left);
if (L == -1) {
return -1;
}
int R = maxDepth(root.right);
if (R == -1) {
return -1;
}
return (Math.abs(L - R) <= 1) ? Math.max(L, R) + 1 : -1;
}
}
| UTF-8 | Java | 2,391 | java | P28_BalancedBinaryTree.java | Java | [
{
"context": "ain.cleancode_v1_0_3.BinaryTree;\n\n/**\n * Author by darcy\n * Date on 17-9-3 下午1:14.\n * Description:\n *\n * 判",
"end": 75,
"score": 0.9976379871368408,
"start": 70,
"tag": "USERNAME",
"value": "darcy"
}
] | null | [] | package com.darcy.main.cleancode_v1_0_3.BinaryTree;
/**
* Author by darcy
* Date on 17-9-3 下午1:14.
* Description:
*
* 判定给定的二叉树是否是平衡树.
*
* Given a binary tree, determine if it is height-balanced.
* For this problem, a height-balanced binary tree is defined as a binary tree in which the
* depth of the two subtrees of every node never differs by more than 1.
*
*/
public class P28_BalancedBinaryTree {
static class TreeNode {
Integer val;
TreeNode left;
TreeNode right;
public TreeNode(Integer val) {
this.val = val;
}
public TreeNode(Integer val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
public TreeNode() {
}
}
/**
*
* 暴力方法.
* 每一个节点都需要判定其高度.
*
* O(n^2)的时间复杂度, O(1)的空间复杂度.
*
* @param root
* @return
*/
public static boolean bruteSolution(TreeNode root) {
if (root == null) {
return true;
}
return Math.abs(depth(root.left) - depth(root.right)) <= 1
&& bruteSolution(root.left)
&& bruteSolution(root.right);
}
// 求以root为根节点的最大深度.
public static int depth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(depth(root.left), depth(root.right)) + 1;
}
/**
* 跟上面应该是一样的意思.
* @param root
* @return
*/
public static boolean solution2(TreeNode root) {
if (root == null) {
return true;
}
int left = depth2(root.left);
int right = depth2(root.right);
return Math.abs(left - right) <= 1 && solution2(root.left) && solution2(root.right);
}
private static int depth2(TreeNode root) {
if (root == null) {
return 0;
}
int left = depth2(root.left);
int right = depth2(root.right);
return Math.max(left, right);
}
/**
* @param root
* @return
*/
public static boolean solution3(TreeNode root) {
return maxDepth(root) != -1;
}
private static int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int L = maxDepth(root.left);
if (L == -1) {
return -1;
}
int R = maxDepth(root.right);
if (R == -1) {
return -1;
}
return (Math.abs(L - R) <= 1) ? Math.max(L, R) + 1 : -1;
}
}
| 2,391 | 0.579973 | 0.563137 | 115 | 18.626087 | 19.798754 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 8 |
7542d04b6b1611a36dc082649501c1a9f9110fbb | 3,710,851,797,924 | d4e85a4a42a72e0098efd25d07891f341eb7af41 | /HelperClasses/DatesFunctions.java | ecbfcaa750513e0a977ecd6eee794c6355090969 | [] | no_license | efthymios1991/sampleCode | https://github.com/efthymios1991/sampleCode | d4a89f681bb968ec605c39a891a903e1d74e313d | 605b5ae3b80f24af71d945e76aa7bbbb82f65029 | refs/heads/master | "2021-01-20T02:57:31.960000" | "2017-04-26T12:01:06" | "2017-04-26T12:01:06" | 88,018,288 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import android.content.Context;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* Created by makis on 1/10/2017.
*/
public class DatesFunctions {
private Context mContext;
public DatesFunctions(Context context){
this.mContext = context;
}
/**
* Function to get the number of weeks a month has
* @param month which month we want to check (as integer)
* @param year of which year
* @return
*/
public Integer[] getWeeksOfMonth(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
Set<Integer> weeks = new HashSet<Integer>();
int ndays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 0; i < ndays; i++) {
weeks.add(cal.get(Calendar.WEEK_OF_YEAR));
cal.add(Calendar.DATE, 1);
}
return weeks.toArray(new Integer[0]);
}
/**
* Compares if Date1 is after Date2 for a date format we want
* @param date1 First date to see if after date2
* @param date2 Second date
* @param format Format that the two above dates are (both dates must be of same format)
* @return Returns true if date1 is after date2, false otherwise
*/
public boolean compareDate1AfterDate2(String date1, String date2, String format){
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date convertedDate1 = null;
Date convertedDate2 = null;
try {
convertedDate1 = dateFormat.parse(date1);
convertedDate2 = dateFormat.parse(date2);
} catch (ParseException e) {
e.printStackTrace();
}
if(convertedDate1!=null && convertedDate2!=null){
if(convertedDate1.after(convertedDate2)){
return true;
}
}
return false;
}
/**
* Function to calculate the difference between two dates of a given format
* @param date_one First date passses
* @param date_two Second date passed
* @param dateFormat The format that the two dates are (both dates must be of the same format)
* @return Returns the days that the two dates differ
*/
public int getDaysDifferenceTwoDates(String date_one, String date_two, String dateFormat) {
int diffint = 0;
try{
SimpleDateFormat date_created = new SimpleDateFormat(dateFormat);
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Date date1 = date_created.parse(date_one);
Date date2 = formatter.parse(date_two);
long diff2 = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff2 / (24 * 60 * 60 * 1000);
diffint = (int) diffDays;
diffint = diffint+1;
}catch (ParseException e1){
e1.printStackTrace();
}
return diffint;
}
/**
* Function to add a specific number of days to a given date of a given format
* @param date Date we want to add the days
* @param format Format of the given date
* @param days Number of days we want to add
* @return Returns the new calculated date in the passed format
*/
public String addDaysToDate(String date, String format, int days){
SimpleDateFormat sdf = new SimpleDateFormat(format);
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, days);
date = sdf.format(c.getTime());
return date;
}
/**
* Function that filters a given date of a given format to a new given format
* @param datestr The date we want to format
* @param inDateFormat The current date format
* @param outDateFormat The new format we want
* @return Returns the given date in the new format if everything went ok, "" otherwise
*/
public String filterDate(String datestr, String inDateFormat, String outDateFormat) {
try{
SimpleDateFormat sdfb = new SimpleDateFormat(inDateFormat);
SimpleDateFormat sdfa = new SimpleDateFormat(outDateFormat);
return sdfa.format(sdfb.parse(datestr));
}catch(Exception ex){
return "";
}
}
/**
* Function to get now date in given format
* @param dateFormat The format we want our date output
* @return Returns now date in given format
*/
public String CDate(String dateFormat){
try{
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date date=new Date();
String cdate=sdf.format(date);
return cdate;
}catch (Exception e){
e.printStackTrace();
return "";
}
}
/**
* Function to get months name based on month int
* @param num
* @return
*/
public String getMonthForInt(int num) {
String month = "wrong";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (num >= 0 && num <= 11 ) {
month = months[num];
}
return month;
}
/**
* Function to calculate the start day and end day of a given week in a given format
* @param enterWeek Week integer
* @param enterYear Year of date
* @param dateFormat Date format
* @param splitSymbol Symbol to split the two values
* @return
*/
public String getStartEndOFWeek(int enterWeek, int enterYear, String dateFormat, String splitSymbol){
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, enterWeek);
calendar.set(Calendar.YEAR, enterYear);
Date startDate = calendar.getTime();
String startDateInStr = formatter.format(startDate);
calendar.add(Calendar.DATE, 6);
Date enddate = calendar.getTime();
String endDaString = formatter.format(enddate);
DebugLogger.debug("Current week started at - "+startDateInStr+" - ends in - "+endDaString);
return startDateInStr+""+splitSymbol+""+endDaString;
}
/**
* Function to calculate the week number of a given date
* @param inputDate given date
* @param dateFormat date format
* @return Returns the week number of the given date
*/
public int calculateWeekNum(String inputDate, String dateFormat) {
String input = inputDate;
String format = dateFormat;
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = null;
try {
date = df.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
DebugLogger.debug("Weeks number is "+week);
return week;
}
public String getDateFromCalendar(Calendar calendar, String frm){
SimpleDateFormat format = new SimpleDateFormat(frm);
return format.format(calendar.getTime());
}
public Calendar getCalendarFromDate(String date, String format){
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
try {
cal.setTime(sdf.parse(date));// all done
} catch (ParseException e) {
e.printStackTrace();
}
return cal;
}
}
| UTF-8 | Java | 7,892 | java | DatesFunctions.java | Java | [
{
"context": ".Locale;\nimport java.util.Set;\n\n\n/**\n * Created by makis on 1/10/2017.\n */\n\npublic class DatesFunctions {\n",
"end": 286,
"score": 0.9994449615478516,
"start": 281,
"tag": "USERNAME",
"value": "makis"
}
] | null | [] |
import android.content.Context;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* Created by makis on 1/10/2017.
*/
public class DatesFunctions {
private Context mContext;
public DatesFunctions(Context context){
this.mContext = context;
}
/**
* Function to get the number of weeks a month has
* @param month which month we want to check (as integer)
* @param year of which year
* @return
*/
public Integer[] getWeeksOfMonth(int month, int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
Set<Integer> weeks = new HashSet<Integer>();
int ndays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 0; i < ndays; i++) {
weeks.add(cal.get(Calendar.WEEK_OF_YEAR));
cal.add(Calendar.DATE, 1);
}
return weeks.toArray(new Integer[0]);
}
/**
* Compares if Date1 is after Date2 for a date format we want
* @param date1 First date to see if after date2
* @param date2 Second date
* @param format Format that the two above dates are (both dates must be of same format)
* @return Returns true if date1 is after date2, false otherwise
*/
public boolean compareDate1AfterDate2(String date1, String date2, String format){
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date convertedDate1 = null;
Date convertedDate2 = null;
try {
convertedDate1 = dateFormat.parse(date1);
convertedDate2 = dateFormat.parse(date2);
} catch (ParseException e) {
e.printStackTrace();
}
if(convertedDate1!=null && convertedDate2!=null){
if(convertedDate1.after(convertedDate2)){
return true;
}
}
return false;
}
/**
* Function to calculate the difference between two dates of a given format
* @param date_one First date passses
* @param date_two Second date passed
* @param dateFormat The format that the two dates are (both dates must be of the same format)
* @return Returns the days that the two dates differ
*/
public int getDaysDifferenceTwoDates(String date_one, String date_two, String dateFormat) {
int diffint = 0;
try{
SimpleDateFormat date_created = new SimpleDateFormat(dateFormat);
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Date date1 = date_created.parse(date_one);
Date date2 = formatter.parse(date_two);
long diff2 = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff2 / (24 * 60 * 60 * 1000);
diffint = (int) diffDays;
diffint = diffint+1;
}catch (ParseException e1){
e1.printStackTrace();
}
return diffint;
}
/**
* Function to add a specific number of days to a given date of a given format
* @param date Date we want to add the days
* @param format Format of the given date
* @param days Number of days we want to add
* @return Returns the new calculated date in the passed format
*/
public String addDaysToDate(String date, String format, int days){
SimpleDateFormat sdf = new SimpleDateFormat(format);
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, days);
date = sdf.format(c.getTime());
return date;
}
/**
* Function that filters a given date of a given format to a new given format
* @param datestr The date we want to format
* @param inDateFormat The current date format
* @param outDateFormat The new format we want
* @return Returns the given date in the new format if everything went ok, "" otherwise
*/
public String filterDate(String datestr, String inDateFormat, String outDateFormat) {
try{
SimpleDateFormat sdfb = new SimpleDateFormat(inDateFormat);
SimpleDateFormat sdfa = new SimpleDateFormat(outDateFormat);
return sdfa.format(sdfb.parse(datestr));
}catch(Exception ex){
return "";
}
}
/**
* Function to get now date in given format
* @param dateFormat The format we want our date output
* @return Returns now date in given format
*/
public String CDate(String dateFormat){
try{
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date date=new Date();
String cdate=sdf.format(date);
return cdate;
}catch (Exception e){
e.printStackTrace();
return "";
}
}
/**
* Function to get months name based on month int
* @param num
* @return
*/
public String getMonthForInt(int num) {
String month = "wrong";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (num >= 0 && num <= 11 ) {
month = months[num];
}
return month;
}
/**
* Function to calculate the start day and end day of a given week in a given format
* @param enterWeek Week integer
* @param enterYear Year of date
* @param dateFormat Date format
* @param splitSymbol Symbol to split the two values
* @return
*/
public String getStartEndOFWeek(int enterWeek, int enterYear, String dateFormat, String splitSymbol){
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, enterWeek);
calendar.set(Calendar.YEAR, enterYear);
Date startDate = calendar.getTime();
String startDateInStr = formatter.format(startDate);
calendar.add(Calendar.DATE, 6);
Date enddate = calendar.getTime();
String endDaString = formatter.format(enddate);
DebugLogger.debug("Current week started at - "+startDateInStr+" - ends in - "+endDaString);
return startDateInStr+""+splitSymbol+""+endDaString;
}
/**
* Function to calculate the week number of a given date
* @param inputDate given date
* @param dateFormat date format
* @return Returns the week number of the given date
*/
public int calculateWeekNum(String inputDate, String dateFormat) {
String input = inputDate;
String format = dateFormat;
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = null;
try {
date = df.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
DebugLogger.debug("Weeks number is "+week);
return week;
}
public String getDateFromCalendar(Calendar calendar, String frm){
SimpleDateFormat format = new SimpleDateFormat(frm);
return format.format(calendar.getTime());
}
public Calendar getCalendarFromDate(String date, String format){
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
try {
cal.setTime(sdf.parse(date));// all done
} catch (ParseException e) {
e.printStackTrace();
}
return cal;
}
}
| 7,892 | 0.619615 | 0.612519 | 236 | 32.43644 | 25.368307 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.504237 | false | false | 8 |
c6f5ed26d17b41bd2b5ed60828333dff7be68e75 | 33,251,636,822,807 | b175b8ec89e7f6be3443b51c2f7c0c42f7cbae7b | /erp/erpsrc/classes/artifacts/erp_jono/src/service/restapi/UploadWeightService.java | b67ab8134489ee27fc1616a21741173a88565844 | [] | no_license | chenjuntao/jonoerp | https://github.com/chenjuntao/jonoerp | 84230a8681471cac7ccce1251316ab51b3d753b1 | 572994ebe7942b062d91a0802b2c2e2325da2a1d | refs/heads/master | "2021-07-22T00:48:09.648000" | "2020-10-30T04:01:57" | "2020-10-30T04:01:57" | 227,536,826 | 0 | 0 | null | false | "2020-08-27T08:50:21" | "2019-12-12T06:32:23" | "2020-08-27T08:48:49" | "2020-08-27T08:50:20" | 65,342 | 0 | 0 | 1 | JavaScript | false | false | /**
* Copyright (c) 2013
* Tanry Electronic Technology Co., Ltd.
* ChangSha, China
*
* All Rights Reserved.
*
* First created on 2016年3月17日 by cjt
* Last edited on 2016年3月17日 by cjt
*/
package service.restapi;
import com.tanry.framework.acl.NoPrivilegeException;
import logic.NoConnection;
import logic.restapi.WeightBean;
import logic.store.BranchBean;
import org.apache.ibatis.annotations.Param;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import java.util.List;
/**
* 说明:上传重量以及图片
*/
public class UploadWeightService {
private WeightBean weightBean;
public void setWeightBean(WeightBean weightBean) {
this.weightBean = weightBean;
}
//
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public int saveWeight(@Param("myid")String myid,@Param("num")String num,@Param("pic")String pic) throws NoPrivilegeException, SQLException, NoConnection {
return weightBean.saveEntity(myid, num, pic);
}
public List selectTest() throws NoPrivilegeException, SQLException, NoConnection {
return null;
}
}
| UTF-8 | Java | 1,254 | java | UploadWeightService.java | Java | [
{
"context": " Reserved.\r\n * \r\n * First created on 2016年3月17日 by cjt\r\n * Last edited on 2016年3月17日 by cjt\r\n */\r\npackag",
"end": 162,
"score": 0.9973968267440796,
"start": 159,
"tag": "USERNAME",
"value": "cjt"
},
{
"context": "2016年3月17日 by cjt\r\n * Last edited on 2016年3月17日 by cjt\r\n */\r\npackage service.restapi;\r\n\r\nimport com.tanr",
"end": 199,
"score": 0.986236572265625,
"start": 196,
"tag": "USERNAME",
"value": "cjt"
}
] | null | [] | /**
* Copyright (c) 2013
* Tanry Electronic Technology Co., Ltd.
* ChangSha, China
*
* All Rights Reserved.
*
* First created on 2016年3月17日 by cjt
* Last edited on 2016年3月17日 by cjt
*/
package service.restapi;
import com.tanry.framework.acl.NoPrivilegeException;
import logic.NoConnection;
import logic.restapi.WeightBean;
import logic.store.BranchBean;
import org.apache.ibatis.annotations.Param;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.sql.SQLException;
import java.util.List;
/**
* 说明:上传重量以及图片
*/
public class UploadWeightService {
private WeightBean weightBean;
public void setWeightBean(WeightBean weightBean) {
this.weightBean = weightBean;
}
//
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public int saveWeight(@Param("myid")String myid,@Param("num")String num,@Param("pic")String pic) throws NoPrivilegeException, SQLException, NoConnection {
return weightBean.saveEntity(myid, num, pic);
}
public List selectTest() throws NoPrivilegeException, SQLException, NoConnection {
return null;
}
}
| 1,254 | 0.744262 | 0.729508 | 46 | 24.52174 | 29.787464 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.869565 | false | false | 8 |
7e94f9e3f22d75f36891aa24ec9d048630f8324d | 36,730,560,321,396 | dadecfaf88b4ee69915731edbdb3d1dc4da08e4b | /pensionmanager/src/ng/com/justjava/epayment/model/MonthlyUpload.java | 5cd01e09225699c482a5e7fc155c3b4b29679a41 | [] | no_license | JustJavaConsultancyNG/Pension-Contribution-Management-System | https://github.com/JustJavaConsultancyNG/Pension-Contribution-Management-System | 23af826edf925eb61ceed905d153a07ccb3c941b | f1d6a5b20d2cedc02808f8255430ba2b15a2ddbb | refs/heads/master | "2020-04-15T12:43:13.495000" | "2016-09-17T21:57:18" | "2016-09-17T21:57:18" | 63,818,104 | 0 | 2 | null | false | "2016-09-17T21:57:20" | "2016-07-20T22:09:22" | "2016-07-22T22:47:29" | "2016-09-17T21:57:19" | 40,743 | 0 | 2 | 0 | CSS | null | null | package ng.com.justjava.epayment.model;
import java.io.*;
import java.math.*;
import java.rmi.*;
import java.security.*;
import java.text.*;
import java.util.*;
import javax.crypto.*;
import javax.persistence.*;
import org.apache.commons.lang3.*;
import org.openxava.annotations.*;
import org.openxava.jpa.*;
import org.openxava.util.*;
import com.etranzact.fundgate.ws.*;
import ng.com.justjava.epayment.action.*;
import ng.com.justjava.epayment.model.Payment.*;
import ng.com.justjava.epayment.model.RemitPension.Months;
import ng.com.justjava.epayment.utility.*;
import ng.com.justjava.filter.*;
@Views({
@View(members = "uploadYear;month;monthlyFigure;holders"),
@View(name = "approve", members = "companyName;payingAccount;paymentSummary;serviceCharge;totalAmount"),
@View(name = "viewOnly", members = "paymentSummary;serviceCharge;totalAmount") })
@Tabs({
@Tab(properties = "month,narration,status", filter = MultiValueFilter.class, baseCondition = "${deleted}=0 AND ${corporate.id}=? AND ${levelReached}=?"),
@Tab(name = "approve", properties = "narration,dateEntered", filter = MultiValueFilter.class, baseCondition = "${status}=1 AND ${corporate.id}=? AND ${levelReached}=?"),
@Tab(name = "retry", properties = "month,narration,status,paymentResponseCode,paymentResponseDescription", baseCondition = "${deleted}=0 AND ${status} NOT IN (0,1,2,3)"),
@Tab(name = "MyUpload", properties = "month,narration,status,paymentResponseCode,paymentResponseDescription", baseCondition = "${deleted}=0 AND ${corporate.id}=?", filter = LoginUserCorporateFilter.class) })
@Entity
public class MonthlyUpload {
public enum Status {
New, awaitingApproval, approve, reject, sent, paid, errorSending, updated;
}
public enum Type {
corporate, personal;
}
private boolean monthlyFigure;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Hidden
private Long id;
@ManyToOne
@DescriptionsList(descriptionProperties = "year")
@NoCreate
@NoModify
private PeriodYear uploadYear;
public PeriodYear getUploadYear() {
return uploadYear;
}
public void setUploadYear(PeriodYear uploadYear) {
this.uploadYear = uploadYear;
}
@ManyToOne
@NoCreate
@NoModify
@DescriptionsList(depends = "companyName", condition = "${corporate.name}=?", descriptionProperties = "display")
// @OnChange(DisplayBalanceAction.class)
private TransitAccount payingAccount;
@Column(columnDefinition = "tinyint(1) default 0")
@Hidden
private boolean deleted;
@Transient
public String getNarration() {
return month + " Pension Contribution Remittance";
}
private int levelReached;
private Status status;
@ManyToOne
private Corporate corporate;
@Transient
@Stereotype("LABEL")
public String getCompanyName() {
return corporate.getName();
}
@Required
@OnChange(OnChnageMonthlyUpload.class)
// @ReadOnly
private Months month;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "upload")
@ReadOnly
// (forViews="approve")
@ListProperties("fullName,pencommNumber,pfa.name,voluntaryDonation,"
+ "grossPay,pensionAmount[upload.totalAmount],upload.status,variance,remark")
@Condition("${upload.id}=-1")
@RowStyle(style = "row-red", property = "variance", value = "vary")
private Collection<RSAHolder> holders;
private Date dateEntered;
private String enteredBy;
// private
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Collection<PensionFundAdministrator> getSummaryList() {
return summaryList;
}
public void setSummaryList(Collection<PensionFundAdministrator> summaryList) {
this.summaryList = summaryList;
}
public Months getMonth() {
return month;
}
public void setMonth(Months month) {
this.month = month;
}
public Collection<RSAHolder> getHolders() {
return holders;
}
public void setHolders(Collection<RSAHolder> holders) {
this.holders = holders;
}
public Date getDateEntered() {
return dateEntered;
}
public void setDateEntered(Date dateEntered) {
this.dateEntered = dateEntered;
}
public String getEnteredBy() {
return enteredBy;
}
public void setEnteredBy(String enteredBy) {
this.enteredBy = enteredBy;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Corporate getCorporate() {
return corporate;
}
public void setCorporate(Corporate corporate) {
this.corporate = corporate;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getLevelReached() {
return levelReached;
}
public void setLevelReached(int levelReached) {
this.levelReached = levelReached;
}
/*
* public PeriodYear getUploadYear() { return uploadYear; } public void
* setUploadYear(PeriodYear uploadYear) { this.uploadYear = uploadYear; }
*/
@ListProperties("name,totalNumberOfHolders,amountSummation")
@Transient
@ReadOnly
@CollectionView("rsaCompanyHolders")
@RowAction("RowAction.showDetail")
@NoModify
@ViewAction("")
public Collection<PensionFundAdministrator> getPaymentSummary() {
Corporate corporate = getCorporate();
if (corporate == null)
corporate = UserManager.getCorporateOfLoginUser();
String query = " FROM PensionFundAdministrator p "
+ "INNER JOIN p.holders h WHERE h.corporate.id="
+ corporate.getId() + " AND h.upload.id=" + getId();
Collection<Object[]> pfas = null;
Collection<PensionFundAdministrator> list = new ArrayList<PensionFundAdministrator>();
try {
pfas = XPersistence.getManager().createQuery(query).getResultList();
for (Object[] object : pfas) {
PensionFundAdministrator pfa = (PensionFundAdministrator) object[0];
RSAHolder holder = (RSAHolder) object[1];
pfa.addAmountSummation(holder.getPensionAmount());
// totalAmount = totalAmount.add(holder.getPensionAmount());
pfa.addCompanyHolders(holder);
if (!list.contains(pfa)) {
list.add(pfa);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
summaryList = list;
return list;
}
/*
* @Transient private BigDecimal totalAmount=new BigDecimal(0.00);
*/
@Transient
@Stereotype("LABEL")
public BigDecimal getServiceCharge() {
String charges = XavaPreferences.getInstance().getXavaProperty(
"charge", "120.00");
return new BigDecimal(charges);
}
@Transient
@Stereotype("LABEL")
public BigDecimal getTotalAmount() {
if (summaryList == null)
summaryList = getPaymentSummary();
BigDecimal result = new BigDecimal(0.00);
for (PensionFundAdministrator pfa : summaryList) {
result = result.add(pfa.getAmountSummation());
}
result = result.add(getServiceCharge());
return result;
}
@Transient
private Collection<PensionFundAdministrator> summaryList = null;
public TransitAccount getPayingAccount() {
return payingAccount;
}
public void setPayingAccount(TransitAccount payingAccount) {
this.payingAccount = payingAccount;
}
public boolean pay() throws RemoteException {
boolean result = false;
FundResponse response = null;
FundRequest request = getBulkFundRequest();
try {
response = WebserviceUtil.getPort().process(request);
this.setPaymentResponseCode(response.getError());
this.setPaymentResponseDescription(response.getMessage());
this.setPaymentReference(response.getReference());
this.setPaymentOtherReference(response.getOtherReference());
result = response.getError() != null&& "0".equalsIgnoreCase(response.getError().trim());
System.out.println(" The result from eTRanzact =="+result);
if (result) {
result = true;
setStatus(Status.paid);
XPersistence.getManager().merge(this);
}
// XPersistence.commit();
System.out.println("After the call pay");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(" The exception here at eTranzact call ======"
+ e);
e.printStackTrace();
}
if (result) {
List<BulkItem> items = request.getTransaction().getBulkItems()
.getBulkItem();
for (BulkItem item : items) {
PaymentLog log = new PaymentLog();
log.setAmount(item.getAmount());
log.setBeneficiaryAccountName(item.getBeneficiaryName());
log.setBeneficiaryAccountNumber(item.getAccountId());
log.setDate(Dates.createCurrent());
log.setSenderName(getCorporate().getUniqueIdentifier());
log.setTerminalID(getPayingAccount() != null ? getPayingAccount().getTerminalId() : "NOT AVAILABLE");
log.setUniqueId(item.getUniqueId());
log.setOtherReference(response.getOtherReference());
log.setReference(response == null ? "NULL RESPONSE" : response
.getReference());
log.setResponseDescription(response == null ? "NULL RESPONSE"
: response.getMessage());
log.setResponseCode("N");
log.setNarration(item.getNarration());
log.setPayee(getCorporate());
log.setBeneficiary(PensionFundAdministrator
.findPFAByAccountNumber(item.getAccountId()));
log.setUpload(this);
XPersistence.getManager().merge(log);
System.out.println("After merge PaymentLog for "
+ log.getUniqueId() + "...........................");
//sendNotification(log);
}
}
XPersistence.commit();
if (response != null) {
System.out.println("Pay Result Code = " + response.getError());
System.out.println("Pay Result Message = " + response.getMessage());
System.out.println("Pay Result Ref = " + response.getReference());
System.out.println("Pay Result OtherRef = "
+ response.getOtherReference());
System.out.println("Pay Result Amount = " + response.getAmount());
System.out.println("Pay Result TotalFailed = "
+ response.getTotalFailed());
System.out.println("Pay Result TotalSuccess = "
+ response.getTotalSuccess());
System.out.println("Pay Result Company = "
+ response.getCompanyId());
System.out.println("Pay Result Action = " + response.getAction());
}
return result;
}
public FundRequest getBulkFundRequest() {
// List<PaymentInstruction> payItems =
// XPersistence.getManager().createQuery(arg0)
System.out.println("1 Entering getBulkFundRequest beginning");
FundRequest request = null;
request = new FundRequest();
request.setAction("BT");
String terminalId = getPayingAccount() != null ? getPayingAccount()
.getTerminalId() : " ";
String pin = getPayingAccount() != null ? getPayingAccount().getPin()
: " ";
// String uniqueId = corporate.getUniqueIdentifier();
request.setTerminalId(terminalId);
com.etranzact.fundgate.ws.Transaction trans = new com.etranzact.fundgate.ws.Transaction();
trans.setPin(pin);
// trans.setPin("kghxqwveJ3eSQJip/cmaMQ==");
// trans.setPin("ZhXy4geRgnpqVOH/7V2beg==");
// trans.setToken("N");
trans.setReference(getPaymentOtherReference());
trans.setSenderName(corporate.getUniqueIdentifier());
trans.setCompanyId(corporate.getUniqueIdentifier());
trans.setEndPoint("A");
System.out.println("Am in here");
// trans.setSenderName("eTranzact");
// BulkItems bulkItems = new BulkItems();
Collection<PensionFundAdministrator> pfas = getPaymentSummary();
BulkItems bulkItems = new BulkItems();
// List<PaymentInstruction> payItems = (List<PaymentInstruction>)
// getPaymentInstructions();
DecimalFormat format = new DecimalFormat("#.##");
double bulkAmount = 0.00;
for (PensionFundAdministrator payItem : pfas) {
double localAmount = 0.00;
BulkItem item = new BulkItem();
Account account = payItem.getAccount();
if (account != null) {
localAmount = Double.valueOf(format.format(payItem
.getAmountSummation().doubleValue()));
bulkAmount = bulkAmount + localAmount;
String bankCode = (account != null ? account.getBank()
.getCode() : "NOT AVAILABLE");
String accountName = (account != null ? account.getName()
: "NOT AVAILABLE");
String accountNumber = (account != null ? account.getNumber()
: "NOT AVAILABLE");
System.out.println(" Amount for " + payItem.getName() + " is "
+ localAmount + " the destination account code=="
+ bankCode + " and the account number =="
+ accountNumber);
item.setBeneficiaryName(accountName);
item.setAccountId(accountNumber);
item.setAmount(localAmount);
item.setBankCode(StringUtils.trim(bankCode));
item.setNarration(payItem.getId() + "_"
+ corporate.getUniqueIdentifier() + "_" + month);
item.setUniqueId(payItem.getId()
+ "_"
+ RandomStringUtils.randomAlphanumeric(10)
.toLowerCase());
bulkItems.getBulkItem().add(item);
}
}
// if(bankBalance < bulkAmount)
bulkAmount = Double.valueOf(format.format(bulkAmount));
System.out.println(" Bulk Amount ==" + bulkAmount);
trans.setAmount(bulkAmount);// bulk amount
trans.setBulkItems(bulkItems);
// trans.setb
request.setTransaction(trans);
return request;
}
private Type type;
@PostCreate
@PostPersist
@PostUpdate
public void setTheType() {
if (getType() == null) {
setType(Type.corporate);
}
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getPaymentResponseCode() {
return paymentResponseCode;
}
public void setPaymentResponseCode(String paymentResponseCode) {
this.paymentResponseCode = paymentResponseCode;
}
public String getPaymentResponseDescription() {
return paymentResponseDescription;
}
public void setPaymentResponseDescription(String paymentResponseDescription) {
this.paymentResponseDescription = paymentResponseDescription;
}
public String getPaymentReference() {
return paymentReference;
}
public void setPaymentReference(String paymentReference) {
this.paymentReference = paymentReference;
}
public String getPaymentOtherReference() {
return paymentOtherReference;
}
public void setPaymentOtherReference(String paymentOtherReference) {
this.paymentOtherReference = paymentOtherReference;
}
public boolean isMonthlyFigure() {
return monthlyFigure;
}
public void setMonthlyFigure(boolean monthlyFigure) {
this.monthlyFigure = monthlyFigure;
}
public boolean updateStatuseTranzact() {
FundResponse response = null;
boolean result = false;
try {
System.out
.println(" About to call a webservice here for bulk query=====");
response = WebserviceUtil.getPort().process(
getBulkFundRequest("BQ"));
System.out.println("Status Result Code = " + response.getError());
System.out.println("Status Result Message = "
+ response.getMessage());
System.out
.println("Status Result Ref = " + response.getReference());
System.out.println("Status Result OtherRef = "
+ response.getOtherReference());
System.out
.println("Status Result Amount = " + response.getAmount());
System.out.println("Status Result TotalFailed = "
+ response.getTotalFailed());
System.out.println("Status Result TotalSuccess = "
+ response.getTotalSuccess());
System.out.println("Status Result Company = "
+ response.getCompanyId());
System.out
.println("Status Result Action = " + response.getAction());
if (response.getBulkItems() == null)
return false;
for (BulkItem item : response.getBulkItems().getBulkItem()) {
System.out
.println(" The Unique id Here ========================================="
+ item.getUniqueId());
String id = item.getUniqueId() != null ? item.getUniqueId()
.split("_")[0] : "0";
System.out
.println(" The id here ========================================="
+ id);
PaymentLog log = PaymentLog.getPaymentLogByUniqueId(item
.getUniqueId());
if (log != null) {
log.setResponseDescription(item.getMessage());
log.setResponseCode(item.getStatus());
log.setOtherReference(getPaymentOtherReference());
log.setReference(getPaymentReference());
XPersistence.getManager().merge(log);
}
}
// this.setErrorCode(response.getError());
// this.setErrorMessage(response.getMessage());
result = true;
XPersistence.getManager().merge(this);
XPersistence.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@Transient
public FundRequest getBulkFundRequest(String action) {
// List<PaymentInstruction> payItems =
// XPersistence.getManager().createQuery(arg0)
FundRequest request = new FundRequest();
request.setAction(action);
Corporate corporate = (Corporate) this.getCorporate();
String terminalId = payingAccount.getTerminalId();
String pin = payingAccount.getPin();
String uniqueId = corporate.getUniqueIdentifier();
request.setTerminalId(terminalId);
com.etranzact.fundgate.ws.Transaction trans = new com.etranzact.fundgate.ws.Transaction();
// "ZhXy4geRgnpqVOH/7V2beg=="
trans.setPin(pin);
// trans.setPin("ZhXy4geRgnpqVOH/7V2beg==");
trans.setToken("N");
// trans.setReference(this.getReferenceId());
try {
// trans.setReference(Cryptor.generateKey());
// trans.setReference("y41A1ggg0CE5ddddde");//+StringUtils.trim(RandomStringUtils.randomAlphanumeric(3)));
trans.setReference(RandomStringUtils.randomAlphanumeric(18)
.toLowerCase());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println("/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n The parameters are ===="
+ "terminalId=="
+ terminalId
+ " and pin=="
+ pin
+ " and uniqueId=="
+ uniqueId
+ " the reference==="
+ trans.getReference() + " the action here ==" + action);
// trans.setCompanyId(getOwner().getName());
// "00000000000000000018"
trans.setCompanyId(uniqueId);
trans.setSenderName(getCorporate().getName());
// trans.setSenderName("eTranzact");
if ("BQ".equalsIgnoreCase(action.trim())) {
trans.setEndPoint("I");
// trans.setReference(getQueryString());
}
BulkItems bulkItems = new BulkItems();
Collection<PensionFundAdministrator> payItems = (List<PensionFundAdministrator>) getPaymentSummary();
DecimalFormat format = new DecimalFormat("#.##");
double bulkAmount = 0.00;
for (PensionFundAdministrator payItem : payItems) {
double localAmount = 0.00;
BulkItem item = new BulkItem();
Account account = payItem.getAccount();
if (account != null) {
localAmount = Double.valueOf(format.format(payItem
.getAmountSummation().doubleValue()));
bulkAmount = bulkAmount + localAmount;
String bankCode = (account != null ? account.getBank()
.getCode() : "NOT AVAILABLE");
String accountName = (account != null ? account.getName()
: "NOT AVAILABLE");
String accountNumber = (account != null ? account.getNumber()
: "NOT AVAILABLE");
System.out.println(" Amount for " + payItem.getName() + " is "
+ localAmount + " the destination account code=="
+ bankCode + " and the account number =="
+ accountNumber);
item.setBeneficiaryName(accountName);
item.setAccountId(accountNumber);
item.setAmount(localAmount);
item.setBankCode(StringUtils.trim(bankCode));
item.setNarration(payItem.getId() + "_"
+ corporate.getUniqueIdentifier() + "_" + month);
// item.setUniqueId(payItem.getId() + "_" +
// RandomStringUtils.randomAlphanumeric(10).toLowerCase());
bulkItems.getBulkItem().add(item);
}
}
// if(bankBalance < bulkAmount)
bulkAmount = Double.valueOf(format.format(bulkAmount));
System.out.println(" Bulk Amount ==" + bulkAmount);
trans.setAmount(bulkAmount);// bulk amount
trans.setBulkItems(bulkItems);
// trans.setb
request.setTransaction(trans);
return request;
}
public Profile getAwaitingApprovalProfile(){
Profile profile = null;
System.out.println(" Inside getAwaitingApprovalProfile =="+Status.awaitingApproval);
if(getStatus() != Status.awaitingApproval)
return null;
try {
System.out.println(" SQL ==="+" FROM Profile p WHERE p.transaction=0 AND p.level="+getLevelReached());
profile = (Profile) XPersistence.getManager().
createQuery("FROM Profile p WHERE p.transaction=0 AND p.level="+getLevelReached()).
getSingleResult();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return profile;
}
private String paymentResponseCode;
private String paymentResponseDescription;
private String paymentReference;
private String paymentOtherReference;
public void sendNotification() {
System.out.println(" Inside Notification of send for approval....");
if(getAwaitingApprovalProfile() ==null)
return;
Collection<CorporateUser> users = getAwaitingApprovalProfile().getUsers();
System.out.println(" Inside Notification of send for approval....");
for (CorporateUser corporateUser : users) {
MailManager notification = new MailManager();
notification.setContent("Dear "+corporateUser.getUser().getGivenName()+
" Pension Contribution for Month "+getMonth()+
" Is Awaiting Your Approval");
notification.setPhoneNumber(corporateUser.getUser().getPhoneNumber());
notification.setSubject("Pension Transaction Awaiting Approval");
notification.setToAddress(corporateUser.getUser().getEmail());
System.out.println(" The notification is hereby persisted..");
XPersistence.getManager().merge(notification);
}
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 21,460 | java | MonthlyUpload.java | Java | [
{
"context": "println(\"Am in here\");\n\n\t\t// trans.setSenderName(\"eTranzact\");\n\n\t\t// BulkItems bulkItems = new BulkItems();\n\n",
"end": 11042,
"score": 0.7315046787261963,
"start": 11033,
"tag": "USERNAME",
"value": "eTranzact"
},
{
"context": "\t\t\t\t+ accountNumber);\n\t\t\t\titem.setBeneficiaryName(accountName);\n\t\t\t\titem.setAccountId(accountNumber);\n\t\t\t\ti",
"end": 12214,
"score": 0.8182598948478699,
"start": 12207,
"tag": "NAME",
"value": "account"
},
{
"context": "Corporate().getName());\n\t\t// trans.setSenderName(\"eTranzact\");\n\t\tif (\"BQ\".equalsIgnoreCase(action.trim())) {\n",
"end": 17849,
"score": 0.9989727139472961,
"start": 17840,
"tag": "USERNAME",
"value": "eTranzact"
}
] | null | [] | package ng.com.justjava.epayment.model;
import java.io.*;
import java.math.*;
import java.rmi.*;
import java.security.*;
import java.text.*;
import java.util.*;
import javax.crypto.*;
import javax.persistence.*;
import org.apache.commons.lang3.*;
import org.openxava.annotations.*;
import org.openxava.jpa.*;
import org.openxava.util.*;
import com.etranzact.fundgate.ws.*;
import ng.com.justjava.epayment.action.*;
import ng.com.justjava.epayment.model.Payment.*;
import ng.com.justjava.epayment.model.RemitPension.Months;
import ng.com.justjava.epayment.utility.*;
import ng.com.justjava.filter.*;
@Views({
@View(members = "uploadYear;month;monthlyFigure;holders"),
@View(name = "approve", members = "companyName;payingAccount;paymentSummary;serviceCharge;totalAmount"),
@View(name = "viewOnly", members = "paymentSummary;serviceCharge;totalAmount") })
@Tabs({
@Tab(properties = "month,narration,status", filter = MultiValueFilter.class, baseCondition = "${deleted}=0 AND ${corporate.id}=? AND ${levelReached}=?"),
@Tab(name = "approve", properties = "narration,dateEntered", filter = MultiValueFilter.class, baseCondition = "${status}=1 AND ${corporate.id}=? AND ${levelReached}=?"),
@Tab(name = "retry", properties = "month,narration,status,paymentResponseCode,paymentResponseDescription", baseCondition = "${deleted}=0 AND ${status} NOT IN (0,1,2,3)"),
@Tab(name = "MyUpload", properties = "month,narration,status,paymentResponseCode,paymentResponseDescription", baseCondition = "${deleted}=0 AND ${corporate.id}=?", filter = LoginUserCorporateFilter.class) })
@Entity
public class MonthlyUpload {
public enum Status {
New, awaitingApproval, approve, reject, sent, paid, errorSending, updated;
}
public enum Type {
corporate, personal;
}
private boolean monthlyFigure;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Hidden
private Long id;
@ManyToOne
@DescriptionsList(descriptionProperties = "year")
@NoCreate
@NoModify
private PeriodYear uploadYear;
public PeriodYear getUploadYear() {
return uploadYear;
}
public void setUploadYear(PeriodYear uploadYear) {
this.uploadYear = uploadYear;
}
@ManyToOne
@NoCreate
@NoModify
@DescriptionsList(depends = "companyName", condition = "${corporate.name}=?", descriptionProperties = "display")
// @OnChange(DisplayBalanceAction.class)
private TransitAccount payingAccount;
@Column(columnDefinition = "tinyint(1) default 0")
@Hidden
private boolean deleted;
@Transient
public String getNarration() {
return month + " Pension Contribution Remittance";
}
private int levelReached;
private Status status;
@ManyToOne
private Corporate corporate;
@Transient
@Stereotype("LABEL")
public String getCompanyName() {
return corporate.getName();
}
@Required
@OnChange(OnChnageMonthlyUpload.class)
// @ReadOnly
private Months month;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "upload")
@ReadOnly
// (forViews="approve")
@ListProperties("fullName,pencommNumber,pfa.name,voluntaryDonation,"
+ "grossPay,pensionAmount[upload.totalAmount],upload.status,variance,remark")
@Condition("${upload.id}=-1")
@RowStyle(style = "row-red", property = "variance", value = "vary")
private Collection<RSAHolder> holders;
private Date dateEntered;
private String enteredBy;
// private
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Collection<PensionFundAdministrator> getSummaryList() {
return summaryList;
}
public void setSummaryList(Collection<PensionFundAdministrator> summaryList) {
this.summaryList = summaryList;
}
public Months getMonth() {
return month;
}
public void setMonth(Months month) {
this.month = month;
}
public Collection<RSAHolder> getHolders() {
return holders;
}
public void setHolders(Collection<RSAHolder> holders) {
this.holders = holders;
}
public Date getDateEntered() {
return dateEntered;
}
public void setDateEntered(Date dateEntered) {
this.dateEntered = dateEntered;
}
public String getEnteredBy() {
return enteredBy;
}
public void setEnteredBy(String enteredBy) {
this.enteredBy = enteredBy;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Corporate getCorporate() {
return corporate;
}
public void setCorporate(Corporate corporate) {
this.corporate = corporate;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getLevelReached() {
return levelReached;
}
public void setLevelReached(int levelReached) {
this.levelReached = levelReached;
}
/*
* public PeriodYear getUploadYear() { return uploadYear; } public void
* setUploadYear(PeriodYear uploadYear) { this.uploadYear = uploadYear; }
*/
@ListProperties("name,totalNumberOfHolders,amountSummation")
@Transient
@ReadOnly
@CollectionView("rsaCompanyHolders")
@RowAction("RowAction.showDetail")
@NoModify
@ViewAction("")
public Collection<PensionFundAdministrator> getPaymentSummary() {
Corporate corporate = getCorporate();
if (corporate == null)
corporate = UserManager.getCorporateOfLoginUser();
String query = " FROM PensionFundAdministrator p "
+ "INNER JOIN p.holders h WHERE h.corporate.id="
+ corporate.getId() + " AND h.upload.id=" + getId();
Collection<Object[]> pfas = null;
Collection<PensionFundAdministrator> list = new ArrayList<PensionFundAdministrator>();
try {
pfas = XPersistence.getManager().createQuery(query).getResultList();
for (Object[] object : pfas) {
PensionFundAdministrator pfa = (PensionFundAdministrator) object[0];
RSAHolder holder = (RSAHolder) object[1];
pfa.addAmountSummation(holder.getPensionAmount());
// totalAmount = totalAmount.add(holder.getPensionAmount());
pfa.addCompanyHolders(holder);
if (!list.contains(pfa)) {
list.add(pfa);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
summaryList = list;
return list;
}
/*
* @Transient private BigDecimal totalAmount=new BigDecimal(0.00);
*/
@Transient
@Stereotype("LABEL")
public BigDecimal getServiceCharge() {
String charges = XavaPreferences.getInstance().getXavaProperty(
"charge", "120.00");
return new BigDecimal(charges);
}
@Transient
@Stereotype("LABEL")
public BigDecimal getTotalAmount() {
if (summaryList == null)
summaryList = getPaymentSummary();
BigDecimal result = new BigDecimal(0.00);
for (PensionFundAdministrator pfa : summaryList) {
result = result.add(pfa.getAmountSummation());
}
result = result.add(getServiceCharge());
return result;
}
@Transient
private Collection<PensionFundAdministrator> summaryList = null;
public TransitAccount getPayingAccount() {
return payingAccount;
}
public void setPayingAccount(TransitAccount payingAccount) {
this.payingAccount = payingAccount;
}
public boolean pay() throws RemoteException {
boolean result = false;
FundResponse response = null;
FundRequest request = getBulkFundRequest();
try {
response = WebserviceUtil.getPort().process(request);
this.setPaymentResponseCode(response.getError());
this.setPaymentResponseDescription(response.getMessage());
this.setPaymentReference(response.getReference());
this.setPaymentOtherReference(response.getOtherReference());
result = response.getError() != null&& "0".equalsIgnoreCase(response.getError().trim());
System.out.println(" The result from eTRanzact =="+result);
if (result) {
result = true;
setStatus(Status.paid);
XPersistence.getManager().merge(this);
}
// XPersistence.commit();
System.out.println("After the call pay");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(" The exception here at eTranzact call ======"
+ e);
e.printStackTrace();
}
if (result) {
List<BulkItem> items = request.getTransaction().getBulkItems()
.getBulkItem();
for (BulkItem item : items) {
PaymentLog log = new PaymentLog();
log.setAmount(item.getAmount());
log.setBeneficiaryAccountName(item.getBeneficiaryName());
log.setBeneficiaryAccountNumber(item.getAccountId());
log.setDate(Dates.createCurrent());
log.setSenderName(getCorporate().getUniqueIdentifier());
log.setTerminalID(getPayingAccount() != null ? getPayingAccount().getTerminalId() : "NOT AVAILABLE");
log.setUniqueId(item.getUniqueId());
log.setOtherReference(response.getOtherReference());
log.setReference(response == null ? "NULL RESPONSE" : response
.getReference());
log.setResponseDescription(response == null ? "NULL RESPONSE"
: response.getMessage());
log.setResponseCode("N");
log.setNarration(item.getNarration());
log.setPayee(getCorporate());
log.setBeneficiary(PensionFundAdministrator
.findPFAByAccountNumber(item.getAccountId()));
log.setUpload(this);
XPersistence.getManager().merge(log);
System.out.println("After merge PaymentLog for "
+ log.getUniqueId() + "...........................");
//sendNotification(log);
}
}
XPersistence.commit();
if (response != null) {
System.out.println("Pay Result Code = " + response.getError());
System.out.println("Pay Result Message = " + response.getMessage());
System.out.println("Pay Result Ref = " + response.getReference());
System.out.println("Pay Result OtherRef = "
+ response.getOtherReference());
System.out.println("Pay Result Amount = " + response.getAmount());
System.out.println("Pay Result TotalFailed = "
+ response.getTotalFailed());
System.out.println("Pay Result TotalSuccess = "
+ response.getTotalSuccess());
System.out.println("Pay Result Company = "
+ response.getCompanyId());
System.out.println("Pay Result Action = " + response.getAction());
}
return result;
}
public FundRequest getBulkFundRequest() {
// List<PaymentInstruction> payItems =
// XPersistence.getManager().createQuery(arg0)
System.out.println("1 Entering getBulkFundRequest beginning");
FundRequest request = null;
request = new FundRequest();
request.setAction("BT");
String terminalId = getPayingAccount() != null ? getPayingAccount()
.getTerminalId() : " ";
String pin = getPayingAccount() != null ? getPayingAccount().getPin()
: " ";
// String uniqueId = corporate.getUniqueIdentifier();
request.setTerminalId(terminalId);
com.etranzact.fundgate.ws.Transaction trans = new com.etranzact.fundgate.ws.Transaction();
trans.setPin(pin);
// trans.setPin("kghxqwveJ3eSQJip/cmaMQ==");
// trans.setPin("ZhXy4geRgnpqVOH/7V2beg==");
// trans.setToken("N");
trans.setReference(getPaymentOtherReference());
trans.setSenderName(corporate.getUniqueIdentifier());
trans.setCompanyId(corporate.getUniqueIdentifier());
trans.setEndPoint("A");
System.out.println("Am in here");
// trans.setSenderName("eTranzact");
// BulkItems bulkItems = new BulkItems();
Collection<PensionFundAdministrator> pfas = getPaymentSummary();
BulkItems bulkItems = new BulkItems();
// List<PaymentInstruction> payItems = (List<PaymentInstruction>)
// getPaymentInstructions();
DecimalFormat format = new DecimalFormat("#.##");
double bulkAmount = 0.00;
for (PensionFundAdministrator payItem : pfas) {
double localAmount = 0.00;
BulkItem item = new BulkItem();
Account account = payItem.getAccount();
if (account != null) {
localAmount = Double.valueOf(format.format(payItem
.getAmountSummation().doubleValue()));
bulkAmount = bulkAmount + localAmount;
String bankCode = (account != null ? account.getBank()
.getCode() : "NOT AVAILABLE");
String accountName = (account != null ? account.getName()
: "NOT AVAILABLE");
String accountNumber = (account != null ? account.getNumber()
: "NOT AVAILABLE");
System.out.println(" Amount for " + payItem.getName() + " is "
+ localAmount + " the destination account code=="
+ bankCode + " and the account number =="
+ accountNumber);
item.setBeneficiaryName(accountName);
item.setAccountId(accountNumber);
item.setAmount(localAmount);
item.setBankCode(StringUtils.trim(bankCode));
item.setNarration(payItem.getId() + "_"
+ corporate.getUniqueIdentifier() + "_" + month);
item.setUniqueId(payItem.getId()
+ "_"
+ RandomStringUtils.randomAlphanumeric(10)
.toLowerCase());
bulkItems.getBulkItem().add(item);
}
}
// if(bankBalance < bulkAmount)
bulkAmount = Double.valueOf(format.format(bulkAmount));
System.out.println(" Bulk Amount ==" + bulkAmount);
trans.setAmount(bulkAmount);// bulk amount
trans.setBulkItems(bulkItems);
// trans.setb
request.setTransaction(trans);
return request;
}
private Type type;
@PostCreate
@PostPersist
@PostUpdate
public void setTheType() {
if (getType() == null) {
setType(Type.corporate);
}
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public String getPaymentResponseCode() {
return paymentResponseCode;
}
public void setPaymentResponseCode(String paymentResponseCode) {
this.paymentResponseCode = paymentResponseCode;
}
public String getPaymentResponseDescription() {
return paymentResponseDescription;
}
public void setPaymentResponseDescription(String paymentResponseDescription) {
this.paymentResponseDescription = paymentResponseDescription;
}
public String getPaymentReference() {
return paymentReference;
}
public void setPaymentReference(String paymentReference) {
this.paymentReference = paymentReference;
}
public String getPaymentOtherReference() {
return paymentOtherReference;
}
public void setPaymentOtherReference(String paymentOtherReference) {
this.paymentOtherReference = paymentOtherReference;
}
public boolean isMonthlyFigure() {
return monthlyFigure;
}
public void setMonthlyFigure(boolean monthlyFigure) {
this.monthlyFigure = monthlyFigure;
}
public boolean updateStatuseTranzact() {
FundResponse response = null;
boolean result = false;
try {
System.out
.println(" About to call a webservice here for bulk query=====");
response = WebserviceUtil.getPort().process(
getBulkFundRequest("BQ"));
System.out.println("Status Result Code = " + response.getError());
System.out.println("Status Result Message = "
+ response.getMessage());
System.out
.println("Status Result Ref = " + response.getReference());
System.out.println("Status Result OtherRef = "
+ response.getOtherReference());
System.out
.println("Status Result Amount = " + response.getAmount());
System.out.println("Status Result TotalFailed = "
+ response.getTotalFailed());
System.out.println("Status Result TotalSuccess = "
+ response.getTotalSuccess());
System.out.println("Status Result Company = "
+ response.getCompanyId());
System.out
.println("Status Result Action = " + response.getAction());
if (response.getBulkItems() == null)
return false;
for (BulkItem item : response.getBulkItems().getBulkItem()) {
System.out
.println(" The Unique id Here ========================================="
+ item.getUniqueId());
String id = item.getUniqueId() != null ? item.getUniqueId()
.split("_")[0] : "0";
System.out
.println(" The id here ========================================="
+ id);
PaymentLog log = PaymentLog.getPaymentLogByUniqueId(item
.getUniqueId());
if (log != null) {
log.setResponseDescription(item.getMessage());
log.setResponseCode(item.getStatus());
log.setOtherReference(getPaymentOtherReference());
log.setReference(getPaymentReference());
XPersistence.getManager().merge(log);
}
}
// this.setErrorCode(response.getError());
// this.setErrorMessage(response.getMessage());
result = true;
XPersistence.getManager().merge(this);
XPersistence.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
@Transient
public FundRequest getBulkFundRequest(String action) {
// List<PaymentInstruction> payItems =
// XPersistence.getManager().createQuery(arg0)
FundRequest request = new FundRequest();
request.setAction(action);
Corporate corporate = (Corporate) this.getCorporate();
String terminalId = payingAccount.getTerminalId();
String pin = payingAccount.getPin();
String uniqueId = corporate.getUniqueIdentifier();
request.setTerminalId(terminalId);
com.etranzact.fundgate.ws.Transaction trans = new com.etranzact.fundgate.ws.Transaction();
// "ZhXy4geRgnpqVOH/7V2beg=="
trans.setPin(pin);
// trans.setPin("ZhXy4geRgnpqVOH/7V2beg==");
trans.setToken("N");
// trans.setReference(this.getReferenceId());
try {
// trans.setReference(Cryptor.generateKey());
// trans.setReference("y41A1ggg0CE5ddddde");//+StringUtils.trim(RandomStringUtils.randomAlphanumeric(3)));
trans.setReference(RandomStringUtils.randomAlphanumeric(18)
.toLowerCase());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println("/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n/n The parameters are ===="
+ "terminalId=="
+ terminalId
+ " and pin=="
+ pin
+ " and uniqueId=="
+ uniqueId
+ " the reference==="
+ trans.getReference() + " the action here ==" + action);
// trans.setCompanyId(getOwner().getName());
// "00000000000000000018"
trans.setCompanyId(uniqueId);
trans.setSenderName(getCorporate().getName());
// trans.setSenderName("eTranzact");
if ("BQ".equalsIgnoreCase(action.trim())) {
trans.setEndPoint("I");
// trans.setReference(getQueryString());
}
BulkItems bulkItems = new BulkItems();
Collection<PensionFundAdministrator> payItems = (List<PensionFundAdministrator>) getPaymentSummary();
DecimalFormat format = new DecimalFormat("#.##");
double bulkAmount = 0.00;
for (PensionFundAdministrator payItem : payItems) {
double localAmount = 0.00;
BulkItem item = new BulkItem();
Account account = payItem.getAccount();
if (account != null) {
localAmount = Double.valueOf(format.format(payItem
.getAmountSummation().doubleValue()));
bulkAmount = bulkAmount + localAmount;
String bankCode = (account != null ? account.getBank()
.getCode() : "NOT AVAILABLE");
String accountName = (account != null ? account.getName()
: "NOT AVAILABLE");
String accountNumber = (account != null ? account.getNumber()
: "NOT AVAILABLE");
System.out.println(" Amount for " + payItem.getName() + " is "
+ localAmount + " the destination account code=="
+ bankCode + " and the account number =="
+ accountNumber);
item.setBeneficiaryName(accountName);
item.setAccountId(accountNumber);
item.setAmount(localAmount);
item.setBankCode(StringUtils.trim(bankCode));
item.setNarration(payItem.getId() + "_"
+ corporate.getUniqueIdentifier() + "_" + month);
// item.setUniqueId(payItem.getId() + "_" +
// RandomStringUtils.randomAlphanumeric(10).toLowerCase());
bulkItems.getBulkItem().add(item);
}
}
// if(bankBalance < bulkAmount)
bulkAmount = Double.valueOf(format.format(bulkAmount));
System.out.println(" Bulk Amount ==" + bulkAmount);
trans.setAmount(bulkAmount);// bulk amount
trans.setBulkItems(bulkItems);
// trans.setb
request.setTransaction(trans);
return request;
}
public Profile getAwaitingApprovalProfile(){
Profile profile = null;
System.out.println(" Inside getAwaitingApprovalProfile =="+Status.awaitingApproval);
if(getStatus() != Status.awaitingApproval)
return null;
try {
System.out.println(" SQL ==="+" FROM Profile p WHERE p.transaction=0 AND p.level="+getLevelReached());
profile = (Profile) XPersistence.getManager().
createQuery("FROM Profile p WHERE p.transaction=0 AND p.level="+getLevelReached()).
getSingleResult();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return profile;
}
private String paymentResponseCode;
private String paymentResponseDescription;
private String paymentReference;
private String paymentOtherReference;
public void sendNotification() {
System.out.println(" Inside Notification of send for approval....");
if(getAwaitingApprovalProfile() ==null)
return;
Collection<CorporateUser> users = getAwaitingApprovalProfile().getUsers();
System.out.println(" Inside Notification of send for approval....");
for (CorporateUser corporateUser : users) {
MailManager notification = new MailManager();
notification.setContent("Dear "+corporateUser.getUser().getGivenName()+
" Pension Contribution for Month "+getMonth()+
" Is Awaiting Your Approval");
notification.setPhoneNumber(corporateUser.getUser().getPhoneNumber());
notification.setSubject("Pension Transaction Awaiting Approval");
notification.setToAddress(corporateUser.getUser().getEmail());
System.out.println(" The notification is hereby persisted..");
XPersistence.getManager().merge(notification);
}
// TODO Auto-generated method stub
}
}
| 21,460 | 0.703588 | 0.699534 | 729 | 28.437586 | 26.37925 | 209 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.484225 | false | false | 8 |
b91b8e2546cf446d07388658c05fd8efbf737c95 | 26,431,228,786,155 | 5f0c5e48d7d2e1405fc6a2d07320c6c1ca193da3 | /src/main/java/com/hangzhou/tfchen/configuration/AddInterceptor.java | dcbbfa4a64865c174d43049caef95a51d7c8f85b | [] | no_license | tfchen2400/javaEden | https://github.com/tfchen2400/javaEden | 0777fabf906416ec0be522c0bf4019b7fd3a473d | d805e1c6ee9d05221c2f559d515faef8c3bd66ea | refs/heads/master | "2018-05-15T08:07:42.483000" | "2017-07-07T06:28:33" | "2017-07-07T06:35:58" | 92,807,354 | 1 | 1 | null | false | "2017-07-07T06:35:59" | "2017-05-30T07:14:42" | "2017-07-06T02:43:19" | "2017-07-07T06:35:59" | 23 | 1 | 1 | 0 | Java | null | null | package com.hangzhou.tfchen.configuration;
import com.hangzhou.tfchen.filter.UserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author chentf(水言Dade)
* @e-mail tfchen5211@foxmail.com
* @date 2017/6/3 23:15
* @描述:
* @注意事项:
*/
@Configuration
public class AddInterceptor extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserInterceptor()).addPathPatterns("/*");
}
}
| UTF-8 | Java | 689 | java | AddInterceptor.java | Java | [
{
"context": "nnotation.WebMvcConfigurerAdapter;\n\n/**\n * @author chentf(水言Dade)\n * @e-mail tfchen5211@foxmail.com\n * @dat",
"end": 338,
"score": 0.999699056148529,
"start": 332,
"tag": "USERNAME",
"value": "chentf"
},
{
"context": "n.WebMvcConfigurerAdapter;\n\n/**\n * @author chentf(水言Dade)\n * @e-mail tfchen5211@foxmail.com\n * @date 2017/",
"end": 345,
"score": 0.990330159664154,
"start": 339,
"tag": "NAME",
"value": "水言Dade"
},
{
"context": "Adapter;\n\n/**\n * @author chentf(水言Dade)\n * @e-mail tfchen5211@foxmail.com\n * @date 2017/6/3 23:15\n * @描述:\n * @注意事项:\n */\n@Co",
"end": 380,
"score": 0.9999287128448486,
"start": 358,
"tag": "EMAIL",
"value": "tfchen5211@foxmail.com"
}
] | null | [] | package com.hangzhou.tfchen.configuration;
import com.hangzhou.tfchen.filter.UserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author chentf(水言Dade)
* @e-mail <EMAIL>
* @date 2017/6/3 23:15
* @描述:
* @注意事项:
*/
@Configuration
public class AddInterceptor extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserInterceptor()).addPathPatterns("/*");
}
}
| 674 | 0.781764 | 0.760837 | 22 | 29.40909 | 28.386391 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 8 |
40c8e6640da2c7f60b4301c41dd9e1e42ae0792b | 34,497,177,337,721 | c7b88eb2cf348c944fffde7e5f3f159f8139a867 | /src/test/java/integration/stepdefs/CommonStepDefinitions.java | 32630645fca6eae8651d9b12c483e66a67c8cf92 | [] | no_license | fabiodomingues/api-testing | https://github.com/fabiodomingues/api-testing | 7ea912074d474e7bcfdc17512d7838fa12cf078f | 17fce2c4ebfc865877d09c2fb1a1b536eaa370c7 | refs/heads/master | "2020-03-30T08:14:42.129000" | "2018-10-02T22:44:16" | "2018-10-02T22:44:16" | 151,000,239 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package integration.stepdefs;
import com.google.inject.Inject;
import cucumber.api.java.en.Then;
import integration.common.ApiTestContext;
import io.restassured.http.ContentType;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
public class CommonStepDefinitions {
@Inject
private ApiTestContext apiTestContext;
@Then("^the status code of response should be (\\d+)$")
public void then_the_status_code_of_response_should_be(Integer statusCode) {
apiTestContext.getResponse().then().statusCode(statusCode);
}
@Then("^content type should be in JSON format$")
public void then_content_type_should_be_in_JSON_format() {
apiTestContext.getResponse().then().assertThat().contentType(ContentType.JSON);
}
@Then("^response body attribute (.*) should not be null$")
public void then_response_body_attribute_should_not_be_null(String attribute) {
apiTestContext.getResponse().then().body(attribute, not(isEmptyOrNullString()));
}
@Then("^response body attribute (.*) should be equals \"(.*)\"$")
public void then_response_body_attribute_should_be_equals(String attribute, String value) {
apiTestContext.getResponse().then().body(attribute, equalTo(value));
}
@Then("^response body attribute (.*) should be null$")
public void response_body_attribute_should_be_null(String attribute) {
apiTestContext.getResponse().then().body(attribute, isEmptyOrNullString());
}
}
| UTF-8 | Java | 1,565 | java | CommonStepDefinitions.java | Java | [] | null | [] | package integration.stepdefs;
import com.google.inject.Inject;
import cucumber.api.java.en.Then;
import integration.common.ApiTestContext;
import io.restassured.http.ContentType;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.hamcrest.Matchers.not;
public class CommonStepDefinitions {
@Inject
private ApiTestContext apiTestContext;
@Then("^the status code of response should be (\\d+)$")
public void then_the_status_code_of_response_should_be(Integer statusCode) {
apiTestContext.getResponse().then().statusCode(statusCode);
}
@Then("^content type should be in JSON format$")
public void then_content_type_should_be_in_JSON_format() {
apiTestContext.getResponse().then().assertThat().contentType(ContentType.JSON);
}
@Then("^response body attribute (.*) should not be null$")
public void then_response_body_attribute_should_not_be_null(String attribute) {
apiTestContext.getResponse().then().body(attribute, not(isEmptyOrNullString()));
}
@Then("^response body attribute (.*) should be equals \"(.*)\"$")
public void then_response_body_attribute_should_be_equals(String attribute, String value) {
apiTestContext.getResponse().then().body(attribute, equalTo(value));
}
@Then("^response body attribute (.*) should be null$")
public void response_body_attribute_should_be_null(String attribute) {
apiTestContext.getResponse().then().body(attribute, isEmptyOrNullString());
}
}
| 1,565 | 0.722684 | 0.722684 | 41 | 37.170731 | 31.907566 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.439024 | false | false | 8 |
da57b982eceb00028d23668c50d7f9254f855e9f | 1,425,929,185,546 | 80452ab838652b27118848ca2266f9fde56ce03f | /app/src/main/java/bola/wiradipa/org/lapanganbola/DetailFieldActivity.java | b56d6a4ced0f2eb707ecefda35270d63bc5ea27a | [] | no_license | CruthOver/UserLapangBola | https://github.com/CruthOver/UserLapangBola | bf5f294ed5e7ca4defdeb8649ecb17ba03cedd23 | 7d40a422c4cb3e1927661682aa62415210cbac3e | refs/heads/master | "2020-04-17T20:59:27.652000" | "2019-02-18T09:44:37" | "2019-02-18T09:44:37" | 166,927,156 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bola.wiradipa.org.lapanganbola;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import bola.wiradipa.org.lapanganbola.controllers.BaseActivity;
import bola.wiradipa.org.lapanganbola.helpers.AppSession;
import bola.wiradipa.org.lapanganbola.helpers.DateHelper;
import bola.wiradipa.org.lapanganbola.helpers.Log;
import bola.wiradipa.org.lapanganbola.helpers.MoneyHelper;
import bola.wiradipa.org.lapanganbola.helpers.adapters.DoubleTypeAdapter;
import bola.wiradipa.org.lapanganbola.helpers.adapters.FieldPagerAdapter;
import bola.wiradipa.org.lapanganbola.models.ApiData;
import bola.wiradipa.org.lapanganbola.models.Booking;
import bola.wiradipa.org.lapanganbola.models.City;
import bola.wiradipa.org.lapanganbola.helpers.adapters.GridViewAdapter;
import bola.wiradipa.org.lapanganbola.models.Booking;
import bola.wiradipa.org.lapanganbola.models.Field;
public class DetailFieldActivity extends BaseActivity {
private TextView tvTitleField,tvTitleVenue,tvRentRate,tvPitchSize,tvGrassType,tvBookingCancel
, tvTanggal;
private Button btnSubmit;
private ViewPager viewPager;
private GridView gvSchedule;
private GridViewAdapter gvAdapter;
private FieldPagerAdapter vpAdapter;
private LinearLayout sliderDotspanel;
private GridView gvSchedule;
private int dotscount;
private ImageView[] dots;
private boolean canSubmit=false;
private NonScrollGridView nonScrollGridView;
DatePickerDialog.OnDateSetListener mDatePicker;
String df_full, mDate, name;
DatePickerDialog.OnDateSetListener mDatePicker;
String df_full, mDate, name;
private Booking booking;
private List<Booking> bookingList;
private Field field;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_field);
checkSession();
Toolbar myToolbar = findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bookingList = new ArrayList<Booking>();
tvTitleField = findViewById(R.id.title_field);
tvTitleVenue = findViewById(R.id.title_venue);
tvRentRate = findViewById(R.id.rent_rate);
tvPitchSize = findViewById(R.id.pitch_size);
tvGrassType = findViewById(R.id.grass_type);
tvBookingCancel = findViewById(R.id.booking_cancel);
tvTanggal = findViewById(R.id.tanggal);
btnSubmit = findViewById(R.id.submit);
gvSchedule = findViewById(R.id.gridview);
nonScrollGridView = (NonScrollGridView) findViewById(R.id.spotsView);
nonScrollGridView.setExpanded(true);
GridViewAdapter adapter = new GridViewAdapter(this, booking);
nonScrollGridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
canSubmit = getBooleanExtraData(CAN_SUBMIT);
// parsingData();
Toast.makeText(context, getStringExtraData(FILTER_DATE), Toast.LENGTH_SHORT).show();
if(canSubmit) {
btnSubmit.setVisibility(View.VISIBLE);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, RentActivity.class);
intent.putExtra(EXTRA_ID, field.getId());
intent.putExtra(EXTRA_NAME, field.getName());
intent.putExtra(EXTRA_PARENT_NAME, field.getVenue_name());
intent.putExtra(FILTER_DATE, getStringExtraData(FILTER_DATE));
intent.putExtra(FILTER_HOUR, getStringExtraData(FILTER_HOUR));
intent.putExtra(FILTER_DURATION, getStringExtraData(FILTER_DURATION));
startActivity(intent);
}
});
} else
btnSubmit.setVisibility(View.GONE);
viewPager = findViewById(R.id.viewpager);
sliderDotspanel = findViewById(R.id.dots_layout);
tvTitleVenue.setText(getStringExtraData(EXTRA_PARENT_NAME));
tvTitleField.setText(getStringExtraData(EXTRA_NAME));
showProgressBar(true);
mApiService.getField(getLongExtraData(EXTRA_ID), getUserToken()).enqueue(getCallback.build());
if (getStringExtraData(FILTER_DATE).equals(getString(R.string.hint_rent_date))){
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), getDate(getStringExtraData(FILTER_DATE)))
.enqueue(getSchedule.build());
} else {
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), getStringExtraData(FILTER_DATE)).enqueue(getSchedule.build());
}
}
private void initData(){
tvRentRate.setText(MoneyHelper.toMoney(""+field.getRent_rate()));
tvPitchSize.setText(field.getPitch_size()+" "+getString(R.string.label_unit_length));
tvGrassType.setText(field.getGrass_type_name());
tvBookingCancel.setText("-");
List<Field> fields = new ArrayList<Field>();
fields.add(field);
vpAdapter = new FieldPagerAdapter(context, fields, null);
viewPager.setAdapter(vpAdapter);
Date rentDate = DateHelper.parsingDate("dd-MM-yyyy kk:mm",
getStringExtraData(FILTER_DATE)+" "+getStringExtraData(FILTER_HOUR));
gvAdapter = new GridViewAdapter(context, bookingList);
gvAdapter.setBackgroundStartHour(getStringExtraData(FILTER_HOUR));
if (!getStringExtraData(FILTER_DURATION).equals("Pilih Durasi")){
Date endDate = DateHelper.addDate(rentDate,DateHelper.HOUR,
Integer.parseInt(getStringExtraData(FILTER_DURATION).split(" ")[0]));
gvAdapter.setBackgroundEndHour(DateHelper.formatDate("kk:mm", endDate));
}
gvSchedule.setAdapter(gvAdapter);
gvSchedule.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@SuppressLint("ResourceType")
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// if (gvAdapter.lyBackground.getTag().equals(R.drawable.dot_tersedia)){
// gvAdapter.lyBackground.setBackground(ContextCompat.getDrawable(context, R.drawable.dot_green));
// gvAdapter.lyBackground.setId(R.drawable.dot_green);
// }
Toast.makeText(context, adapterView.getSelectedItem()+"", Toast.LENGTH_SHORT).show();
}
});
dotscount = vpAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dots));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dots));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private String getDate(String date){
final Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String tempDate = null;
Locale local = new Locale("id", "id");
month = month + 1;
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, local);
df_full = dateFormat.format(cal.getTime());
tempDate = getIntent().getStringExtra("date");
if(tempDate!=null){
date = tempDate;
}else{
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
}
tvTanggal.setText(df_full);
mDatePicker = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String tempDate = year + "-" + checkDigit(month) + "-" + checkDigit(dayOfMonth);
cal.set(year, month, dayOfMonth, 0 , 0 , 0);
df_full = dateFormat.format(cal.getTime());
// if (!getStringExtraData(FILTER_DATE).equals(R.string.hint_rent_date)){
// df_full = getStringExtraData(FILTER_DATE);
// } else {
// df_full = dateFormat.format(cal.getTime());
// }
tvTanggal.setText(df_full);
gvAdapter.clearData();
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), tempDate)
.enqueue(getSchedule.build());
// refreshActivity();
}
};
tvTanggal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(DetailFieldActivity.this,
R.style.Theme_AppCompat_DayNight_Dialog_MinWidth,
mDatePicker,year,month,day);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
dialog.show();
}
});
return date;
}
public String checkDigit(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}
private String getDate(String date){
final Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String tempDate = null;
Locale local = new Locale("id", "id");
month = month + 1;
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, local);
df_full = dateFormat.format(cal.getTime());
tempDate = getIntent().getStringExtra("date");
if(tempDate!=null){
date = tempDate;
}else{
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
}
tvTanggal.setText(df_full);
mDatePicker = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String tempDate = year + "-" + checkDigit(month) + "-" + checkDigit(dayOfMonth);
cal.set(year, month, dayOfMonth, 0 , 0 , 0);
df_full = dateFormat.format(cal.getTime());
// if (!getStringExtraData(FILTER_DATE).equals(R.string.hint_rent_date)){
// df_full = getStringExtraData(FILTER_DATE);
// } else {
// df_full = dateFormat.format(cal.getTime());
// }
tvTanggal.setText(df_full);
gvAdapter.clearData();
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), tempDate)
.enqueue(getSchedule.build());
// refreshActivity();
}
};
tvTanggal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(DetailFieldActivity.this,
R.style.Theme_AppCompat_DayNight_Dialog_MinWidth,
mDatePicker,year,month,day);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
dialog.show();
}
});
return date;
}
// private void parsingData(){
// if (getStringExtraData(FILTER_DATE).equals(R.string.hint_rent_date)){
// getDate(getStringExtraData(FILTER_DATE));
// Toast.makeText(context, getStringExtraData(FILTER_DATE), Toast.LENGTH_SHORT).show();
// } else if (!getStringExtraData(FILTER_HOUR).equals(R.string.hint_hour)){
//
// }
// }
public String checkDigit(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}
ApiCallback getCallback = new ApiCallback() {
@Override
public void onApiSuccess(String result) {
showProgressBar(false);
Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new DoubleTypeAdapter()).create();
field = gson.fromJson(result, Field.class);
Log.d(TAG, new Gson().toJson(field));
if(field!=null)
initData();
}
@Override
public void onApiFailure(String errorMessage) {
showProgressBar(false);
showSnackbar(errorMessage);
}
};
ApiCallback getSchedule = new ApiCallback() {
@Override
public void onApiSuccess(String result) {
showProgressBar(false);
Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new DoubleTypeAdapter()).create();
ApiData<Booking> apiData = gson.fromJson(result, new TypeToken<ApiData<Booking>>(){}.getType());
Log.d(TAG, new Gson().toJson(apiData));
bookingList = apiData.getData();
gvAdapter.setData(bookingList);
if(bookingList.size()==0)
showSnackbar(R.string.error_zero_data);
}
@Override
public void onApiFailure(String errorMessage) {
showProgressBar(false);
showSnackbar(errorMessage);
}
};
public void setValue(String name){
this.name = name;
}
}
| UTF-8 | Java | 16,553 | java | DetailFieldActivity.java | Java | [] | null | [] | package bola.wiradipa.org.lapanganbola;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import bola.wiradipa.org.lapanganbola.controllers.BaseActivity;
import bola.wiradipa.org.lapanganbola.helpers.AppSession;
import bola.wiradipa.org.lapanganbola.helpers.DateHelper;
import bola.wiradipa.org.lapanganbola.helpers.Log;
import bola.wiradipa.org.lapanganbola.helpers.MoneyHelper;
import bola.wiradipa.org.lapanganbola.helpers.adapters.DoubleTypeAdapter;
import bola.wiradipa.org.lapanganbola.helpers.adapters.FieldPagerAdapter;
import bola.wiradipa.org.lapanganbola.models.ApiData;
import bola.wiradipa.org.lapanganbola.models.Booking;
import bola.wiradipa.org.lapanganbola.models.City;
import bola.wiradipa.org.lapanganbola.helpers.adapters.GridViewAdapter;
import bola.wiradipa.org.lapanganbola.models.Booking;
import bola.wiradipa.org.lapanganbola.models.Field;
public class DetailFieldActivity extends BaseActivity {
private TextView tvTitleField,tvTitleVenue,tvRentRate,tvPitchSize,tvGrassType,tvBookingCancel
, tvTanggal;
private Button btnSubmit;
private ViewPager viewPager;
private GridView gvSchedule;
private GridViewAdapter gvAdapter;
private FieldPagerAdapter vpAdapter;
private LinearLayout sliderDotspanel;
private GridView gvSchedule;
private int dotscount;
private ImageView[] dots;
private boolean canSubmit=false;
private NonScrollGridView nonScrollGridView;
DatePickerDialog.OnDateSetListener mDatePicker;
String df_full, mDate, name;
DatePickerDialog.OnDateSetListener mDatePicker;
String df_full, mDate, name;
private Booking booking;
private List<Booking> bookingList;
private Field field;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_field);
checkSession();
Toolbar myToolbar = findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bookingList = new ArrayList<Booking>();
tvTitleField = findViewById(R.id.title_field);
tvTitleVenue = findViewById(R.id.title_venue);
tvRentRate = findViewById(R.id.rent_rate);
tvPitchSize = findViewById(R.id.pitch_size);
tvGrassType = findViewById(R.id.grass_type);
tvBookingCancel = findViewById(R.id.booking_cancel);
tvTanggal = findViewById(R.id.tanggal);
btnSubmit = findViewById(R.id.submit);
gvSchedule = findViewById(R.id.gridview);
nonScrollGridView = (NonScrollGridView) findViewById(R.id.spotsView);
nonScrollGridView.setExpanded(true);
GridViewAdapter adapter = new GridViewAdapter(this, booking);
nonScrollGridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
canSubmit = getBooleanExtraData(CAN_SUBMIT);
// parsingData();
Toast.makeText(context, getStringExtraData(FILTER_DATE), Toast.LENGTH_SHORT).show();
if(canSubmit) {
btnSubmit.setVisibility(View.VISIBLE);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, RentActivity.class);
intent.putExtra(EXTRA_ID, field.getId());
intent.putExtra(EXTRA_NAME, field.getName());
intent.putExtra(EXTRA_PARENT_NAME, field.getVenue_name());
intent.putExtra(FILTER_DATE, getStringExtraData(FILTER_DATE));
intent.putExtra(FILTER_HOUR, getStringExtraData(FILTER_HOUR));
intent.putExtra(FILTER_DURATION, getStringExtraData(FILTER_DURATION));
startActivity(intent);
}
});
} else
btnSubmit.setVisibility(View.GONE);
viewPager = findViewById(R.id.viewpager);
sliderDotspanel = findViewById(R.id.dots_layout);
tvTitleVenue.setText(getStringExtraData(EXTRA_PARENT_NAME));
tvTitleField.setText(getStringExtraData(EXTRA_NAME));
showProgressBar(true);
mApiService.getField(getLongExtraData(EXTRA_ID), getUserToken()).enqueue(getCallback.build());
if (getStringExtraData(FILTER_DATE).equals(getString(R.string.hint_rent_date))){
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), getDate(getStringExtraData(FILTER_DATE)))
.enqueue(getSchedule.build());
} else {
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), getStringExtraData(FILTER_DATE)).enqueue(getSchedule.build());
}
}
private void initData(){
tvRentRate.setText(MoneyHelper.toMoney(""+field.getRent_rate()));
tvPitchSize.setText(field.getPitch_size()+" "+getString(R.string.label_unit_length));
tvGrassType.setText(field.getGrass_type_name());
tvBookingCancel.setText("-");
List<Field> fields = new ArrayList<Field>();
fields.add(field);
vpAdapter = new FieldPagerAdapter(context, fields, null);
viewPager.setAdapter(vpAdapter);
Date rentDate = DateHelper.parsingDate("dd-MM-yyyy kk:mm",
getStringExtraData(FILTER_DATE)+" "+getStringExtraData(FILTER_HOUR));
gvAdapter = new GridViewAdapter(context, bookingList);
gvAdapter.setBackgroundStartHour(getStringExtraData(FILTER_HOUR));
if (!getStringExtraData(FILTER_DURATION).equals("Pilih Durasi")){
Date endDate = DateHelper.addDate(rentDate,DateHelper.HOUR,
Integer.parseInt(getStringExtraData(FILTER_DURATION).split(" ")[0]));
gvAdapter.setBackgroundEndHour(DateHelper.formatDate("kk:mm", endDate));
}
gvSchedule.setAdapter(gvAdapter);
gvSchedule.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@SuppressLint("ResourceType")
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// if (gvAdapter.lyBackground.getTag().equals(R.drawable.dot_tersedia)){
// gvAdapter.lyBackground.setBackground(ContextCompat.getDrawable(context, R.drawable.dot_green));
// gvAdapter.lyBackground.setId(R.drawable.dot_green);
// }
Toast.makeText(context, adapterView.getSelectedItem()+"", Toast.LENGTH_SHORT).show();
}
});
dotscount = vpAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dots));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dots));
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private String getDate(String date){
final Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String tempDate = null;
Locale local = new Locale("id", "id");
month = month + 1;
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, local);
df_full = dateFormat.format(cal.getTime());
tempDate = getIntent().getStringExtra("date");
if(tempDate!=null){
date = tempDate;
}else{
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
}
tvTanggal.setText(df_full);
mDatePicker = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String tempDate = year + "-" + checkDigit(month) + "-" + checkDigit(dayOfMonth);
cal.set(year, month, dayOfMonth, 0 , 0 , 0);
df_full = dateFormat.format(cal.getTime());
// if (!getStringExtraData(FILTER_DATE).equals(R.string.hint_rent_date)){
// df_full = getStringExtraData(FILTER_DATE);
// } else {
// df_full = dateFormat.format(cal.getTime());
// }
tvTanggal.setText(df_full);
gvAdapter.clearData();
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), tempDate)
.enqueue(getSchedule.build());
// refreshActivity();
}
};
tvTanggal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(DetailFieldActivity.this,
R.style.Theme_AppCompat_DayNight_Dialog_MinWidth,
mDatePicker,year,month,day);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
dialog.show();
}
});
return date;
}
public String checkDigit(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}
private String getDate(String date){
final Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String tempDate = null;
Locale local = new Locale("id", "id");
month = month + 1;
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, local);
df_full = dateFormat.format(cal.getTime());
tempDate = getIntent().getStringExtra("date");
if(tempDate!=null){
date = tempDate;
}else{
date = year + "-" + checkDigit(month) + "-" + checkDigit(day);
}
tvTanggal.setText(df_full);
mDatePicker = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String tempDate = year + "-" + checkDigit(month) + "-" + checkDigit(dayOfMonth);
cal.set(year, month, dayOfMonth, 0 , 0 , 0);
df_full = dateFormat.format(cal.getTime());
// if (!getStringExtraData(FILTER_DATE).equals(R.string.hint_rent_date)){
// df_full = getStringExtraData(FILTER_DATE);
// } else {
// df_full = dateFormat.format(cal.getTime());
// }
tvTanggal.setText(df_full);
gvAdapter.clearData();
mApiService.getScheduleField(getUserToken(), getLongExtraData(EXTRA_ID), tempDate)
.enqueue(getSchedule.build());
// refreshActivity();
}
};
tvTanggal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(DetailFieldActivity.this,
R.style.Theme_AppCompat_DayNight_Dialog_MinWidth,
mDatePicker,year,month,day);
dialog.getDatePicker().setMinDate(cal.getTimeInMillis());
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
dialog.show();
}
});
return date;
}
// private void parsingData(){
// if (getStringExtraData(FILTER_DATE).equals(R.string.hint_rent_date)){
// getDate(getStringExtraData(FILTER_DATE));
// Toast.makeText(context, getStringExtraData(FILTER_DATE), Toast.LENGTH_SHORT).show();
// } else if (!getStringExtraData(FILTER_HOUR).equals(R.string.hint_hour)){
//
// }
// }
public String checkDigit(int number)
{
return number<=9?"0"+number:String.valueOf(number);
}
ApiCallback getCallback = new ApiCallback() {
@Override
public void onApiSuccess(String result) {
showProgressBar(false);
Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new DoubleTypeAdapter()).create();
field = gson.fromJson(result, Field.class);
Log.d(TAG, new Gson().toJson(field));
if(field!=null)
initData();
}
@Override
public void onApiFailure(String errorMessage) {
showProgressBar(false);
showSnackbar(errorMessage);
}
};
ApiCallback getSchedule = new ApiCallback() {
@Override
public void onApiSuccess(String result) {
showProgressBar(false);
Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new DoubleTypeAdapter()).create();
ApiData<Booking> apiData = gson.fromJson(result, new TypeToken<ApiData<Booking>>(){}.getType());
Log.d(TAG, new Gson().toJson(apiData));
bookingList = apiData.getData();
gvAdapter.setData(bookingList);
if(bookingList.size()==0)
showSnackbar(R.string.error_zero_data);
}
@Override
public void onApiFailure(String errorMessage) {
showProgressBar(false);
showSnackbar(errorMessage);
}
};
public void setValue(String name){
this.name = name;
}
}
| 16,553 | 0.63203 | 0.629916 | 419 | 38.505966 | 30.362675 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.806683 | false | false | 8 |
b249c21fde5ed6b934dfa24e10957b5aa499d878 | 300,647,767,319 | ef0c1514e9af6de3ba4a20e0d01de7cc3a915188 | /sdk/resourceconnector/azure-resourcemanager-resourceconnector/src/main/java/com/azure/resourcemanager/resourceconnector/models/ApplianceCredentialKubeconfig.java | 5cc4f53b48943f8b91f850b7122fd2dabbc1c079 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"CC0-1.0",
"BSD-3-Clause",
"UPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | Azure/azure-sdk-for-java | https://github.com/Azure/azure-sdk-for-java | 0902d584b42d3654b4ce65b1dad8409f18ddf4bc | 789bdc6c065dc44ce9b8b630e2f2e5896b2a7616 | refs/heads/main | "2023-09-04T09:36:35.821000" | "2023-09-02T01:53:56" | "2023-09-02T01:53:56" | 2,928,948 | 2,027 | 2,084 | MIT | false | "2023-09-14T21:37:15" | "2011-12-06T23:33:56" | "2023-09-14T17:19:10" | "2023-09-14T21:37:14" | 3,043,660 | 1,994 | 1,854 | 1,435 | Java | false | false | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.resourceconnector.models;
import com.azure.core.annotation.Immutable;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Cluster User Credential appliance. */
@Immutable
public final class ApplianceCredentialKubeconfig {
/*
* Name which contains the role of the kubeconfig.
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private AccessProfileType name;
/*
* Contains the kubeconfig value.
*/
@JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY)
private String value;
/** Creates an instance of ApplianceCredentialKubeconfig class. */
public ApplianceCredentialKubeconfig() {
}
/**
* Get the name property: Name which contains the role of the kubeconfig.
*
* @return the name value.
*/
public AccessProfileType name() {
return this.name;
}
/**
* Get the value property: Contains the kubeconfig value.
*
* @return the value value.
*/
public String value() {
return this.value;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| UTF-8 | Java | 1,432 | java | ApplianceCredentialKubeconfig.java | Java | [] | null | [] | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.resourceconnector.models;
import com.azure.core.annotation.Immutable;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Cluster User Credential appliance. */
@Immutable
public final class ApplianceCredentialKubeconfig {
/*
* Name which contains the role of the kubeconfig.
*/
@JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
private AccessProfileType name;
/*
* Contains the kubeconfig value.
*/
@JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY)
private String value;
/** Creates an instance of ApplianceCredentialKubeconfig class. */
public ApplianceCredentialKubeconfig() {
}
/**
* Get the name property: Name which contains the role of the kubeconfig.
*
* @return the name value.
*/
public AccessProfileType name() {
return this.name;
}
/**
* Get the value property: Contains the kubeconfig value.
*
* @return the value value.
*/
public String value() {
return this.value;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| 1,432 | 0.668296 | 0.668296 | 54 | 25.518518 | 24.573202 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.166667 | false | false | 8 |
f7469529ce7b9c99dd9579ab0c638f0886e4c8d5 | 1,460,288,938,667 | e8bf15b7137b1a855c80bc6ca9226ac34bf98fe2 | /app/src/main/java/bd/com/supply/module/transaction/PackingProdActivity.java | df581dc2fd9360c9696b11abf473f97ed410023c | [] | no_license | xime123/supply | https://github.com/xime123/supply | 2907bd6cd29244430acea3437e2f343f60bd6c76 | b06459fa52502b86e4b7eb4c033050352d8bb54b | refs/heads/master | "2020-11-28T15:53:34.168000" | "2019-12-24T03:11:37" | "2019-12-24T03:11:37" | 229,860,306 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bd.com.supply.module.transaction;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import bd.com.appcore.IntentKey;
import bd.com.appcore.qrcode.QrCodePackProdEvent;
import bd.com.appcore.rx.RxTaskCallBack;
import bd.com.appcore.rx.RxTaskScheduler;
import bd.com.appcore.ui.activity.BaseListActivity;
import bd.com.appcore.ui.adapter.CommonAdapter;
import bd.com.appcore.ui.adapter.MultiItemTypeAdapter;
import bd.com.appcore.ui.adapter.base.ViewHolder;
import bd.com.appcore.util.AppSettings;
import bd.com.supply.R;
import bd.com.supply.module.transaction.model.domian.ProductOri;
import bd.com.supply.module.transaction.presenter.PackingProdPresenter;
import bd.com.supply.module.transaction.ui.ScanQrcodeActivity;
import bd.com.supply.web3.Web3Proxy;
import bd.com.supply.web3.contract.Authorized;
import bd.com.supply.web3.contract.Product;
import bd.com.supply.widget.VerifyPwdDialog;
import bd.com.supply.module.transaction.presenter.PackingProdPresenter;
import bd.com.supply.module.transaction.ui.ScanQrcodeActivity;
import bd.com.supply.widget.VerifyPwdDialog;
import bd.com.walletdb.entity.WalletEntity;
import bd.com.walletdb.manager.WalletDBManager;
import de.greenrobot.event.EventBus;
public class PackingProdActivity extends BaseListActivity<PackingProdPresenter, PackingProdPresenter.View, ProductOri> implements PackingProdPresenter.View {
private String aaddr;
private List<String> prodAddrs = new ArrayList<>();
@Override
protected void fetchListItems(@NonNull Map<String, Object> params) {
if (prodAddrs.size() == 0) {
showEmptyView();
}
}
@Override
protected void initTooBar() {
super.initTooBar();
EventBus.getDefault().register(this);
setTitle("打包产品");
actionBar.setRightTv("添加产品");
actionBar.setOnRightTvClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PackingProdActivity.this, ScanQrcodeActivity.class);
intent.putExtra(IntentKey.QRCODE_TYPE, 9);
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Override
protected void initContentView(ViewGroup contentView) {
super.initContentView(contentView);
addBottomView();
mRecyclerView.setPullRefreshEnabled(false);
}
@Override
protected MultiItemTypeAdapter<ProductOri> createAdapter() {
return new CommonAdapter<ProductOri>(this, R.layout.item_auth_layout, datas) {
@Override
protected void convert(ViewHolder holder, ProductOri productOri, int position) {
//holder.setText(R.id.time_tv, DateKit.timeStamp2Date(productOri.getCreateTime() / 1000 + "", null));
holder.setVisible(R.id.time_tv, false);
holder.setVisible(R.id.auth_name_tv, false);
holder.setVisible(R.id.add_auth_info_iv, false);
holder.setText(R.id.auth_address_tv, productOri.getPaddr());
//holder.setText(R.id.product_name_tv, productOri.getName());
//holder.setVisible(R.id.add_prod_info_iv, false);
}
};
}
@Override
protected void initData() {
super.initData();
aaddr = getIntent().getStringExtra(IntentKey.AUTH_ADDRESS);
if (TextUtils.isEmpty(aaddr)) {
showToast("鉴权地址为空");
finish();
return;
}
}
@Override
protected PackingProdPresenter initPresenter() {
return new PackingProdPresenter();
}
@Override
protected PackingProdPresenter.View initView() {
return this;
}
private void addBottomView() {
ViewGroup bottomView = (ViewGroup) View.inflate(this, R.layout.product_list_bottom_layout, null);
TextView addSosoTv = bottomView.findViewById(R.id.add_soso_tv);
addSosoTv.setText("扫盒子码打包");
addSosoTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (prodAddrs.size() == 0) {
showToast("请添加产品");
return;
}
Intent intent = new Intent(PackingProdActivity.this, ScanQrcodeActivity.class);
intent.putExtra(IntentKey.QRCODE_TYPE, 8);
startActivity(intent);
}
});
addBottomFloatView(bottomView);
}
public void onEventMainThread(final QrCodePackProdEvent event) {
if (event.getType() == 8) {//扫码打包盒子
if(SoSoConfig.NEED_PWD){
showPwdDialog(event.getResult());
}else {
mPresenter.packProdList(event.getResult(), prodAddrs, aaddr);
}
} else if (event.getType() == 9) {//扫码添加产品
if (prodAddrs.contains(event.getResult())) {
showToast("重复产品");
return;
}
RxTaskScheduler.postIoMainTask(new RxTaskCallBack<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
super.onSuccess(aBoolean);
if(aBoolean){
prodAddrs.add(event.getResult());
mPresenter.getProd(event.getResult());
}else {
showToast("鉴权地址不合法");
}
}
@Override
public Boolean doWork() throws Exception {
String prodAddr=event.getResult();
Product product=Product.load(prodAddr, Web3Proxy.getWeb3Proxy().getWeb3j(), Web3Proxy.getWeb3Proxy().getPoolTransactionManager(), Web3Proxy.GAS_PRICE, Web3Proxy.PACK_SOSO_GAS_LIMIT);
String authAddr=product.authorizedIdentify().send();
return aaddr.equalsIgnoreCase(authAddr);
}
});
}
}
private VerifyPwdDialog dialog;
private void showPwdDialog(final String boxAddr) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = new VerifyPwdDialog(this);
dialog.setOnOkClickListener(new VerifyPwdDialog.OnOkClickListener() {
@Override
public void onOkClick(String pwd) {
dialog.dismiss();
if (validAccount(pwd)) {
mPresenter.packProdList(boxAddr, prodAddrs, aaddr);
SoSoConfig.NEED_PWD = false;
}
}
});
dialog.show();
}
private boolean validAccount(String password) {
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "交易密码不能为空", Toast.LENGTH_LONG).show();
return false;
}
String currentAddres = AppSettings.getAppSettings().getCurrentAddress();
WalletEntity entity = WalletDBManager.getManager().getWalletEntity(currentAddres);
if (!TextUtils.equals(password, entity.getPassword())) {
Toast.makeText(this, "交易密码不正确", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
@Override
public void packingFailed(String msg) {
showToast(msg);
}
@Override
public void packingSuccess() {
showToast("打包成功");
finish();
}
@Override
public void reportFailed(String msg) {
showToast("上报失败");
}
@Override
public void reportSuccess() {
showToast("上报成功");
finish();
}
@Override
public void unLegalForProd(String errorMsg) {
showToast(errorMsg);
}
@Override
public void remainProdOri(List<ProductOri> remainOriList) {
datas.clear();
datas.addAll(remainOriList);
mAdapter.notifyDataSetChanged();
}
}
| UTF-8 | Java | 8,633 | java | PackingProdActivity.java | Java | [] | null | [] | package bd.com.supply.module.transaction;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import bd.com.appcore.IntentKey;
import bd.com.appcore.qrcode.QrCodePackProdEvent;
import bd.com.appcore.rx.RxTaskCallBack;
import bd.com.appcore.rx.RxTaskScheduler;
import bd.com.appcore.ui.activity.BaseListActivity;
import bd.com.appcore.ui.adapter.CommonAdapter;
import bd.com.appcore.ui.adapter.MultiItemTypeAdapter;
import bd.com.appcore.ui.adapter.base.ViewHolder;
import bd.com.appcore.util.AppSettings;
import bd.com.supply.R;
import bd.com.supply.module.transaction.model.domian.ProductOri;
import bd.com.supply.module.transaction.presenter.PackingProdPresenter;
import bd.com.supply.module.transaction.ui.ScanQrcodeActivity;
import bd.com.supply.web3.Web3Proxy;
import bd.com.supply.web3.contract.Authorized;
import bd.com.supply.web3.contract.Product;
import bd.com.supply.widget.VerifyPwdDialog;
import bd.com.supply.module.transaction.presenter.PackingProdPresenter;
import bd.com.supply.module.transaction.ui.ScanQrcodeActivity;
import bd.com.supply.widget.VerifyPwdDialog;
import bd.com.walletdb.entity.WalletEntity;
import bd.com.walletdb.manager.WalletDBManager;
import de.greenrobot.event.EventBus;
public class PackingProdActivity extends BaseListActivity<PackingProdPresenter, PackingProdPresenter.View, ProductOri> implements PackingProdPresenter.View {
private String aaddr;
private List<String> prodAddrs = new ArrayList<>();
@Override
protected void fetchListItems(@NonNull Map<String, Object> params) {
if (prodAddrs.size() == 0) {
showEmptyView();
}
}
@Override
protected void initTooBar() {
super.initTooBar();
EventBus.getDefault().register(this);
setTitle("打包产品");
actionBar.setRightTv("添加产品");
actionBar.setOnRightTvClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PackingProdActivity.this, ScanQrcodeActivity.class);
intent.putExtra(IntentKey.QRCODE_TYPE, 9);
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Override
protected void initContentView(ViewGroup contentView) {
super.initContentView(contentView);
addBottomView();
mRecyclerView.setPullRefreshEnabled(false);
}
@Override
protected MultiItemTypeAdapter<ProductOri> createAdapter() {
return new CommonAdapter<ProductOri>(this, R.layout.item_auth_layout, datas) {
@Override
protected void convert(ViewHolder holder, ProductOri productOri, int position) {
//holder.setText(R.id.time_tv, DateKit.timeStamp2Date(productOri.getCreateTime() / 1000 + "", null));
holder.setVisible(R.id.time_tv, false);
holder.setVisible(R.id.auth_name_tv, false);
holder.setVisible(R.id.add_auth_info_iv, false);
holder.setText(R.id.auth_address_tv, productOri.getPaddr());
//holder.setText(R.id.product_name_tv, productOri.getName());
//holder.setVisible(R.id.add_prod_info_iv, false);
}
};
}
@Override
protected void initData() {
super.initData();
aaddr = getIntent().getStringExtra(IntentKey.AUTH_ADDRESS);
if (TextUtils.isEmpty(aaddr)) {
showToast("鉴权地址为空");
finish();
return;
}
}
@Override
protected PackingProdPresenter initPresenter() {
return new PackingProdPresenter();
}
@Override
protected PackingProdPresenter.View initView() {
return this;
}
private void addBottomView() {
ViewGroup bottomView = (ViewGroup) View.inflate(this, R.layout.product_list_bottom_layout, null);
TextView addSosoTv = bottomView.findViewById(R.id.add_soso_tv);
addSosoTv.setText("扫盒子码打包");
addSosoTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (prodAddrs.size() == 0) {
showToast("请添加产品");
return;
}
Intent intent = new Intent(PackingProdActivity.this, ScanQrcodeActivity.class);
intent.putExtra(IntentKey.QRCODE_TYPE, 8);
startActivity(intent);
}
});
addBottomFloatView(bottomView);
}
public void onEventMainThread(final QrCodePackProdEvent event) {
if (event.getType() == 8) {//扫码打包盒子
if(SoSoConfig.NEED_PWD){
showPwdDialog(event.getResult());
}else {
mPresenter.packProdList(event.getResult(), prodAddrs, aaddr);
}
} else if (event.getType() == 9) {//扫码添加产品
if (prodAddrs.contains(event.getResult())) {
showToast("重复产品");
return;
}
RxTaskScheduler.postIoMainTask(new RxTaskCallBack<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
super.onSuccess(aBoolean);
if(aBoolean){
prodAddrs.add(event.getResult());
mPresenter.getProd(event.getResult());
}else {
showToast("鉴权地址不合法");
}
}
@Override
public Boolean doWork() throws Exception {
String prodAddr=event.getResult();
Product product=Product.load(prodAddr, Web3Proxy.getWeb3Proxy().getWeb3j(), Web3Proxy.getWeb3Proxy().getPoolTransactionManager(), Web3Proxy.GAS_PRICE, Web3Proxy.PACK_SOSO_GAS_LIMIT);
String authAddr=product.authorizedIdentify().send();
return aaddr.equalsIgnoreCase(authAddr);
}
});
}
}
private VerifyPwdDialog dialog;
private void showPwdDialog(final String boxAddr) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = new VerifyPwdDialog(this);
dialog.setOnOkClickListener(new VerifyPwdDialog.OnOkClickListener() {
@Override
public void onOkClick(String pwd) {
dialog.dismiss();
if (validAccount(pwd)) {
mPresenter.packProdList(boxAddr, prodAddrs, aaddr);
SoSoConfig.NEED_PWD = false;
}
}
});
dialog.show();
}
private boolean validAccount(String password) {
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "交易密码不能为空", Toast.LENGTH_LONG).show();
return false;
}
String currentAddres = AppSettings.getAppSettings().getCurrentAddress();
WalletEntity entity = WalletDBManager.getManager().getWalletEntity(currentAddres);
if (!TextUtils.equals(password, entity.getPassword())) {
Toast.makeText(this, "交易密码不正确", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
@Override
public void packingFailed(String msg) {
showToast(msg);
}
@Override
public void packingSuccess() {
showToast("打包成功");
finish();
}
@Override
public void reportFailed(String msg) {
showToast("上报失败");
}
@Override
public void reportSuccess() {
showToast("上报成功");
finish();
}
@Override
public void unLegalForProd(String errorMsg) {
showToast(errorMsg);
}
@Override
public void remainProdOri(List<ProductOri> remainOriList) {
datas.clear();
datas.addAll(remainOriList);
mAdapter.notifyDataSetChanged();
}
}
| 8,633 | 0.601438 | 0.598845 | 243 | 32.909466 | 28.060488 | 202 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.604938 | false | false | 8 |
667b88e0f409ed7140519f1e2d36d617d9e43455 | 12,051,678,293,865 | 07fc02ca46ebf4d75f4603f3cee8f32e25b7e7bc | /app/src/main/java/com/styleru/multithreadingproject/fragments/ThirdFragment.java | 929e85f3a2f8c06f01b4568fb0f146dd0cab5d74 | [] | no_license | VitalyKalenik/MultiThreadingProject | https://github.com/VitalyKalenik/MultiThreadingProject | ae36f3ef495561ef70b2a30accf1bb777cfef3a0 | 6be768b9d0b3dc740237bf990a8f27b7b6f85602 | refs/heads/master | "2020-04-13T23:33:42.117000" | "2018-12-29T12:37:35" | "2018-12-29T12:37:35" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.styleru.multithreadingproject.fragments;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.styleru.multithreadingproject.MyAdapter;
import com.styleru.multithreadingproject.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ThirdFragment extends Fragment {
public static final String KEY = "key";
private RecyclerView recyclerView;
MyAdapter adapter;
List<String> data;
MyHandler handler = new MyHandler();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_third, container, false);
initViews(view);
init();
runThread();
return view;
}
private void initViews(View view) {
recyclerView = view.findViewById(R.id.recyclerView);
}
private void init() {
data = new ArrayList<>();
adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
}
private void runThread(){
new Thread(new Runnable() {
@Override
public void run() {
Random random = new Random();
for(;;){
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(KEY, String.valueOf(random.nextInt()));
message.setData(bundle);
handler.sendMessage(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
private class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
data.add(msg.getData().getString(KEY));
adapter.setData(data);
}
}
}
| UTF-8 | Java | 2,314 | java | ThirdFragment.java | Java | [] | null | [] | package com.styleru.multithreadingproject.fragments;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.styleru.multithreadingproject.MyAdapter;
import com.styleru.multithreadingproject.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ThirdFragment extends Fragment {
public static final String KEY = "key";
private RecyclerView recyclerView;
MyAdapter adapter;
List<String> data;
MyHandler handler = new MyHandler();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_third, container, false);
initViews(view);
init();
runThread();
return view;
}
private void initViews(View view) {
recyclerView = view.findViewById(R.id.recyclerView);
}
private void init() {
data = new ArrayList<>();
adapter = new MyAdapter(data);
recyclerView.setAdapter(adapter);
}
private void runThread(){
new Thread(new Runnable() {
@Override
public void run() {
Random random = new Random();
for(;;){
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(KEY, String.valueOf(random.nextInt()));
message.setData(bundle);
handler.sendMessage(message);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
private class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
data.add(msg.getData().getString(KEY));
adapter.setData(data);
}
}
}
| 2,314 | 0.596802 | 0.594209 | 82 | 27.219513 | 19.972557 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.597561 | false | false | 8 |
671560693c9548fcc2e497bf3dfacaedf3294c82 | 31,688,268,758,343 | 3bf6fe48acae2e5c4bdd2500fc33fb230905c257 | /src/main/java/com/metanit/zadaniya/ConverterInRoman.java | 818b72c26db505155db85af73ba7e3c391ad6991 | [] | no_license | Romanr1995/java-edu | https://github.com/Romanr1995/java-edu | 9fafece8ec5427c5fe0cf14cf5650ad108688b2a | ef14e1a173f916866e46400663ecc45ad69cb2eb | refs/heads/master | "2023-06-21T12:05:58.311000" | "2021-07-24T15:13:27" | "2021-07-24T15:13:27" | 372,265,013 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.metanit.zadaniya;
import java.util.*;
public class ConverterInRoman {
public static void main(String[] args) {
System.out.println(converterToRomanNumbersTo1000("X"));
}
public static int converterToRomanNumbersTo1000(String number) {
Map<String, Integer> m = new TreeMap<>();
for (int i = 1; i <= 1000; i++) {
try {
m.put(ConverterInArabic2.convertFromArabicToRoman(i), i);
}catch (RuntimeException e) {
throw new RuntimeException("number = " + i, e);
}
}
return m.get(number);
}
}
| UTF-8 | Java | 624 | java | ConverterInRoman.java | Java | [] | null | [] | package com.metanit.zadaniya;
import java.util.*;
public class ConverterInRoman {
public static void main(String[] args) {
System.out.println(converterToRomanNumbersTo1000("X"));
}
public static int converterToRomanNumbersTo1000(String number) {
Map<String, Integer> m = new TreeMap<>();
for (int i = 1; i <= 1000; i++) {
try {
m.put(ConverterInArabic2.convertFromArabicToRoman(i), i);
}catch (RuntimeException e) {
throw new RuntimeException("number = " + i, e);
}
}
return m.get(number);
}
}
| 624 | 0.576923 | 0.554487 | 24 | 25 | 24.310492 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
1c4d03318c5df1fbe9cd652bc53539601b4bf82e | 8,057,358,685,280 | fb16e286a2e669a491e3c3f764c60cff870313bc | /src/main/java/cn/misection/dbstudy/service/StudentPayService.java | b31d7fa26446252f24a3212cdf587cb7ef3bbb8b | [] | no_license | MilitaryIntelligence6/DbStudyDemo | https://github.com/MilitaryIntelligence6/DbStudyDemo | c68be404d3c8903c0fc29df9003fa73607d5916d | 149f26d98e864ae87e0f1843faca1ae447c86173 | refs/heads/master | "2023-06-11T04:33:09.103000" | "2021-07-02T05:48:30" | "2021-07-02T05:48:30" | 382,243,795 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.misection.dbstudy.service;
import cn.misection.dbstudy.dao.StudentPayDAO;
import cn.misection.dbstudy.entity.StudentPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class StudentPayService {
@Autowired
private StudentPayDAO studentPayDAO;
public ArrayList<StudentPay> selectAll() {
return studentPayDAO.selectAll();
}
public StudentPay selectOne(String sno) {
return studentPayDAO.selectOne(sno);
}
public void insertStudentPay(String sno,
String stype,
String time,
int amount){
studentPayDAO.insertStudentPay(sno,stype,time,amount);
}
public void deleteStudentPay(String sno){
studentPayDAO.deleteStudentPay(sno);
}
}
| UTF-8 | Java | 921 | java | StudentPayService.java | Java | [] | null | [] | package cn.misection.dbstudy.service;
import cn.misection.dbstudy.dao.StudentPayDAO;
import cn.misection.dbstudy.entity.StudentPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class StudentPayService {
@Autowired
private StudentPayDAO studentPayDAO;
public ArrayList<StudentPay> selectAll() {
return studentPayDAO.selectAll();
}
public StudentPay selectOne(String sno) {
return studentPayDAO.selectOne(sno);
}
public void insertStudentPay(String sno,
String stype,
String time,
int amount){
studentPayDAO.insertStudentPay(sno,stype,time,amount);
}
public void deleteStudentPay(String sno){
studentPayDAO.deleteStudentPay(sno);
}
}
| 921 | 0.666667 | 0.666667 | 35 | 25.314285 | 21.719999 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485714 | false | false | 8 |
d6475815c8e983408331d8a1781d5b00c3ba4243 | 23,871,428,282,359 | f2c4ec75446964b55792e4fb56aee1536434acfc | /Flint/Phoenix/LinearRegression.java | 21945500c398136882cf4e9a04caed00eaf08467 | [] | no_license | pldi-paper-258/all-implementations | https://github.com/pldi-paper-258/all-implementations | 77dc27ece76c3938bbea6174ab0db453243e2834 | ef018ac5d5f18126c61b1ffe0b58935368e57a7f | refs/heads/master | "2021-01-11T15:20:52.196000" | "2017-04-25T05:44:30" | "2017-04-25T05:44:30" | 80,338,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package phoenix;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import scala.Tuple2;
import java.util.ArrayList;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import java.util.Arrays;
public class LinearRegression {
public static class Point {
public int x;
public int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Point flat$1 = new Point(100, 500);
Point flat$2 = new Point(3, 1000);
Point flat$3 = new Point(7, 600);
Point flat$4 = new Point(300, 34);
List<Point> points = null;
points = Arrays.asList(flat$1, flat$2, flat$3, flat$4);
regress(points);
}
public static int[] regress(List<Point> points) {
int SX_ll = 0;
SX_ll = 0;
int SY_ll = 0;
SY_ll = 0;
int SXX_ll = 0;
SXX_ll = 0;
int SYY_ll = 0;
SYY_ll = 0;
int SXY_ll = 0;
SXY_ll = 0;
{
int i = 0;
i = 0;
boolean loop$0 = false;
loop$0 = false;
SparkConf conf = new SparkConf().setAppName("spark");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<LinearRegression.Point> rdd_0_0 = sc.parallelize(points);
final boolean loop0_final = loop$0;
JavaPairRDD<Integer, Tuple2<Integer,Integer>> mapEmits = rdd_0_0.flatMapToPair(new PairFlatMapFunction<LinearRegression.Point, Integer, Tuple2<Integer,Integer>>() {
public Iterator<Tuple2<Integer, Tuple2<Integer,Integer>>> call(LinearRegression.Point points_i) throws Exception {
List<Tuple2<Integer, Tuple2<Integer,Integer>>> emits = new ArrayList<Tuple2<Integer, Tuple2<Integer,Integer>>>();
emits.add(new Tuple2(1,new Tuple2(1,points_i.x)));
emits.add(new Tuple2(3,new Tuple2(3,points_i.y)));
emits.add(new Tuple2(2,new Tuple2(2,points_i.x*points_i.x)));
emits.add(new Tuple2(5,new Tuple2(5,points_i.x*points_i.y)));
emits.add(new Tuple2(4,new Tuple2(4,points_i.y*points_i.y)));
return emits.iterator();
}
});
JavaPairRDD<Integer, Tuple2<Integer,Integer>> reduceEmits = mapEmits.reduceByKey(new Function2<Tuple2<Integer,Integer>,Tuple2<Integer,Integer>,Tuple2<Integer,Integer>>(){
public Tuple2<Integer,Integer> call(Tuple2<Integer,Integer> val1, Tuple2<Integer,Integer> val2) throws Exception {
if(val1._1 == 1){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 2){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 3){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 4){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 5){
return new Tuple2(val1._1,(val2._2+val1._2));
}
return null;
}
});
Map<Integer, Tuple2<Integer,Integer>> output_rdd_0_0 = reduceEmits.collectAsMap();
SXY_ll = output_rdd_0_0.get(1)._2;
SYY_ll = output_rdd_0_0.get(2)._2;
SY_ll = output_rdd_0_0.get(3)._2;
SXX_ll = output_rdd_0_0.get(4)._2;
SX_ll = output_rdd_0_0.get(5)._2;;
}
int[] result = null;
result = (new int[5]);
result[0] = SX_ll;
result[1] = SXX_ll;
result[2] = SY_ll;
result[3] = SYY_ll;
result[4] = SXY_ll;
return result;
}
public LinearRegression() { super(); }
} | UTF-8 | Java | 3,467 | java | LinearRegression.java | Java | [] | null | [] | package phoenix;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFlatMapFunction;
import scala.Tuple2;
import java.util.ArrayList;
import java.util.Map;
import java.util.Iterator;
import java.util.List;
import java.util.Arrays;
public class LinearRegression {
public static class Point {
public int x;
public int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
public static void main(String[] args) {
Point flat$1 = new Point(100, 500);
Point flat$2 = new Point(3, 1000);
Point flat$3 = new Point(7, 600);
Point flat$4 = new Point(300, 34);
List<Point> points = null;
points = Arrays.asList(flat$1, flat$2, flat$3, flat$4);
regress(points);
}
public static int[] regress(List<Point> points) {
int SX_ll = 0;
SX_ll = 0;
int SY_ll = 0;
SY_ll = 0;
int SXX_ll = 0;
SXX_ll = 0;
int SYY_ll = 0;
SYY_ll = 0;
int SXY_ll = 0;
SXY_ll = 0;
{
int i = 0;
i = 0;
boolean loop$0 = false;
loop$0 = false;
SparkConf conf = new SparkConf().setAppName("spark");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<LinearRegression.Point> rdd_0_0 = sc.parallelize(points);
final boolean loop0_final = loop$0;
JavaPairRDD<Integer, Tuple2<Integer,Integer>> mapEmits = rdd_0_0.flatMapToPair(new PairFlatMapFunction<LinearRegression.Point, Integer, Tuple2<Integer,Integer>>() {
public Iterator<Tuple2<Integer, Tuple2<Integer,Integer>>> call(LinearRegression.Point points_i) throws Exception {
List<Tuple2<Integer, Tuple2<Integer,Integer>>> emits = new ArrayList<Tuple2<Integer, Tuple2<Integer,Integer>>>();
emits.add(new Tuple2(1,new Tuple2(1,points_i.x)));
emits.add(new Tuple2(3,new Tuple2(3,points_i.y)));
emits.add(new Tuple2(2,new Tuple2(2,points_i.x*points_i.x)));
emits.add(new Tuple2(5,new Tuple2(5,points_i.x*points_i.y)));
emits.add(new Tuple2(4,new Tuple2(4,points_i.y*points_i.y)));
return emits.iterator();
}
});
JavaPairRDD<Integer, Tuple2<Integer,Integer>> reduceEmits = mapEmits.reduceByKey(new Function2<Tuple2<Integer,Integer>,Tuple2<Integer,Integer>,Tuple2<Integer,Integer>>(){
public Tuple2<Integer,Integer> call(Tuple2<Integer,Integer> val1, Tuple2<Integer,Integer> val2) throws Exception {
if(val1._1 == 1){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 2){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 3){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 4){
return new Tuple2(val1._1,(val1._2+val2._2));
}
if(val1._1 == 5){
return new Tuple2(val1._1,(val2._2+val1._2));
}
return null;
}
});
Map<Integer, Tuple2<Integer,Integer>> output_rdd_0_0 = reduceEmits.collectAsMap();
SXY_ll = output_rdd_0_0.get(1)._2;
SYY_ll = output_rdd_0_0.get(2)._2;
SY_ll = output_rdd_0_0.get(3)._2;
SXX_ll = output_rdd_0_0.get(4)._2;
SX_ll = output_rdd_0_0.get(5)._2;;
}
int[] result = null;
result = (new int[5]);
result[0] = SX_ll;
result[1] = SXX_ll;
result[2] = SY_ll;
result[3] = SYY_ll;
result[4] = SXY_ll;
return result;
}
public LinearRegression() { super(); }
} | 3,467 | 0.644073 | 0.595904 | 115 | 29.156521 | 30.514313 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.704348 | false | false | 8 |
e6bba501a3576f98e73a3552979ad5ce80196b13 | 21,071,109,587,029 | 276eb5832a58f6cf392278491d5c411dea7daee1 | /development/silver-seed/silver-seed-query-parent/silver-seed-query/src/main/java/com/silver/seed/query/entity/Column.java | ede7eb4dd0d32394b869997f774d66c4e3fe0782 | [] | no_license | strangerC/silver-seed | https://github.com/strangerC/silver-seed | 578c16c10cdf73fd987e4380bbf2d71d38f9900f | b95da11c10b2e6d6660b67df155f2f7d99c67074 | refs/heads/master | "2021-01-16T21:20:00.687000" | "2014-04-06T08:22:16" | "2014-04-06T08:22:16" | 13,802,346 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.silver.seed.query.entity;
/**
*
* @author Liaojian
*/
public class Column {
private String name;
private String index;
private Integer width;
private String align;
private boolean sortable;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public String getAlign() {
return align;
}
public void setAlign(String align) {
this.align = align;
}
public boolean isSortable() {
return sortable;
}
public void setSortable(boolean sortable) {
this.sortable = sortable;
}
}
| UTF-8 | Java | 1,083 | java | Column.java | Java | [
{
"context": "e com.silver.seed.query.entity;\n\n/**\n *\n * @author Liaojian\n */\npublic class Column {\n private String ",
"end": 65,
"score": 0.9557979702949524,
"start": 57,
"tag": "NAME",
"value": "Liaojian"
}
] | null | [] | package com.silver.seed.query.entity;
/**
*
* @author Liaojian
*/
public class Column {
private String name;
private String index;
private Integer width;
private String align;
private boolean sortable;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public String getAlign() {
return align;
}
public void setAlign(String align) {
this.align = align;
}
public boolean isSortable() {
return sortable;
}
public void setSortable(boolean sortable) {
this.sortable = sortable;
}
}
| 1,083 | 0.499538 | 0.499538 | 53 | 19.433962 | 15.415637 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.301887 | false | false | 8 |
870a9f0aae4fb49b77ff144c2a167e5371176d89 | 20,401,094,691,889 | abc62e9faff8019afa0689311f89dbaa07076e8d | /hw_java_0227/Main1828.java | 0b82ec97d386d0e19a142bfe1459831465f75ebd | [] | no_license | reusepaper/homework | https://github.com/reusepaper/homework | d1d7706318be3684f97ba357484323a0ce109401 | 4ad0cfbab3601c2920aa3b6016067713ce6c81df | refs/heads/master | "2022-08-19T04:56:56.697000" | "2019-05-08T08:57:57" | "2019-05-08T08:57:57" | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kr.co.jungol;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main1828 {
public void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int N = Integer.parseInt(str);
ArrayList<Refri> ref = new ArrayList<>();
for(int idx = 1; idx <= N; idx++) {
String[] s = br.readLine().split(" ");
int start = Integer.parseInt(s[0]);
int end = Integer.parseInt(s[1]);
ref.add(new Refri(start, end));
}
Collections.sort(ref, new CompareIdx());
int res = 1;
int idx = 0;
for(int tmp = idx+1; tmp < N; tmp++) {
if(ref.get(idx).start > ref.get(tmp).end) {
res++;
idx = tmp;
}
}
System.out.println(res);
}
class CompareIdx implements Comparator<Refri>{
@Override
public int compare(Refri o1, Refri o2) {
return o1.start > o2.start ? -1 : 1;
}
}
class Refri {
int start;
int end;
public Refri(int start, int end) {
this.start = start;
this.end = end;
}
}
public static void main(String[] args) throws IOException {
Main1828 m1828 = new Main1828();
m1828.solve();
}
}
| UTF-8 | Java | 1,292 | java | Main1828.java | Java | [] | null | [] | package kr.co.jungol;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Main1828 {
public void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int N = Integer.parseInt(str);
ArrayList<Refri> ref = new ArrayList<>();
for(int idx = 1; idx <= N; idx++) {
String[] s = br.readLine().split(" ");
int start = Integer.parseInt(s[0]);
int end = Integer.parseInt(s[1]);
ref.add(new Refri(start, end));
}
Collections.sort(ref, new CompareIdx());
int res = 1;
int idx = 0;
for(int tmp = idx+1; tmp < N; tmp++) {
if(ref.get(idx).start > ref.get(tmp).end) {
res++;
idx = tmp;
}
}
System.out.println(res);
}
class CompareIdx implements Comparator<Refri>{
@Override
public int compare(Refri o1, Refri o2) {
return o1.start > o2.start ? -1 : 1;
}
}
class Refri {
int start;
int end;
public Refri(int start, int end) {
this.start = start;
this.end = end;
}
}
public static void main(String[] args) throws IOException {
Main1828 m1828 = new Main1828();
m1828.solve();
}
}
| 1,292 | 0.644737 | 0.619969 | 60 | 20.533333 | 17.865671 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.283333 | false | false | 8 |
0933d369125a1748c635a31c4ca24ed40863117f | 26,955,214,801,285 | 8b32dc307e1e710f5048fdaa29401c6228c5c569 | /berna-common/src/main/java/com/wlc/berna/common/thread/Executor.java | 83513f1a93b1944514cfc9acdd5dbba240472cd3 | [] | no_license | zgwlc12138/berna | https://github.com/zgwlc12138/berna | fc62046c9740444225f6d121dfb3d3669752a8f7 | 4e3f4ceeed17f74e18983749a58760a1a1ca64f0 | refs/heads/master | "2022-07-12T09:36:55.697000" | "2020-04-16T09:06:46" | "2020-04-16T09:06:46" | 139,238,253 | 0 | 0 | null | false | "2022-06-17T01:57:07" | "2018-06-30T09:54:30" | "2020-04-16T09:06:50" | "2022-06-17T01:57:07" | 2,928 | 0 | 0 | 4 | JavaScript | false | false | package com.wlc.berna.common.thread;
public abstract interface Executor {
public abstract void execute(Runnable paramRunnable)
throws InterruptedException;
public abstract void setName(String paramString);
public abstract void start();
public abstract void shutdown() throws InterruptedException;
public abstract boolean isAlive();
}
| UTF-8 | Java | 371 | java | Executor.java | Java | [] | null | [] | package com.wlc.berna.common.thread;
public abstract interface Executor {
public abstract void execute(Runnable paramRunnable)
throws InterruptedException;
public abstract void setName(String paramString);
public abstract void start();
public abstract void shutdown() throws InterruptedException;
public abstract boolean isAlive();
}
| 371 | 0.749326 | 0.749326 | 14 | 25.5 | 23.396429 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 8 |
e44cf6c47d5cbe66b21e6b7a375f7d284e299715 | 15,960,098,513,713 | 56fbb5e9c1c3d4a4dfa671ba694e5a80fd6c1465 | /src/main/java/com/citrix/web/utility/TimeFormate.java | fd58e5b34492d347d9545b5256c80d7fcca77557 | [] | no_license | ltomar/WebDemo | https://github.com/ltomar/WebDemo | 7f75637a0cb6be4c8de69c6d0a6902d36d606373 | c9c8edc19a4ac986fd38d94689193bde0adf591f | refs/heads/master | "2021-01-10T07:41:23.500000" | "2015-11-19T16:03:56" | "2015-11-19T16:03:56" | 46,196,942 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.citrix.web.utility;
public enum TimeFormate {
PM,AM
}
| UTF-8 | Java | 69 | java | TimeFormate.java | Java | [] | null | [] | package com.citrix.web.utility;
public enum TimeFormate {
PM,AM
}
| 69 | 0.73913 | 0.73913 | 6 | 10.5 | 12.658989 | 31 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
07c3ada568f34dc3d9f4ff10e8293d056a54d2da | 15,960,098,509,691 | 2ed2665e2e9c0a76f5b6d97e1953a4ca19485f89 | /FlyAwayPortal/src/com/flyaway/model/login/LogoutServlet.java | 8b2529d36571fb9dc97813a6da9700e48cc4a075 | [] | no_license | AshwinRanganath/FlyAwayPortal | https://github.com/AshwinRanganath/FlyAwayPortal | 64459b825df308b85f77965991cb049f5049cfe2 | ca6b683ce924ec2a98a66382d3ca558c96b1975d | refs/heads/master | "2022-12-17T23:50:15.380000" | "2020-09-30T04:44:47" | "2020-09-30T04:44:47" | 298,888,161 | 0 | 0 | null | false | "2020-09-30T04:44:49" | "2020-09-26T19:45:42" | "2020-09-28T07:40:32" | "2020-09-30T04:44:48" | 10,464 | 0 | 0 | 0 | Java | false | false | package com.flyaway.model.login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet(description = "Logout servlet", urlPatterns = { "/logout" })
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogoutServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
HttpSession session=request.getSession(false);
PrintWriter out=response.getWriter();
if(session==null)
{
out.println("You are not logged in.");
}
else
{
session.invalidate();
out.print("You have logged out");
response.setHeader("refresh", "1,url='search.jsp");
}
}
}
| UTF-8 | Java | 1,534 | java | LogoutServlet.java | Java | [] | null | [] | package com.flyaway.model.login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LogoutServlet
*/
@WebServlet(description = "Logout servlet", urlPatterns = { "/logout" })
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LogoutServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
HttpSession session=request.getSession(false);
PrintWriter out=response.getWriter();
if(session==null)
{
out.println("You are not logged in.");
}
else
{
session.invalidate();
out.print("You have logged out");
response.setHeader("refresh", "1,url='search.jsp");
}
}
}
| 1,534 | 0.745763 | 0.744459 | 57 | 25.912281 | 24.565187 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.245614 | false | false | 8 |
1740fa90875b79c0448e10d7c26ccb2e8cba773c | 21,517,786,195,969 | ae2d74f3e203fbc333a079a52f91dd0ddf9cc9b4 | /src/com/guoyang/TestArrayGenerator.java | 8fc418060d0964bc50d8a0c8b4326f6a3527f13f | [] | no_license | guoyang1996/Alogrithm | https://github.com/guoyang1996/Alogrithm | 17d65dcd0f7ea92760159826bff91f74205f6507 | 3e2e0648360c31446715f01dc8f7e51ecbde3b8a | refs/heads/master | "2020-05-17T17:42:31.523000" | "2019-04-28T06:03:21" | "2019-04-28T06:03:21" | 183,862,360 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.guoyang;
import java.util.Random;
/**
* @program: Alogrithm
* @description: 测试数组生成器
* @author: guoyang
* @create: 2019-04-23 20:05
**/
public class TestArrayGenerator {
/**
* @param n 数组大小
* @param ratio 1的比例
* @return 生成的数组
*/
public static int[] generateArray(int n,int ratio){
int[] res = new int[n];
Random r = new Random(System.currentTimeMillis());//用于生成数组中的数
Random ran = new Random(System.currentTimeMillis());//用于决定是否为1
for(int i=0;i<n;i++){
if(ran.nextInt(100)<ratio) res[i] = 1;
else res[i] = r.nextInt();
}
return res;
}
}
| UTF-8 | Java | 728 | java | TestArrayGenerator.java | Java | [
{
"context": "am: Alogrithm\n * @description: 测试数组生成器\n * @author: guoyang\n * @create: 2019-04-23 20:05\n **/\npublic class Te",
"end": 119,
"score": 0.9986593127250671,
"start": 112,
"tag": "USERNAME",
"value": "guoyang"
}
] | null | [] | package com.guoyang;
import java.util.Random;
/**
* @program: Alogrithm
* @description: 测试数组生成器
* @author: guoyang
* @create: 2019-04-23 20:05
**/
public class TestArrayGenerator {
/**
* @param n 数组大小
* @param ratio 1的比例
* @return 生成的数组
*/
public static int[] generateArray(int n,int ratio){
int[] res = new int[n];
Random r = new Random(System.currentTimeMillis());//用于生成数组中的数
Random ran = new Random(System.currentTimeMillis());//用于决定是否为1
for(int i=0;i<n;i++){
if(ran.nextInt(100)<ratio) res[i] = 1;
else res[i] = r.nextInt();
}
return res;
}
}
| 728 | 0.572948 | 0.544073 | 27 | 23.370371 | 19.170094 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.407407 | false | false | 8 |
83c483ee6b2df80f1dc974734262aa90d497e168 | 26,688,926,826,885 | 902a524780e2f939ca0590a4fc3a42d4e835e8df | /src/main/com/wemanity/kata/tdd/bejeweledlike/view/GameView.java | 1f20baa2d8dc85fba8df0a6ae157e2bd32c000ce | [
"MIT"
] | permissive | MrArkasia/Bejeweled-like-TDD-Kata | https://github.com/MrArkasia/Bejeweled-like-TDD-Kata | 75d37fa7dc2c7f81e911acf25d225ec0dc14526b | ef82cbe3866c3c30ff76c041bf6fd30fdcec84e8 | refs/heads/master | "2020-04-09T02:43:43.107000" | "2019-01-08T15:25:17" | "2019-01-08T15:25:17" | 159,940,639 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wemanity.kata.tdd.bejeweledlike.view;
import com.wemanity.kata.tdd.bejeweledlike.models.Coordinates;
import com.wemanity.kata.tdd.bejeweledlike.models.DiamondColor;
import com.wemanity.kata.tdd.bejeweledlike.models.Score;
import com.wemanity.kata.tdd.bejeweledlike.rules.GameBoardRules;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class GameView extends JPanel implements MouseListener, MouseMotionListener, Runnable {
private static final int BOX_SIZE = 32;
private final GameBoardRules gameBoardRules;
private final int nbBox;
private int selectedX = -1;
private int selectedY = -1;
private int swappedX = -1;
private int swappedY = -1;
Image buffer;
public GameView(int size) {
this.gameBoardRules = new GameBoardRules(size);
this.nbBox = size;
}
/**
* Main loop
*/
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
if (!gameBoardRules.fill()) {
gameBoardRules.removeAlignments();
}
rePaint();
}
}
/**
* Initialization: mouse events and main loop
*/
public void init() {
new Thread(this).start();
// fill the grid for the first time
while (gameBoardRules.fill()) ;
while (gameBoardRules.removeAlignments()) {
gameBoardRules.fill();
}
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
/**
* Display routine: double buffering
*/
@Override
public void paint(Graphics g2) {
super.paint(g2);
if (buffer == null) buffer = createImage(nbBox * BOX_SIZE + 5, nbBox * BOX_SIZE + 25);
Graphics2D g = (Graphics2D) buffer.getGraphics();
// background
g.setColor(Color.WHITE);
g.fillRect(1, 1, BOX_SIZE * nbBox, BOX_SIZE * nbBox); //getWidth(), getHeight());
// display the empty grid
g.setColor(Color.BLACK);
for (int i = 0; i < nbBox + 1; i++) {
g.drawLine(BOX_SIZE * i + 1, 1, BOX_SIZE * i + 1, nbBox * BOX_SIZE + 1 + 1);
g.drawLine(1, BOX_SIZE * i + 1, nbBox * BOX_SIZE + 1 + 1, BOX_SIZE * i + 1);
}
// show the first box selected
if (selectedX != -1 && selectedY != -1) {
g.setColor(Color.ORANGE);
g.fillRect(selectedX * BOX_SIZE + 1 + 1, selectedY * BOX_SIZE + 1 + 1, BOX_SIZE - 1, BOX_SIZE - 1);
}
// display the second selected box
if (swappedX != -1 && swappedY != -1) {
g.setColor(Color.YELLOW);
g.fillRect(swappedX * BOX_SIZE + 1 + 1, swappedY * BOX_SIZE + 1 + 1, BOX_SIZE - 1, BOX_SIZE - 1);
}
// display the contents of the grid
for (int i = 0; i < nbBox; i++) {
for (int j = 0; j < nbBox; j++) {
final int boxValue = gameBoardRules.getGameBoard().getValue(new Coordinates(i, j));
final Color color = DiamondColor.getColor(boxValue);
g.setColor(color);
g.fillOval(BOX_SIZE * i + 3 + 1, BOX_SIZE * j + 3 + 1, 27, 27);
}
}
g2.drawImage(buffer, 0, 0, null);
g2.drawString("Score : " + Score.getInstance().getValue(), 5, nbBox * BOX_SIZE + 15);
}
/**
* Avoid flickering
*/
@Override
public void update(Graphics g) {
paint(g);
}
public void rePaint() {
repaint();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
// press the mouse button: retrieve the coordinates of the first box
selectedX = (e.getX() / BOX_SIZE);
selectedY = (e.getY() / BOX_SIZE);
rePaint();
}
@Override
public void mouseMoved(MouseEvent e) {
if (selectedX != -1 && selectedY != -1) {
swappedX = (e.getX() / BOX_SIZE);
swappedY = (e.getY() / BOX_SIZE);
// if the exchange is invalid, we hide the second box
if (!(gameBoardRules.isValidSwap(new Coordinates(selectedX, selectedY), new Coordinates(swappedX, swappedY)))) {
swappedX = swappedY = -1;
}
}
rePaint();
}
@Override
public void mouseReleased(MouseEvent e) {
//when you release the mouse you have to make the exchange and hide the boxes
if (selectedX != -1 && selectedY != -1 && swappedX != -1 && swappedY != -1) {
gameBoardRules.swap(new Coordinates(selectedX, selectedY), new Coordinates(swappedX, swappedY));
}
selectedX = selectedY = swappedX = swappedY = -1;
rePaint();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
mouseMoved(e);
}
}
| UTF-8 | Java | 5,124 | java | GameView.java | Java | [] | null | [] | package com.wemanity.kata.tdd.bejeweledlike.view;
import com.wemanity.kata.tdd.bejeweledlike.models.Coordinates;
import com.wemanity.kata.tdd.bejeweledlike.models.DiamondColor;
import com.wemanity.kata.tdd.bejeweledlike.models.Score;
import com.wemanity.kata.tdd.bejeweledlike.rules.GameBoardRules;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class GameView extends JPanel implements MouseListener, MouseMotionListener, Runnable {
private static final int BOX_SIZE = 32;
private final GameBoardRules gameBoardRules;
private final int nbBox;
private int selectedX = -1;
private int selectedY = -1;
private int swappedX = -1;
private int swappedY = -1;
Image buffer;
public GameView(int size) {
this.gameBoardRules = new GameBoardRules(size);
this.nbBox = size;
}
/**
* Main loop
*/
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
if (!gameBoardRules.fill()) {
gameBoardRules.removeAlignments();
}
rePaint();
}
}
/**
* Initialization: mouse events and main loop
*/
public void init() {
new Thread(this).start();
// fill the grid for the first time
while (gameBoardRules.fill()) ;
while (gameBoardRules.removeAlignments()) {
gameBoardRules.fill();
}
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
/**
* Display routine: double buffering
*/
@Override
public void paint(Graphics g2) {
super.paint(g2);
if (buffer == null) buffer = createImage(nbBox * BOX_SIZE + 5, nbBox * BOX_SIZE + 25);
Graphics2D g = (Graphics2D) buffer.getGraphics();
// background
g.setColor(Color.WHITE);
g.fillRect(1, 1, BOX_SIZE * nbBox, BOX_SIZE * nbBox); //getWidth(), getHeight());
// display the empty grid
g.setColor(Color.BLACK);
for (int i = 0; i < nbBox + 1; i++) {
g.drawLine(BOX_SIZE * i + 1, 1, BOX_SIZE * i + 1, nbBox * BOX_SIZE + 1 + 1);
g.drawLine(1, BOX_SIZE * i + 1, nbBox * BOX_SIZE + 1 + 1, BOX_SIZE * i + 1);
}
// show the first box selected
if (selectedX != -1 && selectedY != -1) {
g.setColor(Color.ORANGE);
g.fillRect(selectedX * BOX_SIZE + 1 + 1, selectedY * BOX_SIZE + 1 + 1, BOX_SIZE - 1, BOX_SIZE - 1);
}
// display the second selected box
if (swappedX != -1 && swappedY != -1) {
g.setColor(Color.YELLOW);
g.fillRect(swappedX * BOX_SIZE + 1 + 1, swappedY * BOX_SIZE + 1 + 1, BOX_SIZE - 1, BOX_SIZE - 1);
}
// display the contents of the grid
for (int i = 0; i < nbBox; i++) {
for (int j = 0; j < nbBox; j++) {
final int boxValue = gameBoardRules.getGameBoard().getValue(new Coordinates(i, j));
final Color color = DiamondColor.getColor(boxValue);
g.setColor(color);
g.fillOval(BOX_SIZE * i + 3 + 1, BOX_SIZE * j + 3 + 1, 27, 27);
}
}
g2.drawImage(buffer, 0, 0, null);
g2.drawString("Score : " + Score.getInstance().getValue(), 5, nbBox * BOX_SIZE + 15);
}
/**
* Avoid flickering
*/
@Override
public void update(Graphics g) {
paint(g);
}
public void rePaint() {
repaint();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
// press the mouse button: retrieve the coordinates of the first box
selectedX = (e.getX() / BOX_SIZE);
selectedY = (e.getY() / BOX_SIZE);
rePaint();
}
@Override
public void mouseMoved(MouseEvent e) {
if (selectedX != -1 && selectedY != -1) {
swappedX = (e.getX() / BOX_SIZE);
swappedY = (e.getY() / BOX_SIZE);
// if the exchange is invalid, we hide the second box
if (!(gameBoardRules.isValidSwap(new Coordinates(selectedX, selectedY), new Coordinates(swappedX, swappedY)))) {
swappedX = swappedY = -1;
}
}
rePaint();
}
@Override
public void mouseReleased(MouseEvent e) {
//when you release the mouse you have to make the exchange and hide the boxes
if (selectedX != -1 && selectedY != -1 && swappedX != -1 && swappedY != -1) {
gameBoardRules.swap(new Coordinates(selectedX, selectedY), new Coordinates(swappedX, swappedY));
}
selectedX = selectedY = swappedX = swappedY = -1;
rePaint();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
mouseMoved(e);
}
}
| 5,124 | 0.568696 | 0.55484 | 172 | 28.790697 | 27.59597 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.587209 | false | false | 8 |
cf319b7aeda79bc408977498ee9db60c606f086a | 3,788,161,205,892 | ce524ab4de51bda359adb7d82fe8ba1b0326eb18 | /MobileAutomation/src/com/automation/locators/SecondPageLocators.java | a3190ac3b182d617a8104f1396502289be9630ef | [] | no_license | chiragkhimani/MobileAutomationFramework | https://github.com/chiragkhimani/MobileAutomationFramework | ced413c70642d0a209b0b4bec53940b9e6068418 | 98c81507b11f3e1a53893170b88b1a766318fef5 | refs/heads/master | "2021-01-17T06:28:16.029000" | "2016-07-22T18:36:28" | "2016-07-22T18:36:28" | 51,640,453 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.automation.locators;
public interface SecondPageLocators {
}
| UTF-8 | Java | 74 | java | SecondPageLocators.java | Java | [] | null | [] | package com.automation.locators;
public interface SecondPageLocators {
}
| 74 | 0.824324 | 0.824324 | 4 | 17.5 | 17.095322 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 8 |