blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
679ff68b4411fa04c8051b382b1bb733eec3731e | 23,768,349,070,619 | 0b71627f06f06ef7b29f9385d6069e89c0a779d8 | /Password.java | b57d7b833dd3ccb43e007614304afab9b9667f07 | []
| no_license | alan-valenzuela93/bank-account-java | https://github.com/alan-valenzuela93/bank-account-java | 211cc2d7ee037d76451973908aaa55a156d31755 | d2bfef5819b2ee300ad81d0e5cffba724feb5550 | refs/heads/master | 2022-12-19T04:24:06.641000 | 2020-09-20T09:50:35 | 2020-09-20T09:50:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package account;
import java.util.Random;
public class Password {
private int longitud =15;
private String contraseņa;
private Random randomGenerator = new Random();
private String mayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private String minusculas = mayusculas.toLowerCase();
private String numeros = "0123456789";
private String todo = mayusculas + minusculas + numeros;
private int aleatoria;
public Password() {
this.contraseņa = generarPassword();
while(esFuerte(this.contraseņa)==false) {
this.contraseņa = generarPassword();
}
}
public String generarPassword() {
String nueva ="";
for(int i =0;i<this.longitud;i++) {
this.aleatoria = randomGenerator.nextInt(todo.length());
nueva += todo.charAt(aleatoria);
}
return nueva;
}
public int cantidadMayusculas(String password) {
int cant =0;
for(int j =0;j<mayusculas.length();j++) {
for(int i=0;i<password.length();i++) {
if(mayusculas.charAt(j)==password.charAt(i)) {
cant++;
}
}
}
return cant;
}
public int cantidadMinusculas(String password) {
int cant =0;
for(int j =0;j<minusculas.length();j++) {
for(int i=0;i<password.length();i++) {
if(minusculas.charAt(j)==password.charAt(i)) {
cant++;
}
}
}
return cant;
}
public int cantidadNumeros(String password) {
int cant =0;
for(int j =0;j<numeros.length();j++) {
for(int i=0;i<password.length();i++) {
if(numeros.charAt(j)==password.charAt(i)) {
cant++;
}
}
}
return cant;
}
public boolean esFuerte(String password)
{
boolean fuerte = false;
if(cantidadMayusculas(password)>=2 && cantidadMinusculas(password) >=1 && cantidadNumeros(password)>=3)
{
fuerte = true;
}
return fuerte;
}
}
| ISO-8859-10 | Java | 1,847 | java | Password.java | Java | []
| null | []
| package account;
import java.util.Random;
public class Password {
private int longitud =15;
private String contraseņa;
private Random randomGenerator = new Random();
private String mayusculas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private String minusculas = mayusculas.toLowerCase();
private String numeros = "0123456789";
private String todo = mayusculas + minusculas + numeros;
private int aleatoria;
public Password() {
this.contraseņa = generarPassword();
while(esFuerte(this.contraseņa)==false) {
this.contraseņa = generarPassword();
}
}
public String generarPassword() {
String nueva ="";
for(int i =0;i<this.longitud;i++) {
this.aleatoria = randomGenerator.nextInt(todo.length());
nueva += todo.charAt(aleatoria);
}
return nueva;
}
public int cantidadMayusculas(String password) {
int cant =0;
for(int j =0;j<mayusculas.length();j++) {
for(int i=0;i<password.length();i++) {
if(mayusculas.charAt(j)==password.charAt(i)) {
cant++;
}
}
}
return cant;
}
public int cantidadMinusculas(String password) {
int cant =0;
for(int j =0;j<minusculas.length();j++) {
for(int i=0;i<password.length();i++) {
if(minusculas.charAt(j)==password.charAt(i)) {
cant++;
}
}
}
return cant;
}
public int cantidadNumeros(String password) {
int cant =0;
for(int j =0;j<numeros.length();j++) {
for(int i=0;i<password.length();i++) {
if(numeros.charAt(j)==password.charAt(i)) {
cant++;
}
}
}
return cant;
}
public boolean esFuerte(String password)
{
boolean fuerte = false;
if(cantidadMayusculas(password)>=2 && cantidadMinusculas(password) >=1 && cantidadNumeros(password)>=3)
{
fuerte = true;
}
return fuerte;
}
}
| 1,847 | 0.623983 | 0.610418 | 82 | 20.475609 | 20.828115 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.414634 | false | false | 15 |
9148c8a0a15a16b5ba74f5c3475decfd271e61ad | 17,884,243,888,749 | 0a5226b3856c96d9cb1fd2718f8a8ecd70a63a43 | /src/main/java/com/snh48/picq/entity/snh48/RoomMessageAll.java | d48249ffa913a1bdab038b2a5c7f1fe1f29c73b5 | []
| no_license | ysbss/PICQ48 | https://github.com/ysbss/PICQ48 | 2fb67e5f73cb9b245d89fd0d9138609eb155306a | 055713998a5cd7fc250899ac6b63842f37d8cf54 | refs/heads/master | 2023-04-10T23:34:57.645000 | 2020-07-05T17:55:08 | 2020-07-05T17:55:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.snh48.picq.entity.snh48;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
* 口袋房间留言板消息表
*
* @author shiro
*
*/
@Data
@Entity
@Table(name = "POCKET_ROOM_MESSAGE_ALL")
public class RoomMessageAll implements Serializable {
private static final long serialVersionUID = 180878167764218327L;
/**
* 消息ID,对应msgidClient字段
*/
@Id
@Column(name = "ID", length = 200)
private String id;
/**
* 发送消息时间
*/
@Column(name = "MESSAGE_TIME")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date messageTime;
/**
* 发送人ID
*/
@Column(name = "SENDER_USER_ID")
private Long senderUserId;
/**
* 所属房间ID
*/
@Column(name = "ROOM_ID")
private Long roomId;
/**
* 消息类型
*/
@Column(name = "MESSAGE_TYPE", length = 20)
private String messageType;
/**
* 回复的消息ID
*/
@Column(name = "REPLY_ID", length = 200)
private String replyMessageId;
/**
* 被回复人昵称
*/
@Column(name = "REPLY_NAME", length = 100)
private String replyName;
/**
* 消息内容
*/
@Column(name = "MESSAGE_CONTENT", columnDefinition = "text")
private String messageContent;
}
| UTF-8 | Java | 1,527 | java | RoomMessageAll.java | Java | [
{
"context": "ort lombok.Data;\n\n/**\n * 口袋房间留言板消息表\n * \n * @author shiro\n *\n */\n@Data\n@Entity\n@Table(name = \"POCKET_ROOM_M",
"end": 393,
"score": 0.9995267391204834,
"start": 388,
"tag": "USERNAME",
"value": "shiro"
}
]
| null | []
| package com.snh48.picq.entity.snh48;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
/**
* 口袋房间留言板消息表
*
* @author shiro
*
*/
@Data
@Entity
@Table(name = "POCKET_ROOM_MESSAGE_ALL")
public class RoomMessageAll implements Serializable {
private static final long serialVersionUID = 180878167764218327L;
/**
* 消息ID,对应msgidClient字段
*/
@Id
@Column(name = "ID", length = 200)
private String id;
/**
* 发送消息时间
*/
@Column(name = "MESSAGE_TIME")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date messageTime;
/**
* 发送人ID
*/
@Column(name = "SENDER_USER_ID")
private Long senderUserId;
/**
* 所属房间ID
*/
@Column(name = "ROOM_ID")
private Long roomId;
/**
* 消息类型
*/
@Column(name = "MESSAGE_TYPE", length = 20)
private String messageType;
/**
* 回复的消息ID
*/
@Column(name = "REPLY_ID", length = 200)
private String replyMessageId;
/**
* 被回复人昵称
*/
@Column(name = "REPLY_NAME", length = 100)
private String replyName;
/**
* 消息内容
*/
@Column(name = "MESSAGE_CONTENT", columnDefinition = "text")
private String messageContent;
}
| 1,527 | 0.685094 | 0.661302 | 81 | 16.641975 | 18.126652 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.876543 | false | false | 15 |
2d883155617c6e1e84e0bb5d438e8611c376239f | 36,859,409,349,436 | 6425bd669dfb7b2f2d90bb00638dda178d6fe6ad | /src/main/java/com/musicstore/dao/DetailOrderDAO.java | edea3c2054c649fe2ddc86fea9eb7316d254df89 | []
| no_license | 14520582/MusicStore | https://github.com/14520582/MusicStore | e9cc338a50ec5ffad49332ee27e84a9f584f4812 | 09df10d44b4eb3b33a66e11db4790d7bd2ca41e2 | refs/heads/master | 2018-08-28T12:23:01.925000 | 2018-06-13T14:59:05 | 2018-06-13T14:59:05 | 118,346,433 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.musicstore.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.musicstore.entity.DetailOrder;
import com.musicstore.entity.Orders;
@Repository
public interface DetailOrderDAO extends CrudRepository<DetailOrder, Integer>{
@Query("select u from DetailOrder u where u.order.id = :idOrder and u.album.id = :idAlbum")
public DetailOrder findByIdAlbum(@Param("idOrder") int idOrder, @Param("idAlbum") int idAlbum);
@Query("delete from DetailOrder u where u.order.id = :id")
public void deleteByOrder(@Param("id") int id);
}
| UTF-8 | Java | 756 | java | DetailOrderDAO.java | Java | []
| null | []
| package com.musicstore.dao;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.musicstore.entity.DetailOrder;
import com.musicstore.entity.Orders;
@Repository
public interface DetailOrderDAO extends CrudRepository<DetailOrder, Integer>{
@Query("select u from DetailOrder u where u.order.id = :idOrder and u.album.id = :idAlbum")
public DetailOrder findByIdAlbum(@Param("idOrder") int idOrder, @Param("idAlbum") int idAlbum);
@Query("delete from DetailOrder u where u.order.id = :id")
public void deleteByOrder(@Param("id") int id);
}
| 756 | 0.784392 | 0.784392 | 18 | 41 | 30.739044 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 15 |
73c5bf27b79eb41098460704e2ec73a1b7625a89 | 26,783,416,059,965 | 838cf27c668522c83ef4cd59b9e4b26c1b622384 | /src/main/java/com/grinn/ui/ControlPanel.java | 893a4c01169a45d6fbb6a252d2875cf0886e709a | []
| no_license | AyGi/RkMonitor | https://github.com/AyGi/RkMonitor | e566b45205afea1176f65d6f0373cc23360e4454 | 673ce49b21a200b00e5335e4795a327e899c087c | refs/heads/master | 2016-02-25T14:41:26.374000 | 2014-10-16T12:52:40 | 2014-10-16T12:52:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.grinn.ui;
import com.grinn.ShiftControl;
import com.grinn.logic.*;
import com.grinn.logic.db.RkDbHelper;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import com.grinn.logic.ApplicationConstants.UiEntity;
public class ControlPanel extends JPanel{
private JPanel headPanel; // Head panel contains action button and change color if no db connection
private JLabel infoLHeadLabel;
private Color mainColor;
private JButton refresh, expand;
private RkDbHelper dbHelper = new RkDbHelper();
private Image refreshIc , expandIc;
private UiConstructor uiConstructor = new UiConstructor();
private JScrollPane infoScroll;
private int operationCode;
public ControlPanel(int operationCode){
this.operationCode = operationCode;
infoLHeadLabel = new JLabel();
infoLHeadLabel.setBounds(UiEntity.SMALL_INDENT * 4
,UiEntity.SMALL_INDENT * 2,150,30);
infoLHeadLabel.setForeground(Color.WHITE);
infoLHeadLabel.setFont(new Font("Arial", Font.BOLD, 14));
updateHeader();
try {
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
path = path.substring(0, path.length() - 21);
System.out.println(path);
System.out.println(getClass());
refreshIc = Toolkit.getDefaultToolkit()
.createImage(path + "refresh.png");
expandIc = Toolkit.getDefaultToolkit()
.createImage(path + "expand.png");
} catch (NullPointerException e) {
e.printStackTrace();
}
refresh = new JButton(new ImageIcon(refreshIc));
refresh.setBounds(UiEntity.PANEL_WIDTH
- (UiEntity.BTN_SIDE * 2)
- UiEntity.SMALL_INDENT
,UiEntity.SMALL_INDENT
,UiEntity.BTN_SIDE
,UiEntity.BTN_SIDE);
refresh.setBackground(mainColor);
refresh.setBorder(BorderFactory.createEmptyBorder());
refresh.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// information.setText(""); //remove old results
updateHeader();
updateComponentsColor( headPanel.getComponents());
updateResult();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
expand = new JButton (new ImageIcon(expandIc));
expand.setBounds(UiEntity.PANEL_WIDTH
- UiEntity.BTN_SIDE
- UiEntity.SMALL_INDENT
, UiEntity.SMALL_INDENT
, UiEntity.BTN_SIDE
, UiEntity.BTN_SIDE);
expand.setBackground(mainColor);
expand.setBorder(BorderFactory.createEmptyBorder());
expand.addMouseListener(ApplicationFrame.getHideListener());
headPanel = new JPanel();
headPanel.setBounds(0,0,UiEntity.PANEL_WIDTH
, UiEntity.HEAD_PANEL_HEIGHT);
headPanel.setLayout(null);
headPanel.setBackground(mainColor);
headPanel.add(expand);
headPanel.add(refresh);
headPanel.add(infoLHeadLabel);
add(headPanel);
setLayout(null);
setBounds(0, 0,
UiEntity.PANEL_WIDTH,
UiEntity.PANEL_HEIGHT);
setBackground(UiEntity.BACKGROUND_COLOR);
updateResult();
}
public void updateHeader(){
if(dbHelper.isConnect()){
mainColor = UiEntity.SUCCESS_COLOR;
infoLHeadLabel.setText("");
}else{
mainColor = UiEntity.FAIL_COLOR;
infoLHeadLabel.setText(ApplicationConstants.AppMessages.DB_ERROR);
}
}
public void updateResult(){
refreshScrollPane();
updateComponentsColor(headPanel.getComponents());
}
public void updateComponentsColor(Component... components){
headPanel.setBackground(mainColor);
for(Component component: components){
component.setBackground(mainColor);
}
}
public void refreshScrollPane(){
if(infoScroll != null)
remove(infoScroll);
try {
infoScroll = uiConstructor.constructScrollPanel(operationCode);
add(infoScroll);
mainColor = UiEntity.SUCCESS_COLOR;
} catch (SQLException e) {
mainColor = UiEntity.FAIL_COLOR;
infoLHeadLabel.setText(ApplicationConstants.AppMessages.DB_ERROR);
e.printStackTrace();
}
revalidate();
repaint();
}
}
| UTF-8 | Java | 5,103 | java | ControlPanel.java | Java | []
| null | []
| package com.grinn.ui;
import com.grinn.ShiftControl;
import com.grinn.logic.*;
import com.grinn.logic.db.RkDbHelper;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import com.grinn.logic.ApplicationConstants.UiEntity;
public class ControlPanel extends JPanel{
private JPanel headPanel; // Head panel contains action button and change color if no db connection
private JLabel infoLHeadLabel;
private Color mainColor;
private JButton refresh, expand;
private RkDbHelper dbHelper = new RkDbHelper();
private Image refreshIc , expandIc;
private UiConstructor uiConstructor = new UiConstructor();
private JScrollPane infoScroll;
private int operationCode;
public ControlPanel(int operationCode){
this.operationCode = operationCode;
infoLHeadLabel = new JLabel();
infoLHeadLabel.setBounds(UiEntity.SMALL_INDENT * 4
,UiEntity.SMALL_INDENT * 2,150,30);
infoLHeadLabel.setForeground(Color.WHITE);
infoLHeadLabel.setFont(new Font("Arial", Font.BOLD, 14));
updateHeader();
try {
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
path = path.substring(0, path.length() - 21);
System.out.println(path);
System.out.println(getClass());
refreshIc = Toolkit.getDefaultToolkit()
.createImage(path + "refresh.png");
expandIc = Toolkit.getDefaultToolkit()
.createImage(path + "expand.png");
} catch (NullPointerException e) {
e.printStackTrace();
}
refresh = new JButton(new ImageIcon(refreshIc));
refresh.setBounds(UiEntity.PANEL_WIDTH
- (UiEntity.BTN_SIDE * 2)
- UiEntity.SMALL_INDENT
,UiEntity.SMALL_INDENT
,UiEntity.BTN_SIDE
,UiEntity.BTN_SIDE);
refresh.setBackground(mainColor);
refresh.setBorder(BorderFactory.createEmptyBorder());
refresh.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
// information.setText(""); //remove old results
updateHeader();
updateComponentsColor( headPanel.getComponents());
updateResult();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
expand = new JButton (new ImageIcon(expandIc));
expand.setBounds(UiEntity.PANEL_WIDTH
- UiEntity.BTN_SIDE
- UiEntity.SMALL_INDENT
, UiEntity.SMALL_INDENT
, UiEntity.BTN_SIDE
, UiEntity.BTN_SIDE);
expand.setBackground(mainColor);
expand.setBorder(BorderFactory.createEmptyBorder());
expand.addMouseListener(ApplicationFrame.getHideListener());
headPanel = new JPanel();
headPanel.setBounds(0,0,UiEntity.PANEL_WIDTH
, UiEntity.HEAD_PANEL_HEIGHT);
headPanel.setLayout(null);
headPanel.setBackground(mainColor);
headPanel.add(expand);
headPanel.add(refresh);
headPanel.add(infoLHeadLabel);
add(headPanel);
setLayout(null);
setBounds(0, 0,
UiEntity.PANEL_WIDTH,
UiEntity.PANEL_HEIGHT);
setBackground(UiEntity.BACKGROUND_COLOR);
updateResult();
}
public void updateHeader(){
if(dbHelper.isConnect()){
mainColor = UiEntity.SUCCESS_COLOR;
infoLHeadLabel.setText("");
}else{
mainColor = UiEntity.FAIL_COLOR;
infoLHeadLabel.setText(ApplicationConstants.AppMessages.DB_ERROR);
}
}
public void updateResult(){
refreshScrollPane();
updateComponentsColor(headPanel.getComponents());
}
public void updateComponentsColor(Component... components){
headPanel.setBackground(mainColor);
for(Component component: components){
component.setBackground(mainColor);
}
}
public void refreshScrollPane(){
if(infoScroll != null)
remove(infoScroll);
try {
infoScroll = uiConstructor.constructScrollPanel(operationCode);
add(infoScroll);
mainColor = UiEntity.SUCCESS_COLOR;
} catch (SQLException e) {
mainColor = UiEntity.FAIL_COLOR;
infoLHeadLabel.setText(ApplicationConstants.AppMessages.DB_ERROR);
e.printStackTrace();
}
revalidate();
repaint();
}
}
| 5,103 | 0.606506 | 0.603175 | 155 | 31.922581 | 21.309557 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632258 | false | false | 15 |
fef3e537382a5d88ca30693ec8096f78605241b0 | 26,783,416,062,549 | 2b7ee80e65c9fcaecc01d7f550204329a134addd | /ztest.DesktopTests/src/org/acouster/gameTests/other/_JsonTest.java | 587eca44e40b77f733c79806801a087e3ffa63a9 | []
| no_license | miktemk/AcousterCommons | https://github.com/miktemk/AcousterCommons | ecdbd3b7c75944f444de4fa5ca8513254e12a710 | 81055e4f2a9d0b1b8fd518a218ec218fa20f5e15 | refs/heads/master | 2016-09-13T13:46:11.519000 | 2016-05-26T17:22:06 | 2016-05-26T17:22:06 | 59,766,205 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.acouster.gameTests.other;
import org.acouster.DebugUtil;
import org.acouster.context.desktop.DesktopResourceContext;
import org.json.simple.JsonField;
import org.json.simple.JsonSerialiser;
public class _JsonTest {
public _JsonTest()
{
super();
JsonTestClass diff = new JsonTestClass();
diff.skinBgFilename = "ahahahah you suck with women";
String ser = JsonSerialiser.serialize(diff);
JsonTestClass diff2 = JsonSerialiser.deserialize(JsonTestClass.class, ser);
//String parseme = "{\"nTries\":\"5\",\"nAntsMin\":\"5\",\"antCrawlSpeedFactor\":\"1.0\",\"nStones\":\"7\",\"nAntsMax\":\"10\",\"doWiggle\":\"false\",\"antCrawlSpeedFactor_\":\"1.0\"}";
//LevelDifficulty diff2 = JsonSerialiser.deserialize(LevelDifficulty.class, parseme);
DebugUtil.sss(ser);
DebugUtil.sss(diff);
DebugUtil.sss(diff2);
}
public static void main(String[] args) {
new DesktopResourceContext().makeInstance();
DesktopResourceContext.myInstance().setAssetPrefix("../zterminal.AntsStoned/assets");
DesktopResourceContext.myInstance().setBitmapPrefix("../zterminal.AntsStoned/res/drawable-hdpi");
new _JsonTest();
}
//=========================================================================================
private static class JsonTestClass
{
// ------------ difficulty settings --------------
@JsonField
public int nTries,
nStones,
nAntsMin,
nAntsMax;
@JsonField
public double antCrawlSpeedFactor,
antCrawlSpeedFactor_;
@JsonField
public boolean doWiggle = false;
@JsonField
public int nLosses;
// ------------ difficulty settings --------------
@JsonField
public int skinId;
@JsonField
public String skinBgFilename;
@Override
public String toString() {
return "BundleStruct [nTries=" + nTries + ", nStones=" + nStones
+ ", nAntsMin=" + nAntsMin + ", nAntsMax=" + nAntsMax
+ ", antCrawlSpeedFactor=" + antCrawlSpeedFactor
+ ", antCrawlSpeedFactor_=" + antCrawlSpeedFactor_
+ ", doWiggle=" + doWiggle + ", nLosses=" + nLosses
+ ", skinId=" + skinId + ", skinBgFilename=" + skinBgFilename
+ "]";
}
}
}
| UTF-8 | Java | 2,144 | java | _JsonTest.java | Java | []
| null | []
| package org.acouster.gameTests.other;
import org.acouster.DebugUtil;
import org.acouster.context.desktop.DesktopResourceContext;
import org.json.simple.JsonField;
import org.json.simple.JsonSerialiser;
public class _JsonTest {
public _JsonTest()
{
super();
JsonTestClass diff = new JsonTestClass();
diff.skinBgFilename = "ahahahah you suck with women";
String ser = JsonSerialiser.serialize(diff);
JsonTestClass diff2 = JsonSerialiser.deserialize(JsonTestClass.class, ser);
//String parseme = "{\"nTries\":\"5\",\"nAntsMin\":\"5\",\"antCrawlSpeedFactor\":\"1.0\",\"nStones\":\"7\",\"nAntsMax\":\"10\",\"doWiggle\":\"false\",\"antCrawlSpeedFactor_\":\"1.0\"}";
//LevelDifficulty diff2 = JsonSerialiser.deserialize(LevelDifficulty.class, parseme);
DebugUtil.sss(ser);
DebugUtil.sss(diff);
DebugUtil.sss(diff2);
}
public static void main(String[] args) {
new DesktopResourceContext().makeInstance();
DesktopResourceContext.myInstance().setAssetPrefix("../zterminal.AntsStoned/assets");
DesktopResourceContext.myInstance().setBitmapPrefix("../zterminal.AntsStoned/res/drawable-hdpi");
new _JsonTest();
}
//=========================================================================================
private static class JsonTestClass
{
// ------------ difficulty settings --------------
@JsonField
public int nTries,
nStones,
nAntsMin,
nAntsMax;
@JsonField
public double antCrawlSpeedFactor,
antCrawlSpeedFactor_;
@JsonField
public boolean doWiggle = false;
@JsonField
public int nLosses;
// ------------ difficulty settings --------------
@JsonField
public int skinId;
@JsonField
public String skinBgFilename;
@Override
public String toString() {
return "BundleStruct [nTries=" + nTries + ", nStones=" + nStones
+ ", nAntsMin=" + nAntsMin + ", nAntsMax=" + nAntsMax
+ ", antCrawlSpeedFactor=" + antCrawlSpeedFactor
+ ", antCrawlSpeedFactor_=" + antCrawlSpeedFactor_
+ ", doWiggle=" + doWiggle + ", nLosses=" + nLosses
+ ", skinId=" + skinId + ", skinBgFilename=" + skinBgFilename
+ "]";
}
}
}
| 2,144 | 0.64319 | 0.637593 | 74 | 27.972973 | 31.606094 | 187 | false | false | 0 | 0 | 0 | 0 | 92 | 0.04291 | 2.527027 | false | false | 15 |
33e049838f5bed1080bd55b190563bdd33cf68b2 | 14,319,420,998,727 | ca7c1560320870ba64c3fe45c95449a2cf3f93be | /Project9_InventoryApp Stage 2/app/src/main/java/com/example/raghadtaleb/project8_inventoryapp/MainActivity.java | 7f164868ed683fdcc60058bb9fb45c099e6e6f02 | []
| no_license | raghadt/Udacity-Android-Basic | https://github.com/raghadt/Udacity-Android-Basic | c3f00974ed9e6cf5ecd008f6becd9cbab49f327e | 225c271693ff29b945172d1b5d1eb77741f71914 | refs/heads/master | 2021-09-13T22:47:30.609000 | 2018-02-12T07:50:04 | 2018-02-12T07:50:04 | 111,285,796 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.raghadtaleb.project8_inventoryapp;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.raghadtaleb.project8_inventoryapp.data.Contract.nachosEntry;
import com.example.raghadtaleb.project8_inventoryapp.data.DbHelper;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int ITEM_LOADER = 0;
DbHelper helper;
ItemsCursorActivity cursorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getString(R.string.app_name));
helper = new DbHelper(this);
FloatingActionButton floatin = findViewById(R.id.floatin);
floatin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
ListView itemlistView = findViewById(R.id.list);
View emptyView = findViewById(R.id.empty_view);
itemlistView.setEmptyView(emptyView);
cursorAdapter = new ItemsCursorActivity(this, null);
itemlistView.setAdapter(cursorAdapter);
itemlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
Uri currentItemUri = ContentUris.withAppendedId(nachosEntry.CONTENT_URI, id);
intent.setData(currentItemUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(ITEM_LOADER, null, this);
}
private void deleteAllItems() {
int deletedRows = getContentResolver().delete(nachosEntry.CONTENT_URI, null, null);
Log.v("MainActivity", deletedRows + " ---------- deleted rows ");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete_all_data:
deleteAllItems();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] colum = {
nachosEntry._ID,
nachosEntry.COLUMN_NACHOS_NAME,
nachosEntry.COLUMN_SUPPLIER,
nachosEntry.COLUMN_QUANTITY,
nachosEntry.COLUMN_PRICE,
};
return new CursorLoader(this, nachosEntry.CONTENT_URI, colum, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
cursorAdapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
| UTF-8 | Java | 3,870 | java | MainActivity.java | Java | [
{
"context": "package com.example.raghadtaleb.project8_inventoryapp;\n\nimport android.app.Loader",
"end": 31,
"score": 0.9228721857070923,
"start": 20,
"tag": "USERNAME",
"value": "raghadtaleb"
},
{
"context": "id.widget.ListView;\n\nimport com.example.raghadtaleb.project8_inventoryapp.data.Contract.nachosEntry;\n",
"end": 662,
"score": 0.6352164149284363,
"start": 661,
"tag": "USERNAME",
"value": "b"
},
{
"context": "app.data.Contract.nachosEntry;\nimport com.example.raghadtaleb.project8_inventoryapp.data.DbHelper;\n\npublic clas",
"end": 742,
"score": 0.926374614238739,
"start": 731,
"tag": "USERNAME",
"value": "raghadtaleb"
}
]
| null | []
| package com.example.raghadtaleb.project8_inventoryapp;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.raghadtaleb.project8_inventoryapp.data.Contract.nachosEntry;
import com.example.raghadtaleb.project8_inventoryapp.data.DbHelper;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int ITEM_LOADER = 0;
DbHelper helper;
ItemsCursorActivity cursorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getString(R.string.app_name));
helper = new DbHelper(this);
FloatingActionButton floatin = findViewById(R.id.floatin);
floatin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
ListView itemlistView = findViewById(R.id.list);
View emptyView = findViewById(R.id.empty_view);
itemlistView.setEmptyView(emptyView);
cursorAdapter = new ItemsCursorActivity(this, null);
itemlistView.setAdapter(cursorAdapter);
itemlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
Uri currentItemUri = ContentUris.withAppendedId(nachosEntry.CONTENT_URI, id);
intent.setData(currentItemUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(ITEM_LOADER, null, this);
}
private void deleteAllItems() {
int deletedRows = getContentResolver().delete(nachosEntry.CONTENT_URI, null, null);
Log.v("MainActivity", deletedRows + " ---------- deleted rows ");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete_all_data:
deleteAllItems();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] colum = {
nachosEntry._ID,
nachosEntry.COLUMN_NACHOS_NAME,
nachosEntry.COLUMN_SUPPLIER,
nachosEntry.COLUMN_QUANTITY,
nachosEntry.COLUMN_PRICE,
};
return new CursorLoader(this, nachosEntry.CONTENT_URI, colum, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
cursorAdapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
| 3,870 | 0.67416 | 0.67261 | 125 | 29.959999 | 26.960535 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64 | false | false | 15 |
18e90309891ae16b5d2be7ff3f7709df72b95494 | 13,159,779,828,163 | 09cd00b07599b877d170d73f1e63ca135663f499 | /src/test/java/com/djohannes/ac/za/controller/colour/ColourControllerTest.java | ff41808e2a76dc19ea8a94ede83d794e3868e59b | []
| no_license | Azzurri01/dayCareCenter_216001730_PT_Dimitri_Johannes | https://github.com/Azzurri01/dayCareCenter_216001730_PT_Dimitri_Johannes | 9c86ae8651205e87cc8ebd50c75016e39f935a2b | 28c34b24cd9052b33995e9f088c2768bd2e5baa1 | refs/heads/master | 2022-07-06T20:50:37.509000 | 2019-10-02T21:03:51 | 2019-10-02T21:03:51 | 180,637,975 | 0 | 0 | null | false | 2022-06-21T01:58:29 | 2019-04-10T18:12:12 | 2019-10-02T21:03:56 | 2022-06-21T01:58:29 | 1,520 | 0 | 0 | 2 | Java | false | false | package com.djohannes.ac.za.controller.colour;
import com.djohannes.ac.za.domain.colour.Colour;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class ColourControllerTest {
@Autowired
private TestRestTemplate restTemplate;
private String baseURL="http://localhost:8080/dccs/colour";
@Test
public void testGetAll() {
ResponseEntity result = restTemplate.withBasicAuth("dimitri", "cputPTguest")
.getForEntity(baseURL + "/getall", String.class);
System.out.println(result.getBody());
Assert.assertEquals(HttpStatus.OK, result.getStatusCodeValue());
}
@Test
public void testGetColourById() {
Colour colour = restTemplate.getForObject(baseURL + "/colour/1", Colour.class);
System.out.println(colour.getId());
assertNotNull(colour);
}
@Test
public void testCreateColour() {
ResponseEntity result = restTemplate.withBasicAuth("admin", "cputPTadmin")
.postForEntity( baseURL + "/create/red", MediaType.APPLICATION_JSON, String.class);
System.out.println(result.getBody());
assertEquals(HttpStatus.OK, result.getStatusCode());
}
@Test
public void testUpdateColour() {
int id = 1;
Colour colour = restTemplate.getForObject(baseURL + "/colour/" + id, Colour.class);
restTemplate.put(baseURL + "/colours/" + id, colour);
Colour updatedColour = restTemplate.getForObject(baseURL + "/Colour/" + id, Colour.class);
assertNotNull(updatedColour);
}
@Test
public void testDeleteColour() {
int id = 2;
Colour colour = restTemplate.getForObject(baseURL + "/colours/" + id, Colour.class);
assertNotNull(colour);
restTemplate.delete(baseURL + "/activities/" + id);
try {
colour = restTemplate.getForObject(baseURL + "/colours/" + id, Colour.class);
} catch (final HttpClientErrorException e) {
assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND);
}
}
}
| UTF-8 | Java | 2,739 | java | ColourControllerTest.java | Java | [
{
"context": "sponseEntity result = restTemplate.withBasicAuth(\"dimitri\", \"cputPTguest\")\n .getForEntity(ba",
"end": 1100,
"score": 0.9677988886833191,
"start": 1093,
"tag": "USERNAME",
"value": "dimitri"
}
]
| null | []
| package com.djohannes.ac.za.controller.colour;
import com.djohannes.ac.za.domain.colour.Colour;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class ColourControllerTest {
@Autowired
private TestRestTemplate restTemplate;
private String baseURL="http://localhost:8080/dccs/colour";
@Test
public void testGetAll() {
ResponseEntity result = restTemplate.withBasicAuth("dimitri", "cputPTguest")
.getForEntity(baseURL + "/getall", String.class);
System.out.println(result.getBody());
Assert.assertEquals(HttpStatus.OK, result.getStatusCodeValue());
}
@Test
public void testGetColourById() {
Colour colour = restTemplate.getForObject(baseURL + "/colour/1", Colour.class);
System.out.println(colour.getId());
assertNotNull(colour);
}
@Test
public void testCreateColour() {
ResponseEntity result = restTemplate.withBasicAuth("admin", "cputPTadmin")
.postForEntity( baseURL + "/create/red", MediaType.APPLICATION_JSON, String.class);
System.out.println(result.getBody());
assertEquals(HttpStatus.OK, result.getStatusCode());
}
@Test
public void testUpdateColour() {
int id = 1;
Colour colour = restTemplate.getForObject(baseURL + "/colour/" + id, Colour.class);
restTemplate.put(baseURL + "/colours/" + id, colour);
Colour updatedColour = restTemplate.getForObject(baseURL + "/Colour/" + id, Colour.class);
assertNotNull(updatedColour);
}
@Test
public void testDeleteColour() {
int id = 2;
Colour colour = restTemplate.getForObject(baseURL + "/colours/" + id, Colour.class);
assertNotNull(colour);
restTemplate.delete(baseURL + "/activities/" + id);
try {
colour = restTemplate.getForObject(baseURL + "/colours/" + id, Colour.class);
} catch (final HttpClientErrorException e) {
assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND);
}
}
}
| 2,739 | 0.703541 | 0.700621 | 70 | 38.128571 | 29.047213 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.728571 | false | false | 15 |
124171328edc14a0770bf09ea8c36e3b57d921b4 | 20,426,864,502,397 | ee971725b2b38c5ec8ad1c9d49f4d4265edee9cc | /PLAK/src/main/java/hello/dcsms/plak/widget/MToast.java | 5c485441d5e5cc94a6114f32bc532081614d6de5 | []
| no_license | Rupunx/Plak | https://github.com/Rupunx/Plak | cd216f8659593c9fd644edd3088a44677dcb426b | 5ddbada956d9d924826af931316c5994a13c36a4 | refs/heads/master | 2020-02-04T13:34:48.452000 | 2015-06-21T19:10:06 | 2015-06-21T19:10:06 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hello.dcsms.plak.widget;
import android.content.Context;
import android.widget.Toast;
/**
* Created by jmkl on 4/27/2015.
*/
public class MToast {
public static void show(Context context, String msg) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
| UTF-8 | Java | 307 | java | MToast.java | Java | [
{
"context": "import android.widget.Toast;\r\n\r\n/**\r\n * Created by jmkl on 4/27/2015.\r\n */\r\npublic class MToast {\r\n\r\n\r\n ",
"end": 124,
"score": 0.9996653199195862,
"start": 120,
"tag": "USERNAME",
"value": "jmkl"
}
]
| null | []
| package hello.dcsms.plak.widget;
import android.content.Context;
import android.widget.Toast;
/**
* Created by jmkl on 4/27/2015.
*/
public class MToast {
public static void show(Context context, String msg) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
| 307 | 0.65798 | 0.635179 | 15 | 18.466667 | 20.809826 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 15 |
33d13419ff711d6c202bf5c05d800e8218539285 | 10,780,367,956,277 | d0f49e14c51546bc27142693553c4a363b74eaaf | /FileRouge/src/main/java/groupe1/filrouge/entity/Piece.java | 7f47c317e07499377ef5ba550825857acc7638fd | []
| no_license | reuxm/Fil_Rouge | https://github.com/reuxm/Fil_Rouge | 8413a2c599b4a58dc8779b7202060dbb0a59b168 | 7ef8a3d017aa1a8875736dd5d364ce529acc7daa | refs/heads/master | 2023-01-12T03:52:22.742000 | 2020-02-13T14:59:15 | 2020-02-13T14:59:15 | 232,321,364 | 2 | 0 | null | false | 2023-01-07T14:34:52 | 2020-01-07T12:36:21 | 2020-02-13T14:59:22 | 2023-01-07T14:34:51 | 3,753 | 1 | 0 | 27 | JavaScript | false | false | package groupe1.filrouge.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Marie
* @version 1.0
* @since 2020-01-16 <br>
* <b> Java Doc pour le projet fil rouge</b>
*/
@Entity
@Table( name="pieces" )
public class Piece {
/**
* JAVADOC Id Piece est génerer par Hibernate
*/
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Integer id;
@Column( name="libelle", length = 50, nullable=false )
private String libelle;
/**
* JAVADOC la quantité des pieces
*/
@Column( name="quantite", nullable=true )
private Integer qte;
/**
* JAVADOC la date de création du piece
*/
@Temporal(TemporalType.DATE)
@Column( name="date_saisie", nullable=true )
private Date dateCreation;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public Integer getQte() {
return qte;
}
public void setQte(Integer qte) {
this.qte = qte;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
}
| UTF-8 | Java | 1,472 | java | Piece.java | Java | [
{
"context": "ort javax.persistence.TemporalType;\n/**\n * @author Marie\n * @version 1.0\n * @since 2020-01-16 <br>\n * <b> ",
"end": 361,
"score": 0.999798059463501,
"start": 356,
"tag": "NAME",
"value": "Marie"
}
]
| null | []
| package groupe1.filrouge.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* @author Marie
* @version 1.0
* @since 2020-01-16 <br>
* <b> Java Doc pour le projet fil rouge</b>
*/
@Entity
@Table( name="pieces" )
public class Piece {
/**
* JAVADOC Id Piece est génerer par Hibernate
*/
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Integer id;
@Column( name="libelle", length = 50, nullable=false )
private String libelle;
/**
* JAVADOC la quantité des pieces
*/
@Column( name="quantite", nullable=true )
private Integer qte;
/**
* JAVADOC la date de création du piece
*/
@Temporal(TemporalType.DATE)
@Column( name="date_saisie", nullable=true )
private Date dateCreation;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public Integer getQte() {
return qte;
}
public void setQte(Integer qte) {
this.qte = qte;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
}
| 1,472 | 0.71341 | 0.704561 | 75 | 18.586666 | 16.298952 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.053333 | false | false | 15 |
737b8a27cd4adfe27636c2fe16c9be03e248b149 | 12,283,606,511,066 | 6676d63e3b42b28989e88de94205ed2ccc8c6c2d | /ezen_tour/src/main/java/com/ezen/tour/manager/packDetail/model/ManagerDetailService.java | 00d53dd92ab7e2c35da7cddd874d245583ef00b3 | []
| no_license | ezenTuor/ezenTour | https://github.com/ezenTuor/ezenTour | 3a1d54538f92d5de48c2999cb2fd955d317ded0c | a3843fb00df40d17ccc7767fa03f007828e4c80b | refs/heads/master | 2020-12-05T21:58:36.562000 | 2020-02-14T09:05:57 | 2020-02-14T09:05:57 | 232,257,349 | 1 | 1 | null | false | 2020-06-18T17:07:58 | 2020-01-07T06:23:32 | 2020-02-14T09:06:14 | 2020-06-18T17:07:56 | 27,997 | 0 | 1 | 5 | Java | false | false | package com.ezen.tour.manager.packDetail.model;
import java.util.List;
public interface ManagerDetailService {
int insertDetail(ManagerDetailVO detailVo);
ManagerDetailVO selectDetail(int packDno);
List<ManagerDetailVO> selectDetailsByPackNo(int packNo);
ManagerDetailViewVO selectDetailView(int packDno);
}
| UTF-8 | Java | 324 | java | ManagerDetailService.java | Java | []
| null | []
| package com.ezen.tour.manager.packDetail.model;
import java.util.List;
public interface ManagerDetailService {
int insertDetail(ManagerDetailVO detailVo);
ManagerDetailVO selectDetail(int packDno);
List<ManagerDetailVO> selectDetailsByPackNo(int packNo);
ManagerDetailViewVO selectDetailView(int packDno);
}
| 324 | 0.808642 | 0.808642 | 10 | 30.4 | 21.467184 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 15 |
529a647b99aa15efe970617aadbc65c65ca92c15 | 30,262,339,606,717 | c8736a9594994c951f3c72882749070e4497766f | /src/Editor/View.java | 5b7f69a38380e011582263c9124448552d87370d | []
| no_license | several27/SpaceCadets-4-BareBoneEditor | https://github.com/several27/SpaceCadets-4-BareBoneEditor | 28ce3e2bc38e1ef99e27bebd10ce38eb8e6d2814 | bb5058555868fd632d5013085f61c5c39b449a7d | refs/heads/master | 2021-01-10T04:17:30.525000 | 2015-10-29T15:13:33 | 2015-10-29T15:13:33 | 45,046,762 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Editor;
/**
* Created by maciej on 26/10/15.
*/
public class View
{
}
| UTF-8 | Java | 81 | java | View.java | Java | [
{
"context": "package Editor;\n\n/**\n * Created by maciej on 26/10/15.\n */\npublic class View\n{\n}\n",
"end": 41,
"score": 0.9995707869529724,
"start": 35,
"tag": "USERNAME",
"value": "maciej"
}
]
| null | []
| package Editor;
/**
* Created by maciej on 26/10/15.
*/
public class View
{
}
| 81 | 0.62963 | 0.555556 | 8 | 9.125 | 10.936607 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.125 | false | false | 15 |
c3b551c6baf8a57da35ea8e8d485f6d1fc61df66 | 11,501,922,460,170 | ddca0b74f958181ca7291cabd1e9bbebacf18829 | /src/main/java/com/yuqincar/dao/privilege/impl/DepartmentDaoImpl.java | 6ff050ce3bd12ae5fd0a180249966995d2daf8b1 | []
| no_license | cqucuimao/SSH-Project | https://github.com/cqucuimao/SSH-Project | 39083fdd606c7285f3294a95470b0ea37f5a6901 | 701b5ba0c47465f5391b4905fd1567bfc53f9a5b | refs/heads/master | 2021-06-16T06:05:35.417000 | 2017-04-25T06:04:12 | 2017-04-25T06:04:12 | 89,456,486 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yuqincar.dao.privilege.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.yuqincar.dao.common.impl.BaseDaoImpl;
import com.yuqincar.dao.privilege.DepartmentDao;
import com.yuqincar.domain.order.Order;
import com.yuqincar.domain.privilege.Department;
import com.yuqincar.domain.privilege.User;
@Repository
public class DepartmentDaoImpl extends BaseDaoImpl<Department> implements DepartmentDao{
public List<Department> findChildren(Long parentId) {
return getSession().createQuery(//
"FROM Department d WHERE d.parent.id=?")//
.setParameter(0, parentId)//
.list();
}
public List<Department> findTopList() {
return getSession().createQuery(//
"FROM Department d WHERE d.parent IS NULL")//
.list();
}
public boolean canDeleteDepartment(Long id) {
List<User> users = getSession().createQuery("from User where department.id=?").
setParameter(0, id).list();
if(users.size() != 0)
return false;
return true;
}
public Department getDepartmentByName(String name) {
return (Department)getSession().createQuery(//
"FROM Department d WHERE d.name=?")//
.setParameter(0, name)
.uniqueResult();
}
}
| UTF-8 | Java | 1,256 | java | DepartmentDaoImpl.java | Java | []
| null | []
| package com.yuqincar.dao.privilege.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.yuqincar.dao.common.impl.BaseDaoImpl;
import com.yuqincar.dao.privilege.DepartmentDao;
import com.yuqincar.domain.order.Order;
import com.yuqincar.domain.privilege.Department;
import com.yuqincar.domain.privilege.User;
@Repository
public class DepartmentDaoImpl extends BaseDaoImpl<Department> implements DepartmentDao{
public List<Department> findChildren(Long parentId) {
return getSession().createQuery(//
"FROM Department d WHERE d.parent.id=?")//
.setParameter(0, parentId)//
.list();
}
public List<Department> findTopList() {
return getSession().createQuery(//
"FROM Department d WHERE d.parent IS NULL")//
.list();
}
public boolean canDeleteDepartment(Long id) {
List<User> users = getSession().createQuery("from User where department.id=?").
setParameter(0, id).list();
if(users.size() != 0)
return false;
return true;
}
public Department getDepartmentByName(String name) {
return (Department)getSession().createQuery(//
"FROM Department d WHERE d.name=?")//
.setParameter(0, name)
.uniqueResult();
}
}
| 1,256 | 0.703822 | 0.700637 | 46 | 25.304348 | 23.098907 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.73913 | false | false | 15 |
35bf66f85bc59183ea03f7ff1da0a6f322ea4480 | 39,298,950,786,662 | 03e214ef1943b9500d1666e4c98f021005fcc4df | /src/main/java/m6/s11/Main.java | 20339d1322948c06862c40d908fd860c9f9fecac | []
| no_license | Stefano2107/mpjp | https://github.com/Stefano2107/mpjp | 496a61f30571b20b6acb6569b36d187339d2fed2 | b74aa20ca9db279f70cbd0e1141b124a8ccf3ea5 | refs/heads/master | 2022-08-29T22:08:19.601000 | 2020-05-27T09:54:09 | 2020-05-27T09:54:09 | 267,278,797 | 0 | 1 | null | true | 2020-05-27T09:37:01 | 2020-05-27T09:37:00 | 2020-05-21T08:40:35 | 2020-05-21T08:40:33 | 819 | 0 | 0 | 0 | null | false | false | package m6.s11;
public class Main {
public static void main(String[] args) {
Warrior tom = new Warrior();
System.out.println("A simple warrior. He could only fight.");
System.out.println("Tom fighting power is: " + tom.fight());
System.out.println("Something happens here.");
MysticWarrior magicTom = new MysticWarrior(tom);
System.out.println("Now he could heal, too!");
System.out.println("His fighting power is still: " + magicTom.fight());
System.out.println("His healing power is: " + magicTom.heal());
}
}
| UTF-8 | Java | 604 | java | Main.java | Java | []
| null | []
| package m6.s11;
public class Main {
public static void main(String[] args) {
Warrior tom = new Warrior();
System.out.println("A simple warrior. He could only fight.");
System.out.println("Tom fighting power is: " + tom.fight());
System.out.println("Something happens here.");
MysticWarrior magicTom = new MysticWarrior(tom);
System.out.println("Now he could heal, too!");
System.out.println("His fighting power is still: " + magicTom.fight());
System.out.println("His healing power is: " + magicTom.heal());
}
}
| 604 | 0.614238 | 0.609272 | 17 | 34.529411 | 28.01075 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 15 |
c02a3cfdb3e74b07ffc1f549b243e441cb5d1f5f | 38,311,108,313,118 | 1780b1bfe23995e8e6a4819f62aab676276dfd46 | /tfr1/heimadæmi/hd9/d1/Fibonacci.java | 365b5a9a99e3c5c40ea9da6764c76bf6c400a778 | []
| no_license | teyter/uni | https://github.com/teyter/uni | 6cfd9413fba0efd4a4fabcf6d64c7d158345f8be | 57c895e1d2615f9c443e5c13feb93aeae75f2b27 | refs/heads/master | 2022-12-07T18:19:03.861000 | 2020-08-26T12:31:52 | 2020-08-26T12:31:52 | 152,748,096 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Fibonacci {
public static void Fib(int lo, int hi) {
int a = 0; int b = 1;
for(int i = 0; i <= hi; i++) {
if (a > lo && a < hi)
System.out.print(a + " ");
int sum = a + b;
a = b;
b = sum;
} System.out.println();
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int M = Integer.parseInt(args[1]);
Fib(N,M);
}
}
| UTF-8 | Java | 480 | java | Fibonacci.java | Java | []
| null | []
| public class Fibonacci {
public static void Fib(int lo, int hi) {
int a = 0; int b = 1;
for(int i = 0; i <= hi; i++) {
if (a > lo && a < hi)
System.out.print(a + " ");
int sum = a + b;
a = b;
b = sum;
} System.out.println();
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int M = Integer.parseInt(args[1]);
Fib(N,M);
}
}
| 480 | 0.43125 | 0.420833 | 17 | 27.235294 | 13.960151 | 44 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.823529 | false | false | 15 |
b8c823a1150f7186372ff8200f343f462e097382 | 38,311,108,312,998 | a02cf8ac282e59d404683fca9c99b23a3f23ba52 | /src/main/java/com/hikvision/ga/pandora/cas/shiro/SpringShiroFilterFactoryBean.java | 374dc9874d0ec415bc0d25accf6525ba402d1eaf | []
| no_license | j1nsh1/pandor-cas-client | https://github.com/j1nsh1/pandor-cas-client | aaeb2a521163753367281cad10ca92affcf41655 | c7a6ebb95892f9bd8b4cf923384356b43daa4503 | refs/heads/master | 2016-09-23T03:28:20.483000 | 2016-07-26T15:28:46 | 2016-07-26T15:28:46 | 63,943,837 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hikvision.ga.pandora.cas.shiro;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.util.Nameable;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import javax.servlet.Filter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by j1nsh1 on 2016/7/24.
*/
public class SpringShiroFilterFactoryBean extends ShiroFilterFactoryBean {
private static final transient Logger log = LoggerFactory.getLogger(SpringShiroFilterFactoryBean.class);
private FilterChainManagerProxy filterChainManagerProxy;
/**
* 将PathMatchingFilterChainResolver放入,通过proxy对PathMatchingFilterChainResolver进行操作
*/
private FilterChainResolverProxy filterChainResolverProxy;
public FilterChainManagerProxy getFilterChainManagerProxy() {
return filterChainManagerProxy;
}
public void setFilterChainManagerProxy(FilterChainManagerProxy filterChainManagerProxy) {
this.filterChainManagerProxy = filterChainManagerProxy;
}
public FilterChainResolverProxy getFilterChainResolverProxy() {
return filterChainResolverProxy;
}
public void setFilterChainResolverProxy(FilterChainResolverProxy filterChainResolverProxy) {
this.filterChainResolverProxy = filterChainResolverProxy;
}
protected FilterChainManager createFilterChainManager() {
FilterChainManager filterChainManager = super.createFilterChainManager();
filterChainManagerProxy.setFilterChainManager(filterChainManager);
return filterChainManager;
}
protected AbstractShiroFilter createInstance() throws Exception {
AbstractShiroFilter shiroFilter = super.createInstance();
filterChainResolverProxy.setFilterChainResolver(shiroFilter.getFilterChainResolver());
return shiroFilter;
}
}
| UTF-8 | Java | 2,837 | java | SpringShiroFilterFactoryBean.java | Java | [
{
"context": "dHashMap;\nimport java.util.Map;\n\n/**\n * Created by j1nsh1 on 2016/7/24.\n */\npublic class SpringShiroFilterF",
"end": 1292,
"score": 0.999494194984436,
"start": 1286,
"tag": "USERNAME",
"value": "j1nsh1"
}
]
| null | []
| package com.hikvision.ga.pandora.cas.shiro;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.util.Nameable;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import javax.servlet.Filter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Created by j1nsh1 on 2016/7/24.
*/
public class SpringShiroFilterFactoryBean extends ShiroFilterFactoryBean {
private static final transient Logger log = LoggerFactory.getLogger(SpringShiroFilterFactoryBean.class);
private FilterChainManagerProxy filterChainManagerProxy;
/**
* 将PathMatchingFilterChainResolver放入,通过proxy对PathMatchingFilterChainResolver进行操作
*/
private FilterChainResolverProxy filterChainResolverProxy;
public FilterChainManagerProxy getFilterChainManagerProxy() {
return filterChainManagerProxy;
}
public void setFilterChainManagerProxy(FilterChainManagerProxy filterChainManagerProxy) {
this.filterChainManagerProxy = filterChainManagerProxy;
}
public FilterChainResolverProxy getFilterChainResolverProxy() {
return filterChainResolverProxy;
}
public void setFilterChainResolverProxy(FilterChainResolverProxy filterChainResolverProxy) {
this.filterChainResolverProxy = filterChainResolverProxy;
}
protected FilterChainManager createFilterChainManager() {
FilterChainManager filterChainManager = super.createFilterChainManager();
filterChainManagerProxy.setFilterChainManager(filterChainManager);
return filterChainManager;
}
protected AbstractShiroFilter createInstance() throws Exception {
AbstractShiroFilter shiroFilter = super.createInstance();
filterChainResolverProxy.setFilterChainResolver(shiroFilter.getFilterChainResolver());
return shiroFilter;
}
}
| 2,837 | 0.813499 | 0.809591 | 69 | 39.7971 | 29.951448 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 15 |
432c241658059d798ddd80cf3e2467fec6b97ac2 | 23,897,198,093,225 | 683d1ee7875ec2456c298986330eb954401dfb4c | /app/src/main/java/com/jaychang/demo/slm/MainActivity.java | 8dc2002b72749c5b8982e21710b4d81630952763 | [
"Apache-2.0"
]
| permissive | seriabov/SocialLoginManager | https://github.com/seriabov/SocialLoginManager | fad383db9a3d06b6541a2248c7020eff8f44c800 | 281ec2206afafd7a351fa1fca108b1a82b4545e0 | refs/heads/master | 2021-06-12T15:06:31.388000 | 2017-03-23T18:03:07 | 2017-03-23T18:03:07 | 85,560,452 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jaychang.demo.slm;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import com.jaychang.slm.SocialLoginManager;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fbLoginButton = (Button) findViewById(R.id.fbLoginButton);
fbLoginButton.setOnClickListener(view -> {
loginByFacebook();
});
Button googleLoginButton = (Button) findViewById(R.id.googleLoginButton);
googleLoginButton.setOnClickListener(view -> {
loginByGoogle();
});
}
private void loginByFacebook() {
SocialLoginManager.getInstance(this)
.facebook()
.login()
.subscribe(socialUser -> {
Log.d(TAG, "userId: " + socialUser.userId);
Log.d(TAG, "photoUrl: " + socialUser.photoUrl);
Log.d(TAG, "accessToken: " + socialUser.accessToken);
Log.d(TAG, "name: " + socialUser.profile.name);
Log.d(TAG, "email: " + socialUser.profile.email);
Log.d(TAG, "pageLink: " + socialUser.profile.pageLink);
},
error -> {
Log.d(TAG, "error: " + error.getMessage());
});
}
private void loginByGoogle() {
SocialLoginManager.getInstance(this)
.google(getString(R.string.default_web_client_id))
.login()
.subscribe(socialUser -> {
Log.d(TAG, "userId: " + socialUser.userId);
Log.d(TAG, "photoUrl: " + socialUser.photoUrl);
Log.d(TAG, "accessToken: " + socialUser.accessToken);
Log.d(TAG, "email: " + socialUser.profile.email);
Log.d(TAG, "name: " + socialUser.profile.name);
},
error -> {
Log.d(TAG, "error: " + error.getMessage());
});
}
}
| UTF-8 | Java | 1,985 | java | MainActivity.java | Java | []
| null | []
| package com.jaychang.demo.slm;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import com.jaychang.slm.SocialLoginManager;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fbLoginButton = (Button) findViewById(R.id.fbLoginButton);
fbLoginButton.setOnClickListener(view -> {
loginByFacebook();
});
Button googleLoginButton = (Button) findViewById(R.id.googleLoginButton);
googleLoginButton.setOnClickListener(view -> {
loginByGoogle();
});
}
private void loginByFacebook() {
SocialLoginManager.getInstance(this)
.facebook()
.login()
.subscribe(socialUser -> {
Log.d(TAG, "userId: " + socialUser.userId);
Log.d(TAG, "photoUrl: " + socialUser.photoUrl);
Log.d(TAG, "accessToken: " + socialUser.accessToken);
Log.d(TAG, "name: " + socialUser.profile.name);
Log.d(TAG, "email: " + socialUser.profile.email);
Log.d(TAG, "pageLink: " + socialUser.profile.pageLink);
},
error -> {
Log.d(TAG, "error: " + error.getMessage());
});
}
private void loginByGoogle() {
SocialLoginManager.getInstance(this)
.google(getString(R.string.default_web_client_id))
.login()
.subscribe(socialUser -> {
Log.d(TAG, "userId: " + socialUser.userId);
Log.d(TAG, "photoUrl: " + socialUser.photoUrl);
Log.d(TAG, "accessToken: " + socialUser.accessToken);
Log.d(TAG, "email: " + socialUser.profile.email);
Log.d(TAG, "name: " + socialUser.profile.name);
},
error -> {
Log.d(TAG, "error: " + error.getMessage());
});
}
}
| 1,985 | 0.633753 | 0.633249 | 64 | 30.015625 | 23.69104 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703125 | false | false | 15 |
ff0184426ee7b8c976800dd25245b47d8bdee5b6 | 2,087,354,140,527 | 57234da8dfb0b3e1d7797eaa3543148ba4ad3b36 | /web/src/main/java/com/tek42/docs/webapp/controller/ListDocsController.java | f0397d8c13534e2a597df4f74f5b692dbc123f0c | []
| no_license | kapabh/test1 | https://github.com/kapabh/test1 | d9fadc41d4f618bde8970b403b78799229745612 | bd81139c46f946d37784fb17ad3af914d031a672 | refs/heads/master | 2020-02-27T21:35:35.099000 | 2012-09-23T14:40:42 | 2012-09-23T14:40:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tek42.docs.webapp.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.ModelAndView;
import com.tek42.docs.model.Doc;
import com.tek42.docs.service.DocService;
import com.tek42.base.webapp.util.RequestUtil;
/**
* Controller for viewing documents
* @author Mike
* Date: Nov 3, 2008 10:47:25 AM
*/
public class ListDocsController extends AbstractController {
DocService docService;
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Doc> docs = docService.getAll();
List<Doc> privateDocs = docService.getPrivateDocs();
ModelAndView mav = new ModelAndView("docs/list");
mav.addObject("docs", docs);
mav.addObject("privateDocs", privateDocs);
return mav;
}
public void setDocService(DocService docService) {
this.docService = docService;
}
}
| UTF-8 | Java | 1,044 | java | ListDocsController.java | Java | [
{
"context": "/**\n * Controller for viewing documents\n * @author Mike\n * Date: Nov 3, 2008 10:47:25 AM\n */\npubl",
"end": 455,
"score": 0.980083703994751,
"start": 451,
"tag": "NAME",
"value": "Mike"
}
]
| null | []
| package com.tek42.docs.webapp.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.ModelAndView;
import com.tek42.docs.model.Doc;
import com.tek42.docs.service.DocService;
import com.tek42.base.webapp.util.RequestUtil;
/**
* Controller for viewing documents
* @author Mike
* Date: Nov 3, 2008 10:47:25 AM
*/
public class ListDocsController extends AbstractController {
DocService docService;
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Doc> docs = docService.getAll();
List<Doc> privateDocs = docService.getPrivateDocs();
ModelAndView mav = new ModelAndView("docs/list");
mav.addObject("docs", docs);
mav.addObject("privateDocs", privateDocs);
return mav;
}
public void setDocService(DocService docService) {
this.docService = docService;
}
}
| 1,044 | 0.779693 | 0.761494 | 38 | 26.473684 | 26.525793 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.052632 | false | false | 15 |
61f500a6e7f118f4104eda25b0e43d910b79ee73 | 592,705,494,923 | 8e153a2747aa8b4f30adcb5d0e40aa5b183381a3 | /src/main/java/com/zy/study/ps/com/ProxyFirstChecker.java | e04311a985c2e78862b5adb31e3ade33f883791a | []
| no_license | zy134134/proxy-scraper | https://github.com/zy134134/proxy-scraper | 42259f8343682d2251d23475ca8170fb74610192 | 9b02d9b2aa9548049c0e1c846c3abbdc74c16333 | refs/heads/master | 2020-04-14T10:23:32.583000 | 2019-02-11T06:54:30 | 2019-02-11T06:54:30 | 163,785,506 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zy.study.ps.com;
import com.zy.study.ps.biz.ProxyValidator;
import com.zy.study.ps.bo.ProxyInfoBO;
import com.zy.study.ps.workflow.InboundType;
import com.zy.study.ps.workflow.Pushable;
import com.zy.study.ps.workflow.WorkFlow;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
@Component
@Slf4j
public class ProxyFirstChecker {
@Autowired
private ProxyDbAccessor proxyDbAccessor;
@Autowired
private SchedulerManager schedulerManager;
@Autowired
private ProxyPoolManager proxyPoolManager;
private Pushable<ProxyInfoBO> subject;
@PostConstruct
public void initial() {
subject =
WorkFlow.create(new InboundType<ProxyInfoBO>())
.filter(this::notExist)
.filterAsync(this::validate)
.workOn(schedulerManager.sqlite()).foreach(this::insert);
}
private boolean notExist(ProxyInfoBO proxyInfoBO) {
boolean exist = proxyPoolManager.exist(proxyInfoBO);
if(exist){
log.warn(String.format("已存在IP%s(%s)", proxyInfoBO.getIp(), proxyInfoBO.getSource()));
}
return !exist;
}
private void insert(ProxyInfoBO proxyInfoBO1) {
proxyDbAccessor.insert(proxyInfoBO1);
}
private CompletableFuture<Boolean> validate(ProxyInfoBO proxyInfo) {
CompletableFuture<Response> future=ProxyValidator.validateHttpAsync(proxyInfo);
return future.handleAsync((response, throwable) -> {
boolean validate = ProxyValidator.validateResponse(response, proxyInfo);
log.info(String.format("ProxyFirstChecker[%s:%d](%s)%s", proxyInfo.getIp(), proxyInfo.getPort(), proxyInfo.getSource(), validate));
return validate;
});
}
public void notifyNewProxy(List<ProxyInfoBO> newProxy) {
Predicate<ProxyInfoBO> distinctByKey = new Predicate<ProxyInfoBO>() {
private Set<String> set = new HashSet<>();
@Override
public boolean test(ProxyInfoBO proxyInfoBO) {
return set.add(proxyInfoBO.getIp());
}
};
newProxy.stream().filter(distinctByKey).forEach(subject::push);
}
}
| UTF-8 | Java | 2,514 | java | ProxyFirstChecker.java | Java | []
| null | []
| package com.zy.study.ps.com;
import com.zy.study.ps.biz.ProxyValidator;
import com.zy.study.ps.bo.ProxyInfoBO;
import com.zy.study.ps.workflow.InboundType;
import com.zy.study.ps.workflow.Pushable;
import com.zy.study.ps.workflow.WorkFlow;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
@Component
@Slf4j
public class ProxyFirstChecker {
@Autowired
private ProxyDbAccessor proxyDbAccessor;
@Autowired
private SchedulerManager schedulerManager;
@Autowired
private ProxyPoolManager proxyPoolManager;
private Pushable<ProxyInfoBO> subject;
@PostConstruct
public void initial() {
subject =
WorkFlow.create(new InboundType<ProxyInfoBO>())
.filter(this::notExist)
.filterAsync(this::validate)
.workOn(schedulerManager.sqlite()).foreach(this::insert);
}
private boolean notExist(ProxyInfoBO proxyInfoBO) {
boolean exist = proxyPoolManager.exist(proxyInfoBO);
if(exist){
log.warn(String.format("已存在IP%s(%s)", proxyInfoBO.getIp(), proxyInfoBO.getSource()));
}
return !exist;
}
private void insert(ProxyInfoBO proxyInfoBO1) {
proxyDbAccessor.insert(proxyInfoBO1);
}
private CompletableFuture<Boolean> validate(ProxyInfoBO proxyInfo) {
CompletableFuture<Response> future=ProxyValidator.validateHttpAsync(proxyInfo);
return future.handleAsync((response, throwable) -> {
boolean validate = ProxyValidator.validateResponse(response, proxyInfo);
log.info(String.format("ProxyFirstChecker[%s:%d](%s)%s", proxyInfo.getIp(), proxyInfo.getPort(), proxyInfo.getSource(), validate));
return validate;
});
}
public void notifyNewProxy(List<ProxyInfoBO> newProxy) {
Predicate<ProxyInfoBO> distinctByKey = new Predicate<ProxyInfoBO>() {
private Set<String> set = new HashSet<>();
@Override
public boolean test(ProxyInfoBO proxyInfoBO) {
return set.add(proxyInfoBO.getIp());
}
};
newProxy.stream().filter(distinctByKey).forEach(subject::push);
}
}
| 2,514 | 0.690989 | 0.688995 | 74 | 32.891891 | 28.152369 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567568 | false | false | 15 |
3c1999502cf94f173556d6452ed9662284fc481d | 3,685,081,942,554 | 151db09d1e0ab56dfbb8af78621a0ed5a0cfc0a6 | /softeng_project/src/main/java/io/jg_intelligence/exception/TeacherIdNumAlreadyExistExceptionResponse.java | 9ffd966b63794324e544ac93dcbbcf117b333fdc | []
| no_license | jaspergar/SoftEngProject | https://github.com/jaspergar/SoftEngProject | 391b82eec9428ee5044b93d05ccff240813ea576 | a5f5beba7b33412e783766d1c94c58339642a247 | refs/heads/master | 2022-07-02T12:17:55.573000 | 2020-04-30T04:03:18 | 2020-04-30T04:03:18 | 260,108,240 | 0 | 0 | null | false | 2022-05-20T21:35:39 | 2020-04-30T03:52:12 | 2020-04-30T04:09:15 | 2022-05-20T21:35:38 | 75 | 0 | 0 | 1 | Java | false | false | package io.jg_intelligence.exception;
public class TeacherIdNumAlreadyExistExceptionResponse {
private String idNumber;
public TeacherIdNumAlreadyExistExceptionResponse(String idNumber) {
this.idNumber = idNumber;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
}
| UTF-8 | Java | 361 | java | TeacherIdNumAlreadyExistExceptionResponse.java | Java | []
| null | []
| package io.jg_intelligence.exception;
public class TeacherIdNumAlreadyExistExceptionResponse {
private String idNumber;
public TeacherIdNumAlreadyExistExceptionResponse(String idNumber) {
this.idNumber = idNumber;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
}
| 361 | 0.770083 | 0.770083 | 20 | 17.049999 | 20.602123 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 15 |
fcf55147b54b03f20d83f6b64e4f603076106194 | 1,898,375,554,000 | b573ccb30ede76cef514ffc708a17f330be34eea | /Authentication/src/main/java/web/interceptor/AuthenticationInterceptor.java | dfa20008e412981a4a8be555c64e910a02a130ad | []
| no_license | YoonSung/MSA_SimpleShoppingMall_Yoonsung | https://github.com/YoonSung/MSA_SimpleShoppingMall_Yoonsung | 8040d7ef4944c845acb575f69205be743901e516 | 9756ea0934944e30eabb8f2acb7112a105f3a9c3 | refs/heads/master | 2021-01-22T01:54:42.042000 | 2015-09-09T04:14:48 | 2015-09-09T04:14:48 | 40,252,758 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package web.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by yoon on 15. 8. 5..
*/
public class AuthenticationInterceptor implements HandlerInterceptor {
private final Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
} | UTF-8 | Java | 945 | java | AuthenticationInterceptor.java | Java | [
{
"context": "rvlet.http.HttpServletResponse;\n\n/**\n * Created by yoon on 15. 8. 5..\n */\npublic class AuthenticationInte",
"end": 312,
"score": 0.9996427893638611,
"start": 308,
"tag": "USERNAME",
"value": "yoon"
}
]
| null | []
| package web.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by yoon on 15. 8. 5..
*/
public class AuthenticationInterceptor implements HandlerInterceptor {
private final Logger log = LoggerFactory.getLogger(AuthenticationInterceptor.class);
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
} | 945 | 0.798942 | 0.792593 | 29 | 31.620689 | 42.543621 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.586207 | false | false | 15 |
92b567045acdffed2cd1238f6da11e46277bd686 | 31,920,196,981,022 | 2c7537bf26cbae69cd30ff6bf1326629e4eda118 | /src/practice/Staircase.java | 84889283241fee83cc8931a38592b3cbe50ec0ad | []
| no_license | NoelKocheril/Random-Project | https://github.com/NoelKocheril/Random-Project | 854ac8091d72a3e67c6cc88d6024dd3d8f4278a5 | 311fc1a4c4524a050fd6d42fa90eebc0e8fd6169 | refs/heads/master | 2021-04-18T19:21:50.951000 | 2018-03-28T15:06:23 | 2018-03-28T15:06:23 | 126,361,253 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package practice;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/*
* There is a staircase with N steps, and you can climb 1 or 2 steps at a time.
* Given N, write a function that returns the number of unique ways you can
* climb the staircase. The Order of the Steps matter.
*
* For example, if N is 4, then there are 5 unique ways:
* - 1, 1, 1, 1
* - 2, 1, 1
* - 1, 2, 1
* - 1, 1, 2
* - 2, 2
*
* What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number
* from a set of positive integers X?
*
* For Example, if X = {1, 3, 5},
* you could climb 1, 3, or 5 steps at a time,
*
* Generalize your function to take in X.
*/
public class Staircase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Get Set
System.out.println("Format for Set: N N N N N N... where N can be any Positive Integer (Space Seperated)");
System.out.print("Enter Set of positive integers to increment by: ");
String[] in_Set = in.nextLine().split(" ");
//Make Set
Set<Integer> steps = new HashSet<Integer>();
for(String e:in_Set) {
steps.add(Math.abs(Integer.parseInt(e)));
}
System.out.println(steps);
//Get Step you want to Reach
System.out.print("Enter Step you Wish to Reach: ");
int _final = in.nextInt();
//Print out using only 1 or 2 steps
System.out.printf("Number of Ways to get to Step %d using only 1 or 2 steps is: %d\n", _final, genPathCount1(_final));
System.out.printf("Number of Ways to get to Step %d using the Set %s steps is: %d\n",_final, steps, genPathCount2(steps, _final));
in.close();
}
public static int genPathCount1(int Step){
int[] cache = new int[Step+1];
cache[0] = 1;
cache[1] = 1;
cache[2] = 2;
for(int i = 3; i < Step+1; i++) {
cache[i] += cache[i-1] + cache[i-2];
}
return cache[Step];
}
public static int genPathCount2(Set<Integer> X, int Step) {
// System.out.println(X);
int[] cache = new int[Step+1];
cache[0] = 1;
for (int i = 1; i < Step+1; i++) {
for(int x : X) {
if (i-x >= 0) cache[i] += cache[i-x];
}
}
// for(int e : cache) System.out.printf("%d\n", e);
return cache[Step];
}
}
| UTF-8 | Java | 2,229 | java | Staircase.java | Java | []
| null | []
| package practice;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/*
* There is a staircase with N steps, and you can climb 1 or 2 steps at a time.
* Given N, write a function that returns the number of unique ways you can
* climb the staircase. The Order of the Steps matter.
*
* For example, if N is 4, then there are 5 unique ways:
* - 1, 1, 1, 1
* - 2, 1, 1
* - 1, 2, 1
* - 1, 1, 2
* - 2, 2
*
* What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number
* from a set of positive integers X?
*
* For Example, if X = {1, 3, 5},
* you could climb 1, 3, or 5 steps at a time,
*
* Generalize your function to take in X.
*/
public class Staircase {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Get Set
System.out.println("Format for Set: N N N N N N... where N can be any Positive Integer (Space Seperated)");
System.out.print("Enter Set of positive integers to increment by: ");
String[] in_Set = in.nextLine().split(" ");
//Make Set
Set<Integer> steps = new HashSet<Integer>();
for(String e:in_Set) {
steps.add(Math.abs(Integer.parseInt(e)));
}
System.out.println(steps);
//Get Step you want to Reach
System.out.print("Enter Step you Wish to Reach: ");
int _final = in.nextInt();
//Print out using only 1 or 2 steps
System.out.printf("Number of Ways to get to Step %d using only 1 or 2 steps is: %d\n", _final, genPathCount1(_final));
System.out.printf("Number of Ways to get to Step %d using the Set %s steps is: %d\n",_final, steps, genPathCount2(steps, _final));
in.close();
}
public static int genPathCount1(int Step){
int[] cache = new int[Step+1];
cache[0] = 1;
cache[1] = 1;
cache[2] = 2;
for(int i = 3; i < Step+1; i++) {
cache[i] += cache[i-1] + cache[i-2];
}
return cache[Step];
}
public static int genPathCount2(Set<Integer> X, int Step) {
// System.out.println(X);
int[] cache = new int[Step+1];
cache[0] = 1;
for (int i = 1; i < Step+1; i++) {
for(int x : X) {
if (i-x >= 0) cache[i] += cache[i-x];
}
}
// for(int e : cache) System.out.printf("%d\n", e);
return cache[Step];
}
}
| 2,229 | 0.622252 | 0.598923 | 79 | 27.215189 | 28.291285 | 132 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.012658 | false | false | 15 |
d0bf5dd89b6424f288d920c9dc24346e8d94f9b4 | 13,649,406,079,680 | 5d14e6facb2cdbbb6b46cb5ff654abc116af66b9 | /javaee-rest/src/main/java/dev/vladflore/javaeezerotohero/resource/NasaResource.java | 19197c3243e19fd376afeea4abc3e973febb4ab8 | []
| no_license | vladflore/javaee-from-zero-to-hero | https://github.com/vladflore/javaee-from-zero-to-hero | 803661bc6b98a2e3e17131683ac6fe02746bf5a0 | a45b65244c573d20282e96737841b0af2f10ffc3 | refs/heads/master | 2022-05-06T05:37:49.507000 | 2020-06-30T14:07:19 | 2020-06-30T14:07:19 | 208,659,251 | 0 | 0 | null | false | 2022-03-08T21:17:44 | 2019-09-15T21:23:32 | 2020-06-30T14:07:22 | 2022-03-08T21:17:43 | 62 | 0 | 0 | 2 | Java | false | false | package dev.vladflore.javaeezerotohero.resource;
import dev.vladflore.javaeezerotohero.service.NasaService;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("nasa")
public class NasaResource {
@Inject
private NasaService nasaService;
@GET
@Path("apod")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveApod() {
return Response.ok(nasaService.retrieveApod()).build();
}
}
| UTF-8 | Java | 557 | java | NasaResource.java | Java | []
| null | []
| package dev.vladflore.javaeezerotohero.resource;
import dev.vladflore.javaeezerotohero.service.NasaService;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("nasa")
public class NasaResource {
@Inject
private NasaService nasaService;
@GET
@Path("apod")
@Produces(MediaType.APPLICATION_JSON)
public Response retrieveApod() {
return Response.ok(nasaService.retrieveApod()).build();
}
}
| 557 | 0.739677 | 0.739677 | 24 | 22.208334 | 18.634598 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 15 |
ac625ed9c15c6780a8d4afd340cee577dac0b006 | 29,970,281,857,101 | e4df275bb068565f6a20a886f59b05b3bd1323f0 | /jornada_parent/jornada_model/src/main/java/com/winston/jornada/persistence/jpa/segusuario/SegUsuarioDAO.java | 7ec16e6c1042cf90b04381963f1673f01cb08302 | []
| no_license | winstontransp/jornada | https://github.com/winstontransp/jornada | c333211b3fffbe585e713b59748376651e40d622 | 3a18bd7023f1494200345d2e30d7e47288611508 | refs/heads/master | 2016-09-16T13:29:27.656000 | 2015-09-14T12:05:50 | 2015-09-14T12:05:50 | 35,241,469 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.winston.jornada.persistence.jpa.segusuario;
import com.winston.jornada.persistence.jpa.AppJpaDAO;
import com.winston.jornada.entity.seguranca.SegUrl;
import com.winston.jornada.entity.seguranca.SegUsuario;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryParameter;
import com.powerlogic.jcompany.domain.type.PlcYesNo;
import java.util.List;
import com.powerlogic.jcompany.persistence.jpa.PlcQuery;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryLineAmount;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryOrderBy;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryFirstLine;
import com.powerlogic.jcompany.commons.annotation.PlcAggregationDAOIoC;
import com.powerlogic.jcompany.commons.config.stereotypes.SPlcDataAccessObject;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryService;
import com.powerlogic.jcompany.commons.PlcBaseContextVO;
/**
* Classe de Persistência gerada pelo assistente
*/
@PlcAggregationDAOIoC(SegUsuario.class)
@SPlcDataAccessObject
@PlcQueryService
public class SegUsuarioDAO extends AppJpaDAO {
@PlcQuery("querySel")
public native List<SegUsuario> findList(
PlcBaseContextVO context,
@PlcQueryOrderBy String dynamicOrderByPlc,
@PlcQueryFirstLine Integer primeiraLinhaPlc,
@PlcQueryLineAmount Integer numeroLinhasPlc,
@PlcQueryParameter(name="id", expression="id = :id") Long id,
@PlcQueryParameter(name="nome", expression="nome like :nome || '%' ") String nome,
@PlcQueryParameter(name="bloqueado", expression="bloqueado = :bloqueado") PlcYesNo bloqueado,
@PlcQueryParameter(name="login", expression="login like :login || '%' ") String login
);
@PlcQuery("querySel")
public native Long findCount(
PlcBaseContextVO context,
@PlcQueryParameter(name="id", expression="id = :id") Long id,
@PlcQueryParameter(name="nome", expression="nome like :nome || '%' ") String nome,
@PlcQueryParameter(name="bloqueado", expression="bloqueado = :bloqueado") PlcYesNo bloqueado,
@PlcQueryParameter(name="login", expression="login like :login || '%' ") String login
);
@PlcQuery("obterUsuarioPorLogin")
public native SegUsuario obterUsuarioPorLogin(
PlcBaseContextVO context,
@PlcQueryParameter(name="login", expression="login like :login || '%' ") String login
);
}
| UTF-8 | Java | 2,305 | java | SegUsuarioDAO.java | Java | []
| null | []
| package com.winston.jornada.persistence.jpa.segusuario;
import com.winston.jornada.persistence.jpa.AppJpaDAO;
import com.winston.jornada.entity.seguranca.SegUrl;
import com.winston.jornada.entity.seguranca.SegUsuario;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryParameter;
import com.powerlogic.jcompany.domain.type.PlcYesNo;
import java.util.List;
import com.powerlogic.jcompany.persistence.jpa.PlcQuery;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryLineAmount;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryOrderBy;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryFirstLine;
import com.powerlogic.jcompany.commons.annotation.PlcAggregationDAOIoC;
import com.powerlogic.jcompany.commons.config.stereotypes.SPlcDataAccessObject;
import com.powerlogic.jcompany.persistence.jpa.PlcQueryService;
import com.powerlogic.jcompany.commons.PlcBaseContextVO;
/**
* Classe de Persistência gerada pelo assistente
*/
@PlcAggregationDAOIoC(SegUsuario.class)
@SPlcDataAccessObject
@PlcQueryService
public class SegUsuarioDAO extends AppJpaDAO {
@PlcQuery("querySel")
public native List<SegUsuario> findList(
PlcBaseContextVO context,
@PlcQueryOrderBy String dynamicOrderByPlc,
@PlcQueryFirstLine Integer primeiraLinhaPlc,
@PlcQueryLineAmount Integer numeroLinhasPlc,
@PlcQueryParameter(name="id", expression="id = :id") Long id,
@PlcQueryParameter(name="nome", expression="nome like :nome || '%' ") String nome,
@PlcQueryParameter(name="bloqueado", expression="bloqueado = :bloqueado") PlcYesNo bloqueado,
@PlcQueryParameter(name="login", expression="login like :login || '%' ") String login
);
@PlcQuery("querySel")
public native Long findCount(
PlcBaseContextVO context,
@PlcQueryParameter(name="id", expression="id = :id") Long id,
@PlcQueryParameter(name="nome", expression="nome like :nome || '%' ") String nome,
@PlcQueryParameter(name="bloqueado", expression="bloqueado = :bloqueado") PlcYesNo bloqueado,
@PlcQueryParameter(name="login", expression="login like :login || '%' ") String login
);
@PlcQuery("obterUsuarioPorLogin")
public native SegUsuario obterUsuarioPorLogin(
PlcBaseContextVO context,
@PlcQueryParameter(name="login", expression="login like :login || '%' ") String login
);
}
| 2,305 | 0.781684 | 0.781684 | 58 | 38.724136 | 30.335363 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.948276 | false | false | 15 |
c4a53083bc3480bed7407d5de7b09e3c2ae83233 | 29,738,353,572,085 | 6370724d56544e8c78342f66aa89b3aeb3dbaa09 | /src/Tester/SinglyLinkedListTester.java | 361f60c692148f97a8172f205efa4245606c975c | []
| no_license | iy2chang/Data-Structure-Java | https://github.com/iy2chang/Data-Structure-Java | a76695f59a469ba77dfd485a193a61c27116c75f | d2a13747dace77c9ad28d4af14d2da8487d709af | refs/heads/master | 2021-01-10T10:27:45.563000 | 2016-01-13T22:00:30 | 2016-01-13T22:00:30 | 49,605,002 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Tester;
import DataStructures.SinglyLinkedList;
public class SinglyLinkedListTester {
public static void main(String[] args){
SinglyLinkedList<Integer> sll = new SinglyLinkedList<Integer>();
sll.add(1);
sll.add(2);
sll.add(3);
sll.add(4);
System.out.println("size is : " +sll.getSize());
sll.deleteAfter(2);
sll.traverse();
sll.front();
}
}
| UTF-8 | Java | 371 | java | SinglyLinkedListTester.java | Java | []
| null | []
| package Tester;
import DataStructures.SinglyLinkedList;
public class SinglyLinkedListTester {
public static void main(String[] args){
SinglyLinkedList<Integer> sll = new SinglyLinkedList<Integer>();
sll.add(1);
sll.add(2);
sll.add(3);
sll.add(4);
System.out.println("size is : " +sll.getSize());
sll.deleteAfter(2);
sll.traverse();
sll.front();
}
}
| 371 | 0.695418 | 0.681941 | 17 | 20.82353 | 18.481264 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.823529 | false | false | 15 |
317cfa26fe41fe2e22d62858f2a91957333e2c85 | 19,327,352,842,072 | be1d1917bb2674b74ef61b546dcdb5cc9080dac6 | /pro-manager/pro-manager-pojo/src/main/java/com/leyuan/jiang/pojo/po/ViolentPrivacyExample.java | ff5c7a24589f31b3245f100dcbcc91fb21983be4 | []
| no_license | jiangleyaun/MyMavenForAll | https://github.com/jiangleyaun/MyMavenForAll | 59c0d830bed671cc7523f10e8d0196fe0f27a61b | 83637c73e8d9dd444691a0f42fdd659cbccc550b | refs/heads/master | 2020-03-20T03:25:07.224000 | 2018-06-13T01:19:22 | 2018-06-13T01:19:22 | 137,145,601 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.leyuan.jiang.pojo.po;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ViolentPrivacyExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ViolentPrivacyExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
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(Long value) {
addCriterion("ID =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("ID <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("ID >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("ID >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("ID <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("ID <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("ID in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("ID not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("ID between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("ID not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("NAME is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("NAME is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("NAME =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("NAME <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("NAME >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("NAME >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("NAME <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("NAME <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("NAME like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("NAME not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("NAME in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("NAME not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("NAME between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("NAME not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("CREATE_TIME is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("CREATE_TIME is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("CREATE_TIME =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("CREATE_TIME <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("CREATE_TIME >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("CREATE_TIME >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("CREATE_TIME <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("CREATE_TIME <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("CREATE_TIME in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("CREATE_TIME not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("CREATE_TIME between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("CREATE_TIME not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCrimeHistoryIsNull() {
addCriterion("CRIME_HISTORY is null");
return (Criteria) this;
}
public Criteria andCrimeHistoryIsNotNull() {
addCriterion("CRIME_HISTORY is not null");
return (Criteria) this;
}
public Criteria andCrimeHistoryEqualTo(String value) {
addCriterion("CRIME_HISTORY =", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotEqualTo(String value) {
addCriterion("CRIME_HISTORY <>", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryGreaterThan(String value) {
addCriterion("CRIME_HISTORY >", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryGreaterThanOrEqualTo(String value) {
addCriterion("CRIME_HISTORY >=", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryLessThan(String value) {
addCriterion("CRIME_HISTORY <", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryLessThanOrEqualTo(String value) {
addCriterion("CRIME_HISTORY <=", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryLike(String value) {
addCriterion("CRIME_HISTORY like", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotLike(String value) {
addCriterion("CRIME_HISTORY not like", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryIn(List<String> values) {
addCriterion("CRIME_HISTORY in", values, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotIn(List<String> values) {
addCriterion("CRIME_HISTORY not in", values, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryBetween(String value1, String value2) {
addCriterion("CRIME_HISTORY between", value1, value2, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotBetween(String value1, String value2) {
addCriterion("CRIME_HISTORY not between", value1, value2, "crimeHistory");
return (Criteria) this;
}
public Criteria andDiseaseIsNull() {
addCriterion("DISEASE is null");
return (Criteria) this;
}
public Criteria andDiseaseIsNotNull() {
addCriterion("DISEASE is not null");
return (Criteria) this;
}
public Criteria andDiseaseEqualTo(String value) {
addCriterion("DISEASE =", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotEqualTo(String value) {
addCriterion("DISEASE <>", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseGreaterThan(String value) {
addCriterion("DISEASE >", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseGreaterThanOrEqualTo(String value) {
addCriterion("DISEASE >=", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseLessThan(String value) {
addCriterion("DISEASE <", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseLessThanOrEqualTo(String value) {
addCriterion("DISEASE <=", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseLike(String value) {
addCriterion("DISEASE like", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotLike(String value) {
addCriterion("DISEASE not like", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseIn(List<String> values) {
addCriterion("DISEASE in", values, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotIn(List<String> values) {
addCriterion("DISEASE not in", values, "disease");
return (Criteria) this;
}
public Criteria andDiseaseBetween(String value1, String value2) {
addCriterion("DISEASE between", value1, value2, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotBetween(String value1, String value2) {
addCriterion("DISEASE not between", value1, value2, "disease");
return (Criteria) this;
}
public Criteria andDiseaseHistoryIsNull() {
addCriterion("DISEASE_HISTORY is null");
return (Criteria) this;
}
public Criteria andDiseaseHistoryIsNotNull() {
addCriterion("DISEASE_HISTORY is not null");
return (Criteria) this;
}
public Criteria andDiseaseHistoryEqualTo(String value) {
addCriterion("DISEASE_HISTORY =", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotEqualTo(String value) {
addCriterion("DISEASE_HISTORY <>", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryGreaterThan(String value) {
addCriterion("DISEASE_HISTORY >", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryGreaterThanOrEqualTo(String value) {
addCriterion("DISEASE_HISTORY >=", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryLessThan(String value) {
addCriterion("DISEASE_HISTORY <", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryLessThanOrEqualTo(String value) {
addCriterion("DISEASE_HISTORY <=", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryLike(String value) {
addCriterion("DISEASE_HISTORY like", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotLike(String value) {
addCriterion("DISEASE_HISTORY not like", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryIn(List<String> values) {
addCriterion("DISEASE_HISTORY in", values, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotIn(List<String> values) {
addCriterion("DISEASE_HISTORY not in", values, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryBetween(String value1, String value2) {
addCriterion("DISEASE_HISTORY between", value1, value2, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotBetween(String value1, String value2) {
addCriterion("DISEASE_HISTORY not between", value1, value2, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryIsNull() {
addCriterion("DOMESTIC_VIOLENCE_HISTORY is null");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryIsNotNull() {
addCriterion("DOMESTIC_VIOLENCE_HISTORY is not null");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY =", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY <>", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryGreaterThan(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY >", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryGreaterThanOrEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY >=", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryLessThan(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY <", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryLessThanOrEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY <=", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryLike(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY like", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotLike(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY not like", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryIn(List<String> values) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY in", values, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotIn(List<String> values) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY not in", values, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryBetween(String value1, String value2) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY between", value1, value2, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotBetween(String value1, String value2) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY not between", value1, value2, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andMentalIllnessIsNull() {
addCriterion("MENTAL_ILLNESS is null");
return (Criteria) this;
}
public Criteria andMentalIllnessIsNotNull() {
addCriterion("MENTAL_ILLNESS is not null");
return (Criteria) this;
}
public Criteria andMentalIllnessEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS =", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessNotEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS <>", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessGreaterThan(Boolean value) {
addCriterion("MENTAL_ILLNESS >", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessGreaterThanOrEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS >=", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessLessThan(Boolean value) {
addCriterion("MENTAL_ILLNESS <", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessLessThanOrEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS <=", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessIn(List<Boolean> values) {
addCriterion("MENTAL_ILLNESS in", values, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessNotIn(List<Boolean> values) {
addCriterion("MENTAL_ILLNESS not in", values, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessBetween(Boolean value1, Boolean value2) {
addCriterion("MENTAL_ILLNESS between", value1, value2, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessNotBetween(Boolean value1, Boolean value2) {
addCriterion("MENTAL_ILLNESS not between", value1, value2, "mentalIllness");
return (Criteria) this;
}
public Criteria andPrivacyIsNull() {
addCriterion("PRIVACY is null");
return (Criteria) this;
}
public Criteria andPrivacyIsNotNull() {
addCriterion("PRIVACY is not null");
return (Criteria) this;
}
public Criteria andPrivacyEqualTo(Boolean value) {
addCriterion("PRIVACY =", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyNotEqualTo(Boolean value) {
addCriterion("PRIVACY <>", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyGreaterThan(Boolean value) {
addCriterion("PRIVACY >", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyGreaterThanOrEqualTo(Boolean value) {
addCriterion("PRIVACY >=", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyLessThan(Boolean value) {
addCriterion("PRIVACY <", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyLessThanOrEqualTo(Boolean value) {
addCriterion("PRIVACY <=", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyIn(List<Boolean> values) {
addCriterion("PRIVACY in", values, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyNotIn(List<Boolean> values) {
addCriterion("PRIVACY not in", values, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyBetween(Boolean value1, Boolean value2) {
addCriterion("PRIVACY between", value1, value2, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyNotBetween(Boolean value1, Boolean value2) {
addCriterion("PRIVACY not between", value1, value2, "privacy");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("UPDATE_TIME is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("UPDATE_TIME is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Date value) {
addCriterion("UPDATE_TIME =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Date value) {
addCriterion("UPDATE_TIME <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Date value) {
addCriterion("UPDATE_TIME >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("UPDATE_TIME >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Date value) {
addCriterion("UPDATE_TIME <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
addCriterion("UPDATE_TIME <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Date> values) {
addCriterion("UPDATE_TIME in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Date> values) {
addCriterion("UPDATE_TIME not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Date value1, Date value2) {
addCriterion("UPDATE_TIME between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
addCriterion("UPDATE_TIME not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdIsNull() {
addCriterion("VIOLENT_PERSONNEL_ID is null");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdIsNotNull() {
addCriterion("VIOLENT_PERSONNEL_ID is not null");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID =", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdNotEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID <>", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdGreaterThan(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID >", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdGreaterThanOrEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID >=", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdLessThan(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID <", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdLessThanOrEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID <=", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdIn(List<Long> values) {
addCriterion("VIOLENT_PERSONNEL_ID in", values, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdNotIn(List<Long> values) {
addCriterion("VIOLENT_PERSONNEL_ID not in", values, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdBetween(Long value1, Long value2) {
addCriterion("VIOLENT_PERSONNEL_ID between", value1, value2, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdNotBetween(Long value1, Long value2) {
addCriterion("VIOLENT_PERSONNEL_ID not between", value1, value2, "violentPersonnelId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
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 | 30,652 | java | ViolentPrivacyExample.java | Java | []
| null | []
| package com.leyuan.jiang.pojo.po;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ViolentPrivacyExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ViolentPrivacyExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
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(Long value) {
addCriterion("ID =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("ID <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("ID >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("ID >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("ID <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("ID <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("ID in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("ID not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("ID between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("ID not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("NAME is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("NAME is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("NAME =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("NAME <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("NAME >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("NAME >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("NAME <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("NAME <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("NAME like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("NAME not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("NAME in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("NAME not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("NAME between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("NAME not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("CREATE_TIME is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("CREATE_TIME is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("CREATE_TIME =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("CREATE_TIME <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("CREATE_TIME >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("CREATE_TIME >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("CREATE_TIME <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("CREATE_TIME <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("CREATE_TIME in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("CREATE_TIME not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("CREATE_TIME between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("CREATE_TIME not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCrimeHistoryIsNull() {
addCriterion("CRIME_HISTORY is null");
return (Criteria) this;
}
public Criteria andCrimeHistoryIsNotNull() {
addCriterion("CRIME_HISTORY is not null");
return (Criteria) this;
}
public Criteria andCrimeHistoryEqualTo(String value) {
addCriterion("CRIME_HISTORY =", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotEqualTo(String value) {
addCriterion("CRIME_HISTORY <>", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryGreaterThan(String value) {
addCriterion("CRIME_HISTORY >", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryGreaterThanOrEqualTo(String value) {
addCriterion("CRIME_HISTORY >=", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryLessThan(String value) {
addCriterion("CRIME_HISTORY <", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryLessThanOrEqualTo(String value) {
addCriterion("CRIME_HISTORY <=", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryLike(String value) {
addCriterion("CRIME_HISTORY like", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotLike(String value) {
addCriterion("CRIME_HISTORY not like", value, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryIn(List<String> values) {
addCriterion("CRIME_HISTORY in", values, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotIn(List<String> values) {
addCriterion("CRIME_HISTORY not in", values, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryBetween(String value1, String value2) {
addCriterion("CRIME_HISTORY between", value1, value2, "crimeHistory");
return (Criteria) this;
}
public Criteria andCrimeHistoryNotBetween(String value1, String value2) {
addCriterion("CRIME_HISTORY not between", value1, value2, "crimeHistory");
return (Criteria) this;
}
public Criteria andDiseaseIsNull() {
addCriterion("DISEASE is null");
return (Criteria) this;
}
public Criteria andDiseaseIsNotNull() {
addCriterion("DISEASE is not null");
return (Criteria) this;
}
public Criteria andDiseaseEqualTo(String value) {
addCriterion("DISEASE =", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotEqualTo(String value) {
addCriterion("DISEASE <>", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseGreaterThan(String value) {
addCriterion("DISEASE >", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseGreaterThanOrEqualTo(String value) {
addCriterion("DISEASE >=", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseLessThan(String value) {
addCriterion("DISEASE <", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseLessThanOrEqualTo(String value) {
addCriterion("DISEASE <=", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseLike(String value) {
addCriterion("DISEASE like", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotLike(String value) {
addCriterion("DISEASE not like", value, "disease");
return (Criteria) this;
}
public Criteria andDiseaseIn(List<String> values) {
addCriterion("DISEASE in", values, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotIn(List<String> values) {
addCriterion("DISEASE not in", values, "disease");
return (Criteria) this;
}
public Criteria andDiseaseBetween(String value1, String value2) {
addCriterion("DISEASE between", value1, value2, "disease");
return (Criteria) this;
}
public Criteria andDiseaseNotBetween(String value1, String value2) {
addCriterion("DISEASE not between", value1, value2, "disease");
return (Criteria) this;
}
public Criteria andDiseaseHistoryIsNull() {
addCriterion("DISEASE_HISTORY is null");
return (Criteria) this;
}
public Criteria andDiseaseHistoryIsNotNull() {
addCriterion("DISEASE_HISTORY is not null");
return (Criteria) this;
}
public Criteria andDiseaseHistoryEqualTo(String value) {
addCriterion("DISEASE_HISTORY =", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotEqualTo(String value) {
addCriterion("DISEASE_HISTORY <>", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryGreaterThan(String value) {
addCriterion("DISEASE_HISTORY >", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryGreaterThanOrEqualTo(String value) {
addCriterion("DISEASE_HISTORY >=", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryLessThan(String value) {
addCriterion("DISEASE_HISTORY <", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryLessThanOrEqualTo(String value) {
addCriterion("DISEASE_HISTORY <=", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryLike(String value) {
addCriterion("DISEASE_HISTORY like", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotLike(String value) {
addCriterion("DISEASE_HISTORY not like", value, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryIn(List<String> values) {
addCriterion("DISEASE_HISTORY in", values, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotIn(List<String> values) {
addCriterion("DISEASE_HISTORY not in", values, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryBetween(String value1, String value2) {
addCriterion("DISEASE_HISTORY between", value1, value2, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDiseaseHistoryNotBetween(String value1, String value2) {
addCriterion("DISEASE_HISTORY not between", value1, value2, "diseaseHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryIsNull() {
addCriterion("DOMESTIC_VIOLENCE_HISTORY is null");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryIsNotNull() {
addCriterion("DOMESTIC_VIOLENCE_HISTORY is not null");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY =", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY <>", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryGreaterThan(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY >", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryGreaterThanOrEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY >=", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryLessThan(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY <", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryLessThanOrEqualTo(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY <=", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryLike(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY like", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotLike(String value) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY not like", value, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryIn(List<String> values) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY in", values, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotIn(List<String> values) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY not in", values, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryBetween(String value1, String value2) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY between", value1, value2, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andDomesticViolenceHistoryNotBetween(String value1, String value2) {
addCriterion("DOMESTIC_VIOLENCE_HISTORY not between", value1, value2, "domesticViolenceHistory");
return (Criteria) this;
}
public Criteria andMentalIllnessIsNull() {
addCriterion("MENTAL_ILLNESS is null");
return (Criteria) this;
}
public Criteria andMentalIllnessIsNotNull() {
addCriterion("MENTAL_ILLNESS is not null");
return (Criteria) this;
}
public Criteria andMentalIllnessEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS =", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessNotEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS <>", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessGreaterThan(Boolean value) {
addCriterion("MENTAL_ILLNESS >", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessGreaterThanOrEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS >=", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessLessThan(Boolean value) {
addCriterion("MENTAL_ILLNESS <", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessLessThanOrEqualTo(Boolean value) {
addCriterion("MENTAL_ILLNESS <=", value, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessIn(List<Boolean> values) {
addCriterion("MENTAL_ILLNESS in", values, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessNotIn(List<Boolean> values) {
addCriterion("MENTAL_ILLNESS not in", values, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessBetween(Boolean value1, Boolean value2) {
addCriterion("MENTAL_ILLNESS between", value1, value2, "mentalIllness");
return (Criteria) this;
}
public Criteria andMentalIllnessNotBetween(Boolean value1, Boolean value2) {
addCriterion("MENTAL_ILLNESS not between", value1, value2, "mentalIllness");
return (Criteria) this;
}
public Criteria andPrivacyIsNull() {
addCriterion("PRIVACY is null");
return (Criteria) this;
}
public Criteria andPrivacyIsNotNull() {
addCriterion("PRIVACY is not null");
return (Criteria) this;
}
public Criteria andPrivacyEqualTo(Boolean value) {
addCriterion("PRIVACY =", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyNotEqualTo(Boolean value) {
addCriterion("PRIVACY <>", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyGreaterThan(Boolean value) {
addCriterion("PRIVACY >", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyGreaterThanOrEqualTo(Boolean value) {
addCriterion("PRIVACY >=", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyLessThan(Boolean value) {
addCriterion("PRIVACY <", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyLessThanOrEqualTo(Boolean value) {
addCriterion("PRIVACY <=", value, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyIn(List<Boolean> values) {
addCriterion("PRIVACY in", values, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyNotIn(List<Boolean> values) {
addCriterion("PRIVACY not in", values, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyBetween(Boolean value1, Boolean value2) {
addCriterion("PRIVACY between", value1, value2, "privacy");
return (Criteria) this;
}
public Criteria andPrivacyNotBetween(Boolean value1, Boolean value2) {
addCriterion("PRIVACY not between", value1, value2, "privacy");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("UPDATE_TIME is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("UPDATE_TIME is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Date value) {
addCriterion("UPDATE_TIME =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Date value) {
addCriterion("UPDATE_TIME <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Date value) {
addCriterion("UPDATE_TIME >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("UPDATE_TIME >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Date value) {
addCriterion("UPDATE_TIME <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
addCriterion("UPDATE_TIME <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Date> values) {
addCriterion("UPDATE_TIME in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Date> values) {
addCriterion("UPDATE_TIME not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Date value1, Date value2) {
addCriterion("UPDATE_TIME between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
addCriterion("UPDATE_TIME not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdIsNull() {
addCriterion("VIOLENT_PERSONNEL_ID is null");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdIsNotNull() {
addCriterion("VIOLENT_PERSONNEL_ID is not null");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID =", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdNotEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID <>", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdGreaterThan(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID >", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdGreaterThanOrEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID >=", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdLessThan(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID <", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdLessThanOrEqualTo(Long value) {
addCriterion("VIOLENT_PERSONNEL_ID <=", value, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdIn(List<Long> values) {
addCriterion("VIOLENT_PERSONNEL_ID in", values, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdNotIn(List<Long> values) {
addCriterion("VIOLENT_PERSONNEL_ID not in", values, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdBetween(Long value1, Long value2) {
addCriterion("VIOLENT_PERSONNEL_ID between", value1, value2, "violentPersonnelId");
return (Criteria) this;
}
public Criteria andViolentPersonnelIdNotBetween(Long value1, Long value2) {
addCriterion("VIOLENT_PERSONNEL_ID not between", value1, value2, "violentPersonnelId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
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);
}
}
} | 30,652 | 0.59523 | 0.592098 | 911 | 32.64764 | 27.6388 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727772 | false | false | 15 |
c9dfdb41e609b9a764b2ae14e7284f1f931cc43a | 18,064,632,484,331 | 4b45fe972051d3ddd008037332287d2bdd2aa738 | /src/main/java/com/hada/virtual/hsm/util/CipherAES.java | 2f15ab050043e31952399d3774919f2dbac4bbe4 | []
| no_license | tieuhaoluong/virtual-hsm | https://github.com/tieuhaoluong/virtual-hsm | 664849fad9a30718275d39d863afbd7931d02fb2 | 7782f042acca268a76c03492e722343cbb5b6692 | refs/heads/master | 2022-12-01T07:11:49.698000 | 2022-11-25T09:45:38 | 2022-11-25T09:45:38 | 263,678,105 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hada.virtual.hsm.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;
public class CipherAES {
private static final Logger log = LoggerFactory.getLogger(CipherAES.class);
private static final String secretKey = "cms_secretKey";
private static final String salt = "cms_salt";
private static CipherAES instance;
private Cipher cipherEncrypt;
private Cipher cipherDecrypt;
private CipherAES() throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKeySpec = new SecretKeySpec(tmp.getEncoded(), "AES");
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec iv_spec = new IvParameterSpec(iv);
cipherEncrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv_spec);
log.info("Initialized CipherEncrypt");
cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec, iv_spec);
log.info("Initialized CipherDecrypt");
}
public static CipherAES getInstance() {
try {
if (instance == null)
instance = new CipherAES();
return instance;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public static String encrypt(String strToEncrypt) {
try {
return Base64.getEncoder().encodeToString(getInstance().getCipherEncrypt().doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
} catch (IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
public static String decrypt(String strToDecrypt) {
try {
return new String(getInstance().getCipherDecrypt().doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
public Cipher getCipherEncrypt() {
return cipherEncrypt;
}
public Cipher getCipherDecrypt() {
return cipherDecrypt;
}
}
| UTF-8 | Java | 2,654 | java | CipherAES.java | Java | [
{
"context": "s);\n\n private static final String secretKey = \"cms_secretKey\";\n private static final String salt = \"cms_sal",
"end": 503,
"score": 0.9217992424964905,
"start": 490,
"tag": "KEY",
"value": "cms_secretKey"
}
]
| null | []
| package com.hada.virtual.hsm.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.KeySpec;
import java.util.Base64;
public class CipherAES {
private static final Logger log = LoggerFactory.getLogger(CipherAES.class);
private static final String secretKey = "cms_secretKey";
private static final String salt = "cms_salt";
private static CipherAES instance;
private Cipher cipherEncrypt;
private Cipher cipherDecrypt;
private CipherAES() throws Exception {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKeySpec secretKeySpec = new SecretKeySpec(tmp.getEncoded(), "AES");
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec iv_spec = new IvParameterSpec(iv);
cipherEncrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipherEncrypt.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv_spec);
log.info("Initialized CipherEncrypt");
cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipherDecrypt.init(Cipher.DECRYPT_MODE, secretKeySpec, iv_spec);
log.info("Initialized CipherDecrypt");
}
public static CipherAES getInstance() {
try {
if (instance == null)
instance = new CipherAES();
return instance;
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public static String encrypt(String strToEncrypt) {
try {
return Base64.getEncoder().encodeToString(getInstance().getCipherEncrypt().doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
} catch (IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
public static String decrypt(String strToDecrypt) {
try {
return new String(getInstance().getCipherDecrypt().doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
return null;
}
}
public Cipher getCipherEncrypt() {
return cipherEncrypt;
}
public Cipher getCipherDecrypt() {
return cipherDecrypt;
}
}
| 2,654 | 0.668425 | 0.65373 | 77 | 33.467533 | 29.645342 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.831169 | false | false | 15 |
ed8f689435f1c2ab2d6ab0d61f6ce86ec69dfd40 | 32,332,513,849,815 | 4d07e069c60156047c9dad6360969b34de8859d1 | /app/src/main/java/com/mayank/doodleandrecord/MainActivity.java | 943b5b89a6499ac80e8e4bdb653bff3fb0bf3bd1 | []
| no_license | mayankkanela/doodle-and-record | https://github.com/mayankkanela/doodle-and-record | 84e148213553b27c449273b245b1c1a839529412 | 7b9e8a351f581ee0ea58536724915c76c6dfd87d | refs/heads/master | 2022-08-31T22:35:11.029000 | 2020-05-23T06:29:09 | 2020-05-23T06:29:09 | 265,868,739 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mayank.doodleandrecord;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.projection.MediaProjectionManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import org.jcodec.api.android.AndroidSequenceEncoder;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.common.model.Rational;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final int WRITE_EXTERNAL_REQUEST_CODE = 1;
private MediaProjectionManager mediaProjectionManager;
private int i = 0;
private PaintView paintView;
private String name;
private String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paintView = new PaintView(getApplicationContext());
LinearLayout linearLayout = findViewById(R.id.ll_paint_view);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.addView(paintView, params);
intListener();
}
private void intListener() {
Button preview = findViewById(R.id.bt_next);
preview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Encoding video...");
progressDialog.setCancelable(false);
progressDialog.show();
int n = paintView.getTotalFrames();
encodeImages(n, progressDialog);
}
});
}
private void encodeImages(final int n, final ProgressDialog progressDialog) {
final SeekableByteChannel[] out = {null};
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
name = new Date() +"_Output.mp4";
path = Environment.getExternalStorageDirectory().toString() + File.separator + name;
out[0] = NIOUtils.writableFileChannel(path);
// for Android use: AndroidSequenceEncoder
AndroidSequenceEncoder encoder = new AndroidSequenceEncoder(out[0], Rational.R(12, 1));
for (int i = 1; i < n; i++) {
// Generate the image, for Android use Bitmap
Bitmap image = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() + File.separator + "Folder" + File.separator + i + ".jpg");
Bitmap m = image.copy(Bitmap.Config.ARGB_8888, true);
if (image.getHeight() % 2 != 0)
m.setHeight(image.getHeight() - 1);
// Encode the image
if (image != null)
encoder.encodeImage(m);
}
// Finalize the encoding, i.e. clear the buffers, write the header, etc.
encoder.finish();
initUploadActivity(path, name);
progressDialog.dismiss();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
paintView.clearFiles();
NIOUtils.closeQuietly(out[0]);
}
return null;
}
}.execute();
}
private void initUploadActivity(String path, String name) {
Intent intent = new Intent(MainActivity.this,UploadAndPreviewActivity.class);
intent.putExtra("PATH", path);
intent.putExtra("NAME", name);
startActivity(intent);
MainActivity.this.finish();
}
}
| UTF-8 | Java | 4,433 | java | MainActivity.java | Java | []
| null | []
| package com.mayank.doodleandrecord;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.projection.MediaProjectionManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import org.jcodec.api.android.AndroidSequenceEncoder;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.common.model.Rational;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final int WRITE_EXTERNAL_REQUEST_CODE = 1;
private MediaProjectionManager mediaProjectionManager;
private int i = 0;
private PaintView paintView;
private String name;
private String path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paintView = new PaintView(getApplicationContext());
LinearLayout linearLayout = findViewById(R.id.ll_paint_view);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.addView(paintView, params);
intListener();
}
private void intListener() {
Button preview = findViewById(R.id.bt_next);
preview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Encoding video...");
progressDialog.setCancelable(false);
progressDialog.show();
int n = paintView.getTotalFrames();
encodeImages(n, progressDialog);
}
});
}
private void encodeImages(final int n, final ProgressDialog progressDialog) {
final SeekableByteChannel[] out = {null};
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
name = new Date() +"_Output.mp4";
path = Environment.getExternalStorageDirectory().toString() + File.separator + name;
out[0] = NIOUtils.writableFileChannel(path);
// for Android use: AndroidSequenceEncoder
AndroidSequenceEncoder encoder = new AndroidSequenceEncoder(out[0], Rational.R(12, 1));
for (int i = 1; i < n; i++) {
// Generate the image, for Android use Bitmap
Bitmap image = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() + File.separator + "Folder" + File.separator + i + ".jpg");
Bitmap m = image.copy(Bitmap.Config.ARGB_8888, true);
if (image.getHeight() % 2 != 0)
m.setHeight(image.getHeight() - 1);
// Encode the image
if (image != null)
encoder.encodeImage(m);
}
// Finalize the encoding, i.e. clear the buffers, write the header, etc.
encoder.finish();
initUploadActivity(path, name);
progressDialog.dismiss();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
paintView.clearFiles();
NIOUtils.closeQuietly(out[0]);
}
return null;
}
}.execute();
}
private void initUploadActivity(String path, String name) {
Intent intent = new Intent(MainActivity.this,UploadAndPreviewActivity.class);
intent.putExtra("PATH", path);
intent.putExtra("NAME", name);
startActivity(intent);
MainActivity.this.finish();
}
}
| 4,433 | 0.610422 | 0.606587 | 117 | 36.888889 | 28.672564 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.726496 | false | false | 15 |
81741335779f8b9e2d3b7aa471d673a206a8696f | 19,774,029,439,418 | 0c73d54c8143d759d9e9535611345d77e9a0c12f | /preaccept/src/main/java/com/neusoft/preaccept/model/datamodel/occupyNum/OccupyNumMsg.java | dccba22ee6eb91f56b924384fd75bcecef33bdb0 | []
| no_license | heavenisme/PreAccept | https://github.com/heavenisme/PreAccept | d5c5fdb657b757bf9f2b96a50ec1f70cb2f677a3 | 2605fdad46b7c79b6782b7bb65230bfcab24ed07 | refs/heads/master | 2020-02-26T15:14:16.284000 | 2016-06-20T14:45:43 | 2016-06-20T14:45:43 | 61,548,302 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Project Name:SxPreAccept
* File Name:Msg.java
* Package Name:com.neusoft.preaccept.data.model.preOrderNum
* Date:2015年12月23日上午10:30:02
* Copyright (c) 2015
*
*/
package com.neusoft.preaccept.model.datamodel.occupyNum;
import com.neusoft.preaccept.model.datamodel.BaseMsg;
import com.neusoft.preaccept.model.datamodel.Para;
import java.util.ArrayList;
/**
* ClassName:Msg <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2015年12月23日 上午10:30:02 <br/>
* @author neusoft liu.hongtao
* @version
* @since JDK 1.6
*/
public class OccupyNumMsg extends BaseMsg {
public String serType;
public ArrayList<ResourcesInfo> resourcesInfo;
public Para para;
}
| UTF-8 | Java | 773 | java | OccupyNumMsg.java | Java | [
{
"context": "2015年12月23日 上午10:30:02 <br/> \n * @author neusoft liu.hongtao\n * @version \n * @since JDK 1.6 \n */\npubli",
"end": 558,
"score": 0.9582151174545288,
"start": 547,
"tag": "NAME",
"value": "liu.hongtao"
}
]
| null | []
| /**
* Project Name:SxPreAccept
* File Name:Msg.java
* Package Name:com.neusoft.preaccept.data.model.preOrderNum
* Date:2015年12月23日上午10:30:02
* Copyright (c) 2015
*
*/
package com.neusoft.preaccept.model.datamodel.occupyNum;
import com.neusoft.preaccept.model.datamodel.BaseMsg;
import com.neusoft.preaccept.model.datamodel.Para;
import java.util.ArrayList;
/**
* ClassName:Msg <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2015年12月23日 上午10:30:02 <br/>
* @author neusoft liu.hongtao
* @version
* @since JDK 1.6
*/
public class OccupyNumMsg extends BaseMsg {
public String serType;
public ArrayList<ResourcesInfo> resourcesInfo;
public Para para;
}
| 773 | 0.691899 | 0.646746 | 32 | 22.46875 | 19.254845 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.21875 | false | false | 15 |
1e5f147d660cc7953a2c6e405101886b202132ff | 8,392,366,136,204 | 6d9977c5744ebca4ee4fc5120a8b47438f6b3e72 | /acceptance-test/src/test/java/pivotal/university/acceptance/test/pageObjects/ManageUsersPage.java | 01bb9e29a9a92b89e1eae615b6a36c21147ccf19 | []
| no_license | rusuo/acceptanceTests | https://github.com/rusuo/acceptanceTests | e2709b3a08b105f322740bd27a5bcd420ef26989 | 840a44ef54d627c904f0d295bcda7286ea580a41 | refs/heads/master | 2016-09-10T12:42:33.293000 | 2014-01-24T17:07:30 | 2014-01-24T17:07:30 | 16,210,298 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pivotal.university.acceptance.test.pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import pivotal.university.acceptance.test.config.Settings;
import pivotal.university.acceptance.test.pageObjects.pageElements.Dropdown;
import pivotal.university.acceptance.test.pageObjects.pageElements.Table;
import pivotal.university.acceptance.test.utils.frameworkUtils;
import java.util.List;
public class ManageUsersPage extends Page{
private static String pageUrl = Settings.applicationUrl + "/?q=admin/people";
private By updateButton = By.id("edit-submit--2");
private By updateOptions = By.id("edit-operation");
private By deleteAccountCompletely = By.id("edit-user-cancel-method--5");
private Page page = new Page("", webDriver);
private Table users;
private AddUserPage addUserPage = new AddUserPage(webDriver);
public ManageUsersPage(WebDriver webDriver) {
super(pageUrl, webDriver);
}
public boolean isUserDisplayedInTable(String userName){
List<WebElement> tableList = webDriver.findElements(By.tagName("table"));
for(WebElement table:tableList) {
if(table.getText().contains(userName)) {
users = new Table(table);
return true;
}
}
return false;
}
/**
* set a specific role for a user
*/
public void updateUser(String role, String userName) {
int COL_USER_NAME = 1;
int COL_SELECT = 0;
Dropdown optionsDropdown = new Dropdown(webDriver.findElement(updateOptions));
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
users.getInputCell(i, COL_SELECT).click();
optionsDropdown.selectValue(role);
webDriver.findElement(updateButton).click();
break;
}
}
}
}
/**
* Find a user using his username and delete it
*/
public void deleteUser(String userName) throws InterruptedException {
int COL_USER_NAME = 1;
int COL_SELECT = 0;
Dropdown optionsDropdown = new Dropdown(webDriver.findElement(updateOptions));
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
users.getInputCell(i, COL_SELECT).click();
optionsDropdown.selectValue("Cancel the selected user accounts");
webDriver.findElement(updateButton).click();
webDriver.findElement(deleteAccountCompletely).click();
addUserPage.getSubmitButton().click();
for (int j=0; j<Settings.browserTimeout; j++) {
if(page.isTextPresentOnPage("has been deleted")){
break;
}
//wait for 1 second and try again
frameworkUtils.wait(1);
}
break;
}
}
}
}
public String getUserRole(String userName){
int COL_USER_NAME = 1;
int COL_ROLE = 3;
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
return users.getCell(i, COL_ROLE).getText();
}
}
}
return "";
}
public void editUser(String userName){
int COL_USER_NAME = 1;
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
webDriver.findElement(By.linkText("edit")).click();
break;
}
}
}
}
}
| UTF-8 | Java | 4,145 | java | ManageUsersPage.java | Java | []
| null | []
| package pivotal.university.acceptance.test.pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import pivotal.university.acceptance.test.config.Settings;
import pivotal.university.acceptance.test.pageObjects.pageElements.Dropdown;
import pivotal.university.acceptance.test.pageObjects.pageElements.Table;
import pivotal.university.acceptance.test.utils.frameworkUtils;
import java.util.List;
public class ManageUsersPage extends Page{
private static String pageUrl = Settings.applicationUrl + "/?q=admin/people";
private By updateButton = By.id("edit-submit--2");
private By updateOptions = By.id("edit-operation");
private By deleteAccountCompletely = By.id("edit-user-cancel-method--5");
private Page page = new Page("", webDriver);
private Table users;
private AddUserPage addUserPage = new AddUserPage(webDriver);
public ManageUsersPage(WebDriver webDriver) {
super(pageUrl, webDriver);
}
public boolean isUserDisplayedInTable(String userName){
List<WebElement> tableList = webDriver.findElements(By.tagName("table"));
for(WebElement table:tableList) {
if(table.getText().contains(userName)) {
users = new Table(table);
return true;
}
}
return false;
}
/**
* set a specific role for a user
*/
public void updateUser(String role, String userName) {
int COL_USER_NAME = 1;
int COL_SELECT = 0;
Dropdown optionsDropdown = new Dropdown(webDriver.findElement(updateOptions));
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
users.getInputCell(i, COL_SELECT).click();
optionsDropdown.selectValue(role);
webDriver.findElement(updateButton).click();
break;
}
}
}
}
/**
* Find a user using his username and delete it
*/
public void deleteUser(String userName) throws InterruptedException {
int COL_USER_NAME = 1;
int COL_SELECT = 0;
Dropdown optionsDropdown = new Dropdown(webDriver.findElement(updateOptions));
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
users.getInputCell(i, COL_SELECT).click();
optionsDropdown.selectValue("Cancel the selected user accounts");
webDriver.findElement(updateButton).click();
webDriver.findElement(deleteAccountCompletely).click();
addUserPage.getSubmitButton().click();
for (int j=0; j<Settings.browserTimeout; j++) {
if(page.isTextPresentOnPage("has been deleted")){
break;
}
//wait for 1 second and try again
frameworkUtils.wait(1);
}
break;
}
}
}
}
public String getUserRole(String userName){
int COL_USER_NAME = 1;
int COL_ROLE = 3;
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
return users.getCell(i, COL_ROLE).getText();
}
}
}
return "";
}
public void editUser(String userName){
int COL_USER_NAME = 1;
if (isUserDisplayedInTable(userName)){
for(int i=0; i<users.getRowCount();i++) {
if (users.getCell(i, COL_USER_NAME).getText().equals(userName)) {
webDriver.findElement(By.linkText("edit")).click();
break;
}
}
}
}
}
| 4,145 | 0.576116 | 0.572256 | 127 | 31.637794 | 27.552004 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.519685 | false | false | 15 |
4d835aa942022d5276e2f212774728ec26dcdcbe | 21,655,225,155,339 | 6d28bd052a19adaf9b69725a2682f499fe258575 | /tiendaBases/src/java/conexion/ConnectionDB.java | 5434a813eaa1e9ba6eed33b5a357352657025655 | []
| no_license | juanvalag/tiendaBases | https://github.com/juanvalag/tiendaBases | eb5066722dbbb05f557cee59f9332dea57171490 | 54e69cf616cbafb021cd8165684b402ab6fdb7b2 | refs/heads/master | 2020-08-23T14:08:49.349000 | 2019-11-21T22:24:05 | 2019-11-21T22:24:05 | 216,634,495 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package conexion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConnectionDB
{
private final String url;
private final String username;
private final String password;
private Connection conn;
public ConnectionDB()
{
this.url = "jdbc:mysql://localhost:3306/tiendaBases";
this.username = "root";
this.password = "MySQLRoot";
try
{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();//para MySQL 8.x..x
//Class.forName("com.mysql.jdbc.Driver").newInstance();//para MySQL 5.x..x
this.conn = DriverManager.getConnection(this.url, this.username, this.password);
if(this.conn!=null)
System.out.println("Todo bien..estamos conectados..!!");
else
System.out.println("No se pudo conectar");
}
catch (SQLException e)
{
for (Throwable t : e) {
t.printStackTrace();
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConn() {
return conn;
}
public void cierraConexion()
{
try
{
this.conn.close();
}
catch (SQLException ex)
{
Logger.getLogger(ConnectionDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | UTF-8 | Java | 1,719 | java | ConnectionDB.java | Java | [
{
"context": "lhost:3306/tiendaBases\";\n this.username = \"root\";\n this.password = \"MySQLRoot\";\n \n\n ",
"end": 472,
"score": 0.7480207085609436,
"start": 468,
"tag": "USERNAME",
"value": "root"
},
{
"context": " this.username = \"root\";\n this.password = \"MySQLRoot\";\n \n\n try \n {\n Class.fo",
"end": 509,
"score": 0.9993354678153992,
"start": 500,
"tag": "PASSWORD",
"value": "MySQLRoot"
}
]
| null | []
| package conexion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConnectionDB
{
private final String url;
private final String username;
private final String password;
private Connection conn;
public ConnectionDB()
{
this.url = "jdbc:mysql://localhost:3306/tiendaBases";
this.username = "root";
this.password = "<PASSWORD>";
try
{
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();//para MySQL 8.x..x
//Class.forName("com.mysql.jdbc.Driver").newInstance();//para MySQL 5.x..x
this.conn = DriverManager.getConnection(this.url, this.username, this.password);
if(this.conn!=null)
System.out.println("Todo bien..estamos conectados..!!");
else
System.out.println("No se pudo conectar");
}
catch (SQLException e)
{
for (Throwable t : e) {
t.printStackTrace();
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Connection getConn() {
return conn;
}
public void cierraConexion()
{
try
{
this.conn.close();
}
catch (SQLException ex)
{
Logger.getLogger(ConnectionDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 1,720 | 0.55381 | 0.55032 | 66 | 25.060606 | 22.661461 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.439394 | false | false | 15 |
03f17e037807ddc6b9df34a219ea832cef54dc97 | 24,034,637,039,646 | 12eea525b4b813ef7faf4bc89192d6404ea5ff2b | /app/src/main/java/nyc/c4q/maxrosado/finalexampracticalportion/SettingsScreenActivity.java | 8264787b38c0ec2174460c398e12662677a9db57 | []
| no_license | Maximus027/FinalExamPracticalPortion | https://github.com/Maximus027/FinalExamPracticalPortion | aa039b1edba4594a59de3659bfd647563850eec7 | c2e52969334a96080a8631841c57629756b4603f | refs/heads/master | 2021-01-22T06:07:11.584000 | 2017-02-12T23:18:56 | 2017-02-12T23:18:56 | 81,735,920 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nyc.c4q.maxrosado.finalexampracticalportion;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SettingsScreenActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_screen);
RecyclerView settingsRecyclerView = (RecyclerView) findViewById(R.id.activity_settings_screen);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
settingsRecyclerView.setLayoutManager(linearLayoutManager);
}
public class Setting {
private String setting;
public Setting (int number) {
}
}
public class SettingsViewHolder extends RecyclerView.ViewHolder {
private TextView tv1;
private RecyclerView.ViewHolder settingsVH;
private RecyclerView settingsRV;
public SettingsViewHolder(View itemView) {
super(itemView);
tv1 = (TextView) itemView.findViewById(R.id.settings_tv);
}
public void bind() {
}
}
public class SettingsAdapter extends RecyclerView.Adapter<SettingsViewHolder> {
private Context context;
@Override
public SettingsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(SettingsViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
}
}
| UTF-8 | Java | 1,845 | java | SettingsScreenActivity.java | Java | []
| null | []
| package nyc.c4q.maxrosado.finalexampracticalportion;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SettingsScreenActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_screen);
RecyclerView settingsRecyclerView = (RecyclerView) findViewById(R.id.activity_settings_screen);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
settingsRecyclerView.setLayoutManager(linearLayoutManager);
}
public class Setting {
private String setting;
public Setting (int number) {
}
}
public class SettingsViewHolder extends RecyclerView.ViewHolder {
private TextView tv1;
private RecyclerView.ViewHolder settingsVH;
private RecyclerView settingsRV;
public SettingsViewHolder(View itemView) {
super(itemView);
tv1 = (TextView) itemView.findViewById(R.id.settings_tv);
}
public void bind() {
}
}
public class SettingsAdapter extends RecyclerView.Adapter<SettingsViewHolder> {
private Context context;
@Override
public SettingsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(SettingsViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
}
}
| 1,845 | 0.691057 | 0.687263 | 65 | 27.384615 | 26.681421 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 15 |
50a85889051a45da9d37c82d61bffbb788aecf1f | 32,049,045,973,358 | fe27b8c3ae6f24df22f6eb5e2f9092468c52bb15 | /ProyectoRedesVersionDos/src/Client/HiloClient.java | e9b244304ec7b09c55eeff810c9bc37a7bb0643d | []
| no_license | JassonRomero/ProyectoRedesVersionDos | https://github.com/JassonRomero/ProyectoRedesVersionDos | 525ffd80d15f424366a70297a0dd4d5f36f576ea | 306277f5790835ea4fa5dd4cf46356435a3e8f61 | refs/heads/master | 2022-11-13T13:19:26.058000 | 2020-07-07T04:48:06 | 2020-07-07T04:48:06 | 277,393,120 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Client;
import Utility.Utility;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocketFactory;
public class HiloClient extends Thread {
private int porEsperar;
private boolean execute;
private String[] listaDeArchivosServidor;
private String nombrelog;
private String nombreCarpeta;
private String token;
private Socket socket;
private DataOutputStream send;
private DataInputStream receive;
private InetAddress address;
public HiloClient(String ip, String nombre) throws IOException {
this.porEsperar = 5000;
this.execute = true;
this.listaDeArchivosServidor = null;
this.nombrelog = nombre;
String sistema = System.getProperty("os.name");
if (sistema.equalsIgnoreCase("Linux")) {
this.token = "/";
} else {
this.token = "\\";
}
this.nombreCarpeta = "Respaldo" + this.token;
this.address = InetAddress.getByName(ip);
configurar();
this.send = new DataOutputStream(this.socket.getOutputStream());
this.receive = new DataInputStream(this.socket.getInputStream());
}
private void configurar() throws IOException {
System.setProperty("javax.net.ssl.keyStore", "certs" + this.token + "serverKey.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "112358");
System.setProperty("javax.net.ssl.trustStore", "certs" + this.token + "clientTrustedCerts.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "112358");
SSLSocketFactory clientFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
this.socket = clientFactory.createSocket(this.address, Utility.SOCKETNUMBER);
}
@Override
public void run() {
try {
while (this.execute) {
this.sleep(this.porEsperar);
/*
* Cada treinta segundos descarga la lista de archivos
* del servidor para compararlos con los del cliente.
*/
descargarListaArchivos();
compararListas();
}
} catch (InterruptedException ex) {
Logger.getLogger(HiloClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HiloClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void compararListas() throws IOException, NullPointerException {
File carpetaUsuario = new File(this.nombreCarpeta);
String listaDeArchivosCliente[] = carpetaUsuario.list();
if (this.listaDeArchivosServidor == null) {
System.out.println("this.listaDeArchivosServidor == null");
if (listaDeArchivosCliente.length > 0) {
ArrayList<String> t = new ArrayList<>();
for (String s : listaDeArchivosCliente) {
t.add(s);
}
System.out.println("Línea 96");
cargar(t);
}
return;
}
/* Si en el cliente hay más archivos, éstos son cargados al servidor */
if (listaDeArchivosCliente.length > this.listaDeArchivosServidor.length) {
System.out.println("listaDeArchivosCliente.length > this.listaDeArchivosServidor.length");
tareaComparar(listaDeArchivosCliente, this.listaDeArchivosServidor, 1);
} else if (listaDeArchivosCliente.length < this.listaDeArchivosServidor.length) {
System.out.println("listaDeArchivosCliente.length < this.listaDeArchivosServidor.length");
tareaComparar(this.listaDeArchivosServidor, listaDeArchivosCliente, 2);
}
}
private void tareaComparar(String[] lista1, String[] lista2, int op) throws IOException {
int i;
int j;
boolean existe = false;
ArrayList<String> listaDeDiferencias = new ArrayList();
for (i = 0; i < lista1.length; i++) {
for (j = 0; j < lista2.length; j++) {
if (lista1[i].equalsIgnoreCase(lista2[j])) {
existe = true;
break;
}
}
if (!existe) {
listaDeDiferencias.add(lista1[i]);
}
existe = false;
}
if (!listaDeDiferencias.isEmpty()) {
switch (op) {
case 1:
cargar(listaDeDiferencias);
break;
case 2:
descargar(listaDeDiferencias);
break;
}
}
}
private void cargar(ArrayList<String> lista) throws IOException {
identificarse();
for (String archivoIterador : lista) {
/* Avisa al servidor que se le enviara un archivo */
this.send.writeUTF(Utility.AVISOENVIO);
/* Se envia el nombre del archivo */
this.send.writeUTF(archivoIterador);
byte byteArray[] = null;
byteArray = Files.readAllBytes(Paths.get(this.nombreCarpeta + archivoIterador));
this.send.write(byteArray);
this.send.flush();
this.send.close();
configurar();
this.send = new DataOutputStream(this.socket.getOutputStream());
this.receive = new DataInputStream(this.socket.getInputStream());
identificarse();
System.out.println("[*] Envío satisfactorio");
}
}
private void descargar(ArrayList<String> lista) throws IOException {
identificarse();
for (String archivoIterador : lista) {
this.send.writeUTF(Utility.AVISODESCARGA);
this.send.writeUTF(archivoIterador);
String mensaje = this.receive.readUTF();
if (mensaje.equalsIgnoreCase(Utility.CONFIRMADO)) {
byte readbytes[] = new byte[4096];
InputStream in = this.socket.getInputStream();
try (OutputStream file = Files.newOutputStream(Paths.get(this.nombreCarpeta + archivoIterador))) {
for (int read = -1; (read = in.read(readbytes)) > 0;) {
file.write(readbytes, 0, read);
if (read < 4096) {
break;
}
}
file.flush();
file.close();
}
this.receive.close();
configurar();
this.receive = new DataInputStream(this.socket.getInputStream());
this.send = new DataOutputStream(this.socket.getOutputStream());
in.close();
identificarse();
}
}
}
public void descargarListaArchivos() throws IOException {
identificarse();
this.send.writeUTF(Utility.AVISOLISTAR);
/* Manda la cantidad de archivos */
String mensaje = this.receive.readUTF();
if (mensaje.equalsIgnoreCase(Utility.DENEGADO)) {
this.listaDeArchivosServidor = null;
System.err.println("No se encontraron archivos para listar");
return;
}
try {
int cantidadArchivos = Integer.parseInt(mensaje);
this.listaDeArchivosServidor = new String[cantidadArchivos];
for (int i = 0; i < cantidadArchivos; i++) {
this.listaDeArchivosServidor[i] = this.receive.readUTF();
}
} catch (NumberFormatException e) {
System.err.println(e);
}
}
public void identificarse() throws IOException {
this.send.writeUTF(Utility.IDENTIFICAR);
this.send.writeUTF(this.nombrelog);
}
}
| UTF-8 | Java | 8,152 | java | HiloClient.java | Java | [
{
"context": "em.setProperty(\"javax.net.ssl.keyStorePassword\", \"112358\");\n System.setProperty(\"javax.net.ssl.trus",
"end": 1723,
"score": 0.9931473731994629,
"start": 1717,
"tag": "PASSWORD",
"value": "112358"
},
{
"context": ".setProperty(\"javax.net.ssl.trustStorePassword\", \"112358\");\n\n SSLSocketFactory clientFactory = (SSL",
"end": 1902,
"score": 0.9974643588066101,
"start": 1896,
"tag": "PASSWORD",
"value": "112358"
}
]
| null | []
| package Client;
import Utility.Utility;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocketFactory;
public class HiloClient extends Thread {
private int porEsperar;
private boolean execute;
private String[] listaDeArchivosServidor;
private String nombrelog;
private String nombreCarpeta;
private String token;
private Socket socket;
private DataOutputStream send;
private DataInputStream receive;
private InetAddress address;
public HiloClient(String ip, String nombre) throws IOException {
this.porEsperar = 5000;
this.execute = true;
this.listaDeArchivosServidor = null;
this.nombrelog = nombre;
String sistema = System.getProperty("os.name");
if (sistema.equalsIgnoreCase("Linux")) {
this.token = "/";
} else {
this.token = "\\";
}
this.nombreCarpeta = "Respaldo" + this.token;
this.address = InetAddress.getByName(ip);
configurar();
this.send = new DataOutputStream(this.socket.getOutputStream());
this.receive = new DataInputStream(this.socket.getInputStream());
}
private void configurar() throws IOException {
System.setProperty("javax.net.ssl.keyStore", "certs" + this.token + "serverKey.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "<PASSWORD>");
System.setProperty("javax.net.ssl.trustStore", "certs" + this.token + "clientTrustedCerts.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "<PASSWORD>");
SSLSocketFactory clientFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
this.socket = clientFactory.createSocket(this.address, Utility.SOCKETNUMBER);
}
@Override
public void run() {
try {
while (this.execute) {
this.sleep(this.porEsperar);
/*
* Cada treinta segundos descarga la lista de archivos
* del servidor para compararlos con los del cliente.
*/
descargarListaArchivos();
compararListas();
}
} catch (InterruptedException ex) {
Logger.getLogger(HiloClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(HiloClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void compararListas() throws IOException, NullPointerException {
File carpetaUsuario = new File(this.nombreCarpeta);
String listaDeArchivosCliente[] = carpetaUsuario.list();
if (this.listaDeArchivosServidor == null) {
System.out.println("this.listaDeArchivosServidor == null");
if (listaDeArchivosCliente.length > 0) {
ArrayList<String> t = new ArrayList<>();
for (String s : listaDeArchivosCliente) {
t.add(s);
}
System.out.println("Línea 96");
cargar(t);
}
return;
}
/* Si en el cliente hay más archivos, éstos son cargados al servidor */
if (listaDeArchivosCliente.length > this.listaDeArchivosServidor.length) {
System.out.println("listaDeArchivosCliente.length > this.listaDeArchivosServidor.length");
tareaComparar(listaDeArchivosCliente, this.listaDeArchivosServidor, 1);
} else if (listaDeArchivosCliente.length < this.listaDeArchivosServidor.length) {
System.out.println("listaDeArchivosCliente.length < this.listaDeArchivosServidor.length");
tareaComparar(this.listaDeArchivosServidor, listaDeArchivosCliente, 2);
}
}
private void tareaComparar(String[] lista1, String[] lista2, int op) throws IOException {
int i;
int j;
boolean existe = false;
ArrayList<String> listaDeDiferencias = new ArrayList();
for (i = 0; i < lista1.length; i++) {
for (j = 0; j < lista2.length; j++) {
if (lista1[i].equalsIgnoreCase(lista2[j])) {
existe = true;
break;
}
}
if (!existe) {
listaDeDiferencias.add(lista1[i]);
}
existe = false;
}
if (!listaDeDiferencias.isEmpty()) {
switch (op) {
case 1:
cargar(listaDeDiferencias);
break;
case 2:
descargar(listaDeDiferencias);
break;
}
}
}
private void cargar(ArrayList<String> lista) throws IOException {
identificarse();
for (String archivoIterador : lista) {
/* Avisa al servidor que se le enviara un archivo */
this.send.writeUTF(Utility.AVISOENVIO);
/* Se envia el nombre del archivo */
this.send.writeUTF(archivoIterador);
byte byteArray[] = null;
byteArray = Files.readAllBytes(Paths.get(this.nombreCarpeta + archivoIterador));
this.send.write(byteArray);
this.send.flush();
this.send.close();
configurar();
this.send = new DataOutputStream(this.socket.getOutputStream());
this.receive = new DataInputStream(this.socket.getInputStream());
identificarse();
System.out.println("[*] Envío satisfactorio");
}
}
private void descargar(ArrayList<String> lista) throws IOException {
identificarse();
for (String archivoIterador : lista) {
this.send.writeUTF(Utility.AVISODESCARGA);
this.send.writeUTF(archivoIterador);
String mensaje = this.receive.readUTF();
if (mensaje.equalsIgnoreCase(Utility.CONFIRMADO)) {
byte readbytes[] = new byte[4096];
InputStream in = this.socket.getInputStream();
try (OutputStream file = Files.newOutputStream(Paths.get(this.nombreCarpeta + archivoIterador))) {
for (int read = -1; (read = in.read(readbytes)) > 0;) {
file.write(readbytes, 0, read);
if (read < 4096) {
break;
}
}
file.flush();
file.close();
}
this.receive.close();
configurar();
this.receive = new DataInputStream(this.socket.getInputStream());
this.send = new DataOutputStream(this.socket.getOutputStream());
in.close();
identificarse();
}
}
}
public void descargarListaArchivos() throws IOException {
identificarse();
this.send.writeUTF(Utility.AVISOLISTAR);
/* Manda la cantidad de archivos */
String mensaje = this.receive.readUTF();
if (mensaje.equalsIgnoreCase(Utility.DENEGADO)) {
this.listaDeArchivosServidor = null;
System.err.println("No se encontraron archivos para listar");
return;
}
try {
int cantidadArchivos = Integer.parseInt(mensaje);
this.listaDeArchivosServidor = new String[cantidadArchivos];
for (int i = 0; i < cantidadArchivos; i++) {
this.listaDeArchivosServidor[i] = this.receive.readUTF();
}
} catch (NumberFormatException e) {
System.err.println(e);
}
}
public void identificarse() throws IOException {
this.send.writeUTF(Utility.IDENTIFICAR);
this.send.writeUTF(this.nombrelog);
}
}
| 8,160 | 0.581492 | 0.576092 | 228 | 34.736843 | 26.751801 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622807 | false | false | 15 |
a222ea037e30fd8c4a9996674eebb87e26c8c833 | 30,717,606,160,785 | 8db3b11725811ca3a76e37592475f7a7c0d743f8 | /shop_netty/src/main/java/com/qf/handler/WsHeartHandler.java | 6ae6829b4799799d8d91b1a5d5c396fe98da84e8 | []
| no_license | ordinarypasserby/shop1906 | https://github.com/ordinarypasserby/shop1906 | 3a197857a7047309bc09c668b92e5b9fb3b5cc20 | 64497211978d5f15df67d8a76cd1f48913aa1aa5 | refs/heads/master | 2022-12-21T08:42:53.421000 | 2019-11-17T07:28:51 | 2019-11-17T07:28:51 | 216,718,488 | 0 | 0 | null | false | 2022-06-17T03:23:01 | 2019-10-22T03:47:58 | 2019-11-17T07:29:34 | 2022-06-17T03:23:01 | 3,740 | 0 | 0 | 2 | JavaScript | false | false | package com.qf.handler;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;
/**
* @author DingYuHui
* @Date 2019/11/17
*/
@Component
@ChannelHandler.Sharable
public class WsHeartHandler extends SimpleChannelInboundHandler<JSONObject> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, JSONObject jsonObject) throws Exception {
if (jsonObject.getInteger("msgType")==2){
System.out.println("接收到心跳消息");
//回复心跳消息
channelHandlerContext.writeAndFlush(new TextWebSocketFrame(jsonObject.toJSONString()));
return;
}
//继续透传
channelHandlerContext.fireChannelRead(jsonObject);
}
}
| UTF-8 | Java | 979 | java | WsHeartHandler.java | Java | [
{
"context": "ingframework.stereotype.Component;\n\n/**\n * @author DingYuHui\n * @Date 2019/11/17\n */\n@Component\n@ChannelHandle",
"end": 345,
"score": 0.9994521141052246,
"start": 336,
"tag": "NAME",
"value": "DingYuHui"
}
]
| null | []
| package com.qf.handler;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.stereotype.Component;
/**
* @author DingYuHui
* @Date 2019/11/17
*/
@Component
@ChannelHandler.Sharable
public class WsHeartHandler extends SimpleChannelInboundHandler<JSONObject> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, JSONObject jsonObject) throws Exception {
if (jsonObject.getInteger("msgType")==2){
System.out.println("接收到心跳消息");
//回复心跳消息
channelHandlerContext.writeAndFlush(new TextWebSocketFrame(jsonObject.toJSONString()));
return;
}
//继续透传
channelHandlerContext.fireChannelRead(jsonObject);
}
}
| 979 | 0.744974 | 0.734392 | 30 | 30.5 | 29.935207 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 15 |
1c929f1b250a3520459b0057bd4a4ec14cef902f | 30,717,606,158,333 | 384a79c56af305bc54fa1a435bf153eda3966291 | /winery-mapper/src/main/java/com/changfa/frame/mapper/app/WineryMasterMapper.java | c8fff60bb92f7693c8030404ab05b77507536fcf | [
"Apache-2.0"
]
| permissive | luffykid/smart_wine_java | https://github.com/luffykid/smart_wine_java | c8ad92427ff224306607e7b702e50b696f60d5c9 | e53bea4aef2b7967e9c11ea64428ac729994caa9 | refs/heads/master | 2022-12-22T20:35:56.390000 | 2019-08-26T07:10:29 | 2019-08-26T07:10:29 | 204,379,275 | 0 | 1 | NOASSERTION | false | 2022-12-10T05:42:48 | 2019-08-26T02:21:34 | 2019-08-26T07:15:18 | 2022-12-10T05:42:48 | 1,834 | 0 | 0 | 15 | Java | false | false | /*
* WineryMasterMapper.java
* Copyright(C) 北京畅发科技有限公司
* All rights reserved.
* -----------------------------------------------
* 2019-08-24 Created
*/
package com.changfa.frame.mapper.app;
import com.changfa.frame.mapper.common.BaseMapper;
import com.changfa.frame.model.app.WineryMaster;
public interface WineryMasterMapper extends BaseMapper<WineryMaster, Long> {
} | UTF-8 | Java | 396 | java | WineryMasterMapper.java | Java | []
| null | []
| /*
* WineryMasterMapper.java
* Copyright(C) 北京畅发科技有限公司
* All rights reserved.
* -----------------------------------------------
* 2019-08-24 Created
*/
package com.changfa.frame.mapper.app;
import com.changfa.frame.mapper.common.BaseMapper;
import com.changfa.frame.model.app.WineryMaster;
public interface WineryMasterMapper extends BaseMapper<WineryMaster, Long> {
} | 396 | 0.678191 | 0.656915 | 14 | 25.928572 | 22.948589 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 15 |
f50fe376d19c91343d533fafc1c27c9f6caccdc2 | 11,785,390,317,051 | de9ad2f4efa87ed74efad00d9f1bc83bce5febec | /net.sourceforge.tagsea.resources/src/net/sourceforge/tagsea/resources/ResourceWaypointUtils.java | 3216533cc2f493116c77e228ab4921d1dad443e3 | []
| no_license | rteusner/tagsea | https://github.com/rteusner/tagsea | 7bdd8fd088a8099739a9ce94d3c151ccb89b96ab | 03f15c2456434b0e0d72e0d575eca1d743d6051c | refs/heads/master | 2016-08-05T09:37:57.081000 | 2012-09-28T19:35:26 | 2012-09-28T19:35:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright 2005-2006, CHISEL Group, University of Victoria, Victoria, BC, Canada.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* The Chisel Group, University of Victoria
*******************************************************************************/
package net.sourceforge.tagsea.resources;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import net.sourceforge.tagsea.AbstractWaypointDelegate;
import net.sourceforge.tagsea.TagSEAPlugin;
import net.sourceforge.tagsea.core.IWaypoint;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
/**
* Utilitly methods for resource waypoints.
* @author Del Myers
*/
public class ResourceWaypointUtils {
/**
* Returns the full path for the resource of the given waypoint.
* @param waypoint
* @return
*/
public static IPath getResourcePath(IWaypoint waypoint) {
if (!isResource(waypoint)) return null;
String resourceString = waypoint.getStringValue(IResourceWaypointAttributes.ATTR_RESOURCE, null);
if (resourceString == null) return null;
return new Path(resourceString);
}
/**
* Returns the resource that the waypoint points to, or null if it does not exist.
* @param waypoint
* @return
*/
public static IResource getResource(IWaypoint waypoint) {
IPath path = getResourcePath(waypoint);
if (path == null) return null;
return ResourcesPlugin.getWorkspace().getRoot().findMember(path);
}
public static int getLine(IWaypoint waypoint) {
if (!isText(waypoint)) return -2;
return waypoint.getIntValue(IResourceWaypointAttributes.ATTR_LINE, -2);
}
/**
* Returnst all the resource waypoints for the given resource.
* @param resource the resource to check
* @param includeSubtypes this method should include waypoints that are subtypes of the resource waypoints.
* @return a list of waypoints.
*/
public static IWaypoint[] getWaypointsForResource(IResource resource, boolean includeSubtypes) {
HashSet<AbstractWaypointDelegate> delegatesToCheck = new HashSet<AbstractWaypointDelegate>();
delegatesToCheck.add(TagSEAPlugin.getDefault().getWaypointDelegate(ResourceWaypointPlugin.WAYPOINT_ID));
List<IWaypoint> result = new LinkedList<IWaypoint>();
if (includeSubtypes) {
for (AbstractWaypointDelegate delegate : TagSEAPlugin.getDefault().getWaypointDelegates()) {
if (delegate.isSubtypeOf(ResourceWaypointPlugin.INTERFACE_ID)) {
delegatesToCheck.add(delegate);
}
}
}
for (AbstractWaypointDelegate delegate : delegatesToCheck) {
IWaypoint[] waypoints = TagSEAPlugin.getWaypointsModel().getWaypoints(delegate.getType());
for (IWaypoint waypoint : waypoints) {
if (resource.getFullPath().equals(getResourcePath(waypoint))) {
result.add(waypoint);
}
}
}
return result.toArray(new IWaypoint[result.size()]);
}
private static boolean isText(IWaypoint waypoint) {
return waypoint.isSubtypeOf(IWaypoint.TEXT_WAYPOINT);
}
private static boolean isResource(IWaypoint waypoint) {
return waypoint.isSubtypeOf(ResourceWaypointPlugin.INTERFACE_ID);
}
/**
* Returns all of the waypoints for a given project. Note that the waypoint's need not actually point to
* an existant resource. The resource may not exist in the project.
* @param project
* @return
*/
public static IWaypoint[] getWaypointsForProject(IProject project) {
IWaypoint[] waypoints = TagSEAPlugin.getWaypointsModel().getWaypoints(ResourceWaypointPlugin.WAYPOINT_ID);
List<IWaypoint> result = new ArrayList<IWaypoint>();
for (IWaypoint waypoint : waypoints) {
IPath path = getResourcePath(waypoint);
if (project.getFullPath().isPrefixOf(path)) {
result.add(waypoint);
}
}
return result.toArray(new IWaypoint[result.size()]);
}
}
| UTF-8 | Java | 4,227 | java | ResourceWaypointUtils.java | Java | [
{
"context": "tilitly methods for resource waypoints.\n * @author Del Myers\n */\n\npublic class ResourceWaypointUtils {\n\t\n\t/**\n",
"end": 1144,
"score": 0.9993073344230652,
"start": 1135,
"tag": "NAME",
"value": "Del Myers"
}
]
| null | []
| /*******************************************************************************
* Copyright 2005-2006, CHISEL Group, University of Victoria, Victoria, BC, Canada.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* The Chisel Group, University of Victoria
*******************************************************************************/
package net.sourceforge.tagsea.resources;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import net.sourceforge.tagsea.AbstractWaypointDelegate;
import net.sourceforge.tagsea.TagSEAPlugin;
import net.sourceforge.tagsea.core.IWaypoint;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
/**
* Utilitly methods for resource waypoints.
* @author <NAME>
*/
public class ResourceWaypointUtils {
/**
* Returns the full path for the resource of the given waypoint.
* @param waypoint
* @return
*/
public static IPath getResourcePath(IWaypoint waypoint) {
if (!isResource(waypoint)) return null;
String resourceString = waypoint.getStringValue(IResourceWaypointAttributes.ATTR_RESOURCE, null);
if (resourceString == null) return null;
return new Path(resourceString);
}
/**
* Returns the resource that the waypoint points to, or null if it does not exist.
* @param waypoint
* @return
*/
public static IResource getResource(IWaypoint waypoint) {
IPath path = getResourcePath(waypoint);
if (path == null) return null;
return ResourcesPlugin.getWorkspace().getRoot().findMember(path);
}
public static int getLine(IWaypoint waypoint) {
if (!isText(waypoint)) return -2;
return waypoint.getIntValue(IResourceWaypointAttributes.ATTR_LINE, -2);
}
/**
* Returnst all the resource waypoints for the given resource.
* @param resource the resource to check
* @param includeSubtypes this method should include waypoints that are subtypes of the resource waypoints.
* @return a list of waypoints.
*/
public static IWaypoint[] getWaypointsForResource(IResource resource, boolean includeSubtypes) {
HashSet<AbstractWaypointDelegate> delegatesToCheck = new HashSet<AbstractWaypointDelegate>();
delegatesToCheck.add(TagSEAPlugin.getDefault().getWaypointDelegate(ResourceWaypointPlugin.WAYPOINT_ID));
List<IWaypoint> result = new LinkedList<IWaypoint>();
if (includeSubtypes) {
for (AbstractWaypointDelegate delegate : TagSEAPlugin.getDefault().getWaypointDelegates()) {
if (delegate.isSubtypeOf(ResourceWaypointPlugin.INTERFACE_ID)) {
delegatesToCheck.add(delegate);
}
}
}
for (AbstractWaypointDelegate delegate : delegatesToCheck) {
IWaypoint[] waypoints = TagSEAPlugin.getWaypointsModel().getWaypoints(delegate.getType());
for (IWaypoint waypoint : waypoints) {
if (resource.getFullPath().equals(getResourcePath(waypoint))) {
result.add(waypoint);
}
}
}
return result.toArray(new IWaypoint[result.size()]);
}
private static boolean isText(IWaypoint waypoint) {
return waypoint.isSubtypeOf(IWaypoint.TEXT_WAYPOINT);
}
private static boolean isResource(IWaypoint waypoint) {
return waypoint.isSubtypeOf(ResourceWaypointPlugin.INTERFACE_ID);
}
/**
* Returns all of the waypoints for a given project. Note that the waypoint's need not actually point to
* an existant resource. The resource may not exist in the project.
* @param project
* @return
*/
public static IWaypoint[] getWaypointsForProject(IProject project) {
IWaypoint[] waypoints = TagSEAPlugin.getWaypointsModel().getWaypoints(ResourceWaypointPlugin.WAYPOINT_ID);
List<IWaypoint> result = new ArrayList<IWaypoint>();
for (IWaypoint waypoint : waypoints) {
IPath path = getResourcePath(waypoint);
if (project.getFullPath().isPrefixOf(path)) {
result.add(waypoint);
}
}
return result.toArray(new IWaypoint[result.size()]);
}
}
| 4,224 | 0.728176 | 0.724864 | 118 | 34.822033 | 31.156149 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.618644 | false | false | 15 |
17584c5999457453460ac19e88210bdd181c68fc | 22,058,952,056,353 | 19ca503cd8f1194d826ded783175fed897f13333 | /sts-workspace-examples/example.patterns/src/main/java/example/patterns/facade/ExampleMain.java | 1161efcff899eee080fac7e013a736406d572f05 | []
| no_license | dgkim11/examples | https://github.com/dgkim11/examples | 7ec497f07109ae599d5cec2af83491724bd49442 | 00887a605bc9564380fc9e24c3245c97b8bcc4d6 | refs/heads/master | 2016-08-11T11:37:58.321000 | 2016-01-10T02:15:04 | 2016-01-10T02:15:04 | 49,347,594 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package example.patterns.facade;
public class ExampleMain {
public static void main(String[] args) {
ExampleMain theApp = new ExampleMain();
theApp.execute();
}
private void execute() {
Resterant resterant = new Resterant();
resterant.orderFood("table3", "Stake");
}
}
| UTF-8 | Java | 340 | java | ExampleMain.java | Java | []
| null | []
| package example.patterns.facade;
public class ExampleMain {
public static void main(String[] args) {
ExampleMain theApp = new ExampleMain();
theApp.execute();
}
private void execute() {
Resterant resterant = new Resterant();
resterant.orderFood("table3", "Stake");
}
}
| 340 | 0.591176 | 0.588235 | 14 | 22.285715 | 18.591198 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 15 |
023fbf791d9b6fba6d5159c6ee0db57292c8a39f | 3,925,600,176,534 | efc55d73f1425ac90d227209b70867f4dd487c5c | /Chapter4/Aurora/src/test/java/org/apache/aurora/GuiceUtilsTest.java | 319fac0b4c3d487e5bfb1c69ff698cfc988403e9 | [
"MIT",
"Apache-2.0"
]
| permissive | PacktPublishing/Mastering-Mesos | https://github.com/PacktPublishing/Mastering-Mesos | 9f6171b449ad96222ce18ad3e3f3c6cdfe8fdbf3 | 88dddb51ed9ad070340edb33eef9fd12745b9f8a | refs/heads/master | 2023-02-08T18:51:28.227000 | 2023-01-30T10:09:39 | 2023-01-30T10:09:39 | 58,921,823 | 12 | 6 | MIT | false | 2022-12-14T20:22:53 | 2016-05-16T09:52:00 | 2022-05-26T11:56:02 | 2022-12-14T20:22:50 | 124,577 | 10 | 8 | 12 | Java | false | false | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aurora;
import java.util.List;
import javax.inject.Singleton;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.apache.aurora.GuiceUtils.AllowUnchecked;
import org.junit.Test;
import static org.junit.Assert.fail;
public class GuiceUtilsTest {
interface Flaky {
void get();
void append(List<String> strings);
void skipped();
}
interface AlsoFlaky extends Flaky {
void get(int value);
void put(String s);
}
static class NotSoFlakyImpl implements AlsoFlaky {
@Override
public void put(String s) {
throw new RuntimeException("Call failed");
}
@Override
public void append(List<String> strings) {
throw new RuntimeException("Call failed");
}
@AllowUnchecked
@Override
public void skipped() {
throw new RuntimeException("Call failed");
}
@Override
public void get(int value) {
throw new RuntimeException("Call failed");
}
@Override
public void get() {
throw new RuntimeException("Call failed");
}
}
@Test
public void testExceptionTrapping() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
GuiceUtils.bindExceptionTrap(binder(), Flaky.class);
bind(Flaky.class).to(NotSoFlakyImpl.class);
bind(AlsoFlaky.class).to(NotSoFlakyImpl.class);
bind(NotSoFlakyImpl.class).in(Singleton.class);
}
});
AlsoFlaky flaky = injector.getInstance(AlsoFlaky.class);
flaky.get();
flaky.append(ImmutableList.of("hi"));
try {
flaky.put("hello");
fail("Should have thrown");
} catch (RuntimeException e) {
// Expected.
}
try {
flaky.get(2);
fail("Should have thrown");
} catch (RuntimeException e) {
// Expected.
}
try {
flaky.skipped();
fail("Should have thrown");
} catch (RuntimeException e) {
// Expected.
}
}
interface NonVoid {
int get();
}
@Test(expected = CreationException.class)
public void testNoTrappingNonVoidMethods() {
Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
GuiceUtils.bindExceptionTrap(binder(), NonVoid.class);
fail("Bind should have failed.");
}
});
}
interface NonVoidWhitelisted {
@AllowUnchecked
int getWhitelisted();
}
@Test
public void testWhitelistNonVoidMethods() {
Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
GuiceUtils.bindExceptionTrap(binder(), NonVoidWhitelisted.class);
}
});
}
}
| UTF-8 | Java | 3,385 | java | GuiceUtilsTest.java | Java | []
| null | []
| /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aurora;
import java.util.List;
import javax.inject.Singleton;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.apache.aurora.GuiceUtils.AllowUnchecked;
import org.junit.Test;
import static org.junit.Assert.fail;
public class GuiceUtilsTest {
interface Flaky {
void get();
void append(List<String> strings);
void skipped();
}
interface AlsoFlaky extends Flaky {
void get(int value);
void put(String s);
}
static class NotSoFlakyImpl implements AlsoFlaky {
@Override
public void put(String s) {
throw new RuntimeException("Call failed");
}
@Override
public void append(List<String> strings) {
throw new RuntimeException("Call failed");
}
@AllowUnchecked
@Override
public void skipped() {
throw new RuntimeException("Call failed");
}
@Override
public void get(int value) {
throw new RuntimeException("Call failed");
}
@Override
public void get() {
throw new RuntimeException("Call failed");
}
}
@Test
public void testExceptionTrapping() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
GuiceUtils.bindExceptionTrap(binder(), Flaky.class);
bind(Flaky.class).to(NotSoFlakyImpl.class);
bind(AlsoFlaky.class).to(NotSoFlakyImpl.class);
bind(NotSoFlakyImpl.class).in(Singleton.class);
}
});
AlsoFlaky flaky = injector.getInstance(AlsoFlaky.class);
flaky.get();
flaky.append(ImmutableList.of("hi"));
try {
flaky.put("hello");
fail("Should have thrown");
} catch (RuntimeException e) {
// Expected.
}
try {
flaky.get(2);
fail("Should have thrown");
} catch (RuntimeException e) {
// Expected.
}
try {
flaky.skipped();
fail("Should have thrown");
} catch (RuntimeException e) {
// Expected.
}
}
interface NonVoid {
int get();
}
@Test(expected = CreationException.class)
public void testNoTrappingNonVoidMethods() {
Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
GuiceUtils.bindExceptionTrap(binder(), NonVoid.class);
fail("Bind should have failed.");
}
});
}
interface NonVoidWhitelisted {
@AllowUnchecked
int getWhitelisted();
}
@Test
public void testWhitelistNonVoidMethods() {
Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
GuiceUtils.bindExceptionTrap(binder(), NonVoidWhitelisted.class);
}
});
}
}
| 3,385 | 0.667061 | 0.665583 | 139 | 23.352518 | 20.951765 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.359712 | false | false | 15 |
b63adb35192316baefc927b1288ab29d8768e83d | 9,801,115,417,076 | a048455222ae2ae16e3c5af215f412f2906d329b | /src/test/ClientMain.java | 6e9dd977791ecaccee3951a18ea19411797e7e2a | []
| no_license | hiennguyen0412/tcpclient-file | https://github.com/hiennguyen0412/tcpclient-file | 33bec428cb8ae37fc84080ea3c1eeace413ada17 | ba761b67ab5a6117883756698f805045f2ef7c17 | refs/heads/master | 2021-05-14T00:04:40.570000 | 2018-01-07T02:51:35 | 2018-01-07T02:51:35 | 116,532,217 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import controller.ClientControl;
import view.ClientView;
public class ClientMain {
public static void main(String[] args) {
ClientView view = new ClientView();
ClientControl clientcontrol = new ClientControl(view);
}
}
| UTF-8 | Java | 243 | java | ClientMain.java | Java | []
| null | []
| package test;
import controller.ClientControl;
import view.ClientView;
public class ClientMain {
public static void main(String[] args) {
ClientView view = new ClientView();
ClientControl clientcontrol = new ClientControl(view);
}
}
| 243 | 0.757202 | 0.757202 | 12 | 19.25 | 18.466749 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 15 |
bae0d5f52bc009dbaffb4d1fe7bca16f1c22fb8d | 11,785,390,320,669 | 80f7c5e71a515ac78d034461f0c418d3040324d7 | /app/src/main/java/com/example/database/MovieCursorAdaptor.java | 88632a4caca4e5d86af60a5a3b6d957d1b76a767 | []
| no_license | Vinamrata1086/DataBase_Demo | https://github.com/Vinamrata1086/DataBase_Demo | f6bd2178927b3cc5e354d84a22488e93d6fff17b | ee3f306c6f1c0a7248b0e2dfd10b29231625060c | refs/heads/master | 2022-11-22T09:44:01.452000 | 2020-07-25T09:28:21 | 2020-07-25T09:28:21 | 282,142,763 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.database;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
class MovieCursorAdaptor extends CursorAdapter {
public MovieCursorAdaptor(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.mylistviewdesign,parent,false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name=view.findViewById(R.id.mname);
TextView actor=view.findViewById(R.id.mactor);
TextView actress=view.findViewById(R.id.mactress);
TextView type=view.findViewById(R.id.type);
TextView year=view.findViewById(R.id.year);
String mname=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_Name));
String mactor=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_ACTOR));
String mactress=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_ACTRESS));
String mtype=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_TYPE));
String ryear=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_RYEAR));
name.setText(mname);
actor.setText(mactor);
actress.setText(mactress);
type.setText(mtype);
year.setText(ryear);
}
} | UTF-8 | Java | 1,572 | java | MovieCursorAdaptor.java | Java | []
| null | []
| package com.example.database;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
class MovieCursorAdaptor extends CursorAdapter {
public MovieCursorAdaptor(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.mylistviewdesign,parent,false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name=view.findViewById(R.id.mname);
TextView actor=view.findViewById(R.id.mactor);
TextView actress=view.findViewById(R.id.mactress);
TextView type=view.findViewById(R.id.type);
TextView year=view.findViewById(R.id.year);
String mname=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_Name));
String mactor=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_ACTOR));
String mactress=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_ACTRESS));
String mtype=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_TYPE));
String ryear=cursor.getString(cursor.getColumnIndexOrThrow(Movie.Data.M_RYEAR));
name.setText(mname);
actor.setText(mactor);
actress.setText(mactress);
type.setText(mtype);
year.setText(ryear);
}
} | 1,572 | 0.729008 | 0.729008 | 39 | 39.333332 | 29.043144 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.897436 | false | false | 15 |
baca87146329d3a2a3f43c28d6b98b52ba60bfa1 | 34,059,090,666,126 | f22dc144285e714bff60c21cedf049a106a595ac | /HostelWorld/src/main/java/com/springmvc/bl/ManagerBLImp.java | 652c2d9731f4fc4c452837b27c107c15f8272156 | []
| no_license | luzhichun/Hostel | https://github.com/luzhichun/Hostel | 048c1e55dc4919de664077650931b7067c9fe45e | e1282a797f0b2e1901faa3392097a8b208ed21c1 | refs/heads/master | 2021-01-18T23:09:59.172000 | 2017-03-02T16:27:20 | 2017-03-02T16:27:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springmvc.bl;
import com.springmvc.blservice.ManagerBLService;
import com.springmvc.config.AccountConfig;
import com.springmvc.config.HotelState;
import com.springmvc.config.Msg;
import com.springmvc.config.UserConfig;
import com.springmvc.dataservice.*;
import com.springmvc.entities.AccountEntity;
import com.springmvc.entities.HotelEntity;
import com.springmvc.entities.UserEntity;
import com.springmvc.model.AccountModel;
import com.springmvc.model.PlanModel;
import com.springmvc.util.TimeUtil;
import com.springmvc.vo.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wzh on 31/01/2017.
*/
public class ManagerBLImp implements ManagerBLService {
@Resource
PlanDataService planDataService;
@Resource
HotelDataService hotelDataService;
@Resource
AccountDataService accountDataService;
@Resource
AppointmentDataService appointmentDataService;
@Resource
UserDataService userDataService;
@Override
public ResultMessageVO login(String hotelId, String password) {
if(!hotelId.equals(UserConfig.HEADQUARTERS_ACCOUNT)){
return new ResultMessageVO(Msg.FAIL,"您没有这个权限");
}
if(checkPassword(password,hotelId)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
return new ResultMessageVO(Msg.FAIL,"用户名或密码错误");
}
private boolean checkPassword(String password,String hotelId){
if (hotelId==null||password.equals("")) return false;
UserEntity entity = userDataService.getUserByHotelId(hotelId);
if (entity==null) return false;
if(entity.getPassword().equals(password)) return true;
return false;
}
@Override
public List<PlanVO> getAllPlans() {
List<PlanModel> models = planDataService.getAllPlanModel();
List<PlanVO> vos = new ArrayList<>();
for (PlanModel model:models){
vos.add(new PlanVO(model.getHotelName(),model.getHotelId(), TimeUtil.date2String(model.getStartDate()),TimeUtil.date2String(model.getEndDate())));
}
return vos;
}
@Override
public List<HotelInfoVO> getHotelApplication() {
String keys[] = {"state"};
Object values[] = {HotelState.APPLY};
List<HotelEntity> entities = hotelDataService.getHotelByCondition(keys,values);
List<HotelInfoVO> vos = new ArrayList<>();
for (HotelEntity entity:entities){
vos.add(new HotelInfoVO(entity.getHotelId(),entity.getName(),entity.getOwner(),entity.getAddress(),entity.getNote()));
}
return vos;
}
@Override
public List<HotelInfoVO> getHotelModifiedApplication() {
String keys[] = {"state"};
Object values[] = {HotelState.CHANGED};
List<HotelEntity> entities = hotelDataService.getHotelByCondition(keys,values);
List<HotelInfoVO> vos = new ArrayList<>();
for (HotelEntity entity:entities){
vos.add(new HotelInfoVO(entity.getHotelId(),entity.getName(),entity.getOwner(),entity.getAddress(),entity.getNote()));
}
return vos;
}
@Override
public ResultMessageVO agreeApplication(String hotelId) {
String keys[] = {"state"};
Object values[] = {HotelState.ADOPTED};
if(hotelDataService.updateHotelById(hotelId,keys,values)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
return new ResultMessageVO(Msg.FAIL,"操作失败,请稍后再试");
}
@Override
public ResultMessageVO refuseApplication(String hotelId) {
String keys[] = {"state"};
Object values[] = {HotelState.REFUSED};
if(hotelDataService.updateHotelById(hotelId,keys,values)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
return new ResultMessageVO(Msg.FAIL,"操作失败,请稍后再试");
}
@Override
public ResultMessageVO settleAccounts(String hotelId, double amount) {
synchronized (this.getClass()){
AccountEntity accountEntity = accountDataService.getAccountById(AccountConfig.HEADQUARTERS_ACCOUNT);
AccountEntity accountEntity1 = accountDataService.getAccountById(hotelId);
double balance = accountEntity.getBalance()-amount;
if(balance<0){
return new ResultMessageVO(Msg.FAIL,"余额不足,结算失败");
}
String keys[] = {"balance"};
Object[] values1 = {balance};
Object[] values2 = {accountEntity1.getBalance()+amount};
if(accountDataService.updateAccountById(AccountConfig.HEADQUARTERS_ACCOUNT,keys,values1)&&accountDataService.updateAccountById(hotelId,keys,values2)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
}
return new ResultMessageVO(Msg.FAIL,"操作失败,请稍后再试");
}
@Override
public List<HotelFinanceVO> getAllHotelFinanceInfo() {
List<AccountModel> models = accountDataService.getAllAccountInfo();
List<HotelFinanceVO> vos = new ArrayList<>();
for (AccountModel model:models){
vos.add(new HotelFinanceVO(model.getHotelName(),model.getBalance()));
}
return vos;
}
}
| UTF-8 | Java | 5,279 | java | ManagerBLImp.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by wzh on 31/01/2017.\n */\npublic class ManagerBLImp impl",
"end": 648,
"score": 0.9996725916862488,
"start": 645,
"tag": "USERNAME",
"value": "wzh"
},
{
"context": "getHotelApplication() {\n String keys[] = {\"state\"};\n Object values[] = {HotelState.APPLY};\n",
"end": 2224,
"score": 0.851139485836029,
"start": 2219,
"tag": "KEY",
"value": "state"
},
{
"context": "ModifiedApplication() {\n String keys[] = {\"state\"};\n Object values[] = {HotelState.CHANGED}",
"end": 2730,
"score": 0.9448544383049011,
"start": 2725,
"tag": "KEY",
"value": "state"
},
{
"context": "ation(String hotelId) {\n String keys[] = {\"state\"};\n Object values[] = {HotelState.ADOPTED}",
"end": 3239,
"score": 0.9173917174339294,
"start": 3234,
"tag": "KEY",
"value": "state"
},
{
"context": "ation(String hotelId) {\n String keys[] = {\"state\"};\n Object values[] = {HotelState.REFUSED}",
"end": 3598,
"score": 0.9394984841346741,
"start": 3593,
"tag": "KEY",
"value": "state"
},
{
"context": "失败\");\n }\n String keys[] = {\"balance\"};\n Object[] values1 = {balance};\n ",
"end": 4387,
"score": 0.9921178817749023,
"start": 4380,
"tag": "KEY",
"value": "balance"
}
]
| null | []
| package com.springmvc.bl;
import com.springmvc.blservice.ManagerBLService;
import com.springmvc.config.AccountConfig;
import com.springmvc.config.HotelState;
import com.springmvc.config.Msg;
import com.springmvc.config.UserConfig;
import com.springmvc.dataservice.*;
import com.springmvc.entities.AccountEntity;
import com.springmvc.entities.HotelEntity;
import com.springmvc.entities.UserEntity;
import com.springmvc.model.AccountModel;
import com.springmvc.model.PlanModel;
import com.springmvc.util.TimeUtil;
import com.springmvc.vo.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wzh on 31/01/2017.
*/
public class ManagerBLImp implements ManagerBLService {
@Resource
PlanDataService planDataService;
@Resource
HotelDataService hotelDataService;
@Resource
AccountDataService accountDataService;
@Resource
AppointmentDataService appointmentDataService;
@Resource
UserDataService userDataService;
@Override
public ResultMessageVO login(String hotelId, String password) {
if(!hotelId.equals(UserConfig.HEADQUARTERS_ACCOUNT)){
return new ResultMessageVO(Msg.FAIL,"您没有这个权限");
}
if(checkPassword(password,hotelId)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
return new ResultMessageVO(Msg.FAIL,"用户名或密码错误");
}
private boolean checkPassword(String password,String hotelId){
if (hotelId==null||password.equals("")) return false;
UserEntity entity = userDataService.getUserByHotelId(hotelId);
if (entity==null) return false;
if(entity.getPassword().equals(password)) return true;
return false;
}
@Override
public List<PlanVO> getAllPlans() {
List<PlanModel> models = planDataService.getAllPlanModel();
List<PlanVO> vos = new ArrayList<>();
for (PlanModel model:models){
vos.add(new PlanVO(model.getHotelName(),model.getHotelId(), TimeUtil.date2String(model.getStartDate()),TimeUtil.date2String(model.getEndDate())));
}
return vos;
}
@Override
public List<HotelInfoVO> getHotelApplication() {
String keys[] = {"state"};
Object values[] = {HotelState.APPLY};
List<HotelEntity> entities = hotelDataService.getHotelByCondition(keys,values);
List<HotelInfoVO> vos = new ArrayList<>();
for (HotelEntity entity:entities){
vos.add(new HotelInfoVO(entity.getHotelId(),entity.getName(),entity.getOwner(),entity.getAddress(),entity.getNote()));
}
return vos;
}
@Override
public List<HotelInfoVO> getHotelModifiedApplication() {
String keys[] = {"state"};
Object values[] = {HotelState.CHANGED};
List<HotelEntity> entities = hotelDataService.getHotelByCondition(keys,values);
List<HotelInfoVO> vos = new ArrayList<>();
for (HotelEntity entity:entities){
vos.add(new HotelInfoVO(entity.getHotelId(),entity.getName(),entity.getOwner(),entity.getAddress(),entity.getNote()));
}
return vos;
}
@Override
public ResultMessageVO agreeApplication(String hotelId) {
String keys[] = {"state"};
Object values[] = {HotelState.ADOPTED};
if(hotelDataService.updateHotelById(hotelId,keys,values)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
return new ResultMessageVO(Msg.FAIL,"操作失败,请稍后再试");
}
@Override
public ResultMessageVO refuseApplication(String hotelId) {
String keys[] = {"state"};
Object values[] = {HotelState.REFUSED};
if(hotelDataService.updateHotelById(hotelId,keys,values)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
return new ResultMessageVO(Msg.FAIL,"操作失败,请稍后再试");
}
@Override
public ResultMessageVO settleAccounts(String hotelId, double amount) {
synchronized (this.getClass()){
AccountEntity accountEntity = accountDataService.getAccountById(AccountConfig.HEADQUARTERS_ACCOUNT);
AccountEntity accountEntity1 = accountDataService.getAccountById(hotelId);
double balance = accountEntity.getBalance()-amount;
if(balance<0){
return new ResultMessageVO(Msg.FAIL,"余额不足,结算失败");
}
String keys[] = {"balance"};
Object[] values1 = {balance};
Object[] values2 = {accountEntity1.getBalance()+amount};
if(accountDataService.updateAccountById(AccountConfig.HEADQUARTERS_ACCOUNT,keys,values1)&&accountDataService.updateAccountById(hotelId,keys,values2)){
return new ResultMessageVO(Msg.SUCCESS,"");
}
}
return new ResultMessageVO(Msg.FAIL,"操作失败,请稍后再试");
}
@Override
public List<HotelFinanceVO> getAllHotelFinanceInfo() {
List<AccountModel> models = accountDataService.getAllAccountInfo();
List<HotelFinanceVO> vos = new ArrayList<>();
for (AccountModel model:models){
vos.add(new HotelFinanceVO(model.getHotelName(),model.getBalance()));
}
return vos;
}
}
| 5,279 | 0.674068 | 0.670786 | 139 | 36.258991 | 30.920259 | 162 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.784173 | false | false | 15 |
fb24e051d4442d6071d0740835592ab7a6487286 | 29,772,713,349,294 | a731e72d4d5779af7a9ea87dad76a63a93ecec8f | /api_parent/api_accounting/src/main/java/org/modules/inventory/InventoryApiImpl.java | 167170a540d458342c88cdcf8cbef7fd34b33db3 | []
| no_license | rmt2bsc/business_domain_api | https://github.com/rmt2bsc/business_domain_api | 63d52901ef6a7ce87ec915f286b884019c605458 | 851512ae8dc8bb5cf4822c2628edb3e6e9a88ef4 | refs/heads/master | 2023-07-03T13:14:47.198000 | 2022-09-14T07:25:18 | 2022-09-14T07:25:18 | 77,566,407 | 0 | 0 | null | false | 2022-09-10T20:46:31 | 2016-12-28T22:59:02 | 2021-09-04T20:06:26 | 2022-09-10T20:46:29 | 125,813 | 0 | 0 | 1 | Java | false | false | package org.modules.inventory;
import java.util.List;
import org.apache.log4j.Logger;
import org.dao.AccountingSqlConst;
import org.dao.inventory.InventoryDao;
import org.dao.inventory.InventoryDaoException;
import org.dao.inventory.InventoryDaoFactory;
import org.dao.mapping.orm.rmt2.ItemMaster;
import org.dao.mapping.orm.rmt2.ItemMasterStatus;
import org.dao.mapping.orm.rmt2.ItemMasterStatusHist;
import org.dao.mapping.orm.rmt2.ItemMasterType;
import org.dao.mapping.orm.rmt2.VwItemAssociations;
import org.dao.mapping.orm.rmt2.VwVendorItems;
import org.dto.ItemAssociationDto;
import org.dto.ItemMasterDto;
import org.dto.ItemMasterStatusDto;
import org.dto.ItemMasterStatusHistDto;
import org.dto.ItemMasterTypeDto;
import org.dto.VendorItemDto;
import org.dto.adapter.orm.inventory.Rmt2InventoryDtoFactory;
import org.modules.subsidiary.CreditorApi;
import org.modules.subsidiary.CreditorApiException;
import org.modules.subsidiary.SubsidiaryApiFactory;
import com.InvalidDataException;
import com.RMT2Base;
import com.RMT2Exception;
import com.api.foundation.AbstractTransactionApiImpl;
import com.api.persistence.DaoClient;
import com.api.util.RMT2String;
import com.api.util.RMT2String2;
import com.api.util.assistants.Verifier;
import com.api.util.assistants.VerifyException;
/**
* Implements the {@link InventoryApi} interface for maintaining inventory items.
*
* @author roy terrell
*
*/
class InventoryApiImpl extends AbstractTransactionApiImpl implements InventoryApi {
private static final Logger logger = Logger.getLogger(InventoryApiImpl.class);
private InventoryDaoFactory factory;
private InventoryDao dao;
/**
* Creates a InventoryApiImpl object in which the configuration is
* identified by the name of a given application.
*
* @param appName
*/
public InventoryApiImpl(String appName) {
super();
this.dao = this.factory.createRmt2OrmDao(appName);
this.setSharedDao(this.dao);
this.dao.setDaoUser(this.apiUser);
}
/**
* Creates an InventoryApiImpl initialized with a shared connection,
* <i>dao</i>. object.
*
* @param connection
*/
protected InventoryApiImpl(DaoClient connection) {
super(connection);
this.dao = this.factory.createRmt2OrmDao(this.getSharedDao());
this.dao.setDaoUser(connection.getDaoUser());
}
/*
* (non-Javadoc)
*
* @see com.RMT2Base#init()
*/
@Override
public void init() {
super.init();
this.factory = new InventoryDaoFactory();
}
@Override
public List<ItemMasterDto> getItem(ItemMasterDto criteria) throws InventoryApiException {
try {
Verifier.verifyNotNull(criteria);
}
catch (VerifyException e) {
throw new InvalidDataException("Criteria object is required", e);
}
List<ItemMasterDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item(s)";
throw new InventoryApiException(this.msg, e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemById(int)
*/
@Override
public ItemMasterDto getItemById(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory.createItemMasterInstance(im);
criteria.setItemId(itemId);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item by item id: " + itemId;
throw new InventoryApiException(this.msg, e);
}
if (results == null) {
msgBuf.append("Inventory item, ");
msgBuf.append(itemId);
msgBuf.append(", was not found ");
logger.warn(msgBuf);
return null;
}
if (results.size() > 1) {
msgBuf.append("Too many inventory items returned for item id, ");
msgBuf.append(itemId);
msgBuf.append(" Count: ");
msgBuf.append(results.size());
logger.error(msgBuf);
throw new InventoryApiException(msgBuf.toString());
}
msgBuf.append("Inventory object was retrieved for item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results.get(0);
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemByType(int)
*/
@Override
public List<ItemMasterDto> getItemByType(Integer itemTypeId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item type id is required", e);
}
try {
Verifier.verifyPositive(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item type id must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setItemTypeId(itemTypeId);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by item type id: "
+ itemTypeId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by item type id, ");
msgBuf.append(itemTypeId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by item type id, ");
msgBuf.append(itemTypeId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemByVendorId(int)
*/
@Override
public List<ItemMasterDto> getItemByVendorId(Integer vendorId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setVendorId(vendorId);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by vendor id: "
+ vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by vendor id, ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by vendor id, ");
msgBuf.append(vendorId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#getItemByVendorItemNo(java.lang.String
* )
*/
@Override
public List<ItemMasterDto> getItemByVendorItemNo(String vendItemNo)
throws InventoryApiException {
if (RMT2String2.isEmpty(vendItemNo)) {
throw new InvalidDataException("Vendor Item No. is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setVendorItemNo(vendItemNo);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by vendor item number: "
+ vendItemNo;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by vendor item number, ");
msgBuf.append(vendItemNo);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by vendor item number, ");
msgBuf.append(vendItemNo);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#getItemBySerialNo(java.lang.String)
*/
@Override
public List<ItemMasterDto> getItemBySerialNo(String serialNo) throws InventoryApiException {
if (RMT2String2.isEmpty(serialNo)) {
throw new InvalidDataException("Item Serial No. is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setItemSerialNo(serialNo);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by vendor item number: "
+ serialNo;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by serial number, ");
msgBuf.append(serialNo);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by serial number, ");
msgBuf.append(serialNo);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItem(java.lang.String)
*/
@Override
public List<ItemMasterDto> getItem(String criteria) throws InventoryApiException {
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) using customer SQL predicate: "
+ criteria;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found using customer SQL predicate, ");
msgBuf.append(criteria);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved using customer SQL predicate, ");
msgBuf.append(criteria);
logger.info(msgBuf);
return results;
}
@Override
public List<ItemMasterTypeDto> getItemType(ItemMasterTypeDto criteria)
throws InventoryApiException {
dao.setDaoUser(this.apiUser);
List<ItemMasterTypeDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item type(s)";
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemTypeById(int)
*/
@Override
public ItemMasterTypeDto getItemTypeById(Integer itemTypeId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item type Id is required", e);
}
try {
Verifier.verifyPositive(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Type Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterTypeDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterType imt = null;
ItemMasterTypeDto criteria = Rmt2InventoryDtoFactory
.createItemTypeInstance(imt);
criteria.setItemTypeId(itemTypeId);
results = this.getItemType(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item type by item type id: "
+ itemTypeId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item type, ");
msgBuf.append(itemTypeId);
msgBuf.append(", was not found ");
logger.warn(msgBuf);
return null;
}
if (results.size() > 1) {
msgBuf.append("Too many inventory items returned for item type id, ");
msgBuf.append(itemTypeId);
msgBuf.append(" Count: ");
msgBuf.append(results.size());
logger.error(msgBuf);
throw new InventoryApiException(msgBuf.toString());
}
msgBuf.append("Inventory item type object was retrieved for item type id, ");
msgBuf.append(itemTypeId);
logger.info(msgBuf);
return results.get(0);
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemTypes(java.lang.String)
*/
@Override
public List<ItemMasterTypeDto> getItemTypes(String itemName) throws InventoryApiException {
if (RMT2String2.isEmpty(itemName)) {
throw new InvalidDataException("Item Type Name is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterTypeDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterType imt = null;
ItemMasterTypeDto criteria = Rmt2InventoryDtoFactory
.createItemTypeInstance(imt);
criteria.setItemTypeDescription(itemName);
results = this.getItemType(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item type(s) by item name: "
+ itemName;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item types were not found by item name, ");
msgBuf.append(itemName);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item type object(s) were retrieved by item name, ");
msgBuf.append(itemName);
logger.info(msgBuf);
return results;
}
@Override
public List<ItemMasterStatusDto> getItemStatus(ItemMasterStatusDto criteria)
throws InventoryApiException {
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item status(es)";
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemStatus(java.lang.String)
*/
@Override
public List<ItemMasterStatusDto> getItemStatus(String statusName) throws InventoryApiException {
if (RMT2String2.isEmpty(statusName)) {
throw new InvalidDataException("Item Status Name is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterStatus imt = null;
ItemMasterStatusDto criteria = Rmt2InventoryDtoFactory
.createItemStatusInstance(imt);
criteria.setEntityName(statusName);
results = this.getItemStatus(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item status(es) by status name: "
+ statusName;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item status were not found by item name, ");
msgBuf.append(statusName);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item status object(s) were retrieved by item name, ");
msgBuf.append(statusName);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemStatusById(int)
*/
@Override
public ItemMasterStatusDto getItemStatusById(Integer itemStatusId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemStatusId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Status Id is required", e);
}
try {
Verifier.verifyPositive(itemStatusId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Status Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterStatus imt = null;
ItemMasterStatusDto criteria = Rmt2InventoryDtoFactory
.createItemStatusInstance(imt);
criteria.setEntityId(itemStatusId);
results = this.getItemStatus(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item status by item status id: "
+ itemStatusId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item status, ");
msgBuf.append(itemStatusId);
msgBuf.append(", was not found ");
logger.warn(msgBuf);
return null;
}
if (results.size() > 1) {
msgBuf.append("Too many inventory item status returned for item status id, ");
msgBuf.append(itemStatusId);
msgBuf.append(" Count: ");
msgBuf.append(results.size());
logger.error(msgBuf);
throw new InventoryApiException(msgBuf.toString());
}
msgBuf.append("Inventory item status object was retrieved for item status id, ");
msgBuf.append(itemStatusId);
logger.info(msgBuf);
return results.get(0);
}
@Override
public List<ItemMasterStatusHistDto> getItemStatusHist(ItemMasterStatusHistDto criteria)
throws InventoryApiException {
if (criteria == null) {
throw new InvalidDataException("Criteria object is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusHistDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item status history";
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemStatusHistByItemId(int)
*/
@Override
public List<ItemMasterStatusHistDto> getItemStatusHistByItemId(Integer itemId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusHistDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterStatusHist imt = null;
ItemMasterStatusHistDto criteria = Rmt2InventoryDtoFactory
.createItemStatusHistoryInstance(imt);
criteria.setItemId(itemId);
results = this.getItemStatusHist(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item status history by item id: "
+ itemId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item status history was not found by item id, ");
msgBuf.append(itemId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item status history object(s) were retrieved by item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getCurrentItemStatusHist(int)
*/
@Override
public ItemMasterStatusHistDto getCurrentItemStatusHist(Integer itemId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
if (itemId <= 0) {
throw new InvalidDataException("Item Id must be greater than zero");
}
dao.setDaoUser(this.apiUser);
ItemMasterStatusHistDto results;
StringBuffer msgBuf = new StringBuffer();
try {
results = dao.fetchCurrentItemStatusHistory(itemId);
} catch (Exception e) {
this.msg = "Unable to retrieve current inventory item status history by item id: "
+ itemId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Current inventory item status history was not found by item id, ");
msgBuf.append(itemId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(1);
msgBuf.append(" Current inventory item status history object(s) were retrieved by item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getVendorItem(int, int)
*/
@Override
public List<VendorItemDto> getVendorItem(Integer vendorId, Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor/Creditor Id is required", e);
}
dao.setDaoUser(this.apiUser);
List<VendorItemDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
VwVendorItems imt = null;
VendorItemDto criteria = Rmt2InventoryDtoFactory.createVendorItemInstance(imt);
criteria.setItemId(itemId);
criteria.setVendorId(vendorId);
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve vendor item by item id and vendor id: "
+ itemId + " " + vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null && itemId != null) {
msgBuf.append(" inventory vendor item was not found by item id and vendor id, ");
msgBuf.append(itemId);
msgBuf.append(" ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Vendor inventory item object(s) were retrieved by vendor id and item id, ");
msgBuf.append(vendorId);
msgBuf.append(" ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getVendorAssignItems(int)
*/
@Override
public List<VendorItemDto> getVendorAssignItems(Integer vendorId) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor/Creditor Id is required to fetch assigned items", e);
}
dao.setDaoUser(this.apiUser);
List<VendorItemDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
VwVendorItems imt = null;
VendorItemDto criteria = Rmt2InventoryDtoFactory.createVendorItemInstance(imt);
criteria.setVendorId(vendorId);
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve vendor associated inventory items by vendor id: " + vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Vendor associated inventory items were not found by vendor id, ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Vendor associated inventory item object(s) were retrieved by vendor id, ");
msgBuf.append(vendorId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getVendorUnassignItems(int)
*/
@Override
public List<ItemMasterDto> getVendorUnassignItems(Integer vendorId) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor/Creditor Id is required to fetch unassigned items", e);
}
String criteria = RMT2String.replace(
AccountingSqlConst.SQL_CRTIERIA_VENDOR_UNASSIGNED_ITEM,
String.valueOf(vendorId), "$1");
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve unassociated vendor inventory items by vendor id: "
+ vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Vendor associated inventory items were not found by vendor id, ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Vendor associated inventory item object(s) were retrieved by vendor id, ");
msgBuf.append(vendorId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemAssociations(int)
*/
@Override
public List<ItemAssociationDto> getItemAssociations(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("A valid item id must provided in order to perform an item assoication query", e);
}
// InventoryDao dao = this.factory.createRmt2OrmDao();
dao.setDaoUser(this.apiUser);
List<ItemAssociationDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
VwItemAssociations assoc = null;
ItemAssociationDto criteria = Rmt2InventoryDtoFactory
.createItemAssociationInstance(assoc);
criteria.setItemId(itemId);
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve item associations for item id: " + itemId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Item associations were not found by item id, ");
msgBuf.append(itemId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Item association object(s) were retrieved by item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#updateInventoryItem(org.dto.ItemMasterDto
* )
*/
@Override
public int updateItemMaster(ItemMasterDto item) throws InventoryApiException {
try {
Verifier.verifyNotNull(item);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item master object is required", e);
}
dao.setDaoUser(this.apiUser);
this.computeItemRetail(item);
boolean isNewItem = (item.getItemId() == 0);
ItemMaster newItem = null;
ItemMasterDto imDto = Rmt2InventoryDtoFactory.createItemMasterInstance(newItem);
// Get old version of item record and apply changes
if (!isNewItem) {
imDto = this.getItemById(item.getItemId());
if (imDto == null) {
this.msg = "Inventory item update error: Item id, "
+ item.getItemId() + ", does not exist in the system";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
}
// Capture the original override flag
int oldOverrideRetailFlag = imDto.getOverrideRetail();
// add delta to old inventory item master version
imDto.setItemTypeId(item.getItemTypeId());
imDto.setVendorId(item.getVendorId());
imDto.setItemName(item.getItemName());
imDto.setVendorItemNo(item.getVendorItemNo());
imDto.setItemSerialNo(item.getItemSerialNo());
imDto.setQtyOnHand(item.getQtyOnHand());
imDto.setUnitCost(item.getUnitCost());
imDto.setMarkup(item.getMarkup());
imDto.setRetailPrice(item.getRetailPrice());
imDto.setOverrideRetail(item.getOverrideRetail());
imDto.setActive(item.getActive());
// Perform updates
int rc;
try {
// Update Item master
rc = dao.maintain(imDto);
// Update statuses
ItemMasterStatusHistDto imsh = null;
if (isNewItem) {
// Indicate that item is in service
this.changeItemStatus(imDto, InventoryConst.ITEM_STATUS_INSRVC);
item.setItemId(rc);
}
else {
// Get item master's current status
imsh = dao.fetchCurrentItemStatusHistory(imDto.getItemId());
if (imsh == null) {
this.msg = "Unable to find status history for inventory item id, "
+ imDto.getItemId() + ". History not available.";
logger.error(this.msg);
throw new RMT2Exception(this.msg);
}
// Change the most recent item status, which should be
// 'Replaced'
imsh = this.changeItemStatus(imDto, InventoryConst.ITEM_STATUS_REPLACE);
// User has requested system to activate vendor item override.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_YES
&& oldOverrideRetailFlag == InventoryConst.ITEM_OVERRIDE_NO) {
imsh = this.changeItemStatus(imDto,
InventoryConst.ITEM_STATUS_OVERRIDE_ACTIVE);
}
// User has requested system to deactivate vendor item override.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_NO
&& oldOverrideRetailFlag == InventoryConst.ITEM_OVERRIDE_YES) {
imsh = this.changeItemStatus(imDto,
InventoryConst.ITEM_STATUS_OVERRIDE_INACTIVE);
}
}
// Place Item in "Available" if quantity is greater than zero.
// Otherwise, 'Out of Stock'.
int itemStatusId = imDto.getQtyOnHand() <= 0 ? InventoryConst.ITEM_STATUS_OUTSTOCK
: InventoryConst.ITEM_STATUS_AVAIL;
imsh = this.changeItemStatus(imDto, itemStatusId);
// If item is no longer active, then put in out servive status
if (!isNewItem) {
if (imDto.getActive() == 0) {
imsh = this.changeItemStatus(imDto,
InventoryConst.ITEM_STATUS_OUTSRVC);
}
}
return rc;
} catch (Exception e) {
this.msg = "Unable to process inventory item master updates.";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Validates an inventory item master object.
*
* The following validations must be met:
* <ul>
* <li>Item object cannot be null</li>
* <li>The vendor id is not required, but if its id is greateer than zero,
* then it must exist in the database.</li>
* <li>Item Description must no be null</li>
* <li>Item Type must be valid</li>
* <li>Item Markup must be greater than zero</li>
* <li>Service item types must have a quantity on hand equal to one, and a
* mark value equal to one.</li>
* </ul>
*
* @param item
* an instance of {@link ItemMasterDto}
* @throws InventoryException
*/
protected void validateItemMaster(ItemMasterDto item) throws InventoryApiException {
if (item == null) {
this.msg = "Item Master DTO cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Validate Creditor
SubsidiaryApiFactory f = new SubsidiaryApiFactory();
CreditorApi api = f.createCreditorApi();
if (item.getVendorId() > 0) {
Object cred;
try {
cred = api.getByCreditorId(item.getVendorId());
} catch (CreditorApiException e) {
throw new InventoryApiException(e);
} finally {
api = null;
}
if (cred == null) {
this.msg = "The Vendor associated with the inventory item master does not exist in the system: "
+ item.getVendorId();
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
}
// Common validations
if (item.getItemName() == null || item.getItemName().equals("")) {
this.msg = "Item Name must contain a value and cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
if (item.getItemTypeId() <= 0) {
this.msg = "Item Type is invalid";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Mark Up must be greater than zero and cannot be null
if (item.getMarkup() <= 0) {
this.msg = "Mark Up must be greater than zero and cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
/*
* Not sure if unit cost should be required to have a value greater than
* zero. if (itemBase.getUnitCost() <= 0) { throw new
* ItemMasterException(this.dbo, 419, null); }
*/
// Service item validations
if (item.getItemTypeId() == InventoryConst.ITEM_TYPE_SRVC) {
if (item.getVendorId() > 0) {
this.msg = "Service items cannot be assoicated with a Vendor";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Quantity on Hand must be equal to 1 for service items
if (item.getQtyOnHand() != 1) {
this.msg = "Quantity on Hand must be equal to 1 for service items";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Mark Up must be equal to 1
if (item.getMarkup() != 1) {
this.msg = "Mark Up must be equal to 1";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
}
}
/**
* Calculates the retail price of an item based on its item type value
* (Merchandise or Service). At this point all data components used for
* calculating retail should have been verified. The retail price will be
* determined in one of two ways: 1) as is when the user request that retail
* price calculations be ignored and just accept the user's input or 2)
* apply the formula retail price = unit cost * mark up.
*
* @param item
* an instance of {@link ItemMasterDto}
* @throws InventoryException
*/
private void computeItemRetail(ItemMasterDto item) throws InventoryApiException {
double retailPrice = 0;
// Determine if user requests us to override retail calculations.
if (item.getOverrideRetail() == 0) {
retailPrice = item.getUnitCost() * item.getMarkup();
item.setRetailPrice(retailPrice);
}
return;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#updateVendorItem(org.dto.VendorItemDto
* )
*/
@Override
public int updateVendorItem(VendorItemDto item) throws InventoryApiException {
this.validateVendorItem(item);
// Update Vendor Item
dao.setDaoUser(this.apiUser);
int rc;
try {
List<VendorItemDto> results = this.getVendorItem(item.getVendorId(), item.getItemId());
// Determine if we are creating a new or modifying an existing vendor item
boolean newRec = (results == null || results.size() == 0 ? true : false);
rc = dao.maintain(item, newRec);
return rc;
} catch (Exception e) {
this.msg = "Unable to process inventory vendor item updates.";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Validate a vendor item object.
*
* The following validations must be met:
* <ul>
* <li>The vendor must exist in the database.</li>
* <li>The vendor id is required and must be greater than zero.</li>
* <li>The Vendor Item Number cannot be null</li>
* <li>The Item Serial Number cannot be null</li>
* </ul>
*
* @param vi
* The {@link VendorItemDto} object
* @throws InventoryException
*/
protected void validateVendorItem(VendorItemDto vi) throws InventoryApiException {
dao.setDaoUser(this.apiUser);
try {
Verifier.verifyNotNull(vi);
}
catch (VerifyException e) {
this.msg = "Vendor Item object cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
Verifier.verifyPositive(vi.getVendorId());
}
catch (VerifyException e) {
this.msg = "The vendor item\'s Vendor Id is invalid: " + vi.getVendorId();
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
Verifier.verifyNotNull(vi.getVendorItemNo());
}
catch (VerifyException e) {
this.msg = "New and existing merchandise items must have the vendor's version of an item number or part number";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
Verifier.verifyNotNull(vi.getItemSerialNo());
}
catch (VerifyException e) {
this.msg = "Merchandise items must have a vendor serial number";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Validate Creditor
CreditorApi api = SubsidiaryApiFactory.createCreditorApi(this.dao);
Object cred;
try {
cred = api.getByCreditorId(vi.getVendorId());
} catch (CreditorApiException e) {
throw new InventoryApiException(e);
} finally {
api = null;
}
if (cred == null) {
this.msg = "The Vendor associated with the inventory vendor item does not exist in the system: "
+ vi.getVendorId();
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
return;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#deleteItemMaster(int)
*/
@Override
public int deleteItemMaster(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
// Determine if item is tied to one or more sales orders and/or purchase
// orders.
List<ItemAssociationDto> associations = this.getItemAssociations(itemId);
if (associations != null && associations.size() > 0) {
this.msg = "Invenoty item master , "
+ itemId
+ ", cannot be deleted since it is associated with one or more sales orders and/or purchase orders";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// InventoryDao dao = this.factory.createRmt2OrmDao();
dao.setDaoUser(this.apiUser);
int rc;
try {
// dao.beginTrans();
// Remove all items from item master status history
ItemMasterStatusHistDto imshCriteria = Rmt2InventoryDtoFactory
.createItemStatusHistoryInstance((ItemMasterStatusHist) null);
imshCriteria.setItemId(itemId);
rc = dao.delete(imshCriteria);
this.msg = "Total item status history entries removed for item id, "
+ itemId + ": " + rc;
logger.info(this.msg);
// Remove item from inventory.
ItemMaster nullBean = null;
ItemMasterDto imCriteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(nullBean);
imCriteria.setItemId(itemId);
rc = dao.delete(imCriteria);
this.msg = "Inventory item id, " + itemId
+ ", was successfully deleted from the system";
logger.info(this.msg);
// Commit transaction
// dao.commitTrans();
return RMT2Base.SUCCESS;
} catch (Exception e) {
// dao.rollbackTrans();
this.msg = "Unable to delete inventory item due to database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#pushInventory(int, int)
*/
@Override
public double pushInventory(Integer itemId, Integer qty) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
try {
Verifier.verifyNotNull(qty);
}
catch (VerifyException e) {
throw new InvalidDataException("Quantity is required", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...invenory was not increased";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
int origItemQty = im.getQtyOnHand();
int changeItemQty = origItemQty + qty;
double changeValue = im.getUnitCost() * changeItemQty;
im.setQtyOnHand(changeItemQty);
try {
// this.updateItemMaster(im, null);
this.updateItemMaster(im);
} catch (Exception e) {
this.msg = "Unable to push inventory for item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
return changeValue;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#pullInventory(int, int)
*/
@Override
public double pullInventory(Integer itemId, Integer qty) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
try {
Verifier.verifyNotNull(qty);
}
catch (VerifyException e) {
throw new InvalidDataException("Quantity is required", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...invenory was not decreased";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
int origItemQty = im.getQtyOnHand();
int changeItemQty = origItemQty - qty;
double changeValue = im.getUnitCost() * changeItemQty;
im.setQtyOnHand(changeItemQty);
try {
// this.updateItemMaster(im, null);
this.updateItemMaster(im);
} catch (Exception e) {
this.msg = "Unable to pull inventory for item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
return changeValue;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#deactivateItemMaster(int)
*/
@Override
public int deactivateItemMaster(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id must be greater than zero", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...item was not deactivated";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Throw exception if alread deactivated.
if (im.getActive() == 0) {
throw new InventoryApiException("Inventory item, " + itemId + ", is already deactivated");
}
dao.setDaoUser(this.apiUser);
try {
// dao.beginTrans();
// Set item inactive
im.setActive(InventoryConst.ITEM_ACTIVE_NO);
// Update Item master
dao.maintain(im);
// Render item out of service
this.changeItemStatus(im, InventoryConst.ITEM_STATUS_OUTSRVC);
// dao.commitTrans();
return RMT2Base.SUCCESS;
} catch (Exception e) {
// dao.rollbackTrans();
this.msg = "Unable to deactivate item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#activateItemMaster(int)
*/
@Override
public int activateItemMaster(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id must be greater than zero", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...item was not activated";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Throw exception if alread activated.
if (im.getActive() == 1) {
throw new InventoryApiException("Inventory item, " + itemId + ", is already activated");
}
dao.setDaoUser(this.apiUser);
try {
// Set item active
im.setActive(InventoryConst.ITEM_ACTIVE_YES);
// Update Item master
dao.maintain(im);
// Render item out of service
this.changeItemStatus(im, InventoryConst.ITEM_STATUS_INSRVC);
// Determine if item has quantity to sold or is out of stock.
int itemStatusId = im.getQtyOnHand() <= 0 ? InventoryConst.ITEM_STATUS_OUTSTOCK
: InventoryConst.ITEM_STATUS_AVAIL;
this.changeItemStatus(im, itemStatusId);
return RMT2Base.SUCCESS;
} catch (Exception e) {
this.msg = "Unable to activate item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Associates one or more inventory items with a vendor.
* <p>
* This method iterates through the list of inventory item id's contained in
* <i>items</i> and assigns each one to a vendor identified as
* <i>vendorId</i>. If an error is encountered during an iteration, the
* entire process is aborted and all previous successful transactions are
* rolled back.
*
* @param vendorId
* The id of the vendor
* @param items
* A list inventory item id's
* @return The number of items assigned to the vendor.
* @throws InventoryException
* An inventory item in <i>items</i> does not exist in the
* system or database error trying to assoicate the vendor with
* an inventory item.
*/
@Override
public int assignVendorItems(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of Inventory Item Id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
ItemMasterDto imDto = this.getItemById(items[ndx]);
if (imDto == null) {
this.msg = "Item id is not found in the database: " + items[ndx];
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
VendorItemDto viDto = Rmt2InventoryDtoFactory.createVendorItemInstance(vendorId, imDto);
try {
// count += this.updateVendorItem(viDto);
count += dao.maintain(viDto, true);
} catch (Exception e) {
this.msg = "Error creating vendor id [" + vendorId
+ "] and item id {" + imDto.getItemId()
+ "] associtation";
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
// dao.commitTrans();
return count;
} catch (Exception e) {
// dao.rollbackTrans();
this.msg = "Unable to persist vendor id/item master association to table, vendor_items. The assignment of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Disassociates one or more inventory items from a vendor.
* <p>
* This method iterates through the list of inventory item id's contained in
* <i>items</i> and removes each one from the vendor identified as
* <i>vendorId</i>. If an error is encountered during an iteration, the
* entire process is aborted and all previous successful transactions are
* rolled back.
*
* @param vendorId
* The id of the vendor
* @param items
* A list inventory item id's to remove.
* @return The number of items removed from the vendor.
* @throws InventoryException
* An inventory item in <i>items</i> does not exist in the
* system or database error when disassociating the vendor
* from an inventory item.
*/
@Override
public int removeVendorItems(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of vendor item id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
VendorItemDto viDto = Rmt2InventoryDtoFactory.createVendorItemInstance(null);
viDto.setVendorId(vendorId);
viDto.setItemId(items[ndx]);
try {
count += dao.delete(viDto);
} catch (Exception e) {
this.msg = "Error deleting vendor id [" + vendorId
+ "] and item id {" + items[ndx] + "] associtation";
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
return count;
} catch (Exception e) {
this.msg = "Unable to delete vendor id/item master association from table, vendor_items. The deletion of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Changes the override flag to true for one or more of a vendor's items.
* <p>
* Activates a vendor-item override for all item id's stored in items
* collection. This method enables a vendor-item override targeting the
* inventory item, itemId. Also, the creditor id of the inventory item
* master is set to the vendor's id. An override instructs the system to
* obtain pricing information for an inventory item from the vendor_items
* table instead of the item_master table .
*
* @param vendorId
* The id of the vendor that will be associated with each item
* id.
* @param items
* Collection containing one or more item_master id's to
* override.
* @return The total number of rows effected by the database transaction.
* @throws ItemMasterException
*/
@Override
public int addInventoryOverride(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of Inventory Item Id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
ItemMasterDto imDto = this.getItemById(items[ndx]);
if (imDto == null) {
this.msg = "Item id is not found in the database: "
+ items[ndx];
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Do not attempt to update an item that is currently overridden.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_YES) {
continue;
}
imDto.setVendorId(vendorId);
imDto.setOverrideRetail(InventoryConst.ITEM_OVERRIDE_YES);
// Ensure that item's quantity on hand is not effected after
// updates are applied to the database.
imDto.setQtyOnHand(0);
try {
count += dao.maintain(imDto);
} catch (Exception e) {
this.msg = "Error changing override status of inventory item id, "
+ imDto.getItemId();
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
return count;
} catch (Exception e) {
this.msg = "Unable to persist vendor id/item master association to table, vendor_items. The assignment of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Changes the override flag to false for one or more of a vendor's item.
* <p>
* This method deactivates a vendor-item override targeting the inventory
* item, itemId. Also, the creditor id of the inventory item master is set
* to null. An override instructs the system to obtain pricing information
* for an inventory item from the vendor_items table instead of the
* item_master table .
*
* @param vendorId
* The id of the vendor that will be disassoicated with the item
* id.
* @param items
* An array of item id's to change
* @return The total number of items effected by the database transaction. .
* @throws ItemMasterException
*/
@Override
public int removeInventoryOverride(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of Inventory Item Id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
ItemMasterDto imDto = this.getItemById(items[ndx]);
if (imDto == null) {
this.msg = "Item id is not found in the database: "
+ items[ndx];
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Do not attempt to update an item that is currently overridden.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_NO) {
continue;
}
imDto.setVendorId(0);
imDto.setOverrideRetail(InventoryConst.ITEM_OVERRIDE_NO);
// Ensure that item's quantity on hand is not effected after
// updates are applied to the database.
imDto.setQtyOnHand(0);
try {
count += dao.maintain(imDto);
} catch (Exception e) {
this.msg = "Error changing override status of inventory item id, "
+ imDto.getItemId();
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
return count;
} catch (Exception e) {
this.msg = "Unable to persist vendor id/item master association to table, vendor_items. The assignment of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Changes the status of an inventory item which the database transaction
* object is supplied by the user.
*
* @param dao
* the inventory database transaction object
* @param item
* An instance of {@link ItemMasterDto} which is the item master
* object targeted for the satus change.
* @param newItemStatusId
* The id of the item status.
* @return The {@link ItemMasterStatusHistDto} object which represents
* newItemStatusId
* @throws InventoryException
* If newItemStatusId is out of sequence, if a database error
* occurs, or a system error occurs.
*/
protected ItemMasterStatusHistDto changeItemStatus(ItemMasterDto item, int newItemStatusId)
throws InventoryApiException {
ItemMasterStatusHistDto imsh = null;
dao.setDaoUser(this.apiUser);
// Validate newItemStatusId
List<ItemMasterStatusDto> imsList;
try {
ItemMasterStatusDto imsCriteria = Rmt2InventoryDtoFactory.createItemStatusInstance(null);
imsCriteria.setEntityId(newItemStatusId);
imsList = dao.fetch(imsCriteria);
} catch (InventoryDaoException e) {
this.msg = "Problem querying for new Item status";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
if (imsList == null) {
this.msg = "New item status id does not exist in the system: "
+ newItemStatusId;
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
if (imsList.size() > 1) {
this.msg = "New item status id query return multiple items in the result set. Should only be one element";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
// End current item status
imsh = dao.fetchCurrentItemStatusHistory(item.getItemId());
if (imsh != null) {
dao.maintain(imsh);
}
// Create new item status
imsh = Rmt2InventoryDtoFactory.createItemStatusHistoryInstance((ItemMasterStatusHist) null);
imsh.setItemId(item.getItemId());
imsh.setItemStatusId(newItemStatusId);
imsh.setUnitCost(item.getUnitCost());
imsh.setMarkup(item.getMarkup());
dao.maintain(imsh);
return imsh;
} catch (Exception e) {
this.msg = "Inventory item status history change failed due to a Database or System error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
}
| UTF-8 | Java | 69,508 | java | InventoryApiImpl.java | Java | [
{
"context": "ce for maintaining inventory items.\n * \n * @author roy terrell\n * \n */\nclass InventoryApiImpl extends AbstractTr",
"end": 1405,
"score": 0.9978720545768738,
"start": 1394,
"tag": "NAME",
"value": "roy terrell"
}
]
| null | []
| package org.modules.inventory;
import java.util.List;
import org.apache.log4j.Logger;
import org.dao.AccountingSqlConst;
import org.dao.inventory.InventoryDao;
import org.dao.inventory.InventoryDaoException;
import org.dao.inventory.InventoryDaoFactory;
import org.dao.mapping.orm.rmt2.ItemMaster;
import org.dao.mapping.orm.rmt2.ItemMasterStatus;
import org.dao.mapping.orm.rmt2.ItemMasterStatusHist;
import org.dao.mapping.orm.rmt2.ItemMasterType;
import org.dao.mapping.orm.rmt2.VwItemAssociations;
import org.dao.mapping.orm.rmt2.VwVendorItems;
import org.dto.ItemAssociationDto;
import org.dto.ItemMasterDto;
import org.dto.ItemMasterStatusDto;
import org.dto.ItemMasterStatusHistDto;
import org.dto.ItemMasterTypeDto;
import org.dto.VendorItemDto;
import org.dto.adapter.orm.inventory.Rmt2InventoryDtoFactory;
import org.modules.subsidiary.CreditorApi;
import org.modules.subsidiary.CreditorApiException;
import org.modules.subsidiary.SubsidiaryApiFactory;
import com.InvalidDataException;
import com.RMT2Base;
import com.RMT2Exception;
import com.api.foundation.AbstractTransactionApiImpl;
import com.api.persistence.DaoClient;
import com.api.util.RMT2String;
import com.api.util.RMT2String2;
import com.api.util.assistants.Verifier;
import com.api.util.assistants.VerifyException;
/**
* Implements the {@link InventoryApi} interface for maintaining inventory items.
*
* @author <NAME>
*
*/
class InventoryApiImpl extends AbstractTransactionApiImpl implements InventoryApi {
private static final Logger logger = Logger.getLogger(InventoryApiImpl.class);
private InventoryDaoFactory factory;
private InventoryDao dao;
/**
* Creates a InventoryApiImpl object in which the configuration is
* identified by the name of a given application.
*
* @param appName
*/
public InventoryApiImpl(String appName) {
super();
this.dao = this.factory.createRmt2OrmDao(appName);
this.setSharedDao(this.dao);
this.dao.setDaoUser(this.apiUser);
}
/**
* Creates an InventoryApiImpl initialized with a shared connection,
* <i>dao</i>. object.
*
* @param connection
*/
protected InventoryApiImpl(DaoClient connection) {
super(connection);
this.dao = this.factory.createRmt2OrmDao(this.getSharedDao());
this.dao.setDaoUser(connection.getDaoUser());
}
/*
* (non-Javadoc)
*
* @see com.RMT2Base#init()
*/
@Override
public void init() {
super.init();
this.factory = new InventoryDaoFactory();
}
@Override
public List<ItemMasterDto> getItem(ItemMasterDto criteria) throws InventoryApiException {
try {
Verifier.verifyNotNull(criteria);
}
catch (VerifyException e) {
throw new InvalidDataException("Criteria object is required", e);
}
List<ItemMasterDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item(s)";
throw new InventoryApiException(this.msg, e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemById(int)
*/
@Override
public ItemMasterDto getItemById(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory.createItemMasterInstance(im);
criteria.setItemId(itemId);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item by item id: " + itemId;
throw new InventoryApiException(this.msg, e);
}
if (results == null) {
msgBuf.append("Inventory item, ");
msgBuf.append(itemId);
msgBuf.append(", was not found ");
logger.warn(msgBuf);
return null;
}
if (results.size() > 1) {
msgBuf.append("Too many inventory items returned for item id, ");
msgBuf.append(itemId);
msgBuf.append(" Count: ");
msgBuf.append(results.size());
logger.error(msgBuf);
throw new InventoryApiException(msgBuf.toString());
}
msgBuf.append("Inventory object was retrieved for item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results.get(0);
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemByType(int)
*/
@Override
public List<ItemMasterDto> getItemByType(Integer itemTypeId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item type id is required", e);
}
try {
Verifier.verifyPositive(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item type id must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setItemTypeId(itemTypeId);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by item type id: "
+ itemTypeId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by item type id, ");
msgBuf.append(itemTypeId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by item type id, ");
msgBuf.append(itemTypeId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemByVendorId(int)
*/
@Override
public List<ItemMasterDto> getItemByVendorId(Integer vendorId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setVendorId(vendorId);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by vendor id: "
+ vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by vendor id, ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by vendor id, ");
msgBuf.append(vendorId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#getItemByVendorItemNo(java.lang.String
* )
*/
@Override
public List<ItemMasterDto> getItemByVendorItemNo(String vendItemNo)
throws InventoryApiException {
if (RMT2String2.isEmpty(vendItemNo)) {
throw new InvalidDataException("Vendor Item No. is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setVendorItemNo(vendItemNo);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by vendor item number: "
+ vendItemNo;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by vendor item number, ");
msgBuf.append(vendItemNo);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by vendor item number, ");
msgBuf.append(vendItemNo);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#getItemBySerialNo(java.lang.String)
*/
@Override
public List<ItemMasterDto> getItemBySerialNo(String serialNo) throws InventoryApiException {
if (RMT2String2.isEmpty(serialNo)) {
throw new InvalidDataException("Item Serial No. is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMaster im = null;
ItemMasterDto criteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(im);
criteria.setItemSerialNo(serialNo);
results = this.getItem(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) by vendor item number: "
+ serialNo;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found by serial number, ");
msgBuf.append(serialNo);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved by serial number, ");
msgBuf.append(serialNo);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItem(java.lang.String)
*/
@Override
public List<ItemMasterDto> getItem(String criteria) throws InventoryApiException {
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item(s) using customer SQL predicate: "
+ criteria;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory items were not found using customer SQL predicate, ");
msgBuf.append(criteria);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item object(s) were retrieved using customer SQL predicate, ");
msgBuf.append(criteria);
logger.info(msgBuf);
return results;
}
@Override
public List<ItemMasterTypeDto> getItemType(ItemMasterTypeDto criteria)
throws InventoryApiException {
dao.setDaoUser(this.apiUser);
List<ItemMasterTypeDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item type(s)";
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemTypeById(int)
*/
@Override
public ItemMasterTypeDto getItemTypeById(Integer itemTypeId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item type Id is required", e);
}
try {
Verifier.verifyPositive(itemTypeId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Type Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterTypeDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterType imt = null;
ItemMasterTypeDto criteria = Rmt2InventoryDtoFactory
.createItemTypeInstance(imt);
criteria.setItemTypeId(itemTypeId);
results = this.getItemType(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item type by item type id: "
+ itemTypeId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item type, ");
msgBuf.append(itemTypeId);
msgBuf.append(", was not found ");
logger.warn(msgBuf);
return null;
}
if (results.size() > 1) {
msgBuf.append("Too many inventory items returned for item type id, ");
msgBuf.append(itemTypeId);
msgBuf.append(" Count: ");
msgBuf.append(results.size());
logger.error(msgBuf);
throw new InventoryApiException(msgBuf.toString());
}
msgBuf.append("Inventory item type object was retrieved for item type id, ");
msgBuf.append(itemTypeId);
logger.info(msgBuf);
return results.get(0);
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemTypes(java.lang.String)
*/
@Override
public List<ItemMasterTypeDto> getItemTypes(String itemName) throws InventoryApiException {
if (RMT2String2.isEmpty(itemName)) {
throw new InvalidDataException("Item Type Name is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterTypeDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterType imt = null;
ItemMasterTypeDto criteria = Rmt2InventoryDtoFactory
.createItemTypeInstance(imt);
criteria.setItemTypeDescription(itemName);
results = this.getItemType(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item type(s) by item name: "
+ itemName;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item types were not found by item name, ");
msgBuf.append(itemName);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item type object(s) were retrieved by item name, ");
msgBuf.append(itemName);
logger.info(msgBuf);
return results;
}
@Override
public List<ItemMasterStatusDto> getItemStatus(ItemMasterStatusDto criteria)
throws InventoryApiException {
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item status(es)";
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemStatus(java.lang.String)
*/
@Override
public List<ItemMasterStatusDto> getItemStatus(String statusName) throws InventoryApiException {
if (RMT2String2.isEmpty(statusName)) {
throw new InvalidDataException("Item Status Name is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterStatus imt = null;
ItemMasterStatusDto criteria = Rmt2InventoryDtoFactory
.createItemStatusInstance(imt);
criteria.setEntityName(statusName);
results = this.getItemStatus(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item status(es) by status name: "
+ statusName;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item status were not found by item name, ");
msgBuf.append(statusName);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item status object(s) were retrieved by item name, ");
msgBuf.append(statusName);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemStatusById(int)
*/
@Override
public ItemMasterStatusDto getItemStatusById(Integer itemStatusId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemStatusId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Status Id is required", e);
}
try {
Verifier.verifyPositive(itemStatusId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Status Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterStatus imt = null;
ItemMasterStatusDto criteria = Rmt2InventoryDtoFactory
.createItemStatusInstance(imt);
criteria.setEntityId(itemStatusId);
results = this.getItemStatus(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item status by item status id: "
+ itemStatusId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item status, ");
msgBuf.append(itemStatusId);
msgBuf.append(", was not found ");
logger.warn(msgBuf);
return null;
}
if (results.size() > 1) {
msgBuf.append("Too many inventory item status returned for item status id, ");
msgBuf.append(itemStatusId);
msgBuf.append(" Count: ");
msgBuf.append(results.size());
logger.error(msgBuf);
throw new InventoryApiException(msgBuf.toString());
}
msgBuf.append("Inventory item status object was retrieved for item status id, ");
msgBuf.append(itemStatusId);
logger.info(msgBuf);
return results.get(0);
}
@Override
public List<ItemMasterStatusHistDto> getItemStatusHist(ItemMasterStatusHistDto criteria)
throws InventoryApiException {
if (criteria == null) {
throw new InvalidDataException("Criteria object is required");
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusHistDto> results;
try {
results = dao.fetch(criteria);
return results;
} catch (Exception e) {
this.msg = "Error querying inventory item status history";
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemStatusHistByItemId(int)
*/
@Override
public List<ItemMasterStatusHistDto> getItemStatusHistByItemId(Integer itemId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required and must be greater than zero", e);
}
dao.setDaoUser(this.apiUser);
List<ItemMasterStatusHistDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
ItemMasterStatusHist imt = null;
ItemMasterStatusHistDto criteria = Rmt2InventoryDtoFactory
.createItemStatusHistoryInstance(imt);
criteria.setItemId(itemId);
results = this.getItemStatusHist(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve inventory item status history by item id: "
+ itemId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Inventory item status history was not found by item id, ");
msgBuf.append(itemId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Inventory item status history object(s) were retrieved by item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getCurrentItemStatusHist(int)
*/
@Override
public ItemMasterStatusHistDto getCurrentItemStatusHist(Integer itemId)
throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
if (itemId <= 0) {
throw new InvalidDataException("Item Id must be greater than zero");
}
dao.setDaoUser(this.apiUser);
ItemMasterStatusHistDto results;
StringBuffer msgBuf = new StringBuffer();
try {
results = dao.fetchCurrentItemStatusHistory(itemId);
} catch (Exception e) {
this.msg = "Unable to retrieve current inventory item status history by item id: "
+ itemId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Current inventory item status history was not found by item id, ");
msgBuf.append(itemId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(1);
msgBuf.append(" Current inventory item status history object(s) were retrieved by item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getVendorItem(int, int)
*/
@Override
public List<VendorItemDto> getVendorItem(Integer vendorId, Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor/Creditor Id is required", e);
}
dao.setDaoUser(this.apiUser);
List<VendorItemDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
VwVendorItems imt = null;
VendorItemDto criteria = Rmt2InventoryDtoFactory.createVendorItemInstance(imt);
criteria.setItemId(itemId);
criteria.setVendorId(vendorId);
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve vendor item by item id and vendor id: "
+ itemId + " " + vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null && itemId != null) {
msgBuf.append(" inventory vendor item was not found by item id and vendor id, ");
msgBuf.append(itemId);
msgBuf.append(" ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Vendor inventory item object(s) were retrieved by vendor id and item id, ");
msgBuf.append(vendorId);
msgBuf.append(" ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getVendorAssignItems(int)
*/
@Override
public List<VendorItemDto> getVendorAssignItems(Integer vendorId) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor/Creditor Id is required to fetch assigned items", e);
}
dao.setDaoUser(this.apiUser);
List<VendorItemDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
VwVendorItems imt = null;
VendorItemDto criteria = Rmt2InventoryDtoFactory.createVendorItemInstance(imt);
criteria.setVendorId(vendorId);
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve vendor associated inventory items by vendor id: " + vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Vendor associated inventory items were not found by vendor id, ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Vendor associated inventory item object(s) were retrieved by vendor id, ");
msgBuf.append(vendorId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getVendorUnassignItems(int)
*/
@Override
public List<ItemMasterDto> getVendorUnassignItems(Integer vendorId) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor/Creditor Id is required to fetch unassigned items", e);
}
String criteria = RMT2String.replace(
AccountingSqlConst.SQL_CRTIERIA_VENDOR_UNASSIGNED_ITEM,
String.valueOf(vendorId), "$1");
dao.setDaoUser(this.apiUser);
List<ItemMasterDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve unassociated vendor inventory items by vendor id: "
+ vendorId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Vendor associated inventory items were not found by vendor id, ");
msgBuf.append(vendorId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Vendor associated inventory item object(s) were retrieved by vendor id, ");
msgBuf.append(vendorId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#getItemAssociations(int)
*/
@Override
public List<ItemAssociationDto> getItemAssociations(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("A valid item id must provided in order to perform an item assoication query", e);
}
// InventoryDao dao = this.factory.createRmt2OrmDao();
dao.setDaoUser(this.apiUser);
List<ItemAssociationDto> results;
StringBuffer msgBuf = new StringBuffer();
try {
VwItemAssociations assoc = null;
ItemAssociationDto criteria = Rmt2InventoryDtoFactory
.createItemAssociationInstance(assoc);
criteria.setItemId(itemId);
results = dao.fetch(criteria);
} catch (Exception e) {
this.msg = "Unable to retrieve item associations for item id: " + itemId;
logger.error(this.msg, e);
throw new InventoryApiException(e);
}
if (results == null) {
msgBuf.append("Item associations were not found by item id, ");
msgBuf.append(itemId);
logger.warn(msgBuf);
return null;
}
msgBuf.append(results.size());
msgBuf.append(" Item association object(s) were retrieved by item id, ");
msgBuf.append(itemId);
logger.info(msgBuf);
return results;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#updateInventoryItem(org.dto.ItemMasterDto
* )
*/
@Override
public int updateItemMaster(ItemMasterDto item) throws InventoryApiException {
try {
Verifier.verifyNotNull(item);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory item master object is required", e);
}
dao.setDaoUser(this.apiUser);
this.computeItemRetail(item);
boolean isNewItem = (item.getItemId() == 0);
ItemMaster newItem = null;
ItemMasterDto imDto = Rmt2InventoryDtoFactory.createItemMasterInstance(newItem);
// Get old version of item record and apply changes
if (!isNewItem) {
imDto = this.getItemById(item.getItemId());
if (imDto == null) {
this.msg = "Inventory item update error: Item id, "
+ item.getItemId() + ", does not exist in the system";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
}
// Capture the original override flag
int oldOverrideRetailFlag = imDto.getOverrideRetail();
// add delta to old inventory item master version
imDto.setItemTypeId(item.getItemTypeId());
imDto.setVendorId(item.getVendorId());
imDto.setItemName(item.getItemName());
imDto.setVendorItemNo(item.getVendorItemNo());
imDto.setItemSerialNo(item.getItemSerialNo());
imDto.setQtyOnHand(item.getQtyOnHand());
imDto.setUnitCost(item.getUnitCost());
imDto.setMarkup(item.getMarkup());
imDto.setRetailPrice(item.getRetailPrice());
imDto.setOverrideRetail(item.getOverrideRetail());
imDto.setActive(item.getActive());
// Perform updates
int rc;
try {
// Update Item master
rc = dao.maintain(imDto);
// Update statuses
ItemMasterStatusHistDto imsh = null;
if (isNewItem) {
// Indicate that item is in service
this.changeItemStatus(imDto, InventoryConst.ITEM_STATUS_INSRVC);
item.setItemId(rc);
}
else {
// Get item master's current status
imsh = dao.fetchCurrentItemStatusHistory(imDto.getItemId());
if (imsh == null) {
this.msg = "Unable to find status history for inventory item id, "
+ imDto.getItemId() + ". History not available.";
logger.error(this.msg);
throw new RMT2Exception(this.msg);
}
// Change the most recent item status, which should be
// 'Replaced'
imsh = this.changeItemStatus(imDto, InventoryConst.ITEM_STATUS_REPLACE);
// User has requested system to activate vendor item override.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_YES
&& oldOverrideRetailFlag == InventoryConst.ITEM_OVERRIDE_NO) {
imsh = this.changeItemStatus(imDto,
InventoryConst.ITEM_STATUS_OVERRIDE_ACTIVE);
}
// User has requested system to deactivate vendor item override.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_NO
&& oldOverrideRetailFlag == InventoryConst.ITEM_OVERRIDE_YES) {
imsh = this.changeItemStatus(imDto,
InventoryConst.ITEM_STATUS_OVERRIDE_INACTIVE);
}
}
// Place Item in "Available" if quantity is greater than zero.
// Otherwise, 'Out of Stock'.
int itemStatusId = imDto.getQtyOnHand() <= 0 ? InventoryConst.ITEM_STATUS_OUTSTOCK
: InventoryConst.ITEM_STATUS_AVAIL;
imsh = this.changeItemStatus(imDto, itemStatusId);
// If item is no longer active, then put in out servive status
if (!isNewItem) {
if (imDto.getActive() == 0) {
imsh = this.changeItemStatus(imDto,
InventoryConst.ITEM_STATUS_OUTSRVC);
}
}
return rc;
} catch (Exception e) {
this.msg = "Unable to process inventory item master updates.";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Validates an inventory item master object.
*
* The following validations must be met:
* <ul>
* <li>Item object cannot be null</li>
* <li>The vendor id is not required, but if its id is greateer than zero,
* then it must exist in the database.</li>
* <li>Item Description must no be null</li>
* <li>Item Type must be valid</li>
* <li>Item Markup must be greater than zero</li>
* <li>Service item types must have a quantity on hand equal to one, and a
* mark value equal to one.</li>
* </ul>
*
* @param item
* an instance of {@link ItemMasterDto}
* @throws InventoryException
*/
protected void validateItemMaster(ItemMasterDto item) throws InventoryApiException {
if (item == null) {
this.msg = "Item Master DTO cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Validate Creditor
SubsidiaryApiFactory f = new SubsidiaryApiFactory();
CreditorApi api = f.createCreditorApi();
if (item.getVendorId() > 0) {
Object cred;
try {
cred = api.getByCreditorId(item.getVendorId());
} catch (CreditorApiException e) {
throw new InventoryApiException(e);
} finally {
api = null;
}
if (cred == null) {
this.msg = "The Vendor associated with the inventory item master does not exist in the system: "
+ item.getVendorId();
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
}
// Common validations
if (item.getItemName() == null || item.getItemName().equals("")) {
this.msg = "Item Name must contain a value and cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
if (item.getItemTypeId() <= 0) {
this.msg = "Item Type is invalid";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Mark Up must be greater than zero and cannot be null
if (item.getMarkup() <= 0) {
this.msg = "Mark Up must be greater than zero and cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
/*
* Not sure if unit cost should be required to have a value greater than
* zero. if (itemBase.getUnitCost() <= 0) { throw new
* ItemMasterException(this.dbo, 419, null); }
*/
// Service item validations
if (item.getItemTypeId() == InventoryConst.ITEM_TYPE_SRVC) {
if (item.getVendorId() > 0) {
this.msg = "Service items cannot be assoicated with a Vendor";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Quantity on Hand must be equal to 1 for service items
if (item.getQtyOnHand() != 1) {
this.msg = "Quantity on Hand must be equal to 1 for service items";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Mark Up must be equal to 1
if (item.getMarkup() != 1) {
this.msg = "Mark Up must be equal to 1";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
}
}
/**
* Calculates the retail price of an item based on its item type value
* (Merchandise or Service). At this point all data components used for
* calculating retail should have been verified. The retail price will be
* determined in one of two ways: 1) as is when the user request that retail
* price calculations be ignored and just accept the user's input or 2)
* apply the formula retail price = unit cost * mark up.
*
* @param item
* an instance of {@link ItemMasterDto}
* @throws InventoryException
*/
private void computeItemRetail(ItemMasterDto item) throws InventoryApiException {
double retailPrice = 0;
// Determine if user requests us to override retail calculations.
if (item.getOverrideRetail() == 0) {
retailPrice = item.getUnitCost() * item.getMarkup();
item.setRetailPrice(retailPrice);
}
return;
}
/*
* (non-Javadoc)
*
* @see
* org.modules.inventory.InventoryApi#updateVendorItem(org.dto.VendorItemDto
* )
*/
@Override
public int updateVendorItem(VendorItemDto item) throws InventoryApiException {
this.validateVendorItem(item);
// Update Vendor Item
dao.setDaoUser(this.apiUser);
int rc;
try {
List<VendorItemDto> results = this.getVendorItem(item.getVendorId(), item.getItemId());
// Determine if we are creating a new or modifying an existing vendor item
boolean newRec = (results == null || results.size() == 0 ? true : false);
rc = dao.maintain(item, newRec);
return rc;
} catch (Exception e) {
this.msg = "Unable to process inventory vendor item updates.";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Validate a vendor item object.
*
* The following validations must be met:
* <ul>
* <li>The vendor must exist in the database.</li>
* <li>The vendor id is required and must be greater than zero.</li>
* <li>The Vendor Item Number cannot be null</li>
* <li>The Item Serial Number cannot be null</li>
* </ul>
*
* @param vi
* The {@link VendorItemDto} object
* @throws InventoryException
*/
protected void validateVendorItem(VendorItemDto vi) throws InventoryApiException {
dao.setDaoUser(this.apiUser);
try {
Verifier.verifyNotNull(vi);
}
catch (VerifyException e) {
this.msg = "Vendor Item object cannot be null";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
Verifier.verifyPositive(vi.getVendorId());
}
catch (VerifyException e) {
this.msg = "The vendor item\'s Vendor Id is invalid: " + vi.getVendorId();
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
Verifier.verifyNotNull(vi.getVendorItemNo());
}
catch (VerifyException e) {
this.msg = "New and existing merchandise items must have the vendor's version of an item number or part number";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
Verifier.verifyNotNull(vi.getItemSerialNo());
}
catch (VerifyException e) {
this.msg = "Merchandise items must have a vendor serial number";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Validate Creditor
CreditorApi api = SubsidiaryApiFactory.createCreditorApi(this.dao);
Object cred;
try {
cred = api.getByCreditorId(vi.getVendorId());
} catch (CreditorApiException e) {
throw new InventoryApiException(e);
} finally {
api = null;
}
if (cred == null) {
this.msg = "The Vendor associated with the inventory vendor item does not exist in the system: "
+ vi.getVendorId();
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
return;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#deleteItemMaster(int)
*/
@Override
public int deleteItemMaster(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
// Determine if item is tied to one or more sales orders and/or purchase
// orders.
List<ItemAssociationDto> associations = this.getItemAssociations(itemId);
if (associations != null && associations.size() > 0) {
this.msg = "Invenoty item master , "
+ itemId
+ ", cannot be deleted since it is associated with one or more sales orders and/or purchase orders";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// InventoryDao dao = this.factory.createRmt2OrmDao();
dao.setDaoUser(this.apiUser);
int rc;
try {
// dao.beginTrans();
// Remove all items from item master status history
ItemMasterStatusHistDto imshCriteria = Rmt2InventoryDtoFactory
.createItemStatusHistoryInstance((ItemMasterStatusHist) null);
imshCriteria.setItemId(itemId);
rc = dao.delete(imshCriteria);
this.msg = "Total item status history entries removed for item id, "
+ itemId + ": " + rc;
logger.info(this.msg);
// Remove item from inventory.
ItemMaster nullBean = null;
ItemMasterDto imCriteria = Rmt2InventoryDtoFactory
.createItemMasterInstance(nullBean);
imCriteria.setItemId(itemId);
rc = dao.delete(imCriteria);
this.msg = "Inventory item id, " + itemId
+ ", was successfully deleted from the system";
logger.info(this.msg);
// Commit transaction
// dao.commitTrans();
return RMT2Base.SUCCESS;
} catch (Exception e) {
// dao.rollbackTrans();
this.msg = "Unable to delete inventory item due to database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#pushInventory(int, int)
*/
@Override
public double pushInventory(Integer itemId, Integer qty) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
try {
Verifier.verifyNotNull(qty);
}
catch (VerifyException e) {
throw new InvalidDataException("Quantity is required", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...invenory was not increased";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
int origItemQty = im.getQtyOnHand();
int changeItemQty = origItemQty + qty;
double changeValue = im.getUnitCost() * changeItemQty;
im.setQtyOnHand(changeItemQty);
try {
// this.updateItemMaster(im, null);
this.updateItemMaster(im);
} catch (Exception e) {
this.msg = "Unable to push inventory for item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
return changeValue;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#pullInventory(int, int)
*/
@Override
public double pullInventory(Integer itemId, Integer qty) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Item Id is required", e);
}
try {
Verifier.verifyNotNull(qty);
}
catch (VerifyException e) {
throw new InvalidDataException("Quantity is required", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...invenory was not decreased";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
int origItemQty = im.getQtyOnHand();
int changeItemQty = origItemQty - qty;
double changeValue = im.getUnitCost() * changeItemQty;
im.setQtyOnHand(changeItemQty);
try {
// this.updateItemMaster(im, null);
this.updateItemMaster(im);
} catch (Exception e) {
this.msg = "Unable to pull inventory for item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
return changeValue;
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#deactivateItemMaster(int)
*/
@Override
public int deactivateItemMaster(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id must be greater than zero", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...item was not deactivated";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Throw exception if alread deactivated.
if (im.getActive() == 0) {
throw new InventoryApiException("Inventory item, " + itemId + ", is already deactivated");
}
dao.setDaoUser(this.apiUser);
try {
// dao.beginTrans();
// Set item inactive
im.setActive(InventoryConst.ITEM_ACTIVE_NO);
// Update Item master
dao.maintain(im);
// Render item out of service
this.changeItemStatus(im, InventoryConst.ITEM_STATUS_OUTSRVC);
// dao.commitTrans();
return RMT2Base.SUCCESS;
} catch (Exception e) {
// dao.rollbackTrans();
this.msg = "Unable to deactivate item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/*
* (non-Javadoc)
*
* @see org.modules.inventory.InventoryApi#activateItemMaster(int)
*/
@Override
public int activateItemMaster(Integer itemId) throws InventoryApiException {
try {
Verifier.verifyNotNull(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id is required", e);
}
try {
Verifier.verifyPositive(itemId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id must be greater than zero", e);
}
ItemMasterDto im = this.getItemById(itemId);
if (im == null) {
this.msg = "Invenoty item master , " + itemId
+ ", could not be found...item was not activated";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Throw exception if alread activated.
if (im.getActive() == 1) {
throw new InventoryApiException("Inventory item, " + itemId + ", is already activated");
}
dao.setDaoUser(this.apiUser);
try {
// Set item active
im.setActive(InventoryConst.ITEM_ACTIVE_YES);
// Update Item master
dao.maintain(im);
// Render item out of service
this.changeItemStatus(im, InventoryConst.ITEM_STATUS_INSRVC);
// Determine if item has quantity to sold or is out of stock.
int itemStatusId = im.getQtyOnHand() <= 0 ? InventoryConst.ITEM_STATUS_OUTSTOCK
: InventoryConst.ITEM_STATUS_AVAIL;
this.changeItemStatus(im, itemStatusId);
return RMT2Base.SUCCESS;
} catch (Exception e) {
this.msg = "Unable to activate item master , " + itemId
+ ", due to a database error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Associates one or more inventory items with a vendor.
* <p>
* This method iterates through the list of inventory item id's contained in
* <i>items</i> and assigns each one to a vendor identified as
* <i>vendorId</i>. If an error is encountered during an iteration, the
* entire process is aborted and all previous successful transactions are
* rolled back.
*
* @param vendorId
* The id of the vendor
* @param items
* A list inventory item id's
* @return The number of items assigned to the vendor.
* @throws InventoryException
* An inventory item in <i>items</i> does not exist in the
* system or database error trying to assoicate the vendor with
* an inventory item.
*/
@Override
public int assignVendorItems(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of Inventory Item Id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
ItemMasterDto imDto = this.getItemById(items[ndx]);
if (imDto == null) {
this.msg = "Item id is not found in the database: " + items[ndx];
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
VendorItemDto viDto = Rmt2InventoryDtoFactory.createVendorItemInstance(vendorId, imDto);
try {
// count += this.updateVendorItem(viDto);
count += dao.maintain(viDto, true);
} catch (Exception e) {
this.msg = "Error creating vendor id [" + vendorId
+ "] and item id {" + imDto.getItemId()
+ "] associtation";
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
// dao.commitTrans();
return count;
} catch (Exception e) {
// dao.rollbackTrans();
this.msg = "Unable to persist vendor id/item master association to table, vendor_items. The assignment of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Disassociates one or more inventory items from a vendor.
* <p>
* This method iterates through the list of inventory item id's contained in
* <i>items</i> and removes each one from the vendor identified as
* <i>vendorId</i>. If an error is encountered during an iteration, the
* entire process is aborted and all previous successful transactions are
* rolled back.
*
* @param vendorId
* The id of the vendor
* @param items
* A list inventory item id's to remove.
* @return The number of items removed from the vendor.
* @throws InventoryException
* An inventory item in <i>items</i> does not exist in the
* system or database error when disassociating the vendor
* from an inventory item.
*/
@Override
public int removeVendorItems(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of vendor item id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Vendor Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
VendorItemDto viDto = Rmt2InventoryDtoFactory.createVendorItemInstance(null);
viDto.setVendorId(vendorId);
viDto.setItemId(items[ndx]);
try {
count += dao.delete(viDto);
} catch (Exception e) {
this.msg = "Error deleting vendor id [" + vendorId
+ "] and item id {" + items[ndx] + "] associtation";
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
return count;
} catch (Exception e) {
this.msg = "Unable to delete vendor id/item master association from table, vendor_items. The deletion of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Changes the override flag to true for one or more of a vendor's items.
* <p>
* Activates a vendor-item override for all item id's stored in items
* collection. This method enables a vendor-item override targeting the
* inventory item, itemId. Also, the creditor id of the inventory item
* master is set to the vendor's id. An override instructs the system to
* obtain pricing information for an inventory item from the vendor_items
* table instead of the item_master table .
*
* @param vendorId
* The id of the vendor that will be associated with each item
* id.
* @param items
* Collection containing one or more item_master id's to
* override.
* @return The total number of rows effected by the database transaction.
* @throws ItemMasterException
*/
@Override
public int addInventoryOverride(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of Inventory Item Id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
ItemMasterDto imDto = this.getItemById(items[ndx]);
if (imDto == null) {
this.msg = "Item id is not found in the database: "
+ items[ndx];
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Do not attempt to update an item that is currently overridden.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_YES) {
continue;
}
imDto.setVendorId(vendorId);
imDto.setOverrideRetail(InventoryConst.ITEM_OVERRIDE_YES);
// Ensure that item's quantity on hand is not effected after
// updates are applied to the database.
imDto.setQtyOnHand(0);
try {
count += dao.maintain(imDto);
} catch (Exception e) {
this.msg = "Error changing override status of inventory item id, "
+ imDto.getItemId();
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
return count;
} catch (Exception e) {
this.msg = "Unable to persist vendor id/item master association to table, vendor_items. The assignment of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Changes the override flag to false for one or more of a vendor's item.
* <p>
* This method deactivates a vendor-item override targeting the inventory
* item, itemId. Also, the creditor id of the inventory item master is set
* to null. An override instructs the system to obtain pricing information
* for an inventory item from the vendor_items table instead of the
* item_master table .
*
* @param vendorId
* The id of the vendor that will be disassoicated with the item
* id.
* @param items
* An array of item id's to change
* @return The total number of items effected by the database transaction. .
* @throws ItemMasterException
*/
@Override
public int removeInventoryOverride(Integer vendorId, Integer[] items) throws InventoryApiException {
try {
Verifier.verifyNotNull(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id is required", e);
}
try {
Verifier.verifyPositive(vendorId);
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Vendor Id must be greater than zero", e);
}
try {
Verifier.verifyNotNull(items);
}
catch (VerifyException e) {
throw new InvalidDataException("List of Inventory Item Id's is required", e);
}
try {
for (int ndx = 0; ndx < items.length; ndx++) {
Verifier.verifyNotNull(items[ndx]);
Verifier.verifyPositive(items[ndx]);
}
}
catch (VerifyException e) {
throw new InvalidDataException("Inventory Item Id cannot be null and must be greater than zero", e);
}
int count = 0;
dao.setDaoUser(this.apiUser);
try {
for (int ndx = 0; ndx < items.length; ndx++) {
ItemMasterDto imDto = this.getItemById(items[ndx]);
if (imDto == null) {
this.msg = "Item id is not found in the database: "
+ items[ndx];
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
// Do not attempt to update an item that is currently overridden.
if (imDto.getOverrideRetail() == InventoryConst.ITEM_OVERRIDE_NO) {
continue;
}
imDto.setVendorId(0);
imDto.setOverrideRetail(InventoryConst.ITEM_OVERRIDE_NO);
// Ensure that item's quantity on hand is not effected after
// updates are applied to the database.
imDto.setQtyOnHand(0);
try {
count += dao.maintain(imDto);
} catch (Exception e) {
this.msg = "Error changing override status of inventory item id, "
+ imDto.getItemId();
logger.error(this.msg);
throw new InventoryApiException(this.msg, e);
}
}
return count;
} catch (Exception e) {
this.msg = "Unable to persist vendor id/item master association to table, vendor_items. The assignment of items to vendor is aborted";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
/**
* Changes the status of an inventory item which the database transaction
* object is supplied by the user.
*
* @param dao
* the inventory database transaction object
* @param item
* An instance of {@link ItemMasterDto} which is the item master
* object targeted for the satus change.
* @param newItemStatusId
* The id of the item status.
* @return The {@link ItemMasterStatusHistDto} object which represents
* newItemStatusId
* @throws InventoryException
* If newItemStatusId is out of sequence, if a database error
* occurs, or a system error occurs.
*/
protected ItemMasterStatusHistDto changeItemStatus(ItemMasterDto item, int newItemStatusId)
throws InventoryApiException {
ItemMasterStatusHistDto imsh = null;
dao.setDaoUser(this.apiUser);
// Validate newItemStatusId
List<ItemMasterStatusDto> imsList;
try {
ItemMasterStatusDto imsCriteria = Rmt2InventoryDtoFactory.createItemStatusInstance(null);
imsCriteria.setEntityId(newItemStatusId);
imsList = dao.fetch(imsCriteria);
} catch (InventoryDaoException e) {
this.msg = "Problem querying for new Item status";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
if (imsList == null) {
this.msg = "New item status id does not exist in the system: "
+ newItemStatusId;
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
if (imsList.size() > 1) {
this.msg = "New item status id query return multiple items in the result set. Should only be one element";
logger.error(this.msg);
throw new InventoryApiException(this.msg);
}
try {
// End current item status
imsh = dao.fetchCurrentItemStatusHistory(item.getItemId());
if (imsh != null) {
dao.maintain(imsh);
}
// Create new item status
imsh = Rmt2InventoryDtoFactory.createItemStatusHistoryInstance((ItemMasterStatusHist) null);
imsh.setItemId(item.getItemId());
imsh.setItemStatusId(newItemStatusId);
imsh.setUnitCost(item.getUnitCost());
imsh.setMarkup(item.getMarkup());
dao.maintain(imsh);
return imsh;
} catch (Exception e) {
this.msg = "Inventory item status history change failed due to a Database or System error";
logger.error(this.msg, e);
throw new InventoryApiException(this.msg, e);
}
}
}
| 69,503 | 0.575042 | 0.573574 | 1,852 | 36.531319 | 26.963631 | 147 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.546436 | false | false | 15 |
27f177168ef1de9a02d235184224d8cc8ee79118 | 18,348,100,356,241 | 19ef56b4fadac4e0b11b9c5700adf3b63ac6530f | /Algorithmen und Datenstrukturen/src/aufgabe6_1/DataHandler.java | f3aa441165e77b7b9a569456ab40abb494e99049 | []
| no_license | kalazana/Algorithmen | https://github.com/kalazana/Algorithmen | 7166900c5c832329bf13412365b89521540d3ef6 | 76c9d71dd816f89b997edc97c43c80b4b317a6f6 | refs/heads/master | 2020-12-07T00:53:41.322000 | 2020-01-17T13:49:57 | 2020-01-17T13:49:57 | 232,594,577 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aufgabe6_1;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class DataHandler {
private File filename = new File("data/KHR95_red.txt");
private int counter = 0;
private BufferedReader bufferedReader = null;
private BufferedWriter bufferedWriter = null;
/**
* Reads a list of hospitals from the hard drive.
*
* @return - List of hospitals
*/
public ArrayList<Hospital> read_data() {
try {
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "windows-1252"));
ArrayList<Hospital> hospitals = new ArrayList<>();
if (filename.exists()) {
String fileContent = bufferedReader.readLine();
fileContent = bufferedReader.readLine();
counter++;
while (fileContent != null) {
int index = 0;
Hospital hospital = new Hospital();
if (!fileContent.equals("")) {
for (int i = 0; i < 5; i++) {
switch (i) {
case 0:
hospital.setName(fileContent.substring(index, fileContent.indexOf("\t", index)));
break;
case 1:
hospital.setStreet(fileContent.substring(index, fileContent.indexOf("\t", index)));
break;
case 2:
hospital.setPostcode(Integer.parseInt(fileContent.substring(index, fileContent.indexOf("\t", index))));
break;
case 3:
hospital.setLocation(fileContent.substring(index, fileContent.indexOf("\t", index)));
break;
case 4:
hospital.setNumberOfBeds(Integer.parseInt(fileContent.substring(index)));
break;
}
index = fileContent.indexOf("\t", index);
index++;
}
hospitals.add(hospital);
}
fileContent = bufferedReader.readLine();
counter++;
}
}
return hospitals;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Writes a list of hospitals on the hard drive.
*
* @param hospitals - List of hospitals
* @param filename - name of the file to be write
*/
public void write_data(ArrayList<Hospital> hospitals, String filename) {
try {
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"));
bufferedWriter.write("Name" + "\t" + "StrHausNr" + "\t" + "PLZ" + "\t" + "Ort" + "\t" + "Bettenanzahl\n");
for (Hospital hospital : hospitals) {
bufferedWriter.write(hospital.getName() + "\t" + hospital.getStreet() + "\t" + hospital.getPostcode() + "\t" + hospital.getLocation() + "\t" + hospital.getNumberOfBeds() + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Writes one record of the hospital list on the console.
*/
public void output() {
try {
int input;
bufferedReader = new BufferedReader(new FileReader(filename));
System.out.println("Es wurden " + counter + " Einträge gefunden.");
System.out.print("\nWelcher Eintrag soll ausgeben werden: ");
Scanner scanner = new Scanner(System.in);
input = Integer.parseInt(scanner.next());
for (int i = 0; i < input; i++) {
if (filename.exists()) {
bufferedReader.readLine();
}
}
System.out.println(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Writes one record of the hospital list on the console.
*/
public void toSting() {
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String readLine;
if (filename.exists()) {
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| UTF-8 | Java | 5,463 | java | DataHandler.java | Java | []
| null | []
| package aufgabe6_1;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class DataHandler {
private File filename = new File("data/KHR95_red.txt");
private int counter = 0;
private BufferedReader bufferedReader = null;
private BufferedWriter bufferedWriter = null;
/**
* Reads a list of hospitals from the hard drive.
*
* @return - List of hospitals
*/
public ArrayList<Hospital> read_data() {
try {
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "windows-1252"));
ArrayList<Hospital> hospitals = new ArrayList<>();
if (filename.exists()) {
String fileContent = bufferedReader.readLine();
fileContent = bufferedReader.readLine();
counter++;
while (fileContent != null) {
int index = 0;
Hospital hospital = new Hospital();
if (!fileContent.equals("")) {
for (int i = 0; i < 5; i++) {
switch (i) {
case 0:
hospital.setName(fileContent.substring(index, fileContent.indexOf("\t", index)));
break;
case 1:
hospital.setStreet(fileContent.substring(index, fileContent.indexOf("\t", index)));
break;
case 2:
hospital.setPostcode(Integer.parseInt(fileContent.substring(index, fileContent.indexOf("\t", index))));
break;
case 3:
hospital.setLocation(fileContent.substring(index, fileContent.indexOf("\t", index)));
break;
case 4:
hospital.setNumberOfBeds(Integer.parseInt(fileContent.substring(index)));
break;
}
index = fileContent.indexOf("\t", index);
index++;
}
hospitals.add(hospital);
}
fileContent = bufferedReader.readLine();
counter++;
}
}
return hospitals;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Writes a list of hospitals on the hard drive.
*
* @param hospitals - List of hospitals
* @param filename - name of the file to be write
*/
public void write_data(ArrayList<Hospital> hospitals, String filename) {
try {
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "windows-1252"));
bufferedWriter.write("Name" + "\t" + "StrHausNr" + "\t" + "PLZ" + "\t" + "Ort" + "\t" + "Bettenanzahl\n");
for (Hospital hospital : hospitals) {
bufferedWriter.write(hospital.getName() + "\t" + hospital.getStreet() + "\t" + hospital.getPostcode() + "\t" + hospital.getLocation() + "\t" + hospital.getNumberOfBeds() + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Writes one record of the hospital list on the console.
*/
public void output() {
try {
int input;
bufferedReader = new BufferedReader(new FileReader(filename));
System.out.println("Es wurden " + counter + " Einträge gefunden.");
System.out.print("\nWelcher Eintrag soll ausgeben werden: ");
Scanner scanner = new Scanner(System.in);
input = Integer.parseInt(scanner.next());
for (int i = 0; i < input; i++) {
if (filename.exists()) {
bufferedReader.readLine();
}
}
System.out.println(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Writes one record of the hospital list on the console.
*/
public void toSting() {
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String readLine;
if (filename.exists()) {
while ((readLine = bufferedReader.readLine()) != null) {
System.out.println(readLine);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 5,463 | 0.469059 | 0.465031 | 150 | 35.413334 | 31.096235 | 194 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.493333 | false | false | 15 |
8293562e2603db36d6b4cf8a5842bd8b1961d14d | 7,378,753,853,179 | 409762381eb0b5e6e88723826880b6d48760f155 | /src/main/java/com/baeksupervisor/ticket/service/TicketService.java | 1b3d5bf5417795d3a5a2124c64b311906c61dd8f | []
| no_license | baeksupervisor/cs | https://github.com/baeksupervisor/cs | 8ab7cacdb03ef636c58ece78913b6ecbe68bce65 | 1cd96726240ddd0d3df6b4836cd6f62580044e22 | refs/heads/master | 2021-03-01T02:38:04.487000 | 2020-03-19T08:42:42 | 2020-03-19T08:42:42 | 245,747,436 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.baeksupervisor.ticket.service;
import com.baeksupervisor.ticket.config.UserDetailsHolder;
import com.baeksupervisor.ticket.exception.ResourceNotFoundException;
import com.baeksupervisor.ticket.persistence.Comment;
import com.baeksupervisor.ticket.persistence.Ticket;
import com.baeksupervisor.ticket.persistence.User;
import com.baeksupervisor.ticket.repository.CommentRepository;
import com.baeksupervisor.ticket.repository.TicketRepository;
import com.baeksupervisor.ticket.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by Seunghyun.Baek
* Since 2020/03/15
*/
@Service
public class TicketService {
private final TicketRepository ticketRepository;
private final UserRepository userRepository;
private final CommentRepository commentRepository;
public TicketService(TicketRepository ticketRepository, UserRepository userRepository, CommentRepository commentRepository) {
this.ticketRepository = ticketRepository;
this.userRepository = userRepository;
this.commentRepository = commentRepository;
}
@Transactional(rollbackFor = Exception.class)
public Comment saveComment(Long ticketId, Comment comment) throws Exception {
User user = UserDetailsHolder.getUserDetails().getUser();
comment.setCreator(userRepository.findByEmail("shbaek159@gmail.com").get());
commentRepository.save(comment);
Ticket ticket = ticketRepository.findById(ticketId).orElseThrow(ResourceNotFoundException::new);
ticket.getComments().add(comment);
return comment;
}
}
| UTF-8 | Java | 1,676 | java | TicketService.java | Java | [
{
"context": "ction.annotation.Transactional;\n\n/**\n * Created by Seunghyun.Baek\n * Since 2020/03/15\n */\n@Service\npublic class Tic",
"end": 661,
"score": 0.9998975396156311,
"start": 647,
"tag": "NAME",
"value": "Seunghyun.Baek"
},
{
"context": " comment.setCreator(userRepository.findByEmail(\"shbaek159@gmail.com\").get());\n commentRepository.save(comment)",
"end": 1442,
"score": 0.9999308586120605,
"start": 1423,
"tag": "EMAIL",
"value": "shbaek159@gmail.com"
}
]
| null | []
| package com.baeksupervisor.ticket.service;
import com.baeksupervisor.ticket.config.UserDetailsHolder;
import com.baeksupervisor.ticket.exception.ResourceNotFoundException;
import com.baeksupervisor.ticket.persistence.Comment;
import com.baeksupervisor.ticket.persistence.Ticket;
import com.baeksupervisor.ticket.persistence.User;
import com.baeksupervisor.ticket.repository.CommentRepository;
import com.baeksupervisor.ticket.repository.TicketRepository;
import com.baeksupervisor.ticket.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by Seunghyun.Baek
* Since 2020/03/15
*/
@Service
public class TicketService {
private final TicketRepository ticketRepository;
private final UserRepository userRepository;
private final CommentRepository commentRepository;
public TicketService(TicketRepository ticketRepository, UserRepository userRepository, CommentRepository commentRepository) {
this.ticketRepository = ticketRepository;
this.userRepository = userRepository;
this.commentRepository = commentRepository;
}
@Transactional(rollbackFor = Exception.class)
public Comment saveComment(Long ticketId, Comment comment) throws Exception {
User user = UserDetailsHolder.getUserDetails().getUser();
comment.setCreator(userRepository.findByEmail("<EMAIL>").get());
commentRepository.save(comment);
Ticket ticket = ticketRepository.findById(ticketId).orElseThrow(ResourceNotFoundException::new);
ticket.getComments().add(comment);
return comment;
}
}
| 1,664 | 0.792959 | 0.786396 | 44 | 37.090908 | 31.346174 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false | 15 |
1dad619923478eaf362f8192a6dbf40b8750f6cb | 32,916,629,424,409 | 1b579c8025775339747579a809aaa324e6d77382 | /src/Employee.java | ee986849fe51f2c240b45a181587b1d5547701b1 | []
| no_license | dineshdewangan/sample | https://github.com/dineshdewangan/sample | 3432e88255f270d23c76eb1115b2c3185e770ffd | 547a2aa6e9447c6ece9835050db8f976f0913a86 | refs/heads/master | 2017-12-22T02:32:34.992000 | 2016-11-12T18:21:35 | 2016-11-12T18:21:35 | 72,817,934 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pancardNumber;
}
public static void main(String [] arg){
Employee e = new Employee("adsfasdfasd");
System.out.println(e.getPancardNumber());
}
} | UTF-8 | Java | 475 | java | Employee.java | Java | []
| null | []
| public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pancardNumber;
}
public static void main(String [] arg){
Employee e = new Employee("adsfasdfasd");
System.out.println(e.getPancardNumber());
}
} | 475 | 0.696842 | 0.696842 | 27 | 16.555555 | 16.382767 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.703704 | false | false | 15 |
e2b4ae0641db37363eb3a1f53eabff025563d971 | 18,373,870,112,325 | 2d0500750e229017e5ec317f161a8334075b633b | /sources/SCLibrary/src/stupidchess/network/controller/IncomingMessageHandler.java | 1e425040dac440c419bc62fabe381275c8cabc56 | [
"MIT"
]
| permissive | hungnvjs/stupid-chess | https://github.com/hungnvjs/stupid-chess | 108b6e1dcdb9b497cd1d526238be75c63b573204 | ea6054524bb79cb14ce5e3e8a942af97d658be49 | refs/heads/master | 2020-04-06T13:08:10.576000 | 2018-11-14T03:36:19 | 2018-11-14T03:36:19 | 157,485,571 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package stupidchess.network.controller;
import java.util.logging.*;
import stupidchess.network.datagram.*;
/**
*
* @author Nguyen
*/
public class IncomingMessageHandler implements Runnable {
private static final Logger LOGGER = Logger.getGlobal();
private final MessageTransferrer source;
private final IMessageProcessor processor;
/**
* Start handling the incoming messages from source.
* Message will be continuously retrieve from source and then processed
* by a message processor. The handler will stop if:<br>
* <ul>
* <li>The retrieved message is null (often due to the socket was closed or a connection reset).</li>
* <li>The retrieved message's command is NONE.</li>
* </ul>
*/
@Override
public void run() {
LOGGER.log(Level.INFO, String.format("Message handler thread #%d started, handling message from %s...", Thread.currentThread().getId(), source.getSocket().getRemoteSocketAddress().toString()));
MessageObject message;
while (true) {
message = source.getMessage();
processor.process(message, source);
if (message == null) {
break;
} else if (message.getCommand() == Command.NONE) {
break;
}
}
LOGGER.log(Level.INFO, String.format("Message handler thread #%d stopped.", Thread.currentThread().getId()));
}
/**
* Construct a message handler.
* @param source The source to retrieve the messages.
* @param processor The processor used to process messaged.
*/
public IncomingMessageHandler(MessageTransferrer source, IMessageProcessor processor) {
this.source = source;
this.processor = processor;
}
}
| UTF-8 | Java | 1,773 | java | IncomingMessageHandler.java | Java | [
{
"context": "stupidchess.network.datagram.*;\n\n/**\n *\n * @author Nguyen\n */\npublic class IncomingMessageHandler implement",
"end": 132,
"score": 0.9996030926704407,
"start": 126,
"tag": "NAME",
"value": "Nguyen"
}
]
| null | []
| package stupidchess.network.controller;
import java.util.logging.*;
import stupidchess.network.datagram.*;
/**
*
* @author Nguyen
*/
public class IncomingMessageHandler implements Runnable {
private static final Logger LOGGER = Logger.getGlobal();
private final MessageTransferrer source;
private final IMessageProcessor processor;
/**
* Start handling the incoming messages from source.
* Message will be continuously retrieve from source and then processed
* by a message processor. The handler will stop if:<br>
* <ul>
* <li>The retrieved message is null (often due to the socket was closed or a connection reset).</li>
* <li>The retrieved message's command is NONE.</li>
* </ul>
*/
@Override
public void run() {
LOGGER.log(Level.INFO, String.format("Message handler thread #%d started, handling message from %s...", Thread.currentThread().getId(), source.getSocket().getRemoteSocketAddress().toString()));
MessageObject message;
while (true) {
message = source.getMessage();
processor.process(message, source);
if (message == null) {
break;
} else if (message.getCommand() == Command.NONE) {
break;
}
}
LOGGER.log(Level.INFO, String.format("Message handler thread #%d stopped.", Thread.currentThread().getId()));
}
/**
* Construct a message handler.
* @param source The source to retrieve the messages.
* @param processor The processor used to process messaged.
*/
public IncomingMessageHandler(MessageTransferrer source, IMessageProcessor processor) {
this.source = source;
this.processor = processor;
}
}
| 1,773 | 0.645234 | 0.645234 | 48 | 35.9375 | 37.015991 | 201 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.479167 | false | false | 15 |
7d428e2e1a3067d3e35042bf7aa5988236da96bd | 2,156,073,585,637 | f28a7bd1768569f54ea4dd61b900fc21a70d2cbe | /src/main/java/org/flinnfoundation/repository/VitalSignsRepository.java | 31ff8b1057ef1d7511d96eeac92214d55b6c0521 | []
| no_license | flinn-foundation/mimqip-patient-service | https://github.com/flinn-foundation/mimqip-patient-service | 0975275f1ce51d1135b3df13e3b8416dc4c6a4f5 | 7cc4a39ce73bec8e3cdd54539081f03704050a99 | refs/heads/master | 2021-01-19T16:45:57.934000 | 2017-05-01T14:14:18 | 2017-05-01T14:14:18 | 88,285,064 | 1 | 0 | null | false | 2017-05-01T14:14:19 | 2017-04-14T16:42:00 | 2017-04-14T16:45:08 | 2017-05-01T14:14:19 | 2,713 | 1 | 0 | 0 | Java | null | null | package org.flinnfoundation.repository;
import org.flinnfoundation.model.vitals.VitalSigns;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VitalSignsRepository extends CrudRepository<VitalSigns, Long> {
}
| UTF-8 | Java | 299 | java | VitalSignsRepository.java | Java | []
| null | []
| package org.flinnfoundation.repository;
import org.flinnfoundation.model.vitals.VitalSigns;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VitalSignsRepository extends CrudRepository<VitalSigns, Long> {
}
| 299 | 0.856187 | 0.856187 | 10 | 28.9 | 28.38468 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
cc499707ba625e9c2e626f2df3e450aa5ba24408 | 31,018,253,838,517 | cdbbd1460c4ab3753cafba2ac57611a7c18635d0 | /src/main/java/cn/imp/bootplus/BootPlusApplication.java | 0dc35193e043f2611ffee1e20e23b5e806082c37 | []
| no_license | jilining521/bootPlus | https://github.com/jilining521/bootPlus | ac2970103c7fc36a122c63c1b5f1871648b76282 | 25e84253a4e957bfed77b11f5118207fea14d9f3 | refs/heads/master | 2020-04-02T16:49:38.472000 | 2018-10-31T09:36:16 | 2018-10-31T09:36:16 | 150,524,155 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.imp.bootplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.imp.bootplus.mapper")
public class BootPlusApplication {
public static void main(String[] args) {
SpringApplication.run(BootPlusApplication.class, args);
}
}
| UTF-8 | Java | 398 | java | BootPlusApplication.java | Java | []
| null | []
| package cn.imp.bootplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.imp.bootplus.mapper")
public class BootPlusApplication {
public static void main(String[] args) {
SpringApplication.run(BootPlusApplication.class, args);
}
}
| 398 | 0.821608 | 0.821608 | 14 | 27.428572 | 23.014635 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 15 |
bce7406ef86c043c422451f7bf9130194c153050 | 29,248,727,331,330 | e8c01abf2141306e3ded2ee762b15ca5a70b5a22 | /src/main/java/org/java/practice/java/MethodAccessFlag.java | 5096eaf6df44be77eb1d20575d5b5353bd01ecd1 | []
| no_license | soldiers1989/Jvm_Java_Spring | https://github.com/soldiers1989/Jvm_Java_Spring | f9ebbd6eb5ff6c307267e0f4cd9a67b05c88ba0f | 82b264dd126454cdad951165bd0d356021eddf23 | refs/heads/master | 2020-04-02T08:39:26.060000 | 2018-03-20T10:57:12 | 2018-03-20T10:57:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.java.practice.java;
/**
* Created by 晋阳 on 2017/9/24.
*/
public abstract class MethodAccessFlag {
public void func0() {
//共有方法 表明该数据成员、成员函数是对所有用户开放的,所有用户都可以直接进行调用
}
private void func1() {
//私有方法 示私有,私有的意思就是除了class自己之外,任何人都不可以直接使用,私有财产神圣不可侵犯嘛,即便是子女,朋友,都不可以使用。
}
protected void func2() {
//对于子女、朋友来说,就是public的,可以自由使用,没有任何限制,而对于其他的外部class,protected就变成private。
}
static void fun3() {
//static类能够被它自己使用,而不必引用特定的实例;static类能够在它的类的任何对象创建之前被访问,而不必引用任何对象
}
/**
* 将方法声明为final那有两个原因,第一就是说明你已经知道这个方法提供的功能已经满足你要求,不需要进行扩展,
* 并且也不允许任何从此类继承的类来覆写这个方法,但是继承仍然可以继承这个方法,也就是说可以直接使用。
* 第二就是允许编译器将所有对此方法的调用转化为inline调用的机制,它会使你在调用final方法时,直接将
* 方法主体插入到调用处,而不是进行例行的方法调用,例如保存断点,压栈等,这样可能会使你的程序效率有所提高,
* 然而当你的方法主体非常庞大时,或你在多处调用此方法,那么你的调用主体代码便会迅速膨胀,可能反而会影响效率,
* 所以你要慎用final进行方法定义。
*/
final void fun4() {
}
synchronized void fun5() {
//同步方法,一个线程如果想要调用该方法必须获得锁才能执行
}
/**
* JAVA的native方法适用的情况:
1、为了使用底层的主机平台的某个特性,而这个特性不能通过JAVA API访问。
2、为了访问一个老的系统或者使用一个已有的库,而这个系统或这个库不是用JAVA编写的。
3、为了加快程序的性能,而将一段时间敏感的代码作为本地方法实现。
其实就是JNI。
native是方法修饰符。Native方法是由另外一种语言(如c/c++,FORTRAN,汇编)实现的本地方法。
因为在外部实现了方法,所以在java代码中,就不需要声明了,有点类似于借口方法。
Native可以和其他一些修饰符连用,但是abstract方法和Interface方法不能用native来修饰。
*/
native void fun6();
/**
抽象类不能被实例化。
抽象方法是只有方法声明,而没有方法的实现内容。
一个类中,只要有一个抽象方法,这个类必须被声明为抽象类
抽象方法在非抽象子类中必须被重写。
*/
abstract void fun7();
/**
* strict float point (精确浮点)
* strictfp 关键字可应用于类、接口或方法。使用 strictfp 关键字声明一个方法时,该方法中所有的
* float和double表达式都严格遵守FP-strict的限制,符合IEEE-754规范。
* 当对一个类或接口使用 strictfp 关键字时,该类中的所有代码,包括嵌套类型中的初始设定值和代码,
* 都将严格地进行计算。严格约束意味着所有表达式的结果都必须是 IEEE 754 算法对操作数预期的结果,
* 以单精度和双精度格式表示。
*
* 如果你想让你的浮点运算更加精确,而且不会因为不同的硬件平台所执行的结果不一致的话,可以用关键字strictfp.
*/
strictfp void fun8() {
}
/**
* synthetic总的来说,是由编译器引入的字段、方法、类或其他结构,主要用于JVM内部使用,为了遵循某些规范
* 而作的一些小技巧从而绕过这些规范,有点作弊的感觉,只不过是由编译器光明正大的,人为是没有权限的(但事实
* 上有时候还是能被利用到的)。
*/
void fun9() {
this.getClass().isSynthetic();
}
public void execFun7() {
fun7();
}
}
| UTF-8 | Java | 4,356 | java | MethodAccessFlag.java | Java | [
{
"context": "package org.java.practice.java;\n\n/**\n * Created by 晋阳 on 2017/9/24.\n */\npublic abstract class MethodAc",
"end": 52,
"score": 0.7904044389724731,
"start": 51,
"tag": "NAME",
"value": "晋"
},
{
"context": "ackage org.java.practice.java;\n\n/**\n * Created by 晋阳 on 2017/9/24.\n */\npublic abstract class MethodAcc",
"end": 53,
"score": 0.832838773727417,
"start": 51,
"tag": "USERNAME",
"value": "晋阳"
}
]
| null | []
| package org.java.practice.java;
/**
* Created by 晋阳 on 2017/9/24.
*/
public abstract class MethodAccessFlag {
public void func0() {
//共有方法 表明该数据成员、成员函数是对所有用户开放的,所有用户都可以直接进行调用
}
private void func1() {
//私有方法 示私有,私有的意思就是除了class自己之外,任何人都不可以直接使用,私有财产神圣不可侵犯嘛,即便是子女,朋友,都不可以使用。
}
protected void func2() {
//对于子女、朋友来说,就是public的,可以自由使用,没有任何限制,而对于其他的外部class,protected就变成private。
}
static void fun3() {
//static类能够被它自己使用,而不必引用特定的实例;static类能够在它的类的任何对象创建之前被访问,而不必引用任何对象
}
/**
* 将方法声明为final那有两个原因,第一就是说明你已经知道这个方法提供的功能已经满足你要求,不需要进行扩展,
* 并且也不允许任何从此类继承的类来覆写这个方法,但是继承仍然可以继承这个方法,也就是说可以直接使用。
* 第二就是允许编译器将所有对此方法的调用转化为inline调用的机制,它会使你在调用final方法时,直接将
* 方法主体插入到调用处,而不是进行例行的方法调用,例如保存断点,压栈等,这样可能会使你的程序效率有所提高,
* 然而当你的方法主体非常庞大时,或你在多处调用此方法,那么你的调用主体代码便会迅速膨胀,可能反而会影响效率,
* 所以你要慎用final进行方法定义。
*/
final void fun4() {
}
synchronized void fun5() {
//同步方法,一个线程如果想要调用该方法必须获得锁才能执行
}
/**
* JAVA的native方法适用的情况:
1、为了使用底层的主机平台的某个特性,而这个特性不能通过JAVA API访问。
2、为了访问一个老的系统或者使用一个已有的库,而这个系统或这个库不是用JAVA编写的。
3、为了加快程序的性能,而将一段时间敏感的代码作为本地方法实现。
其实就是JNI。
native是方法修饰符。Native方法是由另外一种语言(如c/c++,FORTRAN,汇编)实现的本地方法。
因为在外部实现了方法,所以在java代码中,就不需要声明了,有点类似于借口方法。
Native可以和其他一些修饰符连用,但是abstract方法和Interface方法不能用native来修饰。
*/
native void fun6();
/**
抽象类不能被实例化。
抽象方法是只有方法声明,而没有方法的实现内容。
一个类中,只要有一个抽象方法,这个类必须被声明为抽象类
抽象方法在非抽象子类中必须被重写。
*/
abstract void fun7();
/**
* strict float point (精确浮点)
* strictfp 关键字可应用于类、接口或方法。使用 strictfp 关键字声明一个方法时,该方法中所有的
* float和double表达式都严格遵守FP-strict的限制,符合IEEE-754规范。
* 当对一个类或接口使用 strictfp 关键字时,该类中的所有代码,包括嵌套类型中的初始设定值和代码,
* 都将严格地进行计算。严格约束意味着所有表达式的结果都必须是 IEEE 754 算法对操作数预期的结果,
* 以单精度和双精度格式表示。
*
* 如果你想让你的浮点运算更加精确,而且不会因为不同的硬件平台所执行的结果不一致的话,可以用关键字strictfp.
*/
strictfp void fun8() {
}
/**
* synthetic总的来说,是由编译器引入的字段、方法、类或其他结构,主要用于JVM内部使用,为了遵循某些规范
* 而作的一些小技巧从而绕过这些规范,有点作弊的感觉,只不过是由编译器光明正大的,人为是没有权限的(但事实
* 上有时候还是能被利用到的)。
*/
void fun9() {
this.getClass().isSynthetic();
}
public void execFun7() {
fun7();
}
}
| 4,356 | 0.677405 | 0.664701 | 87 | 24.333334 | 23.001583 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.068966 | false | false | 15 |
61b84c53677fd52e643fa57bf99dab39d8d8b787 | 12,043,088,344,533 | 27d5dbdbd1d86bc6a6ac2cef53379b443f864dda | /道路养护/src/main/java/com/chengtech/chengtechmt/adapter/sidemonitor/VibratingWireDataAdapter.java | c86069af5c8423bb35e5e85ad3e7fc9f7186b70a | []
| no_license | chengtech/Application1 | https://github.com/chengtech/Application1 | ce7dc31b55d1a04ecbcb02fb07ed5f79f7fc1640 | 63bfb2b630f246ae7635a4a8304b8d4906d9c257 | refs/heads/master | 2020-12-02T19:42:15.224000 | 2018-02-12T06:53:57 | 2018-02-12T06:53:57 | 96,377,008 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chengtech.chengtechmt.adapter.sidemonitor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.chengtech.chengtechmt.R;
import com.chengtech.chengtechmt.entity.monitoremergency.Lvdtdata;
import com.chengtech.chengtechmt.entity.monitoremergency.VibratingWireData;
import com.chengtech.chengtechmt.util.DateUtils;
import java.util.List;
/**
* 作者: LiuFuYingWang on 2017/11/27 16:32.
* 地下水位adapter
*/
public class VibratingWireDataAdapter extends RecyclerView.Adapter {
private List<VibratingWireData> data;
public VibratingWireDataAdapter(List<VibratingWireData> data) {
this.data = data;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vibratingwiredataa, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyViewHolder viewHolder = (MyViewHolder) holder;
if (position == 0) {
viewHolder.tv1.setText("模块号");
viewHolder.tv2.setText("通道号");
viewHolder.tv3.setText("频率值");
viewHolder.tv4.setText("温度值");
viewHolder.tv5.setText("地下水位值");
viewHolder.tv6.setText("采集时间");
} else {
VibratingWireData vibratingWireData = data.get(position - 1);
viewHolder.tv1.setText(vibratingWireData.moduleNo);
viewHolder.tv2.setText(vibratingWireData.channelId);
viewHolder.tv3.setText(String.valueOf(vibratingWireData.frequencyValue));
viewHolder.tv4.setText(String.valueOf(vibratingWireData.temperatureValue));
viewHolder.tv5.setText(String.valueOf(vibratingWireData.physicalValue));
viewHolder.tv6.setText(DateUtils.convertDate3(vibratingWireData.acquisitionDatetime));
}
}
@Override
public int getItemCount() {
return data.size() + 1;
}
private class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tv1, tv2, tv3, tv4, tv5, tv6;
public MyViewHolder(View itemView) {
super(itemView);
tv1 = (TextView) itemView.findViewById(R.id.tv1);
tv2 = (TextView) itemView.findViewById(R.id.tv2);
tv3 = (TextView) itemView.findViewById(R.id.tv3);
tv4 = (TextView) itemView.findViewById(R.id.tv4);
tv5 = (TextView) itemView.findViewById(R.id.tv5);
tv6 = (TextView) itemView.findViewById(R.id.tv6);
}
}
}
| UTF-8 | Java | 2,836 | java | VibratingWireDataAdapter.java | Java | [
{
"context": "til.DateUtils;\n\nimport java.util.List;\n\n/**\n * 作者: LiuFuYingWang on 2017/11/27 16:32.\n * 地下水位adapter\n */\n\npublic c",
"end": 506,
"score": 0.9998520016670227,
"start": 493,
"tag": "NAME",
"value": "LiuFuYingWang"
}
]
| null | []
| package com.chengtech.chengtechmt.adapter.sidemonitor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.chengtech.chengtechmt.R;
import com.chengtech.chengtechmt.entity.monitoremergency.Lvdtdata;
import com.chengtech.chengtechmt.entity.monitoremergency.VibratingWireData;
import com.chengtech.chengtechmt.util.DateUtils;
import java.util.List;
/**
* 作者: LiuFuYingWang on 2017/11/27 16:32.
* 地下水位adapter
*/
public class VibratingWireDataAdapter extends RecyclerView.Adapter {
private List<VibratingWireData> data;
public VibratingWireDataAdapter(List<VibratingWireData> data) {
this.data = data;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vibratingwiredataa, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyViewHolder viewHolder = (MyViewHolder) holder;
if (position == 0) {
viewHolder.tv1.setText("模块号");
viewHolder.tv2.setText("通道号");
viewHolder.tv3.setText("频率值");
viewHolder.tv4.setText("温度值");
viewHolder.tv5.setText("地下水位值");
viewHolder.tv6.setText("采集时间");
} else {
VibratingWireData vibratingWireData = data.get(position - 1);
viewHolder.tv1.setText(vibratingWireData.moduleNo);
viewHolder.tv2.setText(vibratingWireData.channelId);
viewHolder.tv3.setText(String.valueOf(vibratingWireData.frequencyValue));
viewHolder.tv4.setText(String.valueOf(vibratingWireData.temperatureValue));
viewHolder.tv5.setText(String.valueOf(vibratingWireData.physicalValue));
viewHolder.tv6.setText(DateUtils.convertDate3(vibratingWireData.acquisitionDatetime));
}
}
@Override
public int getItemCount() {
return data.size() + 1;
}
private class MyViewHolder extends RecyclerView.ViewHolder {
public TextView tv1, tv2, tv3, tv4, tv5, tv6;
public MyViewHolder(View itemView) {
super(itemView);
tv1 = (TextView) itemView.findViewById(R.id.tv1);
tv2 = (TextView) itemView.findViewById(R.id.tv2);
tv3 = (TextView) itemView.findViewById(R.id.tv3);
tv4 = (TextView) itemView.findViewById(R.id.tv4);
tv5 = (TextView) itemView.findViewById(R.id.tv5);
tv6 = (TextView) itemView.findViewById(R.id.tv6);
}
}
}
| 2,836 | 0.686556 | 0.669662 | 76 | 35.605263 | 29.481073 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 15 |
2bd5eec6f389679631285e6377a077fc1148bb63 | 10,763,188,072,716 | 8910ce44029be99b6271e2f18b5f27e9517ba5fd | /app/src/main/java/com/nobodyknows/chatwithme/Activities/Dashboard/AddNewCall.java | 6a347bd7583c96299b16eb64923da9c51e7a57ea | []
| no_license | Vikram2921/ChatWithMe | https://github.com/Vikram2921/ChatWithMe | fe1f50f3bb907bfcc3aca57893197196ac4dc715 | f1d00047bc7064ecc14d91f757f3a745971a4e48 | refs/heads/master | 2023-05-20T01:46:14.437000 | 2021-06-07T10:37:36 | 2021-06-07T10:37:36 | 367,885,036 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nobodyknows.chatwithme.Activities.Dashboard;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.NobodyKnows.chatlayoutview.Model.User;
import com.google.firebase.firestore.ListenerRegistration;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import com.nobodyknows.chatwithme.Activities.AudioCall;
import com.nobodyknows.chatwithme.Activities.Dashboard.Adapters.AddCallRecyclerViewAdapter;
import com.nobodyknows.chatwithme.Activities.Dashboard.Adapters.ContactsRecyclerViewAdapter;
import com.nobodyknows.chatwithme.Activities.Dashboard.Interfaces.AddCallListener;
import com.nobodyknows.chatwithme.Activities.Dashboard.Interfaces.SelectListener;
import com.nobodyknows.chatwithme.Activities.SearchFreinds;
import com.nobodyknows.chatwithme.Activities.SyncContacts;
import com.nobodyknows.chatwithme.R;
import com.nobodyknows.chatwithme.services.MessageMaker;
import java.util.ArrayList;
import java.util.List;
public class AddNewCall extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<User> contacts = new ArrayList<>();
private ArrayList<String> contactsAdded = new ArrayList<>();
private AddCallRecyclerViewAdapter recyclerViewAdapter;
private ConstraintLayout notfound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_call);
getSupportActionBar().setTitle("Add new call");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
init();
}
private void init() {
recyclerView = findViewById(R.id.contactList);
notfound = findViewById(R.id.notfound);
recyclerViewAdapter = new AddCallRecyclerViewAdapter(AddNewCall.this,getApplicationContext(), contacts, new AddCallListener() {
@Override
public void onVideoCall(User user) {
Intent intent = new Intent(getApplicationContext(), AudioCall.class);
intent.putExtra("username",user.getContactNumber());
intent.putExtra("making",true);
intent.putExtra("video",true);
startActivity(intent);
finish();
}
@Override
public void onAudioCall(User user) {
Intent intent = new Intent(getApplicationContext(), AudioCall.class);
intent.putExtra("username",user.getContactNumber());
intent.putExtra("making",true);
intent.putExtra("video",false);
startActivity(intent);
finish();
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setReverseLayout(false);
layoutManager.setItemPrefetchEnabled(true);
layoutManager.setSmoothScrollbarEnabled(true);
layoutManager.setInitialPrefetchItemCount(5);
layoutManager.setRecycleChildrenOnDetach(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(recyclerViewAdapter);
loadUsers();
}
private void loadUsers() {
contacts.clear();
ArrayList<User> contactsTemp = MessageMaker.getDatabaseHelper().getAllUsers();
if(contactsTemp.size() > 0) {
MessageMaker.hideNotFound(notfound);
for (User user : contactsTemp) {
if (!contactsAdded.contains(user.getContactNumber())) {
contacts.add(user);
contactsAdded.add(user.getContactNumber());
recyclerViewAdapter.notifyItemInserted(contacts.size() - 1);
}
}
}
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
break;
}
return true;
}
} | UTF-8 | Java | 4,470 | java | AddNewCall.java | Java | []
| null | []
| package com.nobodyknows.chatwithme.Activities.Dashboard;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.NobodyKnows.chatlayoutview.Model.User;
import com.google.firebase.firestore.ListenerRegistration;
import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import com.nobodyknows.chatwithme.Activities.AudioCall;
import com.nobodyknows.chatwithme.Activities.Dashboard.Adapters.AddCallRecyclerViewAdapter;
import com.nobodyknows.chatwithme.Activities.Dashboard.Adapters.ContactsRecyclerViewAdapter;
import com.nobodyknows.chatwithme.Activities.Dashboard.Interfaces.AddCallListener;
import com.nobodyknows.chatwithme.Activities.Dashboard.Interfaces.SelectListener;
import com.nobodyknows.chatwithme.Activities.SearchFreinds;
import com.nobodyknows.chatwithme.Activities.SyncContacts;
import com.nobodyknows.chatwithme.R;
import com.nobodyknows.chatwithme.services.MessageMaker;
import java.util.ArrayList;
import java.util.List;
public class AddNewCall extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList<User> contacts = new ArrayList<>();
private ArrayList<String> contactsAdded = new ArrayList<>();
private AddCallRecyclerViewAdapter recyclerViewAdapter;
private ConstraintLayout notfound;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_call);
getSupportActionBar().setTitle("Add new call");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
init();
}
private void init() {
recyclerView = findViewById(R.id.contactList);
notfound = findViewById(R.id.notfound);
recyclerViewAdapter = new AddCallRecyclerViewAdapter(AddNewCall.this,getApplicationContext(), contacts, new AddCallListener() {
@Override
public void onVideoCall(User user) {
Intent intent = new Intent(getApplicationContext(), AudioCall.class);
intent.putExtra("username",user.getContactNumber());
intent.putExtra("making",true);
intent.putExtra("video",true);
startActivity(intent);
finish();
}
@Override
public void onAudioCall(User user) {
Intent intent = new Intent(getApplicationContext(), AudioCall.class);
intent.putExtra("username",user.getContactNumber());
intent.putExtra("making",true);
intent.putExtra("video",false);
startActivity(intent);
finish();
}
});
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setReverseLayout(false);
layoutManager.setItemPrefetchEnabled(true);
layoutManager.setSmoothScrollbarEnabled(true);
layoutManager.setInitialPrefetchItemCount(5);
layoutManager.setRecycleChildrenOnDetach(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(recyclerViewAdapter);
loadUsers();
}
private void loadUsers() {
contacts.clear();
ArrayList<User> contactsTemp = MessageMaker.getDatabaseHelper().getAllUsers();
if(contactsTemp.size() > 0) {
MessageMaker.hideNotFound(notfound);
for (User user : contactsTemp) {
if (!contactsAdded.contains(user.getContactNumber())) {
contacts.add(user);
contactsAdded.add(user.getContactNumber());
recyclerViewAdapter.notifyItemInserted(contacts.size() - 1);
}
}
}
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
break;
}
return true;
}
} | 4,470 | 0.691946 | 0.689485 | 111 | 39.279278 | 25.897987 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747748 | false | false | 15 |
a5b910f672543733730a7df2d8ead4bcb1d9fb8e | 21,320,217,710,366 | 75c482cc6c40d5230b26f46ce61d0ba560332ab8 | /shuchaowen-servlet/src/main/java/scw/servlet/mvc/http/HttpServletChannelUserSessionFactory.java | 22e68592c8a5214ee7ef1512adb75c79a7be227c | []
| no_license | wcnnkh/shuchaowen | https://github.com/wcnnkh/shuchaowen | ab3866796b03384f0383e1e821b2fbb994a148c6 | fd2bb45f6854810d27457f4ff831de9a0603aaae | refs/heads/master | 2020-03-29T05:48:36.037000 | 2020-03-27T10:21:48 | 2020-03-27T10:21:48 | 149,597,393 | 9 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package scw.servlet.mvc.http;
import javax.servlet.http.HttpSession;
import scw.logger.Logger;
import scw.logger.LoggerFactory;
import scw.mvc.http.HttpChannel;
import scw.mvc.http.session.HttpChannelUserSessionFactory;
import scw.security.session.UserSession;
public final class HttpServletChannelUserSessionFactory<T> implements HttpChannelUserSessionFactory<T> {
private static Logger logger = LoggerFactory.getLogger(HttpServletChannelUserSessionFactory.class);
private String uidAttributeName;
public HttpServletChannelUserSessionFactory(String uidAttributeName) {
this.uidAttributeName = uidAttributeName;
}
public UserSession<T> getUserSession(HttpChannel httpChannel) {
if (!(httpChannel instanceof HttpServletChannel)) {
logger.warn("{} not a HttpServletRequest", httpChannel.getRequest().getControllerPath());
return null;
}
HttpServletChannel httpServletChannel = (HttpServletChannel) httpChannel;
HttpSession httpSession = httpServletChannel.getRequest().getHttpServletRequest().getSession();
if (httpSession == null) {
return null;
}
return new HttpServletUserSession<T>(httpSession, uidAttributeName);
}
public UserSession<T> createUserSession(HttpChannel httpChannel, T uid) {
if (!(httpChannel instanceof HttpServletChannel)) {
logger.warn("{} not a HttpServletRequest", httpChannel.getRequest().getControllerPath());
return null;
}
HttpServletChannel httpServletChannel = (HttpServletChannel) httpChannel;
HttpSession httpSession = httpServletChannel.getRequest().getHttpServletRequest().getSession(true);
if (httpSession == null) {
return null;
}
HttpServletUserSession<T> session = new HttpServletUserSession<T>(httpSession, uidAttributeName);
session.setUid(uid);
return session;
}
}
| UTF-8 | Java | 1,826 | java | HttpServletChannelUserSessionFactory.java | Java | []
| null | []
| package scw.servlet.mvc.http;
import javax.servlet.http.HttpSession;
import scw.logger.Logger;
import scw.logger.LoggerFactory;
import scw.mvc.http.HttpChannel;
import scw.mvc.http.session.HttpChannelUserSessionFactory;
import scw.security.session.UserSession;
public final class HttpServletChannelUserSessionFactory<T> implements HttpChannelUserSessionFactory<T> {
private static Logger logger = LoggerFactory.getLogger(HttpServletChannelUserSessionFactory.class);
private String uidAttributeName;
public HttpServletChannelUserSessionFactory(String uidAttributeName) {
this.uidAttributeName = uidAttributeName;
}
public UserSession<T> getUserSession(HttpChannel httpChannel) {
if (!(httpChannel instanceof HttpServletChannel)) {
logger.warn("{} not a HttpServletRequest", httpChannel.getRequest().getControllerPath());
return null;
}
HttpServletChannel httpServletChannel = (HttpServletChannel) httpChannel;
HttpSession httpSession = httpServletChannel.getRequest().getHttpServletRequest().getSession();
if (httpSession == null) {
return null;
}
return new HttpServletUserSession<T>(httpSession, uidAttributeName);
}
public UserSession<T> createUserSession(HttpChannel httpChannel, T uid) {
if (!(httpChannel instanceof HttpServletChannel)) {
logger.warn("{} not a HttpServletRequest", httpChannel.getRequest().getControllerPath());
return null;
}
HttpServletChannel httpServletChannel = (HttpServletChannel) httpChannel;
HttpSession httpSession = httpServletChannel.getRequest().getHttpServletRequest().getSession(true);
if (httpSession == null) {
return null;
}
HttpServletUserSession<T> session = new HttpServletUserSession<T>(httpSession, uidAttributeName);
session.setUid(uid);
return session;
}
}
| 1,826 | 0.771084 | 0.771084 | 51 | 33.803921 | 34.699844 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.745098 | false | false | 15 |
7923caa78619c8f5cefd21e4fc16006b769404c6 | 31,817,117,768,211 | 38ff10d1830845d74c0a4b6dc65d76f24ac7e8f8 | /src/main/java/com/qfedu/pojo/Grade.java | 8ff51169a27df92e16408c7da067e44ce8e050b9 | []
| no_license | anjmin/Tick_Office | https://github.com/anjmin/Tick_Office | 5f25cadca44210f101837abc572582e9bb2f811d | 12cb73bf554b91d8cd30a9870f0570fb46bf4612 | refs/heads/master | 2022-12-20T13:19:15.711000 | 2019-06-22T14:15:12 | 2019-06-22T14:15:12 | 191,899,161 | 0 | 0 | null | false | 2022-12-15T23:48:35 | 2019-06-14T07:44:20 | 2019-06-22T14:14:50 | 2022-12-15T23:48:32 | 1,768 | 0 | 0 | 11 | HTML | false | false | package com.qfedu.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* Created by Administrator on 2019/6/18 0018.
*/
public class Grade {
//id
private Integer id;
//班级名字
private String name;
//标记位
private Integer flag;
//周期
private int week;
//开班日期
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createdate;
//位置
private String location;
//学科编号
private int cid;
/*//嵌套学科
private Course course;
//嵌套学生
private List<Student> studentList;*/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
public int getWeek() {
return week;
}
public void setWeek(int week) {
this.week = week;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Grade{" +
"id=" + id +
", name='" + name + '\'' +
", flag=" + flag +
", week=" + week +
", createdate=" + createdate +
", location='" + location + '\'' +
", cid=" + cid +
'}';
}
}
| UTF-8 | Java | 1,941 | java | Grade.java | Java | [
{
"context": "Format;\n\nimport java.util.Date;\n\n/**\n * Created by Administrator on 2019/6/18 0018.\n */\npublic class Grade {\n\n ",
"end": 142,
"score": 0.8635258674621582,
"start": 129,
"tag": "NAME",
"value": "Administrator"
}
]
| null | []
| package com.qfedu.pojo;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
/**
* Created by Administrator on 2019/6/18 0018.
*/
public class Grade {
//id
private Integer id;
//班级名字
private String name;
//标记位
private Integer flag;
//周期
private int week;
//开班日期
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date createdate;
//位置
private String location;
//学科编号
private int cid;
/*//嵌套学科
private Course course;
//嵌套学生
private List<Student> studentList;*/
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getFlag() {
return flag;
}
public void setFlag(Integer flag) {
this.flag = flag;
}
public int getWeek() {
return week;
}
public void setWeek(int week) {
this.week = week;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Grade{" +
"id=" + id +
", name='" + name + '\'' +
", flag=" + flag +
", week=" + week +
", createdate=" + createdate +
", location='" + location + '\'' +
", cid=" + cid +
'}';
}
}
| 1,941 | 0.520933 | 0.515103 | 103 | 17.320389 | 15.158204 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.320388 | false | false | 15 |
f2b2aa2974c00c71724afa20722b8226ccc2437b | 23,295,902,662,962 | 47caf6ddfe602e18c598e481a5198232bdddf406 | /app/src/main/java/com/example/emery/contact/constant/Constants.java | 65ee8e454d24d4afe28316571828c951d2a953cc | []
| no_license | ZMNOTZ/Contact | https://github.com/ZMNOTZ/Contact | 308934a1b84980ec2d4604f098fa22fb8492cc54 | ec2f6f6bb123fffac8fcd2f9f0305e781253f567 | refs/heads/master | 2021-06-28T13:55:09.559000 | 2017-09-16T03:24:42 | 2017-09-16T03:24:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.emery.contact.constant;
import android.provider.ContactsContract;
/**
* Created by emery on 2017/4/22.
*/
public class Constants {
public static class Contact {
public static final int CONTACT_REQUST_CODE = 1 << 1;
public static final String[] PHONES_PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract
.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
}
public static final String INDEX="INDEX";
public static String ISFORMACREATE="isFromCreate";
public static final int CALL_REQUEST_CODE=1<<2;
public static final int SD_REQUEST_CODE=1<<3;
}
| UTF-8 | Java | 792 | java | Constants.java | Java | [
{
"context": "roid.provider.ContactsContract;\n\n/**\n * Created by emery on 2017/4/22.\n */\n\npublic class Constants {\n\n ",
"end": 111,
"score": 0.9980343580245972,
"start": 106,
"tag": "USERNAME",
"value": "emery"
}
]
| null | []
| package com.example.emery.contact.constant;
import android.provider.ContactsContract;
/**
* Created by emery on 2017/4/22.
*/
public class Constants {
public static class Contact {
public static final int CONTACT_REQUST_CODE = 1 << 1;
public static final String[] PHONES_PROJECTION = new String[]{
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract
.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_ID,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
}
public static final String INDEX="INDEX";
public static String ISFORMACREATE="isFromCreate";
public static final int CALL_REQUEST_CODE=1<<2;
public static final int SD_REQUEST_CODE=1<<3;
}
| 792 | 0.698232 | 0.681818 | 23 | 33.391304 | 29.84123 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 15 |
b82a9ff616e02487627bdedf09f7c5ff4905450a | 23,295,902,661,847 | fc2ebd4c2cc43ec9ac86cef4b43d59949edaeb7f | /4week/src/test/java/com/whiteship/homework/queue/QueueTest.java | 081b235eef4b348d3b28feaa401b204e64ac7f19 | []
| no_license | LeeGiCheol/whiteship-live-study | https://github.com/LeeGiCheol/whiteship-live-study | b1962a971d262ef27d98c17726cdc5ab4c7c1d02 | a2e8232248eb9f4a960b717e257622a1f655fa81 | refs/heads/master | 2023-02-11T18:09:22.513000 | 2021-01-02T18:27:05 | 2021-01-02T18:27:05 | 321,315,448 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.whiteship.homework.queue;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
class QueueTest {
static Queue queue;
@BeforeEach
void setup() {
queue = new Queue(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
}
@Test
@DisplayName("큐에 값이 없는지 확인한다.")
void isEmptyTest() {
queue.clear();
assertTrue(queue.isEmpty());
}
@Test
@DisplayName("큐에 값이 찼는지 확인한다.")
void isFullTest() {
assertTrue(queue.isFull());
}
@Test
@DisplayName("큐에 값을 모두 삭제한다.")
void clearTest() {
queue.clear();
assertEquals(0, queue.size());
}
@Test
@DisplayName("큐에 값을 넣는다.")
void enqueueTest() {
queue.clear();
queue.enqueue(30);
queue.enqueue(40);
assertEquals(30, queue.get(0));
assertEquals(40, queue.get(1));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> queue.get(2));
}
@Test
@DisplayName("큐에서 값을 뺀다.")
void dequeueTest() {
assertEquals(5, queue.size());
queue.dequeue();
assertEquals(4, queue.size());
assertEquals(20, queue.peek());
queue.dequeue();
assertEquals(30, queue.peek());
queue.dequeue();
queue.dequeue();
queue.dequeue();
assertEquals(0, queue.size());
}
} | UTF-8 | Java | 1,566 | java | QueueTest.java | Java | []
| null | []
| package com.whiteship.homework.queue;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
class QueueTest {
static Queue queue;
@BeforeEach
void setup() {
queue = new Queue(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
queue.enqueue(50);
}
@Test
@DisplayName("큐에 값이 없는지 확인한다.")
void isEmptyTest() {
queue.clear();
assertTrue(queue.isEmpty());
}
@Test
@DisplayName("큐에 값이 찼는지 확인한다.")
void isFullTest() {
assertTrue(queue.isFull());
}
@Test
@DisplayName("큐에 값을 모두 삭제한다.")
void clearTest() {
queue.clear();
assertEquals(0, queue.size());
}
@Test
@DisplayName("큐에 값을 넣는다.")
void enqueueTest() {
queue.clear();
queue.enqueue(30);
queue.enqueue(40);
assertEquals(30, queue.get(0));
assertEquals(40, queue.get(1));
assertThrows(ArrayIndexOutOfBoundsException.class, () -> queue.get(2));
}
@Test
@DisplayName("큐에서 값을 뺀다.")
void dequeueTest() {
assertEquals(5, queue.size());
queue.dequeue();
assertEquals(4, queue.size());
assertEquals(20, queue.peek());
queue.dequeue();
assertEquals(30, queue.peek());
queue.dequeue();
queue.dequeue();
queue.dequeue();
assertEquals(0, queue.size());
}
} | 1,566 | 0.555631 | 0.535278 | 73 | 19.205479 | 15.877061 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.547945 | false | false | 15 |
f0deed4671770ebbcd89617f06632db8366f42ea | 12,524,124,664,981 | fe8b0a520bd817e2c7b679bea9eca43cf81f4a3e | /info-srm/src/main/java/com/info/infosrm/service/impl/ScoreServiceImpl.java | 89b1b71497ec40a39999330513a8602bd0ff51c3 | []
| no_license | forhcl/Student-Information-Management-System | https://github.com/forhcl/Student-Information-Management-System | ad7c82f14be5820ccf609be64b3f114e61a3f5d7 | bc59fa3b883c5cea869950a3bc9bb54af00f8c9e | refs/heads/master | 2020-09-16T18:46:43.271000 | 2019-11-25T04:02:01 | 2019-11-25T04:02:01 | 223,857,146 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.info.infosrm.service.impl;
import com.github.pagehelper.PageHelper;
import com.info.infosrm.dao.ScoreMapper;
import com.info.infosrm.entity.Score;
import com.info.infosrm.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Hogan_Lee
* @create 2019-11-23 18:17
*/
@Service
public class ScoreServiceImpl implements ScoreService {
@Autowired
private ScoreMapper scoreMapper;
@Override
public List<Score> findScoreByStudentOrExam(int student_id, int exam_id,int pageNum, int pageSize) {
//如果没有任何一条记录呢,集合为空
//调用pagehelper分页,采用startPage方式。注意:startPage应放在Mapper查询函数之前
PageHelper.startPage(pageNum, pageSize);
PageHelper.orderBy("exam_id ASC");
List<Score> scores=scoreMapper.findScoreByStudentOrExam(student_id, exam_id);
return scores;
}
@Override
public int addOne(Score score) {
return scoreMapper.addOne(score);
}
@Override
public void deleteOne(int exam_id, int student_id) {
scoreMapper.deleteOne(exam_id,student_id);
}
@Override
public int updateScoreByStudentIdAndExamID(Score score) {
return scoreMapper.updateScoreByStudentIdAndExamID(score);
}
}
| UTF-8 | Java | 1,393 | java | ScoreServiceImpl.java | Java | [
{
"context": "e.Service;\n\nimport java.util.List;\n\n/**\n * @author Hogan_Lee\n * @create 2019-11-23 18:17\n */\n@Service\npublic c",
"end": 365,
"score": 0.9960612654685974,
"start": 356,
"tag": "USERNAME",
"value": "Hogan_Lee"
}
]
| null | []
| package com.info.infosrm.service.impl;
import com.github.pagehelper.PageHelper;
import com.info.infosrm.dao.ScoreMapper;
import com.info.infosrm.entity.Score;
import com.info.infosrm.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Hogan_Lee
* @create 2019-11-23 18:17
*/
@Service
public class ScoreServiceImpl implements ScoreService {
@Autowired
private ScoreMapper scoreMapper;
@Override
public List<Score> findScoreByStudentOrExam(int student_id, int exam_id,int pageNum, int pageSize) {
//如果没有任何一条记录呢,集合为空
//调用pagehelper分页,采用startPage方式。注意:startPage应放在Mapper查询函数之前
PageHelper.startPage(pageNum, pageSize);
PageHelper.orderBy("exam_id ASC");
List<Score> scores=scoreMapper.findScoreByStudentOrExam(student_id, exam_id);
return scores;
}
@Override
public int addOne(Score score) {
return scoreMapper.addOne(score);
}
@Override
public void deleteOne(int exam_id, int student_id) {
scoreMapper.deleteOne(exam_id,student_id);
}
@Override
public int updateScoreByStudentIdAndExamID(Score score) {
return scoreMapper.updateScoreByStudentIdAndExamID(score);
}
}
| 1,393 | 0.728929 | 0.719818 | 45 | 28.266666 | 25.537249 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511111 | false | false | 15 |
8eecad1f8da078374a5cb7e5eac649cf3d0b7c73 | 20,418,274,589,662 | 569735b5b975fcc9dd861aeaf9cb3d570b57c15b | /SmartRockets.java | 5d6aae308bdf36857945b7cffb9adb1876317861 | []
| no_license | hardel99/CodingChallenges | https://github.com/hardel99/CodingChallenges | 58d837ed049339e3af6856cedfd5e21740fa70c6 | b68e60fa760129c34214d150ecf94d0a875eaa3a | refs/heads/master | 2020-06-20T10:31:12.178000 | 2019-11-16T19:16:03 | 2019-11-16T19:16:03 | 197,095,563 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | Populate pop;
PVector piniata;
int age = 0;
void setup() {
size(500, 500);
piniata = new PVector(width/2, 50);
pop = new Populate(piniata);
}
void draw() {
background(0);
pop.run();
age++;
if(age >= 500) {
pop.evaluate();
pop.select();
age = 0;
}
rect(250, 240, 300, 20);
ellipse(piniata.x, piniata.y, 30, 30);
}
class Rocket {
PVector pos, vel, acc;
ADN adn;
int counter = 0;
float succes = 0;
boolean isCompleted = false;
boolean isCrahed = false;
int rX = 100;
int rY = 240;
int rW = 300;
int rH = 20;
Rocket() {
pos = new PVector(width/2, height);
vel = new PVector();
acc = new PVector();
adn = new ADN();
}
Rocket(ADN adn) {
pos = new PVector(width/2, height);
vel = new PVector();
acc = new PVector();
this.adn = adn;
}
void addForce(PVector force) {
acc.add(force);
}
void calcSucces(PVector target) {
float dis = dist(pos.x, pos.y, target.x, target.y);
succes = map(dis, 0, width, width, 0);
if(isCompleted) {
succes *= 10;
}
if(isCrahed) {
succes /= 10;
}
}
void refresh(PVector target) {
float dis = dist(pos.x, pos.y, target.x, target.y);
if(dis < 10) {
isCompleted = true;
pos = target.copy();
}
if(pos.x > rX && pos.x < rX + rW && pos.y > rY && pos.y < rY + rH) {
isCrahed = true;
}
if(pos.x < 0 || pos.x > width) {
isCrahed = true;
}
if(pos.y < 0 || pos.y > height) {
isCrahed = true;
}
if(!isCompleted && !isCrahed) {
if(counter < adn.genes.length) {
addForce(adn.genes[counter]);
counter++;
} else{
counter = 0;
}
vel.add(acc);
pos.add(vel);
acc.mult(0);
vel.limit(4);
}
}
void doodle() {
pushMatrix();
noStroke();
fill(255, 200);
translate(pos.x, pos.y);
rotate(vel.heading());
rectMode(CENTER);
rect(0, 0, 20, 4);
popMatrix();
}
}
class Populate {
Rocket[] rockets;
int pob = 100;
PVector target;
ArrayList<Rocket> succesfully = new ArrayList<Rocket>();
Populate(PVector target) {
rockets = new Rocket[pob];
this.target = target;
for (int i = 0; i < rockets.length; i++) {
rockets[i] = new Rocket();
}
}
void evaluate() {
float maxSucces = 0;
for (int i = 0; i < rockets.length; ++i) {
rockets[i].calcSucces(target);
if(rockets[i].succes > maxSucces) {
maxSucces = rockets[i].succes;
}
}
for (int i = 0; i < rockets.length; ++i) {
rockets[i].succes /= maxSucces;
}
succesfully.clear();
for (int i = 0; i < rockets.length; ++i) {
float n = rockets[i].succes * 100;
for (int j = 0; j < n; ++j) {
succesfully.add(rockets[i]);
}
}
}
void select() {
Rocket[] newRockets = new Rocket[pob];
for (int i = 0; i < newRockets.length; ++i) {
Rocket parentA = succesfully.get(floor(random(succesfully.size())));
Rocket parentB = succesfully.get(floor(random(succesfully.size())));
ADN child = parentA.adn.crossover(parentB.adn);
child.mutate();
newRockets[i] = new Rocket(child);
}
rockets = newRockets;
}
void run() {
for (int i = 0; i < rockets.length; i++) {
rockets[i].refresh(target);
rockets[i].doodle();
}
}
}
class ADN {
int lifespawn = 500;
PVector[] genes = new PVector[lifespawn];
ADN() {
for (int i = 0; i < genes.length; ++i) {
genes[i] = PVector.random2D();
genes[i].setMag(0.3);
}
}
ADN(PVector[] genes) {
this.genes = genes;
}
ADN crossover(ADN partnerGenes) {
PVector[] newGenes = new PVector[lifespawn];
int middle = floor(random(lifespawn));
for (int i = 0; i < genes.length; ++i) {
if(i > middle) {
newGenes[i] = genes[i];
} else{
newGenes[i] = partnerGenes.genes[i];
}
}
return new ADN(newGenes);
}
void mutate() {
for (int i = 0; i < genes.length; ++i) {
if(random(1) < 0.01) {
genes[i] = PVector.random2D();
genes[i].setMag(0.3);
}
}
}
}
| UTF-8 | Java | 4,836 | java | SmartRockets.java | Java | []
| null | []
| Populate pop;
PVector piniata;
int age = 0;
void setup() {
size(500, 500);
piniata = new PVector(width/2, 50);
pop = new Populate(piniata);
}
void draw() {
background(0);
pop.run();
age++;
if(age >= 500) {
pop.evaluate();
pop.select();
age = 0;
}
rect(250, 240, 300, 20);
ellipse(piniata.x, piniata.y, 30, 30);
}
class Rocket {
PVector pos, vel, acc;
ADN adn;
int counter = 0;
float succes = 0;
boolean isCompleted = false;
boolean isCrahed = false;
int rX = 100;
int rY = 240;
int rW = 300;
int rH = 20;
Rocket() {
pos = new PVector(width/2, height);
vel = new PVector();
acc = new PVector();
adn = new ADN();
}
Rocket(ADN adn) {
pos = new PVector(width/2, height);
vel = new PVector();
acc = new PVector();
this.adn = adn;
}
void addForce(PVector force) {
acc.add(force);
}
void calcSucces(PVector target) {
float dis = dist(pos.x, pos.y, target.x, target.y);
succes = map(dis, 0, width, width, 0);
if(isCompleted) {
succes *= 10;
}
if(isCrahed) {
succes /= 10;
}
}
void refresh(PVector target) {
float dis = dist(pos.x, pos.y, target.x, target.y);
if(dis < 10) {
isCompleted = true;
pos = target.copy();
}
if(pos.x > rX && pos.x < rX + rW && pos.y > rY && pos.y < rY + rH) {
isCrahed = true;
}
if(pos.x < 0 || pos.x > width) {
isCrahed = true;
}
if(pos.y < 0 || pos.y > height) {
isCrahed = true;
}
if(!isCompleted && !isCrahed) {
if(counter < adn.genes.length) {
addForce(adn.genes[counter]);
counter++;
} else{
counter = 0;
}
vel.add(acc);
pos.add(vel);
acc.mult(0);
vel.limit(4);
}
}
void doodle() {
pushMatrix();
noStroke();
fill(255, 200);
translate(pos.x, pos.y);
rotate(vel.heading());
rectMode(CENTER);
rect(0, 0, 20, 4);
popMatrix();
}
}
class Populate {
Rocket[] rockets;
int pob = 100;
PVector target;
ArrayList<Rocket> succesfully = new ArrayList<Rocket>();
Populate(PVector target) {
rockets = new Rocket[pob];
this.target = target;
for (int i = 0; i < rockets.length; i++) {
rockets[i] = new Rocket();
}
}
void evaluate() {
float maxSucces = 0;
for (int i = 0; i < rockets.length; ++i) {
rockets[i].calcSucces(target);
if(rockets[i].succes > maxSucces) {
maxSucces = rockets[i].succes;
}
}
for (int i = 0; i < rockets.length; ++i) {
rockets[i].succes /= maxSucces;
}
succesfully.clear();
for (int i = 0; i < rockets.length; ++i) {
float n = rockets[i].succes * 100;
for (int j = 0; j < n; ++j) {
succesfully.add(rockets[i]);
}
}
}
void select() {
Rocket[] newRockets = new Rocket[pob];
for (int i = 0; i < newRockets.length; ++i) {
Rocket parentA = succesfully.get(floor(random(succesfully.size())));
Rocket parentB = succesfully.get(floor(random(succesfully.size())));
ADN child = parentA.adn.crossover(parentB.adn);
child.mutate();
newRockets[i] = new Rocket(child);
}
rockets = newRockets;
}
void run() {
for (int i = 0; i < rockets.length; i++) {
rockets[i].refresh(target);
rockets[i].doodle();
}
}
}
class ADN {
int lifespawn = 500;
PVector[] genes = new PVector[lifespawn];
ADN() {
for (int i = 0; i < genes.length; ++i) {
genes[i] = PVector.random2D();
genes[i].setMag(0.3);
}
}
ADN(PVector[] genes) {
this.genes = genes;
}
ADN crossover(ADN partnerGenes) {
PVector[] newGenes = new PVector[lifespawn];
int middle = floor(random(lifespawn));
for (int i = 0; i < genes.length; ++i) {
if(i > middle) {
newGenes[i] = genes[i];
} else{
newGenes[i] = partnerGenes.genes[i];
}
}
return new ADN(newGenes);
}
void mutate() {
for (int i = 0; i < genes.length; ++i) {
if(random(1) < 0.01) {
genes[i] = PVector.random2D();
genes[i].setMag(0.3);
}
}
}
}
| 4,836 | 0.460091 | 0.43962 | 235 | 19.578724 | 17.976261 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612766 | false | false | 15 |
c1c30ef6874f4afa715bfb67dec0669cc457accd | 23,295,902,671,655 | a088efb78e80be5efefd5c98b9538ff479658e21 | /src/main/java/shop/dev/service/RoleServiceImpl.java | c05dff178f7b8f72af5ef16492a9254b76873654 | []
| no_license | becumap/Shop | https://github.com/becumap/Shop | 8a72a9ed3891878a704b53269e1b9f5d6225d840 | 34bb2ce35adffc096519e8777f08e8637280ab17 | refs/heads/master | 2020-03-26T18:53:36.966000 | 2018-08-21T15:20:07 | 2018-08-21T15:20:07 | 145,236,855 | 0 | 0 | null | false | 2018-08-21T15:20:08 | 2018-08-18T16:50:52 | 2018-08-19T14:18:58 | 2018-08-21T15:20:07 | 53 | 0 | 0 | 0 | Java | false | null | package shop.dev.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import shop.dev.common.Result;
import shop.dev.constant.CodeConstant;
import shop.dev.repository.RoleEntity;
import shop.dev.repository.RoleRepository;
@Service
public class RoleServiceImpl {
@Autowired
RoleRepository roleRepository;
@GetMapping("/list")
public Result getList() {
Result result = new Result();
List<RoleEntity> rawData = new ArrayList<>();
try {
rawData = roleRepository.findAll();
result.setCode(CodeConstant.CODESUCCESS);
result.setData(rawData);
result.setMessage(CodeConstant.SUCCESS);
}catch (Exception e) {
e.printStackTrace();
result.setCode(CodeConstant.CODEFAIL);
result.setData(rawData);
result.setMessage(CodeConstant.FAIL);
}
return result;
}
}
| UTF-8 | Java | 974 | java | RoleServiceImpl.java | Java | []
| null | []
| package shop.dev.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import shop.dev.common.Result;
import shop.dev.constant.CodeConstant;
import shop.dev.repository.RoleEntity;
import shop.dev.repository.RoleRepository;
@Service
public class RoleServiceImpl {
@Autowired
RoleRepository roleRepository;
@GetMapping("/list")
public Result getList() {
Result result = new Result();
List<RoleEntity> rawData = new ArrayList<>();
try {
rawData = roleRepository.findAll();
result.setCode(CodeConstant.CODESUCCESS);
result.setData(rawData);
result.setMessage(CodeConstant.SUCCESS);
}catch (Exception e) {
e.printStackTrace();
result.setCode(CodeConstant.CODEFAIL);
result.setData(rawData);
result.setMessage(CodeConstant.FAIL);
}
return result;
}
}
| 974 | 0.76386 | 0.76386 | 40 | 23.35 | 17.775757 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.7 | false | false | 15 |
f98f6a7c7f01206e253822faaa02f3aff8060c4b | 1,099,511,666,704 | b4315485b8b023f754c8f5654ad378a44a2e68da | /src/javaExample/TestFileStream.java | 25c81b9da8578fe7f56ca2df8165c5574d5dc097 | []
| no_license | CIearlove/javaExercises | https://github.com/CIearlove/javaExercises | 6462f7bcdd05f17e4dd3496be01702c9f4330860 | 23af2070927826aef152bb44e761dd57e2b49a9d | refs/heads/master | 2021-05-14T00:49:54.680000 | 2019-05-02T12:39:56 | 2019-05-02T12:39:56 | 116,550,862 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package javaExample;
import java.io.*;
public class TestFileStream {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileOutputStream output = new FileOutputStream("temp.dat");
//i的取值范围是1到256
for(int i =1;i<=10;i++){
output.write(i);
}
output.close();
FileInputStream input = new FileInputStream("temp.dat");
int value;
System.out.println("The number of available bytes:"+input.available());
while((value = input.read())!=-1){
System.out.print(value+" ");
}
input.close();
}
}
| GB18030 | Java | 612 | java | TestFileStream.java | Java | []
| null | []
| package javaExample;
import java.io.*;
public class TestFileStream {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileOutputStream output = new FileOutputStream("temp.dat");
//i的取值范围是1到256
for(int i =1;i<=10;i++){
output.write(i);
}
output.close();
FileInputStream input = new FileInputStream("temp.dat");
int value;
System.out.println("The number of available bytes:"+input.available());
while((value = input.read())!=-1){
System.out.print(value+" ");
}
input.close();
}
}
| 612 | 0.637124 | 0.623746 | 26 | 21 | 21.173277 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.076923 | false | false | 15 |
f6860c73c7d02d997038ee0ec36d23f56a223864 | 26,877,905,352,445 | 82b113f9837298880ad999587a574f4777902256 | /jforum-impl/impl/src/java/org/etudes/component/app/jforum/dao/generic/SpecialAccessGeneric.java | b59cb23890649eb6ea327e43b2427c861bfb1659 | [
"Apache-2.0"
]
| permissive | etudes-inc/etudes-jforum | https://github.com/etudes-inc/etudes-jforum | 12d13941e76b4a7483ded3e1cee08a411b66ba33 | 423d2ac371a0451fbb2ed9be693933a25225514e | refs/heads/master | 2020-06-16T11:28:42.617000 | 2017-06-15T00:43:15 | 2017-06-15T00:43:15 | 94,144,634 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**********************************************************************************
* $URL: https://source.etudes.org/svn/apps/jforum/tags/2.27/jforum-impl/impl/src/java/org/etudes/component/app/jforum/dao/generic/SpecialAccessGeneric.java $
* $Id: SpecialAccessGeneric.java 3638 2012-12-02 21:33:06Z ggolden $
***********************************************************************************
*
* Copyright (c) 2008, 2009, 2010, 2011, 2012 Etudes, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***********************************************************************************/
package org.etudes.component.app.jforum.dao.generic;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etudes.api.app.jforum.AccessDates;
import org.etudes.api.app.jforum.SpecialAccess;
import org.etudes.api.app.jforum.dao.SpecialAccessDao;
import org.etudes.component.app.jforum.AccessDatesImpl;
import org.etudes.component.app.jforum.SpecialAccessImpl;
import org.sakaiproject.db.api.SqlReader;
import org.sakaiproject.db.api.SqlService;
public abstract class SpecialAccessGeneric implements SpecialAccessDao
{
private static Log logger = LogFactory.getLog(SpecialAccessGeneric.class);
/** Dependency: SqlService */
protected SqlService sqlService = null;
/**
* {@inheritDoc}
*/
public int addForumSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() > 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() > 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
return insertForumSpecialAccessTx(specialAccess);
}
/**
* {@inheritDoc}
*/
public int addTopicSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() > 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() <= 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
return insertTopicSpecialAccessTx(specialAccess);
}
/**
* {@inheritDoc}
*/
public void delete(final int specialAccessId)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
deleteTXN(specialAccessId);
}
}, "delete: " + specialAccessId);
}
/**
* {@inheritDoc}
*/
public void deleteUserSpecialAccess(int specialAccessId, int userId)
{
if (specialAccessId <= 0 || userId <= 0)
{
return;
}
deleteUserSpecialAccessTx(specialAccessId, userId);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectByForum(int forumId)
{
String sql;
Object[] fields;
int i = 0;
sql = "SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users FROM jforum_special_access WHERE forum_id = ? AND topic_id = 0";
fields = new Object[1];
fields[i++] = forumId;
return getSpecialAccess(sql, fields);
}
/**
* {@inheritDoc}
*/
public SpecialAccess selectById(int specialAccessId)
{
String sql = "SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users FROM jforum_special_access WHERE special_access_id = ?";
int i = 0;
Object[] fields = new Object[1];
fields[i++] = specialAccessId;
List<SpecialAccess> specialAccessList = getSpecialAccess(sql.toString(), fields);
SpecialAccess specialAccess = null;
if (specialAccessList.size() == 1)
{
specialAccess = specialAccessList.get(0);
}
return specialAccess;
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectBySite(String siteId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.hide_until_open, s.end_date, s.allow_until_date, s.override_start_date, s.override_hide_until_open, s.override_end_date, s.override_allow_until_date, s.password, s.lock_end_date, s.users ");
//sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.end_date, ");
//sql.append("s.lock_end_date, s.override_start_date, s.override_end_date, s.override_lock_end_date, s.password, s.users ");
sql.append("FROM jforum_special_access s, jforum_forums f, jforum_sakai_course_categories cc ");
sql.append("WHERE s.forum_id = f.forum_id ");
sql.append("AND f.categories_id = cc.categories_id ");
sql.append("AND cc.course_id = ? ");
fields = new Object[1];
fields[i++] = siteId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectBySiteAllForums(String siteId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
//sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.end_date, ");
//sql.append("s.lock_end_date, s.override_start_date, s.override_end_date, s.override_lock_end_date, s.password, s.users ");
sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.hide_until_open, s.end_date, s.allow_until_date, s.override_start_date, s.override_hide_until_open, s.override_end_date, s.override_allow_until_date, s.password, s.lock_end_date, s.users ");
sql.append("FROM jforum_special_access s, jforum_forums f, jforum_sakai_course_categories cc ");
sql.append("WHERE s.forum_id = f.forum_id AND s.topic_id = 0 ");
sql.append("AND f.categories_id = cc.categories_id ");
sql.append("AND cc.course_id = ? ");
fields = new Object[1];
fields[i++] = siteId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectBySiteAllTopics(String siteId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
//sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.end_date, ");
//sql.append("s.lock_end_date, s.override_start_date, s.override_end_date, s.override_lock_end_date, s.password, s.users ");
sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.hide_until_open, s.end_date, s.allow_until_date, s.override_start_date, s.override_hide_until_open, s.override_end_date, s.override_allow_until_date, s.password, s.lock_end_date, s.users ");
sql.append("FROM jforum_special_access s, jforum_forums f, jforum_sakai_course_categories cc ");
sql.append("WHERE s.forum_id = f.forum_id AND s.topic_id != 0 ");
sql.append("AND f.categories_id = cc.categories_id ");
sql.append("AND cc.course_id = ? ");
fields = new Object[1];
fields[i++] = siteId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectByTopic(int forumId, int topicId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
sql.append("SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users FROM jforum_special_access");
sql.append(" WHERE forum_id = ? and Topic_id = ?");
fields = new Object[2];
fields[i++] = forumId;
fields[i++] = topicId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectTopicsByForumId(int forumId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
sql.append("SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users ");
sql.append("FROM jforum_special_access WHERE forum_id = ? AND topic_id > 0");
fields = new Object[1];
fields[i++] = forumId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* @param sqlService
* the sqlService to set
*/
public void setSqlService(SqlService sqlService)
{
this.sqlService = sqlService;
}
/**
* {@inheritDoc}
*/
public void updateForumSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() <= 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() > 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
updateForumSpecialAccessTx(specialAccess);
}
/**
* {@inheritDoc}
*/
public void updateTopicSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() <= 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() <= 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
updateTopicSpecialAccessTx(specialAccess);
}
/**
* Delete the special access
*
* @param specialAccessId
*
* @throws RuntimeException
*/
protected void deleteTXN(int specialAccessId)
{
String sql;
Object[] fields;
int i = 0;
sql = "DELETE FROM jforum_special_access WHERE special_access_id = ?";
fields = new Object[1];
fields[i++] = specialAccessId;
if (!sqlService.dbWrite(sql.toString(), fields))
{
throw new RuntimeException("deleteTXN: db write failed");
}
}
/**
* Deletes user special access
*
* @param specialAccessId Special access id
*
* @param userId User id
*/
protected void deleteUserSpecialAccessTx(final int specialAccessId, final int userId)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
SpecialAccess exisSpecialAccess = selectById(specialAccessId);
List<Integer> exisUserIds = exisSpecialAccess.getUserIds();
List<Integer> specialAccessUser = new ArrayList<Integer>();
specialAccessUser.add(new Integer(userId));
if (exisUserIds.removeAll(specialAccessUser))
{
if (exisUserIds.size() > 0)
{
exisSpecialAccess.setUserIds(exisUserIds);
update(exisSpecialAccess);
}
else
{
delete(exisSpecialAccess.getId());
}
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while deleting user special access.", e);
}
}
}, "deleteuser: " + specialAccessId + ":" + userId);
}
/**
* Gets the special access
*
* @param sql
* Query to execute
*
* @param fields
* Query params
*
* @return Returns the list of special access
*/
protected List<SpecialAccess> getSpecialAccess(String sql, Object[] fields)
{
final List<SpecialAccess> specialAccessList = new ArrayList<SpecialAccess>();
this.sqlService.dbRead(sql, fields, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
SpecialAccess specialAccess = new SpecialAccessImpl();
((SpecialAccessImpl)specialAccess).setId(result.getInt("special_access_id"));
((SpecialAccessImpl)specialAccess).setForumId(result.getInt("forum_id"));
((SpecialAccessImpl)specialAccess).setTopicId(result.getInt("topic_id"));
AccessDates accessDates = new AccessDatesImpl();
if (result.getDate("start_date") != null)
{
Timestamp startDate = result.getTimestamp("start_date");
accessDates.setOpenDate(startDate);
accessDates.setHideUntilOpen(result.getInt("hide_until_open") > 0);
}
else
{
accessDates.setOpenDate(null);
}
/*if (result.getDate("end_date") != null)
{
Timestamp endDate = result.getTimestamp("end_date");
accessDates.setDueDate(endDate);
//accessDates.setLocked(result.getInt("lock_end_date") > 0);
}
else
{
accessDates.setDueDate(null);
}*/
accessDates.setDueDate(result.getTimestamp("end_date"));
accessDates.setAllowUntilDate(result.getTimestamp("allow_until_date"));
((SpecialAccessImpl)specialAccess).setAccessDates(accessDates);
if (result.getInt("override_hide_until_open") == 1)
{
specialAccess.setOverrideHideUntilOpen(result.getInt("override_hide_until_open") == 1);
accessDates.setHideUntilOpen(result.getInt("hide_until_open") > 0);
}
specialAccess.setOverrideStartDate(result.getInt("override_start_date") == 1);
specialAccess.setOverrideEndDate(result.getInt("override_end_date") == 1);
specialAccess.setOverrideAllowUntilDate(result.getInt("override_allow_until_date") == 1);
/*if (result.getInt("override_lock_end_date") == 1)
{
specialAccess.setOverrideLockEndDate(result.getInt("override_lock_end_date") == 1);
accessDates.setLocked(result.getInt("lock_end_date") > 0);
}*/
List<Integer> userIds = getUserIdList(result.getString("users"));
specialAccess.setUserIds(userIds);
specialAccessList.add(specialAccess);
return null;
}
catch (SQLException e)
{
if (logger.isWarnEnabled())
{
logger.warn("getSpecialAccess: " + e, e);
}
return null;
}
}
});
return specialAccessList;
}
/**
* get userid list from the string
*
* @param userIds
* userids string
*
* @return list of userid's
*/
protected List<Integer> getUserIdList(String userIds)
{
if ((userIds == null) || (userIds.trim().length() == 0))
{
return null;
}
List<Integer> userIdList = new ArrayList<Integer>();
String[] userIdsArray = userIds.split(":");
if ((userIdsArray != null) && (userIdsArray.length > 0))
{
for (String userId : userIdsArray)
{
userIdList.add(new Integer(userId));
}
}
return userIdList;
}
/**
* Get user id string from the users id's list
* @param userIds List of user id's
* @return User id string
*/
protected String getUserIdString(List<Integer> userIds)
{
if ((userIds == null) || (userIds.size() == 0))
{
return null;
}
StringBuilder userIdSB = new StringBuilder();
for (Integer userId : userIds)
{
if (userId != null)
{
userIdSB.append(userId);
userIdSB.append(":");
}
}
String userIdsStr = userIdSB.toString();
return userIdsStr.substring(0, userIdsStr.length() - 1);
}
/**
* Inserts forum special access. One user must have one special access
*
* @param specialAccess Special access
*
* @return The special access id
*/
protected int insertForumSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users and create new special access
List<SpecialAccess> forumSpecialAccessList = selectByForum(specialAccess.getForumId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : forumSpecialAccessList)
{
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
int specialAccessId = insertSpecialAccess(specialAccess);
((SpecialAccessImpl)specialAccess).setId(specialAccessId);
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while creating new forum special access.", e);
}
}
}, "saveSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
return specialAccess.getId();
}
/**
* Inserts the special access
*
* @param specialAccess Special access
*
* @return The special access id
*/
protected abstract int insertSpecialAccess(SpecialAccess specialAccess);
protected int insertTopicSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users and create new special access
// TODO: validate topic id with forum id
List<SpecialAccess> topicSpecialAccessList = selectByTopic(specialAccess.getForumId(), specialAccess.getTopicId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : topicSpecialAccessList)
{
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
//if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideLockEndDate())) && (users.size() > 0))
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
int specialAccessId = insertSpecialAccess(specialAccess);
((SpecialAccessImpl)specialAccess).setId(specialAccessId);
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while creating new topic special access.", e);
}
}
}, "saveSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
return specialAccess.getId();
}
/**
* Updates the special access
*
* @param specialAccess Special access
*/
protected void update(SpecialAccess specialAccess)
{
StringBuffer sql = new StringBuffer();
sql.append("UPDATE jforum_special_access SET forum_id = ?, topic_id = ?, start_date = ?, hide_until_open = ?, end_date = ?, allow_until_date = ?, ");
sql.append("override_start_date = ?, override_hide_until_open = ?, override_end_date = ?, override_allow_until_date = ?, users = ? WHERE special_access_id = ?");
Object[] fields = new Object[12];
int i = 0;
fields[i++] = specialAccess.getForumId();
fields[i++] = specialAccess.getTopicId();
if (specialAccess.getAccessDates().getOpenDate() == null)
{
fields[i++] = null;
}
else
{
fields[i++] = new Timestamp(specialAccess.getAccessDates().getOpenDate().getTime());
}
fields[i++] = specialAccess.getAccessDates().isHideUntilOpen() ? 1 : 0;
if (specialAccess.getAccessDates().getDueDate() == null)
{
fields[i++] = null;
}
else
{
fields[i++] = new Timestamp(specialAccess.getAccessDates().getDueDate().getTime());
}
if (specialAccess.getAccessDates().getAllowUntilDate() == null)
{
fields[i++] = null;
}
else
{
fields[i++] = new Timestamp(specialAccess.getAccessDates().getAllowUntilDate().getTime());
}
fields[i++] = specialAccess.isOverrideStartDate() ? 1 : 0;
fields[i++] = specialAccess.isOverrideHideUntilOpen() ? 1 : 0;
fields[i++] = specialAccess.isOverrideEndDate() ? 1 : 0;
fields[i++] = specialAccess.isOverrideAllowUntilDate() ? 1 : 0;
fields[i++] = getUserIdString(specialAccess.getUserIds());
fields[i++] = specialAccess.getId();
if (!sqlService.dbWrite(sql.toString(), fields))
{
throw new RuntimeException("update Special Access: db write failed");
}
}
/**
* update forum special access. One user must have one special access.
*
* @param specialAccess Special access
*/
protected void updateForumSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users
List<SpecialAccess> forumSpecialAccessList = selectByForum(specialAccess.getForumId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : forumSpecialAccessList)
{
if (exiSpecialAccess.getId() == specialAccess.getId())
continue;
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
//if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideLockEndDate())) && (users.size() > 0))
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
update(specialAccess);
}
else
{
delete(specialAccess.getId());
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while updating forum special access.", e);
}
}
}, "updateSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
}
/**
* Updates topic special access
*
* @param specialAccess Special access
*/
protected void updateTopicSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users
List<SpecialAccess> topicSpecialAccessList = selectByTopic(specialAccess.getForumId(), specialAccess.getTopicId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : topicSpecialAccessList)
{
if (exiSpecialAccess.getId() == specialAccess.getId())
continue;
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
//if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideLockEndDate())) && (users.size() > 0))
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
update(specialAccess);
}
else
{
delete(specialAccess.getId());
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while creating new special access.", e);
}
}
}, "updateSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
}
}
| UTF-8 | Java | 24,526 | java | SpecialAccessGeneric.java | Java | [
{
"context": "pecialAccessGeneric.java 3638 2012-12-02 21:33:06Z ggolden $ \n *********************************************",
"end": 311,
"score": 0.9979678392410278,
"start": 304,
"tag": "USERNAME",
"value": "ggolden"
},
{
"context": "_end_date, s.override_lock_end_date, s.password, s.users \");\n\t\tsql.append(\"SELECT s.special_access_id, s.f",
"end": 5962,
"score": 0.6792305707931519,
"start": 5957,
"tag": "PASSWORD",
"value": "users"
},
{
"context": "_end_date, s.override_lock_end_date, s.password, s.users \");\n\t\tsql.append(\"SELECT s.special_access_id",
"end": 6995,
"score": 0.6770811676979065,
"start": 6995,
"tag": "PASSWORD",
"value": ""
},
{
"context": "end_date, s.override_allow_until_date, s.password, s.lock_end_date, s.users \");\n\t\tsql.append(\"FROM jforum_special_ac",
"end": 7265,
"score": 0.8982601761817932,
"start": 7250,
"tag": "PASSWORD",
"value": "s.lock_end_date"
}
]
| null | []
| /**********************************************************************************
* $URL: https://source.etudes.org/svn/apps/jforum/tags/2.27/jforum-impl/impl/src/java/org/etudes/component/app/jforum/dao/generic/SpecialAccessGeneric.java $
* $Id: SpecialAccessGeneric.java 3638 2012-12-02 21:33:06Z ggolden $
***********************************************************************************
*
* Copyright (c) 2008, 2009, 2010, 2011, 2012 Etudes, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***********************************************************************************/
package org.etudes.component.app.jforum.dao.generic;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.etudes.api.app.jforum.AccessDates;
import org.etudes.api.app.jforum.SpecialAccess;
import org.etudes.api.app.jforum.dao.SpecialAccessDao;
import org.etudes.component.app.jforum.AccessDatesImpl;
import org.etudes.component.app.jforum.SpecialAccessImpl;
import org.sakaiproject.db.api.SqlReader;
import org.sakaiproject.db.api.SqlService;
public abstract class SpecialAccessGeneric implements SpecialAccessDao
{
private static Log logger = LogFactory.getLog(SpecialAccessGeneric.class);
/** Dependency: SqlService */
protected SqlService sqlService = null;
/**
* {@inheritDoc}
*/
public int addForumSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() > 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() > 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
return insertForumSpecialAccessTx(specialAccess);
}
/**
* {@inheritDoc}
*/
public int addTopicSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() > 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() <= 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
return insertTopicSpecialAccessTx(specialAccess);
}
/**
* {@inheritDoc}
*/
public void delete(final int specialAccessId)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
deleteTXN(specialAccessId);
}
}, "delete: " + specialAccessId);
}
/**
* {@inheritDoc}
*/
public void deleteUserSpecialAccess(int specialAccessId, int userId)
{
if (specialAccessId <= 0 || userId <= 0)
{
return;
}
deleteUserSpecialAccessTx(specialAccessId, userId);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectByForum(int forumId)
{
String sql;
Object[] fields;
int i = 0;
sql = "SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users FROM jforum_special_access WHERE forum_id = ? AND topic_id = 0";
fields = new Object[1];
fields[i++] = forumId;
return getSpecialAccess(sql, fields);
}
/**
* {@inheritDoc}
*/
public SpecialAccess selectById(int specialAccessId)
{
String sql = "SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users FROM jforum_special_access WHERE special_access_id = ?";
int i = 0;
Object[] fields = new Object[1];
fields[i++] = specialAccessId;
List<SpecialAccess> specialAccessList = getSpecialAccess(sql.toString(), fields);
SpecialAccess specialAccess = null;
if (specialAccessList.size() == 1)
{
specialAccess = specialAccessList.get(0);
}
return specialAccess;
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectBySite(String siteId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.hide_until_open, s.end_date, s.allow_until_date, s.override_start_date, s.override_hide_until_open, s.override_end_date, s.override_allow_until_date, s.password, s.lock_end_date, s.users ");
//sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.end_date, ");
//sql.append("s.lock_end_date, s.override_start_date, s.override_end_date, s.override_lock_end_date, s.password, s.users ");
sql.append("FROM jforum_special_access s, jforum_forums f, jforum_sakai_course_categories cc ");
sql.append("WHERE s.forum_id = f.forum_id ");
sql.append("AND f.categories_id = cc.categories_id ");
sql.append("AND cc.course_id = ? ");
fields = new Object[1];
fields[i++] = siteId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectBySiteAllForums(String siteId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
//sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.end_date, ");
//sql.append("s.lock_end_date, s.override_start_date, s.override_end_date, s.override_lock_end_date, s.password, s.<PASSWORD> ");
sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.hide_until_open, s.end_date, s.allow_until_date, s.override_start_date, s.override_hide_until_open, s.override_end_date, s.override_allow_until_date, s.password, s.lock_end_date, s.users ");
sql.append("FROM jforum_special_access s, jforum_forums f, jforum_sakai_course_categories cc ");
sql.append("WHERE s.forum_id = f.forum_id AND s.topic_id = 0 ");
sql.append("AND f.categories_id = cc.categories_id ");
sql.append("AND cc.course_id = ? ");
fields = new Object[1];
fields[i++] = siteId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectBySiteAllTopics(String siteId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
//sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.end_date, ");
//sql.append("s.lock_end_date, s.override_start_date, s.override_end_date, s.override_lock_end_date, s.password, s.users ");
sql.append("SELECT s.special_access_id, s.forum_id, s.topic_id, s.start_date, s.hide_until_open, s.end_date, s.allow_until_date, s.override_start_date, s.override_hide_until_open, s.override_end_date, s.override_allow_until_date, s.password, <PASSWORD>, s.users ");
sql.append("FROM jforum_special_access s, jforum_forums f, jforum_sakai_course_categories cc ");
sql.append("WHERE s.forum_id = f.forum_id AND s.topic_id != 0 ");
sql.append("AND f.categories_id = cc.categories_id ");
sql.append("AND cc.course_id = ? ");
fields = new Object[1];
fields[i++] = siteId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectByTopic(int forumId, int topicId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
sql.append("SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users FROM jforum_special_access");
sql.append(" WHERE forum_id = ? and Topic_id = ?");
fields = new Object[2];
fields[i++] = forumId;
fields[i++] = topicId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* {@inheritDoc}
*/
public List<SpecialAccess> selectTopicsByForumId(int forumId)
{
StringBuilder sql = new StringBuilder();
Object[] fields;
int i = 0;
sql.append("SELECT special_access_id, forum_id, topic_id, start_date, hide_until_open, end_date, allow_until_date, override_start_date, override_hide_until_open, override_end_date, override_allow_until_date, password, lock_end_date, users ");
sql.append("FROM jforum_special_access WHERE forum_id = ? AND topic_id > 0");
fields = new Object[1];
fields[i++] = forumId;
return getSpecialAccess(sql.toString(), fields);
}
/**
* @param sqlService
* the sqlService to set
*/
public void setSqlService(SqlService sqlService)
{
this.sqlService = sqlService;
}
/**
* {@inheritDoc}
*/
public void updateForumSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() <= 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() > 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
updateForumSpecialAccessTx(specialAccess);
}
/**
* {@inheritDoc}
*/
public void updateTopicSpecialAccess(SpecialAccess specialAccess)
{
if (specialAccess == null || specialAccess.getId() <= 0 || (specialAccess.getForumId() <= 0 || specialAccess.getTopicId() <= 0) || (specialAccess.getUserIds() == null || specialAccess.getUserIds().isEmpty()) )
{
throw new IllegalArgumentException("Special access data is missing.");
}
updateTopicSpecialAccessTx(specialAccess);
}
/**
* Delete the special access
*
* @param specialAccessId
*
* @throws RuntimeException
*/
protected void deleteTXN(int specialAccessId)
{
String sql;
Object[] fields;
int i = 0;
sql = "DELETE FROM jforum_special_access WHERE special_access_id = ?";
fields = new Object[1];
fields[i++] = specialAccessId;
if (!sqlService.dbWrite(sql.toString(), fields))
{
throw new RuntimeException("deleteTXN: db write failed");
}
}
/**
* Deletes user special access
*
* @param specialAccessId Special access id
*
* @param userId User id
*/
protected void deleteUserSpecialAccessTx(final int specialAccessId, final int userId)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
SpecialAccess exisSpecialAccess = selectById(specialAccessId);
List<Integer> exisUserIds = exisSpecialAccess.getUserIds();
List<Integer> specialAccessUser = new ArrayList<Integer>();
specialAccessUser.add(new Integer(userId));
if (exisUserIds.removeAll(specialAccessUser))
{
if (exisUserIds.size() > 0)
{
exisSpecialAccess.setUserIds(exisUserIds);
update(exisSpecialAccess);
}
else
{
delete(exisSpecialAccess.getId());
}
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while deleting user special access.", e);
}
}
}, "deleteuser: " + specialAccessId + ":" + userId);
}
/**
* Gets the special access
*
* @param sql
* Query to execute
*
* @param fields
* Query params
*
* @return Returns the list of special access
*/
protected List<SpecialAccess> getSpecialAccess(String sql, Object[] fields)
{
final List<SpecialAccess> specialAccessList = new ArrayList<SpecialAccess>();
this.sqlService.dbRead(sql, fields, new SqlReader()
{
public Object readSqlResultRecord(ResultSet result)
{
try
{
SpecialAccess specialAccess = new SpecialAccessImpl();
((SpecialAccessImpl)specialAccess).setId(result.getInt("special_access_id"));
((SpecialAccessImpl)specialAccess).setForumId(result.getInt("forum_id"));
((SpecialAccessImpl)specialAccess).setTopicId(result.getInt("topic_id"));
AccessDates accessDates = new AccessDatesImpl();
if (result.getDate("start_date") != null)
{
Timestamp startDate = result.getTimestamp("start_date");
accessDates.setOpenDate(startDate);
accessDates.setHideUntilOpen(result.getInt("hide_until_open") > 0);
}
else
{
accessDates.setOpenDate(null);
}
/*if (result.getDate("end_date") != null)
{
Timestamp endDate = result.getTimestamp("end_date");
accessDates.setDueDate(endDate);
//accessDates.setLocked(result.getInt("lock_end_date") > 0);
}
else
{
accessDates.setDueDate(null);
}*/
accessDates.setDueDate(result.getTimestamp("end_date"));
accessDates.setAllowUntilDate(result.getTimestamp("allow_until_date"));
((SpecialAccessImpl)specialAccess).setAccessDates(accessDates);
if (result.getInt("override_hide_until_open") == 1)
{
specialAccess.setOverrideHideUntilOpen(result.getInt("override_hide_until_open") == 1);
accessDates.setHideUntilOpen(result.getInt("hide_until_open") > 0);
}
specialAccess.setOverrideStartDate(result.getInt("override_start_date") == 1);
specialAccess.setOverrideEndDate(result.getInt("override_end_date") == 1);
specialAccess.setOverrideAllowUntilDate(result.getInt("override_allow_until_date") == 1);
/*if (result.getInt("override_lock_end_date") == 1)
{
specialAccess.setOverrideLockEndDate(result.getInt("override_lock_end_date") == 1);
accessDates.setLocked(result.getInt("lock_end_date") > 0);
}*/
List<Integer> userIds = getUserIdList(result.getString("users"));
specialAccess.setUserIds(userIds);
specialAccessList.add(specialAccess);
return null;
}
catch (SQLException e)
{
if (logger.isWarnEnabled())
{
logger.warn("getSpecialAccess: " + e, e);
}
return null;
}
}
});
return specialAccessList;
}
/**
* get userid list from the string
*
* @param userIds
* userids string
*
* @return list of userid's
*/
protected List<Integer> getUserIdList(String userIds)
{
if ((userIds == null) || (userIds.trim().length() == 0))
{
return null;
}
List<Integer> userIdList = new ArrayList<Integer>();
String[] userIdsArray = userIds.split(":");
if ((userIdsArray != null) && (userIdsArray.length > 0))
{
for (String userId : userIdsArray)
{
userIdList.add(new Integer(userId));
}
}
return userIdList;
}
/**
* Get user id string from the users id's list
* @param userIds List of user id's
* @return User id string
*/
protected String getUserIdString(List<Integer> userIds)
{
if ((userIds == null) || (userIds.size() == 0))
{
return null;
}
StringBuilder userIdSB = new StringBuilder();
for (Integer userId : userIds)
{
if (userId != null)
{
userIdSB.append(userId);
userIdSB.append(":");
}
}
String userIdsStr = userIdSB.toString();
return userIdsStr.substring(0, userIdsStr.length() - 1);
}
/**
* Inserts forum special access. One user must have one special access
*
* @param specialAccess Special access
*
* @return The special access id
*/
protected int insertForumSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users and create new special access
List<SpecialAccess> forumSpecialAccessList = selectByForum(specialAccess.getForumId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : forumSpecialAccessList)
{
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
int specialAccessId = insertSpecialAccess(specialAccess);
((SpecialAccessImpl)specialAccess).setId(specialAccessId);
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while creating new forum special access.", e);
}
}
}, "saveSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
return specialAccess.getId();
}
/**
* Inserts the special access
*
* @param specialAccess Special access
*
* @return The special access id
*/
protected abstract int insertSpecialAccess(SpecialAccess specialAccess);
protected int insertTopicSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users and create new special access
// TODO: validate topic id with forum id
List<SpecialAccess> topicSpecialAccessList = selectByTopic(specialAccess.getForumId(), specialAccess.getTopicId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : topicSpecialAccessList)
{
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
//if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideLockEndDate())) && (users.size() > 0))
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
int specialAccessId = insertSpecialAccess(specialAccess);
((SpecialAccessImpl)specialAccess).setId(specialAccessId);
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while creating new topic special access.", e);
}
}
}, "saveSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
return specialAccess.getId();
}
/**
* Updates the special access
*
* @param specialAccess Special access
*/
protected void update(SpecialAccess specialAccess)
{
StringBuffer sql = new StringBuffer();
sql.append("UPDATE jforum_special_access SET forum_id = ?, topic_id = ?, start_date = ?, hide_until_open = ?, end_date = ?, allow_until_date = ?, ");
sql.append("override_start_date = ?, override_hide_until_open = ?, override_end_date = ?, override_allow_until_date = ?, users = ? WHERE special_access_id = ?");
Object[] fields = new Object[12];
int i = 0;
fields[i++] = specialAccess.getForumId();
fields[i++] = specialAccess.getTopicId();
if (specialAccess.getAccessDates().getOpenDate() == null)
{
fields[i++] = null;
}
else
{
fields[i++] = new Timestamp(specialAccess.getAccessDates().getOpenDate().getTime());
}
fields[i++] = specialAccess.getAccessDates().isHideUntilOpen() ? 1 : 0;
if (specialAccess.getAccessDates().getDueDate() == null)
{
fields[i++] = null;
}
else
{
fields[i++] = new Timestamp(specialAccess.getAccessDates().getDueDate().getTime());
}
if (specialAccess.getAccessDates().getAllowUntilDate() == null)
{
fields[i++] = null;
}
else
{
fields[i++] = new Timestamp(specialAccess.getAccessDates().getAllowUntilDate().getTime());
}
fields[i++] = specialAccess.isOverrideStartDate() ? 1 : 0;
fields[i++] = specialAccess.isOverrideHideUntilOpen() ? 1 : 0;
fields[i++] = specialAccess.isOverrideEndDate() ? 1 : 0;
fields[i++] = specialAccess.isOverrideAllowUntilDate() ? 1 : 0;
fields[i++] = getUserIdString(specialAccess.getUserIds());
fields[i++] = specialAccess.getId();
if (!sqlService.dbWrite(sql.toString(), fields))
{
throw new RuntimeException("update Special Access: db write failed");
}
}
/**
* update forum special access. One user must have one special access.
*
* @param specialAccess Special access
*/
protected void updateForumSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users
List<SpecialAccess> forumSpecialAccessList = selectByForum(specialAccess.getForumId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : forumSpecialAccessList)
{
if (exiSpecialAccess.getId() == specialAccess.getId())
continue;
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
//if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideLockEndDate())) && (users.size() > 0))
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
update(specialAccess);
}
else
{
delete(specialAccess.getId());
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while updating forum special access.", e);
}
}
}, "updateSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
}
/**
* Updates topic special access
*
* @param specialAccess Special access
*/
protected void updateTopicSpecialAccessTx(final SpecialAccess specialAccess)
{
this.sqlService.transact(new Runnable()
{
public void run()
{
try
{
// delete any existing special access for the selected users
List<SpecialAccess> topicSpecialAccessList = selectByTopic(specialAccess.getForumId(), specialAccess.getTopicId());
List<Integer> users = specialAccess.getUserIds();
for (SpecialAccess exiSpecialAccess : topicSpecialAccessList)
{
if (exiSpecialAccess.getId() == specialAccess.getId())
continue;
List<Integer> exisUserIds = exiSpecialAccess.getUserIds();
if (exisUserIds.removeAll(users))
{
if (exisUserIds.size() > 0)
{
exiSpecialAccess.setUserIds(exisUserIds);
update(exiSpecialAccess);
}
else
{
delete(exiSpecialAccess.getId());
}
}
}
//if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideLockEndDate())) && (users.size() > 0))
if (((specialAccess.isOverrideStartDate()) || (specialAccess.isOverrideHideUntilOpen()) || (specialAccess.isOverrideEndDate()) || (specialAccess.isOverrideAllowUntilDate())) && (users.size() > 0))
{
update(specialAccess);
}
else
{
delete(specialAccess.getId());
}
}
catch (Exception e)
{
if (logger.isErrorEnabled())
{
logger.error(e.toString(), e);
}
throw new RuntimeException("Error while creating new special access.", e);
}
}
}, "updateSpecialAccess: " + specialAccess.getForumId() + ":" + specialAccess.getTopicId());
}
}
| 24,526 | 0.65979 | 0.654815 | 803 | 29.542963 | 41.364933 | 301 | false | false | 0 | 0 | 0 | 0 | 83 | 0.003384 | 3.404732 | false | false | 15 |
06a118923600d70e625bebad6092249c1f71d2d4 | 24,292,335,038,117 | 9dd2b1753875d69d2d1da7087f504919d71b977e | /src/main/java/com/sulamerica/demo/controller/UserController.java | 6bd50745ecdfda94c33ee2143591b0de706778db | [
"MIT"
]
| permissive | Cleberw3b/sulamerica | https://github.com/Cleberw3b/sulamerica | d5dfe463463bb2b2fa74525e78a61c0f76194ed8 | c635642305d7b608fa92969183b3b45b20ee0f00 | refs/heads/master | 2021-03-31T02:51:23.558000 | 2020-03-19T08:34:06 | 2020-03-19T08:34:06 | 248,069,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sulamerica.demo.controller;
import java.util.List;
import javax.validation.Valid;
import com.sulamerica.demo.model.Cargo;
import com.sulamerica.demo.model.Perfil;
import com.sulamerica.demo.model.User;
import com.sulamerica.demo.service.UserService;
import com.sulamerica.demo.util.enums.Status;
import com.sulamerica.demo.util.validators.UserValidation;
import com.sulamerica.demo.util.validators.UserValidationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/users")
private List<User> getAllUser(@RequestParam(required = false) Cargo cargo,
@RequestParam(required = false) Perfil perfil, @RequestParam(required = false) Status ativo) {
if (cargo != null)
return userService.getUsersByCargo(cargo);
if (perfil != null)
return userService.getUsersByPerfil(perfil);
if (ativo == Status.ATIVO)
return userService.getUsersByStatus(true);
if (ativo == Status.DESATIVO)
return userService.getUsersByStatus(false);
return userService.getAllUsers();
}
@GetMapping("/user")
private User getUser(@RequestParam(required = false) Integer id, @RequestParam(required = false) String nome,
@RequestParam(required = false) String cpf) {
if (id != null)
return userService.getUserById(id);
if (nome != null && !nome.isEmpty())
return userService.getUserByNome(nome);
if (cpf != null && !cpf.isEmpty())
return userService.getUserByCPF(cpf);
return null;
}
@DeleteMapping("/users/{id}")
private void deleteUser(@PathVariable("id") Integer id) {
userService.delete(id);
}
@PostMapping("/users")
private String addUser(@Valid @RequestBody User user) {
// Não será permitido o cadastro de usuários com o mesmo CPF e Nome.
if (userService.getUserByNome(user.getNome()) != null || userService.getUserByCPF(user.getCpf()) != null)
return "Usuário já existe em nosso sistema";
// Ao cadastrar, todos os dados de usuários são obrigatórios.
// Verificar se é um CPF válido.
UserValidationResult userValidationResult = UserValidation.isUserValid(user);
if (!userValidationResult.isValid) {
StringBuilder errors = new StringBuilder();
userValidationResult.errors.forEach(error -> {
errors.append(error);
errors.append(", ");
});
return errors.substring(0, errors.length() - 3);
}
userService.saveOrUpdate(user);
return "Usuário salvo com sucesso - ID=" + user.getId();
}
@PutMapping(value = "/users/{id}")
public Integer updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
userService.saveOrUpdate(user);
return user.getId();
}
} | UTF-8 | Java | 3,493 | java | UserController.java | Java | []
| null | []
| package com.sulamerica.demo.controller;
import java.util.List;
import javax.validation.Valid;
import com.sulamerica.demo.model.Cargo;
import com.sulamerica.demo.model.Perfil;
import com.sulamerica.demo.model.User;
import com.sulamerica.demo.service.UserService;
import com.sulamerica.demo.util.enums.Status;
import com.sulamerica.demo.util.validators.UserValidation;
import com.sulamerica.demo.util.validators.UserValidationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PutMapping;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/users")
private List<User> getAllUser(@RequestParam(required = false) Cargo cargo,
@RequestParam(required = false) Perfil perfil, @RequestParam(required = false) Status ativo) {
if (cargo != null)
return userService.getUsersByCargo(cargo);
if (perfil != null)
return userService.getUsersByPerfil(perfil);
if (ativo == Status.ATIVO)
return userService.getUsersByStatus(true);
if (ativo == Status.DESATIVO)
return userService.getUsersByStatus(false);
return userService.getAllUsers();
}
@GetMapping("/user")
private User getUser(@RequestParam(required = false) Integer id, @RequestParam(required = false) String nome,
@RequestParam(required = false) String cpf) {
if (id != null)
return userService.getUserById(id);
if (nome != null && !nome.isEmpty())
return userService.getUserByNome(nome);
if (cpf != null && !cpf.isEmpty())
return userService.getUserByCPF(cpf);
return null;
}
@DeleteMapping("/users/{id}")
private void deleteUser(@PathVariable("id") Integer id) {
userService.delete(id);
}
@PostMapping("/users")
private String addUser(@Valid @RequestBody User user) {
// Não será permitido o cadastro de usuários com o mesmo CPF e Nome.
if (userService.getUserByNome(user.getNome()) != null || userService.getUserByCPF(user.getCpf()) != null)
return "Usuário já existe em nosso sistema";
// Ao cadastrar, todos os dados de usuários são obrigatórios.
// Verificar se é um CPF válido.
UserValidationResult userValidationResult = UserValidation.isUserValid(user);
if (!userValidationResult.isValid) {
StringBuilder errors = new StringBuilder();
userValidationResult.errors.forEach(error -> {
errors.append(error);
errors.append(", ");
});
return errors.substring(0, errors.length() - 3);
}
userService.saveOrUpdate(user);
return "Usuário salvo com sucesso - ID=" + user.getId();
}
@PutMapping(value = "/users/{id}")
public Integer updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
userService.saveOrUpdate(user);
return user.getId();
}
} | 3,493 | 0.688397 | 0.687823 | 89 | 38.13483 | 27.069279 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.573034 | false | false | 15 |
3a12b7dc0bd429c196dc2343aa7a1f14fc74d091 | 9,259,949,543,335 | dd0518fee6ce9fa9e0d242c66b88152d82ad945d | /SpringMVCFrom/src/com/dev/spring/dao/impl/JDBCVEmployee.java | fc64ad1cf868170e699164e1e70ba4b49fc76637 | []
| no_license | dejavusv/spring | https://github.com/dejavusv/spring | 6e5379a6040ed454fc41c06d825b85c4bcf88141 | ff08d783f09bbe1f2ae537df64e227bf384018a6 | refs/heads/master | 2020-03-01T01:38:15.910000 | 2014-06-30T06:53:02 | 2014-06-30T06:53:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dev.spring.dao.impl;
import com.dev.spring.dao.VEmployeeDao;
import com.dev.spring.dao.model.VEmployee;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
*
* @author 7
*/
public class JDBCVEmployee extends JdbcDaoSupport implements VEmployeeDao{
public List<VEmployee> getEmlist() {
String sql = "SELECT * FROM vemployee";
List<VEmployee> EMList = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper(VEmployee.class));
return EMList;
}
public List<VEmployee> searchEMFromFilter(String Firstname, String Lastname, String Job, String Department, String Manager) {
String name = "%"+Firstname+" "+Lastname+"%";
String sql = "SELECT * FROM `vemployee` where `name` LIKE '"+name+"'";
List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql);
List<VEmployee> EMList = new LinkedList<VEmployee>();
for (Map row : rows) {
VEmployee em = new VEmployee();
em.setName((String)(row.get("name")));
em.setEmail((String)(row.get("Email")));
em.setPhoneNumber((String)(row.get("PhoneNumber")));
Date d = (Date)(row.get("HireDate"));
em.setHireDate(d.toString());
em.setSalary(String.valueOf(row.get("Salary")));
EMList.add(em);
}
return EMList;
}
}
| UTF-8 | Java | 1,546 | java | JDBCVEmployee.java | Java | [
{
"context": "bc.core.support.JdbcDaoSupport;\n/**\n *\n * @author 7\n */\npublic class JDBCVEmployee extends JdbcDaoSup",
"end": 354,
"score": 0.9663354158401489,
"start": 353,
"tag": "USERNAME",
"value": "7"
}
]
| null | []
| package com.dev.spring.dao.impl;
import com.dev.spring.dao.VEmployeeDao;
import com.dev.spring.dao.model.VEmployee;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
*
* @author 7
*/
public class JDBCVEmployee extends JdbcDaoSupport implements VEmployeeDao{
public List<VEmployee> getEmlist() {
String sql = "SELECT * FROM vemployee";
List<VEmployee> EMList = getJdbcTemplate().query(sql,
new BeanPropertyRowMapper(VEmployee.class));
return EMList;
}
public List<VEmployee> searchEMFromFilter(String Firstname, String Lastname, String Job, String Department, String Manager) {
String name = "%"+Firstname+" "+Lastname+"%";
String sql = "SELECT * FROM `vemployee` where `name` LIKE '"+name+"'";
List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql);
List<VEmployee> EMList = new LinkedList<VEmployee>();
for (Map row : rows) {
VEmployee em = new VEmployee();
em.setName((String)(row.get("name")));
em.setEmail((String)(row.get("Email")));
em.setPhoneNumber((String)(row.get("PhoneNumber")));
Date d = (Date)(row.get("HireDate"));
em.setHireDate(d.toString());
em.setSalary(String.valueOf(row.get("Salary")));
EMList.add(em);
}
return EMList;
}
}
| 1,546 | 0.646831 | 0.646184 | 50 | 29.92 | 27.906157 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.92 | false | false | 15 |
f9edc7011e2d613760b8ea9b68bf5ac9307efa6b | 3,796,751,130,855 | d477c9d02f771c98e323a84ce9ac27a496798a5c | /User.java | 12850b907f92d26108cb20b28d861730ef273ecd | []
| no_license | AACuellar96/CS-356-Project2 | https://github.com/AACuellar96/CS-356-Project2 | e3f730b27365e4fd656392595070b9cf8bbea4b6 | 77774393e28d5000474892f98d1eca4fed67f5eb | refs/heads/master | 2020-12-24T11:33:19.837000 | 2016-11-09T07:00:10 | 2016-11-09T07:00:10 | 73,029,046 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by Adrian on 10/29/2016.
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
/**
* User class that will consist of most entries made by users.
*/
public class User extends baseUser implements Observer{
/**
* A user's followings, or the list of Users they are following.
*/
private List<User> followings;
/**
* A user's twitter feeds, or their messages along with the messages of those they are following.
*/
private List<String> twitterFeeds;
/**
* Constructor. Creates everything.
* @param id The user's unique ID.
*/
public User(String id){
setUniqueID(id);
followings=new ArrayList<>();
twitterFeeds=new ArrayList<>();
}
/**
* Follows a user and adds them to the list of followings.
* @param user The user to follow.
*/
public void follow(User user){
followings.add(user);
}
/**
* Updates twitterfeed with observed user's last tweet if that is what is being notified.
* @param obs Observed user.
* @param obj What they are changing.
*/
public void update(Observable obs,Object obj){
if(obj instanceof String)
twitterFeeds.add((String) obj);
}
/**
* 'Tweets' a message, adds it to twitterfeed and alerts followers of this change.
* @param tweet New message to be added to twitterfeed.
*/
public void tweet(String tweet){
tweet=getUniqueID()+":"+tweet;
twitterFeeds.add(tweet);
setChanged();
notifyObservers(new String (tweet));
}
/**
* Gets twitterFeed
* @return TwitterFeed
*/
public List<String> getTwitterFeeds() {
return twitterFeeds;
}
/**
* Gets list of followings.
* @return Followings
*/
public List<User> getFollowings() {
return followings;
}
/**
* Accepts a visitor. Visitor records data.
* @param vis Visitor to accept.
*/
public void accept(Visitor vis){
vis.record(this);
}
/**
* Users id for hashtable storage
* @return uniqueID+"USER"
*/
public String getTableID(){
return getUniqueID()+"USER";
}
}
| UTF-8 | Java | 2,367 | java | User.java | Java | [
{
"context": "/**\r\n * Created by Adrian on 10/29/2016.\r\n */\r\nimport java.util.List;\r\nimpo",
"end": 25,
"score": 0.9996579885482788,
"start": 19,
"tag": "NAME",
"value": "Adrian"
}
]
| null | []
| /**
* Created by Adrian on 10/29/2016.
*/
import java.util.List;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
/**
* User class that will consist of most entries made by users.
*/
public class User extends baseUser implements Observer{
/**
* A user's followings, or the list of Users they are following.
*/
private List<User> followings;
/**
* A user's twitter feeds, or their messages along with the messages of those they are following.
*/
private List<String> twitterFeeds;
/**
* Constructor. Creates everything.
* @param id The user's unique ID.
*/
public User(String id){
setUniqueID(id);
followings=new ArrayList<>();
twitterFeeds=new ArrayList<>();
}
/**
* Follows a user and adds them to the list of followings.
* @param user The user to follow.
*/
public void follow(User user){
followings.add(user);
}
/**
* Updates twitterfeed with observed user's last tweet if that is what is being notified.
* @param obs Observed user.
* @param obj What they are changing.
*/
public void update(Observable obs,Object obj){
if(obj instanceof String)
twitterFeeds.add((String) obj);
}
/**
* 'Tweets' a message, adds it to twitterfeed and alerts followers of this change.
* @param tweet New message to be added to twitterfeed.
*/
public void tweet(String tweet){
tweet=getUniqueID()+":"+tweet;
twitterFeeds.add(tweet);
setChanged();
notifyObservers(new String (tweet));
}
/**
* Gets twitterFeed
* @return TwitterFeed
*/
public List<String> getTwitterFeeds() {
return twitterFeeds;
}
/**
* Gets list of followings.
* @return Followings
*/
public List<User> getFollowings() {
return followings;
}
/**
* Accepts a visitor. Visitor records data.
* @param vis Visitor to accept.
*/
public void accept(Visitor vis){
vis.record(this);
}
/**
* Users id for hashtable storage
* @return uniqueID+"USER"
*/
public String getTableID(){
return getUniqueID()+"USER";
}
}
| 2,367 | 0.581749 | 0.578369 | 92 | 23.72826 | 21.729115 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 15 |
6304a143bbbf6aeaddcb1f0ed0ec1a860ef06f93 | 7,567,732,403,027 | 8180e5f5c04d5c334c2b9f7f3403e15597d17969 | /src/javaBySSS/WrapperClassDemo.java | 2c0e716ee991320ab764a840e40fb5955144bc8b | []
| no_license | nayankumarmpqa/CoreJavaPracticeProject | https://github.com/nayankumarmpqa/CoreJavaPracticeProject | 30efd296568d7ad2a696a84dc73b959dc92d3e5f | 02b76efd1f54a1968f34c6cd1e72403f2b9d069e | refs/heads/master | 2023-04-09T20:00:37.628000 | 2021-04-27T13:33:50 | 2021-04-27T13:33:50 | 332,504,066 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package javaBySSS;
public class WrapperClassDemo {
public static void main(String[] args) {
int a = Integer.parseInt("123");
System.out.println(a);
int parsint = Integer.parseInt("89");
System.out.println(parsint);
Integer refva = Integer.valueOf("565");
int intval =refva.intValue();
System.out.println(intval);
/*
* valueOf()
* ststic method
* return object ref of relative wrapper class
*
* parsexxx()
* static method xxx can be replaced by any primitive type
* it returns
* xxx type value
*
* xxxValue()
* instance method of wrapper class
* xxx can be replaced by any
* primitive type returns corresponding primitive type
*/
}
}
| UTF-8 | Java | 721 | java | WrapperClassDemo.java | Java | []
| null | []
| package javaBySSS;
public class WrapperClassDemo {
public static void main(String[] args) {
int a = Integer.parseInt("123");
System.out.println(a);
int parsint = Integer.parseInt("89");
System.out.println(parsint);
Integer refva = Integer.valueOf("565");
int intval =refva.intValue();
System.out.println(intval);
/*
* valueOf()
* ststic method
* return object ref of relative wrapper class
*
* parsexxx()
* static method xxx can be replaced by any primitive type
* it returns
* xxx type value
*
* xxxValue()
* instance method of wrapper class
* xxx can be replaced by any
* primitive type returns corresponding primitive type
*/
}
}
| 721 | 0.650485 | 0.63939 | 36 | 19.027779 | 17.428404 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.805556 | false | false | 15 |
625406f924310e63ee14c7f3f4ff283465bb4bf2 | 10,462,540,345,506 | f86938ea6307bf6d1d89a07b5b5f9e360673d9b8 | /CodeComment_Data/Code_Jam/train/Magic_Trick/S/A(348).java | f7297511363ebdede621cd7791d3cae983a4149b | []
| no_license | yxh-y/code_comment_generation | https://github.com/yxh-y/code_comment_generation | 8367b355195a8828a27aac92b3c738564587d36f | 2c7bec36dd0c397eb51ee5bd77c94fa9689575fa | refs/heads/master | 2021-09-28T18:52:40.660000 | 2018-11-19T14:54:56 | 2018-11-19T14:54:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package methodEmbedding.Magic_Trick.S.LYD1840;
import java.io.*;
import java.util.*;
public class A {
public static void main(String [] args)throws IOException{
//BufferedReader k = new BufferedReader(new FileReader("H:uva.txt"));
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
PrintWriter z = new PrintWriter(System.out);
//PrintWriter z = new PrintWriter(new FileWriter("H:uvaans.txt"));
int T = Integer.valueOf(k.readLine());
int test = 1;
while(T-->0){
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
int ans1 = Integer.valueOf(k.readLine());
ans1--;
int [][] y = new int[4][4];
for(int c = 0;c<4;c++){
int d = 0;
StringTokenizer s = new StringTokenizer(k.readLine());
while(s.hasMoreTokens()){
y[c][d] = Integer.valueOf(s.nextToken());
if(c==ans1){
list1.add(y[c][d]);
}
d++;
}
}
int ans2 = Integer.valueOf(k.readLine());
ans2--;
int [][] yy = new int[4][4];
for(int c = 0;c<4;c++){
int d = 0;
StringTokenizer s = new StringTokenizer(k.readLine());
while(s.hasMoreTokens()){
yy[c][d] = Integer.valueOf(s.nextToken());
if(c==ans2){
list2.add(yy[c][d]);
}
d++;
}
}
int j = 0;
int fans = 0;
for(int c = 0;c<4;c++){
int v1 = list1.get(c);
for(int d = 0;d<4;d++){
int v2 = list2.get(d);
if(v2==v1){
j++;
fans = v2;
}
}
}
if(j==1){
z.println("Case #"+(test++)+": "+fans);
}
else if(j>1){
z.println("Case #"+(test++)+": "+"Bad magician!");
}
else{
z.println("Case #"+(test++)+": "+"Volunteer cheated!");
}
}
z.flush();
}
}
| UTF-8 | Java | 1,749 | java | A(348).java | Java | []
| null | []
| package methodEmbedding.Magic_Trick.S.LYD1840;
import java.io.*;
import java.util.*;
public class A {
public static void main(String [] args)throws IOException{
//BufferedReader k = new BufferedReader(new FileReader("H:uva.txt"));
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
PrintWriter z = new PrintWriter(System.out);
//PrintWriter z = new PrintWriter(new FileWriter("H:uvaans.txt"));
int T = Integer.valueOf(k.readLine());
int test = 1;
while(T-->0){
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
int ans1 = Integer.valueOf(k.readLine());
ans1--;
int [][] y = new int[4][4];
for(int c = 0;c<4;c++){
int d = 0;
StringTokenizer s = new StringTokenizer(k.readLine());
while(s.hasMoreTokens()){
y[c][d] = Integer.valueOf(s.nextToken());
if(c==ans1){
list1.add(y[c][d]);
}
d++;
}
}
int ans2 = Integer.valueOf(k.readLine());
ans2--;
int [][] yy = new int[4][4];
for(int c = 0;c<4;c++){
int d = 0;
StringTokenizer s = new StringTokenizer(k.readLine());
while(s.hasMoreTokens()){
yy[c][d] = Integer.valueOf(s.nextToken());
if(c==ans2){
list2.add(yy[c][d]);
}
d++;
}
}
int j = 0;
int fans = 0;
for(int c = 0;c<4;c++){
int v1 = list1.get(c);
for(int d = 0;d<4;d++){
int v2 = list2.get(d);
if(v2==v1){
j++;
fans = v2;
}
}
}
if(j==1){
z.println("Case #"+(test++)+": "+fans);
}
else if(j>1){
z.println("Case #"+(test++)+": "+"Bad magician!");
}
else{
z.println("Case #"+(test++)+": "+"Volunteer cheated!");
}
}
z.flush();
}
}
| 1,749 | 0.5506 | 0.527158 | 75 | 22.32 | 19.994772 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.746667 | false | false | 15 |
3cd32207f3f3b766666e17427ee6a632b9b1d607 | 22,299,470,229,408 | 3d60dd286f15b2b18ab3bc5dd21b1bb98ca39040 | /src/main/java/ip/ppro/currencyexchangeservices/CurrencyExchangeController.java | b62f10fd2e0e7bbb83589d2eefa197a1ff56c101 | []
| no_license | MisterMaurya/currency-exchange-service | https://github.com/MisterMaurya/currency-exchange-service | d4815d8cdf0bcd257403514c44d762b9e68568ae | 3e7f22d6dd9f998ff6a7bb386ca92eb0ede9e53a | refs/heads/master | 2023-06-21T05:48:21.594000 | 2021-08-14T10:15:27 | 2021-08-14T10:15:27 | 395,969,759 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ip.ppro.currencyexchangeservices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/***
* @author Pawan Maurya
* @since Aug 07, 2021
*/
@RestController
public class CurrencyExchangeController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
// To get the environment variable
@Autowired
private Environment environment;
@Autowired
private ExchangeValueRepository repository;
@GetMapping("/currency-exchange/from/{from}/to/{to}")
public ExchangeValue retrieveExchangeValue(@PathVariable String from,
@PathVariable String to) {
ExchangeValue byFromAndTo = repository.findByFromAndTo(from, to);
logger.info("{}", "currency-exchange-service");
byFromAndTo.setPort(environment.getProperty("local.server.port", Integer.class));
return byFromAndTo;
}
}
| UTF-8 | Java | 1,202 | java | CurrencyExchangeController.java | Java | [
{
"context": "b.bind.annotation.RestController;\n\n/***\n * @author Pawan Maurya\n * @since Aug 07, 2021\n */\n\n@RestController\npubli",
"end": 424,
"score": 0.9997724294662476,
"start": 412,
"tag": "NAME",
"value": "Pawan Maurya"
}
]
| null | []
| package ip.ppro.currencyexchangeservices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/***
* @author <NAME>
* @since Aug 07, 2021
*/
@RestController
public class CurrencyExchangeController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
// To get the environment variable
@Autowired
private Environment environment;
@Autowired
private ExchangeValueRepository repository;
@GetMapping("/currency-exchange/from/{from}/to/{to}")
public ExchangeValue retrieveExchangeValue(@PathVariable String from,
@PathVariable String to) {
ExchangeValue byFromAndTo = repository.findByFromAndTo(from, to);
logger.info("{}", "currency-exchange-service");
byFromAndTo.setPort(environment.getProperty("local.server.port", Integer.class));
return byFromAndTo;
}
}
| 1,196 | 0.732945 | 0.72629 | 37 | 31.486486 | 27.250214 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false | 15 |
a2cd96dfb9fdfc5028aba480fc69b27bac691167 | 2,018,634,699,485 | 829cfebe49b893542d8a1d42b9dcede638d9e285 | /src/splat/test/task/model/TabHandler.java | eb64824da7bb3d23cea2ac21aad129694e1e280f | []
| no_license | KaryNaiKo/LogScanner | https://github.com/KaryNaiKo/LogScanner | 3de03ba793b25932dfab679830271a1d175506da | 4ef7f754fa35cfc2be051c00e2004729cb69d123 | refs/heads/master | 2020-04-17T12:35:18.897000 | 2019-01-24T12:35:42 | 2019-01-24T12:35:42 | 166,547,390 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package splat.test.task.model;
import splat.test.task.exeptions.ExceptionHandler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayDeque;
public class TabHandler {
private String keyWord;
private RandomAccessFile reader;
private ArrayDeque<Long> positionsOfPreviousKeyWord;
private long currentBytePos;
private final int SIZE_FOR_READING = 1024;
public TabHandler(String keyWord, Path path) throws FileNotFoundException {
this.keyWord = keyWord;
this.reader = new RandomAccessFile(path.toFile(), "r");
this.positionsOfPreviousKeyWord = new ArrayDeque<>();
}
public String[] loadFirst() {
try {
long pos = findFistEntry();
return readFrom(pos - SIZE_FOR_READING / 2);
} catch (IOException e) {
ExceptionHandler.logExeption(e);
}
return null;
}
public String[] loadNext() {
try {
long pos = findNextEntry();
if (pos != -1) {
return readFrom(pos - SIZE_FOR_READING / 2);
}
} catch (IOException e) {
ExceptionHandler.logExeption(e);
}
return null;
}
public String[] loadPrevious() {
try {
long pos = findPreviousEntry();
if (pos != -1) {
return readFrom(pos - SIZE_FOR_READING / 2);
}
} catch (IOException e) {
ExceptionHandler.logExeption(e);
}
return null;
}
private long findFistEntry() throws IOException {
return findEntry(0);
}
private long findEntry(long start) throws IOException {
reader.seek(start);
currentBytePos = start;
boolean isFound = false;
int length;
do {
byte[] bytes = new byte[SIZE_FOR_READING];
length = reader.read(bytes, 0, SIZE_FOR_READING);
if(length != -1) {
String str = new String(bytes, 0, length);
if (str.contains(keyWord)) {
currentBytePos += str.substring(0, str.indexOf(keyWord)).getBytes().length;
isFound = true;
} else {
currentBytePos += length;
}
} else {
break;
}
} while (!isFound);
if (isFound) {
return currentBytePos;
}
return -1;
}
private long findNextEntry() throws IOException {
if (positionsOfPreviousKeyWord.isEmpty()) {
positionsOfPreviousKeyWord.addFirst(currentBytePos);
} else if (positionsOfPreviousKeyWord.peek() != currentBytePos - 1) {
positionsOfPreviousKeyWord.addFirst(currentBytePos);
}
return findEntry(currentBytePos + 1);
}
private long findPreviousEntry() {
currentBytePos = positionsOfPreviousKeyWord.peek() != null ? positionsOfPreviousKeyWord.poll() : -1;
return currentBytePos;
}
private String[] readFrom(long from) throws IOException {
if (from < 0) from = 0;
reader.seek(from);
long index = (currentBytePos - from) % SIZE_FOR_READING;
byte[] bytes = new byte[SIZE_FOR_READING];
int length = reader.read(bytes, 0, SIZE_FOR_READING);
if (length != -1) {
String[] strings = new String[3];
strings[0] = new String(bytes, 0, (int) index, StandardCharsets.UTF_8);
strings[1] = new String(bytes, (int) index, keyWord.length(), StandardCharsets.UTF_8);
strings[2] = new String(bytes, (int) index + keyWord.length(), length - ((int) index + keyWord.length()), StandardCharsets.UTF_8);
return strings;
}
return null;
}
} | UTF-8 | Java | 3,900 | java | TabHandler.java | Java | []
| null | []
| package splat.test.task.model;
import splat.test.task.exeptions.ExceptionHandler;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayDeque;
public class TabHandler {
private String keyWord;
private RandomAccessFile reader;
private ArrayDeque<Long> positionsOfPreviousKeyWord;
private long currentBytePos;
private final int SIZE_FOR_READING = 1024;
public TabHandler(String keyWord, Path path) throws FileNotFoundException {
this.keyWord = keyWord;
this.reader = new RandomAccessFile(path.toFile(), "r");
this.positionsOfPreviousKeyWord = new ArrayDeque<>();
}
public String[] loadFirst() {
try {
long pos = findFistEntry();
return readFrom(pos - SIZE_FOR_READING / 2);
} catch (IOException e) {
ExceptionHandler.logExeption(e);
}
return null;
}
public String[] loadNext() {
try {
long pos = findNextEntry();
if (pos != -1) {
return readFrom(pos - SIZE_FOR_READING / 2);
}
} catch (IOException e) {
ExceptionHandler.logExeption(e);
}
return null;
}
public String[] loadPrevious() {
try {
long pos = findPreviousEntry();
if (pos != -1) {
return readFrom(pos - SIZE_FOR_READING / 2);
}
} catch (IOException e) {
ExceptionHandler.logExeption(e);
}
return null;
}
private long findFistEntry() throws IOException {
return findEntry(0);
}
private long findEntry(long start) throws IOException {
reader.seek(start);
currentBytePos = start;
boolean isFound = false;
int length;
do {
byte[] bytes = new byte[SIZE_FOR_READING];
length = reader.read(bytes, 0, SIZE_FOR_READING);
if(length != -1) {
String str = new String(bytes, 0, length);
if (str.contains(keyWord)) {
currentBytePos += str.substring(0, str.indexOf(keyWord)).getBytes().length;
isFound = true;
} else {
currentBytePos += length;
}
} else {
break;
}
} while (!isFound);
if (isFound) {
return currentBytePos;
}
return -1;
}
private long findNextEntry() throws IOException {
if (positionsOfPreviousKeyWord.isEmpty()) {
positionsOfPreviousKeyWord.addFirst(currentBytePos);
} else if (positionsOfPreviousKeyWord.peek() != currentBytePos - 1) {
positionsOfPreviousKeyWord.addFirst(currentBytePos);
}
return findEntry(currentBytePos + 1);
}
private long findPreviousEntry() {
currentBytePos = positionsOfPreviousKeyWord.peek() != null ? positionsOfPreviousKeyWord.poll() : -1;
return currentBytePos;
}
private String[] readFrom(long from) throws IOException {
if (from < 0) from = 0;
reader.seek(from);
long index = (currentBytePos - from) % SIZE_FOR_READING;
byte[] bytes = new byte[SIZE_FOR_READING];
int length = reader.read(bytes, 0, SIZE_FOR_READING);
if (length != -1) {
String[] strings = new String[3];
strings[0] = new String(bytes, 0, (int) index, StandardCharsets.UTF_8);
strings[1] = new String(bytes, (int) index, keyWord.length(), StandardCharsets.UTF_8);
strings[2] = new String(bytes, (int) index + keyWord.length(), length - ((int) index + keyWord.length()), StandardCharsets.UTF_8);
return strings;
}
return null;
}
} | 3,900 | 0.57641 | 0.568718 | 119 | 31.781513 | 25.456226 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.647059 | false | false | 15 |
b32ef052dc754ea0801edc2a223f126be383201a | 2,018,634,699,768 | 292775f9448489a5d68b27ec3ce4c4fab6fd9b41 | /aPliKa371/base/src/org/openup/model/MITSociosCtaCte.java | f58f10b22ebf1ec1af56cfbce17aa22e5ac9fcc2 | []
| no_license | gvilauy/aPliKa371 | https://github.com/gvilauy/aPliKa371 | 74397dbfabb90c558097632879bd5234d0330e04 | d68cbcaae2527fc88ccf045a8329e14e20bd4660 | refs/heads/master | 2020-05-23T09:36:18.939000 | 2017-03-26T19:22:39 | 2017-03-26T19:22:39 | 84,696,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.openup.model;
import java.sql.ResultSet;
import java.util.Properties;
public class MITSociosCtaCte extends X_IT_Socios_Cta_Cte {
private static final long serialVersionUID = 8340964741045473038L;
public MITSociosCtaCte(Properties ctx, int IT_Socios_Cta_Cte_ID,
String trxName) {
super(ctx, IT_Socios_Cta_Cte_ID, trxName);
}
public MITSociosCtaCte(Properties ctx, ResultSet rs, String trxName) {
super(ctx, rs, trxName);
}
}
| UTF-8 | Java | 454 | java | MITSociosCtaCte.java | Java | []
| null | []
| package org.openup.model;
import java.sql.ResultSet;
import java.util.Properties;
public class MITSociosCtaCte extends X_IT_Socios_Cta_Cte {
private static final long serialVersionUID = 8340964741045473038L;
public MITSociosCtaCte(Properties ctx, int IT_Socios_Cta_Cte_ID,
String trxName) {
super(ctx, IT_Socios_Cta_Cte_ID, trxName);
}
public MITSociosCtaCte(Properties ctx, ResultSet rs, String trxName) {
super(ctx, rs, trxName);
}
}
| 454 | 0.759912 | 0.718062 | 19 | 22.894737 | 25.408028 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.368421 | false | false | 15 |
359cd1935854cfac1252c2b97373c01b045ae944 | 18,064,632,467,254 | eb1796f0afa60b1b3a9a93c0815e48316da1371f | /src/com/service/CommodityServiceImpl.java | d0f8152dc727895de90e3d46ac386b813126883a | []
| no_license | jsczh/graduateDesign | https://github.com/jsczh/graduateDesign | b8ce67de372f5e2fb6b11c2076d25f7dc100ab23 | ea7b8dee2cc16cbfb9ec1d8fb0365192480a25af | refs/heads/master | 2020-05-25T03:18:41.535000 | 2020-05-21T14:32:40 | 2020-05-21T14:32:40 | 187,599,097 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bean.Commodity;
import com.mapper.CommodityMapper;
@Service("commodityService")
public class CommodityServiceImpl implements CommodityService {
@Autowired
CommodityMapper commodity;
@Override
public int deleteByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return commodity.deleteByPrimaryKey(id);
}
@Override
public int insert(Commodity record) {
// TODO Auto-generated method stub
return commodity.insert(record);
}
@Override
public int insertSelective(Commodity record) {
// TODO Auto-generated method stub
return commodity.insertSelective(record);
}
@Override
public Commodity selectByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return commodity.selectByPrimaryKey(id);
}
@Override
public List<Commodity> selectAllCommodityByShopId(Integer id) {
// TODO Auto-generated method stub
return commodity.selectAllCommodityByShopId(id);
}
@Override
public int updateByPrimaryKeySelective(Commodity record) {
// TODO Auto-generated method stub
return commodity.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Commodity record) {
// TODO Auto-generated method stub
return commodity.updateByPrimaryKey(record);
}
@Override
public Commodity selectByCommodityNameAndShopId(String commodityname, int shopid) {
// TODO Auto-generated method stub
return commodity.selectByCommodityNameAndShopId(commodityname, shopid);
}
@Override
public List<Commodity> selectCommodityPartly(Integer start, Integer count) {
// TODO Auto-generated method stub
return commodity.selectCommodityPartly(start, count);
}
@Override
public int selectCommodityNum(Integer id) {
// TODO Auto-generated method stub
return commodity.selectCommodityNum(id);
}
@Override
public List<Commodity> selectCommodityPartlyByShopId(Integer start, Integer count, Integer id) {
// TODO Auto-generated method stub
return commodity.selectCommodityPartlyByShopId(start, count, id);
}
@Override
public List<Commodity> selectCommodityByType(String type) {
// TODO Auto-generated method stub
return commodity.selectCommodityByType(type);
}
@Override
public List<Commodity> selectCommodityByTypeRandom4(String type) {
// TODO Auto-generated method stub
return commodity.selectCommodityByTypeRandom4(type);
}
@Override
public List<Commodity> selectCommodityByVagueName(String name) {
// TODO Auto-generated method stub
return commodity.selectCommodityByVagueName(name);
}
@Override
public List<Commodity> selectCommodityPartlyByVagueName(Integer start, Integer count, String name) {
// TODO Auto-generated method stub
return commodity.selectCommodityPartlyByVagueName(start, count, name);
}
@Override
public List<Integer> selectAllCommodityId() {
// TODO Auto-generated method stub
return commodity.selectAllCommodityId();
}
}
| UTF-8 | Java | 3,029 | java | CommodityServiceImpl.java | Java | []
| null | []
| package com.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bean.Commodity;
import com.mapper.CommodityMapper;
@Service("commodityService")
public class CommodityServiceImpl implements CommodityService {
@Autowired
CommodityMapper commodity;
@Override
public int deleteByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return commodity.deleteByPrimaryKey(id);
}
@Override
public int insert(Commodity record) {
// TODO Auto-generated method stub
return commodity.insert(record);
}
@Override
public int insertSelective(Commodity record) {
// TODO Auto-generated method stub
return commodity.insertSelective(record);
}
@Override
public Commodity selectByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return commodity.selectByPrimaryKey(id);
}
@Override
public List<Commodity> selectAllCommodityByShopId(Integer id) {
// TODO Auto-generated method stub
return commodity.selectAllCommodityByShopId(id);
}
@Override
public int updateByPrimaryKeySelective(Commodity record) {
// TODO Auto-generated method stub
return commodity.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(Commodity record) {
// TODO Auto-generated method stub
return commodity.updateByPrimaryKey(record);
}
@Override
public Commodity selectByCommodityNameAndShopId(String commodityname, int shopid) {
// TODO Auto-generated method stub
return commodity.selectByCommodityNameAndShopId(commodityname, shopid);
}
@Override
public List<Commodity> selectCommodityPartly(Integer start, Integer count) {
// TODO Auto-generated method stub
return commodity.selectCommodityPartly(start, count);
}
@Override
public int selectCommodityNum(Integer id) {
// TODO Auto-generated method stub
return commodity.selectCommodityNum(id);
}
@Override
public List<Commodity> selectCommodityPartlyByShopId(Integer start, Integer count, Integer id) {
// TODO Auto-generated method stub
return commodity.selectCommodityPartlyByShopId(start, count, id);
}
@Override
public List<Commodity> selectCommodityByType(String type) {
// TODO Auto-generated method stub
return commodity.selectCommodityByType(type);
}
@Override
public List<Commodity> selectCommodityByTypeRandom4(String type) {
// TODO Auto-generated method stub
return commodity.selectCommodityByTypeRandom4(type);
}
@Override
public List<Commodity> selectCommodityByVagueName(String name) {
// TODO Auto-generated method stub
return commodity.selectCommodityByVagueName(name);
}
@Override
public List<Commodity> selectCommodityPartlyByVagueName(Integer start, Integer count, String name) {
// TODO Auto-generated method stub
return commodity.selectCommodityPartlyByVagueName(start, count, name);
}
@Override
public List<Integer> selectAllCommodityId() {
// TODO Auto-generated method stub
return commodity.selectAllCommodityId();
}
}
| 3,029 | 0.785738 | 0.785078 | 112 | 26.044643 | 25.247486 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.330357 | false | false | 15 |
de7732cde1fe32c6097d2847a5aa1a3d8d727b2a | 5,626,407,215,944 | 55b604d0500698e1d1c7d45499bea598e9486e57 | /Backtracking/Letter_Combinations_of_a_Phone_Number.java | 068d6bdab3cd36b02b6ae22de704cbcfd7a562f0 | [
"MIT"
]
| permissive | Yujia-Xiao/Leetcode | https://github.com/Yujia-Xiao/Leetcode | f4daef4146cf9674d5fb27249fc3f9693986591a | 45e15f911d6beada99b712253cbec51881dbb1f4 | refs/heads/master | 2020-04-06T13:11:51.673000 | 2018-09-11T06:19:46 | 2018-09-11T06:19:46 | 47,289,017 | 9 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Letter Combinations of a Phone Number My Submissions QuestionEditorial Solution
Total Accepted: 83943 Total Submissions: 286410 Difficulty: Medium
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Hide Company Tags Amazon Dropbox Google Uber Facebook
Hide Tags Backtracking String
Hide Similar Problems (M) Generate Parentheses (M) Combination Sum
*/
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> ans = new LinkedList<String>();
if(digits==null || digits.length()==0)return ans;
Map<Character,String> map = new HashMap<Character,String>();
map.put('1',"");map.put('2',"abc");map.put('3',"def");map.put('4',"ghi");
map.put('5',"jkl");map.put('6',"mno");map.put('7',"pqrs");map.put('8',"tuv");
map.put('9',"wxyz");map.put('0',"");
backtrack(ans,new StringBuilder(),digits,0,map);
return ans;
}
public void backtrack(List<String> ans, StringBuilder temS, String digits,int start, Map<Character,String> map){
if(start==digits.length())ans.add(temS.toString());
else{
char ch = digits.charAt(start);
String s = map.get(ch);
for(int j=0;j<s.length();j++){
temS.append(s.charAt(j));
backtrack(ans,temS,digits,start+1,map);
temS.deleteCharAt(temS.length()-1);
}
}
}
} | UTF-8 | Java | 1,756 | java | Letter_Combinations_of_a_Phone_Number.java | Java | []
| null | []
| /*
Letter Combinations of a Phone Number My Submissions QuestionEditorial Solution
Total Accepted: 83943 Total Submissions: 286410 Difficulty: Medium
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
Hide Company Tags Amazon Dropbox Google Uber Facebook
Hide Tags Backtracking String
Hide Similar Problems (M) Generate Parentheses (M) Combination Sum
*/
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> ans = new LinkedList<String>();
if(digits==null || digits.length()==0)return ans;
Map<Character,String> map = new HashMap<Character,String>();
map.put('1',"");map.put('2',"abc");map.put('3',"def");map.put('4',"ghi");
map.put('5',"jkl");map.put('6',"mno");map.put('7',"pqrs");map.put('8',"tuv");
map.put('9',"wxyz");map.put('0',"");
backtrack(ans,new StringBuilder(),digits,0,map);
return ans;
}
public void backtrack(List<String> ans, StringBuilder temS, String digits,int start, Map<Character,String> map){
if(start==digits.length())ans.add(temS.toString());
else{
char ch = digits.charAt(start);
String s = map.get(ch);
for(int j=0;j<s.length();j++){
temS.append(s.charAt(j));
backtrack(ans,temS,digits,start+1,map);
temS.deleteCharAt(temS.length()-1);
}
}
}
} | 1,756 | 0.628702 | 0.612756 | 44 | 38.93182 | 32.125038 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.363636 | false | false | 15 |
ee824a24edb0b945c29b62099d8f9270fee9d975 | 704,374,698,283 | a0fe2e1b6a0e5a287592a60b434d4e78cf2172ed | /src/main/java/com/yx/test/socket/TCPClient.java | 7d9b7735e97a7b63f19ad095d60297a7e4b01757 | []
| no_license | liyuexin/se_example | https://github.com/liyuexin/se_example | b9de0b0cb81b303669e0fa8123b3a1c99afec890 | d12b33ec951cbc8f0cb36e676efb7293d98367f8 | refs/heads/master | 2016-09-22T05:33:16.432000 | 2016-09-20T09:37:45 | 2016-09-20T09:37:45 | 66,775,719 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yx.test.socket;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost", 8888);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hello server");
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 607 | java | TCPClient.java | Java | []
| null | []
| package com.yx.test.socket;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost", 8888);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hello server");
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 607 | 0.596376 | 0.589786 | 22 | 26.59091 | 16.778393 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.636364 | false | false | 15 |
4ac82d23146c0d6ae4b386f42e88ea58212e24e0 | 20,916,490,748,657 | 235c59a5fdc57cf62d2d40673394308049116c1d | /core/src/com/ppioli/url/actors/actions/Action.java | 51d12b2caf6e47750aa583c5be956d1579e1cd4f | []
| no_license | ppioli/UntitledRogueLIke | https://github.com/ppioli/UntitledRogueLIke | b43b8b883474d63b3d9b7328a1c0e4947a99629f | f6c6c1026651ef3e59a1b2d425966709465e5d01 | refs/heads/master | 2022-11-05T14:49:31.394000 | 2020-06-11T01:05:05 | 2020-06-11T01:05:05 | 271,419,126 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ppioli.url.actors.actions;
public abstract class Action implements IAction {
private long startTime;
private long duration;
public abstract boolean execute( long time );
public Action( long startTime, long duration ) {
this.startTime = startTime;
this.duration = duration;
}
public long getStartTime() {
return startTime;
}
public void setStartTime( long startTime ) {
this.startTime = startTime;
}
public long getDuration() {
return duration;
}
public void setDuration( long duration ) {
this.duration = duration;
}
public long getFinishTime() {
return this.startTime + this.duration;
}
}
| UTF-8 | Java | 728 | java | Action.java | Java | []
| null | []
| package com.ppioli.url.actors.actions;
public abstract class Action implements IAction {
private long startTime;
private long duration;
public abstract boolean execute( long time );
public Action( long startTime, long duration ) {
this.startTime = startTime;
this.duration = duration;
}
public long getStartTime() {
return startTime;
}
public void setStartTime( long startTime ) {
this.startTime = startTime;
}
public long getDuration() {
return duration;
}
public void setDuration( long duration ) {
this.duration = duration;
}
public long getFinishTime() {
return this.startTime + this.duration;
}
}
| 728 | 0.637363 | 0.637363 | 35 | 19.799999 | 18.688116 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.342857 | false | false | 15 |
52b12a2e82e3645c11bdf421b65467486d764877 | 32,444,182,965,017 | 5abd02c8f0eaec1dff43a748a9e77af10b1c15b7 | /java-base/src/main/java/practice/os/practice/threadmodule/sync/SyncDemo.java | a3e7108365ffc529f547fee7011ea1e550f62b89 | []
| no_license | lyf712/java-base | https://github.com/lyf712/java-base | aa104ecb9bcb65d9e3417ca2518a19ea764fc985 | 25460a3501b16f3bedbc9044e11d709a9476d77c | refs/heads/master | 2023-06-08T04:37:25.991000 | 2021-07-05T06:39:52 | 2021-07-05T06:39:52 | 383,035,710 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package practice.os.practice.threadmodule.sync;
/**
* @AUTHOR LYF
* @DATE 2021/5/17
* @VERSION 1.0
* @DESC
*/
public class SyncDemo {
// 同步PV操作的判断检测flag
//volatile
static public boolean flag = false;
public static void main(String[]args){
// 为演示效果,还故意将SyncTask2放在前面进行启动
new Thread(new SyncTask2()).start();
new Thread(new SyncTask1()).start();
}
}
| UTF-8 | Java | 451 | java | SyncDemo.java | Java | [
{
"context": "ice.os.practice.threadmodule.sync;\n\n/**\n * @AUTHOR LYF\n * @DATE 2021/5/17\n * @VERSION 1.0\n * @DESC\n */\np",
"end": 67,
"score": 0.999610960483551,
"start": 64,
"tag": "USERNAME",
"value": "LYF"
}
]
| null | []
| package practice.os.practice.threadmodule.sync;
/**
* @AUTHOR LYF
* @DATE 2021/5/17
* @VERSION 1.0
* @DESC
*/
public class SyncDemo {
// 同步PV操作的判断检测flag
//volatile
static public boolean flag = false;
public static void main(String[]args){
// 为演示效果,还故意将SyncTask2放在前面进行启动
new Thread(new SyncTask2()).start();
new Thread(new SyncTask1()).start();
}
}
| 451 | 0.631579 | 0.601504 | 19 | 20 | 16.657541 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false | 15 |
e46efe9627d2f14aecf522060ab08e324011237b | 2,010,044,717,477 | 1aa7a1b9402a223e56fed69537d3d52c1184713d | /blackjack2/src/main/java/maven/blackjack2/standing_simulator/GenericCacheImpl.java | 79b66bbb38594ad316b77e65a8039c629d523687 | []
| no_license | bpaulsen/blackjack | https://github.com/bpaulsen/blackjack | 9a8d642c799422f5082669e76e39a6e0a3439d02 | 8dc2ae2e95638768af571ebccfecc0bf62609882 | refs/heads/master | 2016-08-06T08:59:31.737000 | 2014-08-23T14:42:42 | 2014-08-23T14:42:42 | 23,319,412 | 0 | 0 | null | false | 2015-11-07T17:58:24 | 2014-08-25T15:52:16 | 2014-08-25T15:54:04 | 2014-08-26T05:29:06 | 194 | 0 | 0 | 0 | Java | null | null | package maven.blackjack2.standing_simulator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import maven.blackjack2.GenericCache;
import maven.blackjack2.Deck;
import maven.blackjack2.Hand;
public class GenericCacheImpl extends NonThreadSafeBaseImpl implements StandingSimulator {
private static GenericCache<Long, Double> expected_return_cache = new GenericCache<>();
public GenericCacheImpl( Hand player, Hand dealer, Deck deck ) {
super( player, dealer, deck );
}
@Override
public double expected_return() {
try {
return expected_return_cache.getValue(hash_key(player, dealer), new Callable<Double>() {
@Override
public Double call() throws Exception {
return expected_return_calc();
}
} );
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0.0;
}
}
}
| UTF-8 | Java | 934 | java | GenericCacheImpl.java | Java | []
| null | []
| package maven.blackjack2.standing_simulator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import maven.blackjack2.GenericCache;
import maven.blackjack2.Deck;
import maven.blackjack2.Hand;
public class GenericCacheImpl extends NonThreadSafeBaseImpl implements StandingSimulator {
private static GenericCache<Long, Double> expected_return_cache = new GenericCache<>();
public GenericCacheImpl( Hand player, Hand dealer, Deck deck ) {
super( player, dealer, deck );
}
@Override
public double expected_return() {
try {
return expected_return_cache.getValue(hash_key(player, dealer), new Callable<Double>() {
@Override
public Double call() throws Exception {
return expected_return_calc();
}
} );
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0.0;
}
}
}
| 934 | 0.730193 | 0.723769 | 31 | 29.129032 | 27.048037 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.032258 | false | false | 15 |
b3efec966ad5836b49fade1726e6ac338bb58f1f | 27,539,330,319,404 | 101cc6e45887f9ce7156f57ed4c72f09e84899fd | /Laborator4/src/pao/interfete/MyClass.java | 7e0d3459afba68e0a844655d7c070930318285d9 | []
| no_license | FlorescuMiruna/pao-labs | https://github.com/FlorescuMiruna/pao-labs | a9f197ea65bcb8e54b434c91bdd3ae19060808b9 | d154f55a835d8b2d8bb6beb99068b1c21067d3a6 | refs/heads/master | 2023-05-01T06:22:17.240000 | 2021-05-25T15:57:07 | 2021-05-25T15:57:07 | 345,727,047 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pao.interfete;
public class MyClass implements MyInterface, MyInterface2{
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.saySomething();
MyInterface.print(myClass.sayHello());
MyInterface.print(myClass.sayBye());
MyInterface myInterface = new MyClass();
myInterface.sayHello();
myInterface.saySomething();
MyInterface2 myInterface2 = new MyClass();
myInterface2.sayBye();
}
@Override
public String sayHello(){
return "Hello";
}
@Override
public String sayBye(){
return "Bye";
}
public void saySomething() {
System.out.println("Say something from MyClass");
}
}
| UTF-8 | Java | 750 | java | MyClass.java | Java | []
| null | []
| package pao.interfete;
public class MyClass implements MyInterface, MyInterface2{
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.saySomething();
MyInterface.print(myClass.sayHello());
MyInterface.print(myClass.sayBye());
MyInterface myInterface = new MyClass();
myInterface.sayHello();
myInterface.saySomething();
MyInterface2 myInterface2 = new MyClass();
myInterface2.sayBye();
}
@Override
public String sayHello(){
return "Hello";
}
@Override
public String sayBye(){
return "Bye";
}
public void saySomething() {
System.out.println("Say something from MyClass");
}
}
| 750 | 0.618667 | 0.613333 | 34 | 21.058823 | 19.233765 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 15 |
b2f6242a3bba87abbb50fecdccc604ae5642e676 | 28,552,942,601,435 | 9177e0718c62bdb76153ec5005e7122baec57aac | /Rhombus.java | f0e167f35f853e87032f1285042261ac99374943 | []
| no_license | KobzarSV/HW-7 | https://github.com/KobzarSV/HW-7 | 146298349da10ef783a565f7fad52b94c58f2077 | 4c7220cb7d12ec88f109618c7131bbb5333081c2 | refs/heads/main | 2023-08-16T09:47:37.163000 | 2021-10-15T10:41:11 | 2021-10-15T10:41:11 | 416,356,308 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.goit.HomeWork7.GraphicsEditor;
public class Rhombus extends Shape {
public Rhombus(String name) {
super(name);
}
}
| UTF-8 | Java | 143 | java | Rhombus.java | Java | []
| null | []
| package ua.goit.HomeWork7.GraphicsEditor;
public class Rhombus extends Shape {
public Rhombus(String name) {
super(name);
}
}
| 143 | 0.685315 | 0.678322 | 7 | 19.428572 | 16.255611 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 15 |
d9f2cd7aada94c2a1c4fd4222e55d16bf857a6a4 | 6,158,983,125,617 | 13a386b98dd6ab5567283a26c5e52cba926de979 | /time-table-management-ejb/src/main/java/edu/ipsas/edt/helper/CreneauHelper.java | 2757ad660d5c346db1a202c4011ee8fdda69e984 | []
| no_license | salomon16/time-table-management | https://github.com/salomon16/time-table-management | a1908f2e9ddf11330541771e6b2078cf072e6781 | 146577ca2af1111635b21aaa4665460624b0bb41 | refs/heads/master | 2021-01-18T14:19:24.933000 | 2015-06-06T11:45:04 | 2015-06-06T11:45:04 | 32,759,546 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.ipsas.edt.helper;
import java.util.ArrayList;
import java.util.Collection;
import edu.ipsas.edt.dto.CreneauDto;
import edu.ipsas.edt.model.Creneau;
public class CreneauHelper {
public static Creneau dtoToModel(CreneauDto creneauDto) {
if (creneauDto == null)
return null;
Creneau creneau = new Creneau();
creneau.setCreneauID(creneauDto.getCreneauID());
creneau.setOrdre(creneauDto.getOrdre());
creneau.setLibelle(creneauDto.getLibelle());
creneau.setDisponibilites(DisponibiliteHelper.dtoToModels(creneauDto
.getDisponibilites()));
return creneau;
}
public static CreneauDto modelToDto(Creneau creneau) {
if (creneau == null)
return null;
CreneauDto creneauDto = new CreneauDto();
creneauDto.setCreneauID(creneau.getCreneauID());
creneauDto.setOrdre(creneau.getOrdre());
creneauDto.setLibelle(creneau.getLibelle());
creneauDto.setDisponibilites(DisponibiliteHelper.modelsToDto(creneau
.getDisponibilites()));
return creneauDto;
}
public static Collection<CreneauDto> modelsToDto(
Collection<Creneau> creneaux) {
Collection<CreneauDto> creneauxDto = new ArrayList<CreneauDto>();
for (Creneau creneau : creneaux) {
creneauxDto.add(modelToDto(creneau));
}
return creneauxDto;
}
}
| UTF-8 | Java | 1,261 | java | CreneauHelper.java | Java | []
| null | []
| package edu.ipsas.edt.helper;
import java.util.ArrayList;
import java.util.Collection;
import edu.ipsas.edt.dto.CreneauDto;
import edu.ipsas.edt.model.Creneau;
public class CreneauHelper {
public static Creneau dtoToModel(CreneauDto creneauDto) {
if (creneauDto == null)
return null;
Creneau creneau = new Creneau();
creneau.setCreneauID(creneauDto.getCreneauID());
creneau.setOrdre(creneauDto.getOrdre());
creneau.setLibelle(creneauDto.getLibelle());
creneau.setDisponibilites(DisponibiliteHelper.dtoToModels(creneauDto
.getDisponibilites()));
return creneau;
}
public static CreneauDto modelToDto(Creneau creneau) {
if (creneau == null)
return null;
CreneauDto creneauDto = new CreneauDto();
creneauDto.setCreneauID(creneau.getCreneauID());
creneauDto.setOrdre(creneau.getOrdre());
creneauDto.setLibelle(creneau.getLibelle());
creneauDto.setDisponibilites(DisponibiliteHelper.modelsToDto(creneau
.getDisponibilites()));
return creneauDto;
}
public static Collection<CreneauDto> modelsToDto(
Collection<Creneau> creneaux) {
Collection<CreneauDto> creneauxDto = new ArrayList<CreneauDto>();
for (Creneau creneau : creneaux) {
creneauxDto.add(modelToDto(creneau));
}
return creneauxDto;
}
}
| 1,261 | 0.762887 | 0.762887 | 46 | 26.413044 | 21.22916 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.826087 | false | false | 15 |
1b01bc2df07c6041209902527e65b684041233e0 | 29,987,461,675,355 | f0f3231d4157ac12ad0b9c0e700e265cdbc35044 | /app/src/main/java/com/bq/daggerskeleton/sample/hardware/PreviewSurfaceReadyAction.java | 7c1e5d10d33808ab384fdfae68227f2110b860eb | []
| no_license | dgallego/DaggerSkeleton | https://github.com/dgallego/DaggerSkeleton | dbe041838654d82a792edc2f94f1337e5b24bc0d | 2cb252242165317aef95cbfb242e58c118ad41a0 | refs/heads/master | 2019-01-14T08:09:06.542000 | 2016-11-15T17:03:37 | 2016-11-15T17:03:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bq.daggerskeleton.sample.hardware;
import android.graphics.SurfaceTexture;
import com.bq.daggerskeleton.flux.Action;
public final class PreviewSurfaceReadyAction implements Action {
public final SurfaceTexture surfaceTexture;
public final int width;
public final int height;
public PreviewSurfaceReadyAction(SurfaceTexture surfaceTexture, int width, int height) {
this.surfaceTexture = surfaceTexture;
this.width = width;
this.height = height;
}
@Override public String toString() {
return "PreviewSurfaceReadyAction{" +
"width=" + width +
", height=" + height +
'}';
}
}
| UTF-8 | Java | 670 | java | PreviewSurfaceReadyAction.java | Java | []
| null | []
| package com.bq.daggerskeleton.sample.hardware;
import android.graphics.SurfaceTexture;
import com.bq.daggerskeleton.flux.Action;
public final class PreviewSurfaceReadyAction implements Action {
public final SurfaceTexture surfaceTexture;
public final int width;
public final int height;
public PreviewSurfaceReadyAction(SurfaceTexture surfaceTexture, int width, int height) {
this.surfaceTexture = surfaceTexture;
this.width = width;
this.height = height;
}
@Override public String toString() {
return "PreviewSurfaceReadyAction{" +
"width=" + width +
", height=" + height +
'}';
}
}
| 670 | 0.692537 | 0.692537 | 24 | 26.916666 | 23.045095 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false | 15 |
d4eb0cac4b8eb0ebdacd96b1b8690928fa18317e | 13,623,636,285,735 | 40183c2c5952c8d4e00eb95d17b508f7f6d7a440 | /20 9-13/src/Main4.java | 1274800b0954f6404af78ea2df4cc88a8187f36e | []
| no_license | Huidaka/Java-code | https://github.com/Huidaka/Java-code | 830f726d0bcf0b87917f030c71f6d3475a32d501 | 8852cb3bcaf931584d449eb2f6a37e2670a5d911 | refs/heads/master | 2021-08-08T09:51:43.960000 | 2020-09-21T11:54:20 | 2020-09-21T11:54:20 | 221,500,060 | 4 | 14 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Arrays;
import java.util.Scanner;
//根据必要性和优先级进行比较
class Matter implements Comparable<Matter>{
int priority;
int essential;
int index;
public Matter(int priority, int essential,int index) {
this.priority = priority;
this.essential = essential;
this.index = index;
}
@Override
public int compareTo(Matter o) {
if(o.essential != this.essential ){
return o.essential - this.essential;
}
else{
return o.priority - this.priority;
}
}
}
public class Main4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
scanner.nextLine();
Matter[] matters = new Matter[len];
for(int i=0; i<len; i++){
String temp = scanner.nextLine();
String[] strings = temp.split(" ");
matters[i] = new Matter(Integer.parseInt(strings[0]),Integer.parseInt(strings[1]),i);
}
Arrays.sort(matters);
for(Matter matter : matters){
System.out.print(matter.index+1 + " ");
}
}
}
| UTF-8 | Java | 1,186 | java | Main4.java | Java | []
| null | []
| import java.util.Arrays;
import java.util.Scanner;
//根据必要性和优先级进行比较
class Matter implements Comparable<Matter>{
int priority;
int essential;
int index;
public Matter(int priority, int essential,int index) {
this.priority = priority;
this.essential = essential;
this.index = index;
}
@Override
public int compareTo(Matter o) {
if(o.essential != this.essential ){
return o.essential - this.essential;
}
else{
return o.priority - this.priority;
}
}
}
public class Main4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int len = scanner.nextInt();
scanner.nextLine();
Matter[] matters = new Matter[len];
for(int i=0; i<len; i++){
String temp = scanner.nextLine();
String[] strings = temp.split(" ");
matters[i] = new Matter(Integer.parseInt(strings[0]),Integer.parseInt(strings[1]),i);
}
Arrays.sort(matters);
for(Matter matter : matters){
System.out.print(matter.index+1 + " ");
}
}
}
| 1,186 | 0.574138 | 0.569828 | 41 | 27.292683 | 20.005175 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.609756 | false | false | 15 |
59bedae837ed062c28d04516858653281e2855a7 | 13,683,765,830,363 | 8d6116b8d1439f5fd5e57884b7ce9b29c2303beb | /app/src/main/java/com/miaxis/inspection/model/IInspectorModel.java | 3054ddb5eb3585f62c6a144213136da5b4f4b7aa | []
| no_license | pumpkinlove/Inspection | https://github.com/pumpkinlove/Inspection | d2920a1811bf1847a8659a745dd53c92ec87ae54 | 96739867ed28d87c3981134e4a722302da9bed01 | refs/heads/master | 2021-05-14T15:39:50.820000 | 2018-03-08T01:34:10 | 2018-03-08T01:34:10 | 115,998,193 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.miaxis.inspection.model;
import com.miaxis.inspection.entity.Config;
import com.miaxis.inspection.entity.Inspector;
import java.util.List;
/**
* Created by Administrator on 2018/2/27 0027.
*/
public interface IInspectorModel {
/**
* 新增检查员
* @param inspector
*/
void addInspector(Inspector inspector);
/**
* 删除检查员
* @param inspectorCode
*/
void delInspector(String inspectorCode);
/**
* 更新检查员
* @param inspector
*/
void updateInspector(Inspector inspector);
/**
* 查询全部检查员
* @return
*/
void findAllInspector(Config config);
}
| UTF-8 | Java | 683 | java | IInspectorModel.java | Java | []
| null | []
| package com.miaxis.inspection.model;
import com.miaxis.inspection.entity.Config;
import com.miaxis.inspection.entity.Inspector;
import java.util.List;
/**
* Created by Administrator on 2018/2/27 0027.
*/
public interface IInspectorModel {
/**
* 新增检查员
* @param inspector
*/
void addInspector(Inspector inspector);
/**
* 删除检查员
* @param inspectorCode
*/
void delInspector(String inspectorCode);
/**
* 更新检查员
* @param inspector
*/
void updateInspector(Inspector inspector);
/**
* 查询全部检查员
* @return
*/
void findAllInspector(Config config);
}
| 683 | 0.630673 | 0.613459 | 38 | 15.815789 | 16.315725 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.210526 | false | false | 15 |
77c1d183a09aa2e2608ee3c0c1b737ade5421d39 | 31,181,462,590,181 | 1015f8820c17c5ae6b815c6cc5f128973c72d550 | /Acme-Canyoning 2.0/src/main/java/repositories/CurriculumRepository.java | 98fa43cf988fc78579efd2071b359cbf131fa192 | []
| no_license | rrodriguezos/Canyoning-2.0 | https://github.com/rrodriguezos/Canyoning-2.0 | 9cea8fdcec8c4a07b4dc822af09663e7811e7333 | 8cf33686cdb9e8312aca786574e65ad516ff6d14 | refs/heads/master | 2021-01-11T09:16:13.830000 | 2017-01-03T11:59:24 | 2017-01-03T11:59:24 | 77,134,960 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Curriculum;
@Repository
public interface CurriculumRepository extends
JpaRepository<Curriculum, Integer> {
@Query("select c from Curriculum c where c.trainer.id = ?1")
Collection<Curriculum> findCurriculumsByTrainer(int id);
@Query("select c from Curriculum c where c.trainer.id=?1 and c.isActive = true ")
Curriculum curriculumActiveByTrainer(Integer trainerId);
@Query("select avg(t.curriculums.size) from Trainer t")
Double averageCurriculumsByTrainer();
}
| UTF-8 | Java | 731 | java | CurriculumRepository.java | Java | []
| null | []
| package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.Curriculum;
@Repository
public interface CurriculumRepository extends
JpaRepository<Curriculum, Integer> {
@Query("select c from Curriculum c where c.trainer.id = ?1")
Collection<Curriculum> findCurriculumsByTrainer(int id);
@Query("select c from Curriculum c where c.trainer.id=?1 and c.isActive = true ")
Curriculum curriculumActiveByTrainer(Integer trainerId);
@Query("select avg(t.curriculums.size) from Trainer t")
Double averageCurriculumsByTrainer();
}
| 731 | 0.777018 | 0.774282 | 24 | 28.458334 | 26.186796 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 15 |
b7025c1f19d123fbee5ac200ae5555b7592e7fe4 | 206,158,493,168 | 72033c0a1f0058b89d4c7a4afa69e7d3d27a20d1 | /src/es/studium/Login/ConsultaProyecto.java | b496f1c2bb5e7a3c0fcb0c9e43c77b3f1dcb9442 | []
| no_license | jorgeeemilio/Login | https://github.com/jorgeeemilio/Login | 232c9e5b849914dec138ff42884a0075a543bc03 | 2dcf7879b8e040238af2f4b34e11f80c77b8d449 | refs/heads/main | 2023-03-17T21:46:56.988000 | 2021-03-03T17:30:39 | 2021-03-03T17:30:39 | 339,521,212 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package es.studium.Login;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConsultaProyecto implements ActionListener, WindowListener
{
// Ventana Consulta de Proyectos
Frame frmConsultaProyectos = new Frame("Consulta Proyectos");
TextArea listadoProyectos = new TextArea(4, 40);
Button btnPdfProyectos = new Button("PDF");
BaseDatos bd;
String sentencia = "";
String subSentencia = "";
Connection connection = null;
Statement statement = null;
Statement statementClientes = null;
ResultSet rs = null;
ResultSet rsClientes = null;
public ConsultaProyecto()
{
frmConsultaProyectos.setLayout(new FlowLayout());
// Conectar
bd = new BaseDatos();
connection = bd.conectar();
// Hacer un SELECT * FROM Proyectos
sentencia = "SELECT * FROM proyectos";
// La información está en ResultSet
// Recorrer el RS y por cada registro,
// meter una línea en el TextArea
try
{
//Crear una sentencia
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statementClientes = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
//Crear un objeto ResultSet para guardar lo obtenido
//y ejecutar la sentencia SQL
rs = statement.executeQuery(sentencia);
listadoProyectos.selectAll();
listadoProyectos.setText("");
listadoProyectos.append("id\tNombre\tInicio\tFin\tCliente\n");
while(rs.next())
{
subSentencia = "SELECT * FROM clientes WHERE idCliente="
+ rs.getString("idClienteFK");
rsClientes = statementClientes.executeQuery(subSentencia);
rsClientes.next();
String[] fechaInicioAmericana = rs.getString("fechaInicioProyecto").split("-");
String[] fechaFinAmericana = rs.getString("fechaFinProyecto").split("-");
listadoProyectos.append(rs.getInt("idProyecto")
+"\t"+rs.getString("nombreProyecto")
+"\t"+fechaInicioAmericana[2]+"/"+fechaInicioAmericana[1]+"/"+fechaInicioAmericana[0]
+"\t"+fechaFinAmericana[2]+"/"+fechaFinAmericana[1]+"/"+fechaFinAmericana[0]
+"\t"+rsClientes.getString("nombreCliente")
+"\t"+rsClientes.getString("cifCliente")
+"\n");
}
}
catch (SQLException sqle)
{
listadoProyectos.setText("Se ha producido un error en la consulta");
}
finally
{
}
listadoProyectos.setEditable(false);
frmConsultaProyectos.add(listadoProyectos);
frmConsultaProyectos.add(btnPdfProyectos);
frmConsultaProyectos.setSize(300,140);
frmConsultaProyectos.setResizable(false);
frmConsultaProyectos.setLocationRelativeTo(null);
frmConsultaProyectos.addWindowListener(this);
frmConsultaProyectos.setVisible(true);
}
@Override
public void windowActivated(WindowEvent e)
{}
@Override
public void windowClosed(WindowEvent e)
{}
@Override
public void windowClosing(WindowEvent e)
{
if(frmConsultaProyectos.isActive())
{
frmConsultaProyectos.setVisible(false);
}
}
@Override
public void windowDeactivated(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
| ISO-8859-2 | Java | 3,754 | java | ConsultaProyecto.java | Java | []
| null | []
| package es.studium.Login;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConsultaProyecto implements ActionListener, WindowListener
{
// Ventana Consulta de Proyectos
Frame frmConsultaProyectos = new Frame("Consulta Proyectos");
TextArea listadoProyectos = new TextArea(4, 40);
Button btnPdfProyectos = new Button("PDF");
BaseDatos bd;
String sentencia = "";
String subSentencia = "";
Connection connection = null;
Statement statement = null;
Statement statementClientes = null;
ResultSet rs = null;
ResultSet rsClientes = null;
public ConsultaProyecto()
{
frmConsultaProyectos.setLayout(new FlowLayout());
// Conectar
bd = new BaseDatos();
connection = bd.conectar();
// Hacer un SELECT * FROM Proyectos
sentencia = "SELECT * FROM proyectos";
// La información está en ResultSet
// Recorrer el RS y por cada registro,
// meter una línea en el TextArea
try
{
//Crear una sentencia
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statementClientes = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
//Crear un objeto ResultSet para guardar lo obtenido
//y ejecutar la sentencia SQL
rs = statement.executeQuery(sentencia);
listadoProyectos.selectAll();
listadoProyectos.setText("");
listadoProyectos.append("id\tNombre\tInicio\tFin\tCliente\n");
while(rs.next())
{
subSentencia = "SELECT * FROM clientes WHERE idCliente="
+ rs.getString("idClienteFK");
rsClientes = statementClientes.executeQuery(subSentencia);
rsClientes.next();
String[] fechaInicioAmericana = rs.getString("fechaInicioProyecto").split("-");
String[] fechaFinAmericana = rs.getString("fechaFinProyecto").split("-");
listadoProyectos.append(rs.getInt("idProyecto")
+"\t"+rs.getString("nombreProyecto")
+"\t"+fechaInicioAmericana[2]+"/"+fechaInicioAmericana[1]+"/"+fechaInicioAmericana[0]
+"\t"+fechaFinAmericana[2]+"/"+fechaFinAmericana[1]+"/"+fechaFinAmericana[0]
+"\t"+rsClientes.getString("nombreCliente")
+"\t"+rsClientes.getString("cifCliente")
+"\n");
}
}
catch (SQLException sqle)
{
listadoProyectos.setText("Se ha producido un error en la consulta");
}
finally
{
}
listadoProyectos.setEditable(false);
frmConsultaProyectos.add(listadoProyectos);
frmConsultaProyectos.add(btnPdfProyectos);
frmConsultaProyectos.setSize(300,140);
frmConsultaProyectos.setResizable(false);
frmConsultaProyectos.setLocationRelativeTo(null);
frmConsultaProyectos.addWindowListener(this);
frmConsultaProyectos.setVisible(true);
}
@Override
public void windowActivated(WindowEvent e)
{}
@Override
public void windowClosed(WindowEvent e)
{}
@Override
public void windowClosing(WindowEvent e)
{
if(frmConsultaProyectos.isActive())
{
frmConsultaProyectos.setVisible(false);
}
}
@Override
public void windowDeactivated(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent e)
{
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
| 3,754 | 0.738736 | 0.734737 | 135 | 26.785185 | 22.144102 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.118519 | false | false | 15 |
7d01b34127ebce9f4654b004b3b1f1fb067bd385 | 32,272,384,275,091 | 59db03b6043804d72ef0e530dd619203da8571de | /app/src/main/java/com/zappos/android/intern/utils/Constants.java | 8b34af6eb12797852fd05316b2c4e7fe5a29dacc | []
| no_license | kevin-pinto/ILoveZappos | https://github.com/kevin-pinto/ILoveZappos | c7635e8fb7b38e55077bfc3d13196301160fc119 | 93df6e54769287958e15118c6d673e462e44db39 | refs/heads/master | 2021-01-22T05:15:25.637000 | 2017-02-11T05:49:10 | 2017-02-11T05:49:10 | 81,630,516 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zappos.android.intern.utils;
/**
* Created by Kevin on 10-02-2017.
*
* Contains a list of reusable constants as keys that can be used throughout the
* application.
*/
public class Constants {
public static final String SEARCH_QUERY_EXTRA = "SEARCH_QUERY";
}
| UTF-8 | Java | 277 | java | Constants.java | Java | [
{
"context": "om.zappos.android.intern.utils;\n\n/**\n * Created by Kevin on 10-02-2017.\n *\n * Contains a list of reusable ",
"end": 65,
"score": 0.9981861114501953,
"start": 60,
"tag": "NAME",
"value": "Kevin"
}
]
| null | []
| package com.zappos.android.intern.utils;
/**
* Created by Kevin on 10-02-2017.
*
* Contains a list of reusable constants as keys that can be used throughout the
* application.
*/
public class Constants {
public static final String SEARCH_QUERY_EXTRA = "SEARCH_QUERY";
}
| 277 | 0.732852 | 0.703971 | 11 | 24.181818 | 26.360502 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.272727 | false | false | 15 |
56a8b3621afb246fe7b143bd434c1b58d6849490 | 32,272,384,274,408 | 511406e5d10885eef74cdb08e8686b3570053e13 | /KanbanApp/app/src/main/java/com/example/user/kanbanapp/HelloIntentService.java | 09d7157b215d4539b8986b9b62092865950d3217 | []
| no_license | JeffrieSaenz/KanbanAppProject | https://github.com/JeffrieSaenz/KanbanAppProject | 60e293fdc8e23773ad9be2902d9745caa0ed8ed6 | 3ddf0ae587fbe90a15bdbc5fb0b6ee3edb13ba4d | refs/heads/master | 2020-03-09T20:45:13.994000 | 2018-05-28T22:47:32 | 2018-05-28T22:47:32 | 128,992,589 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.user.kanbanapp;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class HelloIntentService extends IntentService {
static String ns = Context.NOTIFICATION_SERVICE;
ArrayList<Tarea> tareas;
Timer timer = new Timer();
Tab tab;
Date fechaHoy;
int cont = 0;
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
tareas = new ArrayList<>();
readTabs();
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
//validarFechas();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if(FirebaseAuth.getInstance().getCurrentUser() != null) {
validarFechas();
}else{
tareas.clear();
Thread.currentThread().interrupt();
}
}
}, 5*1000, 5*10000);
} catch (Exception e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
public void readTabs() {
DatabaseReference mtabs = FirebaseDatabase.getInstance().getReference(FirebaseAuth.getInstance().getCurrentUser().getEmail().split("@")[0]);
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
tareas.clear();
tab = dataSnapshot.getValue(Tab.class);//Detecta la tabla en que hice el cambio
if(tab.getTareas() != null) {
for (Tarea t : tab.getTareas()) {
if (!tareas.contains(t)) {
tareas.add(t);
}
}
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
tareas.clear();
tab = dataSnapshot.getValue(Tab.class); //Detecta la tabla en que hice el cambio
if(tab.getTareas() != null) {
for (Tarea t : tab.getTareas()) {
if (!tareas.contains(t)) {
tareas.add(t);
}
}
}
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
//Mensaje("Remove");
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
//Mensaje("Moved");
}
@Override
public void onCancelled(DatabaseError databaseError) {
//Mensaje("Cancelled");
}
};
mtabs.addChildEventListener(childEventListener);
}
public void validarFechas(){
fechaHoy = new Date();
NotificationManager nm = nm = (NotificationManager) getSystemService(ns);
nm.cancelAll();
for (Tarea t : tareas){
if(fechaHoy.after(t.getFecha())){
System.out.println("La fecha "+ t.getFecha() +" está vencida");
Notificacion.creaNotificacion(cont++,"ALERTA: Tarea vencida!",
t.getNombre()+"",
"http://es.stackoverflow.com", getApplicationContext());
}
}
}
} | UTF-8 | Java | 5,123 | java | HelloIntentService.java | Java | []
| null | []
| package com.example.user.kanbanapp;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class HelloIntentService extends IntentService {
static String ns = Context.NOTIFICATION_SERVICE;
ArrayList<Tarea> tareas;
Timer timer = new Timer();
Tab tab;
Date fechaHoy;
int cont = 0;
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
tareas = new ArrayList<>();
readTabs();
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent,flags,startId);
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
//validarFechas();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if(FirebaseAuth.getInstance().getCurrentUser() != null) {
validarFechas();
}else{
tareas.clear();
Thread.currentThread().interrupt();
}
}
}, 5*1000, 5*10000);
} catch (Exception e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
public void readTabs() {
DatabaseReference mtabs = FirebaseDatabase.getInstance().getReference(FirebaseAuth.getInstance().getCurrentUser().getEmail().split("@")[0]);
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
tareas.clear();
tab = dataSnapshot.getValue(Tab.class);//Detecta la tabla en que hice el cambio
if(tab.getTareas() != null) {
for (Tarea t : tab.getTareas()) {
if (!tareas.contains(t)) {
tareas.add(t);
}
}
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
tareas.clear();
tab = dataSnapshot.getValue(Tab.class); //Detecta la tabla en que hice el cambio
if(tab.getTareas() != null) {
for (Tarea t : tab.getTareas()) {
if (!tareas.contains(t)) {
tareas.add(t);
}
}
}
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
//Mensaje("Remove");
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
//Mensaje("Moved");
}
@Override
public void onCancelled(DatabaseError databaseError) {
//Mensaje("Cancelled");
}
};
mtabs.addChildEventListener(childEventListener);
}
public void validarFechas(){
fechaHoy = new Date();
NotificationManager nm = nm = (NotificationManager) getSystemService(ns);
nm.cancelAll();
for (Tarea t : tareas){
if(fechaHoy.after(t.getFecha())){
System.out.println("La fecha "+ t.getFecha() +" está vencida");
Notificacion.creaNotificacion(cont++,"ALERTA: Tarea vencida!",
t.getNombre()+"",
"http://es.stackoverflow.com", getApplicationContext());
}
}
}
} | 5,123 | 0.587466 | 0.584537 | 159 | 31.220125 | 26.824528 | 148 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.503145 | false | false | 15 |
11a117e460778fdfe6ada1b3a58c7767e3487b57 | 3,762,391,384,135 | a2686795c8a70dba3d3fe5253637e529ea083a46 | /src/main/java/bowling/domain/frame/NormalFrame.java | b458bdb1fa518914d28d240e7ae3e120525911ab | []
| no_license | PandaHun/java-bowling | https://github.com/PandaHun/java-bowling | b2baa4b31a5072277698606e3f5660199b76dda0 | edd181e14dba81588bf322a4eaab105be79acc00 | refs/heads/master | 2023-04-19T04:00:32.455000 | 2021-05-05T12:20:45 | 2021-05-05T12:20:45 | 359,379,252 | 0 | 0 | null | true | 2021-05-05T12:20:45 | 2021-04-19T08:10:48 | 2021-04-19T08:10:49 | 2021-05-05T12:20:45 | 4,706 | 0 | 0 | 0 | null | false | false | package bowling.domain.frame;
import bowling.domain.score.Score;
import bowling.domain.score.ScoreState;
import bowling.exception.CannotCalculateException;
import bowling.exception.FrameTryException;
public class NormalFrame extends Frame {
private static final int MAX_PIN_COUNT = 10;
private static final int MAX_TRY_COUNT = 2;
private static final String HIT_COUNT_EXCEPTION_MESSAGE = String.format("핀은 최대 %d개 까지 쓰러트릴 수 있습니다", MAX_PIN_COUNT);
private static final String TRY_COUNT_EXCEPTION_MESSAGE = String.format("최대 %d번 까지 시도할 수 있습니다", MAX_TRY_COUNT);
private static final String CANNOT_CALCULATE_MESSAGE = "앞 투구가 끝나지 않아 계산 할 수 없습니다.";
private NormalFrame() {
super();
}
public static NormalFrame from() {
return new NormalFrame();
}
@Override
public int getScore() {
if (!roundEnded()) {
throw new CannotCalculateException(CANNOT_CALCULATE_MESSAGE);
}
return score.calculateScore();
}
@Override
public boolean roundEnded() {
return pins.tryCount() == MAX_TRY_COUNT || pins.isStrike();
}
@Override
protected void validateTry() {
if (roundEnded()) {
throw new FrameTryException(TRY_COUNT_EXCEPTION_MESSAGE);
}
}
@Override
protected void validateHitCount(int hitCount) {
if (pins.totalCount() + hitCount > MAX_PIN_COUNT) {
throw new IllegalStateException(HIT_COUNT_EXCEPTION_MESSAGE);
}
}
@Override
public void createScore() {
if (pins.isStrike() && isFirstTry()) {
score = Score.of(MAX_PIN_COUNT, ScoreState.ofStrike());
return;
}
if (pins.totalCount() == MAX_PIN_COUNT) {
score = Score.of(MAX_PIN_COUNT, ScoreState.ofSpare());
return;
}
score = Score.of(pins.totalCount(), ScoreState.ofNone());
}
}
| UTF-8 | Java | 2,008 | java | NormalFrame.java | Java | []
| null | []
| package bowling.domain.frame;
import bowling.domain.score.Score;
import bowling.domain.score.ScoreState;
import bowling.exception.CannotCalculateException;
import bowling.exception.FrameTryException;
public class NormalFrame extends Frame {
private static final int MAX_PIN_COUNT = 10;
private static final int MAX_TRY_COUNT = 2;
private static final String HIT_COUNT_EXCEPTION_MESSAGE = String.format("핀은 최대 %d개 까지 쓰러트릴 수 있습니다", MAX_PIN_COUNT);
private static final String TRY_COUNT_EXCEPTION_MESSAGE = String.format("최대 %d번 까지 시도할 수 있습니다", MAX_TRY_COUNT);
private static final String CANNOT_CALCULATE_MESSAGE = "앞 투구가 끝나지 않아 계산 할 수 없습니다.";
private NormalFrame() {
super();
}
public static NormalFrame from() {
return new NormalFrame();
}
@Override
public int getScore() {
if (!roundEnded()) {
throw new CannotCalculateException(CANNOT_CALCULATE_MESSAGE);
}
return score.calculateScore();
}
@Override
public boolean roundEnded() {
return pins.tryCount() == MAX_TRY_COUNT || pins.isStrike();
}
@Override
protected void validateTry() {
if (roundEnded()) {
throw new FrameTryException(TRY_COUNT_EXCEPTION_MESSAGE);
}
}
@Override
protected void validateHitCount(int hitCount) {
if (pins.totalCount() + hitCount > MAX_PIN_COUNT) {
throw new IllegalStateException(HIT_COUNT_EXCEPTION_MESSAGE);
}
}
@Override
public void createScore() {
if (pins.isStrike() && isFirstTry()) {
score = Score.of(MAX_PIN_COUNT, ScoreState.ofStrike());
return;
}
if (pins.totalCount() == MAX_PIN_COUNT) {
score = Score.of(MAX_PIN_COUNT, ScoreState.ofSpare());
return;
}
score = Score.of(pins.totalCount(), ScoreState.ofNone());
}
}
| 2,008 | 0.632568 | 0.631002 | 64 | 28.9375 | 28.360886 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.453125 | false | false | 15 |
f4d07c226d6b2c03725ac013df18796ebc2b290f | 12,730,283,097,245 | aa8575adc1dfee543d15a80a9efeaf4a6cea0c4f | /FacilityBookingSystem/src/business/MailSender.java | 4dcc5ed2e8eb615311bac48a87414199005ae71f | []
| no_license | abhay123lp/java-ca-team | https://github.com/abhay123lp/java-ca-team | 1b040e6e89e8c25b913ad872da1fcc74bece340f | 6ecd83df26b57019af5b6cb6c72ff56a96b926cf | refs/heads/master | 2016-08-12T08:29:25.310000 | 2012-12-11T20:19:33 | 2012-12-11T20:19:33 | 49,435,648 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package business;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailSender {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_PORT = "465";
/*private static final String emailMsgTxt = "Test Message Contents";
private static final String emailSubjectTxt = "A test from gmail";*/
private static final String emailFromAddress = "giftforyou.team4@gmail.com";
private static final String SSL_FACTORY ="javax.net.ssl.SSLSocketFactory";
/* private static final String[] sendTo = {"suria.r.asai@gmail.com","suria@nus.edu.sg"};
private static final String fileAttachment="C:\\hai.txt";
/*public static void main(String args[]) throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
new MailSender().sendSSLMessage(sendTo, emailSubjectTxt,
emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
}*/
public void sendSSLMessage(String recipients, String subject,
String message) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("giftforyou.team4@gmail.com", "asdf!@#$%");
}
});
MimeMessage message1 =new MimeMessage(session);
message1.setFrom(new InternetAddress(emailFromAddress));
message1.addRecipient(Message.RecipientType.TO,new InternetAddress(recipients));
message1.setSubject(subject);
// create the message part
MimeBodyPart messageBodyPart =new MimeBodyPart();
//fill message
messageBodyPart.setText(message);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
/*// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
*/
// Put parts in message
message1.setContent(multipart);
// Send the message
Transport.send( message1 );
}
}
| UTF-8 | Java | 3,090 | java | MailSender.java | Java | [
{
"context": "\n\tprivate static final String emailFromAddress = \"giftforyou.team4@gmail.com\";\r\n\tprivate static final String SSL_FACTORY =\"jav",
"end": 940,
"score": 0.9999305605888367,
"start": 914,
"tag": "EMAIL",
"value": "giftforyou.team4@gmail.com"
},
{
"context": "ry\";\r\n/*\tprivate static final String[] sendTo = {\"suria.r.asai@gmail.com\",\"suria@nus.edu.sg\"};\r\n\r\n\tprivate static final St",
"end": 1087,
"score": 0.9999318718910217,
"start": 1065,
"tag": "EMAIL",
"value": "suria.r.asai@gmail.com"
},
{
"context": "inal String[] sendTo = {\"suria.r.asai@gmail.com\",\"suria@nus.edu.sg\"};\r\n\r\n\tprivate static final String fileAttachment",
"end": 1106,
"score": 0.9999287128448486,
"start": 1090,
"tag": "EMAIL",
"value": "suria@nus.edu.sg"
},
{
"context": "tication() {\r\n\treturn new PasswordAuthentication(\"giftforyou.team4@gmail.com\", \"asdf!@#$%\");\r\n\t}\r\n\t});\r\n\r\n\r\n\r\n\tMimeMessage mes",
"end": 2203,
"score": 0.9999074339866638,
"start": 2177,
"tag": "EMAIL",
"value": "giftforyou.team4@gmail.com"
}
]
| null | []
| package business;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailSender {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_PORT = "465";
/*private static final String emailMsgTxt = "Test Message Contents";
private static final String emailSubjectTxt = "A test from gmail";*/
private static final String emailFromAddress = "<EMAIL>";
private static final String SSL_FACTORY ="javax.net.ssl.SSLSocketFactory";
/* private static final String[] sendTo = {"<EMAIL>","<EMAIL>"};
private static final String fileAttachment="C:\\hai.txt";
/*public static void main(String args[]) throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
new MailSender().sendSSLMessage(sendTo, emailSubjectTxt,
emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
}*/
public void sendSSLMessage(String recipients, String subject,
String message) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("<EMAIL>", "asdf!@#$%");
}
});
MimeMessage message1 =new MimeMessage(session);
message1.setFrom(new InternetAddress(emailFromAddress));
message1.addRecipient(Message.RecipientType.TO,new InternetAddress(recipients));
message1.setSubject(subject);
// create the message part
MimeBodyPart messageBodyPart =new MimeBodyPart();
//fill message
messageBodyPart.setText(message);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
/*// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
*/
// Put parts in message
message1.setContent(multipart);
// Send the message
Transport.send( message1 );
}
}
| 3,028 | 0.754045 | 0.750485 | 94 | 30.851065 | 24.603216 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.297872 | false | false | 15 |
4c3cf2be1cc4eb9127c0910090030b75011e0444 | 28,887,950,072,498 | ea3fa08e295072a87dc8407fc148b2bee03a23d9 | /src/main/java/events/ReactEvent.java | 53863bea13e2a8d05dfac4d8d2106560bec98b5b | []
| no_license | awasur04/toastbot | https://github.com/awasur04/toastbot | 4449739ac8480f6bbc07eefa704848ddce1519aa | b1425aff6f01203a0c8afd2cf5beca2269fe33a7 | refs/heads/master | 2023-04-04T20:25:11.594000 | 2021-04-21T00:31:49 | 2021-04-21T00:31:49 | 275,247,015 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package events;
import net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class ReactEvent extends ListenerAdapter {
public void onGuildMessageReactionAdd(GuildMessageReactionAddEvent event) {
String reaction = event.getReaction().getReactionEmote().getAsCodepoints();
if (reaction.equalsIgnoreCase("U+274c")) {
String messageId = event.getMessageId();
event.getChannel().deleteMessageById(messageId).complete();
}
}
}
| UTF-8 | Java | 562 | java | ReactEvent.java | Java | []
| null | []
| package events;
import net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class ReactEvent extends ListenerAdapter {
public void onGuildMessageReactionAdd(GuildMessageReactionAddEvent event) {
String reaction = event.getReaction().getReactionEmote().getAsCodepoints();
if (reaction.equalsIgnoreCase("U+274c")) {
String messageId = event.getMessageId();
event.getChannel().deleteMessageById(messageId).complete();
}
}
}
| 562 | 0.733096 | 0.724199 | 16 | 34.125 | 32.370655 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 15 |
0b27d0292ee95a07a890abf7e16eebe15997d678 | 4,526,895,554,326 | b2181ba9f5c0ca3b66bb710ea4e67da03d160daa | /src/fitnesse/http/ResponseParserTest.java | 0534c8294272b44e7cd268991c29ff32a30a7596 | []
| no_license | dleonard0/fitnesse | https://github.com/dleonard0/fitnesse | 6749e5927bfd3343f782fec454391a13b609eb85 | 668f14c213d7e034d4d06a7f2dd335755e214a4a | refs/heads/master | 2021-01-15T20:52:17.786000 | 2009-05-11T19:46:17 | 2009-05-11T19:46:17 | 196,173 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.http;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import junit.framework.TestCase;
public class ResponseParserTest extends TestCase {
private String response;
private InputStream input;
public void setUp() throws Exception {
}
public void tearDown() throws Exception {
}
public void testParsing() throws Exception {
response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 12\r\n" +
"Cache-Control: max-age=0\r\n" +
"\r\n" +
"some content";
input = new ByteArrayInputStream(response.getBytes());
ResponseParser parser = new ResponseParser(input);
assertEquals(200, parser.getStatus());
assertEquals("text/html", parser.getHeader("Content-Type"));
assertEquals("some content", parser.getBody());
}
public void testChunkedResponse() throws Exception {
response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Transfer-Encoding: chunked\r\n" +
"\r\n" +
"3\r\n" +
"123\r\n" +
"7\r\n" +
"4567890\r\n" +
"0\r\n" +
"Tail-Header: TheEnd!\r\n";
input = new ByteArrayInputStream(response.getBytes());
ResponseParser parser = new ResponseParser(input);
assertEquals(200, parser.getStatus());
assertEquals("text/html", parser.getHeader("Content-Type"));
assertEquals("1234567890", parser.getBody());
assertEquals("TheEnd!", parser.getHeader("Tail-Header"));
}
}
| UTF-8 | Java | 1,636 | java | ResponseParserTest.java | Java | []
| null | []
| // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.http;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import junit.framework.TestCase;
public class ResponseParserTest extends TestCase {
private String response;
private InputStream input;
public void setUp() throws Exception {
}
public void tearDown() throws Exception {
}
public void testParsing() throws Exception {
response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 12\r\n" +
"Cache-Control: max-age=0\r\n" +
"\r\n" +
"some content";
input = new ByteArrayInputStream(response.getBytes());
ResponseParser parser = new ResponseParser(input);
assertEquals(200, parser.getStatus());
assertEquals("text/html", parser.getHeader("Content-Type"));
assertEquals("some content", parser.getBody());
}
public void testChunkedResponse() throws Exception {
response = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html\r\n" +
"Transfer-Encoding: chunked\r\n" +
"\r\n" +
"3\r\n" +
"123\r\n" +
"7\r\n" +
"4567890\r\n" +
"0\r\n" +
"Tail-Header: TheEnd!\r\n";
input = new ByteArrayInputStream(response.getBytes());
ResponseParser parser = new ResponseParser(input);
assertEquals(200, parser.getStatus());
assertEquals("text/html", parser.getHeader("Content-Type"));
assertEquals("1234567890", parser.getBody());
assertEquals("TheEnd!", parser.getHeader("Tail-Header"));
}
}
| 1,636 | 0.66198 | 0.630196 | 54 | 29.296297 | 21.907743 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
09e9f25f3e4babd7b066ac3758e90d17019f30ef | 16,999,480,596,336 | 013d0211b81effddad167200b75e0dc74769610f | /AreaShop/src/main/java/me/wiefferink/areashop/listeners/PlayerLoginLogoutListener.java | 15b219ed420ae539cae3eea99788d2dd20819a5f | []
| no_license | Srborjaa/AreaShop | https://github.com/Srborjaa/AreaShop | 303713330b60c55395f7ff90af5c4165b2c0417f | 3727751b0c1e688498ae07ab0ef72508a68e47c8 | refs/heads/master | 2021-09-20T05:22:12.092000 | 2017-08-20T13:14:13 | 2017-08-20T13:14:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.wiefferink.areashop.listeners;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.List;
/**
* Notify region expiry and track activity time.
*/
public final class PlayerLoginLogoutListener implements Listener {
private AreaShop plugin;
/**
* Constructor.
* @param plugin The AreaShop plugin
*/
public PlayerLoginLogoutListener(AreaShop plugin) {
this.plugin = plugin;
}
/**
* Called when a sign is changed.
* @param event The event
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogin(PlayerLoginEvent event) {
if(event.getResult() != Result.ALLOWED) {
return;
}
final Player player = event.getPlayer();
// Schedule task to check for notifications, prevents a lag spike at login
new BukkitRunnable() {
@Override
public void run() {
// Delay until all regions are loaded
if(!plugin.isReady()) {
return;
}
if(!player.isOnline()) {
this.cancel();
return;
}
// Notify for rents that almost run out
for(RentRegion region : plugin.getFileManager().getRents()) {
if(region.isRenter(player)) {
String warningSetting = region.getStringSetting("rent.warningOnLoginTime");
if(warningSetting == null || warningSetting.isEmpty()) {
continue;
}
long warningTime = Utils.durationStringToLong(warningSetting);
if(region.getTimeLeft() < warningTime) {
// Send the warning message later to let it appear after general MOTD messages
AreaShop.getInstance().message(player, "rent-expireWarning", region);
}
}
}
// Notify admins for plugin updates
AreaShop.getInstance().notifyUpdate(player);
this.cancel();
}
}.runTaskTimer(plugin, 25, 25);
// Check if the player has regions that use an old name of him and update them
final List<GeneralRegion> regions = new ArrayList<>(plugin.getFileManager().getRegions());
new BukkitRunnable() {
private int current = 0;
@Override
public void run() {
// Delay until all regions are loaded
if(!plugin.isReady()) {
return;
}
// Check all regions
for(int i = 0; i < plugin.getConfig().getInt("nameupdate.regionsPerTick"); i++) {
if(current < regions.size()) {
GeneralRegion region = regions.get(current);
if(region.isOwner(player)) {
if(region instanceof BuyRegion) {
if(!player.getName().equals(region.getStringSetting("buy.buyerName"))) {
region.setSetting("buy.buyerName", player.getName());
region.update();
}
} else if(region instanceof RentRegion) {
if(!player.getName().equals(region.getStringSetting("rent.renterName"))) {
region.setSetting("rent.renterName", player.getName());
region.update();
}
}
}
current++;
}
}
if(current >= regions.size()) {
this.cancel();
}
}
}.runTaskTimer(plugin, 22, 1); // Wait a bit before starting to prevent a lot of stress on the server when a player joins (a lot of plugins already do stuff then)
}
// Active time updates
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogout(PlayerQuitEvent event) {
updateLastActive(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerKick(PlayerKickEvent event) {
updateLastActive(event.getPlayer());
}
/**
* Update the last active time for all regions the player is owner off.
* @param player The player to update the active times for
*/
private void updateLastActive(Player player) {
for(GeneralRegion region : plugin.getFileManager().getRegions()) {
if(region.isOwner(player)) {
region.updateLastActiveTime();
}
}
}
}
| UTF-8 | Java | 4,363 | java | PlayerLoginLogoutListener.java | Java | []
| null | []
| package me.wiefferink.areashop.listeners;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.List;
/**
* Notify region expiry and track activity time.
*/
public final class PlayerLoginLogoutListener implements Listener {
private AreaShop plugin;
/**
* Constructor.
* @param plugin The AreaShop plugin
*/
public PlayerLoginLogoutListener(AreaShop plugin) {
this.plugin = plugin;
}
/**
* Called when a sign is changed.
* @param event The event
*/
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogin(PlayerLoginEvent event) {
if(event.getResult() != Result.ALLOWED) {
return;
}
final Player player = event.getPlayer();
// Schedule task to check for notifications, prevents a lag spike at login
new BukkitRunnable() {
@Override
public void run() {
// Delay until all regions are loaded
if(!plugin.isReady()) {
return;
}
if(!player.isOnline()) {
this.cancel();
return;
}
// Notify for rents that almost run out
for(RentRegion region : plugin.getFileManager().getRents()) {
if(region.isRenter(player)) {
String warningSetting = region.getStringSetting("rent.warningOnLoginTime");
if(warningSetting == null || warningSetting.isEmpty()) {
continue;
}
long warningTime = Utils.durationStringToLong(warningSetting);
if(region.getTimeLeft() < warningTime) {
// Send the warning message later to let it appear after general MOTD messages
AreaShop.getInstance().message(player, "rent-expireWarning", region);
}
}
}
// Notify admins for plugin updates
AreaShop.getInstance().notifyUpdate(player);
this.cancel();
}
}.runTaskTimer(plugin, 25, 25);
// Check if the player has regions that use an old name of him and update them
final List<GeneralRegion> regions = new ArrayList<>(plugin.getFileManager().getRegions());
new BukkitRunnable() {
private int current = 0;
@Override
public void run() {
// Delay until all regions are loaded
if(!plugin.isReady()) {
return;
}
// Check all regions
for(int i = 0; i < plugin.getConfig().getInt("nameupdate.regionsPerTick"); i++) {
if(current < regions.size()) {
GeneralRegion region = regions.get(current);
if(region.isOwner(player)) {
if(region instanceof BuyRegion) {
if(!player.getName().equals(region.getStringSetting("buy.buyerName"))) {
region.setSetting("buy.buyerName", player.getName());
region.update();
}
} else if(region instanceof RentRegion) {
if(!player.getName().equals(region.getStringSetting("rent.renterName"))) {
region.setSetting("rent.renterName", player.getName());
region.update();
}
}
}
current++;
}
}
if(current >= regions.size()) {
this.cancel();
}
}
}.runTaskTimer(plugin, 22, 1); // Wait a bit before starting to prevent a lot of stress on the server when a player joins (a lot of plugins already do stuff then)
}
// Active time updates
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerLogout(PlayerQuitEvent event) {
updateLastActive(event.getPlayer());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerKick(PlayerKickEvent event) {
updateLastActive(event.getPlayer());
}
/**
* Update the last active time for all regions the player is owner off.
* @param player The player to update the active times for
*/
private void updateLastActive(Player player) {
for(GeneralRegion region : plugin.getFileManager().getRegions()) {
if(region.isOwner(player)) {
region.updateLastActiveTime();
}
}
}
}
| 4,363 | 0.690121 | 0.688059 | 141 | 29.716312 | 26.713167 | 164 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.120567 | false | false | 15 |
e9ebe75641c966c11705ccd1a33f01997fb04ddd | 23,905,787,983,150 | 4a580e2b2117f356b704a283ca1fcc2e5b057660 | /NetBeansProjects/sList/src/SLinkedList.java | a09f371bcf05bb2a00f0cae5afc6a251c66f3791 | []
| no_license | jaypoddar/Java-Code | https://github.com/jaypoddar/Java-Code | 3215dd568b7ffe9794ad93b2e75a9a904dbd18aa | d500e0846093b1f0378a325756b2819a9abf8ab1 | refs/heads/master | 2021-01-10T20:00:07.749000 | 2014-11-21T21:45:45 | 2014-11-21T21:45:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class SLinkedList<E> {
protected Node<E> head;
protected int size;
public SLinkedList()
{
head=null;
size=0;
}
public void addElement(E element)
{
Node<E> n= new Node<E>(element);
if (head==null)
{
head= n;
head.next= null;
}
else
{
Node<E> temp= head;
while(temp.next() != null)
{
temp=temp.next();
}
temp.setNext(n);
}
}
public void printList()
{
Node<E> temp = head;
while(temp != null)
{
System.out.println(temp.getElement());
temp=temp.next;
}
}
} | UTF-8 | Java | 564 | java | SLinkedList.java | Java | []
| null | []
| public class SLinkedList<E> {
protected Node<E> head;
protected int size;
public SLinkedList()
{
head=null;
size=0;
}
public void addElement(E element)
{
Node<E> n= new Node<E>(element);
if (head==null)
{
head= n;
head.next= null;
}
else
{
Node<E> temp= head;
while(temp.next() != null)
{
temp=temp.next();
}
temp.setNext(n);
}
}
public void printList()
{
Node<E> temp = head;
while(temp != null)
{
System.out.println(temp.getElement());
temp=temp.next;
}
}
} | 564 | 0.546099 | 0.544326 | 41 | 12.780488 | 11.976628 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.170732 | false | false | 15 |
d4ab1d498fe14bff6df6be587c4a15b3ef234603 | 19,189,913,931,057 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/14/14_c2272785c7edd83c834476c966a0ec750067a568/pptParser/14_c2272785c7edd83c834476c966a0ec750067a568_pptParser_t.java | 701a5d59ed3734f39d7911b0332129455a78f2c0 | []
| no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | //pptParser.java
//------------------------
//part of YaCy
//(C) by Michael Peter Christen; mc@yacy.net
//first published on http://www.anomic.de
//Frankfurt, Germany, 2005
//
//this file is contributed by Tim Riemann
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.anomic.document.parser;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import net.yacy.kelondro.data.meta.DigestURI;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
import de.anomic.document.AbstractParser;
import de.anomic.document.Idiom;
import de.anomic.document.ParserException;
import de.anomic.document.Document;
public class pptParser extends AbstractParser implements Idiom {
/**
* a list of mime types that are supported by this parser class
* @see #getSupportedMimeTypes()
*/
public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
static {
SUPPORTED_EXTENSIONS.add("ppt");
SUPPORTED_EXTENSIONS.add("pps");
SUPPORTED_MIME_TYPES.add("application/mspowerpoint");
SUPPORTED_MIME_TYPES.add("application/powerpoint");
SUPPORTED_MIME_TYPES.add("application/vnd.ms-powerpoint");
SUPPORTED_MIME_TYPES.add("application/ms-powerpoint");
SUPPORTED_MIME_TYPES.add("application/mspowerpnt");
SUPPORTED_MIME_TYPES.add("application/vnd-mspowerpoint");
SUPPORTED_MIME_TYPES.add("application/x-powerpoint");
SUPPORTED_MIME_TYPES.add("application/x-m");
}
public pptParser(){
super("Microsoft Powerpoint Parser");
}
/*
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
public Document parse(final DigestURI location, final String mimeType,
final String charset, final InputStream source) throws ParserException,
InterruptedException {
try {
/*
* create new PowerPointExtractor and extract text and notes
* of the document
*/
final PowerPointExtractor pptExtractor = new PowerPointExtractor(new BufferedInputStream(source));
final String contents = pptExtractor.getText(true, true).trim();
String title = contents.replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("\t"," ").trim();
if (title.length() > 80) title = title.substring(0, 80);
int l = title.length();
while (true) {
title = title.replaceAll(" ", " ");
if (title.length() == l) break;
l = title.length();
}
/*
* create the plasmaParserDocument for the database
* and set shortText and bodyText properly
*/
final Document theDoc = new Document(
location,
mimeType,
"UTF-8",
null,
null,
title,
"", // TODO: AUTHOR
null,
null,
contents.getBytes("UTF-8"),
null,
null);
return theDoc;
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
/*
* an unexpected error occurred, log it and throw a ParserException
*/
final String errorMsg = "Unable to parse the ppt document '" + location + "':" + e.getMessage();
this.theLogger.logSevere(errorMsg);
throw new ParserException(errorMsg, location);
}
}
public Set<String> supportedMimeTypes() {
return SUPPORTED_MIME_TYPES;
}
public Set<String> supportedExtensions() {
return SUPPORTED_EXTENSIONS;
}
@Override
public void reset(){
//nothing to do
super.reset();
}
}
| UTF-8 | Java | 5,141 | java | 14_c2272785c7edd83c834476c966a0ec750067a568_pptParser_t.java | Java | [
{
"context": "----------------------\r\n //part of YaCy\r\n //(C) by Michael Peter Christen; mc@yacy.net\r\n //first published on http://www.an",
"end": 98,
"score": 0.9994401931762695,
"start": 76,
"tag": "NAME",
"value": "Michael Peter Christen"
},
{
"context": " //part of YaCy\r\n //(C) by Michael Peter Christen; mc@yacy.net\r\n //first published on http://www.anomic.de\r\n //F",
"end": 111,
"score": 0.9999316334724426,
"start": 100,
"tag": "EMAIL",
"value": "mc@yacy.net"
},
{
"context": "Germany, 2005\r\n //\r\n //this file is contributed by Tim Riemann\r\n //\r\n // $LastChangedDate$\r\n // $LastChangedRevi",
"end": 233,
"score": 0.9998623132705688,
"start": 222,
"tag": "NAME",
"value": "Tim Riemann"
}
]
| null | []
| //pptParser.java
//------------------------
//part of YaCy
//(C) by <NAME>; <EMAIL>
//first published on http://www.anomic.de
//Frankfurt, Germany, 2005
//
//this file is contributed by <NAME>
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.anomic.document.parser;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import net.yacy.kelondro.data.meta.DigestURI;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
import de.anomic.document.AbstractParser;
import de.anomic.document.Idiom;
import de.anomic.document.ParserException;
import de.anomic.document.Document;
public class pptParser extends AbstractParser implements Idiom {
/**
* a list of mime types that are supported by this parser class
* @see #getSupportedMimeTypes()
*/
public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>();
public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>();
static {
SUPPORTED_EXTENSIONS.add("ppt");
SUPPORTED_EXTENSIONS.add("pps");
SUPPORTED_MIME_TYPES.add("application/mspowerpoint");
SUPPORTED_MIME_TYPES.add("application/powerpoint");
SUPPORTED_MIME_TYPES.add("application/vnd.ms-powerpoint");
SUPPORTED_MIME_TYPES.add("application/ms-powerpoint");
SUPPORTED_MIME_TYPES.add("application/mspowerpnt");
SUPPORTED_MIME_TYPES.add("application/vnd-mspowerpoint");
SUPPORTED_MIME_TYPES.add("application/x-powerpoint");
SUPPORTED_MIME_TYPES.add("application/x-m");
}
public pptParser(){
super("Microsoft Powerpoint Parser");
}
/*
* parses the source documents and returns a plasmaParserDocument containing
* all extracted information about the parsed document
*/
public Document parse(final DigestURI location, final String mimeType,
final String charset, final InputStream source) throws ParserException,
InterruptedException {
try {
/*
* create new PowerPointExtractor and extract text and notes
* of the document
*/
final PowerPointExtractor pptExtractor = new PowerPointExtractor(new BufferedInputStream(source));
final String contents = pptExtractor.getText(true, true).trim();
String title = contents.replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("\t"," ").trim();
if (title.length() > 80) title = title.substring(0, 80);
int l = title.length();
while (true) {
title = title.replaceAll(" ", " ");
if (title.length() == l) break;
l = title.length();
}
/*
* create the plasmaParserDocument for the database
* and set shortText and bodyText properly
*/
final Document theDoc = new Document(
location,
mimeType,
"UTF-8",
null,
null,
title,
"", // TODO: AUTHOR
null,
null,
contents.getBytes("UTF-8"),
null,
null);
return theDoc;
} catch (final Exception e) {
if (e instanceof InterruptedException) throw (InterruptedException) e;
/*
* an unexpected error occurred, log it and throw a ParserException
*/
final String errorMsg = "Unable to parse the ppt document '" + location + "':" + e.getMessage();
this.theLogger.logSevere(errorMsg);
throw new ParserException(errorMsg, location);
}
}
public Set<String> supportedMimeTypes() {
return SUPPORTED_MIME_TYPES;
}
public Set<String> supportedExtensions() {
return SUPPORTED_EXTENSIONS;
}
@Override
public void reset(){
//nothing to do
super.reset();
}
}
| 5,116 | 0.584128 | 0.57907 | 135 | 36.08889 | 26.605059 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.585185 | false | false | 15 |
b3474a3d8eef5c74ef27fce7a2efea6b182d6edc | 7,773,890,849,300 | 3f6a5bbbe5890365556479ed8fb8d019a6be45e5 | /src/main/java/com/ro/dto/ProductPurchase.java | 057e4fed11edec29f4b15d39d9ae262e918098b8 | []
| no_license | Shiv1500/ROProject | https://github.com/Shiv1500/ROProject | f97588fcb676105cfd61a415052f0a55f94817b1 | 0639387fbc23dc9fef09d21663d6ce2c1d27fd19 | refs/heads/main | 2023-06-17T02:26:53.458000 | 2021-07-16T07:46:00 | 2021-07-16T07:46:00 | 381,024,648 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ro.dto;
public class ProductPurchase {
}
| UTF-8 | Java | 55 | java | ProductPurchase.java | Java | []
| null | []
| package com.ro.dto;
public class ProductPurchase {
}
| 55 | 0.745455 | 0.745455 | 5 | 10 | 12.345039 | 30 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 15 |
85ef729b7ba9219df81683350971f498221c723f | 8,340,826,529,587 | 70b9bab6f98745f16c146001a57486c6aa47332a | /mymall-ware/src/main/java/de/killbuqs/mall/ware/service/impl/WareSkuServiceImpl.java | b2a93f4964e0ab62ed7b7ca83408d0fc5393d890 | [
"Apache-2.0"
]
| permissive | clarklj001/mymall | https://github.com/clarklj001/mymall | e3ca41711b83683d92ea1924e403a1071408bd05 | 26755e554adbb16aaaecbe83d19593d994d0202a | refs/heads/master | 2023-05-13T20:57:49.593000 | 2021-06-03T18:35:46 | 2021-06-03T18:35:46 | 347,691,320 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.killbuqs.mall.ware.service.impl;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import de.killbuqs.common.to.SkuHasStockVo;
import de.killbuqs.common.utils.PageUtils;
import de.killbuqs.common.utils.Query;
import de.killbuqs.common.utils.R;
import de.killbuqs.mall.ware.dao.WareSkuDao;
import de.killbuqs.mall.ware.entity.WareSkuEntity;
import de.killbuqs.mall.ware.feign.ProductFeignService;
import de.killbuqs.mall.ware.service.WareSkuService;
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
@Autowired
private WareSkuDao wareSkuDao;
@Autowired
private ProductFeignService productFeignService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<WareSkuEntity>();
String skuId = (String) params.get("skuId");
if (!StringUtils.isEmpty(skuId)) {
queryWrapper.eq("sku_id", skuId);
}
String wareId = (String) params.get("wareId");
if (!StringUtils.isEmpty(wareId)) {
queryWrapper.eq("ware_id", wareId);
}
IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), queryWrapper);
return new PageUtils(page);
}
@Transactional
@Override
public void addStock(Long skuId, Long wareId, Integer skuNum) {
// 判断如果还没有这个库存,就新增记录,有的话就更新
List<WareSkuEntity> wareSkuList = wareSkuDao
.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
if (wareSkuList == null || wareSkuList.size() == 0) {
WareSkuEntity entity = new WareSkuEntity();
entity.setSkuId(skuId);
entity.setStock(skuNum);
entity.setWareId(wareId);
entity.setStockLocked(0);
// 远程查询sku的名字,如果失败,整个事务不需要回滚
// TODO 另外的办法 让异常出现以后不回滚
try {
R info = productFeignService.info(skuId);
if (info.getCode() == 0) {
Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
entity.setSkuName((String) data.get("skuName"));
}
} catch (Exception e) {
// Do not need to handle exception
}
wareSkuDao.insert(entity);
} else {
wareSkuDao.addStock(skuId, wareId, skuNum);
}
}
@Override
public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
// select sum(stock - stock_locked) from wms_ware_sku where sku_id = 1
List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
SkuHasStockVo vo = new SkuHasStockVo();
Long count = wareSkuDao.getSkuStock(skuId);
vo.setSkuId(skuId);
vo.setHasStock(count == null ? false : count > 0);
return vo;
}).collect(Collectors.toList());
return collect;
}
} | UTF-8 | Java | 3,202 | java | WareSkuServiceImpl.java | Java | []
| null | []
| package de.killbuqs.mall.ware.service.impl;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import de.killbuqs.common.to.SkuHasStockVo;
import de.killbuqs.common.utils.PageUtils;
import de.killbuqs.common.utils.Query;
import de.killbuqs.common.utils.R;
import de.killbuqs.mall.ware.dao.WareSkuDao;
import de.killbuqs.mall.ware.entity.WareSkuEntity;
import de.killbuqs.mall.ware.feign.ProductFeignService;
import de.killbuqs.mall.ware.service.WareSkuService;
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
@Autowired
private WareSkuDao wareSkuDao;
@Autowired
private ProductFeignService productFeignService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<WareSkuEntity>();
String skuId = (String) params.get("skuId");
if (!StringUtils.isEmpty(skuId)) {
queryWrapper.eq("sku_id", skuId);
}
String wareId = (String) params.get("wareId");
if (!StringUtils.isEmpty(wareId)) {
queryWrapper.eq("ware_id", wareId);
}
IPage<WareSkuEntity> page = this.page(new Query<WareSkuEntity>().getPage(params), queryWrapper);
return new PageUtils(page);
}
@Transactional
@Override
public void addStock(Long skuId, Long wareId, Integer skuNum) {
// 判断如果还没有这个库存,就新增记录,有的话就更新
List<WareSkuEntity> wareSkuList = wareSkuDao
.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
if (wareSkuList == null || wareSkuList.size() == 0) {
WareSkuEntity entity = new WareSkuEntity();
entity.setSkuId(skuId);
entity.setStock(skuNum);
entity.setWareId(wareId);
entity.setStockLocked(0);
// 远程查询sku的名字,如果失败,整个事务不需要回滚
// TODO 另外的办法 让异常出现以后不回滚
try {
R info = productFeignService.info(skuId);
if (info.getCode() == 0) {
Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
entity.setSkuName((String) data.get("skuName"));
}
} catch (Exception e) {
// Do not need to handle exception
}
wareSkuDao.insert(entity);
} else {
wareSkuDao.addStock(skuId, wareId, skuNum);
}
}
@Override
public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
// select sum(stock - stock_locked) from wms_ware_sku where sku_id = 1
List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
SkuHasStockVo vo = new SkuHasStockVo();
Long count = wareSkuDao.getSkuStock(skuId);
vo.setSkuId(skuId);
vo.setHasStock(count == null ? false : count > 0);
return vo;
}).collect(Collectors.toList());
return collect;
}
} | 3,202 | 0.741234 | 0.73961 | 102 | 29.205883 | 25.592714 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 15 |
1f6984fa59190ee766c36e1c8968cfd61efce4fb | 26,336,739,483,921 | 7a52c982ea6fc8152fb649902ebf3ae0dce3b9cf | /src/main/java/com/tkeians/Dao/UserDaoImpl.java | 770676b90d8530a18aab6b5ecc7a22f5880f6085 | []
| no_license | WcxMilan/SSM | https://github.com/WcxMilan/SSM | 31f31e37fa385c7cb9a464ef4955df27c181ac08 | 90fcd969fc36975af50e0c9689b35899bef8c9ad | refs/heads/master | 2021-01-19T16:09:54.508000 | 2016-09-27T03:20:13 | 2016-09-27T03:20:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tkeians.Dao;
import com.tkeians.Model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
/**
* Created by _ on 2016/9/26.
*/
public class UserDaoImpl implements IUserDao {
private SqlSessionFactory sessionFactory;
private SqlSession session;
public UserDaoImpl() {
String resource = "conf.xml";
try {
Reader reader = Resources.getResourceAsReader(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
session = sessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
}
// 此函数名与 userMapper.xml 中设置的 id 相同
public User findUserById(int id) {
String statement = "userMapper.findUserById";
User user = session.selectOne(statement, id);
return user;
}
}
| UTF-8 | Java | 1,067 | java | UserDaoImpl.java | Java | [
{
"context": "ception;\nimport java.io.Reader;\n\n/**\n * Created by _ on 2016/9/26.\n */\npublic class UserDaoImpl implem",
"end": 324,
"score": 0.6561794877052307,
"start": 323,
"tag": "USERNAME",
"value": "_"
}
]
| null | []
| package com.tkeians.Dao;
import com.tkeians.Model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
/**
* Created by _ on 2016/9/26.
*/
public class UserDaoImpl implements IUserDao {
private SqlSessionFactory sessionFactory;
private SqlSession session;
public UserDaoImpl() {
String resource = "conf.xml";
try {
Reader reader = Resources.getResourceAsReader(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
session = sessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
}
// 此函数名与 userMapper.xml 中设置的 id 相同
public User findUserById(int id) {
String statement = "userMapper.findUserById";
User user = session.selectOne(statement, id);
return user;
}
}
| 1,067 | 0.683254 | 0.676555 | 38 | 26.5 | 21.383406 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 15 |
fc952ba28fd1d6dff64c1fd5df417964fb334dbb | 9,165,460,225,615 | f046291b70092d1b80badae7d4e8e5a869c625e7 | /src/dao/FuncionarioDao.java | c4fcbd5a3ac972bdc6c443e1d113a618d1811172 | []
| no_license | MarioCMesquita/blu-salutem | https://github.com/MarioCMesquita/blu-salutem | c73b3b3a136cd19fa7cdff50495e48ae37b50f25 | a9c8af2f963118c254ec1515d684aa43a6e8e84b | refs/heads/master | 2021-05-23T13:04:44.936000 | 2020-04-05T18:19:33 | 2020-04-05T18:19:33 | 253,300,483 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import beans.FuncionarioBean;
import conexao.Conexao;
public class FuncionarioDao {
//Verificar login
public int verificarLogin(String email, String senha) {
//Conexao
Connection conexao = Conexao.obterConexao();
//Contador
int contador = 0;
//Tentativa
try {
//SQL
String sql = "SELECT COUNT(*) FROM cadastrofuncionarios WHERE emailFuncionario = ? AND senhaFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
//Parâmetros
pstmt.setString(1, email);
pstmt.setString(2, senha);
//Obter dados
ResultSet rs = pstmt.executeQuery();
rs.last();
contador = rs.getInt(1);
}catch(Exception erro) {
System.out.println("Falha ao logar"+erro.getMessage());
}
//Retorno
return contador;
}
//Obter os dados do usuário
public FuncionarioBean dadosUsuario(String email, String senha) {
//Objeto UsuarioBean
FuncionarioBean ub = new FuncionarioBean();
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
//SQL
String sql = "SELECT * FROM cadastrofuncionarios WHERE emailFuncionario = ? AND senhaFuncionario = ?";
//PreparedStatement
PreparedStatement pstmt = conexao.prepareStatement(sql);
//Parâmetros
pstmt.setString(1, email);
pstmt.setString(2, senha);
//Executar
ResultSet rs = pstmt.executeQuery();
//Selecionar a última linha
rs.last();
//Obter dados
ub.setIdFuncionario(rs.getInt(1));
ub.setIdSegmentoFuncionario(rs.getInt(2));
ub.setNomeFuncionario(rs.getString(3));
ub.setRgFuncionario(rs.getString(4));
ub.setCpfFuncionario(rs.getString(5));
ub.setEmailFuncionario(rs.getString(6));
ub.setTelefoneFuncionario(rs.getString(7));
ub.setEnderecoFuncionario(rs.getString(8));
ub.setSenhaFuncionario(rs.getString(9));
}catch(Exception erro) {
System.out.println("Falha ao obter dados"+erro.getMessage());
}
//Retorno
return ub;
}
//Cadastrar usuário
public boolean cadastrar(FuncionarioBean obj) {
//Variável boolean
boolean situacao = false;
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
//SQL
String sql = "INSERT INTO cadastrofuncionarios (nomeFuncionario, rgFuncionario, cpfFuncionario, emailFuncionario, senhaFuncionario, telefoneFuncionario, enderecoFuncionario, idSegmentoFuncionario) VALUES (?,?,?,?,?,?,?,?)";
//PreparedStatement
PreparedStatement pstmt = conexao.prepareStatement(sql);
//Parâmetros
pstmt.setString(1, obj.getNomeFuncionario());
pstmt.setString(2, obj.getRgFuncionario());
pstmt.setString(3, obj.getCpfFuncionario());
pstmt.setString(4, obj.getEmailFuncionario());
pstmt.setString(5, obj.getSenhaFuncionario());
pstmt.setString(6, obj.getTelefoneFuncionario());
pstmt.setString(7, obj.getEnderecoFuncionario());
pstmt.setInt(8, obj.getIdSegmentoFuncionario());
pstmt.execute();
situacao = true;
pstmt.close();
conexao.close();
}catch(Exception erro) {
System.out.println("Falha ao cadastrar"+erro.getMessage());
}
//Retorno
return situacao;
}
//Selecionar Segmentos
public String selecionarSegmentos() {
//Iniciar estrutura
String estrutura = "<select name='segmento'>";
estrutura += "<option>Segmento</option>";
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "SELECT * FROM segmentoFuncionarios";
Statement stmt = conexao.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
estrutura += "<option value='"+rs.getInt(1)+"'>"+rs.getString(2)+"</option>";
}
stmt.close();
conexao.close();
}catch(Exception e) {
}
//Finalizar estrutura
estrutura += "</select>";
//Retorno
return estrutura;
}
//Selecionar funcionários
public String selecionar() {
//Iniciar estrutura
String estrutura = "<table class='tabela'>";
estrutura += "<tr>";
estrutura += "<td>Id</td>";
estrutura += "<td>Nome</td>";
estrutura += "<td>RG</td>";
estrutura += "<td>CPF</td>";
estrutura += "<td>E-mail</td>";
estrutura += "<td>Senha</td>";
estrutura += "<td>Telefone</td>";
estrutura += "<td>Endereço</td>";
estrutura += "<td>Segmento</td>";
estrutura += "<td>Alterar</td>";
estrutura += "<td>Excluir</td>";
estrutura += "</tr>";
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "SELECT * FROM cadastrofuncionarios";
Statement stmt = conexao.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
estrutura += "<tr>";
estrutura += "<td>"+rs.getInt(1)+"</td>";
estrutura += "<td>"+rs.getString(2)+"</td>";
estrutura += "<td>"+rs.getString(3)+"</td>";
estrutura += "<td>"+rs.getString(4)+"</td>";
estrutura += "<td>"+rs.getString(5)+"</td>";
estrutura += "<td>"+rs.getString(6)+"</td>";
estrutura += "<td>"+rs.getString(7)+"</td>";
estrutura += "<td>"+rs.getString(8)+"</td>";
estrutura += "<td>"+rs.getString(9)+"</td>";
estrutura += "<td><a href='cadastroFuncionario.jsp?idFuncionario="+rs.getInt(1)+"'>Alterar</a></td>";
estrutura += "<td><a href='requisicoes/excluirFuncionario.jsp?idFuncionario="+rs.getInt(1)+"'>Excluir</a></td>";
estrutura += "</tr>";
}
stmt.close();
conexao.close();
}catch(Exception e) {
}
//Finalizar estrutura
estrutura += "</table>";
//Retorno
return estrutura;
}
//Selecionar dados do funcionário específico
public FuncionarioBean especificarFuncionario(int idFuncionario) {
//Objeto
FuncionarioBean fb = new FuncionarioBean();
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "SELECT * FROM cadastrofuncionarios WHERE idFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
pstmt.setInt(1, idFuncionario);
ResultSet rs = pstmt.executeQuery();
rs.last();
fb.setIdFuncionario(rs.getInt(1));
fb.setIdSegmentoFuncionario(rs.getInt(2));
fb.setNomeFuncionario(rs.getString(3));
fb.setRgFuncionario(rs.getString(4));
fb.setCpfFuncionario(rs.getString(5));
fb.setEmailFuncionario(rs.getString(6));
fb.setTelefoneFuncionario(rs.getString(7));
fb.setEnderecoFuncionario(rs.getString(8));
fb.setSenhaFuncionario(rs.getString(9));
pstmt.close();
conexao.close();
}catch(Exception e) {}
//Retorno
return fb;
}
//Excluir funcionário
public boolean excluir(int idFuncionario) {
//Situação
boolean situacao = false;
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "DELETE FROM cadastrofuncionarios WHERE idFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
pstmt.setInt(1, idFuncionario);
pstmt.execute();
pstmt.close();
conexao.close();
situacao = true;
}catch(Exception e){}
//Retorno
return situacao;
}
//Alterar funcionário
public boolean alterar(FuncionarioBean pb) {
//Validação
boolean valida = false;
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "UPDATE cadastrofuncionarios SET nomeFuncionario = ?, rgFuncionario = ?, cpfFuncionario = ?, emailFuncionario = ?, senhaFuncionario = ?, telefoneFuncionario = ?, enderecoFuncionario = ?, idSegmentoFuncionario = ? WHERE idFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
pstmt.setString(1, pb.getNomeFuncionario());
pstmt.setString(2, pb.getRgFuncionario());
pstmt.setString(3, pb.getCpfFuncionario());
pstmt.setString(4, pb.getEmailFuncionario());
pstmt.setString(5, pb.getSenhaFuncionario());
pstmt.setString(6, pb.getTelefoneFuncionario());
pstmt.setString(7, pb.getEnderecoFuncionario());
pstmt.setInt(8, pb.getIdSegmentoFuncionario());
pstmt.setInt(9, pb.getIdFuncionario());
pstmt.execute();
pstmt.close();
conexao.close();
valida = true;
}catch(Exception e) {}
//Retorno
return valida;
}
}
| ISO-8859-1 | Java | 8,341 | java | FuncionarioDao.java | Java | []
| null | []
| package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import beans.FuncionarioBean;
import conexao.Conexao;
public class FuncionarioDao {
//Verificar login
public int verificarLogin(String email, String senha) {
//Conexao
Connection conexao = Conexao.obterConexao();
//Contador
int contador = 0;
//Tentativa
try {
//SQL
String sql = "SELECT COUNT(*) FROM cadastrofuncionarios WHERE emailFuncionario = ? AND senhaFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
//Parâmetros
pstmt.setString(1, email);
pstmt.setString(2, senha);
//Obter dados
ResultSet rs = pstmt.executeQuery();
rs.last();
contador = rs.getInt(1);
}catch(Exception erro) {
System.out.println("Falha ao logar"+erro.getMessage());
}
//Retorno
return contador;
}
//Obter os dados do usuário
public FuncionarioBean dadosUsuario(String email, String senha) {
//Objeto UsuarioBean
FuncionarioBean ub = new FuncionarioBean();
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
//SQL
String sql = "SELECT * FROM cadastrofuncionarios WHERE emailFuncionario = ? AND senhaFuncionario = ?";
//PreparedStatement
PreparedStatement pstmt = conexao.prepareStatement(sql);
//Parâmetros
pstmt.setString(1, email);
pstmt.setString(2, senha);
//Executar
ResultSet rs = pstmt.executeQuery();
//Selecionar a última linha
rs.last();
//Obter dados
ub.setIdFuncionario(rs.getInt(1));
ub.setIdSegmentoFuncionario(rs.getInt(2));
ub.setNomeFuncionario(rs.getString(3));
ub.setRgFuncionario(rs.getString(4));
ub.setCpfFuncionario(rs.getString(5));
ub.setEmailFuncionario(rs.getString(6));
ub.setTelefoneFuncionario(rs.getString(7));
ub.setEnderecoFuncionario(rs.getString(8));
ub.setSenhaFuncionario(rs.getString(9));
}catch(Exception erro) {
System.out.println("Falha ao obter dados"+erro.getMessage());
}
//Retorno
return ub;
}
//Cadastrar usuário
public boolean cadastrar(FuncionarioBean obj) {
//Variável boolean
boolean situacao = false;
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
//SQL
String sql = "INSERT INTO cadastrofuncionarios (nomeFuncionario, rgFuncionario, cpfFuncionario, emailFuncionario, senhaFuncionario, telefoneFuncionario, enderecoFuncionario, idSegmentoFuncionario) VALUES (?,?,?,?,?,?,?,?)";
//PreparedStatement
PreparedStatement pstmt = conexao.prepareStatement(sql);
//Parâmetros
pstmt.setString(1, obj.getNomeFuncionario());
pstmt.setString(2, obj.getRgFuncionario());
pstmt.setString(3, obj.getCpfFuncionario());
pstmt.setString(4, obj.getEmailFuncionario());
pstmt.setString(5, obj.getSenhaFuncionario());
pstmt.setString(6, obj.getTelefoneFuncionario());
pstmt.setString(7, obj.getEnderecoFuncionario());
pstmt.setInt(8, obj.getIdSegmentoFuncionario());
pstmt.execute();
situacao = true;
pstmt.close();
conexao.close();
}catch(Exception erro) {
System.out.println("Falha ao cadastrar"+erro.getMessage());
}
//Retorno
return situacao;
}
//Selecionar Segmentos
public String selecionarSegmentos() {
//Iniciar estrutura
String estrutura = "<select name='segmento'>";
estrutura += "<option>Segmento</option>";
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "SELECT * FROM segmentoFuncionarios";
Statement stmt = conexao.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
estrutura += "<option value='"+rs.getInt(1)+"'>"+rs.getString(2)+"</option>";
}
stmt.close();
conexao.close();
}catch(Exception e) {
}
//Finalizar estrutura
estrutura += "</select>";
//Retorno
return estrutura;
}
//Selecionar funcionários
public String selecionar() {
//Iniciar estrutura
String estrutura = "<table class='tabela'>";
estrutura += "<tr>";
estrutura += "<td>Id</td>";
estrutura += "<td>Nome</td>";
estrutura += "<td>RG</td>";
estrutura += "<td>CPF</td>";
estrutura += "<td>E-mail</td>";
estrutura += "<td>Senha</td>";
estrutura += "<td>Telefone</td>";
estrutura += "<td>Endereço</td>";
estrutura += "<td>Segmento</td>";
estrutura += "<td>Alterar</td>";
estrutura += "<td>Excluir</td>";
estrutura += "</tr>";
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "SELECT * FROM cadastrofuncionarios";
Statement stmt = conexao.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
estrutura += "<tr>";
estrutura += "<td>"+rs.getInt(1)+"</td>";
estrutura += "<td>"+rs.getString(2)+"</td>";
estrutura += "<td>"+rs.getString(3)+"</td>";
estrutura += "<td>"+rs.getString(4)+"</td>";
estrutura += "<td>"+rs.getString(5)+"</td>";
estrutura += "<td>"+rs.getString(6)+"</td>";
estrutura += "<td>"+rs.getString(7)+"</td>";
estrutura += "<td>"+rs.getString(8)+"</td>";
estrutura += "<td>"+rs.getString(9)+"</td>";
estrutura += "<td><a href='cadastroFuncionario.jsp?idFuncionario="+rs.getInt(1)+"'>Alterar</a></td>";
estrutura += "<td><a href='requisicoes/excluirFuncionario.jsp?idFuncionario="+rs.getInt(1)+"'>Excluir</a></td>";
estrutura += "</tr>";
}
stmt.close();
conexao.close();
}catch(Exception e) {
}
//Finalizar estrutura
estrutura += "</table>";
//Retorno
return estrutura;
}
//Selecionar dados do funcionário específico
public FuncionarioBean especificarFuncionario(int idFuncionario) {
//Objeto
FuncionarioBean fb = new FuncionarioBean();
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "SELECT * FROM cadastrofuncionarios WHERE idFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
pstmt.setInt(1, idFuncionario);
ResultSet rs = pstmt.executeQuery();
rs.last();
fb.setIdFuncionario(rs.getInt(1));
fb.setIdSegmentoFuncionario(rs.getInt(2));
fb.setNomeFuncionario(rs.getString(3));
fb.setRgFuncionario(rs.getString(4));
fb.setCpfFuncionario(rs.getString(5));
fb.setEmailFuncionario(rs.getString(6));
fb.setTelefoneFuncionario(rs.getString(7));
fb.setEnderecoFuncionario(rs.getString(8));
fb.setSenhaFuncionario(rs.getString(9));
pstmt.close();
conexao.close();
}catch(Exception e) {}
//Retorno
return fb;
}
//Excluir funcionário
public boolean excluir(int idFuncionario) {
//Situação
boolean situacao = false;
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "DELETE FROM cadastrofuncionarios WHERE idFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
pstmt.setInt(1, idFuncionario);
pstmt.execute();
pstmt.close();
conexao.close();
situacao = true;
}catch(Exception e){}
//Retorno
return situacao;
}
//Alterar funcionário
public boolean alterar(FuncionarioBean pb) {
//Validação
boolean valida = false;
//Conexão
Connection conexao = Conexao.obterConexao();
//Tentativa
try {
String sql = "UPDATE cadastrofuncionarios SET nomeFuncionario = ?, rgFuncionario = ?, cpfFuncionario = ?, emailFuncionario = ?, senhaFuncionario = ?, telefoneFuncionario = ?, enderecoFuncionario = ?, idSegmentoFuncionario = ? WHERE idFuncionario = ?";
PreparedStatement pstmt = conexao.prepareStatement(sql);
pstmt.setString(1, pb.getNomeFuncionario());
pstmt.setString(2, pb.getRgFuncionario());
pstmt.setString(3, pb.getCpfFuncionario());
pstmt.setString(4, pb.getEmailFuncionario());
pstmt.setString(5, pb.getSenhaFuncionario());
pstmt.setString(6, pb.getTelefoneFuncionario());
pstmt.setString(7, pb.getEnderecoFuncionario());
pstmt.setInt(8, pb.getIdSegmentoFuncionario());
pstmt.setInt(9, pb.getIdFuncionario());
pstmt.execute();
pstmt.close();
conexao.close();
valida = true;
}catch(Exception e) {}
//Retorno
return valida;
}
}
| 8,341 | 0.664302 | 0.657569 | 322 | 24.829193 | 27.112923 | 254 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.040373 | false | false | 15 |
6b0bc384c6aed9dcb39af2d77f40c3a3aae5e0bc | 29,094,108,514,379 | 7d39f0b7e98614f715d6214f4b421a07d7f38fdc | /src/com/study/util/Multipage.java | 012e9bc2b464f8bb5b8edfcdf3e3712f85c89249 | []
| no_license | XJTUITPM/ITPM | https://github.com/XJTUITPM/ITPM | e1c684c41c810ee9e39b0f12d5577e65cfcd090a | bcfb984491b94e6af85e00a774420d4852de043c | refs/heads/master | 2020-04-04T16:34:15.043000 | 2018-11-22T17:37:28 | 2018-11-22T17:37:28 | 156,083,265 | 0 | 1 | null | false | 2018-11-07T04:28:35 | 2018-11-04T13:09:16 | 2018-11-05T11:55:27 | 2018-11-07T04:28:35 | 3,295 | 0 | 1 | 0 | null | false | null | package com.study.util;
import java.util.ArrayList;
public class Multipage {
private static int recordsPerPage = 10; //一页中显示记录的条数
//计算该页面的总页数
public static <T> int calculatePageCount(ArrayList<T> list) {
int amount = list.size();
if(amount%recordsPerPage == 0)
return amount/recordsPerPage;
else
return amount/recordsPerPage + 1;
}
//生成该页面需要返回的信息列表
public static <T> void makeListOnThisPage(ArrayList<T> listOnThisPage, ArrayList<T> list, int page, int pageCount) {
if(page < pageCount)
for(int i=0; i<recordsPerPage; i++)
listOnThisPage.add(list.get( (page-1) * recordsPerPage + i ));
else
for(int i=0; i<list.size()%recordsPerPage; i++)
listOnThisPage.add(list.get( (page-1) * recordsPerPage + i ));
}
}
| UTF-8 | Java | 844 | java | Multipage.java | Java | []
| null | []
| package com.study.util;
import java.util.ArrayList;
public class Multipage {
private static int recordsPerPage = 10; //一页中显示记录的条数
//计算该页面的总页数
public static <T> int calculatePageCount(ArrayList<T> list) {
int amount = list.size();
if(amount%recordsPerPage == 0)
return amount/recordsPerPage;
else
return amount/recordsPerPage + 1;
}
//生成该页面需要返回的信息列表
public static <T> void makeListOnThisPage(ArrayList<T> listOnThisPage, ArrayList<T> list, int page, int pageCount) {
if(page < pageCount)
for(int i=0; i<recordsPerPage; i++)
listOnThisPage.add(list.get( (page-1) * recordsPerPage + i ));
else
for(int i=0; i<list.size()%recordsPerPage; i++)
listOnThisPage.add(list.get( (page-1) * recordsPerPage + i ));
}
}
| 844 | 0.677378 | 0.667095 | 27 | 26.814816 | 27.620493 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.074074 | false | false | 15 |
cc3f87baffa9fe2bef59483e491323ef79a5aecb | 26,809,185,887,491 | d64f01db590604cf3c2b265bfb2c0ffcccd5fc63 | /src/executor/demo1/test/run/Run1.java | 34a393bd8ec1846aec1128bf7b747cd646eba9f0 | []
| no_license | wangle82/javaDemo | https://github.com/wangle82/javaDemo | d3fb851c5603f0fb1a9624fa42e8245c14a81780 | 5adea5bb77638462aaee269e620494fc786e9919 | refs/heads/master | 2021-09-02T09:41:09.203000 | 2018-01-01T14:51:47 | 2018-01-01T14:51:47 | 115,925,123 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package executor.demo1.test.run;
import java.util.concurrent.*;
public class Run1 {
// 获取基本属性
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(7, 8, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
System.out.println(executor.getCorePoolSize()); //标准线程数
System.out.println(executor.getMaximumPoolSize());//最大线程数
System.out.println(executor.getPoolSize());//当前线程数
System.out.println(executor.getQueue().size());//队列中的数
System.out.println("===========================");
executor = new ThreadPoolExecutor(7, 8, 5, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
System.out.println(executor.getCorePoolSize());
System.out.println(executor.getMaximumPoolSize());
System.out.println(executor.getPoolSize());
System.out.println(executor.getQueue().size());
}
}
| UTF-8 | Java | 1,003 | java | Run1.java | Java | []
| null | []
| package executor.demo1.test.run;
import java.util.concurrent.*;
public class Run1 {
// 获取基本属性
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(7, 8, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
System.out.println(executor.getCorePoolSize()); //标准线程数
System.out.println(executor.getMaximumPoolSize());//最大线程数
System.out.println(executor.getPoolSize());//当前线程数
System.out.println(executor.getQueue().size());//队列中的数
System.out.println("===========================");
executor = new ThreadPoolExecutor(7, 8, 5, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
System.out.println(executor.getCorePoolSize());
System.out.println(executor.getMaximumPoolSize());
System.out.println(executor.getPoolSize());
System.out.println(executor.getQueue().size());
}
}
| 1,003 | 0.642482 | 0.634069 | 24 | 38.625 | 26.531134 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 15 |
03be0f4d5db8daf47a290fd1e01c9c2bd59e83e7 | 34,445,637,725,743 | d18ce16e47f39589cb53da593eb7e9b01a36cf9f | /src/main/java/com/cultuzz/channel/DAO/impl/ListOfMemberMessagesDAOImpl.java | 593cb4bfa1fb30d05bb0aa75928425226d61008a | []
| no_license | tiruappu/CultbayChannelWSs | https://github.com/tiruappu/CultbayChannelWSs | 391dbe5999f680ac1f8ef6fe2ddc3c4b186a5304 | a288a1d789681a580484cdd206d4fb94f825a47a | refs/heads/master | 2020-04-14T13:20:37.242000 | 2019-01-02T16:51:12 | 2019-01-02T16:51:12 | 163,865,903 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cultuzz.channel.DAO.impl;
import java.util.List;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.cultuzz.channel.DAO.ListOfMemberMessagesDAO;
import com.cultuzz.channel.helper.impl.OfferEndHelperImpl;
import com.cultuzz.channel.jdbcTemplate.JDBCTemplate;
@Component
/**
* This class is used to connect to database to retrieve the member messages
*
* @author sowmya
*
*/
public class ListOfMemberMessagesDAOImpl implements ListOfMemberMessagesDAO {
@Autowired
@Qualifier("ebayTemplate")
private JDBCTemplate ebayJdbcTemplate;
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("cusebedaTemplate")
private JDBCTemplate cusebedaJdbcTemplate;
private static final org.slf4j.Logger LOGGER = LoggerFactory
.getLogger(ListOfMemberMessagesDAOImpl.class);
/**
* This method is Required to get the member messages from table
*/
public List<Map<String, Object>> getMemberMessages(String objectId,
String ItemId, String periodFrom, String periodTo,
String upperLimit, String lowerLimit, String status) {
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
String from = null;
String datum = null;
String order = null;
String datum_string = null;
String last_changer = null;
String verfall = null;
int beantwortet = 0;
String bedingung = null;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb = new StringBuffer(
"SELECT meine_nachrichten.message_id,meine_nachrichten.ebayname,meine_nachrichten.beantwortet,meine_nachrichten.message");
if (status != null) {
//int isAnswered = Integer.parseInt(status);
if (status.equalsIgnoreCase("0")) {
beantwortet = 0;
from = " ebay_messages.meine_nachrichten";
datum = " meine_nachrichten.creation_date";
order = " ORDER BY message_id asc";
datum_string = " creation_date";
verfall = " ,date_add(meine_nachrichten.creation_date, INTERVAL 3 MONTH) as verfall";
} else if (status.equalsIgnoreCase("1")) {
beantwortet = 1;
from = " ebay_messages.meine_nachrichten, ebay_messages.nachrichten_x_antworten";
datum = " nachrichten_x_antworten.response_date,meine_nachrichten.creation_date";
last_changer = " ,nachrichten_x_antworten.last_changer";
order = " ORDER BY message_id asc";
datum_string = " response_date";
bedingung = " AND nachrichten_x_antworten.message_id = meine_nachrichten.message_id AND sichtbar = 1";
verfall = "";
}else{
from = " ebay_messages.meine_nachrichten";
}
sb.append(","
+ datum
+ ",meine_nachrichten.subject,meine_nachrichten.message, meine_nachrichten.ebayitemid");
if(null!=last_changer){
sb.append(last_changer);
}
if(null!=verfall){
sb.append(verfall);
}
sb.append(" from " + from
+ " WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != bedingung) {
sb.append(" AND beantwortet = " + beantwortet + bedingung+ "");
} else {
if(status.equalsIgnoreCase("0") || status.equalsIgnoreCase("1")){
sb.append(" AND beantwortet = " + beantwortet + "");
}
}
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom
+ "and"
+ periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}
} else {
sb.append(",meine_nachrichten.subject,meine_nachrichten.message,meine_nachrichten.beantwortet, meine_nachrichten.ebayitemid, meine_nachrichten.creation_date"
+ " from ebay_messages.meine_nachrichten WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom + "and" + periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom + "' and '" + periodTo
+ "' ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}
}
List<Map<String, Object>> listValues = jdbcTemplate.queryForList(sb
.toString());
return listValues;
}
/**
* This method is used to get all the member messages for ItemId
*/
public List<Map<String, Object>> getMemberMessagesForItemId(
String ebayItemId,String periodFrom,String periodTo,String upperLimit,String lowerLimit,String status) {
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb=new StringBuffer("SELECT meine_nachrichten.ebayitemid,meine_nachrichten.ebayname,meine_nachrichten.subject,"
+"meine_nachrichten.message,meine_nachrichten.beantwortet,meine_nachrichten.message_id,meine_nachrichten.creation_date, "
+ "nachrichten_x_antworten.response_date, "
+ "nachrichten_x_antworten.response, "
+ "nachrichten_x_antworten.last_changer"
+ " FROM ebay_messages.meine_nachrichten "
+ "LEFT JOIN ebay_messages.nachrichten_x_antworten ON meine_nachrichten.message_id = nachrichten_x_antworten.message_id "
+ "WHERE meine_nachrichten.ebayitemid ="+ebayItemId);
if(status!=null){
if(status.equalsIgnoreCase("0")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}else if(status.equalsIgnoreCase("1")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}
}
if(null!=periodFrom && null!=periodTo){
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}else{
sb.append(" ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}
List<Map<String, Object>> itemListValues = jdbcTemplate.queryForList(sb
.toString());
return itemListValues;
}
/**
* This method is used to validate the itemId
* @param cusebedaObjectId
* @param ItemId
* @return
*/
public boolean validateItemId(String ItemId, String cusebedaObjectId) {
// TODO Auto-generated method stub
try {
jdbcTemplate = ebayJdbcTemplate.getJdbcTemplate();
String sql = "select count(*) from ebay.auktion where ebayitemid=" + ItemId;
int count = 0;
count = jdbcTemplate.queryForInt(sql);
if (count > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* This method is used to validate the objectId
* @param objectId
* @param itemId
* @return
*/
public boolean validateObjectId(String objectId,String itemId){
boolean isValid=false;
String objectid=null;
jdbcTemplate = ebayJdbcTemplate.getJdbcTemplate();
String sql="select cusebeda_objekt_id from ebay.auktion where ebayitemid="+itemId;
//sql="select cusebeda_objekt_id from ebay.auktion where ebayitemid="+itemId;
objectid=jdbcTemplate.queryForObject(sql, String.class);
if(objectid.equalsIgnoreCase(objectId)){
isValid=true;
}
return isValid;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* This method is required to check the Object validity
*
* @param objectId
* @return
*/
public boolean checkForObjectValidity(String objectId) {
boolean objectIdstatus = false;
LOGGER.debug("Entered checkForObjectValidity ");
jdbcTemplate = ebayJdbcTemplate.getJdbcTemplate();
String objectIdSql = "SELECT count(*) FROM ebay.ebaydaten_token WHERE ebaydaten_token.cusebeda_objekt_id =? ";
@SuppressWarnings("deprecation")
int objectWithItemIdCount = jdbcTemplate.queryForInt(objectIdSql,
new Object[] { Integer.parseInt(objectId) });
LOGGER.debug("Count for objekt Id :::" + objectWithItemIdCount);
if (objectWithItemIdCount != 0) {
objectIdstatus = true;
}
return objectIdstatus;
}
public int getMemeberMessagesCount(String objectId, String ItemId,
String periodFrom, String periodTo, String upperLimit,
String lowerLimit, String status) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
String from = null;
String datum = null;
String order = null;
String datum_string = null;
String last_changer = null;
String verfall = null;
int beantwortet = 0;
String bedingung = null;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb = new StringBuffer(
"SELECT count(meine_nachrichten.message_id) as maxCount");
if (status != null) {
//int isAnswered = Integer.parseInt(status);
if (status.equalsIgnoreCase("0")) {
beantwortet = 0;
from = " ebay_messages.meine_nachrichten";
datum = " meine_nachrichten.creation_date";
order = " ORDER BY meine_nachrichten.message_id asc";
datum_string = " creation_date";
verfall = " ,date_add(meine_nachrichten.creation_date, INTERVAL 3 MONTH) as verfall";
} else if (status.equalsIgnoreCase("1")) {
beantwortet = 1;
from = " ebay_messages.meine_nachrichten, ebay_messages.nachrichten_x_antworten";
datum = " nachrichten_x_antworten.response_date,meine_nachrichten.creation_date";
last_changer = " ,nachrichten_x_antworten.last_changer";
order = " ORDER BY meine_nachrichten.message_id asc";
datum_string = " response_date";
bedingung = " AND nachrichten_x_antworten.message_id = meine_nachrichten.message_id AND sichtbar = 1";
verfall = "";
}
/* sb.append(","
+ datum
+ ",meine_nachrichten.subject,meine_nachrichten.message, meine_nachrichten.ebayitemid");
if(null!=last_changer){
sb.append(last_changer);
}
if(null!=verfall){
sb.append(verfall);
}*/
sb.append(" from " + from
+ " WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != bedingung) {
sb.append(" AND beantwortet = " + beantwortet + bedingung+ "");
} else {
sb.append(" AND beantwortet = " + beantwortet + "");
}
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom
+ "and"
+ periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY meine_nachrichten.message_id asc ");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY meine_nachrichten.message_id asc ");
}
} else {
sb.append(" from ebay_messages.meine_nachrichten WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom + "and" + periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom + "' and '" + periodTo
+ "' ORDER BY meine_nachrichten.message_id asc ");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY meine_nachrichten.message_id asc ");
}
}
int count = jdbcTemplate.queryForInt(sb
.toString());
return count;
}
public int getMemberMessagesForItemIdCount(String ebayItemId,
String periodFrom, String periodTo, String upperLimit,
String lowerLimit, String status) {
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb=new StringBuffer("SELECT count(meine_nachrichten.message_id) as maxCount"
+ " FROM ebay_messages.meine_nachrichten "
+ "LEFT JOIN ebay_messages.nachrichten_x_antworten ON meine_nachrichten.message_id = nachrichten_x_antworten.message_id "
+ "WHERE meine_nachrichten.ebayitemid ="+ebayItemId);
if(status!=null){
if(status.equalsIgnoreCase("0")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}else if(status.equalsIgnoreCase("1")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}
}
if(null!=periodFrom && null!=periodTo){
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY meine_nachrichten.message_id asc ");
}else{
sb.append(" ORDER BY meine_nachrichten.message_id asc ");
}
int count = jdbcTemplate.queryForInt(sb
.toString());
return count;
}
} | UTF-8 | Java | 14,215 | java | ListOfMemberMessagesDAOImpl.java | Java | [
{
"context": "ase to retrieve the member messages\n * \n * @author sowmya\n * \n */\npublic class ListOfMemberMessagesDAOImpl ",
"end": 628,
"score": 0.9994925856590271,
"start": 622,
"tag": "USERNAME",
"value": "sowmya"
}
]
| null | []
| package com.cultuzz.channel.DAO.impl;
import java.util.List;
import java.util.Map;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.cultuzz.channel.DAO.ListOfMemberMessagesDAO;
import com.cultuzz.channel.helper.impl.OfferEndHelperImpl;
import com.cultuzz.channel.jdbcTemplate.JDBCTemplate;
@Component
/**
* This class is used to connect to database to retrieve the member messages
*
* @author sowmya
*
*/
public class ListOfMemberMessagesDAOImpl implements ListOfMemberMessagesDAO {
@Autowired
@Qualifier("ebayTemplate")
private JDBCTemplate ebayJdbcTemplate;
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("cusebedaTemplate")
private JDBCTemplate cusebedaJdbcTemplate;
private static final org.slf4j.Logger LOGGER = LoggerFactory
.getLogger(ListOfMemberMessagesDAOImpl.class);
/**
* This method is Required to get the member messages from table
*/
public List<Map<String, Object>> getMemberMessages(String objectId,
String ItemId, String periodFrom, String periodTo,
String upperLimit, String lowerLimit, String status) {
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
String from = null;
String datum = null;
String order = null;
String datum_string = null;
String last_changer = null;
String verfall = null;
int beantwortet = 0;
String bedingung = null;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb = new StringBuffer(
"SELECT meine_nachrichten.message_id,meine_nachrichten.ebayname,meine_nachrichten.beantwortet,meine_nachrichten.message");
if (status != null) {
//int isAnswered = Integer.parseInt(status);
if (status.equalsIgnoreCase("0")) {
beantwortet = 0;
from = " ebay_messages.meine_nachrichten";
datum = " meine_nachrichten.creation_date";
order = " ORDER BY message_id asc";
datum_string = " creation_date";
verfall = " ,date_add(meine_nachrichten.creation_date, INTERVAL 3 MONTH) as verfall";
} else if (status.equalsIgnoreCase("1")) {
beantwortet = 1;
from = " ebay_messages.meine_nachrichten, ebay_messages.nachrichten_x_antworten";
datum = " nachrichten_x_antworten.response_date,meine_nachrichten.creation_date";
last_changer = " ,nachrichten_x_antworten.last_changer";
order = " ORDER BY message_id asc";
datum_string = " response_date";
bedingung = " AND nachrichten_x_antworten.message_id = meine_nachrichten.message_id AND sichtbar = 1";
verfall = "";
}else{
from = " ebay_messages.meine_nachrichten";
}
sb.append(","
+ datum
+ ",meine_nachrichten.subject,meine_nachrichten.message, meine_nachrichten.ebayitemid");
if(null!=last_changer){
sb.append(last_changer);
}
if(null!=verfall){
sb.append(verfall);
}
sb.append(" from " + from
+ " WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != bedingung) {
sb.append(" AND beantwortet = " + beantwortet + bedingung+ "");
} else {
if(status.equalsIgnoreCase("0") || status.equalsIgnoreCase("1")){
sb.append(" AND beantwortet = " + beantwortet + "");
}
}
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom
+ "and"
+ periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}
} else {
sb.append(",meine_nachrichten.subject,meine_nachrichten.message,meine_nachrichten.beantwortet, meine_nachrichten.ebayitemid, meine_nachrichten.creation_date"
+ " from ebay_messages.meine_nachrichten WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom + "and" + periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom + "' and '" + periodTo
+ "' ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}
}
List<Map<String, Object>> listValues = jdbcTemplate.queryForList(sb
.toString());
return listValues;
}
/**
* This method is used to get all the member messages for ItemId
*/
public List<Map<String, Object>> getMemberMessagesForItemId(
String ebayItemId,String periodFrom,String periodTo,String upperLimit,String lowerLimit,String status) {
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb=new StringBuffer("SELECT meine_nachrichten.ebayitemid,meine_nachrichten.ebayname,meine_nachrichten.subject,"
+"meine_nachrichten.message,meine_nachrichten.beantwortet,meine_nachrichten.message_id,meine_nachrichten.creation_date, "
+ "nachrichten_x_antworten.response_date, "
+ "nachrichten_x_antworten.response, "
+ "nachrichten_x_antworten.last_changer"
+ " FROM ebay_messages.meine_nachrichten "
+ "LEFT JOIN ebay_messages.nachrichten_x_antworten ON meine_nachrichten.message_id = nachrichten_x_antworten.message_id "
+ "WHERE meine_nachrichten.ebayitemid ="+ebayItemId);
if(status!=null){
if(status.equalsIgnoreCase("0")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}else if(status.equalsIgnoreCase("1")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}
}
if(null!=periodFrom && null!=periodTo){
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}else{
sb.append(" ORDER BY message_id asc limit "
+ lowerLimit+","+diffLimit + "");
}
List<Map<String, Object>> itemListValues = jdbcTemplate.queryForList(sb
.toString());
return itemListValues;
}
/**
* This method is used to validate the itemId
* @param cusebedaObjectId
* @param ItemId
* @return
*/
public boolean validateItemId(String ItemId, String cusebedaObjectId) {
// TODO Auto-generated method stub
try {
jdbcTemplate = ebayJdbcTemplate.getJdbcTemplate();
String sql = "select count(*) from ebay.auktion where ebayitemid=" + ItemId;
int count = 0;
count = jdbcTemplate.queryForInt(sql);
if (count > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* This method is used to validate the objectId
* @param objectId
* @param itemId
* @return
*/
public boolean validateObjectId(String objectId,String itemId){
boolean isValid=false;
String objectid=null;
jdbcTemplate = ebayJdbcTemplate.getJdbcTemplate();
String sql="select cusebeda_objekt_id from ebay.auktion where ebayitemid="+itemId;
//sql="select cusebeda_objekt_id from ebay.auktion where ebayitemid="+itemId;
objectid=jdbcTemplate.queryForObject(sql, String.class);
if(objectid.equalsIgnoreCase(objectId)){
isValid=true;
}
return isValid;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* This method is required to check the Object validity
*
* @param objectId
* @return
*/
public boolean checkForObjectValidity(String objectId) {
boolean objectIdstatus = false;
LOGGER.debug("Entered checkForObjectValidity ");
jdbcTemplate = ebayJdbcTemplate.getJdbcTemplate();
String objectIdSql = "SELECT count(*) FROM ebay.ebaydaten_token WHERE ebaydaten_token.cusebeda_objekt_id =? ";
@SuppressWarnings("deprecation")
int objectWithItemIdCount = jdbcTemplate.queryForInt(objectIdSql,
new Object[] { Integer.parseInt(objectId) });
LOGGER.debug("Count for objekt Id :::" + objectWithItemIdCount);
if (objectWithItemIdCount != 0) {
objectIdstatus = true;
}
return objectIdstatus;
}
public int getMemeberMessagesCount(String objectId, String ItemId,
String periodFrom, String periodTo, String upperLimit,
String lowerLimit, String status) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
String from = null;
String datum = null;
String order = null;
String datum_string = null;
String last_changer = null;
String verfall = null;
int beantwortet = 0;
String bedingung = null;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb = new StringBuffer(
"SELECT count(meine_nachrichten.message_id) as maxCount");
if (status != null) {
//int isAnswered = Integer.parseInt(status);
if (status.equalsIgnoreCase("0")) {
beantwortet = 0;
from = " ebay_messages.meine_nachrichten";
datum = " meine_nachrichten.creation_date";
order = " ORDER BY meine_nachrichten.message_id asc";
datum_string = " creation_date";
verfall = " ,date_add(meine_nachrichten.creation_date, INTERVAL 3 MONTH) as verfall";
} else if (status.equalsIgnoreCase("1")) {
beantwortet = 1;
from = " ebay_messages.meine_nachrichten, ebay_messages.nachrichten_x_antworten";
datum = " nachrichten_x_antworten.response_date,meine_nachrichten.creation_date";
last_changer = " ,nachrichten_x_antworten.last_changer";
order = " ORDER BY meine_nachrichten.message_id asc";
datum_string = " response_date";
bedingung = " AND nachrichten_x_antworten.message_id = meine_nachrichten.message_id AND sichtbar = 1";
verfall = "";
}
/* sb.append(","
+ datum
+ ",meine_nachrichten.subject,meine_nachrichten.message, meine_nachrichten.ebayitemid");
if(null!=last_changer){
sb.append(last_changer);
}
if(null!=verfall){
sb.append(verfall);
}*/
sb.append(" from " + from
+ " WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != bedingung) {
sb.append(" AND beantwortet = " + beantwortet + bedingung+ "");
} else {
sb.append(" AND beantwortet = " + beantwortet + "");
}
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom
+ "and"
+ periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY meine_nachrichten.message_id asc ");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY meine_nachrichten.message_id asc ");
}
} else {
sb.append(" from ebay_messages.meine_nachrichten WHERE meine_nachrichten.cusebeda_objekt_id ="
+ objectId + "");
if (null != periodFrom && null != periodTo) {
/*sb.append(" AND meine_nachrichten.creation_date between "
+ periodFrom + "and" + periodTo
+ " ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom + "' and '" + periodTo
+ "' ORDER BY meine_nachrichten.message_id asc ");
} else {
/*sb.append(" ORDER BY ebayitemid, ebayname, creation_date asc limit "
+ diffLimit + "");*/
sb.append(" ORDER BY meine_nachrichten.message_id asc ");
}
}
int count = jdbcTemplate.queryForInt(sb
.toString());
return count;
}
public int getMemberMessagesForItemIdCount(String ebayItemId,
String periodFrom, String periodTo, String upperLimit,
String lowerLimit, String status) {
// TODO Auto-generated method stub
int maxValue = Integer.parseInt(upperLimit);
int minValue = Integer.parseInt(lowerLimit);
int diffLimit = maxValue - minValue;
jdbcTemplate = cusebedaJdbcTemplate.getJdbcTemplate();
StringBuffer sb=new StringBuffer("SELECT count(meine_nachrichten.message_id) as maxCount"
+ " FROM ebay_messages.meine_nachrichten "
+ "LEFT JOIN ebay_messages.nachrichten_x_antworten ON meine_nachrichten.message_id = nachrichten_x_antworten.message_id "
+ "WHERE meine_nachrichten.ebayitemid ="+ebayItemId);
if(status!=null){
if(status.equalsIgnoreCase("0")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}else if(status.equalsIgnoreCase("1")){
sb.append(" AND meine_nachrichten.beantwortet="+status);
}
}
if(null!=periodFrom && null!=periodTo){
sb.append(" AND meine_nachrichten.creation_date between '"
+ periodFrom
+ "' and '"
+ periodTo
+ "' ORDER BY meine_nachrichten.message_id asc ");
}else{
sb.append(" ORDER BY meine_nachrichten.message_id asc ");
}
int count = jdbcTemplate.queryForInt(sb
.toString());
return count;
}
} | 14,215 | 0.672881 | 0.671122 | 426 | 32.370892 | 27.975567 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.697183 | false | false | 15 |
a64ac264eb28a254e41c58fd90cdd1b13921f4a8 | 30,382,598,677,081 | 3387742ffd6b0e62429736b7311d5f010c5d2442 | /src/Pr4/Kvadrat.java | d512b246c7bb8c90cb9923beabd411a7a5522088 | []
| no_license | Vova-oss/PractForJava | https://github.com/Vova-oss/PractForJava | 9360c5aeb6f17b1937c1becf8b6afbaaea47c8de | ce65bb3bc0accabcadf0a7e18dedb7dc8cdda0b4 | refs/heads/master | 2023-01-14T00:40:31.447000 | 2020-11-21T23:19:24 | 2020-11-21T23:19:24 | 295,008,608 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Pr4;
import java.awt.*;
public class Kvadrat extends Shape {
int r,g,b;
int x,y,w,h;
Kvadrat(){
setColor();
setPosition();
}
@Override
public void setColor() {
r = (int) (Math.random() * 255);
b = (int) (Math.random() * 255);
g = (int) (Math.random() * 255);
}
@Override
public void setPosition() {
x = (int) (Math.random()*500);
y = (int) (Math.random()*500);
w = (int) (Math.random()*200);
h = (int) (Math.random()*200);
}
@Override
public void paint(Graphics g) {
Graphics2D gr2d = (Graphics2D) g;
gr2d.setPaint(new Color(r, this.g, b));
gr2d.drawRect(x,y,w,h);
}
}
| UTF-8 | Java | 732 | java | Kvadrat.java | Java | []
| null | []
| package Pr4;
import java.awt.*;
public class Kvadrat extends Shape {
int r,g,b;
int x,y,w,h;
Kvadrat(){
setColor();
setPosition();
}
@Override
public void setColor() {
r = (int) (Math.random() * 255);
b = (int) (Math.random() * 255);
g = (int) (Math.random() * 255);
}
@Override
public void setPosition() {
x = (int) (Math.random()*500);
y = (int) (Math.random()*500);
w = (int) (Math.random()*200);
h = (int) (Math.random()*200);
}
@Override
public void paint(Graphics g) {
Graphics2D gr2d = (Graphics2D) g;
gr2d.setPaint(new Color(r, this.g, b));
gr2d.drawRect(x,y,w,h);
}
}
| 732 | 0.5 | 0.463115 | 35 | 19.914286 | 15.55152 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.742857 | false | false | 15 |
4bbf7d254859112b30e22ec42d0b1b1d61124e0f | 36,335,423,324,552 | c9bf64b07fcd20ae2224b81edc72fde732b7fecc | /src/gui/ListarVendaController.java | 3462fec02c811eb11f143009178a079294f1325e | [
"MIT"
]
| permissive | TomasMeneses/POO-Academia1 | https://github.com/TomasMeneses/POO-Academia1 | 6258b673a7ecee43343c2a4a29254ddb30db8aff | 90285d0d4649311ffba7e9a98035cdeac88bc6dd | refs/heads/master | 2018-11-19T05:08:41.221000 | 2017-08-23T23:57:00 | 2017-08-23T23:57:00 | 94,438,147 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gui;
import java.net.URL;
import java.util.ResourceBundle;
import beans.*;
import beans.Venda;
import excecoes.ClienteNaoExisteException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import negocios.Fachada;
public class ListarVendaController implements Initializable{
@FXML
private Button voltarListar;
@FXML
private TextField idCLiente;
@FXML
private TextField idVenda;
@FXML
private TextField precoVenda;
@FXML
private TextField nomeCliente;
@FXML
private TableView<Venda> tabelaVenda;
@FXML
private TableColumn<Venda, String> vendaId;
@FXML
private TableColumn<Venda, String> clienteId;
private ObservableList<Venda> tvVenda;
private Venda v;
@Override
public void initialize(URL location, ResourceBundle resources) {
tabelaVenda.setEditable(false);
tvVenda = FXCollections.observableArrayList(Fachada.getInstancia().listarVenda());
vendaId = new TableColumn<>("Id Venda");
vendaId.setResizable(true);
clienteId = new TableColumn<>("Id Cliente");
clienteId.setResizable(true);
tabelaVenda.getColumns().addAll(vendaId, clienteId);
vendaId.setCellValueFactory(new PropertyValueFactory<Venda, String>("idVenda"));
clienteId.setCellValueFactory(new PropertyValueFactory<Venda, String>("idCliente"));
tabelaVenda.setItems(tvVenda);
tabelaVenda.setOnMouseClicked(e -> {
v = tabelaVenda.getSelectionModel().getSelectedItem();
idVenda.setText(v.getIdVenda());
idCLiente.setText(v.getIdCliente());
precoVenda.setText("R$" + Double.toString(v.getValorTotal()));
String nomeC = null;
//
// try {
// nomeC = Fachada.getInstancia().procurarCliente(v.getIdCliente()).getNome();
// nomeCliente.setText(nomeC);
//
// } catch (ClienteNaoExisteException e1) {
// e1.printStackTrace();
// }
});
}
@FXML
private void voltarListar(ActionEvent evento){
((Node) (evento.getSource())).getScene().getWindow().hide();
Parent parentT = null;
try {
parentT = FXMLLoader.load(getClass().getResource("OpcoesFuncionario.fxml"));
Stage stageT = new Stage();
Scene cena = new Scene(parentT);
stageT.setScene(cena);
stageT.setTitle("MusclePlus");
stageT.show();
} catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(e.getMessage());
alert.showAndWait();
}
}
}
| UTF-8 | Java | 2,959 | java | ListarVendaController.java | Java | []
| null | []
| package gui;
import java.net.URL;
import java.util.ResourceBundle;
import beans.*;
import beans.Venda;
import excecoes.ClienteNaoExisteException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import negocios.Fachada;
public class ListarVendaController implements Initializable{
@FXML
private Button voltarListar;
@FXML
private TextField idCLiente;
@FXML
private TextField idVenda;
@FXML
private TextField precoVenda;
@FXML
private TextField nomeCliente;
@FXML
private TableView<Venda> tabelaVenda;
@FXML
private TableColumn<Venda, String> vendaId;
@FXML
private TableColumn<Venda, String> clienteId;
private ObservableList<Venda> tvVenda;
private Venda v;
@Override
public void initialize(URL location, ResourceBundle resources) {
tabelaVenda.setEditable(false);
tvVenda = FXCollections.observableArrayList(Fachada.getInstancia().listarVenda());
vendaId = new TableColumn<>("Id Venda");
vendaId.setResizable(true);
clienteId = new TableColumn<>("Id Cliente");
clienteId.setResizable(true);
tabelaVenda.getColumns().addAll(vendaId, clienteId);
vendaId.setCellValueFactory(new PropertyValueFactory<Venda, String>("idVenda"));
clienteId.setCellValueFactory(new PropertyValueFactory<Venda, String>("idCliente"));
tabelaVenda.setItems(tvVenda);
tabelaVenda.setOnMouseClicked(e -> {
v = tabelaVenda.getSelectionModel().getSelectedItem();
idVenda.setText(v.getIdVenda());
idCLiente.setText(v.getIdCliente());
precoVenda.setText("R$" + Double.toString(v.getValorTotal()));
String nomeC = null;
//
// try {
// nomeC = Fachada.getInstancia().procurarCliente(v.getIdCliente()).getNome();
// nomeCliente.setText(nomeC);
//
// } catch (ClienteNaoExisteException e1) {
// e1.printStackTrace();
// }
});
}
@FXML
private void voltarListar(ActionEvent evento){
((Node) (evento.getSource())).getScene().getWindow().hide();
Parent parentT = null;
try {
parentT = FXMLLoader.load(getClass().getResource("OpcoesFuncionario.fxml"));
Stage stageT = new Stage();
Scene cena = new Scene(parentT);
stageT.setScene(cena);
stageT.setTitle("MusclePlus");
stageT.show();
} catch (Exception e) {
e.printStackTrace();
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(e.getMessage());
alert.showAndWait();
}
}
}
| 2,959 | 0.742481 | 0.741805 | 117 | 24.290598 | 21.542271 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.008547 | false | false | 15 |
ce29ca77be4fd4ea06c62ab07a8699bf04e7242d | 18,485,539,269,013 | e2d5fcef818c4aedf9d4fd408bde543277f062d7 | /dropwizard-jobs-guice/src/main/java/io/dropwizard/jobs/GuiceJobFactory.java | 50df8b5d6d21b3adfb39b269e6b50191b80c7702 | [
"Apache-2.0"
]
| permissive | hakandilek/dropwizard-jobs | https://github.com/hakandilek/dropwizard-jobs | 3aa866b29ce93ad56ad870ee79c0df1d274f3540 | 007ad9eb2556aa8ba7ab8c7852e923764f9d7b8f | refs/heads/master | 2023-05-27T14:40:01.139000 | 2023-05-21T20:38:01 | 2023-05-21T20:42:26 | 127,968,925 | 0 | 0 | Apache-2.0 | true | 2018-04-03T21:06:53 | 2018-04-03T21:06:53 | 2018-03-30T22:50:11 | 2018-03-30T20:59:23 | 226 | 0 | 0 | 0 | null | false | null | package io.dropwizard.jobs;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
public class GuiceJobFactory implements JobFactory {
private Injector injector;
@Inject
public GuiceJobFactory(Injector injector) {
this.injector = injector;
}
@Override
public Job newJob(TriggerFiredBundle triggerFiredBundle, Scheduler scheduler) throws SchedulerException {
JobDetail jobDetail = triggerFiredBundle.getJobDetail();
Class<? extends Job> jobClass = jobDetail.getJobClass();
return injector.getInstance(jobClass);
}
}
| UTF-8 | Java | 789 | java | GuiceJobFactory.java | Java | []
| null | []
| package io.dropwizard.jobs;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.quartz.spi.TriggerFiredBundle;
public class GuiceJobFactory implements JobFactory {
private Injector injector;
@Inject
public GuiceJobFactory(Injector injector) {
this.injector = injector;
}
@Override
public Job newJob(TriggerFiredBundle triggerFiredBundle, Scheduler scheduler) throws SchedulerException {
JobDetail jobDetail = triggerFiredBundle.getJobDetail();
Class<? extends Job> jobClass = jobDetail.getJobClass();
return injector.getInstance(jobClass);
}
}
| 789 | 0.759189 | 0.759189 | 27 | 28.222221 | 25.112095 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.