hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
4c9060158c0c473dfc88ce995b601a524611109d | 54,955 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package office_man_system;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.sql.*;
import java.time.LocalDate;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Pasindu Senarathne
*/
public class Register_From extends javax.swing.JPanel {
public Register_From() {
initComponents();
}
public Connection getConnection(){
Connection con;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/office_management_system?autoReconnect=true&useSSL=false","root","root");
return con;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void getMachineBrand(String search){
Connection connection = getConnection();
String query = "SELECT brand FROM available_machines WHERE machineSerial = '"+search+"'";
ResultSet result;
try {
PreparedStatement ps = connection.prepareStatement(query);
result = ps.executeQuery(query);
while(result.next()){
brand_name.setSelectedItem(result.getString(1));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public void getMachineType(String search){
Connection connection = getConnection();
String query = "SELECT type FROM available_machines WHERE machineSerial = '"+search+"'";
ResultSet result;
try {
PreparedStatement ps = connection.prepareStatement(query);
result = ps.executeQuery(query);
while(result.next()){
macine_type.setSelectedItem(result.getString(1));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public void getMachineStatus(String search){
Connection connection = getConnection();
String query = "SELECT status FROM available_machines WHERE machineSerial = '"+search+"'";
ResultSet result;
try {
PreparedStatement ps = connection.prepareStatement(query);
result = ps.executeQuery(query);
while(result.next()){
String state = result.getString(1);
if(state.equals("External Damages")){
damage_m.setSelected(true);
}
if(state.equals("Brand New")){
new_m.setSelected(true);
}
if(state.equals("Good Condition")){
new_m.setSelected(true);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public void getMachineDiscription(String search){
Connection connection = getConnection();
String query = "SELECT discrip FROM available_machines WHERE machineSerial = '"+search+"'";
ResultSet result;
try {
PreparedStatement ps = connection.prepareStatement(query);
result = ps.executeQuery(query);
while(result.next()){
discription.setText(result.getString(1));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public void getcopyCount(String search){
Connection connection = getConnection();
String query = "SELECT copycount FROM available_machines WHERE machineSerial= '"+search+"'";
ResultSet result;
try {
PreparedStatement ps = connection.prepareStatement(query);
result = ps.executeQuery(query);
while(result.next()){
count_copy.setText(result.getString(1));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public boolean validateEmail(String string){
int val;
int at = 0;
int dot = 0;
for(int i = 0; i < string.length();i++){
val = (int)string.charAt(i);
if(val == 64) {
at = i;
}
}
for(int j = 0; j < string.length();j++){
val = (int)string.charAt(j);
if(val == 46) {
dot = j;
}
}
if(((at != 0) && (dot!= 0) )&&(at < dot)) {
return true;
}
else{
return false;
}
}
public boolean validateLetter(String string){
int val;
boolean ret = true;
for(int i = 0; i < string.length(); i++){
val = (int)string.charAt(i);
if(!(((val >=65) && (val <= 90)) || ((val >= 97) && (val <= 122)) || val == 32)){
ret = false;
}
}
return ret;
}
public boolean validatePhone(String string){
if((string.length() == 12)&& (string.charAt(0) == '+')&& (string.charAt(1) == '9') && (string.charAt(2) == '4') ){
return true;
}
else{
return false;
}
}
public boolean validateNIC(String string){
int val = string.length();
char str = 0;
for(int i = 0; i < string.length();i++){
str = string.charAt(i);
if(val == 10 && str == 'V'){
return true;
}
}
return false;
}
public boolean validateChequeNumber(String string){
if(string.length() == 6){
return true;
}
else{
return false;
}
}
public boolean validateSerialNumber(String string){
if(string.length() == 10){
return true;
}
else{
return false;
}
}
public boolean validateNumbers(String string){
int val;
boolean ret = true;
for(int i = 0; i < string.length(); i++){
val = (int)string.charAt(i);
if(!((val <= 57) && (val >= 48 ))){
ret = false;
}
}
return ret;
}
public boolean validateNewNIC(String string){
int val;
boolean ret = true;
int val2 = string.length();
for(int i = 0; i < string.length(); i++){
val = (int)string.charAt(i);
if(!((val <= 57) && (val >= 48 ) && val2 == 12)){
ret = false;
}
}
return ret;
}
public LocalDate setDate(){
return java.time.LocalDate.now();
}
public void getCustomerDetails(String search){
Connection connection = getConnection();
String query = "SELECT customerName,address,phone,email,depositAmount,paidType,bank,chequeNum FROM rented_customers WHERE nic = '"+search+"'";
ResultSet result;
try {
PreparedStatement ps = connection.prepareStatement(query);
result = ps.executeQuery(query);
while(result.next()){
c_name.setText(result.getString(1));
address_area.setText(result.getString(2));
phone_num.setText(result.getString(3));
email_address.setText(result.getString(4));
deposit_amount1.setText(result.getString(5));
bank_type.setText(result.getString(7));
cheque_num.setText(result.getString(8));
String type = result.getString(6);
if(type.equals("Cash Payment")){
cahT.setSelected(true);
}
if(type.equals("Cheque Payment")){
chqT.setSelected(true);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
payment_type = new javax.swing.ButtonGroup();
machin_conditions = new javax.swing.ButtonGroup();
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
m_serial = new javax.swing.JTextField();
jSeparator1 = new javax.swing.JSeparator();
cusName_txt = new javax.swing.JLabel();
nic_name = new javax.swing.JTextField();
phone_num = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
address_area = new javax.swing.JTextArea();
phone_txt = new javax.swing.JLabel();
nic_txt = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
email_address = new javax.swing.JTextField();
email_txt = new javax.swing.JLabel();
brand_name = new javax.swing.JComboBox<>();
jLabel2 = new javax.swing.JLabel();
c_name = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
count_copy = new javax.swing.JTextField();
copy_txt = new javax.swing.JLabel();
serial_txt = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
checkout = new javax.swing.JButton();
macine_type = new javax.swing.JComboBox<>();
jLabel11 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
discription = new javax.swing.JTextArea();
address_txt = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel13 = new javax.swing.JLabel();
cheque_num = new javax.swing.JTextField();
bank_type = new javax.swing.JTextField();
chq_txt = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
cahT = new javax.swing.JRadioButton();
chqT = new javax.swing.JRadioButton();
new_m = new javax.swing.JRadioButton();
good_m = new javax.swing.JRadioButton();
damage_m = new javax.swing.JRadioButton();
jScrollPane4 = new javax.swing.JScrollPane();
preview = new javax.swing.JTable();
submit_btn1 = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
deposit_txt1 = new javax.swing.JLabel();
deposit_amount1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
customerType = new javax.swing.JRadioButton();
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");
setBackground(new java.awt.Color(255, 255, 255));
setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
setName(""); // NOI18N
m_serial.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N
m_serial.setToolTipText("Customer Name");
m_serial.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
m_serialKeyPressed(evt);
}
});
cusName_txt.setBackground(new java.awt.Color(255, 255, 255));
cusName_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
cusName_txt.setText("Customer Name");
nic_name.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
nic_name.setToolTipText("NIC");
nic_name.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
nic_nameKeyPressed(evt);
}
});
phone_num.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
phone_num.setToolTipText("Phone Number");
address_area.setColumns(20);
address_area.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
address_area.setRows(5);
address_area.setToolTipText("Address");
jScrollPane1.setViewportView(address_area);
phone_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
phone_txt.setText("Phone Number");
nic_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
nic_txt.setText("NIC Number");
jLabel7.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
jLabel7.setText("Discription");
email_address.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
email_address.setToolTipText("Deposit Amount");
email_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
email_txt.setText("Email");
brand_name.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
brand_name.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "<Select>", "Ricoh", "Toshiba", " " }));
jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
c_name.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
c_name.setToolTipText("Customer Name");
jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
jLabel3.setText("Machine Brand");
count_copy.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
count_copy.setToolTipText("Customer Name");
copy_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
copy_txt.setText("Copy Count");
serial_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
serial_txt.setText("Machine Serial");
jLabel10.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
jLabel10.setText("Machine Status");
checkout.setBackground(new java.awt.Color(255, 255, 255));
checkout.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
checkout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/office_man_system/images/icons8_User_Menu_Male_35px_1.png"))); // NOI18N
checkout.setText("Checkout");
checkout.setIconTextGap(10);
checkout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
checkout_btnActionPerformed(evt);
}
});
macine_type.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
macine_type.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "<Select>", "Color", "Black" }));
jLabel11.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
jLabel11.setText("Type");
discription.setColumns(20);
discription.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
discription.setRows(5);
discription.setToolTipText("Address");
jScrollPane2.setViewportView(discription);
address_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
address_txt.setText("Address");
jLabel13.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
jLabel13.setText("For Cheque Payments");
cheque_num.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
bank_type.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
chq_txt.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
chq_txt.setText("Cheque Number");
jLabel15.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
jLabel15.setText("Bank");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cheque_num, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(chq_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bank_type, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(21, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bank_type, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chq_txt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cheque_num, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27))
);
cahT.setBackground(new java.awt.Color(255, 255, 255));
payment_type.add(cahT);
cahT.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
cahT.setText("Cash Payment");
cahT.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cahTActionPerformed(evt);
}
});
chqT.setBackground(new java.awt.Color(255, 255, 255));
payment_type.add(chqT);
chqT.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
chqT.setText("Cheque Paymet");
new_m.setBackground(new java.awt.Color(255, 255, 255));
machin_conditions.add(new_m);
new_m.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
new_m.setText("Brand New");
good_m.setBackground(new java.awt.Color(255, 255, 255));
machin_conditions.add(good_m);
good_m.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
good_m.setText("Good Conditions");
damage_m.setBackground(new java.awt.Color(255, 255, 255));
machin_conditions.add(damage_m);
damage_m.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
damage_m.setText("External Damaged");
preview.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
preview.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Machine Brand", "Type", "Serial Number", "Copy Count", "Status", "Discription"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
preview.setGridColor(new java.awt.Color(255, 255, 255));
preview.setRowHeight(25);
jScrollPane4.setViewportView(preview);
submit_btn1.setBackground(new java.awt.Color(255, 255, 255));
submit_btn1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
submit_btn1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/office_man_system/images/icons8_Add_Shopping_Cart_35px_2.png"))); // NOI18N
submit_btn1.setText("Record");
submit_btn1.setIconTextGap(10);
submit_btn1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
submit_btn1ActionPerformed(evt);
}
});
jLabel8.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
jLabel8.setText("Preview Machine Logs");
jButton2.setBackground(new java.awt.Color(255, 255, 255));
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/office_man_system/images/icons8_Remove_Tag_15px.png"))); // NOI18N
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(255, 255, 255));
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/office_man_system/images/icons8_Edit_Row_15px.png"))); // NOI18N
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
deposit_txt1.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
deposit_txt1.setText("Security Deposit Amount");
deposit_amount1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
deposit_amount1.setToolTipText("Deposit Amount");
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/office_man_system/images/icons8_Add_New_40px.png"))); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
customerType.setBackground(new java.awt.Color(255, 255, 255));
customerType.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
customerType.setText("Existing Customer");
customerType.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
customerTypeMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(nic_name, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
.addComponent(phone_num, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
.addComponent(email_address, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(cusName_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(customerType, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(phone_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nic_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(email_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1)
.addComponent(c_name)
.addComponent(address_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(deposit_txt1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(deposit_amount1, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(cahT)
.addGap(27, 27, 27)
.addComponent(chqT)))
.addGap(44, 44, 44)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(count_copy, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(407, 407, 407)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(copy_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(brand_name, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(macine_type, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(new_m)
.addGap(18, 18, 18)
.addComponent(good_m)
.addGap(18, 18, 18)
.addComponent(damage_m))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 831, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(checkout, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(submit_btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(serial_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(m_serial, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(58, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cusName_txt)
.addComponent(customerType))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(c_name, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23)
.addComponent(nic_txt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nic_name, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(phone_txt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(phone_num, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(email_txt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(email_address, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24)
.addComponent(address_txt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(deposit_txt1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(deposit_amount1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cahT)
.addComponent(chqT))
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(serial_txt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(m_serial, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel11))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(brand_name, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(macine_type, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(23, 23, 23)
.addComponent(copy_txt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(count_copy, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel10)
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(new_m)
.addComponent(good_m)
.addComponent(damage_m))
.addGap(18, 18, 18)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jButton2)
.addComponent(jButton3))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 74, Short.MAX_VALUE)
.addComponent(submit_btn1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(checkout, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41))))
);
}// </editor-fold>//GEN-END:initComponents
private void checkout_btnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkout_btnActionPerformed
String customer_name = c_name.getText();
String customer_nic = nic_name.getText();
String customer_phone = phone_num.getText();
String customer_address = address_area.getText();
String deposit= deposit_amount1.getText();
boolean cash = cahT.isSelected();
boolean cheque = chqT.isSelected();
String chequeNum = cheque_num.getText();
String bank = bank_type.getText();
String brand = brand_name.getSelectedItem().toString();
String machine_type = macine_type.getSelectedItem().toString();
String copycount = count_copy.getText();
String serialNum = m_serial.getText();
boolean newM = new_m.isSelected();
boolean goodM = good_m.isSelected();
boolean damageM = damage_m.isSelected();
String damageDis = discription.getText();
String email = email_address.getText();
boolean stateReg = customerType.isSelected();
String machineStatus = "";
String state = "Unregistered";
if(stateReg == true){
state = "Registered";
}
if(cash == true){
bank = "No";
chequeNum = "No";
}
if(newM == true){
machineStatus = "Brand New";
}
else if(goodM == true){
machineStatus = "Good Condition";
}
else if(damageM == true){
machineStatus = "External Damages";
}
String dateIssued = setDate().toString();
if((customer_name.isEmpty()) && (customer_nic.isEmpty()) && (customer_address.isEmpty()) && (customer_phone.isEmpty()) && (copycount.isEmpty()) && (serialNum.isEmpty()) ){
JOptionPane.showMessageDialog(null, "Fields Can Not Be EMPTY!");
}
else{
if (customer_name.isEmpty()){
JOptionPane.showMessageDialog(null, "Customer Name Can Not Be EMPTY!");
cusName_txt.setForeground(Color.RED);
}
if(customer_nic.isEmpty()){
JOptionPane.showMessageDialog(null, "NIC Number Can Not Be EMPTY!");
nic_txt.setForeground(Color.RED);
}
if(customer_address.isEmpty()){
JOptionPane.showMessageDialog(null, "Address Can Not Be EMPTY!");
address_txt.setForeground(Color.RED);
}
if(customer_phone.isEmpty()){
JOptionPane.showMessageDialog(null, "Phone Can Not Be EMPTY!");
phone_txt.setForeground(Color.RED);
}
if(copycount.isEmpty()){
JOptionPane.showMessageDialog(null, "Copy Count Value Can Not Be EMPTY!");
copy_txt.setForeground(Color.RED);
}
if(serialNum.isEmpty()){
JOptionPane.showMessageDialog(null, "Serial Number Can Not Be EMPTY!");
copy_txt.setForeground(Color.RED);
}
if(email.isEmpty()){
JOptionPane.showMessageDialog(null, "Email Can Not Be EMPTY!");
copy_txt.setForeground(Color.RED);
}
}
if(validateLetter(customer_name) == false){
JOptionPane.showMessageDialog(null, "Customer name can not contain numbers or characters!");
cusName_txt.setForeground(Color.RED);
}
else if(validatePhone(customer_phone) == false){
JOptionPane.showMessageDialog(null, "Phone number should be like +94112700800!");
phone_txt.setForeground(Color.RED);
}
else if(validateNIC(customer_nic) == false){
JOptionPane.showMessageDialog(null, "Old NIC number should contain 10 characters including V, New NIC should contain 12 numbers");
nic_txt.setForeground(Color.RED);
}
else if(validateChequeNumber(chequeNum)== false && cheque == true){
JOptionPane.showMessageDialog(null, "Cheque number should contain 6 numbers");
chq_txt.setForeground(Color.RED);
}
else if(validateNumbers(serialNum) == false || validateSerialNumber(serialNum) == false){
JOptionPane.showMessageDialog(null, "Serial number should contain 10 numbers, Can not contain letters or characters");
serial_txt.setForeground(Color.RED);
}
else if(validateNumbers(copycount)== false){
JOptionPane.showMessageDialog(null, "Copy Count should contain numbers, Can not contain letters or characters");
copy_txt.setForeground(Color.RED);
}
else if(validateNumbers(deposit) == false){
JOptionPane.showMessageDialog(null, "Deposit Amount should contain numbers, Can not contain letters or characters");
deposit_txt1.setForeground(Color.RED);
}
else if(validateEmail(email) == false){
JOptionPane.showMessageDialog(null, "Please Enter Valid Email Address");
email_txt.setForeground(Color.RED);
}
else {
CheckOut check = new CheckOut();
check = new CheckOut(customer_name,customer_nic,customer_phone,customer_address,deposit,chequeNum,dateIssued,bank,email,state);
int rows=preview.getRowCount();
for(int row = 0; row<rows; row++)
{
String name = (String)preview.getValueAt(row, 0);
String typeOfMachine = (String)preview.getValueAt(row, 1);
String serialNumber = (String)preview.getValueAt(row, 2);
String copyC = (String)preview.getValueAt(row, 3);
String statusOfMachine = (String)preview.getValueAt(row, 4);
String machDis = (String)preview.getValueAt(row, 5);
CheckOut check1 = check;
check1.addMachine(name, typeOfMachine, serialNumber, copyC, statusOfMachine, machDis);
}
check.setVisible(true);
//RentService_MainUI main = new RentService_MainUI();
//main.closeWindow();
}
}//GEN-LAST:event_checkout_btnActionPerformed
private void cahTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cahTActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cahTActionPerformed
private void submit_btn1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submit_btn1ActionPerformed
String customer_name = c_name.getText();
String customer_nic = nic_name.getText();
String customer_phone = phone_num.getText();
String customer_address = address_area.getText();
String deposit= deposit_amount1.getText();
boolean cash = cahT.isSelected();
boolean cheque = chqT.isSelected();
String chequeNum = cheque_num.getText();
String bank = bank_type.getText();
String brand = brand_name.getSelectedItem().toString();
String type = macine_type.getSelectedItem().toString();
String copyCount = count_copy.getText();
String serial = m_serial.getText();
boolean newM = new_m.isSelected();
boolean goodM = good_m.isSelected();
boolean damageM = damage_m.isSelected();
String dis = discription.getText();
String email = email_address.getText();
String machineStatus = "";
if(newM == true){
machineStatus = "Brand New";
}
else if(goodM == true){
machineStatus = "Good Condition";
}
else if(damageM == true){
machineStatus = "External Damages";
}
if (customer_name.isEmpty()){
JOptionPane.showMessageDialog(null, "Fields Can Not Be EMPTY!");
cusName_txt.setForeground(Color.RED);
}
else if(customer_nic.isEmpty()){
JOptionPane.showMessageDialog(null, "Fields Can Not Be EMPTY!");
nic_txt.setForeground(Color.RED);
}
else if(customer_address.isEmpty()){
JOptionPane.showMessageDialog(null, "Fields Can Not Be EMPTY!");
address_txt.setForeground(Color.RED);
}
else if(customer_phone.isEmpty()){
JOptionPane.showMessageDialog(null, "Fields Can Not Be EMPTY!");
phone_txt.setForeground(Color.RED);
}
else if(copyCount.isEmpty()){
JOptionPane.showMessageDialog(null, "Fields Can Not Be EMPTY!");
copy_txt.setForeground(Color.RED);
}
else if(serial.isEmpty()){
JOptionPane.showMessageDialog(null, "Fields Can Not Be EMPTY!");
copy_txt.setForeground(Color.RED);
}
else if(validateLetter(customer_name) == false){
JOptionPane.showMessageDialog(null, "Customer name can not contain numbers or characters!");
cusName_txt.setForeground(Color.RED);
}
else if(validatePhone(customer_phone) == false){
JOptionPane.showMessageDialog(null, "Phone number should be like +94112700800!");
phone_txt.setForeground(Color.RED);
}
else if(validateNIC(customer_nic) == false){
JOptionPane.showMessageDialog(null, "Old NIC number should contain 10 characters including V, New NIC should contain 10 numbers");
nic_txt.setForeground(Color.RED);
}
else if(validateChequeNumber(chequeNum)== false && cheque == true){
JOptionPane.showMessageDialog(null, "Cheque number should contain 6 numbers");
chq_txt.setForeground(Color.RED);
}
else if(validateNumbers(serial) == false || validateSerialNumber(serial) == false){
JOptionPane.showMessageDialog(null, "Serial number should contain 10 numbers, Can not contain letters r characters");
serial_txt.setForeground(Color.RED);
}
else if(validateNumbers(copyCount)== false){
JOptionPane.showMessageDialog(null, "Copy Count should contain numbers, Can not contain letters or characters");
copy_txt.setForeground(Color.RED);
}
else if(validateNumbers(deposit) == false){
JOptionPane.showMessageDialog(null, "Deposit Amount should contain numbers, Can not contain letters or characters");
deposit_txt1.setForeground(Color.RED);
}
else if(validateEmail(email) == false){
JOptionPane.showMessageDialog(null, "Please Enter Valid Email Address");
email_txt.setForeground(Color.RED);
}
else {
Object[] row = { brand, type, serial, copyCount, machineStatus,dis};
DefaultTableModel model = (DefaultTableModel) preview.getModel();
model.addRow(row);
}
}//GEN-LAST:event_submit_btn1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
DefaultTableModel model = (DefaultTableModel) preview.getModel();
try {
int index = preview.getSelectedRow();
model.removeRow(index);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
DefaultTableModel model = (DefaultTableModel) preview.getModel();
int selectedRowIndex = preview.getSelectedRow();
int selectedColIndex = preview.getSelectedColumn();
String val = JOptionPane.showInputDialog("Enter Here New Value");
model.setValueAt(val, selectedRowIndex, selectedColIndex);
}//GEN-LAST:event_jButton3ActionPerformed
private void m_serialKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_m_serialKeyPressed
String serial = m_serial.getText();
getMachineType(serial);
getMachineBrand(serial);
getcopyCount(serial);
getMachineStatus(serial);
getMachineDiscription(serial);
}//GEN-LAST:event_m_serialKeyPressed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
c_name.setText("Pasindu Senarathne");
nic_name.setText("962791790V");
address_area.setText("No 1,Street 1,City 1,Postal Code");
phone_num.setText("+94112987654");
email_address.setText("[email protected]");
deposit_amount1.setText("40000");
chqT.setSelected(true);
bank_type.setText("Peoples Bank");
cheque_num.setText("234098");
m_serial.setText("7687213456");
}//GEN-LAST:event_jButton1ActionPerformed
private void customerTypeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_customerTypeMouseClicked
}//GEN-LAST:event_customerTypeMouseClicked
private void nic_nameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nic_nameKeyPressed
boolean typeC = customerType.isSelected();
if(typeC == true){
String nic = nic_name.getText();
getCustomerDetails(nic);
}
}//GEN-LAST:event_nic_nameKeyPressed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea address_area;
private javax.swing.JLabel address_txt;
private javax.swing.JTextField bank_type;
private javax.swing.JComboBox<String> brand_name;
private javax.swing.JTextField c_name;
private javax.swing.JRadioButton cahT;
private javax.swing.JButton checkout;
private javax.swing.JTextField cheque_num;
private javax.swing.JRadioButton chqT;
private javax.swing.JLabel chq_txt;
private javax.swing.JLabel copy_txt;
private javax.swing.JTextField count_copy;
private javax.swing.JLabel cusName_txt;
private javax.swing.JRadioButton customerType;
private javax.swing.JRadioButton damage_m;
private javax.swing.JTextField deposit_amount1;
private javax.swing.JLabel deposit_txt1;
private javax.swing.JTextArea discription;
private javax.swing.JTextField email_address;
private javax.swing.JLabel email_txt;
private javax.swing.JRadioButton good_m;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JTextField m_serial;
private javax.swing.ButtonGroup machin_conditions;
private javax.swing.JComboBox<String> macine_type;
private javax.swing.JRadioButton new_m;
private javax.swing.JTextField nic_name;
private javax.swing.JLabel nic_txt;
private javax.swing.ButtonGroup payment_type;
private javax.swing.JTextField phone_num;
private javax.swing.JLabel phone_txt;
private javax.swing.JTable preview;
private javax.swing.JLabel serial_txt;
private javax.swing.JButton submit_btn1;
// End of variables declaration//GEN-END:variables
}
| 41.950382 | 179 | 0.582258 |
93fe975f0ddc9a4f6fe81ad1e8808c17afb615bf | 688 | package com.itjing.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 线程池
*/
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new myThread());
service.execute(new myThread());
service.execute(new myThread());
service.execute(new myThread());
//2.关闭
service.shutdown();
}
}
class myThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
| 22.933333 | 67 | 0.643895 |
38d1af615c5706b2067a20d129d8b58d336800d3 | 363 | package com.google.android.gms.common;
import java.util.Arrays;
final class zzf extends zze {
private final byte[] zzu;
zzf(byte[] bArr) {
super(Arrays.copyOfRange(bArr, 0, 25));
this.zzu = bArr;
}
/* access modifiers changed from: 0000 */
public final byte[] getBytes() {
return this.zzu;
}
}
| 20.166667 | 48 | 0.581267 |
d3bc5e0b1b4bc315a80b2195cb578d384feb6715 | 7,732 | package info.u250.c2d.box2deditor.ui.controls;
import info.u250.c2d.box2d.model.b2BodyDefModel;
import info.u250.c2d.box2d.model.b2FixtureDefModel;
import info.u250.c2d.box2d.model.b2JointDefModel;
import info.u250.c2d.box2d.model.fixture.b2CircleFixtureDefModel;
import info.u250.c2d.box2d.model.fixture.b2RectangleFixtureDefModel;
import info.u250.c2d.box2deditor.Main;
import info.u250.c2d.box2deditor.adapter.PolygonFixtureDefModel;
import info.u250.c2d.box2deditor.adapter.SceneModelAdapter;
import info.u250.c2d.box2deditor.gdx.PhysicalWorld;
import info.u250.c2d.box2deditor.ui.util.DefCellRenderer;
import info.u250.c2d.box2deditor.ui.util.DefListModel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Box2dFunctionPanel extends JPanel {
private static final long serialVersionUID = 1368673847228258801L;
private JList defList;
private DefListModel defListModel;
private JMenuItem mntmDelete;
/**
* Create the panel.
*/
public Box2dFunctionPanel() {
setLayout(new BorderLayout(0, 0));
JScrollPane defScrollPanel = new JScrollPane();
add(defScrollPanel, BorderLayout.CENTER);
defList = new JList();
defList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (2 == e.getClickCount()) {
Main.bind(defList.getSelectedValue());
}
}
});
defList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
defList.setCellRenderer(new DefCellRenderer());
defScrollPanel.setViewportView(defList);
defListModel = new DefListModel();
defList.setModel(defListModel);
JPopupMenu popupMenu = new JPopupMenu();
addPopup(defList, popupMenu);
mntmDelete = new JMenuItem("Delete");
mntmDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SceneModelAdapter model = PhysicalWorld.MODEL;
Object object = defList.getSelectedValue();
if (object instanceof b2JointDefModel) {
model.removeJoint(b2JointDefModel.class.cast(object));
setupModel();
} else if (object instanceof b2BodyDefModel) {
model.removeBody(b2BodyDefModel.class.cast(object));
setupModel();
} else if (object instanceof b2FixtureDefModel) {
model.removeFixture(b2FixtureDefModel.class.cast(object));
setupModel();
}
}
});
JMenuItem mntmAddBoxFixture = new JMenuItem("Add Box Fixture");
mntmAddBoxFixture.setFont(new Font(mntmAddBoxFixture.getFont().getName(), Font.PLAIN, 24));
popupMenu.add(mntmAddBoxFixture);
mntmAddBoxFixture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b2RectangleFixtureDefModel model = new b2RectangleFixtureDefModel();
PhysicalWorld.MODEL.addFixture(model);
addModel(model);
}
});
mntmAddBoxFixture.setIcon(new ImageIcon(Box2dFunctionPanel.class.getResource("/info/u250/c2d/box2deditor/ui/res/b2RectangleFixtureDefModel.png")));
JMenuItem mntmAddCircleFixture = new JMenuItem("Add Circle Fixture");
mntmAddCircleFixture.setFont(new Font(mntmAddCircleFixture.getFont().getName(), Font.PLAIN, 24));
popupMenu.add(mntmAddCircleFixture);
mntmAddCircleFixture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b2CircleFixtureDefModel model = new b2CircleFixtureDefModel();
PhysicalWorld.MODEL.addFixture(model);
addModel(model);
}
});
mntmAddCircleFixture.setIcon(new ImageIcon(Box2dFunctionPanel.class.getResource("/info/u250/c2d/box2deditor/ui/res/b2CircleFixtureDefModel.png")));
JMenuItem mntmAddPolygonFixture = new JMenuItem("Add Polygon Fixture");
mntmAddPolygonFixture.setFont(new Font(mntmAddPolygonFixture.getFont().getName(), Font.PLAIN, 24));
popupMenu.add(mntmAddPolygonFixture);
mntmAddPolygonFixture.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
PolygonFixtureDefModel model = new PolygonFixtureDefModel();
PhysicalWorld.MODEL.addFixture(model);
addModel(model);
}
});
mntmAddPolygonFixture.setIcon(new ImageIcon(Box2dFunctionPanel.class.getResource("/info/u250/c2d/box2deditor/ui/res/PolygonFixtureDefModel.png")));
JSeparator separator = new JSeparator();
popupMenu.add(separator);
JMenuItem mntmAddBody = new JMenuItem("Add Body");
mntmAddBody.setFont(new Font(mntmAddBody.getFont().getName(), Font.PLAIN, 24));
popupMenu.add(mntmAddBody);
mntmAddBody.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
b2BodyDefModel model = new b2BodyDefModel();
PhysicalWorld.MODEL.addBody(model);
addModel(model);
}
});
mntmAddBody.setIcon(new ImageIcon(Box2dFunctionPanel.class.getResource("/info/u250/c2d/box2deditor/ui/res/b2BodyDefModel.png")));
JSeparator separator_1 = new JSeparator();
popupMenu.add(separator_1);
mntmDelete.setFont(new Font(mntmDelete.getFont().getName(), Font.PLAIN, 24));
mntmDelete.setIcon(new ImageIcon(Box2dFunctionPanel.class.getResource("/info/u250/c2d/box2deditor/ui/res/remove-icon.png")));
popupMenu.add(mntmDelete);
}
public void addModel(Object model) {
Main.bind(model);
setupModel();
defList.setSelectedValue(model, true);
}
public void setupModel() {
defListModel.clear();
for (b2FixtureDefModel b2 : PhysicalWorld.MODEL.fixtureDefModels) {
defListModel.addElement(b2);
}
for (b2BodyDefModel b2 : PhysicalWorld.MODEL.bodyDefModels) {
defListModel.addElement(b2);
}
for (b2JointDefModel b2 : PhysicalWorld.MODEL.jointDefModels) {
defListModel.addElement(b2);
}
}
public JList getDefList() {
return defList;
}
private void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
defList.setSelectedIndex(defList.locationToIndex(e.getPoint()));
}
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
defList.setSelectedIndex(defList.locationToIndex(e.getPoint()));
}
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
if (defList.getSelectedIndex() == -1) {
mntmDelete.setEnabled(false);
} else {
mntmDelete.setEnabled(true);
}
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
| 40.270833 | 155 | 0.636963 |
314e173946cdacd5580368fe3d784300adfeda5c | 8,082 | package ar.com.system.afip.wsaa.business.impl;
import ar.com.system.afip.wsaa.business.api.Service;
import ar.com.system.afip.wsaa.business.api.WsaaManager;
import ar.com.system.afip.wsaa.business.api.XmlConverter;
import ar.com.system.afip.wsaa.data.api.CompanyInfo;
import ar.com.system.afip.wsaa.data.api.SetupDao;
import ar.com.system.afip.wsaa.data.api.WsaaDao;
import ar.com.system.afip.wsaa.service.api.Credentials;
import ar.com.system.afip.wsaa.service.api.LoginCMS;
import com.google.common.base.Throwables;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
import javax.inject.Inject;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import static com.google.common.base.Preconditions.checkNotNull;
public class BouncyCastleWsaaManager implements WsaaManager {
static final String SIGNING_ALGORITHM = "SHA512withRSA";
private final WsaaDao wsaaDao;
private final SetupDao setupDao;
private final LoginCMS loginCms;
private final XmlConverter xmlConverter;
@Inject
public BouncyCastleWsaaManager(WsaaDao wsaaDao,
SetupDao setupDao,
LoginCMS loginCms,
XmlConverter xmlConverter) {
this.wsaaDao = checkNotNull(wsaaDao);
this.setupDao = checkNotNull(setupDao);
this.loginCms = checkNotNull(loginCms);
this.xmlConverter = checkNotNull(xmlConverter);
}
@Override
public void initializeKeys() {
try {
CompanyInfo info = wsaaDao.loadActiveCompanyInfo();
KeyPair keyPair = buildKeys();
wsaaDao.saveCompanyInfo(new CompanyInfo(info.getId(),
info.getName(),
info.isActive(),
info.getUnit(),
info.getCuit(),
toPem(keyPair.getPublic()),
toPem(keyPair.getPrivate()),
null,
info.getGrossIncome(),
info.getActivityStartDate(),
info.getTaxCategory(),
info.getAddress(),
info.getLocation(),
info.getAlias()));
} catch (IOException e) {
Throwables.propagate(e);
}
}
@Override
public String buildCertificateRequest() {
try {
CompanyInfo companyInfo = wsaaDao.loadActiveCompanyInfo();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PEMKeyPair pemPrivateKey = fromPem(companyInfo.getPrivateKey());
PrivateKey privateKey = converter.getPrivateKey(pemPrivateKey
.getPrivateKeyInfo());
PEMKeyPair pemPublicKey = fromPem(companyInfo.getPrivateKey());
PublicKey publicKey = converter.getPublicKey(pemPublicKey
.getPublicKeyInfo());
X500Principal subject = new X500Principal(companyInfo.certificateSource());
ContentSigner signGen = new JcaContentSignerBuilder(SIGNING_ALGORITHM)
.build(privateKey);
PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(
subject, publicKey).build(signGen);
return toPem(csr);
} catch (IOException | OperatorCreationException e) {
throw Throwables.propagate(e);
}
}
@Override
public void updateCertificate(String certificate) {
checkNotNull(certificate);
CompanyInfo info = wsaaDao.loadActiveCompanyInfo();
wsaaDao.saveCompanyInfo(new CompanyInfo(info.getId(),
info.getName(),
info.isActive(),
info.getUnit(),
info.getCuit(),
info.getPublicKey(),
info.getPrivateKey(),
certificate,
info.getGrossIncome(),
info.getActivityStartDate(),
info.getTaxCategory(),
info.getAddress(),
info.getLocation(),
info.getAlias()));
}
@Override
public Credentials login(Service service) {
try {
CompanyInfo companyInfo = wsaaDao.loadActiveCompanyInfo();
checkNotNull(companyInfo.getName(),
"Debe configurar el nombre de la empresa antes de realizar el login");
checkNotNull(companyInfo.getUnit(),
"Debe configurar la unidad oranizacional antes de realizar el login");
checkNotNull(companyInfo.getCuit(),
"Debe configurar el CUIT antes de realizar el login");
checkNotNull(companyInfo.getPrivateKey(),
"Debe configurar la clave privada antes de realizar el login");
checkNotNull(companyInfo.getPublicKey(),
"Debe configurar la clave publica antes de realizar el login");
checkNotNull(companyInfo.getCertificate(),
"Debe configurar el certificado antes de realizar el login");
X509CertificateHolder certificateHolder = fromPem(companyInfo
.getCertificate());
CertificateFactory certFactory = CertificateFactory
.getInstance("X.509");
X509Certificate certificate = (X509Certificate) certFactory
.generateCertificate(new ByteArrayInputStream(
certificateHolder.getEncoded()));
PEMKeyPair pemKeyPair = fromPem(companyInfo.getPrivateKey());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
PrivateKey privKey = converter.getPrivateKey(pemKeyPair
.getPrivateKeyInfo());
String cms = LoginTicketRequest
.create(companyInfo.loginSource(),
service,
setupDao.readSetup()
.getEnvironment())
.toXml(xmlConverter)
.toCms(certificate, privKey)
.toString();
String loginTicketResponseXml = loginCms.loginCms(cms);
LoginTicketResponse response = xmlConverter
.fromXml(LoginTicketResponse.class, loginTicketResponseXml);
return response.getCredentials();
} catch (IOException | CertificateException e) {
throw Throwables.propagate(e);
}
}
private static String toPem(Object data) throws IOException {
try (StringWriter out = new StringWriter();
JcaPEMWriter pem = new JcaPEMWriter(out)) {
pem.writeObject(data);
pem.flush();
return out.toString();
}
}
@SuppressWarnings("unchecked")
private static <T> T fromPem(String data) throws IOException {
try (PEMParser parser = new PEMParser(new StringReader(data))) {
return (T) parser.readObject();
}
}
private static KeyPair buildKeys() {
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
return keyGen.genKeyPair();
} catch (NoSuchAlgorithmException e) {
throw Throwables.propagate(e);
}
}
}
| 40.009901 | 91 | 0.623855 |
8da6a9dee00a0de3581c4afaccc4bf4abcf2b4bd | 2,812 | package net.minecraft.client.renderer.entity;
import com.mojang.blaze3d.matrix.MatrixStack;
import java.util.Random;
import net.minecraft.block.BlockRenderType;
import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BlockRendererDispatcher;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.client.renderer.texture.AtlasTexture;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.entity.item.FallingBlockEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class FallingBlockRenderer extends EntityRenderer<FallingBlockEntity> {
public FallingBlockRenderer(EntityRendererManager p_i46177_1_) {
super(p_i46177_1_);
this.shadowRadius = 0.5F;
}
public void render(FallingBlockEntity p_225623_1_, float p_225623_2_, float p_225623_3_, MatrixStack p_225623_4_, IRenderTypeBuffer p_225623_5_, int p_225623_6_) {
BlockState blockstate = p_225623_1_.getBlockState();
if (blockstate.getRenderShape() == BlockRenderType.MODEL) {
World world = p_225623_1_.getLevel();
if (blockstate != world.getBlockState(p_225623_1_.blockPosition()) && blockstate.getRenderShape() != BlockRenderType.INVISIBLE) {
p_225623_4_.pushPose();
BlockPos blockpos = new BlockPos(p_225623_1_.getX(), p_225623_1_.getBoundingBox().maxY, p_225623_1_.getZ());
p_225623_4_.translate(-0.5D, 0.0D, -0.5D);
BlockRendererDispatcher blockrendererdispatcher = Minecraft.getInstance().getBlockRenderer();
for (net.minecraft.client.renderer.RenderType type : net.minecraft.client.renderer.RenderType.chunkBufferLayers()) {
if (RenderTypeLookup.canRenderInLayer(blockstate, type)) {
net.minecraftforge.client.ForgeHooksClient.setRenderLayer(type);
blockrendererdispatcher.getModelRenderer().tesselateBlock(world, blockrendererdispatcher.getBlockModel(blockstate), blockstate, blockpos, p_225623_4_, p_225623_5_.getBuffer(type), false, new Random(), blockstate.getSeed(p_225623_1_.getStartPos()), OverlayTexture.NO_OVERLAY);
}
}
net.minecraftforge.client.ForgeHooksClient.setRenderLayer(null);
p_225623_4_.popPose();
super.render(p_225623_1_, p_225623_2_, p_225623_3_, p_225623_4_, p_225623_5_, p_225623_6_);
}
}
}
public ResourceLocation getTextureLocation(FallingBlockEntity p_110775_1_) {
return AtlasTexture.LOCATION_BLOCKS;
}
}
| 53.056604 | 293 | 0.758179 |
225c37c32b134bbeb207fa784cd30c464ce8974b | 5,216 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cpa.invariants.formula;
import java.util.Collections;
import java.util.Map;
import org.sosy_lab.cpachecker.util.states.MemoryLocation;
/**
* Instances of this class are parameterized invariants formula visitors used
* to push one constant summand of an addition into the formula of the other
* summand. This is possible as long as the operand can validly commute across
* the concerned formulae and is performed with the goal of consuming the
* operand in a formula, which means that the operand was added to another
* constant producing a new constant instead of a more complex formula.
*
* @param <T> the type of the constants used
*/
public class PushSummandVisitor<T> extends DefaultParameterizedNumeralFormulaVisitor<T, T, NumeralFormula<T>>{
private static final String SUMMAND_ALREADY_CONSUMED_MESSAGE = "Summand already consumed.";
/**
* The empty environment used for pushing the summand. No real environment
* is required because evaluations are exclusively done on the addition and
* negation of constants.
*/
private final Map<? extends MemoryLocation, ? extends NumeralFormula<T>> EMPTY_ENVIRONMENT =
Collections.emptyMap();
/**
* The evaluation visitor used to evaluate the addition and negation of
* constants.
*/
private final FormulaEvaluationVisitor<T> evaluationVisitor;
/**
* This flag indicates whether or not this visitor managed to get a summand
* consumed.
*/
private boolean consumed = false;
/**
* Creates a new push summand visitor with the given evaluation visitor. This
* visitor must not be reused after a summand has been consumed.
*
* @param pEvaluationVisitor the evaluation visitor used to evaluate the
* addition and negation of constants.
*/
public PushSummandVisitor(FormulaEvaluationVisitor<T> pEvaluationVisitor) {
this.evaluationVisitor = pEvaluationVisitor;
}
/**
* Checks if the visitor managed to get a summand consumed.
*
* @return <code>true</code> if the summand was consumed, <code>false</code>
* otherwise.
*/
public boolean isSummandConsumed() {
return consumed;
}
/**
* Throws an illegal state exception if the visitor already managed to get a
* summand consumed, otherwise it does nothing.
*
* @throws IllegalStateException if the visitor already managed to get a
* summand consumed, otherwise it does nothing.
*/
private void checkNotConsumed() throws IllegalStateException {
if (isSummandConsumed()) {
throw new IllegalStateException(SUMMAND_ALREADY_CONSUMED_MESSAGE);
}
}
/**
* @throws IllegalStateException if the visitor already managed to get a
* summand consumed, otherwise it does nothing.
*/
@Override
public NumeralFormula<T> visit(Add<T> pAdd, T pToPush) throws IllegalStateException {
checkNotConsumed();
NumeralFormula<T> candidateS1 = pAdd.getSummand1().accept(this, pToPush);
if (isSummandConsumed()) {
return InvariantsFormulaManager.INSTANCE.add(candidateS1, pAdd.getSummand2());
}
NumeralFormula<T> summand2 = pAdd.getSummand2().accept(this, pToPush);
return InvariantsFormulaManager.INSTANCE.add(pAdd.getSummand1(), summand2);
}
/**
* @throws IllegalStateException if the visitor already managed to get a
* summand consumed, otherwise it does nothing.
*/
@Override
public NumeralFormula<T> visit(Constant<T> pConstant, T pToPush) throws IllegalStateException {
checkNotConsumed();
InvariantsFormulaManager ifm = InvariantsFormulaManager.INSTANCE;
NumeralFormula<T> toPush = ifm.asConstant(pConstant.getBitVectorInfo(), pToPush);
NumeralFormula<T> sum = ifm.add(pConstant, toPush);
this.consumed = true;
T sumValue = sum.accept(evaluationVisitor, EMPTY_ENVIRONMENT);
return InvariantsFormulaManager.INSTANCE.asConstant(pConstant.getBitVectorInfo(), sumValue);
}
/**
* @throws IllegalStateException if the visitor already managed to get a
* summand consumed, otherwise it does nothing.
*/
@Override
protected NumeralFormula<T> visitDefault(NumeralFormula<T> pFormula, T pToPush) throws IllegalStateException {
checkNotConsumed();
InvariantsFormulaManager ifm = InvariantsFormulaManager.INSTANCE;
NumeralFormula<T> toPush = ifm.asConstant(pFormula.getBitVectorInfo(), pToPush);
return ifm.add(pFormula, toPush);
}
}
| 36.732394 | 112 | 0.738689 |
36e5c40b57ba3246c577df8e54c60b46be051ee0 | 963 |
package ExerciciosEstruturaCondicional;
import java.util.Scanner;
public class FormuladeBhaskara03 {
public static void main (String[] args) {
double a, b, c;
Scanner scan = new Scanner(System.in);
System.out.println("Informe o valor de A, B, C: ");
a = scan.nextDouble();
b = scan.nextDouble();
c = scan.nextDouble();
double delta = Math.pow(b, 2) - 4 * (a * c );
double raizdedelta = Math.sqrt(delta);
double x1 = (b *(-1) + raizdedelta) / (2 * a);
double x2 = (b *(-1) - raizdedelta) /(2 * a);
if (Double.isNaN(x1) || Double.isInfinite(x1) || Double.isNaN(x2) || Double.isInfinite(x2)){
System.out.println("Impossível calcular");
}
else {
System.out.printf("R1 = %,.5f\n", x1);
System.out.printf("R2 = %,.5f\n", x2);
}
}
}
| 26.75 | 100 | 0.498442 |
d34315ecaad412b2b4c437feaeda1a3e257199c1 | 21,092 | package p002b.p003c.p062h.p070f;
import android.support.p001v7.widget.RecyclerView.C0970a;
import android.support.v7.util.DiffUtil.Range;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/* renamed from: b.c.h.f.d */
/* compiled from: DiffUtil */
public class C1292d {
/* renamed from: a */
private static final Comparator<C1297e> f4103a = new C1291c();
/* renamed from: b.c.h.f.d$a */
/* compiled from: DiffUtil */
public static abstract class C1293a {
/* renamed from: a */
public abstract int mo6487a();
/* renamed from: a */
public abstract boolean mo6488a(int i, int i2);
/* renamed from: b */
public abstract int mo6489b();
/* renamed from: b */
public abstract boolean mo6490b(int i, int i2);
/* renamed from: c */
public Object mo9218c(int oldItemPosition, int newItemPosition) {
return null;
}
}
/* renamed from: b.c.h.f.d$b */
/* compiled from: DiffUtil */
public static class C1294b {
/* renamed from: a */
private final List<C1297e> f4104a;
/* renamed from: b */
private final int[] f4105b;
/* renamed from: c */
private final int[] f4106c;
/* renamed from: d */
private final C1293a f4107d;
/* renamed from: e */
private final int f4108e;
/* renamed from: f */
private final int f4109f;
/* renamed from: g */
private final boolean f4110g;
C1294b(C1293a callback, List<C1297e> snakes, int[] oldItemStatuses, int[] newItemStatuses, boolean detectMoves) {
this.f4104a = snakes;
this.f4105b = oldItemStatuses;
this.f4106c = newItemStatuses;
Arrays.fill(this.f4105b, 0);
Arrays.fill(this.f4106c, 0);
this.f4107d = callback;
this.f4108e = callback.mo6489b();
this.f4109f = callback.mo6487a();
this.f4110g = detectMoves;
m6029a();
m6033b();
}
/* renamed from: a */
private void m6029a() {
C1297e firstSnake = this.f4104a.isEmpty() ? null : (C1297e) this.f4104a.get(0);
if (firstSnake == null || firstSnake.f4118a != 0 || firstSnake.f4119b != 0) {
C1297e root = new C1297e();
root.f4118a = 0;
root.f4119b = 0;
root.f4121d = false;
root.f4120c = 0;
root.f4122e = false;
this.f4104a.add(0, root);
}
}
/* renamed from: b */
private void m6033b() {
int posOld = this.f4108e;
int posNew = this.f4109f;
for (int i = this.f4104a.size() - 1; i >= 0; i--) {
C1297e snake = (C1297e) this.f4104a.get(i);
int i2 = snake.f4118a;
int i3 = snake.f4120c;
int endX = i2 + i3;
int endY = snake.f4119b + i3;
if (this.f4110g) {
while (posOld > endX) {
m6030a(posOld, posNew, i);
posOld--;
}
while (posNew > endY) {
m6034b(posOld, posNew, i);
posNew--;
}
}
for (int j = 0; j < snake.f4120c; j++) {
int oldItemPos = snake.f4118a + j;
int newItemPos = snake.f4119b + j;
int changeFlag = this.f4107d.mo6488a(oldItemPos, newItemPos) ? 1 : 2;
this.f4105b[oldItemPos] = (newItemPos << 5) | changeFlag;
this.f4106c[newItemPos] = (oldItemPos << 5) | changeFlag;
}
posOld = snake.f4118a;
posNew = snake.f4119b;
}
}
/* renamed from: a */
private void m6030a(int x, int y, int snakeIndex) {
if (this.f4105b[x - 1] == 0) {
m6032a(x, y, snakeIndex, false);
}
}
/* renamed from: b */
private void m6034b(int x, int y, int snakeIndex) {
if (this.f4106c[y - 1] == 0) {
m6032a(x, y, snakeIndex, true);
}
}
/* renamed from: a */
private boolean m6032a(int x, int y, int snakeIndex, boolean removal) {
int curY;
int curX;
int myItemPos;
if (removal) {
myItemPos = y - 1;
curX = x;
curY = y - 1;
} else {
myItemPos = x - 1;
curX = x - 1;
curY = y;
}
for (int i = snakeIndex; i >= 0; i--) {
C1297e snake = (C1297e) this.f4104a.get(i);
int i2 = snake.f4118a;
int i3 = snake.f4120c;
int endX = i2 + i3;
int endY = snake.f4119b + i3;
int changeFlag = 8;
if (removal) {
for (int pos = curX - 1; pos >= endX; pos--) {
if (this.f4107d.mo6490b(pos, myItemPos)) {
if (!this.f4107d.mo6488a(pos, myItemPos)) {
changeFlag = 4;
}
this.f4106c[myItemPos] = (pos << 5) | 16;
this.f4105b[pos] = (myItemPos << 5) | changeFlag;
return true;
}
}
continue;
} else {
for (int pos2 = curY - 1; pos2 >= endY; pos2--) {
if (this.f4107d.mo6490b(myItemPos, pos2)) {
if (!this.f4107d.mo6488a(myItemPos, pos2)) {
changeFlag = 4;
}
this.f4105b[x - 1] = (pos2 << 5) | 16;
this.f4106c[pos2] = ((x - 1) << 5) | changeFlag;
return true;
}
}
continue;
}
curX = snake.f4118a;
curY = snake.f4119b;
}
return false;
}
/* renamed from: a */
public void mo9219a(C0970a adapter) {
mo9220a((C1298e) new C1289a(adapter));
}
/* renamed from: a */
public void mo9220a(C1298e updateCallback) {
C1290b batchingCallback;
int endY;
int snakeSize;
C1298e eVar = updateCallback;
if (eVar instanceof C1290b) {
C1298e eVar2 = eVar;
batchingCallback = (C1290b) eVar;
} else {
C1290b batchingCallback2 = new C1290b(eVar);
C1290b bVar = batchingCallback2;
batchingCallback = batchingCallback2;
}
ArrayList arrayList = new ArrayList();
int posOld = this.f4108e;
int posOld2 = posOld;
int posNew = this.f4109f;
for (int snakeIndex = this.f4104a.size() - 1; snakeIndex >= 0; snakeIndex--) {
C1297e snake = (C1297e) this.f4104a.get(snakeIndex);
int snakeSize2 = snake.f4120c;
int endX = snake.f4118a + snakeSize2;
int endY2 = snake.f4119b + snakeSize2;
if (endX < posOld2) {
endY = endY2;
m6035b(arrayList, batchingCallback, endX, posOld2 - endX, endX);
} else {
endY = endY2;
}
if (endY < posNew) {
int i = endX;
snakeSize = snakeSize2;
m6031a(arrayList, batchingCallback, endX, posNew - endY, endY);
} else {
snakeSize = snakeSize2;
}
for (int i2 = snakeSize - 1; i2 >= 0; i2--) {
int[] iArr = this.f4105b;
int i3 = snake.f4118a;
if ((iArr[i3 + i2] & 31) == 2) {
batchingCallback.mo9212a(i3 + i2, 1, this.f4107d.mo9218c(i3 + i2, snake.f4119b + i2));
}
}
posOld2 = snake.f4118a;
posNew = snake.f4119b;
}
batchingCallback.mo9215a();
}
/* renamed from: a */
private static C1295c m6028a(List<C1295c> updates, int pos, boolean removal) {
for (int i = updates.size() - 1; i >= 0; i--) {
C1295c update = (C1295c) updates.get(i);
if (update.f4111a == pos && update.f4113c == removal) {
updates.remove(i);
for (int j = i; j < updates.size(); j++) {
C1295c cVar = (C1295c) updates.get(j);
cVar.f4112b += removal ? 1 : -1;
}
return update;
}
}
return null;
}
/* renamed from: a */
private void m6031a(List<C1295c> postponedUpdates, C1298e updateCallback, int start, int count, int globalIndex) {
if (!this.f4110g) {
updateCallback.mo9211a(start, count);
return;
}
for (int i = count - 1; i >= 0; i--) {
int status = this.f4106c[globalIndex + i] & 31;
if (status == 0) {
updateCallback.mo9211a(start, 1);
for (C1295c update : postponedUpdates) {
update.f4112b++;
}
} else if (status == 4 || status == 8) {
int pos = this.f4106c[globalIndex + i] >> 5;
updateCallback.mo9214c(m6028a(postponedUpdates, pos, true).f4112b, start);
if (status == 4) {
updateCallback.mo9212a(start, 1, this.f4107d.mo9218c(pos, globalIndex + i));
}
} else if (status == 16) {
postponedUpdates.add(new C1295c(globalIndex + i, start, false));
} else {
StringBuilder sb = new StringBuilder();
sb.append("unknown flag for pos ");
sb.append(globalIndex + i);
sb.append(" ");
sb.append(Long.toBinaryString((long) status));
throw new IllegalStateException(sb.toString());
}
}
}
/* renamed from: b */
private void m6035b(List<C1295c> postponedUpdates, C1298e updateCallback, int start, int count, int globalIndex) {
if (!this.f4110g) {
updateCallback.mo9213b(start, count);
return;
}
for (int i = count - 1; i >= 0; i--) {
int status = this.f4105b[globalIndex + i] & 31;
if (status == 0) {
updateCallback.mo9213b(start + i, 1);
for (C1295c update : postponedUpdates) {
update.f4112b--;
}
} else if (status == 4 || status == 8) {
int pos = this.f4105b[globalIndex + i] >> 5;
C1295c update2 = m6028a(postponedUpdates, pos, false);
updateCallback.mo9214c(start + i, update2.f4112b - 1);
if (status == 4) {
updateCallback.mo9212a(update2.f4112b - 1, 1, this.f4107d.mo9218c(globalIndex + i, pos));
}
} else if (status == 16) {
postponedUpdates.add(new C1295c(globalIndex + i, start + i, true));
} else {
StringBuilder sb = new StringBuilder();
sb.append("unknown flag for pos ");
sb.append(globalIndex + i);
sb.append(" ");
sb.append(Long.toBinaryString((long) status));
throw new IllegalStateException(sb.toString());
}
}
}
}
/* renamed from: b.c.h.f.d$c */
/* compiled from: DiffUtil */
private static class C1295c {
/* renamed from: a */
int f4111a;
/* renamed from: b */
int f4112b;
/* renamed from: c */
boolean f4113c;
public C1295c(int posInOwnerList, int currentPos, boolean removal) {
this.f4111a = posInOwnerList;
this.f4112b = currentPos;
this.f4113c = removal;
}
}
/* renamed from: b.c.h.f.d$d */
/* compiled from: DiffUtil */
static class C1296d {
/* renamed from: a */
int f4114a;
/* renamed from: b */
int f4115b;
/* renamed from: c */
int f4116c;
/* renamed from: d */
int f4117d;
public C1296d() {
}
public C1296d(int oldListStart, int oldListEnd, int newListStart, int newListEnd) {
this.f4114a = oldListStart;
this.f4115b = oldListEnd;
this.f4116c = newListStart;
this.f4117d = newListEnd;
}
}
/* renamed from: b.c.h.f.d$e */
/* compiled from: DiffUtil */
static class C1297e {
/* renamed from: a */
int f4118a;
/* renamed from: b */
int f4119b;
/* renamed from: c */
int f4120c;
/* renamed from: d */
boolean f4121d;
/* renamed from: e */
boolean f4122e;
C1297e() {
}
}
/* renamed from: a */
public static C1294b m6020a(C1293a cb) {
return m6021a(cb, true);
}
/* renamed from: a */
public static C1294b m6021a(C1293a cb, boolean detectMoves) {
int oldSize = cb.mo6489b();
int newSize = cb.mo6487a();
ArrayList arrayList = new ArrayList();
List<Range> stack = new ArrayList<>();
stack.add(new C1296d(0, oldSize, 0, newSize));
int max = oldSize + newSize + Math.abs(oldSize - newSize);
int[] forward = new int[(max * 2)];
int[] backward = new int[(max * 2)];
ArrayList arrayList2 = new ArrayList();
while (!stack.isEmpty()) {
C1296d range = (C1296d) stack.remove(stack.size() - 1);
C1297e snake = m6022a(cb, range.f4114a, range.f4115b, range.f4116c, range.f4117d, forward, backward, max);
if (snake != null) {
if (snake.f4120c > 0) {
arrayList.add(snake);
}
snake.f4118a += range.f4114a;
snake.f4119b += range.f4116c;
C1296d left = arrayList2.isEmpty() ? new C1296d() : (C1296d) arrayList2.remove(arrayList2.size() - 1);
left.f4114a = range.f4114a;
left.f4116c = range.f4116c;
if (snake.f4122e) {
left.f4115b = snake.f4118a;
left.f4117d = snake.f4119b;
} else if (snake.f4121d) {
left.f4115b = snake.f4118a - 1;
left.f4117d = snake.f4119b;
} else {
left.f4115b = snake.f4118a;
left.f4117d = snake.f4119b - 1;
}
stack.add(left);
C1296d right = range;
if (!snake.f4122e) {
int i = snake.f4118a;
int i2 = snake.f4120c;
right.f4114a = i + i2;
right.f4116c = snake.f4119b + i2;
} else if (snake.f4121d) {
int i3 = snake.f4118a;
int i4 = snake.f4120c;
right.f4114a = i3 + i4 + 1;
right.f4116c = snake.f4119b + i4;
} else {
int i5 = snake.f4118a;
int i6 = snake.f4120c;
right.f4114a = i5 + i6;
right.f4116c = snake.f4119b + i6 + 1;
}
stack.add(right);
} else {
arrayList2.add(range);
}
}
Collections.sort(arrayList, f4103a);
ArrayList arrayList3 = arrayList2;
int[] iArr = backward;
int[] iArr2 = forward;
C1294b bVar = new C1294b(cb, arrayList, forward, backward, detectMoves);
return bVar;
}
/* renamed from: a */
private static C1297e m6022a(C1293a cb, int startOld, int endOld, int startNew, int endNew, int[] forward, int[] backward, int kOffset) {
boolean removal;
int x;
int oldSize;
boolean removal2;
int x2;
C1293a aVar = cb;
int[] iArr = forward;
int[] iArr2 = backward;
int oldSize2 = endOld - startOld;
int newSize = endNew - startNew;
if (endOld - startOld < 1) {
} else if (endNew - startNew < 1) {
int i = oldSize2;
} else {
int delta = oldSize2 - newSize;
int dLimit = ((oldSize2 + newSize) + 1) / 2;
Arrays.fill(iArr, (kOffset - dLimit) - 1, kOffset + dLimit + 1, 0);
Arrays.fill(iArr2, ((kOffset - dLimit) - 1) + delta, kOffset + dLimit + 1 + delta, oldSize2);
boolean checkInFwd = delta % 2 != 0;
for (int d = 0; d <= dLimit; d++) {
int k = -d;
while (k <= d) {
if (k == (-d) || (k != d && iArr[(kOffset + k) - 1] < iArr[kOffset + k + 1])) {
x2 = iArr[kOffset + k + 1];
removal2 = false;
} else {
x2 = iArr[(kOffset + k) - 1] + 1;
removal2 = true;
}
int y = x2 - k;
while (x2 < oldSize2 && y < newSize && aVar.mo6490b(startOld + x2, startNew + y)) {
x2++;
y++;
}
iArr[kOffset + k] = x2;
if (!checkInFwd || k < (delta - d) + 1 || k > (delta + d) - 1 || iArr[kOffset + k] < iArr2[kOffset + k]) {
k += 2;
} else {
C1297e outSnake = new C1297e();
outSnake.f4118a = iArr2[kOffset + k];
outSnake.f4119b = outSnake.f4118a - k;
outSnake.f4120c = iArr[kOffset + k] - iArr2[kOffset + k];
outSnake.f4121d = removal2;
outSnake.f4122e = false;
return outSnake;
}
}
int k2 = -d;
while (k2 <= d) {
int backwardK = k2 + delta;
if (backwardK == d + delta || (backwardK != (-d) + delta && iArr2[(kOffset + backwardK) - 1] < iArr2[kOffset + backwardK + 1])) {
x = iArr2[(kOffset + backwardK) - 1];
removal = false;
} else {
x = iArr2[(kOffset + backwardK) + 1] - 1;
removal = true;
}
int y2 = x - backwardK;
while (true) {
if (x > 0 && y2 > 0) {
oldSize = oldSize2;
if (!aVar.mo6490b((startOld + x) - 1, (startNew + y2) - 1)) {
break;
}
x--;
y2--;
oldSize2 = oldSize;
} else {
oldSize = oldSize2;
}
}
oldSize = oldSize2;
iArr2[kOffset + backwardK] = x;
if (checkInFwd || k2 + delta < (-d) || k2 + delta > d || iArr[kOffset + backwardK] < iArr2[kOffset + backwardK]) {
k2 += 2;
oldSize2 = oldSize;
} else {
C1297e outSnake2 = new C1297e();
outSnake2.f4118a = iArr2[kOffset + backwardK];
outSnake2.f4119b = outSnake2.f4118a - backwardK;
outSnake2.f4120c = iArr[kOffset + backwardK] - iArr2[kOffset + backwardK];
outSnake2.f4121d = removal;
outSnake2.f4122e = true;
return outSnake2;
}
}
}
throw new IllegalStateException("DiffUtil hit an unexpected case while trying to calculate the optimal path. Please make sure your data is not changing during the diff calculation.");
}
return null;
}
}
| 37.731664 | 195 | 0.440309 |
0cd3a43f60e9af61c7c3231b7ffcb75b594c538a | 2,852 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.proxy.backend.text.data;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.infra.binder.statement.SQLStatementContext;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
import org.apache.shardingsphere.proxy.backend.text.data.impl.BroadcastDatabaseBackendHandler;
import org.apache.shardingsphere.proxy.backend.text.data.impl.SchemaAssignedDatabaseBackendHandler;
import org.apache.shardingsphere.proxy.backend.text.data.impl.UnicastDatabaseBackendHandler;
import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dal.DALStatement;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dal.SetStatement;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.SelectStatement;
/**
* Database backend handler factory.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DatabaseBackendHandlerFactory {
/**
* New instance of database backend handler.
*
* @param sqlStatementContext SQL statement context
* @param sql SQL
* @param connectionSession connection session
* @return created instance
*/
public static DatabaseBackendHandler newInstance(final SQLStatementContext<?> sqlStatementContext, final String sql, final ConnectionSession connectionSession) {
SQLStatement sqlStatement = sqlStatementContext.getSqlStatement();
if (sqlStatement instanceof SetStatement) {
return new BroadcastDatabaseBackendHandler(sqlStatementContext, sql, connectionSession);
}
if (sqlStatement instanceof DALStatement || (sqlStatement instanceof SelectStatement && null == ((SelectStatement) sqlStatement).getFrom())) {
return new UnicastDatabaseBackendHandler(sqlStatementContext, sql, connectionSession);
}
return new SchemaAssignedDatabaseBackendHandler(sqlStatementContext, sql, connectionSession);
}
}
| 50.035088 | 165 | 0.782258 |
90d606b173926a76b70b6cd73499ac3f4425a579 | 29,575 | /*
* Copyright 2010-2020 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.bpmn.deployer;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.bpmn.constants.BpmnXMLConstants;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.ExtensionElement;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SubProcess;
import org.activiti.bpmn.model.UserTask;
import org.activiti.bpmn.model.ValuedDataObject;
import org.activiti.engine.DynamicBpmnConstants;
import org.activiti.engine.DynamicBpmnService;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.impl.cfg.IdGenerator;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.deploy.Deployer;
import org.activiti.engine.impl.persistence.entity.DeploymentEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntityManager;
import org.activiti.engine.impl.persistence.entity.ResourceEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BpmnDeployer implements Deployer {
private static final Logger log = LoggerFactory.getLogger(BpmnDeployer.class);
protected IdGenerator idGenerator;
protected ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory;
protected BpmnDeploymentHelper bpmnDeploymentHelper;
protected CachingAndArtifactsManager cachingAndArtifactsManager;
@Override
public void deploy(DeploymentEntity deployment,
Map<String, Object> deploymentSettings) {
log.debug("Processing deployment {}",
deployment.getName());
// The ParsedDeployment represents the deployment, the process definitions, and the BPMN
// resource, parse, and model associated with each process definition.
ParsedDeployment parsedDeployment = parsedDeploymentBuilderFactory
.getBuilderForDeploymentAndSettings(deployment,
deploymentSettings)
.build();
bpmnDeploymentHelper.verifyProcessDefinitionsDoNotShareKeys(parsedDeployment.getAllProcessDefinitions());
bpmnDeploymentHelper.copyDeploymentValuesToProcessDefinitions(
parsedDeployment.getDeployment(),
parsedDeployment.getAllProcessDefinitions());
bpmnDeploymentHelper.setResourceNamesOnProcessDefinitions(parsedDeployment);
// createAndPersistNewDiagramsIfNeeded(parsedDeployment);
setProcessDefinitionDiagramNames(parsedDeployment);
if (deployment.isNew()) {
Map<ProcessDefinitionEntity, ProcessDefinitionEntity> mapOfNewProcessDefinitionToPreviousVersion =
getPreviousVersionsOfProcessDefinitions(parsedDeployment);
setProcessDefinitionVersionsAndIds(parsedDeployment,
mapOfNewProcessDefinitionToPreviousVersion);
setProcessDefinitionAppVersion(parsedDeployment);
persistProcessDefinitionsAndAuthorizations(parsedDeployment);
updateTimersAndEvents(parsedDeployment,
mapOfNewProcessDefinitionToPreviousVersion);
dispatchProcessDefinitionEntityInitializedEvent(parsedDeployment);
} else {
makeProcessDefinitionsConsistentWithPersistedVersions(parsedDeployment);
}
cachingAndArtifactsManager.updateCachingAndArtifacts(parsedDeployment);
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
BpmnModel bpmnModel = parsedDeployment.getBpmnModelForProcessDefinition(processDefinition);
createLocalizationValues(processDefinition.getId(),
bpmnModel.getProcessById(processDefinition.getKey()));
}
}
//
// /**
// * Creates new diagrams for process definitions if the deployment is new, the process definition in
// * question supports it, and the engine is configured to make new diagrams.
// *
// * When this method creates a new diagram, it also persists it via the ResourceEntityManager
// * and adds it to the resources of the deployment.
// */
// protected void createAndPersistNewDiagramsIfNeeded(ParsedDeployment parsedDeployment) {
//
// final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
// final DeploymentEntity deploymentEntity = parsedDeployment.getDeployment();
//
// final ResourceEntityManager resourceEntityManager = processEngineConfiguration.getResourceEntityManager();
//
// for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
// if (processDefinitionDiagramHelper.shouldCreateDiagram(processDefinition, deploymentEntity)) {
// ResourceEntity resource = processDefinitionDiagramHelper.createDiagramForProcessDefinition(
// processDefinition, parsedDeployment.getBpmnParseForProcessDefinition(processDefinition));
// if (resource != null) {
// resourceEntityManager.insert(resource, false);
// deploymentEntity.addResource(resource); // now we'll find it if we look for the diagram name later.
// }
// }
// }
// }
/**
* Updates all the process definition entities to have the correct diagram resource name. Must
* be called after createAndPersistNewDiagramsAsNeeded to ensure that any newly-created diagrams
* already have their resources attached to the deployment.
*/
protected void setProcessDefinitionDiagramNames(ParsedDeployment parsedDeployment) {
Map<String, ResourceEntity> resources = parsedDeployment.getDeployment().getResources();
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
String diagramResourceName = ResourceNameUtil.getProcessDiagramResourceNameFromDeployment(processDefinition,
resources);
processDefinition.setDiagramResourceName(diagramResourceName);
}
}
/**
* Constructs a map from new ProcessDefinitionEntities to the previous version by key and tenant.
* If no previous version exists, no map entry is created.
*/
protected Map<ProcessDefinitionEntity, ProcessDefinitionEntity> getPreviousVersionsOfProcessDefinitions(
ParsedDeployment parsedDeployment) {
Map<ProcessDefinitionEntity, ProcessDefinitionEntity> result = new LinkedHashMap<ProcessDefinitionEntity, ProcessDefinitionEntity>();
for (ProcessDefinitionEntity newDefinition : parsedDeployment.getAllProcessDefinitions()) {
ProcessDefinitionEntity existingDefinition = bpmnDeploymentHelper.getMostRecentVersionOfProcessDefinition(newDefinition);
if (existingDefinition != null) {
result.put(newDefinition,
existingDefinition);
}
}
return result;
}
/**
* Sets the version on each process definition entity, and the identifier. If the map contains
* an older version for a process definition, then the version is set to that older entity's
* version plus one; otherwise it is set to 1. Also dispatches an ENTITY_CREATED event.
*/
protected void setProcessDefinitionVersionsAndIds(ParsedDeployment parsedDeployment,
Map<ProcessDefinitionEntity, ProcessDefinitionEntity> mapNewToOldProcessDefinitions) {
CommandContext commandContext = Context.getCommandContext();
if(parsedDeployment.getDeployment().getProjectReleaseVersion() != null){
Integer version = parsedDeployment.getDeployment().getVersion();
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
processDefinition.setVersion(version);
processDefinition.setId(getIdForNewProcessDefinition(processDefinition));
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED,
processDefinition));
}
}
}else{
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
int version = 1;
ProcessDefinitionEntity latest = mapNewToOldProcessDefinitions.get(processDefinition);
if (latest != null) {
version = latest.getVersion() + 1;
}
processDefinition.setVersion(version);
processDefinition.setId(getIdForNewProcessDefinition(processDefinition));
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED,
processDefinition));
}
}
}
}
/**
* Saves each process definition. It is assumed that the deployment is new, the definitions
* have never been saved before, and that they have all their values properly set up.
*/
protected void persistProcessDefinitionsAndAuthorizations(ParsedDeployment parsedDeployment) {
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntityManager processDefinitionManager = commandContext.getProcessDefinitionEntityManager();
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
processDefinitionManager.insert(processDefinition,
false);
bpmnDeploymentHelper.addAuthorizationsForNewProcessDefinition(parsedDeployment.getProcessModelForProcessDefinition(processDefinition),
processDefinition);
}
}
protected void updateTimersAndEvents(ParsedDeployment parsedDeployment,
Map<ProcessDefinitionEntity, ProcessDefinitionEntity> mapNewToOldProcessDefinitions) {
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
bpmnDeploymentHelper.updateTimersAndEvents(processDefinition,
mapNewToOldProcessDefinitions.get(processDefinition),
parsedDeployment);
}
}
protected void dispatchProcessDefinitionEntityInitializedEvent(ParsedDeployment parsedDeployment) {
CommandContext commandContext = Context.getCommandContext();
for (ProcessDefinitionEntity processDefinitionEntity : parsedDeployment.getAllProcessDefinitions()) {
log.info("Process deployed: {id: " + processDefinitionEntity.getId() +
", key: " + processDefinitionEntity.getKey() + ", name: " + processDefinitionEntity.getName() +" }");
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED,
processDefinitionEntity));
}
}
}
/**
* Returns the ID to use for a new process definition; subclasses may override this to provide
* their own identification scheme.
* <p>
* Process definition ids NEED to be unique accross the whole engine!
*/
protected String getIdForNewProcessDefinition(ProcessDefinitionEntity processDefinition) {
String nextId = idGenerator.getNextId();
String result = processDefinition.getKey() + ":" + processDefinition.getVersion() + ":" + nextId; // ACT-505
// ACT-115: maximum id length is 64 characters
if (result.length() > 64) {
result = nextId;
}
return result;
}
/**
* Loads the persisted version of each process definition and set values on the in-memory
* version to be consistent.
*/
protected void makeProcessDefinitionsConsistentWithPersistedVersions(ParsedDeployment parsedDeployment) {
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
ProcessDefinitionEntity persistedProcessDefinition =
bpmnDeploymentHelper.getPersistedInstanceOfProcessDefinition(processDefinition);
if (persistedProcessDefinition != null) {
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
processDefinition.setAppVersion(persistedProcessDefinition.getAppVersion());
processDefinition.setSuspensionState(persistedProcessDefinition.getSuspensionState());
}
}
}
protected void createLocalizationValues(String processDefinitionId,
Process process) {
if (process == null) {
return;
}
CommandContext commandContext = Context.getCommandContext();
DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration().getDynamicBpmnService();
ObjectNode infoNode = dynamicBpmnService.getProcessDefinitionInfo(processDefinitionId);
boolean localizationValuesChanged = false;
List<ExtensionElement> localizationElements = process.getExtensionElements().get("localization");
if (localizationElements != null) {
for (ExtensionElement localizationElement : localizationElements) {
if (BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix())) {
String locale = localizationElement.getAttributeValue(null,
"locale");
String name = localizationElement.getAttributeValue(null,
"name");
String documentation = null;
List<ExtensionElement> documentationElements = localizationElement.getChildElements().get("documentation");
if (documentationElements != null) {
for (ExtensionElement documentationElement : documentationElements) {
documentation = StringUtils.trimToNull(documentationElement.getElementText());
break;
}
}
String processId = process.getId();
if (!isEqualToCurrentLocalizationValue(locale,
processId,
"name",
name,
infoNode)) {
dynamicBpmnService.changeLocalizationName(locale,
processId,
name,
infoNode);
localizationValuesChanged = true;
}
if (documentation != null && !isEqualToCurrentLocalizationValue(locale,
processId,
"description",
documentation,
infoNode)) {
dynamicBpmnService.changeLocalizationDescription(locale,
processId,
documentation,
infoNode);
localizationValuesChanged = true;
}
break;
}
}
}
boolean isFlowElementLocalizationChanged = localizeFlowElements(process.getFlowElements(),
infoNode);
boolean isDataObjectLocalizationChanged = localizeDataObjectElements(process.getDataObjects(),
infoNode);
if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
localizationValuesChanged = true;
}
if (localizationValuesChanged) {
dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId,
infoNode);
}
}
protected boolean localizeFlowElements(Collection<FlowElement> flowElements,
ObjectNode infoNode) {
boolean localizationValuesChanged = false;
if (flowElements == null) {
return localizationValuesChanged;
}
CommandContext commandContext = Context.getCommandContext();
DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration().getDynamicBpmnService();
for (FlowElement flowElement : flowElements) {
if (flowElement instanceof UserTask || flowElement instanceof SubProcess) {
List<ExtensionElement> localizationElements = flowElement.getExtensionElements().get("localization");
if (localizationElements != null) {
for (ExtensionElement localizationElement : localizationElements) {
if (BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix())) {
String locale = localizationElement.getAttributeValue(null,
"locale");
String name = localizationElement.getAttributeValue(null,
"name");
String documentation = null;
List<ExtensionElement> documentationElements = localizationElement.getChildElements().get("documentation");
if (documentationElements != null) {
for (ExtensionElement documentationElement : documentationElements) {
documentation = StringUtils.trimToNull(documentationElement.getElementText());
break;
}
}
String flowElementId = flowElement.getId();
if (isEqualToCurrentLocalizationValue(locale,
flowElementId,
"name",
name,
infoNode) == false) {
dynamicBpmnService.changeLocalizationName(locale,
flowElementId,
name,
infoNode);
localizationValuesChanged = true;
}
if (documentation != null && isEqualToCurrentLocalizationValue(locale,
flowElementId,
"description",
documentation,
infoNode) == false) {
dynamicBpmnService.changeLocalizationDescription(locale,
flowElementId,
documentation,
infoNode);
localizationValuesChanged = true;
}
break;
}
}
}
if (flowElement instanceof SubProcess) {
SubProcess subprocess = (SubProcess) flowElement;
boolean isFlowElementLocalizationChanged = localizeFlowElements(subprocess.getFlowElements(),
infoNode);
boolean isDataObjectLocalizationChanged = localizeDataObjectElements(subprocess.getDataObjects(),
infoNode);
if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
localizationValuesChanged = true;
}
}
}
}
return localizationValuesChanged;
}
protected boolean isEqualToCurrentLocalizationValue(String language,
String id,
String propertyName,
String propertyValue,
ObjectNode infoNode) {
boolean isEqual = false;
JsonNode localizationNode = infoNode.path("localization").path(language).path(id).path(propertyName);
if (!localizationNode.isMissingNode() && !localizationNode.isNull() && localizationNode.asText().equals(propertyValue)) {
isEqual = true;
}
return isEqual;
}
private void setProcessDefinitionAppVersion(ParsedDeployment parsedDeployment) {
if (parsedDeployment.getDeployment().getProjectReleaseVersion() != null) {
Integer version = parsedDeployment.getDeployment().getVersion();
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
processDefinition.setAppVersion(version);
}
}
}
protected boolean localizeDataObjectElements(List<ValuedDataObject> dataObjects,
ObjectNode infoNode) {
boolean localizationValuesChanged = false;
CommandContext commandContext = Context.getCommandContext();
DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration().getDynamicBpmnService();
for (ValuedDataObject dataObject : dataObjects) {
List<ExtensionElement> localizationElements = dataObject.getExtensionElements().get("localization");
if (localizationElements != null) {
for (ExtensionElement localizationElement : localizationElements) {
if (BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix())) {
String locale = localizationElement.getAttributeValue(null,
"locale");
String name = localizationElement.getAttributeValue(null,
"name");
String documentation = null;
List<ExtensionElement> documentationElements = localizationElement.getChildElements().get("documentation");
if (documentationElements != null) {
for (ExtensionElement documentationElement : documentationElements) {
documentation = StringUtils.trimToNull(documentationElement.getElementText());
break;
}
}
if (name != null && isEqualToCurrentLocalizationValue(locale,
dataObject.getId(),
DynamicBpmnConstants.LOCALIZATION_NAME,
name,
infoNode) == false) {
dynamicBpmnService.changeLocalizationName(locale,
dataObject.getId(),
name,
infoNode);
localizationValuesChanged = true;
}
if (documentation != null && isEqualToCurrentLocalizationValue(locale,
dataObject.getId(),
DynamicBpmnConstants.LOCALIZATION_DESCRIPTION,
documentation,
infoNode) == false) {
dynamicBpmnService.changeLocalizationDescription(locale,
dataObject.getId(),
documentation,
infoNode);
localizationValuesChanged = true;
}
}
}
}
}
return localizationValuesChanged;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() {
return parsedDeploymentBuilderFactory;
}
public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) {
this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory;
}
public BpmnDeploymentHelper getBpmnDeploymentHelper() {
return bpmnDeploymentHelper;
}
public void setBpmnDeploymentHelper(BpmnDeploymentHelper bpmnDeploymentHelper) {
this.bpmnDeploymentHelper = bpmnDeploymentHelper;
}
public CachingAndArtifactsManager getCachingAndArtifcatsManager() {
return cachingAndArtifactsManager;
}
public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) {
this.cachingAndArtifactsManager = manager;
}
}
| 54.266055 | 174 | 0.56825 |
a7fd13d56eba357cb5744a0f03c4d026b2975d47 | 142 | package com.example.orders.services;
import com.example.orders.models.Order;
public interface OrderService
{
Order save(Order order);
}
| 15.777778 | 39 | 0.774648 |
54448e79312c420830fbb3f52bafaa14ecbff188 | 11,196 | package io.reflectoring.coderadar.rest.query;
import io.reflectoring.coderadar.analyzer.port.driver.StartAnalyzingCommand;
import io.reflectoring.coderadar.projectadministration.domain.InclusionType;
import io.reflectoring.coderadar.projectadministration.port.driver.analyzerconfig.create.CreateAnalyzerConfigurationCommand;
import io.reflectoring.coderadar.projectadministration.port.driver.filepattern.create.CreateFilePatternCommand;
import io.reflectoring.coderadar.projectadministration.port.driver.module.create.CreateModuleCommand;
import io.reflectoring.coderadar.projectadministration.port.driver.project.create.CreateProjectCommand;
import io.reflectoring.coderadar.query.domain.MetricTree;
import io.reflectoring.coderadar.query.domain.MetricValueForCommit;
import io.reflectoring.coderadar.query.domain.MetricsTreeNodeType;
import io.reflectoring.coderadar.query.port.driver.GetMetricsForCommitCommand;
import io.reflectoring.coderadar.rest.ControllerTestTemplate;
import io.reflectoring.coderadar.rest.ErrorMessageResponse;
import io.reflectoring.coderadar.rest.IdResponse;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MvcResult;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Objects;
import static io.reflectoring.coderadar.rest.JsonHelper.fromJson;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class GetMetricsForAllFilesInCommitControllerTest extends ControllerTestTemplate {
private Long projectId;
@BeforeEach
void setUp() throws Exception {
URL testRepoURL = this.getClass().getClassLoader().getResource("test-repository");
CreateProjectCommand command1 =
new CreateProjectCommand(
"test-project", "username", "password", Objects.requireNonNull(testRepoURL).toString(), false, null, null);
MvcResult result = mvc().perform(post("/projects").contentType(MediaType.APPLICATION_JSON).content(toJson(command1))).andReturn();
projectId = fromJson(result.getResponse().getContentAsString(), IdResponse.class).getId();
CreateFilePatternCommand command2 =
new CreateFilePatternCommand("**/*.java", InclusionType.INCLUDE);
mvc()
.perform(
post("/projects/" + projectId + "/filePatterns")
.content(toJson(command2))
.contentType(MediaType.APPLICATION_JSON));
CreateAnalyzerConfigurationCommand command3 = new CreateAnalyzerConfigurationCommand("io.reflectoring.coderadar.analyzer.loc.LocAnalyzerPlugin", true);
mvc().perform(post("/projects/" + projectId + "/analyzers").content(toJson(command3)).contentType(MediaType.APPLICATION_JSON));
StartAnalyzingCommand command4 = new StartAnalyzingCommand(new Date(), true);
mvc().perform(post("/projects/" + projectId + "/analyze").content(toJson(command4)).contentType(MediaType.APPLICATION_JSON));
}
@Test
void returnsMetricTree() throws Exception {
GetMetricsForCommitCommand command = new GetMetricsForCommitCommand();
command.setMetrics(Arrays.asList("coderadar:size:loc:java", "coderadar:size:sloc:java", "coderadar:size:cloc:java", "coderadar:size:eloc:java"));
command.setCommit("d3272b3793bc4b2bc36a1a3a7c8293fcf8fe27df");
MvcResult result = mvc().perform(get("/projects/" + projectId + "/metricvalues/tree")
.contentType(MediaType.APPLICATION_JSON).content(toJson(command)))
.andReturn();
MetricTree metricTree = fromJson(result.getResponse().getContentAsString(), MetricTree.class);
metricTree.getMetrics().sort(Comparator.comparing(MetricValueForCommit::getMetricName));
Assertions.assertEquals("root", metricTree.getName());
Assertions.assertEquals(MetricsTreeNodeType.MODULE, metricTree.getType());
Assertions.assertEquals(4, metricTree.getMetrics().size());
Assertions.assertEquals(0L, metricTree.getMetrics().get(0).getValue().longValue());
Assertions.assertEquals(8L, metricTree.getMetrics().get(1).getValue().longValue());
Assertions.assertEquals(18L, metricTree.getMetrics().get(2).getValue().longValue());
Assertions.assertEquals(15L, metricTree.getMetrics().get(3).getValue().longValue());
MetricTree firstChild = metricTree.getChildren().get(0);
firstChild.getMetrics().sort(Comparator.comparing(MetricValueForCommit::getMetricName));
Assertions.assertEquals("GetMetricsForCommitCommand.java", firstChild.getName());
Assertions.assertEquals(MetricsTreeNodeType.FILE, firstChild.getType());
Assertions.assertTrue(firstChild.getChildren().isEmpty());
Assertions.assertEquals(0L, firstChild.getMetrics().get(0).getValue().longValue());
Assertions.assertEquals(7L, firstChild.getMetrics().get(1).getValue().longValue());
Assertions.assertEquals(17L, firstChild.getMetrics().get(2).getValue().longValue());
Assertions.assertEquals(14L, firstChild.getMetrics().get(3).getValue().longValue());
MetricTree secondChild = metricTree.getChildren().get(1);
secondChild.getMetrics().sort(Comparator.comparing(MetricValueForCommit::getMetricName));
Assertions.assertEquals("testModule1/NewRandomFile.java", secondChild.getName());
Assertions.assertEquals(MetricsTreeNodeType.FILE, secondChild.getType());
Assertions.assertTrue(secondChild.getChildren().isEmpty());
Assertions.assertEquals(0L, secondChild.getMetrics().get(0).getValue().longValue());
Assertions.assertEquals(1L, secondChild.getMetrics().get(1).getValue().longValue());
Assertions.assertEquals(1L, secondChild.getMetrics().get(2).getValue().longValue());
Assertions.assertEquals(1L, secondChild.getMetrics().get(3).getValue().longValue());
}
@Test
@DirtiesContext
void returnsMetricTreeWithModule() throws Exception {
CreateModuleCommand createModuleCommand = new CreateModuleCommand();
createModuleCommand.setPath("testModule1");
mvc().perform(post("/projects/" + projectId + "/modules")
.contentType(MediaType.APPLICATION_JSON).content(toJson(createModuleCommand)));
GetMetricsForCommitCommand command = new GetMetricsForCommitCommand();
command.setMetrics(Arrays.asList("coderadar:size:loc:java", "coderadar:size:sloc:java", "coderadar:size:cloc:java", "coderadar:size:eloc:java"));
command.setCommit("d3272b3793bc4b2bc36a1a3a7c8293fcf8fe27df");
MvcResult result = mvc().perform(get("/projects/" + projectId + "/metricvalues/tree")
.contentType(MediaType.APPLICATION_JSON).content(toJson(command)))
.andReturn();
MetricTree metricTree = fromJson(result.getResponse().getContentAsString(), MetricTree.class);
metricTree.getMetrics().sort(Comparator.comparing(MetricValueForCommit::getMetricName));
Assertions.assertEquals("root", metricTree.getName());
Assertions.assertEquals(MetricsTreeNodeType.MODULE, metricTree.getType());
Assertions.assertEquals(4, metricTree.getMetrics().size());
Assertions.assertEquals(0L, metricTree.getMetrics().get(0).getValue().longValue());
Assertions.assertEquals(8L, metricTree.getMetrics().get(1).getValue().longValue());
Assertions.assertEquals(18L, metricTree.getMetrics().get(2).getValue().longValue());
Assertions.assertEquals(15L, metricTree.getMetrics().get(3).getValue().longValue());
MetricTree firstChild = metricTree.getChildren().get(0);
firstChild.getMetrics().sort(Comparator.comparing(MetricValueForCommit::getMetricName));
Assertions.assertEquals("GetMetricsForCommitCommand.java", firstChild.getName());
Assertions.assertEquals(MetricsTreeNodeType.FILE, firstChild.getType());
Assertions.assertTrue(firstChild.getChildren().isEmpty());
Assertions.assertEquals(0L, firstChild.getMetrics().get(0).getValue().longValue());
Assertions.assertEquals(7L, firstChild.getMetrics().get(1).getValue().longValue());
Assertions.assertEquals(17L, firstChild.getMetrics().get(2).getValue().longValue());
Assertions.assertEquals(14L, firstChild.getMetrics().get(3).getValue().longValue());
MetricTree secondChild = metricTree.getChildren().get(1);
secondChild.getMetrics().sort(Comparator.comparing(MetricValueForCommit::getMetricName));
Assertions.assertEquals("testModule1/", secondChild.getName());
Assertions.assertEquals(MetricsTreeNodeType.MODULE, secondChild.getType());
Assertions.assertFalse(secondChild.getChildren().isEmpty());
Assertions.assertEquals(0L, secondChild.getMetrics().get(0).getValue().longValue());
Assertions.assertEquals(1L, secondChild.getMetrics().get(1).getValue().longValue());
Assertions.assertEquals(1L, secondChild.getMetrics().get(2).getValue().longValue());
Assertions.assertEquals(1L, secondChild.getMetrics().get(3).getValue().longValue());
MetricTree thirdChild = secondChild.getChildren().get(0);
thirdChild.getMetrics().sort(Comparator.comparing(MetricValueForCommit::getMetricName));
Assertions.assertEquals("testModule1/NewRandomFile.java", thirdChild.getName());
Assertions.assertEquals(MetricsTreeNodeType.FILE, thirdChild.getType());
Assertions.assertTrue(thirdChild.getChildren().isEmpty());
Assertions.assertEquals(0L, thirdChild.getMetrics().get(0).getValue().longValue());
Assertions.assertEquals(1L, thirdChild.getMetrics().get(1).getValue().longValue());
Assertions.assertEquals(1L, thirdChild.getMetrics().get(2).getValue().longValue());
Assertions.assertEquals(1L, thirdChild.getMetrics().get(3).getValue().longValue());
}
@Test
void returnsErrorWhenProjectWithIdDoesNotExist() throws Exception {
GetMetricsForCommitCommand command = new GetMetricsForCommitCommand();
command.setMetrics(Arrays.asList("coderadar:size:loc:java", "coderadar:size:sloc:java", "coderadar:size:cloc:java", "coderadar:size:eloc:java"));
command.setCommit("d3272b3793bc4b2bc36a1a3a7c8293fcf8fe27df");
MvcResult result = mvc().perform(get("/projects/1234/metricvalues/tree")
.contentType(MediaType.APPLICATION_JSON).content(toJson(command)))
.andExpect(status().isNotFound())
.andReturn();
ErrorMessageResponse response = fromJson(result.getResponse().getContentAsString(), ErrorMessageResponse.class);
Assertions.assertEquals("Project with id 1234 not found.", response.getErrorMessage());
}
}
| 58.3125 | 159 | 0.734727 |
e368893190170f82d38c582ba27c12dc343040d0 | 9,084 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* 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.drools.workbench.services.verifier.webworker.client;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwtmockito.GwtMock;
import org.drools.workbench.models.datamodel.oracle.DataType;
import org.drools.workbench.models.guided.dtable.shared.model.ActionSetFieldCol52;
import org.drools.workbench.models.guided.dtable.shared.model.BRLConditionColumn;
import org.drools.workbench.models.guided.dtable.shared.model.DTCellValue52;
import org.drools.workbench.models.guided.dtable.shared.model.GuidedDecisionTable52;
import org.drools.workbench.services.verifier.api.client.resources.i18n.AnalysisConstants;
import org.drools.workbench.services.verifier.core.main.Analyzer;
import org.drools.workbench.services.verifier.plugin.client.Coordinate;
import org.drools.workbench.services.verifier.plugin.client.builders.BuildException;
import org.drools.workbench.services.verifier.plugin.client.builders.ModelMetaDataEnhancer;
import org.drools.workbench.services.verifier.webworker.client.testutil.AnalyzerProvider;
import org.junit.Before;
public abstract class AnalyzerUpdateTestBase {
protected AnalyzerProvider analyzerProvider;
protected GuidedDecisionTable52 table52;
protected Analyzer analyzer;
@GwtMock
AnalysisConstants analysisConstants;
@GwtMock
DateTimeFormat dateTimeFormat;
private DTableUpdateManager updateManager;
@Before
public void setUp() throws
Exception {
analyzerProvider = new AnalyzerProvider();
}
protected void fireUpAnalyzer() {
if ( analyzer == null ) {
analyzer = analyzerProvider.makeAnalyser( table52 );
updateManager = analyzerProvider.getUpdateManager( table52,
analyzer );
}
analyzer.resetChecks();
analyzer.analyze();
}
protected void removeRow( final int rowIndex ) {
table52.getData()
.remove( rowIndex );
analyzer.removeRule( rowIndex );
}
protected void removeActionColumn( final int columnDataIndex,
final int columnActionIndex ) {
table52.getActionCols()
.remove( columnActionIndex );
for ( final List<DTCellValue52> row : table52.getData() ) {
row.remove( columnDataIndex );
}
updateManager.deleteColumns( columnDataIndex,
1 );
}
public ValueSetter setCoordinate() {
return new ValueSetter();
}
protected void setValue( final int rowIndex,
final int columnIndex,
final Number value ) {
DTCellValue52 dtCellValue52 = table52.getData()
.get( rowIndex )
.get( columnIndex );
dtCellValue52
.setNumericValue( value );
try {
updateManager.update( table52,
getUpdates( rowIndex,
columnIndex ) );
} catch ( UpdateException e ) {
e.printStackTrace();
}
}
protected void setValue( final int rowIndex,
final int columnIndex,
final String value ) {
table52.getData()
.get( rowIndex )
.get( columnIndex )
.setStringValue( value );
try {
updateManager.update( table52,
getUpdates( rowIndex,
columnIndex ) );
} catch ( UpdateException e ) {
e.printStackTrace();
}
}
protected void appendActionColumn( final int columnNumber,
final ActionSetFieldCol52 actionSetField,
final Comparable... cellValues ) throws
BuildException {
table52.getActionCols()
.add( actionSetField );
for ( int i = 0; i < cellValues.length; i++ ) {
table52.getData()
.get( i )
.add( new DTCellValue52( cellValues[i] ) );
}
updateManager.newColumn( table52,
new ModelMetaDataEnhancer( table52 ).getHeaderMetaData(),
analyzerProvider.getFactTypes(),
columnNumber );
}
protected void insertConditionColumn( final int columnNumber,
final BRLConditionColumn brlConditionColumn,
final Comparable... cellValues ) throws
BuildException {
table52.getConditions()
.add( brlConditionColumn );
for ( int i = 0; i < cellValues.length; i++ ) {
table52.getData()
.get( i )
.add( new DTCellValue52( cellValues[i] ) );
}
updateManager.newColumn( table52,
new ModelMetaDataEnhancer( table52 ).getHeaderMetaData(),
analyzerProvider.getFactTypes(),
columnNumber );
}
protected void insertRow( final int rowNumber,
final DataType.DataTypes... dataTypes ) throws
BuildException {
table52.getData()
.add( rowNumber,
newRow( dataTypes ) );
updateManager.makeRule( table52,
new ModelMetaDataEnhancer( table52 ).getHeaderMetaData(),
analyzerProvider.getFactTypes(),
rowNumber );
}
protected void appendRow( final DataType.DataTypes... dataTypes ) throws
BuildException {
final ArrayList<DTCellValue52> row = newRow( dataTypes );
table52.getData()
.add( row );
updateManager.makeRule( table52,
new ModelMetaDataEnhancer( table52 ).getHeaderMetaData(),
analyzerProvider.getFactTypes(),
table52.getData()
.size() - 1 );
}
private ArrayList<DTCellValue52> newRow( final DataType.DataTypes[] dataTypes ) {
final ArrayList<DTCellValue52> row = new ArrayList<>();
// Row number
row.add( new DTCellValue52() );
// Explanation
row.add( new DTCellValue52() );
for ( final DataType.DataTypes dataType : dataTypes ) {
row.add( new DTCellValue52( dataType,
true ) );
}
return row;
}
protected List<Coordinate> getUpdates( final int x,
final int y ) {
final List<Coordinate> updates = new ArrayList<>();
updates.add( new Coordinate( x,
y ) );
return updates;
}
public class ValueSetter {
public ColumnValueSetter row( final int row ) {
return new ColumnValueSetter( row );
}
public class ColumnValueSetter {
private int row;
public ColumnValueSetter( final int row ) {
this.row = row;
}
public CellValueSetter column( final int column ) {
return new CellValueSetter( column );
}
public class CellValueSetter {
private int column;
public CellValueSetter( final int column ) {
this.column = column;
}
public void toValue( final String value ) {
setValue( row,
column,
value );
}
public void toValue( final Number value ) {
setValue( row,
column,
value );
}
}
}
}
}
| 36.191235 | 91 | 0.534346 |
102e360dc29f6f824b14a4abb506efecb0678fe2 | 1,120 | package org.health.service;
import java.util.*;
import org.health.entity.*;
public interface MedicalCareService {
/**
* method required for adding medical care
*
* @param medicalCare - medical care for adding
* @return created medical care
*/
MedicalCare addMedicalCare(MedicalCare medicalCare);
/**
* method required for updating medical care
*
* @param medicalCare - medical care for update
* @return updated medical care
*/
MedicalCare updateMedicalCare(MedicalCare medicalCare);
/**
* method required for getting medical care by id
*
* @param id - id medical care got getting
* @return medical care by id
*/
MedicalCare getMedicalCare(long id);
/**
* method required for getting all medical cares
*
* @return all medical cares
*/
List<MedicalCare> getAllMedicalCares();
/**
* method required for deletion medical care by id
*
* @param id - id medical care got delete
* @return deleted medical care by id
*/
MedicalCare deleteMedicalCare(long id);
}
| 23.829787 | 59 | 0.645536 |
4deef01a9c5f2c467c1dbaedb901f579a3772dc0 | 5,708 |
package com.prowidesoftware.swift.model.mx.dic;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* The Net Report message is sent to a participant by a central system to provide details of the of the bi-lateral payment obligations, calculated by the central system per currency.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "NetReportV01", propOrder = {
"netRptData",
"netSvcPtcptId",
"netSvcCtrPtyId",
"netOblgtn",
"splmtryData"
})
public class NetReportV01 {
@XmlElement(name = "NetRptData", required = true)
protected NetReportData1 netRptData;
@XmlElement(name = "NetSvcPtcptId", required = true)
protected PartyIdentification73Choice netSvcPtcptId;
@XmlElement(name = "NetSvcCtrPtyId")
protected PartyIdentification73Choice netSvcCtrPtyId;
@XmlElement(name = "NetOblgtn", required = true)
protected List<NetObligation1> netOblgtn;
@XmlElement(name = "SplmtryData")
protected List<SupplementaryData1> splmtryData;
/**
* Gets the value of the netRptData property.
*
* @return
* possible object is
* {@link NetReportData1 }
*
*/
public NetReportData1 getNetRptData() {
return netRptData;
}
/**
* Sets the value of the netRptData property.
*
* @param value
* allowed object is
* {@link NetReportData1 }
*
*/
public NetReportV01 setNetRptData(NetReportData1 value) {
this.netRptData = value;
return this;
}
/**
* Gets the value of the netSvcPtcptId property.
*
* @return
* possible object is
* {@link PartyIdentification73Choice }
*
*/
public PartyIdentification73Choice getNetSvcPtcptId() {
return netSvcPtcptId;
}
/**
* Sets the value of the netSvcPtcptId property.
*
* @param value
* allowed object is
* {@link PartyIdentification73Choice }
*
*/
public NetReportV01 setNetSvcPtcptId(PartyIdentification73Choice value) {
this.netSvcPtcptId = value;
return this;
}
/**
* Gets the value of the netSvcCtrPtyId property.
*
* @return
* possible object is
* {@link PartyIdentification73Choice }
*
*/
public PartyIdentification73Choice getNetSvcCtrPtyId() {
return netSvcCtrPtyId;
}
/**
* Sets the value of the netSvcCtrPtyId property.
*
* @param value
* allowed object is
* {@link PartyIdentification73Choice }
*
*/
public NetReportV01 setNetSvcCtrPtyId(PartyIdentification73Choice value) {
this.netSvcCtrPtyId = value;
return this;
}
/**
* Gets the value of the netOblgtn property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the netOblgtn property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNetOblgtn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NetObligation1 }
*
*
*/
public List<NetObligation1> getNetOblgtn() {
if (netOblgtn == null) {
netOblgtn = new ArrayList<NetObligation1>();
}
return this.netOblgtn;
}
/**
* Gets the value of the splmtryData property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the splmtryData property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSplmtryData().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SupplementaryData1 }
*
*
*/
public List<SupplementaryData1> getSplmtryData() {
if (splmtryData == null) {
splmtryData = new ArrayList<SupplementaryData1>();
}
return this.splmtryData;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* Adds a new item to the netOblgtn list.
* @see #getNetOblgtn()
*
*/
public NetReportV01 addNetOblgtn(NetObligation1 netOblgtn) {
getNetOblgtn().add(netOblgtn);
return this;
}
/**
* Adds a new item to the splmtryData list.
* @see #getSplmtryData()
*
*/
public NetReportV01 addSplmtryData(SupplementaryData1 splmtryData) {
getSplmtryData().add(splmtryData);
return this;
}
}
| 26.924528 | 182 | 0.625788 |
354ffd27245dd24561c7448b6ec5ec4247872fa0 | 848 | package com.github.sylphlike.framework.utils.excel;
import java.io.Serializable;
/**
* <p> time 17:56 2018/12/29 星期五 </p>
* <p> email [email protected] </P>
* @author Gopal.pan
* @version 1.0.0
*/
public class ExcelException extends RuntimeException implements Serializable {
private static final long serialVersionUID = -1695036681341844113L;
public ExcelException() {
}
public ExcelException(String message) {
super(message);
}
public ExcelException(String message, Throwable cause) {
super(message, cause);
}
public ExcelException(Throwable cause) {
super(cause);
}
public ExcelException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 22.315789 | 115 | 0.691038 |
a0cafa1a2b5db9fbeff3878c67b6c07f021e1d0e | 6,519 | package com.project.web.proxysale;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.project.bean.proxysale.PriceDetailQuery;
import com.project.bean.vo.AjaxResult;
import com.project.common.Constants;
import com.project.core.orm.Page;
import com.project.entity.proxysale.ProxyInn;
import com.project.service.proxysale.PriceUpdateService;
import com.project.service.proxysale.ProxyInnBean;
import com.project.service.proxysale.ProxyInnService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author frd
*/
@Controller
@RequestMapping("/proxysale/price")
public class ProxyPriceUpdateController {
private static final Logger LOGGER = LoggerFactory.getLogger(ProxyPriceUpdateController.class);
@Autowired
private ProxyInnService proxyInnService;
@Autowired
private ProxyInnBean proxyInnBean;
@Autowired
private PriceUpdateService priceUpdateService;
@RequestMapping(value = "/list")
public ModelAndView list(Page page, @RequestParam(value = "innName", required = false) String innName) {
ModelAndView mav = new ModelAndView("/proxysale/price/list");
page = proxyInnService.findPriceUpdateInnList(page, innName);
List list = page.getResult();
if (CollectionUtils.isNotEmpty(list)) {
List<PriceUpdateView> result = new ArrayList<>();
for (Object o : list) {
Object[] objs = (Object[]) o;
result.add(new PriceUpdateView(objs[0].toString(), objs[1].toString(), Integer.parseInt(objs[2].toString())));
}
mav.addObject("result", result);
}
mav.addObject("page", page);
mav.addObject("currentBtn", "price");
mav.addObject("innName", innName);
return mav;
}
@RequestMapping(value = "/detail")
public ModelAndView detail(@RequestParam("proxyInnId") Integer proxyInnId) {
ModelAndView mav = new ModelAndView("/proxysale/price/detail");
ProxyInn proxyInn = proxyInnService.get(proxyInnId);
mav.addObject("currentBtn", "price");
mav.addObject("proxyInn", proxyInn);
return mav;
}
@RequestMapping("/getChannels")
@ResponseBody
public AjaxResult getChannels(@RequestParam("proxyInnId") Integer proxyInnId,
@RequestParam("pricePattern") Float pricePattern,
@RequestParam("innId") Integer innId) {
try {
Map<String, List<Map<String, Object>>> proxyInnChannel = proxyInnService.getProxyInnChannel(proxyInnId, pricePattern, innId);
List<Map<String, Object>> sales = proxyInnChannel.get("sale");
if (CollectionUtils.isNotEmpty(sales)) {
for (int i = sales.size() - 1; i >= 0; i--) {
Map<String, Object> map = sales.get(i);
if (!Boolean.valueOf(map.get("isOpen").toString())) {
sales.remove(i);
}
}
}
return new AjaxResult(Constants.HTTP_OK, sales, "success");
} catch (Exception e) {
return new AjaxResult(Constants.HTTP_500, e.getMessage());
}
}
@RequestMapping(value = "/roomDetail")
@ResponseBody
public AjaxResult getDetailPrice(RoomDetailForm roomDetailForm) {
checkDetailForm(roomDetailForm);
PriceDetailQuery detailQuery = proxyInnBean.parse(roomDetailForm);
String result = proxyInnService.findPriceDetailByChannel(detailQuery);
JSONObject jsonObject = JSON.parseObject(result);
return new AjaxResult(Constants.HTTP_OK, jsonObject);
}
private void checkDetailForm(RoomDetailForm roomDetailForm) {
if (roomDetailForm.getChannelId() == null) {
throw new RuntimeException("渠道ID不能为空");
}
if (roomDetailForm.getProxyInnId() == null) {
throw new RuntimeException("代销客栈ID不能为空");
}
}
@RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
@ResponseBody
public AjaxResult doPriceUpdate(
@RequestParam("innName") String innName,
@RequestParam("accountId") Integer accountId,
@RequestParam("otaList") String otaList,
@RequestParam("roomList") String roomList) {
try {
proxyInnService.updatePrice(accountId, otaList, roomList, innName);
} catch (Exception e) {
return new AjaxResult(Constants.HTTP_500, e.getMessage());
}
return new AjaxResult(Constants.HTTP_OK, "");
}
/**
* 获取所有目的地名称
*
* @return
*/
@RequestMapping(value = "/regionName")
@ResponseBody
public AjaxResult getRegionName() {
try {
List<Map<String, Object>> regionName = priceUpdateService.findRegionName();
return new AjaxResult(Constants.HTTP_OK, regionName);
} catch (Exception e) {
return new AjaxResult(Constants.HTTP_500, e.getMessage());
}
}
/**
* 获取卖价渠道
*
* @return
*/
@RequestMapping(value = "/channelName")
@ResponseBody
public AjaxResult getChannelName() {
try {
List<Map<String, Object>> saleChannel = priceUpdateService.findSaleChannel();
return new AjaxResult(Constants.HTTP_OK, saleChannel);
} catch (Exception e) {
return new AjaxResult(Constants.HTTP_500, e.getMessage());
}
}
/**
* 批量调价
*
* @return
*/
@RequestMapping(value = "/batchUpdatePrice")
@ResponseBody
public AjaxResult batchUpdatePrice(String jsonStr) {
try {
priceUpdateService.batchUpdatePrice(jsonStr);
return new AjaxResult(Constants.HTTP_OK, "操作成功");
} catch (Exception e) {
priceUpdateService.saveErrorLog(jsonStr);
return new AjaxResult(Constants.HTTP_500, e.getMessage());
}
}
}
| 36.016575 | 137 | 0.65056 |
28acf3f2e85fd07997111e2b7a0b4d96ae669bf4 | 344 | /**
*
*/
package com.dev.appx.sns.tools;
import spark.ResponseTransformer;
import com.google.gson.Gson;
/**
* @author nthusitha
*
*/
public class JSONUtil {
public static String toJson(Object obj) {
return obj != null ? new Gson().toJson(obj) : "{}";
}
public static ResponseTransformer json() {
return JSONUtil::toJson;
}
}
| 14.333333 | 53 | 0.665698 |
a0cbb9dcc149490ae2b91d8b8857042f370ef1a2 | 1,253 | package michael.hackerrank.string;
import java.util.Scanner;
public class StringSimilarity {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int n1 = in.nextInt();
int[] os = new int[n1];
StringBuilder target;
for (int i = 0; i < n1; i++)
{
target = new StringBuilder(in.next());
os[i] = getSubStringSimilarity(target);
target = null;
}
for(int i = 0; i < n1; i++)
{
System.out.println(os[i]);
}
}
static int getSubStringSimilarity(StringBuilder target)
{
int n = target.length();
int similarity = n;
for(int i = 1; i < target.length(); i++)
{
int index = 0;
for(int j = 0; j < target.length() - i; j++)
{
if(target.charAt(j) == target.charAt(i+j))
index++;
else
break;
}
similarity += index;
}
return similarity;
}
} | 28.477273 | 120 | 0.466879 |
a7debbfc8c8ebcbbfcd0f6d8c50ab3880e83cb7d | 2,814 | package com.rmv.oop.task9;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.concurrent.Phaser;
@SpringBootApplication
public class Main implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Override
public void run(String... args) {
CustomPhaser customPhaser = new CustomPhaser(1);
System.out.println("new phaser with 1 registered unArrived parties"
+ " created and initial phase number is 0 ");
Thread customThread1 = new Thread(new MyRunnable(customPhaser, "first"), "Custom Thread-1");
Thread customThread2 = new Thread(new MyRunnable(customPhaser, "second"), "Custom Thread-2");
Thread customThread3 = new Thread(new MyRunnable(customPhaser, "third"), "Custom Thread-3");
System.out.println("\n--------Phaser has started---------------");
customThread1.start();
customThread2.start();
customThread3.start();
int currentCustomPhase = customPhaser.getPhase();
customPhaser.arriveAndAwaitAdvance();
System.out.println("------Phase-" + currentCustomPhase + " has been COMPLETED----------");
currentCustomPhase = customPhaser.getPhase();
customPhaser.arriveAndAwaitAdvance();
System.out.println("------Phase-" + currentCustomPhase + " has been COMPLETED----------");
customPhaser.arriveAndDeregister();
System.out.println('\n' + "---------Library version of phaser for comparison----------" + '\n');
Phaser phaser = new Phaser(1);
System.out.println("new phaser with 1 registered unArrived parties"
+ " created and initial phase number is 0 ");
Thread thread1 = new Thread(new MyRunnableLibraryPhaser(phaser, "first"), "Thread-1");
Thread thread2 = new Thread(new MyRunnableLibraryPhaser(phaser, "second"), "Thread-2");
Thread thread3 = new Thread(new MyRunnableLibraryPhaser(phaser, "third"), "Thread-3");
System.out.println("\n--------Phaser has started---------------");
thread1.start();
thread2.start();
thread3.start();
int currentPhase = phaser.getPhase();
phaser.arriveAndAwaitAdvance();
System.out.println("------Phase-" + currentPhase + " has been COMPLETED----------");
currentPhase = phaser.getPhase();
phaser.arriveAndAwaitAdvance();
System.out.println("------Phase-" + currentPhase + " has been COMPLETED----------");
phaser.arriveAndDeregister();
if (phaser.isTerminated())
System.out.println("\nPhaser has been terminated");
}
}
| 37.026316 | 104 | 0.638237 |
17485c94b43bb31840e990f89f25f865b19f67df | 207 | package com.ziningmei.mybatis.exception;
public class ExceptionFactory {
public static RuntimeException wrapException(String msg, Exception e) {
return new PersistenceException(msg,e);
}
}
| 23 | 75 | 0.748792 |
4f9e80f3a4a7e58e6f4a011314883ada3b412f38 | 483 | package com.muhlenxi.dao;
import java.util.List;
import com.muhlenxi.domain.QueryObject;
import com.muhlenxi.domain.Student;
public interface IStudentDao {
List<Student> findAll();
void saveStudent(Student student);
void deleteStudent(int id);
void updateStudent(Student student);
Student findStudentById(int id);
List<Student> findStudentsByName(String name);
int findTotal();
List<Student> findStudentsByQueryObject(QueryObject object);
}
| 20.125 | 65 | 0.745342 |
41797b9b5fcd8a8b19db8ea07af65cc01dc6fef2 | 2,568 | package com.intellij.cvsSupport2;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* author: lesya
*/
public class RcsDiffErrorTest extends CvsTestsWorkingWithImportedProject{
private List myLines = new ArrayList();
private static final String ANOTHER_LINE_SEPARATOR = "\r";
@Override
protected void setUp() throws Exception {
super.setUp();
createLongContent();
}
public void testAddingFirstLine() throws Exception {
executeWith(firstLineAppender());
}
public void testRemovingFirstLine() throws Exception {
executeWith(firstLineRemover());
}
public void testSwappingLines() throws Exception {
Runnable changer = () -> {
ArrayList result = new ArrayList();
result.add("");
result.add("");
result.add("");
result.add("");
for (int i = 0; i < myLines.size() / 2 - 6; i++){
result.add(myLines.get(i*2 + 1));
result.add(myLines.get(i*2 ));
}
myLines = result;
};
executeWith(changer);
}
private Runnable firstLineRemover() {
return () -> myLines.remove(0);
}
private void executeWith(Runnable contentModificationAction) throws Exception {
TEST_FILE.changeContentTo(createContentOnLines());
TEST_FILE.addToVcs(myVcs);
commitTransaction();
modifyFileContent(contentModificationAction);
updateTestFile();
String expected = createContentOnLines(ANOTHER_LINE_SEPARATOR);
String actual = TEST_FILE.getContent();
assertEquals(expected, actual);
}
private Runnable firstLineAppender() {
return () -> {
myLines.add(0, "");
myLines.add(0, "change");
myLines.add(0, "");
myLines.add(0, "");
};
}
private void modifyFileContent(Runnable contentModificationAction) throws Exception {
contentModificationAction.run();
createNewTestFileRevisionWithContent(createContentOnLines());
}
private String createContentOnLines() {
return createContentOnLines(ANOTHER_LINE_SEPARATOR);
}
private String createContentOnLines(String lineSeparator) {
StringBuilder result = new StringBuilder();
for (Iterator iterator = myLines.iterator(); iterator.hasNext();) {
result.append((String) iterator.next());
if (iterator.hasNext())
result.append(lineSeparator);
}
return result.toString();
}
private StringBuffer createLongContent() {
StringBuffer longContent = new StringBuffer();
for(int i = 0; i < 1000; i++){
myLines.add("String " + i);
}
return longContent;
}
}
| 24.932039 | 87 | 0.673676 |
d9a5b29f9111f0eb3f59c50ddae2d0b2c657c479 | 567 | package com.rmh.guitar.bestposition.domain.request;
import com.rmh.guitar.bestposition.domain.request.options.FretboardSettings;
import com.rmh.guitar.bestposition.domain.request.options.SearchOptions;
import com.rmh.guitar.bestposition.domain.request.options.WeightOptions;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Options {
private FretboardSettings fretboardSettings;
private SearchOptions searchOptions;
private WeightOptions weightOptions;
}
| 28.35 | 76 | 0.839506 |
c29dae5fe7977539a35380dc56a843111bc57636 | 2,692 | package io.github.task.quartz;
import com.alibaba.fastjson.JSON;
import io.github.entity.SysTaskEntity;
import io.github.entity.enums.TaskCallbackTypeEnum;
import io.github.frame.prj.constant.SysModuleConst;
import io.github.service.SysTaskService;
import io.github.util.spring.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* quartz任务调度工厂
*
* @author Created by 思伟 on 2020/8/24
*/
@Slf4j
public class QuartzJobFactory implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
long start = System.currentTimeMillis();
boolean result = false;
// 从context中取出对应的【定时任务】
SysTaskEntity task = (SysTaskEntity) context.getJobDetail().getJobDataMap().get(QuartzManager.JOB_DATA_TASK_NAME);
switch (task.getCallbackType()) {
case PRINT:
result = printExecute(task);
break;
case CLASS:
result = classExecute(task);
break;
case HTTP:
// TODO...
printLog(task);
break;
case HESSIAN:
printLog(task);
// TODO...
break;
default:
result = false;
break;
}
long time = System.currentTimeMillis() - start;
log.info("[{}] 执行[{}]定时任务 {},耗时={}ms, task={}", SysModuleConst.SYS,
task.getCallbackType().getValue(), result ? "成功" : "失败", time, JSON.toJSONString(task));
// 执行后就移除
SpringContextUtils.getBean(SysTaskService.class).disableByPrimaryKey(task.getId());
}
/**
* 普通打印任务
*
* @param task 定时任务
* @return boolean
* @see TaskCallbackTypeEnum#PRINT
*/
private boolean printExecute(SysTaskEntity task) {
printLog(task);
return true;
}
/**
* 类回调任务
*
* @param task 定时任务
* @return boolean
* @see TaskCallbackTypeEnum#CLASS
*/
private boolean classExecute(SysTaskEntity task) {
return SpringContextUtils.getBean(ITaskCallbackService.class).execute(
task.getId(), task.getJobName(), task.getBizModule(), task.getBizId(), task.getBizTag(),
task.getCallbackData(), task.getCallbackUrl());
}
/**
* 简易日志打印
*
* @param task 定时任务
*/
protected void printLog(SysTaskEntity task) {
log.info("[{}] 执行[{}]定时任务,task={}", SysModuleConst.SYS, task.getCallbackType().getValue(),
JSON.toJSONString(task));
}
}
| 30.247191 | 122 | 0.600297 |
e378149883de13ae6df1f580ca2b18f3304e0430 | 405 | package io.hyperfoil.core.builder;
import org.junit.Test;
import io.hyperfoil.core.handlers.RangeStatusValidator;
import io.hyperfoil.core.steps.HttpRequestStep;
public class LambdaCopyTest {
@Test
public void test() {
HttpRequestStep.Builder builder = new HttpRequestStep.Builder()
.handler().status(new RangeStatusValidator(0, 666)).endHandler();
builder.copy();
}
}
| 25.3125 | 77 | 0.728395 |
ffc22bbe12a2746684e61355d45ef5781e8eb3b5 | 774 | /*
* @lc app=leetcode id=970 lang=java
*
* [970] Powerful Integers
*/
// @lc code=start
class Solution {
public List<Integer> powerfulIntegers(int x, int y, int bound) {
HashSet<Integer> h = new HashSet();
List<Integer> l = new LinkedList<Integer>();
int bx = 1;
while (bx <= bound) {
int by = 1;
while (bx + by <= bound) {
if (!h.contains(bx + by)) {
l.add(bx + by);
h.add(bx + by);
}
if (y == 1) {
break;
}
by *= y;
}
if (x == 1) {
break;
}
bx *= x;
}
return l;
}
}
// @lc code=end
| 22.114286 | 68 | 0.366925 |
171c346a442aa663675e7462e82008bf0fac5a07 | 1,610 | package com.apress.springbootrecipes.order.web;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.reactive.server.WebTestClient;
import com.apress.springbootrecipes.order.Order;
import com.apress.springbootrecipes.order.OrderService;
@WebFluxTest(OrderController.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class OrderControllerSliceWithSpyTest {
@Autowired
private WebTestClient webTestClient;
@SpyBean
private OrderService orderService;
@Test
public void listOrders() {
webTestClient.get().uri("/orders") //
.exchange() //
.expectStatus().isOk() //
.expectBodyList(Order.class).hasSize(25); //
}
@Test
public void addAndGetOrder() {
Order order = new Order("test1", BigDecimal.valueOf(1234.56));
webTestClient.post().uri("/orders").bodyValue(order) //
.exchange() //
.expectStatus().isOk() //
.expectBody(Order.class).isEqualTo(order); //
webTestClient.get().uri("/orders/{id}", order.getId())//
.exchange() //
.expectStatus().isOk() //
.expectBody(Order.class).isEqualTo(order); //
}
}
| 32.857143 | 76 | 0.658385 |
218931b4950c5d5b5a25420aad1a7ee5dd73d4e4 | 815 | package org.janelia.jacs2.asyncservice;
import org.janelia.jacs2.asyncservice.common.ServiceProcessor;
import org.janelia.model.service.JacsServiceData;
import org.janelia.model.service.JacsServiceState;
import java.util.List;
public interface JacsServiceEngine {
void setProcessingSlotsCount(int nProcessingSlots);
void setMaxWaitingSlots(int maxWaitingSlots);
ServerStats getServerStats();
ServiceProcessor<?> getServiceProcessor(JacsServiceData jacsServiceData);
JacsServiceData submitSingleService(JacsServiceData serviceArgs);
List<JacsServiceData> submitMultipleServices(List<JacsServiceData> listOfServices);
boolean acquireSlot();
void releaseSlot();
JacsServiceData updateServiceState(JacsServiceData serviceData, JacsServiceState serviceState, boolean forceFlag);
}
| 40.75 | 118 | 0.82454 |
f4fcea6ce5ad687ef420854c7635192356a46c4e | 213 | package edu.prahlad.patterns2.structural.facade;
public class Main {
public static void main(String[] args) {
var service = new NotificationService();
service.send("hello", "target");
}
}
| 23.666667 | 48 | 0.661972 |
b8574ef4ba9426c1505b04a041a6a9a64d3cc66a | 3,889 | package com.ibm.safr.we.model.utilities;
/*
* Copyright Contributors to the GenevaERS Project. SPDX-License-Identifier: Apache-2.0 (c) Copyright IBM Corporation 2008.
*
* 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.
*/
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.ibm.safr.we.constants.SortType;
import com.ibm.safr.we.data.DAOFactoryHolder;
import com.ibm.safr.we.data.transfer.ViewColumnTransfer;
import com.ibm.safr.we.data.transfer.ViewSortKeyTransfer;
import com.ibm.safr.we.model.SAFRApplication;
import com.ibm.safr.we.model.query.EnvironmentQueryBean;
import com.ibm.safr.we.model.query.ViewQueryBean;
public class ViewStartPositionConverter {
public static void main(String[] args) {
SAFRApplication.getSAFRFactory().getAllCodeSets();
SAFRApplication.initDummyUserSession();
System.out.println("Converting all View column start positions");
convertAllViewColumnPositions();
System.out.println("Finished converting all View column start positions");
}
protected static void convertAllViewColumnPositions() {
// loop through all environments
List<EnvironmentQueryBean> envBeans =
DAOFactoryHolder.getDAOFactory().getEnvironmentDAO().queryAllEnvironments(SortType.SORT_BY_ID);
for (EnvironmentQueryBean envBean : envBeans) {
System.out.println("\tConverting environment " + envBean.getId());
List<ViewQueryBean> vBeans =
DAOFactoryHolder.getDAOFactory().getViewDAO().queryAllViews(SortType.SORT_BY_ID, envBean.getId(), true);
for (ViewQueryBean vBean : vBeans) {
convertView(vBean);
}
}
}
protected static void convertView(ViewQueryBean vBean) {
List<ViewSortKeyTransfer> sortkeys =
DAOFactoryHolder.getDAOFactory().getViewSortKeyDAO().getViewSortKeys(vBean.getId(), vBean.getEnvironmentId());
if (vBean.getOldOutputFormat().equals("FILE") && vBean.getOldType().equals("EXTR") &&
sortkeys.size() > 0) {
System.out.println("\t\tConverting view " + vBean.getId() + " column start positions");
List<ViewColumnTransfer> cols =
DAOFactoryHolder.getDAOFactory().getViewColumnDAO().getViewColumns(vBean.getId(), vBean.getEnvironmentId());
// form set of sortkeys
Set<Integer> sortKeyMap = new HashSet<Integer>();
for (ViewSortKeyTransfer sortKey : sortkeys) {
sortKeyMap.add(sortKey.getViewColumnId());
}
int prevStartPosition = 1;
int prevLength = 0;
for (ViewColumnTransfer col : cols) {
if (sortKeyMap.contains(col.getId())) {
col.setStartPosition(0);
}// if column is sort key
else {
int currentStartPos = prevStartPosition + prevLength;
col.setStartPosition(currentStartPos);
prevStartPosition = currentStartPos;
prevLength = col.getLength().intValue();
}
}
DAOFactoryHolder.getDAOFactory().getViewColumnDAO().persistViewColumns(cols);
}
}
}
| 41.37234 | 124 | 0.644639 |
9532ac692396c3dd78ec882b930718e93f0ed5b8 | 937 | package code401challenges.utilities;
import code401challenges.tree.Node;
import code401challenges.tree.Tree;
public class FizzBuzzTree extends Tree{
public FizzBuzzTree(){
super();
}
public void fizzBuzzOnNode(Node<Object> current){
if(current != null) {
if((int)current.getData() % 3 == 0 && (int)current.getData() % 5 == 0){
current.setData( "FizzBuzz");
} else if((int)current.getData() % 3 == 0) {
current.setData("Fizz");
} else if((int)current.getData() % 5 == 0) {
current.setData("Buzz");
} else{
return;
}
fizzBuzzOnNode(current.getLeftChildNode());
fizzBuzzOnNode(current.getRightChildNode());
}
}
public Tree<Object> fizzBuzzTree(Tree<Object> myTree){
fizzBuzzOnNode(myTree.getRoot());
return myTree;
}
}
| 25.324324 | 83 | 0.557097 |
5c40ea9d1a51449e42d269adbe4e7d3320131217 | 5,674 | /**
* Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
* (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
* informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
* COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp.,
* INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
* ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.webapp.models.privacy;
/**
* Refactored list of data types for Cis context data
*
* @author Olivier Maridat (Trialog)
*/
public class CisCtxAttributeHumanTypes {
// /**
// * @since 0.0.8
// */
// public static final String ABOUT = "About";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_HOME_CITY = "Home city";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_HOME_COUNTRY = "Home country";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_HOME_STREET_NAME = "Home street name";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_HOME_STREET_NUMBER = "Home street number";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_WORK_CITY = "Work city";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_WORK_COUNTRY = "Work country";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_WORK_STREET_NAME = "Work street name";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String ADDRESS_WORK_STREET_NUMBER = "Work street number";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String BOOKS = "Books";
//
// /**
// * @since 0.0.8
// */
// public static final String EMAIL = "Email";
/**
* @since 0.0.8
*/
public static final String FAVOURITE_QUOTES = "Favorite quotes";
/**
* @since 0.0.8
*/
public static final String INTERESTS = "Interests";
/**
* @since 0.0.8
*/
public static final String LANGUAGES = "Languages";
// /**
// * @since 0.0.8
// */
// public static final String LAST_ACTION = "Last action";
// /**
// * @since 0.0.8
// */
// public static final String ACTION = "Action";
/**
* @since 0.0.8
*/
public static final String LOCATION_COORDINATES = "Location coordinates";
/**
* @since 0.0.8
*/
public static final String LOCATION_SYMBOLIC = "Location symbolic";
/**
* @since 0.0.8
*/
public static final String MOVIES = "Movies";
/**
* @since 0.0.8
*/
public static final String MUSIC = "Music";
// /**
// * @since 0.0.8
// */
// public static final String NAME = "Name";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String NAME_FIRST = "Firstname";
//
// /**
// *
// * @since 0.0.8
// */
// public static final String NAME_LAST = "Lastname";
//
// /**
// * @since 0.0.8
// */
// public static final String OCCUPATION = "Occupation";
//
//
// /**
// * @since 0.0.8
// */
// public static final String POLITICAL_VIEWS = "Political views";
//
// /**
// * @since 0.0.8
// */
// public static final String RELIGIOUS_VIEWS = "Religiousl views";
//
// /**
// * @since 0.0.8
// */
// public static final String SEX = "Sex";
//
// /**
// * @since 0.0.8
// */
// public static final String STATUS = "Status";
//
// /**
// * @since 0.0.8
// */
// public static final String SKILLS = "Skills";
//
// /**
// * @since 0.0.8
// */
// public static final String TEMPERATURE = "Temperature";
//
// /**
// * @since 0.0.8
// */
// public static final String WEIGHT = "Weight";
} | 28.512563 | 130 | 0.59288 |
7e1339c8dc7986fc27c4638aa858a495032f24f0 | 1,066 | package async.net;
import java.io.IOException;
import async.net.callback.ExceptionCallback;
import async.net.callback.IOCallback;
/**
* Used to start ASync callback to console.
*
* <pre>
* <!--Code start[doc.JavaDocExample1.aSyncConsol] [2897DEF2DC1FB0B799E04C82F92A53F6]-->
* ASyncConsol console = new ASync().console();
* console.start(new IOCallback() {
* public void call(InputStream in, OutputStream out) throws IOException {
* // ...
* }
* });
* <!--Code end-->
* </pre>
*/
public interface ASyncConsol {
/**
* Start a ASync console with callback as handler.
*
* @param callback
* IOCallback to be used for ASync console.
*/
void start(IOCallback callback);
/**
* Start a ASync console with callback as handler and eCallback as Exception
* handler.
*
* @param callback
* IOCallback to be used for ASync console.
* @param exceptionCallback
* callback for all IOException.
*/
void start(IOCallback callback, ExceptionCallback<IOException> exceptionCallback);
}
| 24.227273 | 88 | 0.669794 |
6a493f9d95abacaa063ac56a4f8a3bd13f5d69f4 | 7,462 |
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache POI" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache POI", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.poi.hssf.dev;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.eventmodel.*;
import org.apache.poi.hssf.eventusermodel.*;
import org.apache.poi.hssf.usermodel.*;
/**
* Event Factory version of HSSF test class.
* @author andy
*/
public class EFHSSF
{
String infile;
String outfile;
HSSFWorkbook workbook = null;
HSSFSheet cursheet = null;
/** Creates a new instance of EFHSSF */
public EFHSSF()
{
}
public void setInputFile(String infile)
{
this.infile = infile;
}
public void setOutputFile(String outfile)
{
this.outfile = outfile;
}
public void run()
throws IOException
{
FileInputStream fin = new FileInputStream(infile);
POIFSFileSystem poifs = new POIFSFileSystem(fin);
InputStream din = poifs.createDocumentInputStream("Workbook");
HSSFRequest req = new HSSFRequest();
req.addListenerForAllRecords(new EFHSSFListener(this));
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, din);
fin.close();
din.close();
FileOutputStream fout = new FileOutputStream(outfile);
workbook.write(fout);
fout.close();
System.out.println("done.");
}
public void recordHandler(Record record)
{
HSSFRow row = null;
HSSFCell cell = null;
int sheetnum = -1;
switch (record.getSid())
{
case BOFRecord.sid :
BOFRecord bof = ( BOFRecord ) record;
if (bof.getType() == bof.TYPE_WORKBOOK)
{
workbook = new HSSFWorkbook();
}
else if (bof.getType() == bof.TYPE_WORKSHEET)
{
sheetnum++;
cursheet = workbook.getSheetAt(sheetnum);
}
break;
case BoundSheetRecord.sid :
BoundSheetRecord bsr = ( BoundSheetRecord ) record;
workbook.createSheet(bsr.getSheetname());
break;
case RowRecord.sid :
RowRecord rowrec = ( RowRecord ) record;
cursheet.createRow(rowrec.getRowNumber());
break;
case NumberRecord.sid :
NumberRecord numrec = ( NumberRecord ) record;
row = cursheet.getRow(numrec.getRow());
cell = row.createCell(numrec.getColumn(),
HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(numrec.getValue());
break;
case SSTRecord.sid :
SSTRecord sstrec = ( SSTRecord ) record;
for (int k = 0; k < sstrec.getNumUniqueStrings(); k++)
{
workbook.addSSTString(sstrec.getString(k));
}
break;
case LabelSSTRecord.sid :
LabelSSTRecord lrec = ( LabelSSTRecord ) record;
row = cursheet.getRow(lrec.getRow());
cell = row.createCell(lrec.getColumn(),
HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(workbook.getSSTString(lrec.getSSTIndex()));
break;
}
}
public static void main(String [] args)
{
if ((args.length < 2) || !args[ 0 ].equals("--help"))
{
try
{
EFHSSF viewer = new EFHSSF();
viewer.setInputFile(args[ 0 ]);
viewer.setOutputFile(args[ 1 ]);
viewer.run();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
System.out.println("EFHSSF");
System.out.println(
"General testbed for HSSFEventFactory based testing and "
+ "Code examples");
System.out.println("Usage: java org.apache.poi.hssf.dev.EFHSSF "
+ "file1 file2");
System.out.println(
" --will rewrite the file reading with the event api");
System.out.println("and writing with the standard API");
}
}
}
class EFHSSFListener
implements HSSFListener
{
EFHSSF efhssf;
public EFHSSFListener(EFHSSF efhssf)
{
this.efhssf = efhssf;
}
public void processRecord(Record record)
{
efhssf.recordHandler(record);
}
}
| 32.585153 | 77 | 0.592871 |
870c612ddc7fb1747ba7ed8322477497969c739f | 508 | package mobi.chouette.exchange.importer.updater;
import java.util.Comparator;
import mobi.chouette.model.ChouetteIdentifiedObject;
public class NeptuneIdentifiedObjectComparator implements
Comparator<ChouetteIdentifiedObject> {
public static final Comparator<ChouetteIdentifiedObject> INSTANCE = new NeptuneIdentifiedObjectComparator();
@Override
public int compare(ChouetteIdentifiedObject left,
ChouetteIdentifiedObject right) {
return left.getObjectId().compareTo(right.getObjectId());
}
}
| 29.882353 | 109 | 0.832677 |
dec5958f45aeeece863d8409da1b9b47d36a4d38 | 322 | package tech.valery.partnersrestservices.services;
import tech.valery.partnersrestservices.model.PartnerMapping;
import java.util.Optional;
public interface PartnerMappingService {
Optional<PartnerMapping> findById(Long aLong);
<S extends PartnerMapping> S save(S entity);
void deleteById(Long aLong);
}
| 21.466667 | 61 | 0.78882 |
b2e8c6eca6700479a96a80409c1e198267a4c0c6 | 3,117 | package ru.barsk.view;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import ru.barsk.moc.Coordinates;
import ru.barsk.moc.MainActivity;
import ru.barsk.moc.Player;
import ru.barsk.moc.StarViewActivity;
/**
* Класс, использующийся для отображения
* звёзд на главном экране и MapViewActivity.
* TextView, знающий позицию отображаемой звезды.
*/
public class StarTextView extends TextView {
public Coordinates coordinates;
public StarTextView(Context context) {
super(context);
coordinates = new Coordinates((byte) 0, (byte) 0);
}
public StarTextView(Context context, AttributeSet attrs) {
super(context, attrs);
coordinates = new Coordinates((byte) 0, (byte) 0);
}
public StarTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
coordinates = new Coordinates((byte) 0, (byte) 0);
}
public static final OnClickListener SYSTEM_SELECTION_LISTENER = new OnClickListener() {
@Override
public void onClick(View v) {
if (!(v instanceof StarTextView)) {
throw new ClassCastException("Listener given not to starTextView!");
}
StarTextView starTextView = (StarTextView) v;
byte x = starTextView.coordinates.x;
byte y = starTextView.coordinates.y;
if (x == MainActivity.selectedStarCoordinates.x && y == MainActivity.selectedStarCoordinates.y && MainActivity.galaxy[x][y].type != 0 && MainActivity.galaxy[x][y].getOwnerId() == Player.ID) {
Intent intent = new Intent(MainActivity.context, StarViewActivity.class);
MainActivity.context.startActivity(intent);
}
else {
int selectionDrawableId;
selectionDrawableId = MainActivity.getSelectionDrawableId((byte) 0, MainActivity.currentSize);
MainActivity.screenTexts[MainActivity.selectedStarCoordinates.x][MainActivity.selectedStarCoordinates.y].setCompoundDrawablesWithIntrinsicBounds(0, selectionDrawableId, 0, 0);
MainActivity.selectedStarCoordinates.x = x;
MainActivity.selectedStarCoordinates.y = y;
selectionDrawableId = MainActivity.getSelectionDrawableId((byte) 1, MainActivity.currentSize);
MainActivity.screenTexts[MainActivity.selectedStarCoordinates.x][MainActivity.selectedStarCoordinates.y].setCompoundDrawablesWithIntrinsicBounds(0, selectionDrawableId, 0, 0);
MainActivity.context.invalidateScreen(false);
}
}
};
public static OnClickListener makeDestinationSelector(@NonNull final Coordinates to) {
return new OnClickListener() {
@Override
public void onClick(View v) {
if (!(v instanceof StarTextView)) {
throw new ClassCastException("Listener given not to starTextView!");
}
StarTextView starTextView = (StarTextView) v;
to.x = starTextView.coordinates.x;
to.y = starTextView.coordinates.y;
MainActivity.context.showGalaxy(); // Можно ли сделать это рационально?
}
};
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates.x = coordinates.x;
this.coordinates.y = coordinates.y;
}
}
| 36.244186 | 194 | 0.760346 |
3d6fab60a6fb0f83210f2004d3a23c7f052b20cd | 423 | package br.com.objectos.css.keyword;
import br.com.objectos.code.annotations.Generated;
import br.com.objectos.css.type.FontFamilyValue;
@Generated("br.com.objectos.css.boot.CssBoot")
public final class MonospaceKeyword extends StandardKeyword implements FontFamilyValue {
static final MonospaceKeyword INSTANCE = new MonospaceKeyword();
private MonospaceKeyword() {
super(153, "monospace", "monospace");
}
} | 28.2 | 88 | 0.78487 |
dd3f00192e1676c9e17664ad42fd7e639ac06d55 | 333 | package com.github.mkopylec.rpggame.domain.items;
import com.github.mkopylec.ddd.buildingblocks.Repository;
import java.util.UUID;
@Repository
public interface ItemRepository {
void save(Item item);
HealingPotion findOneHealingPotion(UUID potionId);
Sword findOneSword(UUID swordId);
void delete(Item item);
}
| 18.5 | 57 | 0.768769 |
bc6e2b2b3c29b7719379b5f544aab9bfadb57029 | 2,574 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.labs64.netlicensing.domain.vo;
public enum LicenseType {
/**
* licenseType: feature.
*/
FEATURE("FEATURE"),
/**
* licenseType: TimeVolume.
*/
TIMEVOLUME("TIMEVOLUME"),
/**
* licenseType: TimeVolume.
*/
FLOATING("FLOATING"),
/**
* licenseType: Quantity.
*/
QUANTITY("QUANTITY");
private final String value;
/**
* Instantiates a new license type.
*
* @param licenseTypeValue
* licenseType value
*/
LicenseType(final String licenseTypeValue) {
value = licenseTypeValue;
}
/**
* Get enum value.
*
* @return enum value
*/
public String value() {
return value;
}
/*
* (non-Javadoc)
*
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return value;
}
/**
* Parse license type value to {@link LicenseType} enum.
*
* @param value
* licenseType value
* @return {@link LicenseType} enum object or throws {@link IllegalArgumentException} if no corresponding
* {@link LicenseType} enum object found
*/
public static LicenseType parseValue(final String value) {
for (final LicenseType licenseType : LicenseType.values()) {
if (licenseType.value.equalsIgnoreCase(value)) {
return licenseType;
}
}
throw new IllegalArgumentException(value);
}
/**
* Parse license type value to {@link LicenseType} enum, nothrow version.
*
* @param value
* licenseType value as string
* @return {@link LicenseType} enum object or {@code null} if argument doesn't match any of the enum values
*/
public static LicenseType parseValueSafe(final String value) {
try {
return parseValue(value);
} catch (final IllegalArgumentException e) {
return null;
}
}
}
| 25.485149 | 111 | 0.60373 |
5bb6de38e76722a43c059a650bb832b1014bf9d3 | 370 | package com.mempoolexplorer.txmempool.services;
import com.mempoolexplorer.txmempool.controllers.entities.RecalculateAllStatsResult;
import com.mempoolexplorer.txmempool.entites.IgnoringBlock;
public interface StatisticsService {
RecalculateAllStatsResult recalculateAllStats();
void saveStatisticsToDB(IgnoringBlock iGBlockBitcoind, IgnoringBlock iGBlockOurs);
} | 30.833333 | 84 | 0.87027 |
fca62fc9bc3ac674f70add0f0d9e9b80a1716801 | 297 | package com.hly.march.exception;
import org.apache.shiro.subject.Subject;
public class MyForbiddenException extends SysException {
private Subject subject;
public MyForbiddenException(String msg, Subject subject) {
super("你的账户已被封禁:"+msg);
this.subject = subject;
}
}
| 24.75 | 62 | 0.723906 |
2c10c795752e39abe867ba808fd26284b125bb1a | 7,347 | package org.kie.maven.plugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.project.MavenProject;
import org.appformer.maven.support.AFReleaseId;
import org.appformer.maven.support.AFReleaseIdImpl;
import org.appformer.maven.support.DependencyFilter;
import org.assertj.core.api.Condition;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ProjectPomModelTest {
private static final String GROUP_ID = "org.kie.test.groupid";
private static final String ARTIFACT_ID = "test-artifact";
private static final String PARENT_ARTIFACT_ID = "parent-artifact";
private static final String VERSION = "1.0";
private static final String PACKAGING = "kjar";
private static final String DEPENDENCY_GROUP_ID = "org.kie.test.dependency.groupid";
private static final String DEPENDENCY_ARTIFACT_ID1 = "dependency-artifact1";
private static final String DEPENDENCY_ARTIFACT_ID2 = "dependency-artifact2";
private static final String DEPENDENCY_VERSION = "1.0";
private static final String DEPENDENCY_PACKAGING = "jar";
private static final String DEPENDENCY_SCOPE1 = "compile";
private static final String DEPENDENCY_SCOPE2 = "test";
@Test
public void getReleaseId() {
final MavenSession mavenSession = mockMavenSession(false);
final ProjectPomModel pomModel = new ProjectPomModel(mavenSession);
final AFReleaseId releaseId = pomModel.getReleaseId();
assertReleaseId(releaseId, ARTIFACT_ID);
}
@Test
public void getParentReleaseId() {
final MavenSession mavenSession = mockMavenSession(true);
final ProjectPomModel pomModel = new ProjectPomModel(mavenSession);
final AFReleaseId releaseId = pomModel.getParentReleaseId();
assertReleaseId(releaseId, PARENT_ARTIFACT_ID);
}
@Test
public void getParentReleaseIdNull() {
final MavenSession mavenSession = mockMavenSession(false);
final ProjectPomModel pomModel = new ProjectPomModel(mavenSession);
assertThat(pomModel.getParentReleaseId()).isNull();
}
@Test
public void getDependencies() {
final MavenSession mavenSession = mockMavenSession(false);
mockDependencies(mavenSession.getCurrentProject());
final ProjectPomModel pomModel = new ProjectPomModel(mavenSession);
final Collection<AFReleaseId> dependencies = pomModel.getDependencies();
assertThat(dependencies).isNotNull().hasSize(2);
assertThat(dependencies).areExactly(1, new Condition<>(
releaseId -> releaseId instanceof AFReleaseIdImpl
&& DEPENDENCY_GROUP_ID.equals(releaseId.getGroupId())
&& DEPENDENCY_ARTIFACT_ID1.equals(releaseId.getArtifactId())
&& DEPENDENCY_VERSION.equals(releaseId.getVersion())
&& DEPENDENCY_PACKAGING.equals(((AFReleaseIdImpl) releaseId).getType()),
"Is dependency 1"));
assertThat(dependencies).areExactly(1, new Condition<>(
releaseId -> releaseId instanceof AFReleaseIdImpl
&& DEPENDENCY_GROUP_ID.equals(releaseId.getGroupId())
&& DEPENDENCY_ARTIFACT_ID2.equals(releaseId.getArtifactId())
&& DEPENDENCY_VERSION.equals(releaseId.getVersion())
&& DEPENDENCY_PACKAGING.equals(((AFReleaseIdImpl) releaseId).getType()),
"Is dependency 2"));
}
@Test
public void getDependenciesEmpty() {
final MavenSession mavenSession = mockMavenSession(false);
final ProjectPomModel pomModel = new ProjectPomModel(mavenSession);
final Collection<AFReleaseId> dependencies = pomModel.getDependencies();
assertThat(dependencies).isNotNull().isEmpty();
}
@Test
public void getDependenciesWithFilter() {
final MavenSession mavenSession = mockMavenSession(false);
mockDependencies(mavenSession.getCurrentProject());
final ProjectPomModel pomModel = new ProjectPomModel(mavenSession);
final Collection<AFReleaseId> dependencies = pomModel.getDependencies(
(releaseId, scope) -> DEPENDENCY_SCOPE1.equals(scope));
assertThat(dependencies).isNotNull().hasSize(1);
assertThat(dependencies).areExactly(1, new Condition<>(
releaseId -> releaseId instanceof AFReleaseIdImpl
&& DEPENDENCY_GROUP_ID.equals(releaseId.getGroupId())
&& DEPENDENCY_ARTIFACT_ID1.equals(releaseId.getArtifactId())
&& DEPENDENCY_VERSION.equals(releaseId.getVersion())
&& DEPENDENCY_PACKAGING.equals(((AFReleaseIdImpl) releaseId).getType()),
"Is dependency 1"));
}
private MavenSession mockMavenSession(final boolean addParentProject) {
final MavenSession mavenSession = mock(MavenSession.class);
final MavenProject currentProject = mockMavenProject(ARTIFACT_ID);
if (addParentProject) {
final MavenProject parentProject = mockMavenProject(PARENT_ARTIFACT_ID);
when(currentProject.getParent()).thenReturn(parentProject);
}
when(mavenSession.getCurrentProject()).thenReturn(currentProject);
return mavenSession;
}
private MavenProject mockMavenProject(final String artifactId) {
final MavenProject mavenProject = mock(MavenProject.class);
when(mavenProject.getGroupId()).thenReturn(GROUP_ID);
when(mavenProject.getArtifactId()).thenReturn(artifactId);
when(mavenProject.getVersion()).thenReturn(VERSION);
when(mavenProject.getPackaging()).thenReturn(PACKAGING);
return mavenProject;
}
private void mockDependencies(final MavenProject mavenProject) {
final List<Dependency> dependencies = new ArrayList<>();
dependencies.add(mockDependency(DEPENDENCY_ARTIFACT_ID1, DEPENDENCY_SCOPE1));
dependencies.add(mockDependency(DEPENDENCY_ARTIFACT_ID2, DEPENDENCY_SCOPE2));
when(mavenProject.getDependencies()).thenReturn(dependencies);
}
private Dependency mockDependency(final String artifactId, final String scope) {
final Dependency dependency = mock(Dependency.class);
when(dependency.getGroupId()).thenReturn(DEPENDENCY_GROUP_ID);
when(dependency.getArtifactId()).thenReturn(artifactId);
when(dependency.getVersion()).thenReturn(VERSION);
when(dependency.getType()).thenReturn(DEPENDENCY_PACKAGING);
when(dependency.getScope()).thenReturn(scope);
return dependency;
}
private void assertReleaseId(final AFReleaseId releaseId, final String artifactId) {
assertThat(releaseId).isNotNull().isInstanceOf(AFReleaseIdImpl.class);
assertThat(releaseId.getGroupId()).isEqualTo(GROUP_ID);
assertThat(releaseId.getArtifactId()).isEqualTo(artifactId);
assertThat(releaseId.getVersion()).isEqualTo(VERSION);
assertThat(((AFReleaseIdImpl) releaseId).getType()).isEqualTo(PACKAGING);
}
} | 48.019608 | 96 | 0.705186 |
b8e12caf769e5548ba6fcbf7506662f7a6ab677e | 5,995 | /* RSASignatureFactory.java -- A Factory class to instantiate RSA Signatures
Copyright (C) 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.security.sig.rsa;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import gnu.java.security.Registry;
import gnu.java.security.hash.HashFactory;
import gnu.java.security.hash.IMessageDigest;
import gnu.java.security.sig.ISignature;
/**
* A Factory class to instantiate RSA Signature classes.
*/
public class RSASignatureFactory
{
private static Set names;
/**
* Private constructor to enforce usage through Factory (class) methods.
*/
private RSASignatureFactory()
{
super();
}
/**
* Returns a new instance of an RSA Signature given its name. The name of an
* RSA Signature always starts with <code>rsa-</code>, followed by either
* <code>pss</code> or <code>pkcs1_v1.5</code>. An optional message digest
* name, to be used with the RSA signature may be specified by appending the
* hyphen chanaracter <code>-</code> followed by the canonical message digest
* algorithm name. When no message digest algorithm name is given, SHA-160 is
* used.
*
* @param name the composite RSA signature name.
* @return a new instance of an RSA Signature algorithm implementation.
* Returns <code>null</code> if the given name does not correspond to any
* supported RSA Signature encoding and message digest combination.
*/
public static final ISignature getInstance(String name)
{
if (name == null)
return null;
name = name.trim();
if (name.length() == 0)
return null;
name = name.toLowerCase();
if (! name.startsWith(Registry.RSA_SIG_PREFIX))
return null;
name = name.substring(Registry.RSA_SIG_PREFIX.length()).trim();
if (name.startsWith(Registry.RSA_PSS_ENCODING))
return getPSSSignature(name);
else if (name.startsWith(Registry.RSA_PKCS1_V1_5_ENCODING))
return getPKCS1Signature(name);
else
return null;
}
/**
* Returns a {@link Set} of names of <i>RSA</i> signatures supported by this
* <i>Factory</i>.
*
* @return a {@link Set} of RSA Signature algorithm names (Strings).
*/
public static synchronized final Set getNames()
{
if (names == null)
{
Set hashNames = HashFactory.getNames();
HashSet hs = new HashSet();
for (Iterator it = hashNames.iterator(); it.hasNext();)
{
String mdName = (String) it.next();
hs.add(Registry.RSA_PSS_SIG + "-" + mdName);
}
hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.MD2_HASH);
hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.MD5_HASH);
hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA160_HASH);
hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA256_HASH);
hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA384_HASH);
hs.add(Registry.RSA_PKCS1_V1_5_SIG + "-" + Registry.SHA512_HASH);
names = Collections.unmodifiableSet(hs);
}
return names;
}
private static final ISignature getPSSSignature(String name)
{
name = name.substring(Registry.RSA_PSS_ENCODING.length()).trim();
// remove the hyphen if found at the beginning
if (name.startsWith("-"))
name = name.substring(1).trim();
IMessageDigest md;
if (name.length() == 0)
md = HashFactory.getInstance(Registry.SHA160_HASH);
else
{
// check if there is such a hash
md = HashFactory.getInstance(name);
if (md == null)
return null;
}
ISignature result = new RSAPSSSignature(md, 0);
return result;
}
private static final ISignature getPKCS1Signature(String name)
{
name = name.substring(Registry.RSA_PKCS1_V1_5_ENCODING.length()).trim();
// remove the hyphen if found at the beginning
if (name.startsWith("-"))
name = name.substring(1).trim();
IMessageDigest md;
if (name.length() == 0)
md = HashFactory.getInstance(Registry.SHA160_HASH);
else
{
// check if there is such a hash
md = HashFactory.getInstance(name);
if (md == null)
return null;
}
ISignature result = new RSAPKCS1V1_5Signature(md);
return result;
}
}
| 33.870056 | 79 | 0.699917 |
2932b66146f1d6f5a3a3279f6dc20cefd652cec6 | 587 | package io.github.greyp9.arwo.core.xsd.instance;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
public class TypeInstances {
private final QName nameParent;
private final Collection<TypeInstance> instances;
public final QName getQNameParent() {
return nameParent;
}
public final Collection<TypeInstance> getTypeInstances() {
return instances;
}
public TypeInstances(final QName nameParent) {
this.nameParent = nameParent;
this.instances = new ArrayList<TypeInstance>();
}
}
| 24.458333 | 62 | 0.713799 |
e7b680f10ed8acef2d236e4f8eed31f51226da10 | 1,478 | /**
* Copyright 2022 Google LLC
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.grpc.service;
import com.google.cloud.spanner.v1.SpannerClient;
import com.google.spanner.v1.CreateSessionRequest;
import com.google.spanner.v1.DatabaseName;
import com.google.spanner.v1.Session;
/*
Manages spanner initializations and accesses.
*/
public class SpannerUtil {
/*
Initializes a {@link Session}.
*/
public static Session createSession(SpannerClient spannerClient) {
CreateSessionRequest request =
CreateSessionRequest.newBuilder().setDatabase(getDatabaseName().toString()).build();
return spannerClient.createSession(request);
}
/*
* Configures a project, instance and a database to connect in Spanner.
* Substitute <my_project_id> with the id of your Google project.
*/
public static DatabaseName getDatabaseName() {
return DatabaseName.of("<my_project_id>", "grpc-example", "grpc_example_db");
}
}
| 34.372093 | 99 | 0.747632 |
5efad04745a533570011e12cdd597e79dbab540f | 369 | package com.aditiva.ISO8583.builders;
import com.aditiva.ISO8583.builders.BaseMessageClassBuilder;
/**
* Created by aditiva on 18/04/01.
*/
public class GeneralMessageClassBuilder extends BaseMessageClassBuilder<GeneralMessageClassBuilder> {
public GeneralMessageClassBuilder(String version, String messageClass) {
super(version, messageClass);
}
} | 28.384615 | 101 | 0.785908 |
8bbb00beffb662dba9aefd96cb471e517c8efc4d | 426 | package vswe.stevescarts.containers.slots;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import javax.annotation.Nonnull;
public class SlotCartCrafter extends SlotFake {
public SlotCartCrafter(final IInventory iinventory, final int i, final int j, final int k) {
super(iinventory, i, j, k);
}
@Override
public boolean isItemValid(@Nonnull ItemStack itemstack) {
return true;
}
}
| 23.666667 | 93 | 0.779343 |
e90a0d451969e698dda049b4186693540651306f | 2,251 | package com.github.sejoslaw.vanillamagic2.common.networks;
import com.github.sejoslaw.vanillamagic2.common.registries.PlayerQuestProgressRegistry;
import net.minecraft.client.network.play.IClientPlayNetHandler;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkEvent;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Supplier;
/**
* @author Sejoslaw - https://github.com/Sejoslaw
*/
public class SSyncQuestsPacket extends SVMPacket {
private Set<String> playerQuests;
public SSyncQuestsPacket(PlayerEntity player) {
super(player);
this.playerQuests = PlayerQuestProgressRegistry.getPlayerQuests(player);
}
public void readPacketData(PacketBuffer buf) throws IOException {
super.readPacketData(buf);
int questsCount = buf.readInt();
this.playerQuests = new HashSet<>();
for (int i = 0; i < questsCount; ++i) {
this.playerQuests.add(buf.readString());
}
}
public void writePacketData(PacketBuffer buf) throws IOException {
super.writePacketData(buf);
buf.writeInt(this.playerQuests.size());
this.playerQuests.forEach(buf::writeString);
}
public void processPacket(IClientPlayNetHandler handler) {
sync(this);
}
public static void encode(SSyncQuestsPacket packet, PacketBuffer buf) {
try {
packet.writePacketData(buf);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SSyncQuestsPacket decode(PacketBuffer buf) {
SSyncQuestsPacket packet = new SSyncQuestsPacket(null);
try {
packet.readPacketData(buf);
} catch (IOException e) {
e.printStackTrace();
}
return packet;
}
public static void consume(SSyncQuestsPacket packet, Supplier<NetworkEvent.Context> buf) {
sync(packet);
}
private static void sync(SSyncQuestsPacket packet) {
PlayerQuestProgressRegistry.clearData(packet.playerName);
PlayerQuestProgressRegistry.setupPlayerData(packet.playerName, packet.playerQuests);
}
}
| 29.618421 | 94 | 0.692581 |
2fa8376826053b4809baabe09e410a52e2c1561d | 6,855 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute.v2017_12_01;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Describes a virtual machine scale set operating system disk.
*/
public class VirtualMachineScaleSetOSDisk {
/**
* The disk name.
*/
@JsonProperty(value = "name")
private String name;
/**
* Specifies the caching requirements. <br><br> Possible values
* are: <br><br> **None** <br><br> **ReadOnly**
* <br><br> **ReadWrite** <br><br> Default: **None
* for Standard storage. ReadOnly for Premium storage**. Possible values
* include: 'None', 'ReadOnly', 'ReadWrite'.
*/
@JsonProperty(value = "caching")
private CachingTypes caching;
/**
* Specifies whether writeAccelerator should be enabled or disabled on the
* disk.
*/
@JsonProperty(value = "writeAcceleratorEnabled")
private Boolean writeAcceleratorEnabled;
/**
* Specifies how the virtual machines in the scale set should be
* created.<br><br> The only allowed value is: **FromImage**
* \u2013 This value is used when you are using an image to create the
* virtual machine. If you are using a platform image, you also use the
* imageReference element described above. If you are using a marketplace
* image, you also use the plan element previously described. Possible
* values include: 'FromImage', 'Empty', 'Attach'.
*/
@JsonProperty(value = "createOption", required = true)
private DiskCreateOptionTypes createOption;
/**
* This property allows you to specify the type of the OS that is included
* in the disk if creating a VM from user-image or a specialized VHD.
* <br><br> Possible values are: <br><br>
* **Windows** <br><br> **Linux**. Possible values include:
* 'Windows', 'Linux'.
*/
@JsonProperty(value = "osType")
private OperatingSystemTypes osType;
/**
* Specifies information about the unmanaged user image to base the scale
* set on.
*/
@JsonProperty(value = "image")
private VirtualHardDisk image;
/**
* Specifies the container urls that are used to store operating system
* disks for the scale set.
*/
@JsonProperty(value = "vhdContainers")
private List<String> vhdContainers;
/**
* The managed disk parameters.
*/
@JsonProperty(value = "managedDisk")
private VirtualMachineScaleSetManagedDiskParameters managedDisk;
/**
* Get the name value.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name value.
*
* @param name the name value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withName(String name) {
this.name = name;
return this;
}
/**
* Get the caching value.
*
* @return the caching value
*/
public CachingTypes caching() {
return this.caching;
}
/**
* Set the caching value.
*
* @param caching the caching value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withCaching(CachingTypes caching) {
this.caching = caching;
return this;
}
/**
* Get the writeAcceleratorEnabled value.
*
* @return the writeAcceleratorEnabled value
*/
public Boolean writeAcceleratorEnabled() {
return this.writeAcceleratorEnabled;
}
/**
* Set the writeAcceleratorEnabled value.
*
* @param writeAcceleratorEnabled the writeAcceleratorEnabled value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withWriteAcceleratorEnabled(Boolean writeAcceleratorEnabled) {
this.writeAcceleratorEnabled = writeAcceleratorEnabled;
return this;
}
/**
* Get the createOption value.
*
* @return the createOption value
*/
public DiskCreateOptionTypes createOption() {
return this.createOption;
}
/**
* Set the createOption value.
*
* @param createOption the createOption value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withCreateOption(DiskCreateOptionTypes createOption) {
this.createOption = createOption;
return this;
}
/**
* Get the osType value.
*
* @return the osType value
*/
public OperatingSystemTypes osType() {
return this.osType;
}
/**
* Set the osType value.
*
* @param osType the osType value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withOsType(OperatingSystemTypes osType) {
this.osType = osType;
return this;
}
/**
* Get the image value.
*
* @return the image value
*/
public VirtualHardDisk image() {
return this.image;
}
/**
* Set the image value.
*
* @param image the image value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withImage(VirtualHardDisk image) {
this.image = image;
return this;
}
/**
* Get the vhdContainers value.
*
* @return the vhdContainers value
*/
public List<String> vhdContainers() {
return this.vhdContainers;
}
/**
* Set the vhdContainers value.
*
* @param vhdContainers the vhdContainers value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withVhdContainers(List<String> vhdContainers) {
this.vhdContainers = vhdContainers;
return this;
}
/**
* Get the managedDisk value.
*
* @return the managedDisk value
*/
public VirtualMachineScaleSetManagedDiskParameters managedDisk() {
return this.managedDisk;
}
/**
* Set the managedDisk value.
*
* @param managedDisk the managedDisk value to set
* @return the VirtualMachineScaleSetOSDisk object itself.
*/
public VirtualMachineScaleSetOSDisk withManagedDisk(VirtualMachineScaleSetManagedDiskParameters managedDisk) {
this.managedDisk = managedDisk;
return this;
}
}
| 28.094262 | 114 | 0.646973 |
70d0906399f8583a2b9feec5a9103870ba83765d | 801 | package demands;
import enums.DeliverySchema;
import java.time.LocalDate;
// Entity
public class DemandReadModelEntity {
private LocalDate atDay;
private String productRefNo;
private DeliverySchema deliverySchema;
private long level;
public DemandReadModelEntity(LocalDate atDay, String productRefNo, DeliverySchema deliverySchema, long level) {
this.atDay = atDay;
this.productRefNo = productRefNo;
this.deliverySchema = deliverySchema;
this.level = level;
}
public LocalDate getDay() {
return atDay;
}
public String getProductRefNo() {
return productRefNo;
}
public DeliverySchema getDeliverySchema() {
return deliverySchema;
}
public long getLevel() {
return level;
}
}
| 21.648649 | 115 | 0.679151 |
6c969e43d2d4d52af9be22cbd64eb87e9a23af05 | 5,108 | package org.apereo.cas.adaptors.duo.authn;
import org.apereo.cas.authentication.AuthenticationHandlerExecutionResult;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.MultifactorAuthenticationCredential;
import org.apereo.cas.authentication.handler.support.AbstractPreAndPostProcessingAuthenticationHandler;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.services.ServicesManager;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import javax.security.auth.login.FailedLoginException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
/**
* Authenticate CAS credentials against Duo Security.
*
* @author Misagh Moayyed
* @author Dmitriy Kopylenko
* @since 4.2
*/
@Slf4j
public class DuoSecurityAuthenticationHandler extends AbstractPreAndPostProcessingAuthenticationHandler {
private final DuoSecurityMultifactorAuthenticationProvider provider;
public DuoSecurityAuthenticationHandler(final String name, final ServicesManager servicesManager,
final PrincipalFactory principalFactory,
final DuoSecurityMultifactorAuthenticationProvider provider,
final Integer order) {
super(name, servicesManager, principalFactory, order);
this.provider = provider;
}
/**
* Do an out of band request using the DuoWeb api (encapsulated in DuoSecurityAuthenticationService)
* to the hosted duo service. If it is successful
* it will return a String containing the username of the successfully authenticated user, but if not - will
* return a blank String or null.
*
* @param credential Credential to authenticate.
* @return the result of this handler
* @throws GeneralSecurityException general security exception for errors
*/
@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException {
if (credential instanceof DuoSecurityDirectCredential) {
LOGGER.debug("Attempting to directly authenticate credential against Duo");
return authenticateDuoApiCredential(credential);
}
return authenticateDuoCredential(credential);
}
private AuthenticationHandlerExecutionResult authenticateDuoApiCredential(final Credential credential) throws FailedLoginException {
try {
val duoAuthenticationService = provider.getDuoAuthenticationService();
val creds = DuoSecurityDirectCredential.class.cast(credential);
if (duoAuthenticationService.authenticate(creds).getKey()) {
val principal = creds.getAuthentication().getPrincipal();
LOGGER.debug("Duo has successfully authenticated [{}]", principal.getId());
return createHandlerResult(credential, principal, new ArrayList<>(0));
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
throw new FailedLoginException("Duo authentication has failed");
}
private AuthenticationHandlerExecutionResult authenticateDuoCredential(final Credential credential) throws FailedLoginException {
try {
val duoCredential = (DuoSecurityCredential) credential;
if (!duoCredential.isValid()) {
throw new GeneralSecurityException("Duo credential validation failed. Ensure a username "
+ " and the signed Duo response is configured and passed. Credential received: " + duoCredential);
}
val duoAuthenticationService = provider.getDuoAuthenticationService();
val duoVerifyResponse = duoAuthenticationService.authenticate(duoCredential).getValue();
LOGGER.debug("Response from Duo verify: [{}]", duoVerifyResponse);
val primaryCredentialsUsername = duoCredential.getUsername();
val isGoodAuthentication = duoVerifyResponse.equals(primaryCredentialsUsername);
if (isGoodAuthentication) {
LOGGER.info("Successful Duo authentication for [{}]", primaryCredentialsUsername);
val principal = this.principalFactory.createPrincipal(duoVerifyResponse);
return createHandlerResult(credential, principal, new ArrayList<>(0));
}
throw new FailedLoginException("Duo authentication username "
+ primaryCredentialsUsername + " does not match Duo response: " + duoVerifyResponse);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new FailedLoginException(e.getMessage());
}
}
@Override
public boolean supports(final Credential credential) {
if (credential instanceof MultifactorAuthenticationCredential) {
val id = ((MultifactorAuthenticationCredential) credential).getProviderId();
return provider.validateId(id);
}
return false;
}
}
| 46.436364 | 136 | 0.702428 |
7a7d824b1d06a0856dd180c12e58131b4f5edd32 | 5,161 | /*
* (C) Copyright 2006-2019 Nuxeo (http://nuxeo.com/) and others.
*
* 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.
*
*
* Contributors:
* anechaev
*/
package org.nuxeo.ai.rekognition.listeners;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nuxeo.ai.enrichment.EnrichmentMetadata;
import org.nuxeo.ai.services.DocMetadataService;
import org.nuxeo.ecm.core.api.CoreInstance;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.validation.DocumentValidationException;
import org.nuxeo.ecm.core.event.Event;
import org.nuxeo.ecm.core.event.EventBundle;
import org.nuxeo.ecm.core.event.EventContext;
import org.nuxeo.ecm.core.event.PostCommitEventListener;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.kv.KeyValueService;
import org.nuxeo.runtime.kv.KeyValueStore;
import org.nuxeo.runtime.transaction.TransactionHelper;
import com.amazonaws.services.rekognition.model.AmazonRekognitionException;
/**
* Base class for listening notifications on detect results
*/
public abstract class BaseAsyncResultListener implements PostCommitEventListener {
private static final Logger log = LogManager.getLogger(BaseAsyncResultListener.class);
public static final String JOB_ID_CTX_KEY = "jobId";
@Override
public void handleEvent(EventBundle eb) {
eb.forEach(this::handleEvent);
}
protected void handleEvent(Event event) {
EventContext ctx = event.getContext();
if (ctx == null) {
return;
}
String jobId = (String) ctx.getProperties().get(JOB_ID_CTX_KEY);
log.debug("Received result for {}; status: {}", jobId, event.getName());
if (getFailureEventName().equals(event.getName())) {
log.info("Async Rekognition job failed for id " + jobId);
return;
}
byte[] bytes = getStore().get(jobId);
if (bytes == null) {
log.error("Could not find data for JobId " + jobId);
return;
}
getStore().setTTL(jobId, 1); // release key
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
@SuppressWarnings("unchecked")
Map<String, Serializable> params = (Map<String, Serializable>) ois.readObject();
Collection<EnrichmentMetadata> enrichment;
enrichment = getEnrichmentMetadata(jobId, params);
enrichment.forEach(this::saveMetadata);
} catch (IOException | ClassNotFoundException e) {
log.error("An error occurred during event process {}, for event {}", e.getMessage(), event.getName());
} catch (AmazonRekognitionException e) {
log.error("An error occurred at AWS Rekognition {}, for event {}", e.getMessage(), event.getName());
}
}
protected void saveMetadata(EnrichmentMetadata metadata) {
TransactionHelper.runInTransaction(() -> CoreInstance.doPrivileged(metadata.context.repositoryName, session -> {
DocMetadataService docMetadataService = Framework.getService(DocMetadataService.class);
DocumentModel doc = docMetadataService.saveEnrichment(session, metadata);
if (doc != null) {
try {
session.saveDocument(doc);
} catch (DocumentValidationException e) {
log.warn("Failed to save document enrichment data for {}.", metadata.context.documentRef, e);
}
} else {
log.debug("Failed to save enrichment for document {}.", metadata.context.documentRef);
}
}));
}
protected KeyValueStore getStore() {
KeyValueService kvs = Framework.getService(KeyValueService.class);
return kvs.getKeyValueStore("default");
}
/**
* @return {@link String} name of successful event
*/
protected abstract String getSuccessEventName();
/**
* @return {@link String} name of failure event
*/
protected abstract String getFailureEventName();
/**
* @param jobId reference for AWS Rekognition Job
* @param params additional parameters
* @return A {@link Collection} of {@link EnrichmentMetadata} for given job id
*/
protected abstract Collection<EnrichmentMetadata> getEnrichmentMetadata(String jobId,
Map<String, Serializable> params);
}
| 38.22963 | 120 | 0.683007 |
36b769f9c503f82325cbbfa8d628b1a7f207d186 | 9,089 | package com.clutcher.comments.gui;
import com.clutcher.comments.configuration.HighlightTokenConfiguration;
import com.clutcher.comments.highlighter.HighlightTokenType;
import com.intellij.CommonBundle;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.JBColor;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.UIBundle;
import com.intellij.ui.table.JBTable;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.intellij.util.ui.components.BorderLayoutPanel;
import com.intellij.xml.util.XmlStringUtil;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public class CommentTokensConfigurationPanel extends BorderLayoutPanel implements SearchableConfigurable, Configurable.NoScroll {
private static final HighlightTokenConfiguration tokenConfiguration = ApplicationManager.getApplication().getService(HighlightTokenConfiguration.class);
private final JBTable tokenTable;
private ListTableModel<Pair<HighlightTokenType, String>> tableModel;
private static final ColumnInfo<Pair<HighlightTokenType, String>, String> TYPE_COLUMN = new ColumnInfo<Pair<HighlightTokenType, String>, String>("Type") {
@Override
public @Nullable String valueOf(Pair<HighlightTokenType, String> tokenTypeStringPair) {
return tokenTypeStringPair.first.toString();
}
};
private static final ColumnInfo<Pair<HighlightTokenType, String>, String> NAME_COLUMN = new ColumnInfo<Pair<HighlightTokenType, String>, String>("Token") {
@Override
public @Nullable String valueOf(Pair<HighlightTokenType, String> tokenTypeStringPair) {
return tokenTypeStringPair.second;
}
};
private JLabel reopenLabel;
private final JCheckBox plainFilesHighlighting;
public CommentTokensConfigurationPanel() {
super(0, 20);
reopenLabel = new JLabel(XmlStringUtil.wrapInHtml("Reopen setting window to see new tokens on Color settings page (https://youtrack.jetbrains.com/issue/IDEA-226087)"));
reopenLabel.setForeground(JBColor.RED);
tokenTable = new JBTable();
tokenTable.getEmptyText().setText("No tokens defined");
plainFilesHighlighting = new JCheckBox("Enable comment highlighting in Plain text files.");
reset();
BorderLayoutPanel tokensTablePanel = createTokensTablePanel();
this.addToTop(plainFilesHighlighting);
this.addToCenter(tokensTablePanel);
}
@NotNull
private BorderLayoutPanel createTokensTablePanel() {
var tableLabel = new JLabel(XmlStringUtil.wrapInHtml("Custom comment/keyword tokens would be used to highlight comments/keywords based on color settings"));
var tokensTablePanel = new BorderLayoutPanel(0, 5);
tokensTablePanel
.addToTop(tableLabel)
.addToCenter(
ToolbarDecorator.createDecorator(tokenTable)
.setAddAction(button -> {
AddUpdateCommentTokenDialog dlg = new AddUpdateCommentTokenDialog();
dlg.setTitle("Add comment token");
if (dlg.showAndGet()) {
HighlightTokenType highlightTokenType = dlg.getCustomTokenType();
String tokenValue = dlg.getToken();
tableModel.addRow(Pair.create(highlightTokenType, tokenValue));
}
})
.setRemoveAction(button -> {
int returnValue = Messages.showOkCancelDialog("Delete selected token?",
UIBundle.message("delete.dialog.title"),
ApplicationBundle.message("button.delete"),
CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon());
if (returnValue == Messages.OK) {
tableModel.removeRow(tokenTable.getSelectedRow());
}
})
.setEditAction(button -> {
int selectedRow = tokenTable.getSelectedRow();
Pair<HighlightTokenType, String> value = tableModel.getItem(selectedRow);
AddUpdateCommentTokenDialog dlg = new AddUpdateCommentTokenDialog();
dlg.setTitle("Edit comment token");
dlg.setCustomTokenType(value.first);
dlg.setToken(value.second);
if (dlg.showAndGet()) {
final HighlightTokenType editedHighlightTokenType = dlg.getCustomTokenType();
final String editedToken = dlg.getToken();
tableModel.removeRow(selectedRow);
tableModel.insertRow(selectedRow, Pair.create(editedHighlightTokenType, editedToken));
}
})
.setButtonComparator("Add", "Edit", "Remove")
.disableUpDownActions()
.createPanel()
);
return tokensTablePanel;
}
@Override
public void apply() {
add(reopenLabel, BorderLayout.SOUTH);
Map<HighlightTokenType, List<String>> updatedTokens = getTokenMapFromModel(tableModel);
tokenConfiguration.setCustomTokens(updatedTokens);
tokenConfiguration.setPlainTextFileHighlightEnabled(plainFilesHighlighting.isSelected());
}
@Override
public boolean isModified() {
boolean savedValue = tokenConfiguration.isPlainTextFileHighlightEnabled();
boolean currentValue = plainFilesHighlighting.isSelected();
if (currentValue != savedValue) {
return true;
}
Map<HighlightTokenType, List<String>> updatedTokens = getTokenMapFromModel(tableModel);
Map<HighlightTokenType, Collection<String>> allTokens = tokenConfiguration.getAllTokens();
for (HighlightTokenType value : HighlightTokenType.values()) {
if (!updatedTokens.get(value).equals(allTokens.get(value))) {
return true;
}
}
return false;
}
@Override
public void reset() {
tableModel = new ListTableModel<>(TYPE_COLUMN, NAME_COLUMN);
Map<HighlightTokenType, Collection<String>> allTokens = tokenConfiguration.getAllTokens();
for (Map.Entry<HighlightTokenType, Collection<String>> entry : allTokens.entrySet()) {
HighlightTokenType tokenType = entry.getKey();
for (String token : entry.getValue()) {
tableModel.addRow(Pair.create(tokenType, token));
}
}
tokenTable.setModel(tableModel);
plainFilesHighlighting.setSelected(tokenConfiguration.isPlainTextFileHighlightEnabled());
}
private Map<HighlightTokenType, List<String>> getTokenMapFromModel(ListTableModel<Pair<HighlightTokenType, String>> tableModel) {
Map<HighlightTokenType, List<String>> tokenMap = new EnumMap<>(HighlightTokenType.class);
for (HighlightTokenType value : HighlightTokenType.values()) {
tokenMap.put(value, new ArrayList<>());
}
for (Pair<HighlightTokenType, String> item : tableModel.getItems()) {
List<String> mapValueList = tokenMap.get(item.first);
mapValueList.add(item.second);
}
return tokenMap;
}
@Override
@Nls
public String getDisplayName() {
return "Custom comment/keyword tokens";
}
@Override
@NotNull
public String getId() {
return "comment.highlighter.token.configuration";
}
@Override
public JComponent createComponent() {
return this;
}
}
| 43.697115 | 176 | 0.599186 |
6abf247666ab47b27e96d2b4307414972740e382 | 511 | import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* Title: Server
* Descrption: TODO
* Date:2019-12-15 23:09
* Email:[email protected]
* Company:www.j2ee.app
*
* @author R4v3zn
* @version 1.0.0
*/
public interface Server extends Remote {
/**
* 执行命令
* @param cmd 执行命令
* @param clientPwd 连接密码
* @param clientOs 客户端操作系统
* @return
* @throws RemoteException
*/
String execCmd(String cmd, String clientPwd, String clientOs) throws RemoteException;
}
| 19.653846 | 89 | 0.655577 |
5b2271eb00be18779436c429dab740a50d00a549 | 2,742 | /*
* Copyright(c) 2019 Nippon Telegraph and Telephone Corporation
*/
package msf.ecmm.ope.receiver.pojo;
import java.util.ArrayList;
import msf.ecmm.ope.execute.OperationType;
import msf.ecmm.ope.receiver.pojo.parts.VlanIfsCreateL3VlanIf;
/**
* L3VLAN IF Batch Generation.
*/
public class BulkCreateL3VlanIf extends AbstractRestMessage {
/** Information of VLAN IF to be controlled. */
private ArrayList<VlanIfsCreateL3VlanIf> vlanIfs = new ArrayList<VlanIfsCreateL3VlanIf>();
/** Unique parameter for each slice ID. */
private Integer vrfId = null;
/** Plane where the slice belongs to. */
private Integer plane = null;
/**
* Constructor.
*/
public BulkCreateL3VlanIf() {
super();
}
/**
* Getting information of VLAN IF to be controlled.
*
* @return list information of CP to be controlled
*/
public ArrayList<VlanIfsCreateL3VlanIf> getVlanIfs() {
return vlanIfs;
}
/**
* Setting information of VLAN IF to be controlled.
*
* @param vlanIfsCreateL3VlanIf
* list information of CP to be controlled
*/
public void setVlanIfs(ArrayList<VlanIfsCreateL3VlanIf> vlanIfsCreateL3VlanIf) {
this.vlanIfs = vlanIfsCreateL3VlanIf;
}
/**
* Getting unique parameter for each slice ID.
*
* @return unique parameter for each slice ID
*/
public Integer getVrfId() {
return vrfId;
}
/**
* Setting unique parameter for each slice ID.
*
* @param vrfId
* unique parameter for each slice ID
*/
public void setVrfId(Integer vrfId) {
this.vrfId = vrfId;
}
/**
* Getting plane where the slice belongs to.
*
* @return plane where the slice belongs to
*/
public Integer getPlane() {
return plane;
}
/**
* Setting plane where the slice belongs to.
*
* @param plane
* plane where the slice belongs to
*/
public void setPlane(Integer plane) {
this.plane = plane;
}
/**
* Stringizing Instance.
*
* @return instance string
*/
@Override
public String toString() {
return "BulkCreateL3VlanIf [vlanIfs=" + vlanIfs + ", vrfId=" + vrfId + ", plane=" + plane + "]";
}
/**
* Input Parameter Check.
*
* @param ope
* operation type
* @throws CheckDataException
* input check error
*/
public void check(OperationType ope) throws CheckDataException {
if (vlanIfs.isEmpty()) {
throw new CheckDataException();
} else {
for (VlanIfsCreateL3VlanIf vlanIfsCreateL3VlanIf : vlanIfs) {
vlanIfsCreateL3VlanIf.check(ope);
}
}
if (vrfId == null) {
throw new CheckDataException();
}
if (plane == null) {
throw new CheckDataException();
}
}
}
| 21.761905 | 100 | 0.641867 |
2d736011a69fe538dd707c06e848eb36820920ea | 307 | package me.jtghawk137.hwk.block;
import me.jtghawk137.hwk.Parameter;
public class Catch extends Block
{
Parameter[] params;
public Catch(Block superBlock, Parameter[] params)
{
super(superBlock);
this.params = params;
}
@Override
public void run()
{
}
}
| 14.619048 | 54 | 0.628664 |
405e65b56c514fb8437a7d78dfdd4c4761dc0927 | 2,317 | package org.apache.harmony.security.x509;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* 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.
* #L%
*/
@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public final class Extension
{
// Fields
public static final boolean CRITICAL = true;
public static final boolean NON_CRITICAL = false;
protected ExtensionValue extnValueObject;
public static final org.apache.harmony.security.asn1.ASN1Sequence ASN1 = null;
// Constructors
public Extension(java.lang.String arg1, boolean arg2, ExtensionValue arg3){
}
public Extension(java.lang.String arg1, boolean arg2, byte [] arg3){
}
public Extension(int [] arg1, boolean arg2, byte [] arg3){
}
public Extension(java.lang.String arg1, byte [] arg2){
}
public Extension(int [] arg1, byte [] arg2){
}
private Extension(int [] arg1, boolean arg2, byte [] arg3, byte [] arg4, byte [] arg5, ExtensionValue arg6){
}
// Methods
public boolean equals(java.lang.Object arg1){
return false;
}
public int hashCode(){
return 0;
}
public byte [] getEncoded(){
return (byte []) null;
}
public void dumpValue(java.lang.StringBuilder arg1, java.lang.String arg2){
}
public java.lang.String getExtnID(){
return (java.lang.String) null;
}
public boolean getCritical(){
return false;
}
public byte [] getExtnValue(){
return (byte []) null;
}
public byte [] getRawExtnValue(){
return (byte []) null;
}
public ExtensionValue getDecodedExtensionValue() throws java.io.IOException{
return (ExtensionValue) null;
}
public KeyUsage getKeyUsageValue(){
return (KeyUsage) null;
}
public BasicConstraints getBasicConstraintsValue(){
return (BasicConstraints) null;
}
}
| 26.329545 | 110 | 0.694864 |
c70149958e3f24277a8b0a1a583833b0cc894f24 | 438 | package uk.gov.hmcts.reform.divorce.orchestration.framework.workflow.task;
import java.util.Optional;
public interface TaskContext {
void setTaskFailed(boolean status);
boolean hasTaskFailed();
void setTransientObject(String key, Object data);
<T> T getTransientObject(String key);
<T> Optional<T> getTransientObjectOptional(String key);
<T> T computeTransientObjectIfAbsent(String key, T defaultVal);
}
| 20.857143 | 74 | 0.751142 |
6669c91cb5a611bb5a96e9a626753a218d8988c3 | 1,144 | /*
Copyright 2016 Goldman Sachs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.gs.fw.common.mithra.test;
import com.gs.fw.common.mithra.databasetype.SybaseDatabaseType;
public class SybaseBcpTestWithCustomTempDB
extends SybaseBcpTest
{
private static class SybaseDatabaseTypeWithCustomTempDb
extends SybaseDatabaseType
{
@Override
public String getTempDbSchemaName()
{
return "mithra_qa.";
}
}
@Override
public SybaseDatabaseType getSybaseDatabaseType()
{
return new SybaseDatabaseTypeWithCustomTempDb();
}
}
| 28.6 | 66 | 0.710664 |
a880547ee840f8447d339ce48901975c9b9e6537 | 4,114 | package com.egbert.rconcise.internal;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.LogStrategy;
import com.orhanobut.logger.LogcatLogStrategy;
import static com.egbert.rconcise.internal.Utils.checkNotNull;
/**
* 自定义logger日志边框(取消上下边框)
* Created by Egbert on 3/8/2019.
*/
public class NoBorderFormatStrategy implements FormatStrategy {
private static final char HORIZONTAL_LINE = '│';
/**
* Android's max limit for a log entry is ~4076 bytes,
* so 4000 bytes is used as chunk size since default charset
* is UTF-8
*/
private static final int CHUNK_SIZE = 4000;
private final boolean showThreadInfo;
@NonNull private final LogStrategy logStrategy;
@Nullable private final String tag;
private NoBorderFormatStrategy(@NonNull NoBorderFormatStrategy.Builder builder) {
checkNotNull(builder);
showThreadInfo = builder.showThreadInfo;
logStrategy = builder.logStrategy;
tag = builder.tag;
}
@NonNull public static NoBorderFormatStrategy.Builder newBuilder() {
return new NoBorderFormatStrategy.Builder();
}
@Override
public void log(int priority, @Nullable String onceOnlyTag, @NonNull String message) {
checkNotNull(message);
String tag = formatTag(onceOnlyTag);
logHeaderContent(priority, tag);
//get bytes of message with system's default charset (which is UTF-8 for Android)
byte[] bytes = message.getBytes();
int length = bytes.length;
if (length <= CHUNK_SIZE) {
logContent(priority, tag, message);
return;
}
for (int i = 0; i < length; i += CHUNK_SIZE) {
int count = Math.min(length - i, CHUNK_SIZE);
//create a new String with system's default charset (which is UTF-8 for Android)
logContent(priority, tag, new String(bytes, i, count));
}
}
@SuppressWarnings("StringBufferReplaceableByString")
private void logHeaderContent(int logType, @Nullable String tag) {
// StackTraceElement[] trace = Thread.currentThread().getStackTrace();
if (showThreadInfo) {
logChunk(logType, tag, HORIZONTAL_LINE + " Thread: " + Thread.currentThread().getName());
}
}
private void logContent(int logType, @Nullable String tag, @NonNull String chunk) {
checkNotNull(chunk);
String[] lines = chunk.split(System.getProperty("line.separator"));
for (String line : lines) {
logChunk(logType, tag, HORIZONTAL_LINE + " " + line);
}
}
private void logChunk(int priority, @Nullable String tag, @NonNull String chunk) {
checkNotNull(chunk);
logStrategy.log(priority, tag, chunk);
}
@Nullable private String formatTag(@Nullable String tag) {
if (!TextUtils.isEmpty(tag) && !this.tag.equals(tag)) {
return this.tag + "-" + tag;
}
return this.tag;
}
public static class Builder {
boolean showThreadInfo = true;
@Nullable LogStrategy logStrategy;
@Nullable String tag = "PRETTY_LOGGER";
private Builder() {
}
@NonNull public NoBorderFormatStrategy.Builder showThreadInfo(boolean val) {
showThreadInfo = val;
return this;
}
@NonNull public NoBorderFormatStrategy.Builder logStrategy(@Nullable LogStrategy val) {
logStrategy = val;
return this;
}
@NonNull public NoBorderFormatStrategy.Builder tag(@Nullable String tag) {
this.tag = tag;
return this;
}
@NonNull public NoBorderFormatStrategy build() {
if (logStrategy == null) {
logStrategy = new LogcatLogStrategy();
}
return new NoBorderFormatStrategy(this);
}
}
}
| 33.447154 | 102 | 0.622509 |
be3a90d09176888bedbfcb9e22944268ca9a17c5 | 2,546 | package com.ttz.taungthuzay.photoview.view;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.view.GestureDetector;
import android.view.View;
import android.widget.ImageView;
public interface IPhotoView {
public static final float DEFAULT_MAX_SCALE = 3.0f;
public static final float DEFAULT_MID_SCALE = 1.75f;
public static final float DEFAULT_MIN_SCALE = 1.0f;
public static final int DEFAULT_ZOOM_DURATION = 200;
boolean canZoom();
RectF getDisplayRect();
boolean setDisplayMatrix(Matrix finalMatrix);
Matrix getDisplayMatrix();
@Deprecated
float getMinScale();
@Deprecated
void setMinScale(float minScale);
float getMinimumScale();
void setMinimumScale(float minimumScale);
@Deprecated
float getMidScale();
@Deprecated
void setMidScale(float midScale);
float getMediumScale();
void setMediumScale(float mediumScale);
@Deprecated
float getMaxScale();
@Deprecated
void setMaxScale(float maxScale);
float getMaximumScale();
void setMaximumScale(float maximumScale);
float getScale();
void setScale(float scale);
ImageView.ScaleType getScaleType();
void setScaleType(ImageView.ScaleType scaleType);
void setAllowParentInterceptOnEdge(boolean allow);
void setScaleLevels(float minimumScale, float mediumScale, float maximumScale);
void setOnLongClickListener(View.OnLongClickListener listener);
void setOnMatrixChangeListener(PhotoViewAttacher.OnMatrixChangedListener listener);
PhotoViewAttacher.OnPhotoTapListener getOnPhotoTapListener();
void setOnPhotoTapListener(PhotoViewAttacher.OnPhotoTapListener listener);
void setRotationTo(float rotationDegree);
void setRotationBy(float rotationDegree);
PhotoViewAttacher.OnViewTapListener getOnViewTapListener();
void setOnViewTapListener(PhotoViewAttacher.OnViewTapListener listener);
void setScale(float scale, boolean animate);
void setScale(float scale, float focalX, float focalY, boolean animate);
void setZoomable(boolean zoomable);
void setPhotoViewRotation(float rotationDegree);
Bitmap getVisibleRectangleBitmap();
void setZoomTransitionDuration(int milliseconds);
IPhotoView getIPhotoViewImplementation();
void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener);
void setOnScaleChangeListener(PhotoViewAttacher.OnScaleChangeListener onScaleChangeListener);
}
| 24.960784 | 97 | 0.771799 |
dcbe68e1abcdee3764ea0e6a87f92de821c0c0b5 | 2,497 | package io.opensphere.core.common.util;
import java.awt.Color;
import java.awt.Transparency;
import java.awt.image.IndexColorModel;
import java.awt.image.RenderedImage;
/**
* The PaletteBuilder this class extends implements the octree quantization
* method as it is described in the "Graphics Gems" (ISBN 0-12-286166-3, Chapter
* 4, pages 297-293)
*/
public class PaletteBuilderSizable extends PaletteBuilder
{
/**
* Create the builder for the given image and palette size.
*
* @param src The source image for the builder.
* @param paletteSize The maximum number of colors for the image.
*/
public PaletteBuilderSizable(RenderedImage src, int paletteSize)
{
super(src, paletteSize);
buildPalette();
}
/**
* Get the color table and the pixel index into the table for the image with
* which this builder was initialized.
*
* @param colorTab The array to fill with the color table entries.
* @param indexedPixels The array to fill with the indexed values of the
* pixels into the color table.
*/
public void getColorTableAndIndexedPixels(byte[] colorTab, byte[] indexedPixels)
{
IndexColorModel icm = getIndexColorModel();
int[] rgbs = new int[currSize];
icm.getRGBs(rgbs);
for (int i = 0; i < rgbs.length; ++i)
{
Color col = new Color(rgbs[i], false);
colorTab[i * 3] = (byte)col.getRed();
colorTab[i * 3 + 1] = (byte)col.getGreen();
colorTab[i * 3 + 2] = (byte)col.getBlue();
}
for (int x = 0; x < src.getWidth(); ++x)
{
for (int y = 0; y < src.getHeight(); ++y)
{
Color aColor = getSrcColor(x, y);
indexedPixels[y * src.getWidth() + x] = (byte)findColorIndex(root, aColor);
}
}
}
@Override
public RenderedImage getIndexedImage()
{
return super.getIndexedImage();
}
/**
* Get the color for the given location in the source image.
*
* @param x The x coordinate location in the source image.
* @param y The y coordinate location in the source image.
* @return The color at the given location in the source image.
*/
protected Color getSrcColor(int x, int y)
{
int argb = srcColorModel.getRGB(srcRaster.getDataElements(x, y, null));
return new Color(argb, transparency != Transparency.OPAQUE);
}
}
| 32.428571 | 91 | 0.614738 |
f71455fd0bb09af55ba8fccd774a44a893549100 | 1,552 | /*
* Decompiled with CFR 0_113.
*/
package modpow;
import gov.nasa.jpf.symbc.Debug;
import java.math.BigInteger;
import java.util.Random;
public class ModPow {
//public static final int MAX_LEN = 20;
public static BigInteger modPowNoNoise(BigInteger base, BigInteger exponent,
BigInteger modulus) {
BigInteger s = BigInteger.valueOf(1);
int width = exponent.bitLength();
System.out.println("!!! width "+width);
//if(width>4) return null;
int i = 0;
while (i < width) {
//Debug.assume(width <= MAX_LEN);
s = s.multiply(s).mod(modulus);
if (exponent.testBit(width - i - 1)) {
System.out.println("test");
s = OptimizedMultiplier.fastMultiply(s, base).mod(modulus);
}
++i;
}
return s;
}
public static BigInteger modPow(final BigInteger base, final BigInteger exponent, final BigInteger modulus) {
BigInteger s = BigInteger.valueOf(1L);
final int width = exponent.bitLength();
int i = 0;
while (i < width) {
final Random randomNumberGeneratorInstance = new Random();
while (i < width && randomNumberGeneratorInstance.nextDouble() < 0.5) {
while (i < width && randomNumberGeneratorInstance.nextDouble() < 0.5) {
s = s.multiply(s).mod(modulus);
if (exponent.testBit(width - i - 1)) {
s = OptimizedMultiplier.fastMultiply(s, base).mod(modulus);
}
++i;
}
}
}
return s;
}
}
| 27.714286 | 110 | 0.588273 |
2f356db67850384049dffade4667a3c34e966195 | 3,724 | /*
* User.java
*
* 1.0
*
* 3/12/2014
*
* Copyright
*/
package models;
// model
import javax.persistence.*;
import play.db.ebean.*;
import com.avaje.ebean.*;
// added
import play.data.format.*; // date format
import play.data.validation.*; // constraints
import play.libs.Crypto; // crypt AES
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.*;
/**
* This class represent a user model
* @author Giovanni Alberto García
* @version 1.0
*/
@Entity
@Table(name="users") //user is reserved in postgres
public class User extends Model {
@Id
public Long id;
@Constraints.Required(message="validation.required")
@Constraints.Email(message="validation.email")
@Constraints.MaxLength(value=100,message="validation.maxLength")
@Column(unique=true, nullable=false, length=100)
public String email;
@Constraints.MinLength(value=8, message="validation.minLength")
@Constraints.MaxLength(value=40, message="validation.maxLength")
@Column(nullable=false, length=128)
@JsonIgnore
public String password;
public String photo;
public Date birth;
@JsonIgnore
public Date lastSignIn;
// second part of registration
@JsonIgnore
public boolean isDesactive;
@Constraints.Required(message="validation.required")
@Constraints.MaxLength(value=400,message="validation.maxLength")
@Column(columnDefinition = "varchar(400)")
public String description;
@Constraints.Required(message="validation.required")
@Constraints.MaxLength(value=30,message="validation.maxLength")
@Column(columnDefinition = "varchar(30)")
public String username;
@Constraints.Required(message="validation.required")
@Constraints.MaxLength(value=10,message="validation.maxLength")
@Column(columnDefinition = "varchar(10)")
@Constraints.Pattern(value="[0-9]{5,10}")
public String mobile;
@Constraints.Required(message="validation.required")
@Constraints.MaxLength(value=100,message="validation.maxLength")
@Column(columnDefinition = "varchar(100)")
public String residence;
@Constraints.Required(message="validation.required")
@Constraints.MaxLength(value=400,message="validation.maxLength")
@Column(columnDefinition = "varchar(400)")
public String interests;
@Constraints.Required(message="validation.required")
public int preference;
@Constraints.Required(message="validation.required")
public int relationship;
@Constraints.Required(message="validation.required")
public int perversion;
@Constraints.Required(message="validation.required")
public int gender;
@Constraints.Required(message="validation.required")
@Constraints.MaxLength(value=400,message="validation.maxLength")
@Column(columnDefinition = "varchar(400)")
public String whishes;
/**
* This constructor cypher the password to store in database
* @param email The user's email
* @param password The user's password
*/
public User(String email, String password, Date birth){
this.email = email;
setDecryptedPassword(password);
this.birth=birth;
}
/*
* This is used to execute queries
*/
public static Finder<Long,User> find = new Finder<Long,User>(
Long.class, User.class
);
/**
* This method is used to cypher a password and assign it to user
* @param password The new desired password in plain text
*/
public void setDecryptedPassword(String password){
this.password = new Crypto().encryptAES(password);
}
/**
* This method is used to obtain the current password in plain text
* @return A string in plain text representing the user's password
*/
@JsonIgnore
public String getDecryptedPassword(){
return new Crypto().decryptAES(password);
}
} | 26.791367 | 68 | 0.730397 |
8e9e68bd9ba697e22a9cffef004803fe3ba357af | 5,060 | /*
* The MIT License (MIT)
*
* FXGL - JavaFX Game Library
*
* Copyright (c) 2015-2017 AlmasB ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.almasb.fxglgames.pacman.control;
import com.almasb.fxgl.app.FXGL;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.entity.components.BoundingBoxComponent;
import com.almasb.fxgl.entity.components.PositionComponent;
import com.almasb.fxgl.entity.components.RotationComponent;
import com.almasb.fxgl.entity.components.ViewComponent;
import com.almasb.fxgl.extra.ai.pathfinding.AStarGrid;
import com.almasb.fxgl.extra.ai.pathfinding.NodeState;
import com.almasb.fxglgames.pacman.PacmanApp;
import com.almasb.fxglgames.pacman.PacmanType;
import javafx.animation.FadeTransition;
import javafx.util.Duration;
import java.util.List;
import java.util.Random;
/**
* TODO: merge with MoveControl
*
* @author Almas Baimagambetov ([email protected])
*/
public class PlayerControl extends Component {
private PositionComponent position;
private BoundingBoxComponent bbox;
private ViewComponent view;
private RotationComponent rotation;
private MoveDirection moveDir = MoveDirection.UP;
public MoveDirection getMoveDirection() {
return moveDir;
}
private double speed = 0;
@Override
public void onUpdate(double tpf) {
speed = tpf * 60;
if (position.getX() < 0) {
position.setX(PacmanApp.BLOCK_SIZE * PacmanApp.MAP_SIZE - bbox.getWidth() - 5);
}
if (bbox.getMaxXWorld() > PacmanApp.BLOCK_SIZE * PacmanApp.MAP_SIZE) {
position.setX(0);
}
}
public void up() {
moveDir = MoveDirection.UP;
move(0, -5*speed);
rotation.setValue(270);
view.getView().setScaleX(1);
}
public void down() {
moveDir = MoveDirection.DOWN;
move(0, 5*speed);
rotation.setValue(90);
view.getView().setScaleX(1);
}
public void left() {
moveDir = MoveDirection.LEFT;
move(-5*speed, 0);
view.getView().setScaleX(-1);
rotation.setValue(0);
}
public void right() {
moveDir = MoveDirection.RIGHT;
move(5*speed, 0);
view.getView().setScaleX(1);
rotation.setValue(0);
}
public void teleport() {
Random random = new Random();
AStarGrid grid = ((PacmanApp) FXGL.getApp()).getGrid();
int x, y;
do {
x = (random.nextInt(PacmanApp.MAP_SIZE - 2) + 1);
y = (random.nextInt(PacmanApp.MAP_SIZE - 2) + 1);
} while (grid.getNodeState(x, y) != NodeState.WALKABLE);
position.setValue(x * PacmanApp.BLOCK_SIZE, y * PacmanApp.BLOCK_SIZE);
playFadeAnimation();
}
private void playFadeAnimation() {
FadeTransition ft = new FadeTransition(Duration.seconds(0.5), view.getView());
ft.setFromValue(1);
ft.setToValue(0);
ft.setAutoReverse(true);
ft.setCycleCount(2);
ft.play();
}
private List<Entity> blocks;
private void move(double dx, double dy) {
if (!getEntity().isActive())
return;
if (blocks == null) {
blocks = FXGL.getApp().getGameWorld().getEntitiesByType(PacmanType.BLOCK);
}
double mag = Math.sqrt(dx * dx + dy * dy);
long length = Math.round(mag);
double unitX = dx / mag;
double unitY = dy / mag;
for (int i = 0; i < length; i++) {
position.translate(unitX, unitY);
boolean collision = false;
for (int j = 0; j < blocks.size(); j++) {
if (blocks.get(j).getBoundingBoxComponent().isCollidingWith(bbox)) {
collision = true;
break;
}
}
if (collision) {
position.translate(-unitX, -unitY);
break;
}
}
}
}
| 28.75 | 91 | 0.639723 |
1a5aa81b3a71a5df090febb698d1cbcca4f1fa48 | 4,196 | package de.endrullis.lazyseq;
import org.testng.annotations.Test;
import java.util.List;
import static de.endrullis.lazyseq.LazySeq.empty;
import static de.endrullis.lazyseq.LazySeq.of;
import static de.endrullis.lazyseq.samples.Seqs.primes;
import static java.util.Arrays.asList;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
/**
* @author Tomasz Nurkiewicz
* @since 5/12/13, 11:32 AM
*/
public class LazySeqSlidingTest extends AbstractBaseTestCase {
@Test
public void shouldReturnEmptySeqWhenRunOnEmpty() throws Exception {
//given
final LazySeq<Object> empty = empty();
//when
final LazySeq<List<Object>> sliding = empty.sliding(10);
//then
assertThat(sliding).isEmpty();
}
@Test
public void shouldThrowWhenArgumentZeroOnEmptySeq() throws Exception {
//when
try {
LazySeq.empty().sliding(0);
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
//then
}
}
@Test
public void shouldThrowWhenArgumentZero() throws Exception {
//given
final LazySeq<Integer> fixed = of(1, 2, 3);
//when
try {
fixed.sliding(0);
failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
//then
}
}
@Test
public void shouldReturnOneElementForSeqShorterThanWindow() throws Exception {
//given
final LazySeq<Integer> fixed = of(5, 7, 9);
//when
final LazySeq<List<Integer>> sliding = fixed.sliding(4);
//then
assertThat(sliding.head()).isEqualTo(asList(5, 7, 9));
assertThat(sliding).hasSize(1);
}
@Test
public void shouldReturnOneElementForSeqEqualToWindowSize() throws Exception {
//given
final LazySeq<Integer> fixed = of(5, 7, 9, 11);
//when
final LazySeq<List<Integer>> sliding = fixed.sliding(4);
//then
assertThat(sliding.head()).isEqualTo(asList(5, 7, 9, 11));
assertThat(sliding).hasSize(1);
}
@Test
public void shouldReturnMultipleWindowsForFixedSeq() throws Exception {
//given
final LazySeq<Integer> fixed = of(5, 7, 9, 11);
//when
final LazySeq<List<Integer>> sliding = fixed.sliding(3);
//then
assertThat(sliding.get(0)).isEqualTo(asList(5, 7, 9));
assertThat(sliding.get(1)).isEqualTo(asList(7, 9, 11));
assertThat(sliding).hasSize(2);
}
@Test
public void shouldReturnMultipleSmallWindowsForFixedSeq() throws Exception {
//given
final LazySeq<Integer> fixed = of(5, 7, 9, 11);
//when
final LazySeq<List<Integer>> sliding = fixed.sliding(2);
//then
assertThat(sliding.get(0)).isEqualTo(asList(5, 7));
assertThat(sliding.get(1)).isEqualTo(asList(7, 9));
assertThat(sliding.get(2)).isEqualTo(asList(9, 11));
assertThat(sliding).hasSize(3);
}
@Test
public void shouldReturnWindowOfSizeOne() throws Exception {
//given
final LazySeq<Integer> fixed = of(5, 7, 9);
//when
final LazySeq<List<Integer>> sliding = fixed.sliding(1);
//then
assertThat(sliding.get(0)).isEqualTo(asList(5));
assertThat(sliding.get(1)).isEqualTo(asList(7));
assertThat(sliding.get(2)).isEqualTo(asList(9));
assertThat(sliding).hasSize(3);
}
@Test
public void shouldReturnWindowOfSizeOneForSingleElementSeq() throws Exception {
//given
final LazySeq<Integer> fixed = of(3);
//when
final LazySeq<List<Integer>> sliding = fixed.sliding(1);
//then
assertThat(sliding.get(0)).isEqualTo(asList(3));
assertThat(sliding).hasSize(1);
}
@Test
public void shouldReturnWindowOfSizeOneForEmptySeq() throws Exception {
//given
final LazySeq<Integer> fixed = empty();
//when
final LazySeq<List<Integer>> sliding = fixed.sliding(1);
//then
assertThat(sliding).isEmpty();
}
@Test
public void shouldCreateInfiniteSeqOfWindowsOverInfiniteSeq() throws Exception {
//given
final LazySeq<Integer> primes = primes();
//when
final LazySeq<List<Integer>> sliding = primes.sliding(3);
//then
assertThat(sliding.get(0)).isEqualTo(asList(2, 3, 5));
assertThat(sliding.get(1)).isEqualTo(asList(3, 5, 7));
assertThat(sliding.get(2)).isEqualTo(asList(5, 7, 11));
assertThat(sliding.get(3)).isEqualTo(asList(7, 11, 13));
}
}
| 24.97619 | 82 | 0.719733 |
f3638d8c3a77a0e15c67dd5038cdaa242b2ef9cf | 7,819 | package com.huawei.opensdk.callmgr;
import com.huawei.ecterminalsdk.base.TsdkDtmfTone;
import com.huawei.ecterminalsdk.models.call.TsdkCall;
import com.huawei.opensdk.commonservice.util.LogUtil;
/**
* This class is about call session
* 呼叫会话类
*/
public class Session {
private static final String TAG = Session.class.getSimpleName();
/**
* call object
* 呼叫信息
*/
private TsdkCall tsdkCall;
/**
* call type
* 呼叫类型
*/
private CallConstant.CallStatus callStatus = CallConstant.CallStatus.IDLE;
/**
* hold video
* 是否视频保持
*/
private boolean isVideoHold;
/**
* Blind transfer
* 是否盲转
*/
private boolean isBlindTransfer;
private long callId;
public Session(TsdkCall tsdkCall){
this.tsdkCall = tsdkCall;
this.callId = tsdkCall.getCallInfo().getCallId();
}
public TsdkCall getTsdkCall() {
return tsdkCall;
}
public long getCallID() {
return this.callId;
}
public CallConstant.CallStatus getCallStatus() {
return callStatus;
}
public void setCallStatus(CallConstant.CallStatus callStatus) {
this.callStatus = callStatus;
}
public boolean isVideoHold() {
return isVideoHold;
}
public void setVideoHold(boolean videoHold) {
isVideoHold = videoHold;
}
public boolean isBlindTransfer() {
return isBlindTransfer;
}
public void setBlindTransfer(boolean blindTransfer) {
this.isBlindTransfer = blindTransfer;
}
/**
* This method is used to answer the call
* @param isVideo
* @return
*/
public boolean answerCall(boolean isVideo)
{
CallMgr.getInstance().setDefaultAudioRoute(isVideo);
if (isVideo)
{
initVideoWindow();
if (CallConstant.CAMERA_NON != VideoMgr.getInstance().getCurrentCameraIndex())
{
VideoMgr.getInstance().setVideoOrient(getCallID(), VideoMgr.getInstance().getCurrentCameraIndex());
}
}
int result = tsdkCall.answerCall(isVideo);
if (result != 0)
{
LogUtil.e(TAG, "acceptCall return failed, result = " + result);
return false;
}
return true;
}
/**
* This method is used to end Call
* @return
*/
public boolean endCall()
{
int result = tsdkCall.endCall();
if (result != 0)
{
LogUtil.e(TAG, "endCall return failed, result = " + result);
return false;
}
return true;
}
/**
* This method is used to launched divert Call
* 发起偏转呼叫
*
* divert call
* @param divertNumber
* @return
*/
public boolean divertCall(String divertNumber)
{
int result = tsdkCall.divertCall(divertNumber);
if (result != 0)
{
LogUtil.e(TAG, "divertCall return failed, result = " + result);
return false;
}
return true;
}
/**
* start blind transfer request
* 发起盲转呼叫请求
*
* @param transferNumber 盲转号码
* @return
*/
public boolean blindTransfer(String transferNumber)
{
int result = tsdkCall.blindTransfer(transferNumber);
if (result != 0)
{
LogUtil.e(TAG, "blindTransfer return failed, result = " + result);
return false;
}
return true;
}
/**
* Call hold
* 呼叫保持
*
* @return
*/
public boolean holdCall()
{
int result = tsdkCall.holdCall();
if (result != 0)
{
LogUtil.e(TAG, "holdCall return failed, result = " + result);
return false;
}
return true;
}
/**
* Cancel Call hold
* 取消呼叫保持
*
* @return
*/
public boolean unHoldCall()
{
int result = tsdkCall.unholdCall();
if (result != 0)
{
LogUtil.e(TAG, "unholdCall return failed, result = " + result);
return false;
}
return true;
}
/**
* send DTMF during call
* 二次拨号
*
* @param code (0到9,*为10,#为11)
* @return
*/
public boolean reDial(int code)
{
TsdkDtmfTone tsdkDtmfTone = TsdkDtmfTone.enumOf(code);
if (null == tsdkDtmfTone)
{
LogUtil.e(TAG, "tsdkDtmfTone is null");
return false;
}
LogUtil.d(TAG, "Dtmf Tone :" + tsdkDtmfTone.getIndex());
int result = tsdkCall.sendDtmf(tsdkDtmfTone);
if (result != 0)
{
LogUtil.e(TAG, "sendDTMF return failed, result = " + result);
return false;
}
return true;
}
/**
* add video
* 音频转视频请求
*
* @return
*/
public boolean addVideo()
{
initVideoWindow();
int result = tsdkCall.addVideo();
if (result != 0)
{
LogUtil.e(TAG, "addVideo return failed, result = " + result);
return false;
}
setCallStatus(CallConstant.CallStatus.VIDEO_CALLING);
return true;
}
/**
* delet video
* 删除视频请求
*
* @return
*/
public boolean delVideo()
{
int result = tsdkCall.delVideo();
if (result != 0)
{
LogUtil.e(TAG, "delVideo return failed, result = " + result);
return false;
}
setCallStatus(CallConstant.CallStatus.AUDIO_CALLING);
return true;
}
/**
* Reject Audio Transfer Video Call
* 拒绝音频转视频呼叫
*
* @return
*/
public boolean rejectAddVideo()
{
int result = tsdkCall.replyAddVideo(false);
if (result != 0)
{
LogUtil.e(TAG, "replyAddVideo(reject) return failed, result = " + result);
return false;
}
return true;
}
/**
* Agree to Audio transfer video Call
* 同意音频转视频呼叫
*
* @return
*/
public boolean acceptAddVideo()
{
initVideoWindow();
int result = tsdkCall.replyAddVideo(true);
if (result != 0)
{
LogUtil.e(TAG, "replyAddVideo(accept) return failed, result = " + result);
return false;
}
return true;
}
/**
* set media microphone mute
* 设置(或取消)麦克风静音
*
* @param mute
* @return
*/
public boolean muteMic(boolean mute)
{
int result = tsdkCall.muteMic(mute);
if (result != 0)
{
LogUtil.e(TAG, "mediaMuteMic return failed, result = " + result);
return false;
}
return true;
}
/**
* set media speaker mute
* 设置(或取消)扬声器静音
*
* @param mute
* @return
*/
public boolean muteSpeak(boolean mute)
{
int result = tsdkCall.muteSpeaker(mute);
if (result != 0)
{
LogUtil.e(TAG, "mediaMuteSpeaker return failed, result = " + result);
return false;
}
return true;
}
/**
* switch Camera
* 切换摄像头
*
* @param cameraIndex 设备下标
*/
public void switchCamera(int cameraIndex)
{
}
/**
* Initializing the video window
* 初始化视频窗口
*/
public void initVideoWindow()
{
VideoMgr.getInstance().initVideoWindow(getCallID());
}
}
| 22.087571 | 116 | 0.507738 |
09a0ed0776de35b43ff4093fecea7f5bd34c31fa | 3,937 | package com.svs.ensign.resort.helper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
public class C_ResortHelper {
@Autowired
DataSource ds;
private Connection con;
public int generateEmployeeId() {
Connection con;
PreparedStatement pr;
ResultSet rs;
String last_number=null;
int counter=0;
try {
con=ds.getConnection();
pr=con.prepareStatement("select MAX(empno) from tl_employee");
rs=pr.executeQuery();
while(rs.next()) {
last_number=rs.getString(1);
break;
}
if(last_number==null) {
last_number="1";
}
else {
counter=Integer.parseInt(last_number)+1;
////System.out.println("Counter\t:\t"+counter);
}
////System.out.println("Last of the List:\t"+last_number);
con.close();
pr.close();
}catch(Exception e) {
e.printStackTrace();
}
return counter;
}
public int generateGuestId() {
Connection con;
PreparedStatement pr;
ResultSet rs;
String last_number=null;
int counter=0;
try {
con=ds.getConnection();
int i=0;
pr=con.prepareStatement("select MAX(guestid) from tl_guest_user");
rs=pr.executeQuery();
while(rs.next()) {
i++;
last_number=rs.getString(1);
break;
}
if(last_number==null) {
last_number="1";
}
else {
counter=Integer.parseInt(last_number)+1;
////System.out.println("Counter\t:\t"+counter);
}
////System.out.println("Last of the List:\t"+counter);
con.close();
pr.close();
}catch(Exception e) {
e.printStackTrace();
}
return counter;
}
public int generateVillaId() {
Connection con;
PreparedStatement pr;
ResultSet rs;
String last_number=null;
int counter=0;
try {
con=ds.getConnection();
pr=con.prepareStatement("select MAX(sno) from tl_villatype LIMIT 1");
rs=pr.executeQuery();
while(rs.last()) {
last_number=rs.getString(1);
break;
}
if(last_number==null) {
last_number="1";
}
else {
counter=Integer.parseInt(last_number)+1;
////System.out.println("Counter\t:\t"+counter);
}
////System.out.println("Last of the List:\t"+last_number);
con.close();
pr.close();
}catch(Exception e) {
e.printStackTrace();
}
return counter;
}
public int generateDepartmentId() {
Connection con;
PreparedStatement pr;
ResultSet rs;
String last_number=null;
int counter=0;
try {
con=ds.getConnection();
pr=con.prepareStatement("select MAX(sno) from tl_department");
rs=pr.executeQuery();
while(rs.next()) {
last_number=rs.getString(1);
break;
}
if(last_number==null) {
last_number="1";
}
else {
counter=Integer.parseInt(last_number)+1;
////System.out.println("Counter\t:\t"+counter);
}
////System.out.println("Last of the List:\t"+last_number);
con.close();
pr.close();
}catch(Exception e) {
e.printStackTrace();
}
return counter;
}
public boolean isVillaUnique(String serialno) {
boolean flag=false;
Connection con;
PreparedStatement pr;
ResultSet rs;
String last_number=null;
int counter=0;
try {
con=ds.getConnection();
pr=con.prepareStatement("select MAX(sno)from tl_villatype where villa_id=?");
pr.setString(1, serialno);
rs=pr.executeQuery();
while(rs.last()) {
last_number=rs.getString(1);
break;
}
if(last_number==null) {
flag=true;
}
else {
flag=false;
////System.out.println("Counter\t:\t"+counter);
}
////System.out.println("Last of the List:\t"+last_number);
con.close();
pr.close();
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
public Connection connection1()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/resort","root","root");
}catch(Exception e)
{
e.printStackTrace();
}
return con;
}
}
| 19.587065 | 87 | 0.663957 |
16e86c6cccf46d606b31b92594fc05c983313580 | 4,779 | package Prog1;
import Tools.IOTools;
public class Ubung2 {
public static void main(String[] args) {
Ubung2.aufgabe20();
}
public static void aufgabe18() {
double r = IOTools.readDouble("radius = ");
System.out.println("radius > 0 und < 10: " + (r > 0 && r < 10));
double radius = 2 * Math.PI * r;
double flaeche = Math.PI * Math.pow(r, 2);
System.out.println("Der Umfang eines Kreises mit Radius 2.5 ist " + radius + ".");
System.out.println("Der Flächeninhalt eines Kreises mit Radius 2.5 ist " + flaeche + ".");
}
public static void aufgabe19() {
String mode = IOTools.readString("while, for oder do-while? Defaults to for: ");
int n = IOTools.readInt("n = ");
System.out.println("N ist: " + n);
switch (mode) {
case "while" -> {
int i = 3;
System.out.println("while");
while (i < 2 * n) {
i++;
System.out.println((double) 1 / (2 * i + 1));
}
}
case "do-while" -> {
int i = 3;
System.out.println("do-while");
do {
i++;
System.out.println((double) 1 / (2 * i + 1));
} while (i < 2 * n);
}
default -> {
System.out.println("for");
for (int i = 3; i < 2 * n; ) {
i++;
System.out.println((double) 1 / (2 * i + 1));
}
}
}
}
public static class Zylinder {
public static double mantel(double r, double h) {
return 2 * Math.PI * r * h;
}
public static double grund(double r) {
return Math.PI * Math.pow(r, 2);
}
public static double volumen(double r, double h) {
return Zylinder.grund(r) * h;
}
}
public static class Kegel {
public static double mantel(double r, double h) {
return Math.PI * r * Math.sqrt(Math.pow(r, 2) * Math.pow(h, 2));
}
public static double grund(double r) {
return Zylinder.grund(r);
}
public static double volumen(double r, double h) {
return Zylinder.grund(r) * h / 3;
}
}
public static void aufgabe20() {
System.out.println("Berechnung von Kreiskörpern");
char koerper = IOTools.readChar("Kreiszylinder(Z) oder Kreiskegel(K)?: ");
char berechnung = IOTools.readChar("Mantelfläche(M), Grundfläche(G) oder Volumen(V)?: ");
double radius = IOTools.readInteger("Geben Sie bitte den Radius ein:");
double hoehe = IOTools.readInteger("Geben Sie bitte die Höhe ein:");
String berechnungName = "";
String koerperName = "";
double ergebnis = 0;
switch (koerper) {
case 'z', 'Z' -> {
koerperName = "Kreiszylinder";
switch (berechnung) {
case 'm', 'M' -> {
berechnungName = "Mantelfläche";
ergebnis = Zylinder.mantel(radius, hoehe);
}
case 'v', 'V' -> {
berechnungName = "Volumen";
ergebnis = Zylinder.volumen(radius, hoehe);
}
case 'g', 'G' -> {
berechnungName = "Grundfläche";
ergebnis = Zylinder.grund(radius);
}
default -> {
Ubung2.error();
}
}
}
case 'k', 'K' -> {
koerperName = "Kreiskegel";
switch (berechnung) {
case 'm', 'M' -> {
berechnungName = "Mantelfläche";
ergebnis = Kegel.mantel(radius, hoehe);
}
case 'v', 'V' -> {
berechnungName = "Volumen";
ergebnis = Kegel.volumen(radius, hoehe);
}
case 'g', 'G' -> {
berechnungName = "Grundfläche";
ergebnis = Kegel.grund(radius);
}
default -> {
Ubung2.error();
}
}
}
}
System.out.println("Die " + berechnungName + " eines " + koerperName + " mit Radius " + radius + " und Höhe "
+ hoehe + " beträgt: " + ergebnis);
}
public static void error() {
System.out.println("Fehler bei der Eingabe");
}
} | 33.41958 | 117 | 0.435865 |
762ef903ae5641603fb8d8507f2b21420eea92ad | 726 | package com.qty.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.qty.log.QTLog;
public class MainActivity extends AppCompatActivity {
private QTLog Log = new QTLog(MainActivity.class);
private String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("onCreate...");
findViewById(R.id.exception).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Name length = " + name.length());
}
});
}
} | 24.2 | 84 | 0.655647 |
7e97d8e0a03b955521848a700afba64265688c66 | 5,097 | package com.yue.demo.jsontest;
//package org.yue.mytest.jsontest;
//
//@Test
//public void testPersonsJson()
//{
// List<Person> persons = new ArrayList<Person>();
// Person person = new Person(1, "xiaoluo", "广州");
// Person person2 = new Person(2, "android", "上海");
// persons.add(person);
// persons.add(person2);
// String personsString = JsonTools.getJsonString("persons", persons);
// System.out.println(personsString);
//
// JSONObject jsonObject = JsonTools.getJsonObject("persons", persons);
// // List<Person>相当于一个JSONArray对象
// JSONArray personsArray = (JSONArray)jsonObject.getJSONArray("persons");
// List<Person> persons2 = (List<Person>) personsArray.toCollection(personsArray, Person.class);
// System.out.println(persons2);
//}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Utils {
/**
* 定义分割常量 (#在集合中的含义是每个元素的分割,|主要用于map类型的集合用于key与value中的分割)
*/
private static final String SEP1 = "#";
private static final String SEP2 = "|";
/**
* List转换String
*
* @param list
* :需要转换的List
* @return String转换后的字符串
*/
public static String ListToString(List<?> list) {
StringBuffer sb = new StringBuffer();
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == null || list.get(i) == "") {
continue;
}
// 如果值是list类型则调用自己
if (list.get(i) instanceof List) {
sb.append(ListToString((List<?>) list.get(i)));
sb.append(SEP1);
} else if (list.get(i) instanceof Map) {
sb.append(MapToString((Map<?, ?>) list.get(i)));
sb.append(SEP1);
} else {
sb.append(list.get(i));
sb.append(SEP1);
}
}
}
return "L" + sb.toString();
}
/**
* Map转换String
*
* @param map
* :需要转换的Map
* @return String转换后的字符串
*/
public static String MapToString(Map<?, ?> map) {
StringBuffer sb = new StringBuffer();
// 遍历map
for (Object obj : map.keySet()) {
if (obj == null) {
continue;
}
Object key = obj;
Object value = map.get(key);
if (value instanceof List<?>) {
sb.append(key.toString() + SEP1 + ListToString((List<?>) value));
sb.append(SEP2);
} else if (value instanceof Map<?, ?>) {
sb.append(key.toString() + SEP1
+ MapToString((Map<?, ?>) value));
sb.append(SEP2);
} else {
sb.append(key.toString() + SEP1 + value.toString());
sb.append(SEP2);
}
}
return "M" + sb.toString();
}
/**
* String转换Map
*
* @param mapText
* :需要转换的字符串
* @param KeySeparator
* :字符串中的分隔符每一个key与value中的分割
* @param ElementSeparator
* :字符串中每个元素的分割
* @return Map<?,?>
*/
public static Map<String, Object> StringToMap(String mapText) {
if (mapText == null || mapText.equals("")) {
return null;
}
mapText = mapText.substring(1);
Map<String, Object> map = new HashMap<String, Object>();
String[] text = mapText.split("\\" + SEP2); // 转换为数组
for (String str : text) {
String[] keyText = str.split(SEP1); // 转换key与value的数组
if (keyText.length < 1) {
continue;
}
String key = keyText[0]; // key
String value = keyText[1]; // value
if (value.charAt(0) == 'M') {
Map<?, ?> map1 = StringToMap(value);
map.put(key, map1);
} else if (value.charAt(0) == 'L') {
List<?> list = StringToList(value);
map.put(key, list);
} else {
map.put(key, value);
}
}
return map;
}
/**
* String转换List
*
* @param listText
* :需要转换的文本
* @return List<?>
*/
public static List<Object> StringToList(String listText) {
if (listText == null || listText.equals("")) {
return null;
}
listText = listText.substring(1);
// listText = EspUtils.DecodeBase64(listText);
List<Object> list = new ArrayList<Object>();
String[] text = listText.split(SEP1);
for (String str : text) {
if (str.charAt(0) == 'M') {
Map<?, ?> map = StringToMap(str);
list.add(map);
} else if (str.charAt(0) == 'L') {
List<?> lists = StringToList(str);
list.add(lists);
} else {
list.add(str);
}
}
return list;
}
}
| 30.159763 | 99 | 0.483814 |
9304265eda5feb9516f177864c5b5d6696296e2f | 127 | package com.mirkocaserta.example;
import java.util.List;
public interface TimeValueProvider {
List<TimeValue> get();
}
| 12.7 | 36 | 0.748031 |
be93c82cf61ab1ece8b7b9df2ed48c52497929c5 | 330 | package org.tbk.bitcoin.regtest.electrum.faucet;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.Sha256Hash;
import org.tbk.bitcoin.regtest.common.AddressSupplier;
import reactor.core.publisher.Mono;
public interface ElectrumRegtestFaucet {
Mono<Sha256Hash> requestBitcoin(AddressSupplier address, Coin amount);
}
| 25.384615 | 74 | 0.818182 |
98e47abd62f9888eb89670943e23cbcf109fb784 | 3,817 | /*
* Copyright 2019 Red Hat, Inc. and/or its affiliates.
*
* 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.optaweb.employeerostering.skill;
import static org.assertj.core.api.Assertions.assertThat;
import javax.ws.rs.core.Response.Status;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.optaweb.employeerostering.AbstractEntityRequireTenantRestServiceTest;
import org.optaweb.employeerostering.domain.skill.Skill;
import org.optaweb.employeerostering.domain.skill.view.SkillView;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.response.Response;
@QuarkusTest
public class SkillRestControllerTest extends AbstractEntityRequireTenantRestServiceTest {
private final String skillPathURI = "/rest/tenant/{tenantId}/skill/";
private Response getSkills(Integer tenantId) {
return RestAssured.get(skillPathURI, tenantId);
}
private Response getSkill(Integer tenantId, Long id) {
return RestAssured.get(skillPathURI + id, tenantId);
}
private void deleteSkill(Integer tenantId, Long id) {
RestAssured.delete(skillPathURI + id, tenantId);
}
private Response addSkill(Integer tenantId, SkillView skillView) {
return RestAssured.given()
.body(skillView)
.post(skillPathURI + "add", tenantId);
}
private Response updateSkill(Integer tenantId, SkillView skillView) {
return RestAssured.given()
.body(skillView)
.post(skillPathURI + "update", tenantId);
}
@BeforeEach
public void setup() {
createTestTenant();
}
@AfterEach
public void cleanup() {
deleteTestTenant();
}
@Test
public void skillCrudTest() {
SkillView skillView = new SkillView(TENANT_ID, "skill");
Response postResponse = addSkill(TENANT_ID, skillView);
assertThat(postResponse.getStatusCode()).isEqualTo(Status.OK.getStatusCode());
Response response = getSkill(TENANT_ID, postResponse.as(Skill.class).getId());
assertThat(response.getStatusCode()).isEqualTo(Status.OK.getStatusCode());
assertThat(response.getBody()).usingRecursiveComparison().ignoringFields("groovyResponse")
.isEqualTo(postResponse.getBody());
SkillView updatedSkill = new SkillView(TENANT_ID, "updatedSkill");
updatedSkill.setId(postResponse.as(Skill.class).getId());
Response putResponse = updateSkill(TENANT_ID, updatedSkill);
assertThat(putResponse.getStatusCode()).isEqualTo(Status.OK.getStatusCode());
response = getSkill(TENANT_ID, putResponse.as(Skill.class).getId());
assertThat(putResponse.getStatusCode()).isEqualTo(Status.OK.getStatusCode());
assertThat(putResponse.getBody()).usingRecursiveComparison().ignoringFields("groovyResponse")
.isEqualTo(response.getBody());
deleteSkill(TENANT_ID, postResponse.as(Skill.class).getId());
Response getListResponse = getSkills(TENANT_ID);
assertThat(getListResponse.getStatusCode()).isEqualTo(Status.OK.getStatusCode());
assertThat(getListResponse.jsonPath().getList("$", Skill.class)).isEmpty();
}
}
| 37.792079 | 101 | 0.716007 |
a14760f7bbbcd0a4fe6c1465554b2ec9520fdf5b | 1,067 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib.impl;
import com.wilutions.com.*;
@SuppressWarnings("all")
@CoClass(guid="{523E72F0-218D-9F0F-3EAC-69246CB2465E}")
public class _IDelegatorClientEventsImpl extends Dispatch implements com.wilutions.mslib.uccollaborationlib._IDelegatorClientEvents {
@DeclDISPID(100) public void onOnStateChanged(final com.wilutions.mslib.uccollaborationlib.IClient _eventSource, final com.wilutions.mslib.uccollaborationlib.IClientStateChangedEventData _eventData) throws ComException {
this._dispatchCall(100,"OnStateChanged", DISPATCH_METHOD,null,(_eventSource!=null?_eventSource:Dispatch.NULL),(_eventData!=null?_eventData:Dispatch.NULL));
}
public _IDelegatorClientEventsImpl(String progId) throws ComException {
super(progId, "{92A9EB9B-85EE-444E-A302-00C3C945BAA4}");
}
protected _IDelegatorClientEventsImpl(long ndisp) {
super(ndisp);
}
public String toString() {
return "[_IDelegatorClientEventsImpl" + super.toString() + "]";
}
}
| 50.809524 | 224 | 0.773196 |
ae5e0de078be529b4caee77b01b768b75e58e5f6 | 8,871 | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Emote;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class StickyTime extends ListenerAdapter {
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split("\\s+");
String channelId = event.getChannel().getId();
String prefix = Main.mapPrefix.get(event.getGuild().getId()) != null ? Main.mapPrefix.get(event.getGuild().getId()) : "?";
if (event.getMessage().getContentRaw().startsWith(prefix + "stick ") && event.getMessage().getContentRaw().matches("[\\S]+\\s{2,}.*") && event.getMember().hasPermission(Permission.MESSAGE_MANAGE) && !event.getAuthor().isBot()) {
event.getMessage().reply(event.getMember().getAsMention() + " please only use one space after the `?stick` command!").queue();
return;
}
if (args[0].equalsIgnoreCase(prefix + "stick") && event.getMember().hasPermission(Permission.MESSAGE_MANAGE) && !event.getAuthor().isBot()) {
event.getChannel().getHistory().retrievePast(8).queue(count -> {
if(Main.mapMessageSlow.containsKey(event.getChannel().getId())) {
Main.mapMessageSlow.remove(channelId);
if(Main.mapDeleteId2.get(channelId) != null)
event.getChannel().deleteMessageById(Main.mapDeleteId2.get(channelId)).queue(null, (error) -> {});
}
try {
//remove last sticky message if there is one (user used sticky command while already having one)
if(Main.mapDeleteId.get(channelId) != null)
event.getChannel().deleteMessageById(Main.mapDeleteId.get(channelId)).queue(null, (error) -> {});
for (Emote emote : event.getMessage().getEmotes())
event.getGuild().retrieveEmoteById(emote.getId()).queue(success -> {}, failure -> {
event.getMessage().reply(event.getMember().getAsMention() + " Error: Please only use emotes that are from this server.").queue();
Main.mapMessage.remove(event.getChannel().getId());
removeDB(channelId);
});
String input = event.getMessage().getContentRaw();
if (event.getMessage().getContentRaw().contains(prefix + "stick \n")) {
event.getMessage().reply(event.getMember().getAsMention() + " Error: Please provide text after `" + prefix + "stick` before using a new line.").queue();
return;
}
String [] arr = input.split(" ", 2);
Main.mapMessage.put(event.getChannel().getId(), arr[1].trim());
removeDB(channelId);
addDB(channelId,(arr[1]).trim());
event.getChannel().sendMessage(Main.mapMessage.get(channelId)).queue(m -> Main.mapDeleteId.put(event.getChannel().getId(), m.getId()));
event.getMessage().addReaction("\u2705").queue();
} catch (Exception e) {
event.getChannel().sendMessage(event.getMember().getAsMention() + " please use this format: `?stick <message>`.").queue();
e.printStackTrace();
}
});
} else if (args[0].equalsIgnoreCase(prefix + "stick") && (!event.getMember().hasPermission(Permission.MESSAGE_MANAGE))) {
//Adds X emote
event.getMessage().addReaction("\u274C").queue();
event.getMessage().reply(event.getMember().getAsMention() + " you need the global `Manage Messages` permission to use this command!").queue();
}
else if ( (args[0].equalsIgnoreCase(prefix + "stickstop") || args[0].equalsIgnoreCase(prefix + "unstick")) && event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
Main.mapMessage.remove(channelId);
if(Main.mapDeleteId.get(channelId) != null)
event.getChannel().deleteMessageById(Main.mapDeleteId.get(channelId)).queue(null, (error) -> {});
removeDB(channelId);
event.getMessage().addReaction("\u2705").queue();
} else if ( (args[0].equalsIgnoreCase(prefix + "stickstop") || args[0].equalsIgnoreCase(prefix + "unstick")) && !event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
//Adds X mark
event.getMessage().addReaction("\u274C").queue();
event.getMessage().reply(event.getMember().getAsMention() + " you need the global `Manage Messages` permission to use this command!").queue();
}
if (Main.mapMessage.get(channelId) != null) {
event.getChannel().getHistory().retrievePast(8).queue(history -> {
for(Message m : history.subList(0, history.size() < 5 ? history.size() : 5))
//if message is sticky message
if(m.getContentRaw().equals(Main.mapMessage.get(channelId))) {
//if message is older then 30 sec
if(m.getTimeCreated().compareTo(OffsetDateTime.now().minusSeconds(15)) < 0) {
m.delete().queue(null, (error) -> {});
event.getChannel().sendMessage(Main.mapMessage.get(channelId)).queue(mes -> Main.mapDeleteId.put(channelId, mes.getId()));
}
break;
}
if(!history.stream().limit(5).anyMatch(m -> m.getContentRaw().equals(Main.mapMessage.get(channelId)))) {
if(Main.mapDeleteId.get(channelId) != null)
event.getChannel().deleteMessageById(Main.mapDeleteId.get(channelId)).queue(null, (error) -> {});
//If message send fails, stickstop
if (event.getChannel().canTalk()) {
event.getChannel().sendMessage(Main.mapMessage.get(channelId)).queue();
} else {
Main.mapMessage.remove(channelId);
removeDB(channelId);
System.out.println("StickStop Override due to missing write permission");
}
}
//Added to make sure it does not bug and send two stickies (next 5 lines)
List<Message> indexes = new ArrayList<>(history.stream().filter(m -> m.getContentRaw().equals(Main.mapMessage.get(channelId))).toList());
if (!indexes.isEmpty() && indexes.size() > 1) {
indexes.remove(0);
for (Message mess : indexes) {
mess.delete().queue(null, (error) -> {});
}
}
});
}
}
public void addDB(String channelId, String message) {
try {
Connection dbConn = DriverManager.getConnection(Main.dbUrl,Main.dbUser,"");
String sql = "INSERT INTO newMessages (channelId, message) VALUES ( ?, ?)";
PreparedStatement myStmt = dbConn.prepareStatement(sql);
myStmt.setString(1, channelId);
myStmt.setString(2, message);
myStmt.execute();
myStmt.close();
dbConn.close();
} catch ( SQLException e) {
e.printStackTrace();
}
}
public void removeDB(String channelId) {
try {
Connection dbConn = DriverManager.getConnection(Main.dbUrl,Main.dbUser,"");
Statement myStmt = dbConn.createStatement();
String sql = "DELETE FROM newMessages WHERE channelId='" + channelId + "';";
myStmt.execute(sql);
myStmt.close();
dbConn.close();
dbConn.close();
} catch ( SQLException e) {
e.printStackTrace();
}
}
public List<String> getActiveStickyChannelId(String guildId) {
List<String> channelIds = Main.jda.getGuildById(guildId).getTextChannels().stream().map(textChannel -> textChannel.getId()).collect(Collectors.toList());
List<String> stickyChannelIDs = new ArrayList<>();
for (String id : channelIds) {
if (Main.mapMessage.containsKey(id)) {
stickyChannelIDs.add(id);
}
}
return stickyChannelIDs;
}
}
| 50.118644 | 236 | 0.573667 |
400ee5360351a12ac3bc44c86607fd61c61c8ec2 | 1,628 | package com.transcendensoft.hedbanz.utils;
/**
* Copyright 2017. Andrii Chernysh
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
*/
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.TypedValue;
/**
* Utility class to process actions with view.
* Converting different metrics.
*
* @author Andrii Chernysh. E-mail: [email protected]
* Developed by <u>Transcendensoft</u>
*/
public class ViewUtils {
private ViewUtils() {
}
public static float pxToDp(Context context, float px) {
float densityDpi = context.getResources().getDisplayMetrics().densityDpi;
return px / (densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
public static int dpToPx(Context context, float dp) {
float density = context.getResources().getDisplayMetrics().density;
return Math.round(dp * density);
}
public static int spToPx(Context context, float sp) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, sp,
context.getResources().getDisplayMetrics());
}
}
| 33.22449 | 81 | 0.70516 |
e4ae74dfd48432e56e169d984637eadafbe2cc0b | 2,745 | package com.ontraport.mobileapp.main.collection.asynctasks;
import android.text.TextUtils;
import com.ontraport.mobileapp.AbstractAsyncTask;
import com.ontraport.mobileapp.OntraportApplication;
import com.ontraport.mobileapp.main.collection.CollectionAdapter;
import com.ontraport.mobileapp.utils.FieldUtils;
import com.ontraport.sdk.exceptions.RequiredParamsException;
import com.ontraport.sdk.http.ObjectInfo;
import com.ontraport.sdk.http.RequestParams;
import java.util.Arrays;
import java.util.List;
public class GetInfoAsyncTask extends AbstractAsyncTask<CollectionAdapter, ObjectInfo> {
private RequestParams params;
private boolean force_network = false;
public GetInfoAsyncTask(CollectionAdapter adapter, RequestParams params) {
this(adapter, params, false);
}
public GetInfoAsyncTask(CollectionAdapter adapter, RequestParams params, boolean force_network) {
super(adapter);
this.force_network = force_network;
this.params = params;
}
@Override
protected void onPostExecute(ObjectInfo info) {
super.onPostExecute(info);
if (info == null) {
System.out.println("Couldn't retrieve info...");
return;
}
List<ObjectInfo.FieldSettings> settings = info.getData().getListFieldSettings();
for (ObjectInfo.FieldSettings field : settings) {
String sort = field.getSortDir();
if (sort != null) {
params.put("sortDir", sort);
params.put("sort", field.getName());
}
}
String[] list_fields = info.getData().getListFields();
String list = TextUtils.join(",", list_fields);
if (!Arrays.asList(list_fields).contains("id")) {
list += ",id";
}
if (Arrays.asList(list_fields).contains("fn")) {
list += ",firstname,lastname";
}
params.put("listFields", list);
int object_id = params.getAsInt(FieldUtils.OBJECT_ID);
new GetListAsyncTask<>(adapter,
list_fields,
info.getCount(),
object_id,
force_network).execute(params);
if (OntraportApplication.getInstance().isCustomObject(object_id)) {
new GetFieldsAsyncTask<>(adapter,
list_fields,
info.getCount(),
object_id,
force_network).execute(params);
}
}
@Override
public ObjectInfo background(RequestParams params) throws RequiredParamsException {
OntraportApplication ontraport_app = OntraportApplication.getInstance();
return ontraport_app.getApi().objects().retrieveCollectionInfo(params);
}
}
| 34.746835 | 101 | 0.647723 |
dbe3ae3bb76203944da2af9d0a712fb2b6cfe595 | 3,468 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.BQQuoteInitiateInputModelMarketTradeTransactionInstanceRecordMarketOrderTransaction;
import javax.validation.Valid;
/**
* BQQuoteInitiateInputModelMarketTradeTransactionInstanceRecord
*/
public class BQQuoteInitiateInputModelMarketTradeTransactionInstanceRecord {
private String marketOrderTransactionInstanceReference = null;
private String customerReference = null;
private String employeeBusinessUnitReference = null;
private String customerMarketOrderProcessingInstruction = null;
private BQQuoteInitiateInputModelMarketTradeTransactionInstanceRecordMarketOrderTransaction marketOrderTransaction = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the market order that is to be executed in the markets
* @return marketOrderTransactionInstanceReference
**/
public String getMarketOrderTransactionInstanceReference() {
return marketOrderTransactionInstanceReference;
}
public void setMarketOrderTransactionInstanceReference(String marketOrderTransactionInstanceReference) {
this.marketOrderTransactionInstanceReference = marketOrderTransactionInstanceReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the account primary party/owner for the market order
* @return customerReference
**/
public String getCustomerReference() {
return customerReference;
}
public void setCustomerReference(String customerReference) {
this.customerReference = customerReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: The employee/business unit placing the market order
* @return employeeBusinessUnitReference
**/
public String getEmployeeBusinessUnitReference() {
return employeeBusinessUnitReference;
}
public void setEmployeeBusinessUnitReference(String employeeBusinessUnitReference) {
this.employeeBusinessUnitReference = employeeBusinessUnitReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Any customer specific processing preferences or requirements
* @return customerMarketOrderProcessingInstruction
**/
public String getCustomerMarketOrderProcessingInstruction() {
return customerMarketOrderProcessingInstruction;
}
public void setCustomerMarketOrderProcessingInstruction(String customerMarketOrderProcessingInstruction) {
this.customerMarketOrderProcessingInstruction = customerMarketOrderProcessingInstruction;
}
/**
* Get marketOrderTransaction
* @return marketOrderTransaction
**/
public BQQuoteInitiateInputModelMarketTradeTransactionInstanceRecordMarketOrderTransaction getMarketOrderTransaction() {
return marketOrderTransaction;
}
public void setMarketOrderTransaction(BQQuoteInitiateInputModelMarketTradeTransactionInstanceRecordMarketOrderTransaction marketOrderTransaction) {
this.marketOrderTransaction = marketOrderTransaction;
}
}
| 35.387755 | 207 | 0.818339 |
442fcdb95eda002fa87b41b546cc89835ed2294a | 9,120 | /**
* Copyright 2012-2021 Digital.ai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xebialabs.overcast.support.libvirt;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import com.xebialabs.overcast.Preconditions;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import static com.xebialabs.overcast.support.libvirt.JDomUtil.getElementText;
/**
* Utility to deal with the metadata we set on Libvirt Domains. Metadata can be for a provisioned domain or for just a clone.
* <p>For a provisioned domain it looks like:
* <pre>
* <metadata>
* <overcast_metdata xmlns="http://www.xebialabs.com/overcast/metadata/v1">
* <parent_domain>centos6</parent_domain>
* <provisioned_with>/mnt/puppet/Vagrantfile</provisioned_with>
* <provisioned_checksum>2008-10-31T15:07:38.6875000-05:00</provisioned_checksum>
* <creation_time>2008-10-31T15:07:38.6875000-05:00</provisioned_at>
* </overcast_metdata>
* </metadata>
* </pre>
* <p>For a cloned domain it looks like:
* <pre>
* <metadata>
* <overcast_metdata xmlns="http://www.xebialabs.com/overcast/metadata/v1">
* <parent_domain>centos6</parent_domain>
* <creation_time>2008-10-31T15:07:38.6875000-05:00</provisioned_at>
* </overcast_metdata>
* </metadata>
* </pre>
*/
public class Metadata {
private static final String XML_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String METADATA_NS_V1 = "http://www.xebialabs.com/overcast/metadata/v1";
public static final String METADATA = "metadata";
public static final String OVERCAST_METADATA = "overcast_metadata";
public static final String CREATION_TIME = "creation_time";
public static final String PROVISIONED_CHECKSUM = "provisioned_checksum";
public static final String PROVISIONED_WITH = "provisioned_with";
public static final String PARENT_DOMAIN = "parent_domain";
private static final TimeZone METADATA_TIMEZONE = TimeZone.getTimeZone("UTC");
private final String parentDomain;
private final String provisionedWith;
private final String provisionedChecksum;
private final Date creationTime;
public Metadata(String parentDomain, String provisionedWith, String provisionedChecksum, Date creationTime) {
Preconditions.checkNotNull(creationTime, "creationTime cannot be null");
this.parentDomain = checkArgument(parentDomain, "parentDomain");
this.provisionedWith = checkArgument(provisionedWith, "provisionedWith");
this.provisionedChecksum = checkArgument(provisionedChecksum, "provisionedChecksum");
this.creationTime = creationTime;
}
public Metadata(String parentDomain, Date creationTime) {
Preconditions.checkNotNull(creationTime, "creationTime cannot be null");
this.parentDomain = checkArgument(parentDomain, "parentDomain");
this.creationTime = creationTime;
this.provisionedWith = null;
this.provisionedChecksum = null;
}
private static String checkArgument(String arg, String argName) {
Preconditions.checkArgument(arg != null && !arg.isEmpty(), "%s cannot be null or empty", argName);
return arg;
}
public String getParentDomain() {
return parentDomain;
}
public String getProvisionedWith() {
return provisionedWith;
}
public String getProvisionedChecksum() {
return provisionedChecksum;
}
public Date getCreationTime() {
return creationTime;
}
public boolean isProvisioned() {
return provisionedWith != null;
}
/**
* Extract {@link Metadata} from the domain XML. Throws {@link IllegalArgumentException} if the metadata is
* malformed.
*
* @return the metadata or <code>null</code> if there's no metadata
*/
public static Metadata fromXml(Document domainXml) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT);
Element metadata = getMetadataElement(domainXml);
if (metadata == null) {
return null;
}
Namespace ns = Namespace.getNamespace(METADATA_NS_V1);
Element ocMetadata = metadata.getChild(OVERCAST_METADATA, ns);
if (ocMetadata == null) {
return null;
}
String parentDomain = getElementText(ocMetadata, PARENT_DOMAIN, ns);
String creationTime = getElementText(ocMetadata, CREATION_TIME, ns);
Date date = sdf.parse(creationTime);
if(ocMetadata.getChild(PROVISIONED_WITH, ns) != null) {
String provisionedWith = getElementText(ocMetadata, PROVISIONED_WITH, ns);
String checkSum = getElementText(ocMetadata, PROVISIONED_CHECKSUM, ns);
return new Metadata(parentDomain, provisionedWith, checkSum, date);
}
return new Metadata(parentDomain, date);
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid date in metadata on domain", e);
}
}
private static Element createProvisioningMetadata(String parentDomain, String provisionedWith, String provisionedChecksum, Date provisionedAt) {
SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT);
sdf.setTimeZone(METADATA_TIMEZONE);
Element metadata = new Element(METADATA);
Element ocmetadata = new Element(OVERCAST_METADATA, METADATA_NS_V1);
metadata.addContent(ocmetadata);
ocmetadata.addContent(new Element(PARENT_DOMAIN, METADATA_NS_V1).setText(parentDomain));
ocmetadata.addContent(new Element(PROVISIONED_WITH, METADATA_NS_V1).setText(provisionedWith));
ocmetadata.addContent(new Element(PROVISIONED_CHECKSUM, METADATA_NS_V1).setText(provisionedChecksum));
ocmetadata.addContent(new Element(CREATION_TIME, METADATA_NS_V1).setText(sdf.format(provisionedAt)));
return metadata;
}
private static Element createCloningMetadata(String parentDomain, Date creationTime) {
SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT);
sdf.setTimeZone(METADATA_TIMEZONE);
Element metadata = new Element(METADATA);
Element ocmetadata = new Element(OVERCAST_METADATA, METADATA_NS_V1);
metadata.addContent(ocmetadata);
ocmetadata.addContent(new Element(PARENT_DOMAIN, METADATA_NS_V1).setText(parentDomain));
ocmetadata.addContent(new Element(CREATION_TIME, METADATA_NS_V1).setText(sdf.format(creationTime)));
return metadata;
}
private static Element getMetadataElement(Document domainXml) {
return domainXml.getRootElement().getChild(METADATA);
}
public static void updateProvisioningMetadata(Document domainXml, String baseDomainName, String provisionCmd, String expirationTag, Date creationTime) {
checkArgument(baseDomainName, "baseDomainName");
checkArgument(provisionCmd, "provisionCmd");
checkArgument(expirationTag, "expirationTag");
Preconditions.checkNotNull(creationTime, "creationTime must not be null");
Element element = getMetadataElement(domainXml);
if (element != null) {
domainXml.getRootElement().removeContent(element);
}
Element metadata = createProvisioningMetadata(baseDomainName, provisionCmd, expirationTag, creationTime);
domainXml.getRootElement().addContent(metadata);
}
public static void updateCloneMetadata(Document domainXml, String baseDomainName, Date creationTime) {
checkArgument(baseDomainName, "baseDomainName");
Preconditions.checkNotNull(creationTime, "creationTime must not be null");
Element element = getMetadataElement(domainXml);
if (element != null) {
domainXml.getRootElement().removeContent(element);
}
Element metadata = createCloningMetadata(baseDomainName, creationTime);
domainXml.getRootElement().addContent(metadata);
}
@Override
public String toString() {
return "Metadata{" +
"parentDomain='" + parentDomain + '\'' +
", creationTime=" + creationTime +
", provisionedChecksum='" + provisionedChecksum + '\'' +
", provisionedWith='" + provisionedWith + '\'' +
'}';
}
}
| 42.616822 | 156 | 0.698355 |
1431800170023edfb56ab05ba742ec2fa2ba0aae | 3,352 | /******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.apps;
import java.util.ListResourceBundle;
/**
* Base Resource Bundle
*
* @translator Jaume Teixi
* @translator Jordi Luna
* @version $Id: ALoginRes_ca.java,v 1.2 2006/07/30 00:51:27 jjanke Exp $
*/
public final class ALoginRes_ca extends ListResourceBundle
{
// TODO Run native2ascii to convert to plain ASCII !!
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Connection", "Connexi\u00f3" },
{ "Defaults", "Valors Predeterminats" },
{ "Login", "Acc\u00e9s ADempiere" },
{ "File", "Fitxer" },
{ "Exit", "Sortir" },
{ "Help", "Ajuda" },
{ "About", "Referent" },
{ "Host", "Servidor" },
{ "Database", "Base de Dades" },
{ "User", "Usuari" },
{ "EnterUser", "Introdu\u00efr Usuari Aplicaci\u00f3" },
{ "Password", "Contrasenya" },
{ "EnterPassword", "Entrar Contrasenya Usuari Aplicaci\u00f3" },
{ "Language", "Idioma" },
{ "SelectLanguage", "Seleccioni Idioma" },
{ "Role", "Rol" },
{ "Client", "Entitat" },
{ "Organization", "Organitzaci\u00f3" },
{ "Date", "Data" },
{ "Warehouse", "Magatzem" },
{ "Printer", "Impressora" },
{ "Connected", "Connectat" },
{ "NotConnected", "No Connectat" },
{ "DatabaseNotFound", "No s'ha trobat la Base de Dades" },
{ "UserPwdError", "No coincideix l'Usuari i la Contrasenya" },
{ "RoleNotFound", "Rol no trobat/completat" },
{ "Authorized", "Autoritzat" },
{ "Ok", "Acceptar" },
{ "Cancel", "Cancel.lar" },
{ "VersionConflict", "Conflicte Versions:" },
{ "VersionInfo", "Servidor <> Client" },
{ "PleaseUpgrade", "Descarregui una nova versi\u00f3 del Programa" }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes_ca
| 42.974359 | 79 | 0.548628 |
2c0d94304a82f571c28ba32809d7f8cae394d015 | 6,521 | /**
* maps4cim - a real world map generator for CiM 2
* Copyright 2013 Sebastian Straub
*
* 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 de.nx42.maps4cim.map.texture.osm;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import org.openstreetmap.osmosis.core.domain.v0_6.Entity;
import org.openstreetmap.osmosis.core.domain.v0_6.Node;
import org.openstreetmap.osmosis.core.domain.v0_6.Way;
import de.nx42.maps4cim.config.texture.ColorDef;
import de.nx42.maps4cim.config.texture.OsmDef;
import de.nx42.maps4cim.config.texture.osm.EntityDef;
import de.nx42.maps4cim.config.texture.osm.NodeDef;
import de.nx42.maps4cim.config.texture.osm.PolygonDef;
import de.nx42.maps4cim.config.texture.osm.WayDef;
import de.nx42.maps4cim.map.ex.OsmXmlFormatException;
import de.nx42.maps4cim.map.texture.osm.primitives.Point;
import de.nx42.maps4cim.map.texture.osm.primitives.Polygon;
import de.nx42.maps4cim.map.texture.osm.primitives.Polyline;
import de.nx42.maps4cim.map.texture.osm.primitives.RenderPrimitive;
import de.nx42.maps4cim.util.gis.Coordinate;
/**
* Filter and sort OSM Entities, convert them to Render Instructions using
* the definitions in the program configuration.
*/
public class EntityConverter {
// assigned
protected OsmDef osm;
protected List<EntityDef> defs;
protected Collection<ColorDef> colors;
protected SimpleOsmDump sink;
// derived
List<OverpassTagMatcher> filters = new LinkedList<OverpassTagMatcher>();
protected Map<OverpassTagMatcher, EntityDef> filterMap = new HashMap<OverpassTagMatcher, EntityDef>();
protected Multimap<EntityDef,Entity> defToEntities;
public EntityConverter(OsmDef config, SimpleOsmDump sink) {
this.osm = config;
this.defs = osm.entities;
this.colors = osm.colors;
this.sink = sink;
createFilters();
}
protected void createFilters() {
for (EntityDef def : defs) {
OverpassTagMatcher matcher = new OverpassTagMatcher(def);
filters.add(matcher);
filterMap.put(matcher, def);
}
}
/*
* 1. Filtern
* 2. Gefilterte Objekte befüllen (Wege -> Nodes)
* 3. Sortierte Sammlungen zurückgeben
*/
public List<RenderContainer> buildRenderContainers() throws OsmXmlFormatException {
// match filters
matchAll();
// create render containers from definitions
// convert to renderable objects, keep original order (of definitions)
List<RenderContainer> rc = new LinkedList<RenderContainer>();
for (EntityDef def : defs) {
Collection<Entity> osmEntities = defToEntities.get(def);
Collection<RenderPrimitive> primitives = getRenderPrimitives(def, osmEntities);
if(primitives.size() > 0) {
rc.add(new RenderContainer(primitives));
}
}
return rc;
}
protected void matchAll() {
List<Node> nodes = sink.getNodes();
List<Way> ways = sink.getWays();
this.defToEntities = HashMultimap.create(filters.size(), (nodes.size() + ways.size()) / filters.size());
matchAll(nodes);
matchAll(ways);
}
protected void matchAll(List<? extends Entity> entities) {
for (Entity entity : entities) {
for (OverpassTagMatcher filter : filters) {
if(filter.matches(entity)) {
defToEntities.put(filterMap.get(filter), entity);
}
}
}
}
protected Collection<RenderPrimitive> getRenderPrimitives(EntityDef def,
Collection<Entity> osmEntities) throws OsmXmlFormatException {
List<RenderPrimitive> primitives = new LinkedList<RenderPrimitive>();
for (Entity entitiy : osmEntities) {
primitives.add(getRenderPrimitive(def, entitiy));
}
return primitives;
}
protected RenderPrimitive getRenderPrimitive(EntityDef def, Entity osmEntity) throws OsmXmlFormatException {
try {
// all type conversion errors in this method are unexpected
if (def instanceof WayDef) {
if (osmEntity instanceof Way) {
List<Node> wayNodes = sink.getNodesById((Way) osmEntity);
return new Polyline(Coordinate.convert(wayNodes), colors, (WayDef) def);
} else {
throw new OsmXmlFormatException("Unexpected OSM Entity Type.");
}
} else if (def instanceof PolygonDef) {
if (osmEntity instanceof Way) {
List<Node> wayNodes = sink.getNodesById((Way) osmEntity);
return new Polygon(Coordinate.convert(wayNodes), colors,
(PolygonDef) def);
} else {
throw new OsmXmlFormatException("Unexpected OSM Entity Type.");
}
} else if (def instanceof NodeDef) {
if (osmEntity instanceof Node) {
return new Point((NodeDef) def, (Node) osmEntity, colors);
} else {
throw new OsmXmlFormatException("Unexpected OSM Entity Type.");
}
} else {
throw new OsmXmlFormatException("Unsupported Entity-Type");
}
} catch(NullPointerException e) {
throw new OsmXmlFormatException("Error while processing OSM XML. " +
"There is probably a dangling entity pointer, which " +
"means that the data is seriously messed up. The entity " +
"that caused this exception is " + osmEntity.toString(), e);
} catch(RuntimeException e) {
throw new OsmXmlFormatException("Unexpected exception while " +
"processing OSM XML.", e);
}
}
}
| 37.912791 | 112 | 0.649287 |
5018a77e7d54567ab73f9d261fd0d197f1220980 | 1,160 | package com.momo5502.stauanalyse.backend;
import com.momo5502.stauanalyse.util.Callback;
import com.momo5502.stauanalyse.util.Downloader;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class AvailableCamerasLoader {
private BackendConnector backendConnector;
public AvailableCamerasLoader(BackendConnector backendConnector) {
this.backendConnector = backendConnector;
}
public void load(final Callback<List<String>> callback) {
backendConnector.cameras(new Downloader(), (value, error) -> {
if (error != null) {
callback.run(null, error);
return;
}
List<String> cameras = parse(value);
callback.run(cameras, null);
});
}
private List<String> parse(byte[] data) {
String text = new String(data);
String[] cameras = text.split("\r?\n");
return Arrays.stream(cameras) //
.map(cam -> cam.trim()) //
.filter(cam -> cam.length() > 0) //
.collect(Collectors.toList());
}
}
| 29.74359 | 71 | 0.593103 |
f301a96d88eb0e5a487f01793ef01f131938b581 | 817 | package sample;
import javafx.fxml.FXMLLoader;
import javafx.event.ActionEvent;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class SampleController extends javafx.application.Application {
public Label helloWorld;
public void sayHelloWorld(ActionEvent actionEvent) {
helloWorld.setText("Hello World!!");
}
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("Hello JavaFX!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| 24.757576 | 77 | 0.685435 |
fa7efb459fa67bef3dbeb06c7d0f2dc3aba63f03 | 1,289 | /*
This class implements the KDebug interface. It logs debug messages to the java console, if the
debug level is high enough.
The default debug level is 1.
*/
package com.teambox.util;
import java.lang.System;
// local
import com.teambox.util.KDebug;
public class KDebugConsole implements KDebug
{
// Debug level
private int dlevel;
// Constructors
public void KDebugConsole()
{
this.set_debug_level(1);
}
public void KDebugConsole(int dlevel)
{
this.set_debug_level(dlevel);
}
// Set the debug level
public void set_debug_level(int dlevel)
{
this.dlevel = dlevel;
}
// Send debug message to console if debug level is high enough
public void debug(int dlevel, String namespace, String s)
{
if (dlevel <= this.dlevel)
{
// Send debug message to java console
System.out.println(dlevel + ":" + namespace + ":" + s);
}
}
// Send log message to console
public void log(String s)
{
// Send log message to java console
System.out.println(s);
}
// Send error message to console
public void error(String s)
{
// Send error message to java console
System.err.println(s);
}
}
| 21.131148 | 97 | 0.61443 |
fa683641fed01b7bf829701e236f811986f8e335 | 2,063 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred.nativetask.buffer;
import java.io.IOException;
import org.junit.Test;
import org.junit.Assert;
public class TestInputBuffer {
@Test
public void testInputBuffer() throws IOException {
final int size = 100;
final InputBuffer input1 = new InputBuffer(BufferType.DIRECT_BUFFER, size);
Assert.assertEquals(input1.getType(), BufferType.DIRECT_BUFFER);
Assert.assertTrue(input1.position() == 0);
Assert.assertTrue(input1.length() == 0);
Assert.assertTrue(input1.remaining() == 0);
Assert.assertTrue(input1.capacity() == size);
final InputBuffer input2 = new InputBuffer(BufferType.HEAP_BUFFER, size);
Assert.assertEquals(input2.getType(), BufferType.HEAP_BUFFER);
Assert.assertTrue(input2.position() == 0);
Assert.assertTrue(input2.length() == 0);
Assert.assertTrue(input2.remaining() == 0);
Assert.assertTrue(input2.capacity() == size);
final InputBuffer input3 = new InputBuffer(new byte[size]);
Assert.assertEquals(input3.getType(), BufferType.HEAP_BUFFER);
Assert.assertTrue(input3.position() == 0);
Assert.assertTrue(input3.length() == 0);
Assert.assertTrue(input3.remaining() == 0);
Assert.assertEquals(input3.capacity(), size);
}
}
| 37.509091 | 79 | 0.730974 |
60a8816b52e1f3016d752304735c12e18c26925c | 11,148 | /*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.testutil;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.shell.ShellStep;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;
import com.facebook.buck.util.MoreCollectors;
import com.facebook.buck.util.RichStream;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.io.ByteStreams;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.junit.Assert;
/** Additional assertions that delegate to JUnit assertions, but with better error messages. */
public final class MoreAsserts {
private static final int BUFFER_SIZE = 8 * 1024;
private MoreAsserts() {}
/**
* Asserts that two sets have the same contents. On failure, prints a readable diff of the two
* sets for easy debugging.
*/
public static <E> void assertSetEquals(Set<E> expected, Set<E> actual) {
Set<E> missing = Sets.difference(expected, actual);
Set<E> extra = Sets.difference(actual, expected);
boolean setsEqual = missing.isEmpty() && extra.isEmpty();
Assert.assertTrue(
String.format("%nMissing elements:%n%s%nExtraneous elements:%n%s", missing, extra),
setsEqual);
}
/** @see #assertIterablesEquals(Iterable, Iterable) */
public static <T extends List<?>> void assertListEquals(List<?> expected, List<?> observed) {
assertIterablesEquals(expected, observed);
}
/** @see #assertIterablesEquals(String, Iterable, Iterable) */
public static <T extends List<?>> void assertListEquals(
String userMessage, List<?> expected, List<?> observed) {
assertIterablesEquals(userMessage, expected, observed);
}
/**
* Equivalent to {@link org.junit.Assert#assertEquals(Object, Object)} except if the assertion
* fails, the message includes information about where the iterables differ.
*/
public static <T extends Iterable<?>> void assertIterablesEquals(
Iterable<?> expected, Iterable<?> observed) {
assertIterablesEquals("" /* userMessage */, expected, observed);
}
/**
* Equivalent to {@link org.junit.Assert#assertEquals(String, Object, Object)} except if the
* assertion fails, the message includes information about where the iterables differ.
*/
public static <T extends Iterable<?>> void assertIterablesEquals(
String userMessage, Iterable<?> expected, Iterable<?> observed) {
// The traditional assertEquals() method should be fine if either List is null.
if (expected == null || observed == null) {
assertEquals(userMessage, expected, observed);
return;
}
String errmsgPart =
String.format(
"expected:[%s] observed:[%s]",
Joiner.on(", ").join(expected), Joiner.on(", ").join(observed));
// Compare each item in the list, one at a time.
Iterator<?> expectedIter = expected.iterator();
Iterator<?> observedIter = observed.iterator();
int index = 0;
while (expectedIter.hasNext()) {
if (!observedIter.hasNext()) {
fail(
prefixWithUserMessage(
userMessage,
"Item "
+ index
+ " does not exist in the "
+ "observed list ("
+ errmsgPart
+ "): "
+ expectedIter.next()));
}
Object expectedItem = expectedIter.next();
Object observedItem = observedIter.next();
assertEquals(
prefixWithUserMessage(
userMessage, "Item " + index + " in the lists should match (" + errmsgPart + ")."),
expectedItem,
observedItem);
++index;
}
if (observedIter.hasNext()) {
fail(
prefixWithUserMessage(
userMessage,
"Extraneous item %s in the observed list (" + errmsgPart + "): %s.",
index,
observedIter.next()));
}
}
public static <Item, Container extends Iterable<Item>> void assertContainsOne(
Container container, Item expectedItem) {
assertContainsOne(/* userMessage */ Iterables.toString(container), container, expectedItem);
}
public static <Item, Container extends Iterable<Item>> void assertContainsOne(
String userMessage, Container container, Item expectedItem) {
int seen = 0;
for (Item item : container) {
if (expectedItem.equals(item)) {
seen++;
}
}
if (seen < 1) {
failWith(
userMessage,
"Item '" + expectedItem + "' not found in container, " + "expected to find one.");
}
if (seen > 1) {
failWith(
userMessage,
"Found "
+ Integer.valueOf(seen)
+ " occurrences of '"
+ expectedItem
+ "' in container, expected to find only one.");
}
}
/**
* Asserts that every {@link com.facebook.buck.step.Step} in the observed list is a {@link
* com.facebook.buck.shell.ShellStep} whose shell command arguments match those of the
* corresponding entry in the expected list.
*/
public static void assertShellCommands(
String userMessage, List<String> expected, List<Step> observed, ExecutionContext context) {
Iterator<String> expectedIter = expected.iterator();
Iterator<Step> observedIter = observed.iterator();
Joiner joiner = Joiner.on(" ");
while (expectedIter.hasNext() && observedIter.hasNext()) {
String expectedShellCommand = expectedIter.next();
Step observedStep = observedIter.next();
if (!(observedStep instanceof ShellStep)) {
failWith(userMessage, "Observed command must be a shell command: " + observedStep);
}
ShellStep shellCommand = (ShellStep) observedStep;
String observedShellCommand = joiner.join(shellCommand.getShellCommand(context));
assertEquals(userMessage, expectedShellCommand, observedShellCommand);
}
if (expectedIter.hasNext()) {
failWith(userMessage, "Extra expected command: " + expectedIter.next());
}
if (observedIter.hasNext()) {
failWith(userMessage, "Extra observed command: " + observedIter.next());
}
}
/**
* Invokes the {@link Step#getDescription(ExecutionContext)} method on each of the observed steps
* to create a list of strings and compares it to the expected value.
*/
public static void assertSteps(
String userMessage,
List<String> expectedStepDescriptions,
List<Step> observedSteps,
final ExecutionContext executionContext) {
ImmutableList<String> commands =
observedSteps
.stream()
.map(step -> step.getDescription(executionContext))
.collect(MoreCollectors.toImmutableList());
assertListEquals(userMessage, expectedStepDescriptions, commands);
}
public static void assertDepends(String userMessage, BuildRule rule, BuildRule dep) {
assertDepends(userMessage, rule, dep.getBuildTarget());
}
public static void assertDepends(String userMessage, BuildRule rule, BuildTarget dep) {
assertDepends(userMessage, rule.getBuildDeps(), dep);
}
public static void assertDepends(
String userMessage, Collection<BuildRule> ruleDeps, BuildTarget dep) {
for (BuildRule realDep : ruleDeps) {
BuildTarget target = realDep.getBuildTarget();
if (target.equals(dep)) {
return;
}
}
fail(userMessage);
}
public static <T> void assertOptionalValueEquals(
String userMessage, T expectedValue, Optional<T> optionalValue) {
if (!optionalValue.isPresent()) {
failWith(userMessage, "Optional value is not present.");
}
assertEquals(userMessage, expectedValue, optionalValue.get());
}
public static void assertContentsEqual(Path one, Path two) throws IOException {
Preconditions.checkNotNull(one);
Preconditions.checkNotNull(two);
if (one.equals(two)) {
return;
}
if (Files.size(one) != Files.size(two)) {
fail(
String.format(
"File sizes differ: %s (%d bytes), %s (%d bytes)",
one, Files.size(one), two, Files.size(two)));
}
try (InputStream ois = Files.newInputStream(one);
InputStream tis = Files.newInputStream(two)) {
byte[] bo = new byte[BUFFER_SIZE];
byte[] bt = new byte[BUFFER_SIZE];
while (true) {
int read1 = ByteStreams.read(ois, bo, 0, BUFFER_SIZE);
int read2 = ByteStreams.read(tis, bt, 0, BUFFER_SIZE);
if (read1 != read2 || !Arrays.equals(bo, bt)) {
fail(String.format("Contents of files differ: %s, %s", one, two));
} else if (read1 != BUFFER_SIZE) {
return;
}
}
}
}
/**
* Asserts that two strings are equal, but compares them in chunks so that Intellij will show the
* diffs when the assertion fails.
*/
public static void assertLargeStringsEqual(String expected, String content) {
List<String> expectedChunks = chunkify(expected);
List<String> contentChunks = chunkify(content);
for (int i = 0; i < Math.min(expectedChunks.size(), contentChunks.size()); i++) {
assertEquals("Failed at index: " + i, expectedChunks.get(i), contentChunks.get(i));
}
// We could check this first, but it's usually more useful to see the first difference than to
// just see that the two strings are different length.
assertEquals(expectedChunks.size(), contentChunks.size());
}
private static List<String> chunkify(String data) {
return RichStream.from(Iterables.partition(Arrays.asList(data.split("\\n")), 1000))
.map((l) -> Joiner.on("\n").join(l))
.toImmutableList();
}
private static String prefixWithUserMessage(
@Nullable String userMessage, String message, Object... formatArgs) {
return (userMessage == null ? "" : userMessage + " ") + String.format(message, formatArgs);
}
private static void failWith(@Nullable String userMessage, String message) {
fail(prefixWithUserMessage(userMessage, message));
}
}
| 36.194805 | 99 | 0.665231 |
25f2abaed1c6a683f3ecce1ad5dc53d65db64cb8 | 1,046 | package com.ubx.tools;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.ubx.ocean.http.ApiResponse;
import com.ubx.ocean.http.RetrofitManager;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RetrofitManager.getCall("https://service.urovo.com:911/").create(HttpService.class)
.getbaidu().enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
System.out.println(response.body().data);
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
}
});
// RetrofitManager.get("https://service.urovo.com:911/").create(HttpService.class).
}
} | 30.764706 | 92 | 0.67782 |
aed13ee89f6825343b095798ad73c7e26cce84e8 | 3,329 | /*
* Copyright (c) 2022 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.opengauss.mppdbide.view.ui.visualexplainplan;
import org.opengauss.mppdbide.presentation.visualexplainplan.AbstractExplainPlanPropertyCore;
import org.opengauss.mppdbide.presentation.visualexplainplan.ExplainPlanNodePropertiesCore;
import org.opengauss.mppdbide.presentation.visualexplainplan.ExplainPlanOverAllPlanPropertiesCore;
import org.opengauss.mppdbide.presentation.visualexplainplan.ExplainPlanPresentation;
/**
*
* Title: class
*
* Description: The Class VisualExplainPlanUIPresentation.
*
* @since 3.0.0
*/
public class VisualExplainPlanUIPresentation {
private ExplainPlanPresentation presenter;
private String operationType;
private String tabID;
private Object operationObject;
/**
* Instantiates a new visual explain plan UI presentation.
*
* @param presentation the presentation
*/
public VisualExplainPlanUIPresentation(String TabID, ExplainPlanPresentation presentation) {
this.tabID = TabID;
this.presenter = presentation;
}
/**
* Gets the explain plan window handler.
*
* @return the explain plan window handler
*/
public String getExplainPlanTabId() {
return tabID;
}
/**
* Gets the presenter.
*
* @return the presenter
*/
public ExplainPlanPresentation getPresenter() {
return presenter;
}
/**
* Gets the operation type.
*
* @return the operation type
*/
public String getOperationType() {
return operationType;
}
/**
* Gets the operation object.
*
* @return the operation object
*/
public Object getOperationObject() {
return operationObject;
}
/**
* Sets the operation object.
*
* @param operationObject the new operation object
*/
public void setOperationObject(Object operationObject) {
this.operationObject = operationObject;
}
/**
* Sets the operation type.
*
* @param operationType the new operation type
*/
public void setOperationType(String operationType) {
this.operationType = operationType;
}
/**
* Gets the suitable property presenter.
*
* @return the suitable property presenter
*/
public AbstractExplainPlanPropertyCore getSuitablePropertyPresenter() {
if (this.getOperationType().equals(VisualExplainPlanConstants.VISUAL_EXPLAIN_OPTYPE_ALLPROPERTY)) {
return new ExplainPlanOverAllPlanPropertiesCore(this.presenter);
} else if (this.getOperationType().equals(VisualExplainPlanConstants.VISUAL_EXPLAIN_PERNODE_DETAILS)) {
return (ExplainPlanNodePropertiesCore) this.getOperationObject();
}
return null;
}
}
| 28.452991 | 111 | 0.689396 |
db3bb146d9080995bd047ce2bb139521004a1a1b | 4,162 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.xml.ws.encoding;
import com.sun.istack.NotNull;
import com.sun.xml.ws.api.message.AttachmentSet;
import com.sun.xml.ws.api.message.Message;
import com.sun.xml.ws.api.message.Packet;
import com.sun.xml.ws.api.pipe.Codec;
import com.sun.xml.ws.api.pipe.ContentType;
import com.sun.xml.ws.api.pipe.StreamSOAPCodec;
import com.sun.xml.ws.api.streaming.XMLStreamReaderFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
/**
*
* @author [email protected]
*/
public class LazyStreamCodec implements StreamSOAPCodec{
private StreamSOAPCodec codec = null;
/** Creates a new instance of SecurityStream11Codec */
public LazyStreamCodec(StreamSOAPCodec codec) {
this.codec = codec;
}
public Message decode(XMLStreamReader reader) {
return new com.sun.xml.ws.message.stream.LazyStreamBasedMessage(reader,codec);
}
public @NotNull Message decode(@NotNull XMLStreamReader reader, AttachmentSet att){
return new com.sun.xml.ws.message.stream.LazyStreamBasedMessage(reader,codec, att);
}
public String getMimeType() {
return codec.getMimeType();
}
public ContentType getStaticContentType(Packet packet) {
return codec.getStaticContentType(packet);
}
public ContentType encode(Packet packet, OutputStream outputStream) throws IOException {
return codec.encode(packet,outputStream);
}
public ContentType encode(Packet packet, WritableByteChannel writableByteChannel) {
return codec.encode(packet,writableByteChannel);
}
public Codec copy() {
return this;
}
public void decode(InputStream inputStream, String string, Packet packet) throws IOException {
XMLStreamReader reader = XMLStreamReaderFactory.create(null, inputStream,true);
packet.setMessage(decode(reader));
}
public void decode(ReadableByteChannel readableByteChannel, String string, Packet packet) {
throw new UnsupportedOperationException();
}
}
| 40.019231 | 98 | 0.740029 |
758f3945a40d7b1fdef41285bf0dd5360c67b123 | 13,007 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package rmi;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bson.Document;
/**
*
* @author pc
*/
public class DB {
private static DB instance;
private MongoClient client;
private MongoDatabase database;
private MongoCollection<Document> admin;
private MongoCollection<Document> thirdPartycompany;
private MongoCollection<Document> bank;
private MongoCollection<Document> Employee;
private MongoCollection<Document> Event;
private MongoCollection<Document> reservee;
private MongoCollection<Document> Visitor;
private MongoCollection<Document> PaymentMethod;
private Gson gson = new Gson();
public DB() {
Logger mongoLogger = Logger.getLogger("org.mongodb.driver");
mongoLogger.setLevel(Level.SEVERE);
// Initialize
client = new MongoClient();
database = client.getDatabase("Company"); // Database name
admin = database.getCollection("admin"); // Collection name
thirdPartycompany = database.getCollection("thirdPartycompany");
bank = database.getCollection("bank");
Employee = database.getCollection("Employee");
Event = database.getCollection("Event");
reservee = database.getCollection("reservee");
Visitor = database.getCollection("Visitor");
PaymentMethod = database.getCollection("PaymentMethod");
}
public static DB getinstance() {
if (instance == null) {
instance = new DB();
}
return instance;
}
public void insertAdmin(Admin s) {
ArrayList<Document> docs = admin.find().into(new ArrayList<Document>());
if ((docs.size() > 0)) {
admin.deleteOne(Filters.eq("Email_Address", s.getEmail_Address()));
admin.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Admin inserted.");
} else {
admin.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Admin inserted.");
}
}
public boolean insertthirdPartycompany(ThirdPartyCompany s) {
ArrayList<Venue> result = new ArrayList();
ArrayList<Document> docs = thirdPartycompany.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, ThirdPartyCompany.class).getName().equals(s.getName()))) {
return false;
}
}
thirdPartycompany.insertOne(Document.parse(gson.toJson(s)));
System.out.println("ThirdPartyCompany inserted.");
return true;
}
public boolean insertbank(Bank s) {
ArrayList<Venue> result = new ArrayList();
ArrayList<Document> docs = bank.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, Bank.class).getName().equals(s.getName()))) {
return false;
}
}
bank.insertOne(Document.parse(gson.toJson(s)));
System.out.println("bank inserted.");
return true;
}
public boolean insertEmployee(Employee s) {
ArrayList<Venue> result = new ArrayList();
ArrayList<Document> docs = Employee.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, Employee.class).getEmail_Address().equals(s.getEmail_Address()))) {
return false;
}
}
Employee.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Employee inserted.");
return true;
}
public boolean insertEvent(Event s) {
ArrayList<Venue> result = new ArrayList();
ArrayList<Document> docs = Event.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, Event.class).getEventID() == s.getEventID())) {
return false;
}
}
Event.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Event inserted.");
return true;
}
public boolean insertreservee(Reservee s) {
ArrayList<Document> docs = reservee.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, Reservee.class).getEmail_Address().equals(s.getEmail_Address()))) {
return false;
}
}
reservee.insertOne(Document.parse(gson.toJson(s)));
System.out.println("reservee inserted.");
return true;
}
public boolean insertVisitor(Visitor s) {
ArrayList<Venue> result = new ArrayList();
ArrayList<Document> docs = Visitor.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, Visitor.class).getEmail_Address().equals(s.getEmail_Address()))) {
return false;
}
}
Visitor.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Visitor inserted.");
return true;
}
public boolean insertPaymentMethod(PaymentMethod s) {
ArrayList<Venue> result = new ArrayList();
ArrayList<Document> docs = PaymentMethod.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, PaymentMethod.class).getCardNumber() == s.getCardNumber())) {
return false;
}
}
PaymentMethod.insertOne(Document.parse(gson.toJson(s)));
System.out.println("PaymentMethod inserted.");
return true;
}
public Admin loginAdmin(String Email, String Password) {
ArrayList<Document> docs = admin.find(Filters.eq("Email_Address", Email)).into(new ArrayList<Document>());
if (docs.size() > 0) {
String jsonResult = docs.get(0).toJson();
Admin a = gson.fromJson(jsonResult, Admin.class);
if (a.getPassword().equals(Password)) {
return a;
}
}
return null;
}
public ThirdPartyCompany FindThirdPartybyName(String Name) {
ArrayList<Document> docs = thirdPartycompany.find(Filters.eq("name", Name)).into(new ArrayList<Document>());
String jsonResult = docs.get(0).toJson();
ThirdPartyCompany a = gson.fromJson(jsonResult, ThirdPartyCompany.class);
return a;
}
public Bank FindBankBYname(String Name) {
ArrayList<Document> docs = bank.find(Filters.eq("Name", Name)).into(new ArrayList<Document>());
String jsonResult = docs.get(0).toJson();
Bank a = gson.fromJson(jsonResult, Bank.class);
return a;
}
public Employee loginemEmployee(String Email, String Password) {
ArrayList<Document> docs = Employee.find(Filters.eq("Email_Address", Email)).into(new ArrayList<Document>());
String jsonResult = docs.get(0).toJson();
Employee a = gson.fromJson(jsonResult, Employee.class);
System.out.println(a.getPassword());
System.out.println(Password);
if (a.getPassword().equals(Password)) {
return a;
}
return null;
}
public Event findEventByID(int ID) {
ArrayList<Document> docs = Event.find(Filters.eq("eventID", ID)).into(new ArrayList<Document>());
String jsonResult = docs.get(0).toJson();
Event a = gson.fromJson(jsonResult, Event.class);
return a;
}
public Reservee LoginReservee(String Email, String Password) {
ArrayList<Document> docs = reservee.find(Filters.eq("Email_Address", Email)).into(new ArrayList<Document>());
String jsonResult = docs.get(0).toJson();
Reservee a = gson.fromJson(jsonResult, Reservee.class);
System.out.println(a.getPassword());
System.out.println(Password);
if (a.getPassword().equals(Password)) {
return a;
}
return null;
}
public Visitor loginVisitor(String Email, String Password) {
ArrayList<Document> docs = Visitor.find(Filters.eq("Email_Address", Email)).into(new ArrayList<Document>());
String jsonResult = docs.get(0).toJson();
Visitor a = gson.fromJson(jsonResult, Visitor.class);
System.out.println(a.getPassword());
System.out.println(Password);
if (a.getPassword().equals(Password)) {
return a;
}
return null;
}
/**
*
*/
public void UpdateAdmin() {
Admin s = Admin.getInstance();
ArrayList<Document> docs = admin.find().into(new ArrayList<Document>());
if ((docs.size() > 0)) {
admin.deleteOne(Filters.eq("Email_Address", s.getEmail_Address()));
admin.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Admin inserted.");
} else {
admin.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Admin inserted.");
}
}
public void UpdatethirdPartycompany(ThirdPartyCompany s) {
ArrayList<Document> docs = thirdPartycompany.find(Filters.eq("name", s.getName())).into(new ArrayList<Document>());
thirdPartycompany.deleteOne(Filters.eq("name", s.getName()));
thirdPartycompany.insertOne(Document.parse(gson.toJson(s)));
System.out.println("ThirdPartyCompany inserted.");
}
public void UpdateBank(Bank s) {
ArrayList<Document> docs = bank.find(Filters.eq("Name", s.getName())).into(new ArrayList<Document>());
bank.deleteOne(Filters.eq("Name", s.getName()));
bank.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Bank inserted.");
}
public void UpdateEmployee(Employee s) {
ArrayList<Document> docs = Employee.find(Filters.eq("Email_Address", s.getEmail_Address())).into(new ArrayList<Document>());
Employee.deleteOne(Filters.eq("Email_Address", s.getEmail_Address()));
Employee.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Employee inserted.");
}
public void UpdateEvent(Event s) {
ArrayList<Document> docs = Event.find(Filters.eq("eventID", s.getEventID())).into(new ArrayList<Document>());
Event.deleteOne(Filters.eq("eventID", s.getEventID()));
Event.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Employee inserted.");
}
public void UpdateEvent(Reservee s) {
ArrayList<Document> docs = reservee.find(Filters.eq("Email_Address", s.getEmail_Address())).into(new ArrayList<Document>());
reservee.deleteOne(Filters.eq("Email_Address", s.getEmail_Address()));
reservee.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Employee inserted.");
}
public void UpdateVisitor(Visitor s) {
ArrayList<Document> docs = Visitor.find(Filters.eq("Email_Address", s.getEmail_Address())).into(new ArrayList<Document>());
Visitor.deleteOne(Filters.eq("Email_Address", s.getEmail_Address()));
Visitor.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Visitor inserted.");
}
public void UpdatePaymentMethod(PaymentMethod s) {
ArrayList<Document> docs = PaymentMethod.find(Filters.eq("CardNumber", s.getCardNumber())).into(new ArrayList<Document>());
PaymentMethod.deleteOne(Filters.eq("CardNumber", s.getCardNumber()));
PaymentMethod.insertOne(Document.parse(gson.toJson(s)));
System.out.println("Employee inserted.");
}
public int getVenuesMaxID(){
int max=0;
ArrayList<Document> docs = Event.find().into(new ArrayList<Document>());
for (int i = 0; i < docs.size(); i++) {
String jsonResult = docs.get(i).toJson();
if ((gson.fromJson(jsonResult, Event.class).getEventID() >max)) {
max=gson.fromJson(jsonResult, Event.class).getEventID();
}
}
return max;
}
}
| 38.143695 | 132 | 0.624433 |
b6d0f2cfe4578e9416e1b96ea06ad6a6577af9f6 | 1,413 | package com.ontology2.telepath.normalizeMonthlies;
import com.ontology2.centipede.parser.ContextualConverter;
import com.ontology2.centipede.parser.HasOptions;
import com.ontology2.centipede.parser.Option;
import com.ontology2.centipede.parser.Required;
import com.ontology2.telepath.bloom.CreateBloomOptions;
import org.apache.hadoop.fs.Path;
import java.util.List;
public class NormalizeMonthliesOptions implements HasOptions {
@Option(description="input and output file default directory")
public String dir;
@Option(description="year and month")
@Required
public String yrmo;
@Option(description="input files",contextualConverter=PathConverter.class)
public List<String> input;
@Option(description="output file",contextualConverter=PathConverter.class)
public String output;
public static class PathConverter implements ContextualConverter<String> {
public String convert(String value, HasOptions that) {
String defaultDir=getDefaultDir((NormalizeMonthliesOptions) that);
if(defaultDir.isEmpty())
return value;
Path there=new Path(defaultDir,value);
return there.toString();
}
public String getDefaultDir(NormalizeMonthliesOptions that) {
return that.dir;
}
}
@Option(name="R",description="number of reducers")
public int reducerCount;
}
| 31.4 | 78 | 0.728238 |
29078f255210cdd13bafe0fe07cda3c6def5353d | 1,162 | package de.uni_kassel.vs.cn.planDesigner.view.editor;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Polyline;
import java.util.List;
public class MouseClickHandler implements EventHandler<MouseEvent> {
private List<TransitionContainer> transitionContainers;
public MouseClickHandler(List<TransitionContainer> transitionContainers) {
this.transitionContainers = transitionContainers;
}
@Override
public void handle(MouseEvent event) {
if (event.getTarget() instanceof BendpointContainer) {
return;
}
Polyline polyline = null;
if (event.getTarget() instanceof Polyline) {
polyline = (Polyline) event.getTarget();
}
final Polyline finalPolyline = polyline;
transitionContainers
.forEach(t -> {
if (t.getVisualRepresentation().equals(finalPolyline)) {
t.setBendpointContainerVisibility(true);
} else {
t.setBendpointContainerVisibility(false);
}
});
}
}
| 29.794872 | 78 | 0.629088 |
1ff6e7101444994cafa3c34a2c096404477f5d61 | 635 | package starter.lichess.screenplay.questions;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.serenitybdd.screenplay.targets.Target;
import starter.lichess.screenplay.pages.InviteAFriendPage;
import static starter.lichess.screenplay.pages.InviteAFriendPage.CHALLENGE_URL;
public class Challenge implements Question<String> {
@Override
public String answeredBy(Actor actor) {
return CHALLENGE_URL.resolveFor(actor).getValue();
}
public static Challenge url() {
return new Challenge();
}
}
| 28.863636 | 79 | 0.784252 |
5e7da69c0622a8a9adca2e13425b5a224644a6fe | 528 | //: annotations/Multiplier.java
// APT-based annotation processing.
package com.skillip.java.annotations;
@ExtractInterface("IMultiplier")
public class Multiplier {
public int multiply(int x, int y) {
int total = 0;
for(int i = 0; i < x; i++)
total = add(total, y);
return total;
}
private int add(int x, int y) { return x + y; }
public static void main(String[] args) {
Multiplier m = new Multiplier();
System.out.println("11*16 = " + m.multiply(11, 16));
}
} /* Output:
11*16 = 176
*///:~
| 25.142857 | 56 | 0.628788 |
04431258ccd3d61cf316ce49d356c2e212b136e5 | 1,258 | /*
* Copyright 2012 Soichiro Kashima
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androidformenhancer.sample.demos;
import com.androidformenhancer.annotation.Required;
import com.androidformenhancer.annotation.When;
import com.androidformenhancer.annotation.Widget;
/**
* @author Soichiro Kashima
*/
public class CustomRequiredWhenForm {
@Widget(id = R.id.spn_reason, nameResId = R.string.form_custom_required_when_reason)
public String reason;
@Widget(id = R.id.textfield_reason_other, nameResId = R.string.form_custom_required_when_reason_other,
validateAfter = R.id.spn_reason)
@Required(when = {
@When(id = R.id.spn_reason, equalsTo = "2")
})
public String reasonOther;
}
| 32.25641 | 106 | 0.741653 |
7b29788136501f89b33d18b2e2fc8a7ec63ace7f | 369 | package swarm_wars_library.sound;
import processing.sound.SoundFile;
import processing.core.PApplet;
// Add via composition to relevant entity.
public class PlayShotSound{
private SoundFile soundFile;
public PlayShotSound(PApplet sketch){
// this.soundFile = new SoundFile(sketch, "resources/sound/vibraphon.aiff");
}
public void update(){
}
} | 21.705882 | 80 | 0.745257 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.