text
stringlengths 10
2.72M
|
|---|
package counter;
import java.lang.*;
import bsh.Interpreter;
import bsh.EvalError;
public class CALCULATOR extends javax.swing.JFrame
{
double radianToDegreeConstant = 180/Math.PI;
String inputString , outputString , oldString , newString , finalString;
//angle type combo box item list
String[] angleTypeItemList = new String[]{"Radian","Degree"};
Interpreter interpreter = new Interpreter();
//function to get numbers as string only including decimal point
public double asinh(double x)
{
return Math.log(x + Math.sqrt(x*x + 1.0));
}
public double acosh(double x)
{
return Math.log(x + Math.sqrt(x*x - 1.0));
}
public double atanh(double x)
{
return 0.5*Math.log( (x + 1.0) / (x - 1.0) );
}
public String captureNumber(String any)
{
String newString = "";
char[] anyArray = new char[any.length()];
anyArray=any.toCharArray();
int i=anyArray.length;
int d = i-1;
while(d>=0)
{
if((anyArray[d]>='0'&&anyArray[d]<='9')||anyArray[d]=='.')
{
newString = newString + anyArray[d];
}
else
{
break;
}
d--;
}
return newString;
}
public void asinhInverseSet()
{
if(!calculatorInputTextField.getText().equals(""))
{
//get input from text field
inputString = calculatorInputTextField.getText();
//capture the number reversely
String s1 = captureNumber(inputString);
//reverse the string
String s2 = reverseString(s1);
//parse string to double
double x1 = Double.parseDouble(s2);
//get the asinh to double
double x2 = asinh(x1);
//convert the number to string
String s3 = ""+x2;
//deference between the input string and captured string
int difference = inputString.length()-s1.length();
//make substring from old input string
String s4 = inputString.substring(0, difference);
//add input and new string to the string
String s5 = s4+s3;
//set it to the output textField
calculatorInputTextField.setText(s5);
}
}
public void acoshInverseSet()
{
if(!calculatorInputTextField.getText().equals(""))
{
//get input from text field
inputString = calculatorInputTextField.getText();
//capture the number reversely
String s1 = captureNumber(inputString);
//reverse the string
String s2 = reverseString(s1);
//parse string to double
double x1 = Double.parseDouble(s2);
//get the asinh to double
double x2 = acosh(x1);
//convert the number to string
String s3 = ""+x2;
//deference between the input string and captured string
int difference = inputString.length()-s1.length();
//make substring from old input string
String s4 = inputString.substring(0, difference);
//add input and new string to the string
String s5 = s4+s3;
//set it to the output textField
calculatorInputTextField.setText(s5);
}
}
public void atanhInverseSet()
{
if(!calculatorInputTextField.getText().equals(""))
{
//get input from text field
inputString = calculatorInputTextField.getText();
//capture the number reversely
String s1 = captureNumber(inputString);
//reverse the string
String s2 = reverseString(s1);
//parse string to double
double x1 = Double.parseDouble(s2);
//get the asinh to double
double x2 = atanh(x1);
//convert the number to string
String s3 = ""+x2;
//deference between the input string and captured string
int difference = inputString.length()-s1.length();
//make substring from old input string
String s4 = inputString.substring(0, difference);
//add input and new string to the string
String s5 = s4+s3;
//set it to the output textField
calculatorInputTextField.setText(s5);
}
}
//function to get numbers as string without decimal point
public String captureNumberWithoutDecimal(String any)
{
String newString = "";
char[] anyArray = new char[any.length()];
anyArray=any.toCharArray();
int i=anyArray.length;
int d = i-1;
while(d>=0)
{
if((anyArray[d]>='0'&&anyArray[d]<='9'))
{
newString = newString + anyArray[d];
}
else
{
break;
}
d--;
}
return newString;
}
//function to reverse a string
public String reverseString(String anyString1)
{
int anyString1Length = anyString1.length();
int anyString1FinalIndex = anyString1Length-1;
char[] anyString1Array = new char[anyString1Length];
anyString1Array = anyString1.toCharArray();
String finalString1 ="";
for(int i=anyString1FinalIndex;i>=0;i--)
{
finalString1 = finalString1 + anyString1Array[i] ;
}
return finalString1;
}
//function to calculate factorial
public int factorial(int x)
{
if(x==0)
{
return 1;
}
if(x==1)
{
return 1;
}
return x* factorial(x-1);
}
/**
* Creates new form CALCULATOR
*/
public CALCULATOR()
{
initComponents();
getContentPane().setBackground(java.awt.Color.gray);
//Initialize the angle type combo box model list with constructor
//It will help to initialize the value of model at the starting of converter JFrame
}
/**
* 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() {
calculatorOneButton = new javax.swing.JButton();
calculatorTwoButton = new javax.swing.JButton();
calculatorThreeButton = new javax.swing.JButton();
calculatorFourButton = new javax.swing.JButton();
calculatorFiveButton = new javax.swing.JButton();
calculatorSixButton = new javax.swing.JButton();
calculatorSevenButton = new javax.swing.JButton();
calculatorEightButton = new javax.swing.JButton();
calculatorNineButton = new javax.swing.JButton();
calculatorZeroButton = new javax.swing.JButton();
calculatorDecimalPointButton = new javax.swing.JButton();
calculatorInputTextField = new javax.swing.JTextField();
calculatorEqualButton = new javax.swing.JButton();
calculatorPlusButton = new javax.swing.JButton();
calculatorMinusButton = new javax.swing.JButton();
calculatorMultiplyButton = new javax.swing.JButton();
calculatorDivideButton = new javax.swing.JButton();
calculatorStartingBracketButton = new javax.swing.JButton();
calculatorEndingBracketButton = new javax.swing.JButton();
calculatorXToThePowerYButton = new javax.swing.JButton();
calculatorEToThePowerYButton = new javax.swing.JButton();
calculatorOutputTextField = new javax.swing.JTextField();
calculatorCommaButton = new javax.swing.JButton();
calculatorBackspaceButton = new javax.swing.JButton();
calculatorClearButton = new javax.swing.JButton();
calculatorLogBase10Button = new javax.swing.JButton();
calculatorLogBaseEButton = new javax.swing.JButton();
calculatorSineButton = new javax.swing.JButton();
calculatorCosineButton = new javax.swing.JButton();
calculatorTangentButton = new javax.swing.JButton();
calculatorHyperbolicSineButton = new javax.swing.JButton();
calculatorHyperbolicCosineButton = new javax.swing.JButton();
calculatorHyperbolicTangentButton = new javax.swing.JButton();
calculatorSineInverseButton = new javax.swing.JButton();
calculatorCosineInverseButton = new javax.swing.JButton();
calculatorTangentInverseButton = new javax.swing.JButton();
calculatorRandomButton = new javax.swing.JButton();
calculatorSquareRootButton = new javax.swing.JButton();
calculatorCubicRootButton = new javax.swing.JButton();
calculatorFactorialButton = new javax.swing.JButton();
calculatorFloorButton = new javax.swing.JButton();
calculatorCellingButton = new javax.swing.JButton();
calculatorPiButton = new javax.swing.JButton();
calculator10ToThePowerXButton = new javax.swing.JButton();
calculatorAnswerButton = new javax.swing.JButton();
calculatorBackToMenuButton = new javax.swing.JButton();
calculatorHyperbolicSineInverseButton = new javax.swing.JButton();
calculatorHyperbolicCosineInverseButton = new javax.swing.JButton();
calculatorHyperbolicTangentInverseButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("CALCULATOR");
setBackground(new java.awt.Color(0, 0, 0));
setForeground(new java.awt.Color(0, 0, 0));
setName("CALCULATOR_Frame"); // NOI18N
calculatorOneButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorOneButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorOneButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorOneButton.setText("1");
calculatorOneButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorOneButtonActionPerformed(evt);
}
});
calculatorTwoButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorTwoButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorTwoButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorTwoButton.setText("2");
calculatorTwoButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorTwoButtonActionPerformed(evt);
}
});
calculatorThreeButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorThreeButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorThreeButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorThreeButton.setText("3");
calculatorThreeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorThreeButtonActionPerformed(evt);
}
});
calculatorFourButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorFourButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorFourButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorFourButton.setText("4");
calculatorFourButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorFourButtonActionPerformed(evt);
}
});
calculatorFiveButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorFiveButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorFiveButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorFiveButton.setText("5");
calculatorFiveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorFiveButtonActionPerformed(evt);
}
});
calculatorSixButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorSixButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorSixButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorSixButton.setText("6");
calculatorSixButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorSixButtonActionPerformed(evt);
}
});
calculatorSevenButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorSevenButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorSevenButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorSevenButton.setText("7");
calculatorSevenButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorSevenButtonActionPerformed(evt);
}
});
calculatorEightButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorEightButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorEightButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorEightButton.setText("8");
calculatorEightButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorEightButtonActionPerformed(evt);
}
});
calculatorNineButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorNineButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorNineButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorNineButton.setText("9");
calculatorNineButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorNineButtonActionPerformed(evt);
}
});
calculatorZeroButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorZeroButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorZeroButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorZeroButton.setText("0");
calculatorZeroButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorZeroButtonActionPerformed(evt);
}
});
calculatorDecimalPointButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorDecimalPointButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorDecimalPointButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorDecimalPointButton.setText(".");
calculatorDecimalPointButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorDecimalPointButtonActionPerformed(evt);
}
});
calculatorInputTextField.setEditable(false);
calculatorInputTextField.setBackground(new java.awt.Color(0, 0, 0));
calculatorInputTextField.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorInputTextField.setForeground(new java.awt.Color(0, 255, 0));
calculatorEqualButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorEqualButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorEqualButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorEqualButton.setText("=");
calculatorEqualButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorEqualButtonActionPerformed(evt);
}
});
calculatorPlusButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorPlusButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorPlusButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorPlusButton.setText("+");
calculatorPlusButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorPlusButtonActionPerformed(evt);
}
});
calculatorMinusButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorMinusButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorMinusButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorMinusButton.setText("-");
calculatorMinusButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorMinusButtonActionPerformed(evt);
}
});
calculatorMultiplyButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorMultiplyButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorMultiplyButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorMultiplyButton.setText("*");
calculatorMultiplyButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorMultiplyButtonActionPerformed(evt);
}
});
calculatorDivideButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorDivideButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorDivideButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorDivideButton.setText("/");
calculatorDivideButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorDivideButtonActionPerformed(evt);
}
});
calculatorStartingBracketButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorStartingBracketButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorStartingBracketButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorStartingBracketButton.setText("(");
calculatorStartingBracketButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorStartingBracketButtonActionPerformed(evt);
}
});
calculatorEndingBracketButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorEndingBracketButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorEndingBracketButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorEndingBracketButton.setText(")");
calculatorEndingBracketButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorEndingBracketButtonActionPerformed(evt);
}
});
calculatorXToThePowerYButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorXToThePowerYButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorXToThePowerYButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorXToThePowerYButton.setText("x^y");
calculatorXToThePowerYButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorXToThePowerYButtonActionPerformed(evt);
}
});
calculatorEToThePowerYButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorEToThePowerYButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorEToThePowerYButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorEToThePowerYButton.setText(" e^x");
calculatorEToThePowerYButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorEToThePowerYButtonActionPerformed(evt);
}
});
calculatorOutputTextField.setEditable(false);
calculatorOutputTextField.setBackground(new java.awt.Color(0, 0, 0));
calculatorOutputTextField.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorOutputTextField.setForeground(new java.awt.Color(0, 255, 0));
calculatorCommaButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorCommaButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorCommaButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorCommaButton.setText(",");
calculatorCommaButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorCommaButtonActionPerformed(evt);
}
});
calculatorBackspaceButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorBackspaceButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorBackspaceButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorBackspaceButton.setText("BACKSPACE");
calculatorBackspaceButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorBackspaceButtonActionPerformed(evt);
}
});
calculatorClearButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorClearButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorClearButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorClearButton.setText("CLEAR");
calculatorClearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorClearButtonActionPerformed(evt);
}
});
calculatorLogBase10Button.setBackground(new java.awt.Color(0, 0, 0));
calculatorLogBase10Button.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorLogBase10Button.setForeground(new java.awt.Color(0, 255, 0));
calculatorLogBase10Button.setText("log");
calculatorLogBase10Button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorLogBase10ButtonActionPerformed(evt);
}
});
calculatorLogBaseEButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorLogBaseEButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorLogBaseEButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorLogBaseEButton.setText("ln");
calculatorLogBaseEButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorLogBaseEButtonActionPerformed(evt);
}
});
calculatorSineButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorSineButton.setFont(new java.awt.Font("Lucida Console", 1, 13)); // NOI18N
calculatorSineButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorSineButton.setText("sin");
calculatorSineButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorSineButtonActionPerformed(evt);
}
});
calculatorCosineButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorCosineButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorCosineButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorCosineButton.setText("cos");
calculatorCosineButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorCosineButtonActionPerformed(evt);
}
});
calculatorTangentButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorTangentButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorTangentButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorTangentButton.setText("tan");
calculatorTangentButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorTangentButtonActionPerformed(evt);
}
});
calculatorHyperbolicSineButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorHyperbolicSineButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorHyperbolicSineButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorHyperbolicSineButton.setText("sinh");
calculatorHyperbolicSineButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorHyperbolicSineButtonActionPerformed(evt);
}
});
calculatorHyperbolicCosineButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorHyperbolicCosineButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorHyperbolicCosineButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorHyperbolicCosineButton.setText("cosh");
calculatorHyperbolicCosineButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorHyperbolicCosineButtonActionPerformed(evt);
}
});
calculatorHyperbolicTangentButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorHyperbolicTangentButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorHyperbolicTangentButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorHyperbolicTangentButton.setText("tanh");
calculatorHyperbolicTangentButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorHyperbolicTangentButtonActionPerformed(evt);
}
});
calculatorSineInverseButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorSineInverseButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorSineInverseButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorSineInverseButton.setText("sin-1");
calculatorSineInverseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorSineInverseButtonActionPerformed(evt);
}
});
calculatorCosineInverseButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorCosineInverseButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorCosineInverseButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorCosineInverseButton.setText("cos-1");
calculatorCosineInverseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorCosineInverseButtonActionPerformed(evt);
}
});
calculatorTangentInverseButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorTangentInverseButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorTangentInverseButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorTangentInverseButton.setText("tan-1");
calculatorTangentInverseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorTangentInverseButtonActionPerformed(evt);
}
});
calculatorRandomButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorRandomButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorRandomButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorRandomButton.setText("RANDOM");
calculatorRandomButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorRandomButtonActionPerformed(evt);
}
});
calculatorSquareRootButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorSquareRootButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorSquareRootButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorSquareRootButton.setText("√");
calculatorSquareRootButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorSquareRootButtonActionPerformed(evt);
}
});
calculatorCubicRootButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorCubicRootButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorCubicRootButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorCubicRootButton.setText("3√");
calculatorCubicRootButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorCubicRootButtonActionPerformed(evt);
}
});
calculatorFactorialButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorFactorialButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorFactorialButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorFactorialButton.setText("!");
calculatorFactorialButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorFactorialButtonActionPerformed(evt);
}
});
calculatorFloorButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorFloorButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorFloorButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorFloorButton.setText("FLOOR");
calculatorFloorButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorFloorButtonActionPerformed(evt);
}
});
calculatorCellingButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorCellingButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorCellingButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorCellingButton.setText("CEILLING");
calculatorCellingButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorCellingButtonActionPerformed(evt);
}
});
calculatorPiButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorPiButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorPiButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorPiButton.setText("PI(π)");
calculatorPiButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorPiButtonActionPerformed(evt);
}
});
calculator10ToThePowerXButton.setBackground(new java.awt.Color(0, 0, 0));
calculator10ToThePowerXButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculator10ToThePowerXButton.setForeground(new java.awt.Color(0, 255, 0));
calculator10ToThePowerXButton.setText("10^x");
calculator10ToThePowerXButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculator10ToThePowerXButtonActionPerformed(evt);
}
});
calculatorAnswerButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorAnswerButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorAnswerButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorAnswerButton.setText("ANSWER");
calculatorAnswerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorAnswerButtonActionPerformed(evt);
}
});
calculatorBackToMenuButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorBackToMenuButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorBackToMenuButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorBackToMenuButton.setText("MENU");
calculatorBackToMenuButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorBackToMenuButtonActionPerformed(evt);
}
});
calculatorHyperbolicSineInverseButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorHyperbolicSineInverseButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorHyperbolicSineInverseButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorHyperbolicSineInverseButton.setText("sinh-1");
calculatorHyperbolicSineInverseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorHyperbolicSineInverseButtonActionPerformed(evt);
}
});
calculatorHyperbolicCosineInverseButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorHyperbolicCosineInverseButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorHyperbolicCosineInverseButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorHyperbolicCosineInverseButton.setText("cosh-1");
calculatorHyperbolicCosineInverseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorHyperbolicCosineInverseButtonActionPerformed(evt);
}
});
calculatorHyperbolicTangentInverseButton.setBackground(new java.awt.Color(0, 0, 0));
calculatorHyperbolicTangentInverseButton.setFont(new java.awt.Font("Lucida Console", 1, 15)); // NOI18N
calculatorHyperbolicTangentInverseButton.setForeground(new java.awt.Color(0, 255, 0));
calculatorHyperbolicTangentInverseButton.setText("tanh-1");
calculatorHyperbolicTangentInverseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
calculatorHyperbolicTangentInverseButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(calculatorOutputTextField)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorTwoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorFourButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorSixButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(calculatorEightButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorCommaButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorZeroButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(calculatorThreeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorOneButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(calculatorEqualButton, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorFiveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorSevenButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(calculatorMultiplyButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorCubicRootButton, javax.swing.GroupLayout.DEFAULT_SIZE, 62, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(calculatorEndingBracketButton, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)
.addComponent(calculatorMinusButton, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)
.addComponent(calculatorDivideButton, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)
.addComponent(calculatorSquareRootButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(calculatorNineButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorDecimalPointButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorPlusButton, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorStartingBracketButton, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(calculatorPiButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorSineButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorCosineButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorTangentButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorLogBase10Button, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorXToThePowerYButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(calculatorTangentInverseButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorLogBaseEButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorHyperbolicTangentButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(calculatorFloorButton, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(calculatorSineInverseButton, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
.addComponent(calculatorCosineInverseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(4, 4, 4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorHyperbolicSineButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorHyperbolicCosineButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(calculatorEToThePowerYButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(calculator10ToThePowerXButton, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(calculatorBackspaceButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(calculatorCellingButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorAnswerButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicTangentInverseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicCosineInverseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicSineInverseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(calculatorRandomButton, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
.addComponent(calculatorClearButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorBackToMenuButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorFactorialButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(calculatorInputTextField))
.addContainerGap(27, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(calculatorInputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(calculatorOutputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorStartingBracketButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorEndingBracketButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorSineButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicSineButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(calculatorSineInverseButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(calculatorHyperbolicSineInverseButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorCommaButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorDecimalPointButton, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorPlusButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorMinusButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorCosineInverseButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicCosineButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicCosineInverseButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorCosineButton)
.addComponent(calculatorEightButton)
.addComponent(calculatorNineButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addComponent(calculatorBackToMenuButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorMultiplyButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorDivideButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorTangentButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorTangentInverseButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicTangentButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorHyperbolicTangentInverseButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorFactorialButton)
.addComponent(calculatorSixButton)
.addComponent(calculatorSevenButton)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(calculatorCubicRootButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorSquareRootButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorLogBase10Button, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorLogBaseEButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorFloorButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorCellingButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorRandomButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorFourButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(calculatorFiveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(calculatorClearButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)
.addComponent(calculatorAnswerButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(calculatorEqualButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorPiButton)
.addComponent(calculatorBackspaceButton))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorTwoButton)
.addComponent(calculatorThreeButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorOneButton)
.addComponent(calculatorZeroButton)))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(calculatorXToThePowerYButton)
.addComponent(calculatorEToThePowerYButton)
.addComponent(calculator10ToThePowerXButton))))))
.addContainerGap())
);
setSize(new java.awt.Dimension(842, 388));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void calculatorThreeButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorThreeButtonActionPerformed
{//GEN-HEADEREND:event_calculatorThreeButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorThreeButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorThreeButtonActionPerformed
private void calculatorEightButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorEightButtonActionPerformed
{//GEN-HEADEREND:event_calculatorEightButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorEightButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorEightButtonActionPerformed
private void calculatorFiveButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorFiveButtonActionPerformed
{//GEN-HEADEREND:event_calculatorFiveButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorFiveButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorFiveButtonActionPerformed
private void calculatorStartingBracketButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorStartingBracketButtonActionPerformed
{//GEN-HEADEREND:event_calculatorStartingBracketButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorStartingBracketButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorStartingBracketButtonActionPerformed
private void calculatorOneButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorOneButtonActionPerformed
{//GEN-HEADEREND:event_calculatorOneButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorOneButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorOneButtonActionPerformed
private void calculatorTwoButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorTwoButtonActionPerformed
{//GEN-HEADEREND:event_calculatorTwoButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorTwoButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorTwoButtonActionPerformed
private void calculatorXToThePowerYButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorXToThePowerYButtonActionPerformed
{//GEN-HEADEREND:event_calculatorXToThePowerYButtonActionPerformed
/* if(!calculatorInputTextField.getText().equals(""))
{
//get input from text field
inputString = calculatorInputTextField.getText();
//capture the number reversely
String s1 = captureNumber(inputString);
//reverse the string
String s2 = reverseString(s1);
//parse string to double
double x1 = Double.parseDouble(s2);
//convert the number to string
String s3 = ""+x1;
//create math.pow string
String s4 = "Math.pow(";
//input the number in pow
String s5 = s4+s3+",";
//deference between the input string and captured string
int difference = inputString.length()-s1.length();
//make substring from old input string
String s6 = inputString.substring(0, difference);
//add input and new string to the string
String s7 = s6+s5;
//set it to the output textField
calculatorInputTextField.setText(s7);
}
*/
String s1 = calculatorInputTextField.getText();
String s2 = "(Math.pow(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorXToThePowerYButtonActionPerformed
private void calculatorFourButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorFourButtonActionPerformed
{//GEN-HEADEREND:event_calculatorFourButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorFourButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorFourButtonActionPerformed
private void calculatorSixButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorSixButtonActionPerformed
{//GEN-HEADEREND:event_calculatorSixButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorSixButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorSixButtonActionPerformed
private void calculatorSevenButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorSevenButtonActionPerformed
{//GEN-HEADEREND:event_calculatorSevenButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorSevenButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorSevenButtonActionPerformed
private void calculatorNineButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorNineButtonActionPerformed
{//GEN-HEADEREND:event_calculatorNineButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorNineButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorNineButtonActionPerformed
private void calculatorZeroButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorZeroButtonActionPerformed
{//GEN-HEADEREND:event_calculatorZeroButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorZeroButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorZeroButtonActionPerformed
private void calculatorPlusButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorPlusButtonActionPerformed
{//GEN-HEADEREND:event_calculatorPlusButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorPlusButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorPlusButtonActionPerformed
private void calculatorMinusButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorMinusButtonActionPerformed
{//GEN-HEADEREND:event_calculatorMinusButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorMinusButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorMinusButtonActionPerformed
private void calculatorMultiplyButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorMultiplyButtonActionPerformed
{//GEN-HEADEREND:event_calculatorMultiplyButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorMultiplyButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorMultiplyButtonActionPerformed
private void calculatorDivideButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorDivideButtonActionPerformed
{//GEN-HEADEREND:event_calculatorDivideButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorDivideButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorDivideButtonActionPerformed
private void calculatorEndingBracketButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorEndingBracketButtonActionPerformed
{//GEN-HEADEREND:event_calculatorEndingBracketButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorEndingBracketButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorEndingBracketButtonActionPerformed
private void calculatorCommaButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorCommaButtonActionPerformed
{//GEN-HEADEREND:event_calculatorCommaButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorCommaButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorCommaButtonActionPerformed
private void calculatorDecimalPointButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorDecimalPointButtonActionPerformed
{//GEN-HEADEREND:event_calculatorDecimalPointButtonActionPerformed
// TODO add your handling code here:
String s1 , s2 , s3 ;
s1=calculatorInputTextField.getText();
s2=calculatorDecimalPointButton.getText();
s3=s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorDecimalPointButtonActionPerformed
private void calculatorBackspaceButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorBackspaceButtonActionPerformed
{//GEN-HEADEREND:event_calculatorBackspaceButtonActionPerformed
// TODO add your handling code here:
int isInputEmptyFlag=0;
String s0 = calculatorInputTextField.getText();
if(s0.equals(""))
{
isInputEmptyFlag=1;
}
if(isInputEmptyFlag==0)
{
String oldString,newString;
oldString=calculatorInputTextField.getText();
int oldStringLength = oldString.length();
int index = oldStringLength-1;
newString=oldString.substring(0,index);
calculatorInputTextField.setText(newString);
}
}//GEN-LAST:event_calculatorBackspaceButtonActionPerformed
private void calculatorClearButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorClearButtonActionPerformed
{//GEN-HEADEREND:event_calculatorClearButtonActionPerformed
// TODO add your handling code here:
String s1="";
calculatorInputTextField.setText(s1);
calculatorOutputTextField.setText(s1);
}//GEN-LAST:event_calculatorClearButtonActionPerformed
private void calculatorEqualButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorEqualButtonActionPerformed
{//GEN-HEADEREND:event_calculatorEqualButtonActionPerformed
// TODO add your handling code here:
String inputString = "1.0*"+calculatorInputTextField.getText();
try
{
Object result = interpreter.eval(inputString);
String outputString = result.toString();
calculatorOutputTextField.setText(outputString);
}
catch (EvalError ex)
{
//String message = ex.getMessage();
//calculatorOutputTextField.setText(message);
}
catch(Exception e)
{
}
}//GEN-LAST:event_calculatorEqualButtonActionPerformed
private void calculatorEToThePowerYButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorEToThePowerYButtonActionPerformed
{//GEN-HEADEREND:event_calculatorEToThePowerYButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "(Math.pow("+Math.E+",";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorEToThePowerYButtonActionPerformed
private void calculatorLogBase10ButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorLogBase10ButtonActionPerformed
{//GEN-HEADEREND:event_calculatorLogBase10ButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.log10(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorLogBase10ButtonActionPerformed
private void calculatorLogBaseEButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorLogBaseEButtonActionPerformed
{//GEN-HEADEREND:event_calculatorLogBaseEButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.log(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorLogBaseEButtonActionPerformed
private void calculatorSineButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorSineButtonActionPerformed
{//GEN-HEADEREND:event_calculatorSineButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.sin(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorSineButtonActionPerformed
private void calculatorCosineButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorCosineButtonActionPerformed
{//GEN-HEADEREND:event_calculatorCosineButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.cos(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorCosineButtonActionPerformed
private void calculatorTangentButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorTangentButtonActionPerformed
{//GEN-HEADEREND:event_calculatorTangentButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.tan(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorTangentButtonActionPerformed
private void calculatorHyperbolicSineButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorHyperbolicSineButtonActionPerformed
{//GEN-HEADEREND:event_calculatorHyperbolicSineButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.sinh(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorHyperbolicSineButtonActionPerformed
private void calculatorHyperbolicCosineButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorHyperbolicCosineButtonActionPerformed
{//GEN-HEADEREND:event_calculatorHyperbolicCosineButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.cosh(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorHyperbolicCosineButtonActionPerformed
private void calculatorHyperbolicTangentButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorHyperbolicTangentButtonActionPerformed
{//GEN-HEADEREND:event_calculatorHyperbolicTangentButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.tanh(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorHyperbolicTangentButtonActionPerformed
private void calculatorSineInverseButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorSineInverseButtonActionPerformed
{//GEN-HEADEREND:event_calculatorSineInverseButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.asin(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorSineInverseButtonActionPerformed
private void calculatorCosineInverseButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorCosineInverseButtonActionPerformed
{//GEN-HEADEREND:event_calculatorCosineInverseButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.acos(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorCosineInverseButtonActionPerformed
private void calculatorTangentInverseButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorTangentInverseButtonActionPerformed
{//GEN-HEADEREND:event_calculatorTangentInverseButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.atan(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorTangentInverseButtonActionPerformed
private void calculatorRandomButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorRandomButtonActionPerformed
{//GEN-HEADEREND:event_calculatorRandomButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.random()";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorRandomButtonActionPerformed
private void calculatorSquareRootButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorSquareRootButtonActionPerformed
{//GEN-HEADEREND:event_calculatorSquareRootButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.sqrt(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorSquareRootButtonActionPerformed
private void calculatorCubicRootButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorCubicRootButtonActionPerformed
{//GEN-HEADEREND:event_calculatorCubicRootButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.cbrt(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorCubicRootButtonActionPerformed
private void calculatorFactorialButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorFactorialButtonActionPerformed
{//GEN-HEADEREND:event_calculatorFactorialButtonActionPerformed
// TODO add your handling code here:
try
{
//get input from text field
inputString = calculatorInputTextField.getText();
//capture the number reversely
String s1 = captureNumber(inputString);
//reverse the string
String s2 = reverseString(s1);
//parse string to integer
int x1 = Integer.parseInt(s2);
//calculate the factorial
int x2 = factorial(x1);
//convert the factorial to string
String s3 = ""+x2;
//deference between the input string and captured string
int difference = inputString.length()-s1.length();
//make substring from old input string
String s4 = inputString.substring(0, difference);
//add factorial to the string
String s5 = s4+s3;
//set it to the output textField
calculatorInputTextField.setText(s5);
}
catch(Exception e)
{
//String message = e.getMessage();
//calculatorOutputTextField.setText(message);
}
}//GEN-LAST:event_calculatorFactorialButtonActionPerformed
private void calculatorFloorButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorFloorButtonActionPerformed
{//GEN-HEADEREND:event_calculatorFloorButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.floor(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorFloorButtonActionPerformed
private void calculatorCellingButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorCellingButtonActionPerformed
{//GEN-HEADEREND:event_calculatorCellingButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.ceil(";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorCellingButtonActionPerformed
private void calculatorPiButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorPiButtonActionPerformed
{//GEN-HEADEREND:event_calculatorPiButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.PI";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorPiButtonActionPerformed
private void calculator10ToThePowerXButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculator10ToThePowerXButtonActionPerformed
{//GEN-HEADEREND:event_calculator10ToThePowerXButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = "Math.pow(10,";
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculator10ToThePowerXButtonActionPerformed
private void calculatorAnswerButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorAnswerButtonActionPerformed
{//GEN-HEADEREND:event_calculatorAnswerButtonActionPerformed
// TODO add your handling code here:
String s1 = calculatorInputTextField.getText();
String s2 = calculatorOutputTextField.getText();
String s3 = s1+s2;
calculatorInputTextField.setText(s3);
}//GEN-LAST:event_calculatorAnswerButtonActionPerformed
private void calculatorBackToMenuButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorBackToMenuButtonActionPerformed
{//GEN-HEADEREND:event_calculatorBackToMenuButtonActionPerformed
// TODO add your handling code here:
this.setVisible(false);
Menu object = new Menu();
object.setVisible(true);
}//GEN-LAST:event_calculatorBackToMenuButtonActionPerformed
private void calculatorHyperbolicSineInverseButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorHyperbolicSineInverseButtonActionPerformed
{//GEN-HEADEREND:event_calculatorHyperbolicSineInverseButtonActionPerformed
// TODO add your handling code here:
try
{
asinhInverseSet();
}
catch(Exception e)
{
}
}//GEN-LAST:event_calculatorHyperbolicSineInverseButtonActionPerformed
private void calculatorHyperbolicCosineInverseButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorHyperbolicCosineInverseButtonActionPerformed
{//GEN-HEADEREND:event_calculatorHyperbolicCosineInverseButtonActionPerformed
// TODO add your handling code here:
try
{
acoshInverseSet();
}
catch(Exception e)
{
}
}//GEN-LAST:event_calculatorHyperbolicCosineInverseButtonActionPerformed
private void calculatorHyperbolicTangentInverseButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_calculatorHyperbolicTangentInverseButtonActionPerformed
{//GEN-HEADEREND:event_calculatorHyperbolicTangentInverseButtonActionPerformed
// TODO add your handling code here:
try
{
atanhInverseSet();
}
catch(Exception e)
{
}
}//GEN-LAST:event_calculatorHyperbolicTangentInverseButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(CALCULATOR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CALCULATOR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CALCULATOR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CALCULATOR.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CALCULATOR().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton calculator10ToThePowerXButton;
private javax.swing.JButton calculatorAnswerButton;
private javax.swing.JButton calculatorBackToMenuButton;
private javax.swing.JButton calculatorBackspaceButton;
private javax.swing.JButton calculatorCellingButton;
private javax.swing.JButton calculatorClearButton;
private javax.swing.JButton calculatorCommaButton;
private javax.swing.JButton calculatorCosineButton;
private javax.swing.JButton calculatorCosineInverseButton;
private javax.swing.JButton calculatorCubicRootButton;
private javax.swing.JButton calculatorDecimalPointButton;
private javax.swing.JButton calculatorDivideButton;
private javax.swing.JButton calculatorEToThePowerYButton;
private javax.swing.JButton calculatorEightButton;
private javax.swing.JButton calculatorEndingBracketButton;
private javax.swing.JButton calculatorEqualButton;
private javax.swing.JButton calculatorFactorialButton;
private javax.swing.JButton calculatorFiveButton;
private javax.swing.JButton calculatorFloorButton;
private javax.swing.JButton calculatorFourButton;
private javax.swing.JButton calculatorHyperbolicCosineButton;
private javax.swing.JButton calculatorHyperbolicCosineInverseButton;
private javax.swing.JButton calculatorHyperbolicSineButton;
private javax.swing.JButton calculatorHyperbolicSineInverseButton;
private javax.swing.JButton calculatorHyperbolicTangentButton;
private javax.swing.JButton calculatorHyperbolicTangentInverseButton;
private javax.swing.JTextField calculatorInputTextField;
private javax.swing.JButton calculatorLogBase10Button;
private javax.swing.JButton calculatorLogBaseEButton;
private javax.swing.JButton calculatorMinusButton;
private javax.swing.JButton calculatorMultiplyButton;
private javax.swing.JButton calculatorNineButton;
private javax.swing.JButton calculatorOneButton;
private javax.swing.JTextField calculatorOutputTextField;
private javax.swing.JButton calculatorPiButton;
private javax.swing.JButton calculatorPlusButton;
private javax.swing.JButton calculatorRandomButton;
private javax.swing.JButton calculatorSevenButton;
private javax.swing.JButton calculatorSineButton;
private javax.swing.JButton calculatorSineInverseButton;
private javax.swing.JButton calculatorSixButton;
private javax.swing.JButton calculatorSquareRootButton;
private javax.swing.JButton calculatorStartingBracketButton;
private javax.swing.JButton calculatorTangentButton;
private javax.swing.JButton calculatorTangentInverseButton;
private javax.swing.JButton calculatorThreeButton;
private javax.swing.JButton calculatorTwoButton;
private javax.swing.JButton calculatorXToThePowerYButton;
private javax.swing.JButton calculatorZeroButton;
// End of variables declaration//GEN-END:variables
}
|
/*
* Copyright 2018 Bakumon. https://github.com/Bakumon
*
* 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 me.bakumon.moneykeeper.ui.common;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import androidx.preference.Preference;
public abstract class BaseTextPreference extends Preference {
private String mText;
public BaseTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
public BaseTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public BaseTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BaseTextPreference(Context context) {
super(context);
init();
}
public abstract void init();
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
@Override
protected void onSetInitialValue(Object defaultValue) {
setText(getPersistedString((String) defaultValue));
}
@Override
public boolean shouldDisableDependents() {
return TextUtils.isEmpty(mText) || super.shouldDisableDependents();
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
final SavedState myState = new SavedState(superState);
myState.mText = getText();
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state == null || !state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
setText(myState.mText);
}
private static class SavedState extends BaseSavedState {
public static final Creator<SavedState> CREATOR =
new Creator<BaseTextPreference.SavedState>() {
@Override
public BaseTextPreference.SavedState createFromParcel(Parcel in) {
return new BaseTextPreference.SavedState(in);
}
@Override
public BaseTextPreference.SavedState[] newArray(int size) {
return new BaseTextPreference.SavedState[size];
}
};
String mText;
SavedState(Parcel source) {
super(source);
mText = source.readString();
}
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeString(mText);
}
}
public void setText(String text) {
final boolean wasBlocking = shouldDisableDependents();
mText = text;
persistString(text);
final boolean isBlocking = shouldDisableDependents();
if (isBlocking != wasBlocking) {
notifyDependencyChange(isBlocking);
}
notifyChanged();
if (getOnPreferenceChangeListener() != null) {
getOnPreferenceChangeListener().onPreferenceChange(this, text);
}
}
public String getText() {
return mText;
}
}
|
package gui.comp;
import gui.ButtonGroup;
import gui.ComponentTools;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.Border;
public class CheckBoxMenu<T>
{
private static final long serialVersionUID = 2;
private static final int VSCROLL_INC = 8;
private Map<String, T> map;
private String heading;
private int maxSelectable; // 0 means no max
private List<T> selectedItems;
private Map<T, JCheckBox> checkBoxes;
private int cellWidth = 85;
private JDialog checkBoxDialog;
private JPanel checkBoxForm;
public CheckBoxMenu (final Collection<T> items, final String heading)
{
setItems (items);
setHeading (heading);
}
public void setItems (final Collection<T> items)
{
map = new HashMap<String, T>();
checkBoxes = new LinkedHashMap<T, JCheckBox>();
for (T obj : items)
{
String name = obj.toString();
map.put (name, obj);
JCheckBox box = new JCheckBox (name, false);
checkBoxes.put (obj, box);
}
makeForm();
}
public void setHeading (final String h)
{
heading = h;
}
public void setMaxSelectable (final int max)
{
maxSelectable = max;
}
public void setSelected (final Collection<T> selected)
{
for (T obj : selected)
checkBoxes.get (obj).setSelected (true);
}
public Collection<T> getSelected()
{
Collection<T> selected = new ArrayList<T>();
for (JCheckBox box : checkBoxes.values())
if (box.isSelected())
selected.add (map.get (box.getText()));
return selected;
}
private void makeForm()
{
checkBoxForm = new JPanel (new GridLayout (0, 1));
for (JCheckBox checkBox : checkBoxes.values())
checkBoxForm.add (checkBox);
}
public List<T> select (final Frame owner, final String title)
{
selectedItems = new ArrayList<T>();
JPanel panel = getPanel (new Dimension (400, 200));
JPanel btnPanel = createBtnPanel (new ActionListener()
{
@Override
public void actionPerformed (final ActionEvent event)
{
String action = event.getActionCommand();
if (action.equals ("OK"))
selectItems();
if (action.equals ("ALL"))
selectAllItems();
if (action.equals ("CANCEL"))
cancelSelection();
}
});
panel.add (btnPanel, BorderLayout.SOUTH);
checkBoxDialog = new JDialog (owner, title, true);
checkBoxDialog.add (panel);
checkBoxDialog.pack();
ComponentTools.centerComponent (checkBoxDialog);
for (JCheckBox box : checkBoxes.values())
if (box.getPreferredSize().width > cellWidth)
cellWidth = box.getPreferredSize().width; // determine the widest cell
checkBoxDialog.setVisible (true);
return selectedItems;
}
public JPanel getPanel (final Dimension prefSize)
{
if (maxSelectable > 0)
{
ButtonGroup group = new ButtonGroup();
group.setMaxSelectable (maxSelectable);
for (JCheckBox checkBox : checkBoxes.values())
group.add (checkBox);
}
JPanel panel = new JPanel (new BorderLayout());
Border up = BorderFactory.createRaisedBevelBorder();
Border down = BorderFactory.createLoweredBevelBorder();
Border border = BorderFactory.createCompoundBorder (up, down);
panel.setBorder (border);
if (heading != null)
{
JTextArea header = new JTextArea (heading);
header.setBackground (null);
header.setEditable (false);
panel.add (header, BorderLayout.NORTH);
}
JScrollPane scroll = new JScrollPane (checkBoxForm);
scroll.getVerticalScrollBar().setUnitIncrement (VSCROLL_INC);
scroll.addComponentListener (new ResizeListener());
scroll.setPreferredSize (prefSize);
panel.add (scroll, BorderLayout.CENTER);
return panel;
}
private void selectItems()
{
for (JCheckBox checkBox : checkBoxes.values())
if (checkBox.isSelected())
selectedItems.add (map.get (checkBox.getText()));
if (checkBoxDialog != null)
{
checkBoxDialog.setVisible (false);
checkBoxDialog.dispose();
}
}
public void selectAllItems()
{
for (JCheckBox checkBox : checkBoxes.values())
checkBox.setSelected (true);
}
private void cancelSelection()
{
if (checkBoxDialog != null)
{
checkBoxDialog.setVisible (false);
checkBoxDialog.dispose();
}
}
private JPanel createBtnPanel (final ActionListener listener)
{
JPanel panel = new JPanel();
if (maxSelectable == 0 || checkBoxes.size() <= maxSelectable)
{
JButton all = new JButton ("Select All");
all.setActionCommand ("ALL");
all.addActionListener (listener);
panel.add (all);
}
JButton ok = new JButton ("OK");
ok.setActionCommand ("OK");
ok.addActionListener (listener);
panel.add (ok);
JButton cancel = new JButton ("Cancel");
cancel.setActionCommand ("CANCEL");
cancel.addActionListener (listener);
panel.add (cancel);
return panel;
}
// set the number of columns based on current size of the scroll panel
class ResizeListener extends ComponentAdapter
{
@Override
public void componentResized (final ComponentEvent e)
{
JScrollPane scroll = (JScrollPane) e.getSource();
Dimension dim = scroll.getSize();
int width = dim.width - scroll.getVerticalScrollBar().getWidth();
int columns = Math.max (1, (width / cellWidth) - 1);
checkBoxForm.setLayout (new GridLayout (0, columns));
}
}
public static void main (final String[] args)
{
List<Integer> values = new ArrayList<Integer>();
for (int i = 1; i <= 100; i++)
values.add (i);
CheckBoxMenu<Integer> menu =
new CheckBoxMenu<Integer> (values, "Select values");
List<Integer> selected = menu.select (null, "CheckBoxMenu Test");
for (int i : selected)
System.out.println (i);
}
}
|
package com.explore.service.Impl;
import com.explore.common.Const;
import com.explore.common.ServerResponse;
import com.explore.dao.StudentMapper;
import com.explore.dao.SubjectMapper;
import com.explore.dao.SubjectStudentMapper;
import com.explore.form.AddSubjectStudent;
import com.explore.pojo.Student;
import com.explore.pojo.StudentExam;
import com.explore.pojo.Subject;
import com.explore.pojo.SubjectStudent;
import com.explore.service.ISubjectStudentService;
import com.explore.dao.StudentExamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SubjectStudentServiceImpl implements ISubjectStudentService {
@Autowired
StudentMapper studentMapper;
@Autowired
SubjectStudentMapper subjectStudentMapper;
@Autowired
StudentExamMapper studentExamMapper;
@Autowired
SubjectMapper subjectMapper;
@Override
public ServerResponse addSubjectStudent(AddSubjectStudent addSubjectStudent) {
int count = studentMapper.checkStudent(addSubjectStudent.getPhone(), addSubjectStudent.getIdcard());
if(count <= 0){
return ServerResponse.createByErrorMessage("申请失败,请验证您的身份信息!");
}
SubjectStudent subjectStudent = new SubjectStudent();
subjectStudent.setStatus(1);
subjectStudent.setStartTime(addSubjectStudent.getStartTime());
subjectStudent.setPosition(addSubjectStudent.getPosition());
subjectStudentMapper.insert(subjectStudent);
return ServerResponse.createBySuccessMessage("申请发送成功,正在等待管理员同意申请");
}
@Override
public ServerResponse showSubjectStudent() {
List<SubjectStudent> subjectStudents = studentExamMapper.showSubjectStudent();
if(subjectStudents.size() != 0)
return ServerResponse.createBySuccess(subjectStudents);
return ServerResponse.createByErrorMessage("暂时没有数据");
}
@Override
public ServerResponse reviewSubjectStudent(SubjectStudent subjectStudent) {
int count = subjectStudentMapper.updateByPrimaryKeySelective(subjectStudent);
if(count==1)
return ServerResponse.createBySuccessMessage("修改成功");
return ServerResponse.createByErrorMessage("修改失败");
}
@Override
public ServerResponse deleteSubjectStudent( int id) {
int count = subjectStudentMapper.deleteByPrimaryKey(id);
if(count==1)
return ServerResponse.createBySuccessMessage("删除成功");
return ServerResponse.createByErrorMessage("删除失败");
}
@Override
public ServerResponse showStudentExam(StudentExam studentExam) {
List<SubjectStudent> subjectStudents = studentExamMapper.findStudentExam(studentExam);
if(subjectStudents.size() != 0)
return ServerResponse.createBySuccess(subjectStudents);
return ServerResponse.createByErrorMessage("暂时没有数据");
}
@Override
public ServerResponse sign(SubjectStudent subjectStudent) {
subjectStudent.setStatus(Const.ExamStatus.WAIT_CHECK_PASS);
int count = subjectStudentMapper.insert(subjectStudent);
if (count == 1){
return ServerResponse.createBySuccessMessage("申请发送成功,正在等待管理员同意申请");
}
return ServerResponse.createByErrorMessage("申请失败");
}
@Override
public ServerResponse findByStudentId(Integer id) {
List<SubjectStudent> list = subjectStudentMapper.selectByStudentId(id);
List<Map<String,Object>> ret = new ArrayList<>();
for (SubjectStudent subjectStudent : list) {
Map<String,Object> map = new HashMap<>();
map.put("subjectStudent",subjectStudent);
map.put("subject",subjectMapper.selectByPrimaryKey(subjectStudent.getSubjectId()));
ret.add(map);
}
return ServerResponse.createBySuccess(ret);
}
@Override
public ServerResponse cancel(Integer studentId, Integer sbId) {
int count = subjectStudentMapper.cancel(studentId,sbId);
if (count==1){
return ServerResponse.createBySuccessMessage("取消成功");
}
return ServerResponse.createByErrorMessage("取消失败");
}
@Override
public ServerResponse acceptSubjectStudent(SubjectStudent subjectStudent) {
int count = subjectStudentMapper.updateByPrimaryKey(subjectStudent);
if(count==1)
return ServerResponse.createBySuccessMessage("确认成功");
return ServerResponse.createByErrorMessage("确认失败");
}
@Override
public ServerResponse passSubjectStudent(SubjectStudent subjectStudent) {
int count = subjectStudentMapper.updateByPrimaryKey(subjectStudent);
if(count==1)
return ServerResponse.createBySuccessMessage("通过成功");
return ServerResponse.createByErrorMessage("通过失败");
}
}
|
package io.nuls.provider.api.resources;
import io.nuls.base.api.provider.Result;
import io.nuls.core.constant.CommonCodeConstanst;
import io.nuls.core.core.annotation.Autowired;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.rpc.model.*;
import io.nuls.provider.api.config.Config;
import io.nuls.provider.model.ErrorData;
import io.nuls.provider.model.RpcClientResult;
import io.nuls.provider.model.dto.VirtualBankDirectorDTO;
import io.nuls.provider.rpctools.ConverterTools;
import io.nuls.provider.utils.ResultUtil;
import io.nuls.v2.model.annotation.Api;
import io.nuls.v2.model.annotation.ApiOperation;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("/api/converter")
@Component
@Api
public class ConverterResource {
@Autowired
Config config;
@Autowired
ConverterTools converterTools;
@GET
@Path("/address/eth/{packingAddress}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(description = "根据共识节点打包地址查询相应的以太坊地址", order = 601)
@Parameters({
@Parameter(parameterName = "packingAddress", requestType = @TypeDescriptor(value = String.class), parameterDes = "共识节点打包地址")
})
@ResponseData(name = "返回值", description = "返回一个Map对象", responseType = @TypeDescriptor(value = Map.class, mapKeys = {
@Key(name = "ethAddress", description = "以太坊地址")
}))
public RpcClientResult getEthAddress(@PathParam("packingAddress") String packingAddress) {
if (packingAddress == null) {
return RpcClientResult.getFailed(new ErrorData(CommonCodeConstanst.PARAMETER_ERROR.getCode(), "packingAddress is empty"));
}
Result<Map<String, Object>> result = converterTools.getHeterogeneousAddress(config.getChainId(), 101, packingAddress);
RpcClientResult clientResult = ResultUtil.getRpcClientResult(result);
return clientResult;
}
@GET
@Path("/bank")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(description = "获取虚拟银行成员信息", order = 602)
@ResponseData(name = "返回值", description = "返回一个List对象", responseType = @TypeDescriptor(value = List.class,
collectionElement = VirtualBankDirectorDTO.class))
public RpcClientResult getVirtualBankInfo() {
Result<List<VirtualBankDirectorDTO>> result = converterTools.getVirtualBankInfo(config.getChainId());
RpcClientResult clientResult = ResultUtil.getRpcClientResult(result);
return clientResult;
}
@GET
@Path("/disqualification")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(description = "获取已撤销虚拟银行资格节点地址列表", order = 603)
@ResponseData(name = "返回值", description = "返回一个List对象", responseType = @TypeDescriptor(value = List.class,
collectionElement = String.class))
public RpcClientResult getDisqualification() {
Result<String> result = converterTools.getDisqualification(config.getChainId());
RpcClientResult clientResult = ResultUtil.getRpcClientResult(result);
return clientResult;
}
@POST
@Path("/proposal")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(description = "申请提案",order = 604)
@Parameters({
@Parameter(parameterName = "chainId", requestType = @TypeDescriptor(value = int.class), parameterDes = "链id"),
@Parameter(parameterName = "type", requestType = @TypeDescriptor(value = byte.class), parameterDes = "提案类型"),
@Parameter(parameterName = "content", requestType = @TypeDescriptor(value = String.class), parameterDes = "提案类容"),
@Parameter(parameterName = "heterogeneousChainId", requestType = @TypeDescriptor(value = int.class), parameterDes = "异构链chainId"),
@Parameter(parameterName = "heterogeneousTxHash", requestType = @TypeDescriptor(value = String.class), parameterDes = "异构链交易hash"),
@Parameter(parameterName = "businessAddress", requestType = @TypeDescriptor(value = String.class), parameterDes = "地址(账户、节点地址等)"),
@Parameter(parameterName = "hash", requestType = @TypeDescriptor(value = String.class), parameterDes = "链内交易hash"),
@Parameter(parameterName = "voteRangeType", requestType = @TypeDescriptor(value = byte.class), parameterDes = "投票范围类型"),
@Parameter(parameterName = "remark", requestType = @TypeDescriptor(value = String.class), parameterDes = "备注"),
@Parameter(parameterName = "address", requestType = @TypeDescriptor(value = String.class), parameterDes = "签名地址"),
@Parameter(parameterName = "password", requestType = @TypeDescriptor(value = String.class), parameterDes = "密码")
})
@ResponseData(name = "返回值", description = "返回一个Map对象", responseType = @TypeDescriptor(value = Map.class, mapKeys = {
@Key(name = "value", description = "交易hash")
}))
public RpcClientResult createProposal(Map params) {
Result<String> proposal = converterTools.proposal(params);
return ResultUtil.getRpcClientResult(proposal);
}
@POST
@Path("/fee")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(description = "追加提现手续费/原路退回的提案",order = 605)
@Parameters({
@Parameter(parameterName = "chainId", requestType = @TypeDescriptor(value = int.class), parameterDes = "链id"),
@Parameter(parameterName = "txHash", requestType = @TypeDescriptor(value = String.class), parameterDes = "原始交易hash"),
@Parameter(parameterName = "amount", requestType = @TypeDescriptor(value = BigInteger.class), parameterDes = "追加的手续费金额"),
@Parameter(parameterName = "remark", requestType = @TypeDescriptor(value = String.class), parameterDes = "交易备注"),
@Parameter(parameterName = "address", requestType = @TypeDescriptor(value = String.class), parameterDes = "支付/签名地址"),
@Parameter(parameterName = "password", requestType = @TypeDescriptor(value = String.class), parameterDes = "密码")
})
@ResponseData(name = "返回值", description = "返回一个Map对象", responseType = @TypeDescriptor(value = Map.class, mapKeys = {
@Key(name = "value", description = "交易hash")
}))
public RpcClientResult withdrawalAdditionalFee(Map params) {
Result<String> proposal = converterTools.withdrawalAdditionalFee(params);
return ResultUtil.getRpcClientResult(proposal);
}
@GET
@Path("/heterogeneous/mainasset/{chainId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(description = "返回异构链主资产在NERVE网络的资产信息", order = 606)
@Parameters({
@Parameter(parameterName = "chainId", requestType = @TypeDescriptor(value = Integer.class), parameterDes = "异构链ID")
})
@ResponseData(name = "返回值", description = "返回一个Map对象", responseType = @TypeDescriptor(value = Map.class, mapKeys = {
@Key(name = "chainId", valueType = int.class, description = "资产链ID"),
@Key(name = "assetId", valueType = int.class, description = "资产ID"),
@Key(name = "symbol", description = "资产symbol"),
@Key(name = "decimals", valueType = int.class, description = "资产小数位数")
})
)
public RpcClientResult getHeterogeneousMainAsset(@PathParam("chainId") Integer chainId) {
if (chainId == null) {
return RpcClientResult.getFailed(new ErrorData(CommonCodeConstanst.PARAMETER_ERROR.getCode(), "chainId is empty"));
}
Result<Map<String, Object>> result = converterTools.getHeterogeneousMainAsset(chainId);
RpcClientResult clientResult = ResultUtil.getRpcClientResult(result);
return clientResult;
}
/*@GET
@Path("/heterogeneous/test/{params}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(description = "测试", order = 607)
@Parameters({
@Parameter(parameterName = "params", requestType = @TypeDescriptor(value = String.class), parameterDes = "测试")
})
@ResponseData(name = "返回值", description = "返回一个Map对象", responseType = @TypeDescriptor(value = Map.class)
)
public RpcClientResult test(@PathParam("params") String params) {
Map map = new HashMap();
map.put("params", params);
Result result = converterTools.commonRequest("cv_test", map);
RpcClientResult clientResult = ResultUtil.getRpcClientResult(result);
return clientResult;
}*/
}
|
/*
* TreeMap is sorted according to natural ordering of the key.
* key object implements comparable interface.
* it offers log(n) cost as using put(), get(), remove().
*/
package Map;
import java.util.Map;
import java.util.TreeMap;
/**
*
* @author YNZ
*/
public class UsingTreeMap {
private static Map<String, String> map = new TreeMap<>();
public static void main(String[] args) {
map.put("one", "java persistence with jpa");
map.put("two", "java generics and collections");
map.put("three", "building restful web service with spring");
map.put("four", "introduction to java programming");
System.out.println("map content: "+ map);
map.replace("four", "my book");
System.out.println("map content: "+ map);
}
}
|
package com.cdero.gamerbot.commands;
//import statements
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
/**
*
* @author Christopher DeRoche
* @version 1.0
* @since 1.0
*
*/
public class TimerCommandListener extends ListenerAdapter {
/**
* Logger for the MessageListener class.
*/
private final static Logger log = LogManager.getLogger(TimerCommandListener.class.getName());
/**
* Prefix for the application commands on client side.
*/
private final String PREFIX = ">>";
/**
* Overridden method to receive and respond to the timer command. Users can have a task and timer to be notified later.
*
* @param event includes information about the event.
*/
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
User author = event.getAuthor();
if(author.isBot()) {
return;
}
Guild guild = event.getGuild();
String[] command = event.getMessage().getContentRaw().split(" ");
int commandLength = command.length;
TextChannel channel = event.getChannel();
if(command[0].equalsIgnoreCase(PREFIX + "timer")) {
if(commandLength == 1 || (command[1].equalsIgnoreCase("help") && commandLength == 2)) {
channel.sendMessage(":white_check_mark: **Usage: Create a timer given a time."
+ "\n" + PREFIX + "timer [task] => [value].[hours/minutes/seconds]"
+ "\nExample: " + PREFIX + "timer Play Games! => 4.hours"
+ "**").queue();
log.info("Command: " + PREFIX + "timer"
+ "\nGuild: " + guild.toString()
+ "\nChannel: " + channel.toString()
+ "\nAuthor: " + author.toString());
}else if(command[commandLength - 2].equals("=>") && (command[commandLength - 1].contains(".hours") || command[commandLength - 1].contains(".hour") || command[commandLength - 1].contains(".minutes") || command[commandLength - 1].contains(".minute") || command[commandLength - 1].contains(".seconds") || command[commandLength - 1].contains(".second"))) {
StringBuilder task = new StringBuilder();
String[] totalTime = command[commandLength - 1].split("\\.");
String timeValue = "";
String timeNumeral = "";
TimeUnit timeUnit = null;
Long authorLong = author.getIdLong();
for(int i = 1; i < commandLength - 2; i++) {
task.append(command[i] + " ");
}
timeNumeral = totalTime[0];
timeValue = totalTime[1];
switch(timeValue) {
case "hours":
timeUnit = TimeUnit.HOURS;
break;
case "hour":
timeUnit = TimeUnit.HOURS;
break;
case "minutes":
timeUnit = TimeUnit.MINUTES;
break;
case "minute":
timeUnit = TimeUnit.MINUTES;
break;
case "seconds":
timeUnit = TimeUnit.SECONDS;
break;
case "second":
timeUnit = TimeUnit.SECONDS;
break;
}
try {
channel.sendMessage(":white_check_mark: **<@!" + authorLong + ">, " + task.toString() + "**").queueAfter(Integer.parseInt(timeNumeral), timeUnit);
} catch (ErrorResponseException e){
channel.sendMessage(":x: **<@!" + authorLong + ">" + ", there was an error creating your timer! Check your input!**").queue();
log.warn("Error with the timer command!"
+ "\nGuild: " + guild.toString()
+ "\nChannel: " + channel.toString()
+ "\nAuthor: " + author.toString());
} catch (IllegalArgumentException e) {
channel.sendMessage(":x: **<@!" + authorLong + ">" + ", there was an error creating your timer! Check your input!**").queue();
log.warn("Error with the timer command!"
+ "\nGuild: " + guild.toString()
+ "\nChannel: " + channel.toString()
+ "\nAuthor: " + author.toString());
} finally {
channel.sendMessage(":white_check_mark: **<@!" + authorLong + ">" + ", you will be notified in " + timeNumeral + " " + timeValue + "!**").queue();
log.info("Command: " + PREFIX + "remindme"
+ "\nTime: " + Integer.parseInt(timeNumeral) + " " + timeUnit.toString()
+ "\nGuild: " + guild.toString()
+ "\nChannel: " + channel.toString()
+ "\nAuthor: " + author.toString());
}
}else {
channel.sendMessage(":white_check_mark: **Usage: Create a timer given a time."
+ "\n" + PREFIX + "timer [task] => [value].[hours/minutes/seconds]"
+ "\nExample: " + PREFIX + "timer Play Games! => 4.hours"
+ "**").queue();
log.info("Command: " + PREFIX + "timer"
+ "\nGuild: " + guild.toString()
+ "\nChannel: " + channel.toString()
+ "\nAuthor: " + author.toString());
}
}
}
}
|
/**
*
*/
package me.d2o.statemachine.config.configexceptiontests;
public class StatesNotUniqueTest {
public static final String STATE_1 = "STATE_1";
public static final String STATE_2 = "STATE_1";
}
|
package domen;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ProizvodTest {
private Proizvod p;
@Before
public void setUp() throws Exception {
p = new Proizvod("123", "cokolada", 50);
}
@After
public void tearDown() throws Exception {
p = null;
}
@Test
public void testHashCode() {
p.hashCode();
}
@Test
public void testProizvod() {
p = new Proizvod("123", "cokolada", 50);
assertEquals("123", p.getSifra());
assertEquals("cokolada", p.getNaziv());
assertEquals(50, p.getCena(), 0);
}
@Test(expected = java.lang.RuntimeException.class)
public void testProizvodNekaVrednostNijeDozvoljenaUSetMetodama() {
p = new Proizvod(null, null, -1);
}
@Test
public void testGetSifra() {
assertEquals("123", p.getSifra());
}
@Test
public void testSetSifra() {
p.setSifra("555");
assertEquals("555", p.getSifra());
}
@Test(expected = java.lang.RuntimeException.class)
public void testSetSifraNull() {
p.setSifra(null);
}
@Test(expected = java.lang.RuntimeException.class)
public void testSetSifraIsEmpty() {
p.setSifra("");
}
@Test
public void testGetNaziv() {
assertEquals("cokolada", p.getNaziv());
}
@Test
public void testSetNaziv() {
p.setNaziv("banana");
assertEquals("banana", p.getNaziv());
}
@Test(expected = java.lang.RuntimeException.class)
public void testSetNazivNull() {
p.setNaziv(null);
}
@Test(expected = java.lang.RuntimeException.class)
public void testSetNazivIsEmpty() {
p.setNaziv("");
}
@Test
public void testGetCena() {
assertEquals(50, p.getCena(), 0);
}
@Test
public void testSetCena() {
p.setCena(40);
assertEquals(40, p.getCena(), 0);
}
@Test(expected = java.lang.RuntimeException.class)
public void testSetCenaManjeOdNule() {
p.setCena(-1);
}
@Test
public void testEqualsObject() {
Proizvod p2 = new Proizvod("123", "cokolada", 50);
assertEquals(true, p.equals(p2));
}
@Test
public void testToString() {
String sifra = "123";
String naziv = "cokolada";
double cena = 50;
String s = "Proizvod [sifra=" + sifra + ", naziv=" + naziv + ", cena=" + cena + "]";
assertEquals(s, p.toString());
}
}
|
package org.student.controller;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.student.dao.StudentDAO;
import org.student.model.Student;
import java.util.List;
public class StudentController
{
public static void main(String[] args)
{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring4.xml");
StudentDAO studentDAO=context.getBean(StudentDAO.class);
Student student= new Student("SURBHI","VERMA","surbhi@gmail.com");
studentDAO.save(student);
System.out.println("Student::"+student);
List<Student> studentList = studentDAO.list();
for(Student stu : studentList){
System.out.println("Person List::"+stu);
}
context.close();
}
}
|
package com.com3018.dao;
import com.com3018.model.Cart;
/**
* Created by Anisha on 08/05/2016.
*/
public interface CartDao {
Cart create(Cart cart);
Cart read(String cartId);
void update(String cartId, Cart cart);
void delete(String cartId);
}
|
package com.xixiwan.platform.module.minio;
import java.io.InputStream;
public interface MinioComponent {
void upload(String objectName, InputStream stream);
void uploadBase64(String objectName, String base64);
String getUrl(String objectName);
}
|
public class ServeiMaquina extends Servei {
// CONSTRUCTORS
public ServeiMaquina() {
this.quotaServei = 35.;
this.nomServei = "Servei de màquines";
}
// GETTERS & SETTERS
@Override
public void anunciServei() {
System.out.println("Si vols un lloc perfecte per entrenar el teu cos i ànima, possa a prova els teus músculs" +
"a la nostra sal");
}
}
|
package com;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
* Created by Administrator on 2017/07/14.
*/
public class Main03 extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Text Fonts");
Group root = new Group();
Scene scene = new Scene(root, 550, 250, Color.hsb(270,1.0,1.0,1.0));
Text text = new Text(50, 100, "JavaFX 2.0 from Moreyoung");
Font sanSerif = Font.font("Dialog", 30);
text.setFont(sanSerif);
text.setFill(Color.RED);
root.getChildren().add(text);
primaryStage.setScene(scene);
primaryStage.show();
}
}
|
package org.study.reservation.controller;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.print.attribute.standard.SheetCollate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.study.admin.DataDAO;
import org.study.admin.DataVO;
import org.study.admin.MovieDAO;
import org.study.admin.MovieVO;
import org.study.admin.ReserveDAO;
import org.study.admin.ReserveVO;
import org.springframework.web.bind.annotation.RequestParam;
import org.study.member.AuthInfo;
import org.study.member.AuthService;
import org.study.member.MemberDAO;
import org.study.member.MemberVO;
import org.study.member.controller.LoginCommand;
import org.study.reservation.ReservationInfoVO;
import org.study.reservation.ReservationService;
import org.study.schedule.ScheduleService;
import org.study.admin.ScheduleVO;
@Controller
@RequestMapping("reservation")
public class ReservationController {
Logger log = LoggerFactory.getLogger(ReservationController.class);
@Autowired
ScheduleService scheduleService;
@Autowired
ReservationService reservationService;
@Autowired
ReserveDAO reserveDAO;
@Autowired
MemberDAO memberDAO;
@Autowired
DataDAO dataDAO;
@Autowired
MovieDAO movieDao;
@Autowired
private AuthService authService;
public void setAuthService(AuthService authService) {
this.authService = authService;
}
// 예약 페이지 1 첫 화면
@GetMapping("reservePage01")
public String getReserveMoviePage(Model model) throws Exception {
//스케줄 정보 가져오기
List<ReservationInfoVO> scheduleList = reservationService.selectScheduleAll();
model.addAttribute("scheduleList", scheduleList);
model.addAttribute("center", "reservation/reservePage01");
return "home";
}
// @PostMapping("reservePage01")
// public String postReserveMoviePage(Model model, HttpServletRequest request) throws Exception {
// log.info("reserveTime");
// String movie_code = request.getParameter("movie");
// String cinema_code = request.getParameter("cinema");
// String day = request.getParameter("day");
//
// SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
// Date reserveDay = fm.parse(day);
//
// //List<MovieVO> movieList = movieService.reserveSelectMovie();
// //List<CinemaVO2> cinemaList = cinemaService.reserveSelectCinema();
// List<ScheduleVO> scheduleList = scheduleService.reserveSelectDay(); // 스케줄 리스트 전부
// List<ScheduleVO> schedule_dateList = scheduleService.selectSchedule_date();//스케줄 날짜 리스트
//
// //model.addAttribute("movieList", movieList);
// //model.addAttribute("cinemaList", cinemaList);
// model.addAttribute("scheduleList", scheduleList);
// model.addAttribute("schedule_dateList", schedule_dateList);
//
// System.out.println("영화정보 : " + movie_code + ", " + cinema_code + ", " + reserveDay);
//
// List<ScheduleVO> timeList = scheduleService.reserveSelectTime(movie_code, cinema_code, day);
//
// /* 영화정보 */
// //MovieVO movieInfo = movieService.selectMovieInfo(movie_code);// 선택된movie
// //CinemaVO2 cinemaInfo = cinemaService.selectCinemaInfo(cinema_code);// 선택된cinema
//
// // reserveInfoVO에 넣기
// ReservationInfoVO reserveInfo = new ReservationInfoVO();
// //reserveInfo.setMovie_code(movieInfo.getMovie_code());
// //reserveInfo.setMovie_sub(movieInfo.getMovie_sub());
// //reserveInfo.setCinema_code(cinemaInfo.getCinema_code());
// //reserveInfo.setCinema_name(cinemaInfo.getCinema_name());
// reserveInfo.setDay(reserveDay);
//
// System.out.println("Page01 : reserveDay : " + reserveInfo.getDay());
//// reserveInfo.setCinema_room();
//// reserveInfo.setStart_time();
//// reserveInfo.setEnd_time();
//// reserveInfo.setTotalSeat();
//// reserveInfo.setExtraSeat();
//// reserveInfo.setId();
//// reserveInfo.setBirth();
//
//// List<MovieVO2> movie_list = movieService.selectMovieSub(movie_code);
//
// // 선택된 영화 정보//
// // model.addAttribute("movie_code", movie_code);
// model.addAttribute("reserveInfo", reserveInfo);
// ////////////////
// // 시간 목록//
// model.addAttribute("timeList", timeList);
// ////////////////
// model.addAttribute("center", "reservation/reservePage01");
// return "home";
// }
// @PostMapping("reservePage02")
// public String postReserveSeat(ReservationInfoVO reserveInfo, Model model, HttpServletRequest request)
// throws Exception {
// log.info("reserveSeat");
//
// String strDay = request.getParameter("strDay");
// String strStart_time = request.getParameter("strStart_time");
// String strEnd_time = request.getParameter("strEnd_time");
//
// String seatArr[] = request.getParameterValues("seat");
//
// int seat;
//
// SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd");
// Date day = fm.parse(strDay);
//
// // String ->LocalTime
// LocalTime start_time = LocalTime.parse(strStart_time);
// LocalTime end_time = LocalTime.parse(strEnd_time);
//
// reserveInfo.setDay(day);
// reserveInfo.setStart_time(start_time);
// reserveInfo.setEnd_time(end_time);
//
// System.out.println("좌석 : ");
// for (int i = 0; i < seatArr.length; i++) {
// System.out.println(seatArr[i]);
//
// seat = Integer.parseInt(seatArr[i]);
// reserveInfo.setSeat_num(seat);;
//
// System.out.println("예약정보 : " + reserveInfo.getId() + "/"
// + reserveInfo.getCinema_code() + "/"
// + reserveInfo.getCinema_room() + "/"
// + reserveInfo.getMovie_code() + "/"
// + reserveInfo.getSchedule_code() + "/"
// + reserveInfo.getSeat_num() + "/"
// );
//
// //reservationService.insert(reserveInfo); //예약
// //좌석수 update
// reservationService.updateSeat_num(reserveInfo.getSchedule_code());
// }
//
// model.addAttribute("reserveInfo", reserveInfo);
// model.addAttribute("center", "reservation/reserveCompletePage");
// return "home";
// }
/* admin - 예매 관리 */
@GetMapping("reserveList")
public String getReserveList(Model model, HttpServletRequest request) throws Exception {
List<DataVO> data = dataDAO.selectAll();
model.addAttribute("data", data);
model.addAttribute("a_center", "reservation/reserveList");
return "a_home";
}
/* 나의 예매 내역 확인 */
@GetMapping("myReserveList")
public String memreserveList(Model model, HttpServletRequest request, HttpSession session) throws Exception {
AuthInfo authInfo = (AuthInfo) session.getAttribute("authInfo");
List<DataVO> reserveList = dataDAO.selectIdReserve(authInfo.getId());
model.addAttribute("reserveList", reserveList);
model.addAttribute("center", "reservation/myReserveList");
return "home";
}
}
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.DAO.LaguageDAO;
import model.object.Language;
@WebServlet("/insertLanguage")
public class InsertLanguage extends HttpServlet {
private static final long serialVersionUID = 1L;
public InsertLanguage() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String language = request.getParameter("language");
PrintWriter printWriter = response.getWriter();
Language languageObj = new Language(1, language);
if(LaguageDAO.insertLanguage(languageObj)) {
request.getRequestDispatcher("default?page=AddNewBook").forward(request, response);
}else {
printWriter.println("error");
}
}
}
|
package utils;
/**
* @author XuFankang
* @date 2019-7-7
* 用于扫描数字(含英文)只适用印刷体
*/
import com.java4less.ocr.tess3.OCRFacade;
public class OCR {
public static String OCR_recognition(String picAddress) {
OCRFacade facade=new OCRFacade();
String text="";
try {
text=facade.recognizeFile(picAddress, "eng");
System.out.println("Text in the image is: ");
System.out.println(text);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return text;
}
/**
* @param args
*/
public static void main(String[] args) {
//测试用例
System.out.println(OCR_recognition("C:\\Users\\lenovo\\Desktop\\670.jpg"));
}
}
|
/**
*
*/
package com.awssdt.entity;
import java.util.Map;
import lombok.Data;
/**
* @author lembrent
*
*/
@Data
public class ApiOutput {
private Integer statusCode;
private Map<String, String> headers;
private String body;
}
|
package com.biblio.api.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.biblio.api.core.LigneEmprunt;
@Repository
public interface LigneEmpruntRepository extends JpaRepository<LigneEmprunt, Long> {
public Iterable<LigneEmprunt> findByEmprunt_Id(long id);
public Iterable<LigneEmprunt> findByExemplaire_Id(long id);
}
|
package structure.list;
public class YeyDoublyLinkedList {
public YeyDoublyLinkedListNode head;
public YeyDoublyLinkedList() {}
public void store(String element) {
YeyDoublyLinkedListNode temp = this.head;
YeyDoublyLinkedListNode newElement = new YeyDoublyLinkedListNode(element);
if (isEmpty()) {
this.head = newElement;
return;
}
while (temp.next != null) {
temp = temp.next;
}
newElement.prev = temp;
temp.next = newElement;
}
public void store(int index, String element) {
int counter = 0;
YeyDoublyLinkedListNode tail;
YeyDoublyLinkedListNode temp = this.head;
YeyDoublyLinkedListNode newElement = new YeyDoublyLinkedListNode(element);
while (counter < index-1) {
temp = temp.next;
counter++;
}
tail = temp.next;
newElement.prev = temp;
temp.next = newElement;
temp.next.next = tail;
}
public String get(int index) {
int counter = 0;
YeyDoublyLinkedListNode temp = this.head;
while (counter < index ) {
temp = temp.next;
counter++;
}
return temp.data;
}
public void remove(int index) {
int counter = 0;
YeyDoublyLinkedListNode tail;
YeyDoublyLinkedListNode temp = this.head;
while (counter < index-1) {
temp = temp.next;
counter++;
}
tail = temp.next.next;
tail.prev = temp;
temp.next = tail;
}
public void update(int index, String newData) {
int counter = 0;
YeyDoublyLinkedListNode temp = this.head;
while (counter < index) {
temp = temp.next;
counter++;
}
temp.data = newData;
}
public int count() {
int counter = 1;
YeyDoublyLinkedListNode temp = this.head;
if (isEmpty()) return 0;
while (temp.next != null) {
temp = temp.next;
counter++;
}
return counter;
}
public boolean isEmpty() {
return (this.head == null);
}
public void printList() {
YeyDoublyLinkedListNode temp = this.head;
if (isEmpty()) return;
while (temp.next != null) {
System.out.println(temp.data);
temp = temp.next;
}
System.out.println(temp.data);
}
}
|
package EmmaD;
/**
* Created by rodrique on 3/12/2018.
*/
public class Client
{
private String clientName;
private String clientSurname;
private Account clientAccount;
public Client()
{
}
public Client(String n, String sn, Account acc)
{
}
public void setClientName(String n)
{
clientName = n;
}
public void setClientSurname(String sn)
{
clientSurname = sn;
}
public void setClientAccount(Account acc)
{
clientAccount = acc;
}
public String getClientName()
{
return clientName;
}
public String getClientSurname()
{
return clientSurname;
}
public Account getClientAccount()
{
return clientAccount;
}
public String toString()
{
String msg = String.format("Client Name: %s\nClient Surname: %s\n%s\n", getClientName(), getClientSurname(), getClientAccount());
return msg;
}
}
|
package Views.ProductParts;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import Controllers.ProductsParts.ProductPartsController;
import MVC.MasterFrame;
import MVC.Product;
import Models.ProductTemplateModel;
public class ProductPartsView extends JPanel{
private MasterFrame master;
private ProductTemplateModel model;
private JDesktopPane desktop;
private Product product;
private ArrayList<String> partArray = new ArrayList();
private String[] parts;
private String myTitle = "Product Parts";
private int newFrameX = 50, newFrameY = 50; //used to cascade or stagger starting x,y of JInternalFrames
JButton add = new JButton("Add Part to Template");
JList list = new JList();
public ProductPartsView(final ProductTemplateModel model, MasterFrame m){
master = m;
this.model = model;
product = model.getCurrentProductObject();
ProductPartsController Controller = new ProductPartsController(model, this, master);
this.setLayout(new BorderLayout());
desktop = master.getDesktop();
model.setProductPartArray(product.getId());
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AddProductPartView child = new AddProductPartView(model, master);
JInternalFrame frame = new JInternalFrame(child.getTitle(), true, true, true, true );
frame.add(child, BorderLayout.CENTER);
frame.pack();
//wimpy little cascade for new frame starting x and y
frame.setLocation(newFrameX, newFrameY);
newFrameX = (newFrameX) % desktop.getWidth();
newFrameY = (newFrameY) % desktop.getHeight();
desktop.add(frame);
frame.setVisible(true);
}
});
if(model.getProductPartList().isEmpty()){
master.displayChildMessage("This template contains no parts");
}else{
partArray = model.getProductPartList();//gets ArrayList of names
parts = new String[partArray.size()];//creates new String array the size of ArrayList namesArray
parts = partArray.toArray(parts);
list = new JList(parts);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.addListSelectionListener(Controller);
this.add(list, BorderLayout.CENTER);
this.add(add, BorderLayout.SOUTH);
}
}
public String getTitle(){
return myTitle;
}
public String getSelectedValue(){
return list.getSelectedValue().toString();
}
}
|
package com.baopinghui.bin.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baopinghui.bin.dto.ResultDto;
import com.baopinghui.bin.entity.ActiveEntity;
import com.baopinghui.bin.entity.ArticleEntity;
import com.baopinghui.bin.entity.CourseEntity;
import com.baopinghui.bin.entity.DianMianEntity;
import com.baopinghui.bin.mapper.app.ActiveMapper;
import com.baopinghui.bin.mapper.app.ArticleMapper;
import com.baopinghui.bin.mapper.app.CourseMapper;
import com.baopinghui.bin.service.ActiveService;
import com.baopinghui.bin.service.ArticleService;
import com.baopinghui.bin.service.CourseService;
import com.baopinghui.bin.service.DianMianService;
@Service
@Transactional
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Override
public Integer insertArticle(ArticleEntity a) {
// TODO Auto-generated method stub
Integer rd=articleMapper.insertArticle(a);
return rd;
}
@Override
public Integer updateArticle(ArticleEntity c) {
// TODO Auto-generated method stub
Integer a=articleMapper.updateArticle(c);
return a;
}
@Override
public Integer deleteArticle(int id) {
// TODO Auto-generated method stub
Integer a=articleMapper.deleteArticle(id);
return a;
}
@Override
public List<Map<String, Object>> selectArticle() {
// TODO Auto-generated method stub
List<Map<String, Object>> a=articleMapper.selectArticle();
return a;
}
}
|
/*
Esta clase es la encargada de conectarse con la base de datos en MySql
*/
package ordena_revistas;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author JesusDavid
*/
public class Conexion
{
//Información necesaria para poder conectarse con la base de datos
private static Connection conn;
private static String driver = "com.mysql.jdbc.Driver";
//private static String user = "root";
//private static String password = "";
private static String user = "chuchito";
private static String password = "root";
private static String url = "jdbc:mysql://localhost/datosudea";
//Metodo encargado de conectarse con la base de datos
public Conexion()
{
conn = null;
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
JOptionPane.showMessageDialog(null,"Se conecto con el servidor");
}
catch(ClassNotFoundException | SQLException e)
{
JOptionPane.showMessageDialog(null,"Error al conectar con el servidor");
}
}
public Connection getConection()
{
return conn;
}
public void desconectar()
{
conn = null;
if(conn == null)
{
System.out.println("conexion terminada");
}
}
public void creartb_estadisticas_generales_columnas()
{
try
{
String i = "CREATE TABLE IF NOT EXISTS estadisticas_generales_columnas (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, columna varchar(100), total int(11), promedio float(11), valores float(11), separadores int(11)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_spanish_ci";
System.out.println(i);
Statement st = conn.createStatement();
st.execute(i);
}
catch (Exception e)
{
System.out.println("Ocurrio este error "+e.getMessage());
}
}
public void creartb_distribucion_columnas(String[] columnas)
{
try
{
String i = "CREATE TABLE IF NOT EXISTS distribucion_columnas (name_file VARCHAR(50) NOT NULL PRIMARY KEY, ";
for (int j = 0; j < columnas.length; j++) {
if(columnas[j] != null){
i = i + columnas[j] + " VARCHAR(20),";
}
}
i = i.substring(0, i.length()-1)+") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_spanish_ci";
System.out.println(i);
Statement st = conn.createStatement();
st.execute(i);
}
catch (Exception e)
{
System.out.println("Ocurrio este error "+e.getMessage());
}
}
public void creartb_estadisticas_distribucion_columnas(String[] columnas)
{
try
{
String i = "CREATE TABLE IF NOT EXISTS estadisticas_distribucion_columnas (name_file VARCHAR(50) NOT NULL PRIMARY KEY, ";
for (int j = 0; j < columnas.length; j++) {
if(columnas[j] != null){
i = i + columnas[j] + " FLOAT,";
}
}
i = i.substring(0, i.length()-1)+") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_spanish_ci";
System.out.println(i);
Statement st = conn.createStatement();
st.execute(i);
}
catch (Exception e)
{
System.out.println("Ocurrio este error "+e.getMessage());
}
}
public void creartb_estadisticas_celdas_diferentes(String[] columnas)
{
try
{
String i = "CREATE TABLE IF NOT EXISTS estadisticas_celdas_diferentes (name_file VARCHAR(50) NOT NULL PRIMARY KEY, ";
for (int j = 0; j < columnas.length; j++) {
if(columnas[j] != null){
i = i + columnas[j] + " FLOAT,";
}
}
i = i.substring(0, i.length()-1)+") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_spanish_ci";
System.out.println(i);
Statement st = conn.createStatement();
st.execute(i);
}
catch (Exception e)
{
System.out.println("Ocurrio este error "+e.getMessage());
}
}
//too many columns
public void creartb_final(String[] columnas) {
try
{
String i = "CREATE TABLE IF NOT EXISTS tabla_final (title_id VARCHAR(50) NOT NULL PRIMARY KEY, ";
for (int j = 1; j < columnas.length; j++) {
if(columnas[j] != null){
i = i + columnas[j] + " text(50),";
}
}
i = i.substring(0, i.length()-1)+") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_spanish_ci";
System.out.println(i);
Statement st = conn.createStatement();
st.execute(i);
}
catch (Exception e)
{
System.out.println("Ocurrio este error "+e.getMessage());
}
}
public void inserta_valores_columnas(String[] columnas)
{
try
{
for (int j = 0; j < columnas.length; j++) {
if(columnas[j] != null){
String i = "INSERT INTO estadisticas_generales_columnas (columna,total) VALUES ('" + columnas[j] + "','0');";
System.out.println(i);
Statement st = conn.createStatement();
st.execute(i);
}
}
}
catch (Exception e)
{
System.out.println("Ocurrio este error "+e.getMessage());
}
}
//método para obtener la información de un alumno por semestre
public void ejecuta_sql(String sql)
{
try
{
System.out.println(sql);
Statement st = conn.createStatement();
st.execute(sql);
}
catch (SQLException e)
{
System.out.println("Ocurrio este error "+e.getMessage());
}
}
//métodos para obtener la información de todos los columnas
public String[] get_columnas()
{
String sql = "";
ResultSet columnas = null;
String[] stats_columnas = null;
try
{
sql = "SELECT * FROM estadisticas_generales_columnas";
System.out.println(sql);
Statement st = conn.createStatement();
columnas = st.executeQuery(sql);
stats_columnas = new String[obtenerCantFilas(columnas)];
int i = 0;
do{
stats_columnas[i] = columnas.getString(2);
i++;
}while(columnas.next());
}
catch (SQLException ex)
{
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
return stats_columnas;
}
public String[][] get_estadisticas_generales_columnas2()
{
String sql = "";
ResultSet columnas = null;
String[][] stats_columnas = null;
try
{
sql = "SELECT * FROM estadisticas_generales_columnas";
System.out.println(sql);
Statement st = conn.createStatement();
columnas = st.executeQuery(sql);
stats_columnas = new String[obtenerCantFilas(columnas)][6];
int i = 0;
do{
for (int j = 0; j < 6; j++) {
stats_columnas[i][j] = columnas.getString(j+1);
}
i++;
}while(columnas.next());
}
catch (SQLException ex)
{
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
return stats_columnas;
}
public String[][] get_estadisticas_distribucion_columnas()
{
String sql = "";
ResultSet columnas = null;
String[][] stats_columnas = null;
try
{
sql = "SELECT * FROM estadisticas_distribucion_columnas";
System.out.println(sql);
Statement st = conn.createStatement();
columnas = st.executeQuery(sql);
stats_columnas = new String[obtenerCantFilas(columnas)][68];
int i = 0;
do{
for (int j = 1; j < 68; j++) {
stats_columnas[i][j-1] = columnas.getString(j+1);
}
i++;
}while(columnas.next());
}
catch (SQLException ex)
{
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
return stats_columnas;
}
public String[][] get_distribucion_columnas()
{
String sql = "";
ResultSet columnas = null;
String[][] stats_columnas = null;
try
{
sql = "SELECT * FROM distribucion_columnas";
System.out.println(sql);
Statement st = conn.createStatement();
columnas = st.executeQuery(sql);
stats_columnas = new String[obtenerCantFilas(columnas)][68];
int i = 0;
do{
for (int j = 1; j < 68; j++) {
stats_columnas[i][j-1] = columnas.getString(j+1);
}
i++;
}while(columnas.next());
}
catch (SQLException ex)
{
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
return stats_columnas;
}
public String[][] get_distribucion_caracteres()
{
String sql = "";
ResultSet columnas = null;
String[][] stats_columnas = null;
try
{
sql = "SELECT * FROM estadisticas_celdas_diferentes";
System.out.println(sql);
Statement st = conn.createStatement();
columnas = st.executeQuery(sql);
stats_columnas = new String[obtenerCantFilas(columnas)][68];
int i = 0;
do{
for (int j = 1; j < 68; j++) {
stats_columnas[i][j-1] = columnas.getString(j+1);
}
i++;
}while(columnas.next());
}
catch (SQLException ex)
{
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
return stats_columnas;
}
public int obtenerCantFilas(ResultSet resultSet) throws SQLException
{
resultSet.last();
int filas = resultSet.getRow();
resultSet.first();
return filas;
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.explorer.client.grid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.editor.client.Editor.Path;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBean.PropertyName;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.client.loader.ScriptTagProxy;
import com.sencha.gxt.data.client.loader.StorageReadProxy;
import com.sencha.gxt.data.client.loader.StorageWriteProxy;
import com.sencha.gxt.data.client.loader.StorageWriteProxy.Entry;
import com.sencha.gxt.data.client.writer.UrlEncodingWriter;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import com.sencha.gxt.data.shared.loader.DataProxy;
import com.sencha.gxt.data.shared.loader.JsonReader;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.data.shared.loader.PagingLoadConfig;
import com.sencha.gxt.data.shared.loader.PagingLoadResult;
import com.sencha.gxt.data.shared.loader.PagingLoader;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.FramedPanel;
import com.sencha.gxt.widget.core.client.box.MessageBox;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.BoxLayoutContainer.BoxLayoutPack;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.toolbar.PagingToolBar;
@Detail(name = "LocalStorage Grid", icon = "localstoragegrid", category = "Grid", classes = {})
public class LocalStorageGridExample implements IsWidget, EntryPoint {
private FramedPanel fp;
interface TestAutoBeanFactory extends AutoBeanFactory {
static TestAutoBeanFactory instance = GWT.create(TestAutoBeanFactory.class);
AutoBean<ForumCollection> dataCollection();
AutoBean<ForumListLoadResult> dataLoadResult();
AutoBean<ForumLoadConfig> loadConfig();
}
public interface Forum {
@PropertyName("topic_title")
public String getTitle();
@PropertyName("topic_id")
public String getTopicId();
public String getAuthor();
@PropertyName("forumid")
public String getForumId();
@PropertyName("post_text")
public String getExcerpt();
@PropertyName("post_id")
public String getPostId();
@PropertyName("post_time")
public Date getDate();
}
interface ForumCollection {
String getTotalCount();
List<Forum> getTopics();
}
interface ForumLoadConfig extends PagingLoadConfig {
String getQuery();
void setQuery(String query);
@Override
@PropertyName("start")
public int getOffset();
@Override
@PropertyName("start")
public void setOffset(int offset);
}
interface ForumListLoadResult extends PagingLoadResult<Forum> {
void setData(List<Forum> data);
@Override
@PropertyName("start")
public int getOffset();
@Override
@PropertyName("start")
public void setOffset(int offset);
}
interface ForumProperties extends PropertyAccess<Forum> {
@Path("topicId")
ModelKeyProvider<Forum> key();
ValueProvider<Forum, String> title();
ValueProvider<Forum, String> excerpt();
ValueProvider<Forum, String> author();
ValueProvider<Forum, Date> date();
}
@Override
public void onModuleLoad() {
RootPanel.get().add(this);
}
@Override
public Widget asWidget() {
if (fp == null) {
final Storage storage = Storage.getLocalStorageIfSupported();
if (storage == null) {
new MessageBox("Not Supported","Your browser doesn't appear to supprt HTML5 localStorage").show();
return new HTML("LocalStorage not supported in this browser");
}
// Writer to translate load config into string
UrlEncodingWriter<ForumLoadConfig> writer = new UrlEncodingWriter<ForumLoadConfig>(TestAutoBeanFactory.instance, ForumLoadConfig.class);
// Reader to translate String results into objects
JsonReader<ForumListLoadResult, ForumCollection> reader = new JsonReader<ForumListLoadResult, ForumCollection>(
TestAutoBeanFactory.instance, ForumCollection.class) {
@Override
protected ForumListLoadResult createReturnData(Object loadConfig, ForumCollection records) {
PagingLoadConfig cfg = (PagingLoadConfig) loadConfig;
ForumListLoadResult res = TestAutoBeanFactory.instance.dataLoadResult().as();
res.setData(records.getTopics());
res.setOffset(cfg.getOffset());
res.setTotalLength(Integer.parseInt(records.getTotalCount()));
return res;
}
};
// Proxy to load from server
String url = "http://www.sencha.com/forum/topics-remote.php";
final ScriptTagProxy<ForumLoadConfig> remoteProxy = new ScriptTagProxy<ForumLoadConfig>(url);
remoteProxy.setWriter(writer);
// Proxy to load objects from local storage
final StorageReadProxy<ForumLoadConfig> localReadProxy = new StorageReadProxy<ForumLoadConfig>(storage);
localReadProxy.setWriter(writer);
// Proxy to persist network-loaded objects into local storage
final StorageWriteProxy<ForumLoadConfig, String> localWriteProxy = new StorageWriteProxy<ForumLoadConfig, String>(storage);
localWriteProxy.setKeyWriter(writer);
// Wrapper Proxy to dispatch to either storage or scripttag, and to save results
DataProxy<ForumLoadConfig, String> proxy = new DataProxy<ForumLoadConfig, String>() {
@Override
public void load(final ForumLoadConfig loadConfig, final Callback<String, Throwable> callback) {
// Storage read is known to be synchronous, so read it first - if null, continue
localReadProxy.load(loadConfig, new Callback<String, Throwable>() {
@Override
public void onFailure(Throwable reason) {
// ignore failure, go remote
onSuccess(null);
}
@Override
public void onSuccess(String result) {
if (result != null) {
callback.onSuccess(result);
} else {
//read from remote and save it
remoteProxy.load(loadConfig, new Callback<JavaScriptObject, Throwable>() {
@Override
public void onSuccess(JavaScriptObject result) {
//write results to local db
String json = new JSONObject(result).toString();
Entry<ForumLoadConfig, String> data = new Entry<ForumLoadConfig, String>(loadConfig, json);
localWriteProxy.load(data, new Callback<Void, Throwable>() {
@Override
public void onSuccess(Void result) {
// ignore response
}
@Override
public void onFailure(Throwable reason) {
// ignore response
}
});
callback.onSuccess(json);
}
@Override
public void onFailure(Throwable reason) {
callback.onFailure(reason);
}
});
}
}
});
}
};
PagingLoader<ForumLoadConfig, ForumListLoadResult> loader = new PagingLoader<ForumLoadConfig, ForumListLoadResult>(
proxy, reader);
loader.useLoadConfig(TestAutoBeanFactory.instance.loadConfig().as());
ForumProperties props = GWT.create(ForumProperties.class);
ListStore<Forum> store = new ListStore<Forum>(props.key());
loader.addLoadHandler(new LoadResultListStoreBinding<ForumLoadConfig, Forum, ForumListLoadResult>(store));
ColumnConfig<Forum, String> cc1 = new ColumnConfig<Forum, String>(props.title(), 100, "Title");
cc1.setSortable(false);
ColumnConfig<Forum, String> cc2 = new ColumnConfig<Forum, String>(props.excerpt(), 165, "Excerpt");
cc2.setSortable(false);
ColumnConfig<Forum, Date> cc3 = new ColumnConfig<Forum, Date>(props.date(), 100, "Date");
cc3.setSortable(false);
ColumnConfig<Forum, String> cc4 = new ColumnConfig<Forum, String>(props.author(), 50, "Author");
cc4.setSortable(false);
List<ColumnConfig<Forum, ?>> l = new ArrayList<ColumnConfig<Forum, ?>>();
l.add(cc1);
l.add(cc2);
l.add(cc3);
l.add(cc4);
ColumnModel<Forum> cm = new ColumnModel<Forum>(l);
Grid<Forum> grid = new Grid<Forum>(store, cm);
grid.getView().setForceFit(true);
grid.setLoader(loader);
grid.setLoadMask(true);
grid.setBorders(true);
final PagingToolBar toolBar = new PagingToolBar(50);
toolBar.getElement().getStyle().setProperty("borderBottom", "none");
toolBar.add(new TextButton("Clear Cache", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
storage.clear();
}
}));
toolBar.bind(loader);
fp = new FramedPanel();
fp.setHeadingText("LocalStorage Grid Example");
fp.setCollapsible(true);
fp.setAnimCollapse(true);
fp.setPixelSize(575, 350);
fp.addStyleName("margin-10");
fp.setButtonAlign(BoxLayoutPack.CENTER);
VerticalLayoutContainer con = new VerticalLayoutContainer();
con.setBorders(true);
con.add(grid, new VerticalLayoutData(1, 1));
con.add(toolBar, new VerticalLayoutData(1, -1));
fp.setWidget(con);
loader.load();
}
return fp;
}
}
|
package com.example.aplikasiuntukuts.data;
import android.app.Application;
import androidx.lifecycle.LiveData;
import java.util.List;
public class CheeseRepository {
private CheeseDao dao;
private LiveData<List<Cheese>> cheeseLiveData;
public CheeseRepository(Application application){
SampleDatabase db = SampleDatabase.getInstance(application);
dao = db.cheeseDao();
cheeseLiveData= dao.getAlphabetizedTasks();
}
LiveData<List<Cheese>> getAllCheese(){ return cheeseLiveData; }
}
|
package com.dian.diabetes.dialog;
import java.util.Calendar;
import com.dian.diabetes.R;
import com.dian.diabetes.widget.wheel.NumericWheelAdapter;
import com.dian.diabetes.widget.wheel.WheelView;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class TimeDialog extends Dialog implements
android.view.View.OnClickListener {
private Calendar calendar;
private String title;
private CallBack callBack;
private TextView titleView;
private Button okBtn;
private WheelView hourView;
private WheelView miniView;
public TimeDialog(Context context, String title) {
super(context, R.style.Dialog);
this.title = title;
setCanceledOnTouchOutside(true);
setContentView(R.layout.dialog_hourmin_layout);
calendar = Calendar.getInstance();
initView();
}
private void initView() {
titleView = (TextView) findViewById(R.id.dialog_operate_name);
titleView.setText(title);
okBtn = (Button) findViewById(R.id.ok_btn);
okBtn.setOnClickListener(this);
Button btnCancel = (Button) findViewById(R.id.cancel_btn);
btnCancel.setOnClickListener(this);
hourView = (WheelView) findViewById(R.id.hour);
miniView = (WheelView) findViewById(R.id.mini);
// hour
int curHour = calendar.get(Calendar.HOUR);
hourView.setAdapter(new NumericWheelAdapter(0, 23, "00"));
hourView.setCurrentItem(curHour);
hourView.setCyclic(true);
hourView.setVisibleItems(3);
// mini
int curMini = calendar.get(Calendar.MINUTE);
miniView.setAdapter(new NumericWheelAdapter(0, 59, "00"));
miniView.setCurrentItem(curMini);
miniView.setCyclic(true);
miniView.setVisibleItems(3);
}
/**
* 展现出来
*
* @param cal
*/
public void show(int hour, int mini) {
super.show();
hourView.setCurrentItem(hour);
miniView.setCurrentItem(mini);
}
public void show(long timeMini) {
super.show();
Calendar tcalendar = Calendar.getInstance();
tcalendar.setTimeInMillis(timeMini);
hourView.setCurrentItem(tcalendar.get(Calendar.HOUR_OF_DAY));
miniView.setCurrentItem(tcalendar.get(Calendar.MINUTE));
}
public void show() {
super.show();
Calendar tcalendar = Calendar.getInstance();
tcalendar.setTimeInMillis(System.currentTimeMillis());
hourView.setCurrentItem(tcalendar.get(Calendar.HOUR_OF_DAY));
miniView.setCurrentItem(tcalendar.get(Calendar.MINUTE));
}
public void setCallBack(CallBack cal) {
this.callBack = cal;
}
public interface CallBack {
boolean callBack(int hour, int mini);
}
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.ok_btn:
boolean state = callBack.callBack(hourView.getCurrentItem(),
miniView.getCurrentItem());
if (state) {
dismiss();
}
break;
case R.id.cancel_btn:
dismiss();
break;
}
}
}
|
package dotplot;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.applet.Applet;
import symap.frame.HelpBar;
import util.DatabaseReader;
// mdb added 7/10/09 for ProjectManagerFrame - FIXME: redundant with DotPlot.java
@SuppressWarnings("serial") // Prevent compiler warning for missing serialVersionUID
public class DotPlotFrame extends JFrame {
Data data;
public DotPlotFrame(DatabaseReader dbReader, int projXIdx, int projYIdx) {
this(null, dbReader, new int[] { projXIdx, projYIdx }, null, null, null, true);
}
public DotPlotFrame(DatabaseReader dbReader) {
this(null, dbReader, null, null, null, null, true);
}
public DotPlotFrame(Applet applet, DatabaseReader dbReader,
int[] projIDs, int[] xGroupIDs, int[] yGroupIDs,
HelpBar helpBar, boolean hasReferenceSelector)
{
super("SyMAP Dot Plot");
if (applet != null)
data = new Data( applet );
else
data = new Data( new DotPlotDBUser(dbReader) );
data.getSyMAP().clear(); // Clear caches - fixes "Couldn't find pair for projects" bug due to stale pairs data
HelpBar hb = helpBar;
if (helpBar == null)
hb = new HelpBar(-1, 17, true, false, false);
Plot plot = new Plot(data,hb);
ControlPanel controls = new ControlPanel(applet,data,plot,hb);
if (projIDs != null) {
data.initialize(projIDs, xGroupIDs, yGroupIDs);
controls.setProjects( data.getProjects() ); // mdb added 2/1/10 #210
}
if (projIDs == null || !hasReferenceSelector)
controls.setProjects(null);
// Setup frame
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
if (data != null) data.kill();
data = null;
}
});
setLayout( new BorderLayout() );
add( controls, BorderLayout.NORTH );
add( plot.getScrollPane(),BorderLayout.CENTER );
if (helpBar == null)
add( hb, BorderLayout.SOUTH );
}
public Data getData() { return data; }
}
|
package ninja.pelirrojo.takibat.irc;
public class ModeLine extends ParsedLine{
private final User sender;
private final Channel destChan;
private final String destUser;
private final String opts;
protected ModeLine(String line){
super(line);
String[] chars = line.substring(1).split(" ");
sender = User.parse(chars[0]);
if(chars[2].indexOf("#") > -1){
destChan = new Channel(chars[2]);
opts = chars[3];
destUser = chars[4];
}
else{
destChan = null;
destUser = chars[2];
opts = chars[3].substring(1);
}
}
public User getSender(){
return sender;
}
public Channel getDestChan(){
return destChan;
}
public String getDestUser(){
return destUser;
}
public String getOpts(){
return opts;
}
}
|
package com.ngocdt.tttn.service;
import com.ngocdt.tttn.dto.SizeDTO;
public interface SizeService extends GenericService<SizeDTO, Integer> {
}
|
package com.jinglangtech.teamchat.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import com.jinglangtech.teamchat.R;
import com.umeng.message.UmengNotifyClickActivity;
import org.android.agoo.common.AgooConstants;
public class MeizuPushActivity extends UmengNotifyClickActivity {
private static String TAG = MeizuPushActivity.class.getName();
private TextView mipushTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mipush);
mipushTextView = (TextView) findViewById(R.id.mipushTextView);
}
@Override
public void onMessage(Intent intent) {
super.onMessage(intent); //此方法必须调用,否则无法统计打开数
final String body = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
Log.i(TAG, body);
if (!TextUtils.isEmpty(body)) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mipushTextView.setText(body);
}
});
}
}
}
|
package com.cinema.biz.action;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cinema.biz.model.SimDeviceDependency;
import com.cinema.biz.model.base.TSimDeviceDependency;
import com.cinema.biz.service.SimDeviceDependencyService;
import com.cinema.sys.action.util.ActionContext;
import com.cinema.sys.action.util.Service;
import com.cinema.sys.service.LogService;
import com.cinema.sys.utils.ExceptionUtil;
import com.cinema.sys.utils.MyParam;
import com.cinema.sys.utils.MyUUID;
import com.cinema.sys.utils.TimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
/**依赖关系设置模块Action层*/
@Component
@Service(name = "simDeviceDependencyAction")
public class SimDeviceDependencyAction {
@Autowired
private SimDeviceDependencyService simDeviceDependencyService;
@Autowired
private LogService logService;
/**列表*/
public JSONObject getList(ActionContext cxt) {
Map<String, Object> paraMap = new HashMap<> ();
paraMap.put("deviceDependencyId", MyParam.getString(cxt, "deviceDependencyId"));
paraMap.put("code", MyParam.getString(cxt, "code"));
paraMap.put("dependencyId", MyParam.getString(cxt, "dependencyId"));
//分页查询
PageHelper.startPage(MyParam.getInt(cxt, "page", 1),MyParam.getInt(cxt, "rows", 15));
Page<SimDeviceDependency> p=(Page<SimDeviceDependency>)simDeviceDependencyService.getList(paraMap);
JSONObject json = new JSONObject();
json.put("list",p.getResult());
json.put("total", p.getTotal());
return json;
}
/**详情*/
public JSONObject getDetail(ActionContext cxt) {
Map<String, Object> paraMap = new HashMap<> ();
paraMap.put("deviceDependencyId", MyParam.getString(cxt, "deviceDependencyId"));
JSONObject json = new JSONObject();
json.put("model",simDeviceDependencyService.getDetail(paraMap));
return json;
}
/**添加*/
public JSONObject insert(ActionContext cxt) {
JSONObject json = new JSONObject();
try {
TSimDeviceDependency t = JSON.toJavaObject(MyParam.getDataItem(cxt, "dataItem"), TSimDeviceDependency.class);
t.setDeviceDependencyId(MyUUID.getUUID());
simDeviceDependencyService.insert(t);
json.put("success", true);
json.put("message","添加依赖关系设置成功");
} catch (Exception e) {
e.printStackTrace();
json.put("message", ExceptionUtil.getInsertMessage(e, "添加依赖关系设置失败"));
json.put("success", false);
}
logService.addLog("添加依赖关系设置", cxt, json);
return json;
}
/**更新*/
public JSONObject update(ActionContext cxt) {
JSONObject json = new JSONObject();
try {
TSimDeviceDependency t = JSON.toJavaObject(MyParam.getDataItem(cxt, "dataItem"), TSimDeviceDependency.class);
simDeviceDependencyService.update(t);
json.put("success", true);
json.put("message","修改依赖关系设置成功");
} catch (Exception e) {
e.printStackTrace();
json.put("message", ExceptionUtil.getUpdateMessage(e, "修改依赖关系设置失败"));
json.put("success", false);
}
logService.addLog("修改依赖关系设置", cxt, json);
return json;
}
/**删除*/
public JSONObject delete(ActionContext cxt) {
JSONObject json = new JSONObject();
try {
JSONArray ids = JSON.parseArray(MyParam.getString(cxt, "ids"));
if (ids.size() == 0)
throw new Exception("ids不能为空");
for (int i = 0; i < ids.size(); i++)
simDeviceDependencyService.delete(ids.getString(i));
json.put("success", true);
json.put("message","删除依赖关系设置成功");
} catch (Exception ex) {
ex.printStackTrace();
json.put("message", ExceptionUtil.getDeleteMessage(ex, "删除依赖关系设置失败"));
json.put("success", false);
}
logService.addLog("删除依赖关系设置", cxt, json);
return json;
}
}
|
package com.thinkitive;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
if (DatabaseValidation.validateUser(username, password)) {
out.println("Username: " + username);
out.println("Password: " + password);
} else {
out.println("Your Username or Password is incorrect.");
}
}
}
|
package com.programapprentice.app;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* User: program-apprentice
* Date: 10/15/15
* Time: 8:08 PM
*/
public class ShortestPalindrome_Test {
ShortestPalindrome_214 obj = new ShortestPalindrome_214();
@Test
public void test1() {
String s = "abcd";
String expected = "dcbabcd";
String actual = obj.shortestPalindrome(s);
assertEquals(expected, actual);
}
@Test
public void test2() {
String s = "aacecaaa";
String expected = "aaacecaaa";
String actual = obj.shortestPalindrome(s);
assertEquals(expected, actual);
}
}
|
package id.barkost.waris;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MateriMasalah extends Activity {
public Button a1, a2, a3, a4, a5, a6, a7;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.materi_masalah);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
int new_h = height / 11;
int new_w = width;
a1 = (Button) findViewById(R.id.mat_masalah1);
a2 = (Button) findViewById(R.id.mat_masalah2);
a3 = (Button) findViewById(R.id.mat_masalah3);
a4 = (Button) findViewById(R.id.mat_masalah4);
a5 = (Button) findViewById(R.id.mat_masalah5);
a6 = (Button) findViewById(R.id.mat_masalah6);
a7 = (Button) findViewById(R.id.mat_masalah7);
a1.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h));
a2.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h));
a3.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h));
a4.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h));
a5.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h));
a6.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h));
a7.setLayoutParams(new LinearLayout.LayoutParams(new_w, new_h));
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.mat_masalah1:
MateriMasalahCnt.pos = 0;
break;
case R.id.mat_masalah2:
MateriMasalahCnt.pos = 1;
break;
case R.id.mat_masalah3:
MateriMasalahCnt.pos = 2;
break;
case R.id.mat_masalah4:
MateriMasalahCnt.pos = 3;
break;
case R.id.mat_masalah5:
MateriMasalahCnt.pos = 4;
break;
case R.id.mat_masalah6:
MateriMasalahCnt.pos = 5;
break;
case R.id.mat_masalah7:
MateriMasalahCnt.pos = 6;
break;
default:
break;
}
Intent i = new Intent(MateriMasalah.this, MateriMasalahCnt.class);
startActivity(i);
overridePendingTransition(R.anim.slide_from_right, R.anim.stand);
}
public void onBackPressed() {
finish();
overridePendingTransition(R.anim.stand, R.anim.slide_to_right);
}
}
|
package lithe.lithe;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.content.Context;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import java.io.IOException;
import Lithe_Data.GateWay;
import Lithe_Data.Post.Post;
import Lithe_Data.User;
public class HomeScreenActivity extends ListActivity {
private static User user;
private static Post[] values;
private TextView TVgreeting;
private int NewMessage=0;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private PostsTask mFetchTask = null;
private LogoutTask mLogoutTask = null;
private View mProgressView;
private ListView mListView;
private GeneralSwipeRefreshLayout mSwipeRefreshLayout;
private TextView newmessage;
private Spinner PostTypeSpinner;
private EditText SearchBar;
private ImageButton HomeSearchButton;
private int CurrentPostType=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
//pull from server to get profile information
super.onCreate(savedInstanceState);
user = MainActivity.getUser();
setContentView(R.layout.activity_home_screen);
PostTypeSpinner=(Spinner) findViewById(R.id.PostTypeSpinner);
setSpinnerAdapter();
PostTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (CurrentPostType != position) {
CurrentPostType = position;
attemptFetch();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
SearchBar=(EditText)findViewById(R.id.SearchBar);
HomeSearchButton=(ImageButton)findViewById(R.id.HomeSearchButton);
HomeSearchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CurrentPostType=7;
if(SearchBar.getText().toString().equals(""))
SearchBar.setError("Please input keyword(s)");
else
attemptFetch();
}
});
newmessage=(TextView)findViewById(R.id.newmessage);
TVgreeting=(TextView) findViewById(R.id.Greeting);
mListView =(ListView) findViewById(android.R.id.list);
mProgressView = findViewById(R.id.fetch_progress);
Button CreatePost = (Button) findViewById(R.id.CreateButton);
CreatePost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
create_post();
}
});
if(user.getUserName().equals("viewer")) {
TVgreeting.setText("Click here to login.");
TVgreeting.setTextColor(Color.rgb(0, 0, 225));
TVgreeting.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
back();
}
});
}
else{TVgreeting.setText("Welcome back, "+user.getUserName()+" !");
TVgreeting.setTextColor(Color.rgb(0, 225, 0));}
if(user.getUserName().equals("viewer")){CreatePost.setEnabled(false);}
attemptFetch();
//values = new Post[] {};
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt,
long paramLong) {
switch(user.getMyPost()[paramInt].getPostType()){
case 1:ViewListingActivity.setPostNo(paramInt);
ViewListing();break;
case 2:ViewRequest.setPostNo(paramInt);
ViewRequest();break;
case 3:ViewTicketActivity.setPostNo(paramInt);
ViewTicket();break;
case 4:ViewEventActivity.setPostNo(paramInt);
ViewEvent();break;
case 5:ViewRideShare.setPostNo(paramInt);
ViewRideShare();break;
}
}
});
mSwipeRefreshLayout = (GeneralSwipeRefreshLayout) findViewById(R.id.home_swipe_container);
mSwipeRefreshLayout.setOnChildScrollUpListener(new GeneralSwipeRefreshLayout.OnChildScrollUpListener() {
@Override
public boolean canChildScrollUp() {
return mListView.getFirstVisiblePosition() > 0 ||
mListView.getChildAt(0) == null ||
mListView.getChildAt(0).getTop() < 0;
}
});
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
attemptFetch();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_home_screen, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_mail_box:
if(!user.getUserName().equals("viewer"))
{openMailbox();}
return true;
case R.id.action_search:
//openSearch();
return true;
case R.id.action_log_out:
mLogoutTask = new LogoutTask();
mLogoutTask.execute((Void) null);
return true;
case R.id.action_settings:
//openSettings();
return true;
case R.id.action_profile:
openProfile();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openMailbox() {
Intent intent = new Intent(this, MailBox.class);
startActivity(intent);
}
private void openProfile() {
Intent intent = new Intent(this, ProfileActivity.class);
startActivity(intent);
}
private void logout() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mListView.setVisibility(show ? View.GONE : View.VISIBLE);
mListView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mListView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mListView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
private class LogoutTask extends AsyncTask<Void, Void, Integer> {
LogoutTask() { }
@Override
protected Integer doInBackground(Void... params) {
GateWay test = user.getGateway();
test.ConnectToServer("logout to viewer");
user.setUser("viewer");
try { test.end(); } catch (IOException e) { e.printStackTrace(); }
return 0;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(final Integer success) {
mLogoutTask = null;
showProgress(false);
switch (success) {
case 0: logout(); break;
}
}
@Override
protected void onCancelled() {
mLogoutTask = null;
showProgress(false);
}
}
private class PostsTask extends AsyncTask<Void, Void, Integer> {
private Post[] fetch;
PostsTask() {
}
@Override
protected Integer doInBackground(Void... params) {
GateWay test = user.getGateway();
test.ConnectToServer(user.getUserName());
switch (CurrentPostType) {
case 0: user.GetListing();break;
case 1: user.GetRequest();break;
case 2: user.GetTicket();break;
case 3: user.GetRideShare();break;
case 4: user.GetEvent();break;
case 5: user.GetMyPost(4);break;
case 6: user.GetMyPost(5);break;
case 7: user.GetPostByKeyword(SearchBar.getText().toString());break;
}
fetch =user.getMyPost();
NewMessage=user.CheckNewMessage();
try { test.end(); } catch (IOException e) { e.printStackTrace(); }
return 0;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(final Integer success) {
mFetchTask = null;
showProgress(false);
switch (success) {
case 0:
values = fetch;
finish();
SearchBar.setText("");
}
}
@Override
protected void onCancelled() {
mFetchTask = null;
showProgress(false);
}
}
public void attemptFetch() {
mFetchTask = new PostsTask();
mFetchTask.execute((Void) null);
}
public void finish() {
ArrayAdapter<Post> adapter = new ArrayAdapter<Post>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
PostAdapter adapter2=new PostAdapter(values, this);
mListView.setAdapter(adapter2);
if(NewMessage==1)
{ newmessage.setText("New Message(s)");}
else newmessage.setText("");
}
public void create_post() {
Intent intent = new Intent(this, CreatePost.class);
startActivity(intent);
}
public void back()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void ViewListing()
{
Intent intent = new Intent(this, ViewListingActivity.class);
startActivity(intent);
}
public void ViewRequest()
{
Intent intent = new Intent(this, ViewRequest.class);
startActivity(intent);
}
public void ViewEvent()
{
Intent intent = new Intent(this, ViewEventActivity.class);
startActivity(intent);
}
public void ViewRideShare()
{
Intent intent = new Intent(this, ViewRideShare.class);
startActivity(intent);
}
public void ViewTicket()
{
Intent intent = new Intent(this, ViewTicketActivity.class);
startActivity(intent);
}
public void setSpinnerAdapter(){
ArrayAdapter<CharSequence> adapter1;
if(user.getUserName().equals("viewer"))
adapter1 = ArrayAdapter.createFromResource(this,
R.array.Post_Type2, android.R.layout.simple_spinner_item);
else
adapter1 = ArrayAdapter.createFromResource(this,
R.array.Post_Type, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
PostTypeSpinner.setAdapter(adapter1);
}
private class PostAdapter extends ArrayAdapter<Post>{
private Post[] post;
private Context context;
private PostAdapter(Post[] post, Context context) {
super(context,R.layout.single_item_post_listview,post);
this.post=post;
this.context=context;}
private class PostListViewHolder{
public TextView title;
public TextView type;
public TextView timeleft;
public TextView username;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v=convertView;
PostListViewHolder holder =new PostListViewHolder();
//if(convertView==null)
if(true){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
v=inflater.inflate(R.layout.single_item_post_listview,null);
holder.title=(TextView) v.findViewById(R.id.LVtitle);
holder.type=(TextView) v.findViewById(R.id.TVtype1);
holder.timeleft=(TextView) v.findViewById(R.id.TVdutation);
holder.username=(TextView) v.findViewById(R.id.TVusername);
}
else {holder=(PostListViewHolder)v.getTag();}
Post o=post[position];
holder.username.setText("By: "+o.getOwner());
if(o.getDuration().equals("expired"))holder.timeleft.setTextColor(Color.rgb(225, 0, 0));
else holder.timeleft.setTextColor(Color.rgb(0, 225, 0));
holder.timeleft.setText(o.getDuration());
holder.title.setText(o.getTitle());
if(o.getPostType()==1){holder.type.setText("Listing");}
if(o.getPostType()==2){holder.type.setText("Request");}
if(o.getPostType()==3&&o.isType()==true){holder.type.setText("Lost Ticket");}
if(o.getPostType()==3&&o.isType()==false){holder.type.setText("Found Ticket");}
if(o.getPostType()==4){holder.type.setText("Event");}
if(o.getPostType()==5&&o.isType()==true){holder.type.setText("Ride Share Offer");}
if(o.getPostType()==5&&o.isType()==false){holder.type.setText("Ride Share Request");}
return v;
}
}
}
|
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import javax.annotation.Nonnull;
public class InputLexerSource extends LexerSource {
@Deprecated
public InputLexerSource(@Nonnull InputStream input) {
this(input, Charset.defaultCharset());
}
public InputLexerSource(@Nonnull InputStream input, Charset charset) {
this(new InputStreamReader(input, charset));
}
public InputLexerSource(@Nonnull Reader input, boolean ppvalid) {
super(input, true);
}
public InputLexerSource(@Nonnull Reader input) {
this(input, true);
}
@Override
public String getPath() {
return "<standard-input>";
}
@Override
public String getName() {
return "standard input";
}
@Override
public String toString() {
return String.valueOf(getPath());
}
}
|
package com.jvschool.view;
import com.jvschool.security.SecurityService;
import com.jvschool.svc.api.UserService;
import com.jvschool.dto.SessionUser;
import com.jvschool.util.validators.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
@Controller
@SessionAttributes("user")
public class LoginController {
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidator;
@GetMapping(value = {"/", "/home"})
public String home() {
return "home";
}
@GetMapping(value = "/login")
public String start(Model model, String error, HttpServletRequest request) {
if (error != null)
model.addAttribute("error", "Username or password is incorrect.");
else {
String referrer = request.getHeader("Referer");
request.getSession().setAttribute("url_prior_login", referrer);
}
return "login";
}
@GetMapping(value = "/403")
public String accessDenied() {
return "error/accessDenied";
}
@PostMapping(value = "/sendPassword")
public @ResponseBody boolean sendForgotPassword(@RequestParam("sendEmail") String email) {
return userService.sendLoginPasswordToEmail(email);
}
@GetMapping(value = "/registration")
public String registration(Model model) {
model.addAttribute("userForm", new SessionUser());
return "registration";
}
@PostMapping(value = "/registration")
public String registration(@ModelAttribute("userForm") SessionUser userForm, BindingResult bindingResult,
@ModelAttribute("user") SessionUser user, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.addUser(userForm);
userForm.setId(userService.getUserIdByEmail(user.getEmail()));
securityService.autoLogin(userForm.getLogin(),userForm.getConfirmPassword());
userForm.setPass("");
userForm.setConfirmPassword("");
userForm.setProducts(user.getProducts());
model.addAttribute("user",userForm);
return "redirect:/home";
}
@PostMapping(value = "/registration/findEmail/")
@ResponseBody
public String checkEmailExisting(@RequestParam String email) {
if (userService.getUserIdByEmail(email)!=0) {
return "this email already exists";
} else
return "";
}
@PostMapping(value = "/registration/findLogin/")
@ResponseBody
public String checkLoginExisting(@RequestParam String login) {
if (userService.getUserIdByLogin(login)!=0) {
return "this login already exists";
} else
return "";
}
}
|
package edu.erlm.epi.service.util;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;
import edu.erlm.epi.web.rest.dto.ImageDTO;
public class FileUtil {
private FileUtil() {
}
public final static String IMAGE_DIRECTORY_ABSOLUTE_PATH = "D:/DevTools/Workspace/epi/epi/src/main/webapp/dist/uploads";
public final static String IMAGE_DIRECTORY_RELATIVE_PATH = "dist/uploads";
public static ImageDTO uploadImage(MultipartFile multipartFile) throws IOException {
if (multipartFile.isEmpty()) {
throw new RuntimeException("error occured during image upload: the Image is Empty");
}
String fileName = generateUniqueFileName();
File file = new File(IMAGE_DIRECTORY_ABSOLUTE_PATH + File.separator + fileName
+ FilenameUtils.EXTENSION_SEPARATOR + FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());
return new ImageDTO(IMAGE_DIRECTORY_RELATIVE_PATH + File.separator + file.getName());
}
public static edu.erlm.epi.domain.exercise.File valueOfFile(MultipartFile multipartFile, Long techingExerciseId)
throws IOException {
if (multipartFile.isEmpty()) {
throw new RuntimeException("error occured during file upload: the multipartFile is Empty");
}
edu.erlm.epi.domain.exercise.File file = new edu.erlm.epi.domain.exercise.File();
file.setBinaryData(multipartFile.getBytes());
file.setName(multipartFile.getOriginalFilename());
file.setLength((int) multipartFile.getSize());
file.setTeachingExerciseId(techingExerciseId);
return file;
}
public static String generateUniqueFileName() {
String filename = "";
long millis = System.currentTimeMillis();
@SuppressWarnings("deprecation")
String datetime = new Date().toGMTString();
datetime = datetime.replace(" ", "");
datetime = datetime.replace(":", "");
String rndchars = RandomStringUtils.randomAlphanumeric(16);
filename = rndchars + datetime + millis;
return filename;
}
}
|
/* Copyright (C) RunRightFast.co - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
* Written by Alfio Zappala azappala@azaptree.com, March 2014
*/
package co.runrightfast.zest.concurrent.disruptor;
import org.apache.commons.lang3.StringUtils;
/**
*
* @author alfio
* @param <DATA> reference to RingBuffer
*/
public final class RingBufferReference<DATA> {
public DATA data;
@Override
public String toString() {
return data != null ? data.toString() : StringUtils.EMPTY;
}
}
|
package net.datacrow.console.components;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JToolTip;
import net.datacrow.util.DcSwingUtilities;
public class DcPopupMenu extends JPopupMenu {
@Override
public JMenuItem add(JMenuItem menuItem) {
if (menuItem != null)
super.add(menuItem);
return menuItem;
}
@Override
public void addSeparator() {
if (getComponentCount() > 0) {
Component[] c = getComponents();
if (c[c.length - 1] instanceof JMenuItem)
super.addSeparator();
}
}
@Override
public JToolTip createToolTip() {
return new DcMultiLineToolTip();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(DcSwingUtilities.setRenderingHint(g));
}
}
|
package com.mariusgrams.dynamicgridlib;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.mariusgrams.dynamicgrid.DynamicGrid;
import com.mariusgrams.dynamicgrid.GridItem;
import com.mariusgrams.dynamicgrid.IViewCallback;
import com.mariusgrams.dynamicgridlib.examples.HomeFragment;
import com.mariusgrams.dynamicgridlib.examples.RandomItemsColor;
import com.mariusgrams.dynamicgridlib.examples.SimpleExampleFragment;
import com.mariusgrams.dynamicgridlib.gridItems.ExampleGridItem1;
import com.mariusgrams.dynamicgridlib.gridItems.ExampleGridItem2;
public class MainActivity extends AppCompatActivity {
private static ImageButton ibtnBack;
private static FragmentManager fm;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
ibtnBack = findViewById(R.id.ibtnBack);
ibtnBack.setOnClickListener(v -> switchFragment(new HomeFragment()));
showBackButton(false);
switchFragment(new HomeFragment());
}
public static void switchFragment(Fragment fragment){
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.rootLayout, fragment);
transaction.addToBackStack(fragment.toString());
transaction.commit();
}
public static void showBackButton(boolean isBackButtonShown){
if(isBackButtonShown){
ibtnBack.setVisibility(View.VISIBLE);
}else{
ibtnBack.setVisibility(View.INVISIBLE);
}
}
}
|
package dk.jrpe.monitor.service.command;
import dk.jrpe.monitor.db.datasource.HttpAccessDataSource;
import dk.jrpe.monitor.db.datasource.DataSourceFactory;
import dk.jrpe.monitor.db.httpaccess.to.JsonHTTPAccessTO;
import dk.jrpe.monitor.json.JSONMapper;
import dk.jrpe.monitor.source.httpaccess.to.HTTPAccessTOFactory;
/**
* Command for sending on successful HTTP request
* @author Jörgen Persson
*/
public class SendHttpSuccessPerMinuteDataCmd extends Command {
private final HttpAccessDataSource dataSource = DataSourceFactory.get();
@Override public void execute(CommandHandler cmdHandler) {
JsonHTTPAccessTO to = JSONMapper.toJsonHTTPAccessTO(cmdHandler.getJson());
if(to != null) this.dataSource.updateHttpSuccessPerMinute(HTTPAccessTOFactory.convertToDbTo(to));
}
}
|
package mine.exceptions;
public class InvalidSequence extends Exception {
}
|
package com.xinyu.simple.common.constant;
/**
*@Author xinyu
*@Description 常量类
*@Date 18:18 2019/12/17
**/
public class WebConstants {
//接口前缀
public static final String API_PREFIX = "/xinyu/ximple";
}
|
package com.citibank.ods.entity.pl;
import java.util.Date;
import java.util.HashMap;
import com.citibank.ods.entity.pl.valueobject.TplMrDocPrvtEntityVO;
/**
* @author m.nakamura
*
* Agregador da tabela de Memória de Risco.
*/
public class TplMrDocPrvtEntity extends BaseTplMrDocPrvtEntity
{
/**
* Cria novo objeto TplMrDocPrvtEntity.
*/
public TplMrDocPrvtEntity()
{
m_data = new TplMrDocPrvtEntityVO();
m_tplContactCustEntities = new HashMap();
}
/**
* Cria novo objeto TplMrDocPrvtEntity com valores definidos.
*
* @param mrDocPrvtMovEntity_ - Entidade com os valores de Movimento do
* Cadastro.
* @param lastAuthDate_ - A data da aprovação.
* @param lastAuthUserId_ - O usuário da aprovação.
*/
public TplMrDocPrvtEntity( TplMrDocPrvtMovEntity mrDocPrvtMovEntity_,
Date lastAuthDate_, String lastAuthUserId_ )
{
m_data = new TplMrDocPrvtEntityVO( mrDocPrvtMovEntity_, lastAuthDate_,
lastAuthUserId_ );
}
}
|
package controller.registrar.student;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import configuration.*;
import connection.DBConfiguration;
/**
* Servlet implementation class AdmissionCurriculumItemViewController
*/
@WebServlet("/Registrar/Controller/Registrar/Student/Curriculum3")
public class Curriculum3 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Curriculum3() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("plain/text");
EncryptandDecrypt ec = new EncryptandDecrypt();
String studentnumber = request.getParameter("studentnumber");
Fullname fn = new Fullname();
DBConfiguration db = new DBConfiguration();
Connection conn = db.getConnection();
Statement stmnt = null;
Statement stmnt2 = null;
Statement stmnt3 = null;
Statement stmnt4 = null;
Statement stmnt5 = null;
try {
stmnt = conn.createStatement();
stmnt2 = conn.createStatement();
stmnt3 = conn.createStatement();
stmnt4 = conn.createStatement();
stmnt5 = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sql = "";
String yearlvl = "";
String courid = "";
String curyear = "";
String studaccid = "";
try {
sql = "SELECT * from t_student_account inner join r_student_profile on Student_Account_Student_Profile_ID = Student_Profile_ID where Student_Account_Student_Number= '"+studentnumber+"'";
ResultSet rs = stmnt.executeQuery(sql);
while(rs.next()){
yearlvl = rs.getString("Student_Account_Year");
courid = rs.getString("Student_Account_CourseID");
curyear = rs.getString("Student_Account_CurriculumYearID");
studaccid = rs.getString("Student_Account_ID");
}
sql = "SELECT * FROM r_curriculumitem inner join `r_curriculum` on CurriculumItem_CurriculumID = Curriculum_ID inner join r_semester on Curriculum_SemesterID = Semester_ID where Curriculum_CourseID = '"+courid+"' and Curriculum_CurriculumYearID = '"+curyear+"' and CurriculumItem_Display_Status = 'Active' group by Curriculum_YearLevel ";
rs = stmnt.executeQuery(sql);
String peryearlvl ="";
String persem = "";
String semid = "";
PrintWriter out = response.getWriter();
JSONArray wholecurriculum = new JSONArray();
while(rs.next()){
peryearlvl = rs.getString("Curriculum_YearLevel");
String sql2 = "SELECT * FROM r_curriculumitem inner join `r_curriculum` on CurriculumItem_CurriculumID = Curriculum_ID inner join r_semester on Curriculum_SemesterID = Semester_ID where Curriculum_CourseID = '"+courid+"' and Curriculum_CurriculumYearID = '"+curyear+"' and Curriculum_YearLevel = '"+peryearlvl+"' and CurriculumItem_Display_Status = 'Active' group by Semester_ID ";
// out.print(sql2+"\n");
ResultSet rs2 = stmnt2.executeQuery(sql2);
while(rs2.next()){
persem = ec.decrypt(ec.key, ec.initVector, rs2.getString("Semester_Description"));
semid = rs2.getString("Semester_ID");
String sql3 = "SELECT Subject_ID,Subject_Code,Subject_Description,Subject_Credited_Units,Subject_Tuition_Hours FROM `r_curriculumitem` inner join r_curriculum on CurriculumItem_CurriculumID = Curriculum_ID INNER JOIN r_curriculumyear ON CurriculumYear_ID = Curriculum_CurriculumYearID INNER JOIN r_subject as t1 ON CurriculumItem_SubjectID = Subject_ID WHERE Curriculum_CourseID = '"+courid+"' and Curriculum_SemesterID = '"+semid+"' and Curriculum_YearLevel = '"+peryearlvl+"' and CurriculumItem_Display_Status = 'Active'and CurriculumYear_Ative_Flag = 'Active' order by (select count(*) from r_subject as er where er.Subject_Group = t1.Subject_ID) asc ";
//out.print(sql3+"\n");
JSONArray subjectcurholder = new JSONArray();
ResultSet rs3 = stmnt3.executeQuery(sql3);
while(rs3.next()){
JSONObject subjectcur = new JSONObject();
JSONArray grouplist = new JSONArray();
JSONArray prereq = new JSONArray();
subjectcur.put("code", ec.decrypt(ec.key, ec.initVector, rs3.getString("Subject_Code")));
subjectcur.put("desc", ec.decrypt(ec.key, ec.initVector, rs3.getString("Subject_Description")));
subjectcur.put("tuition", rs3.getString("Subject_Tuition_Hours"));
subjectcur.put("units", rs3.getString("Subject_Credited_Units"));
String subid = rs3.getString("Subject_ID");
String sql4 = "SELECT * FROM r_prerequisite inner join r_subject on Prerequisite_Prequisite_SubjectID = Subject_ID where Prerequisite_Main_SubjectID = '"+subid+"' and Prerequisite_Display_Status = 'Active' ";
ResultSet rs4 = stmnt4.executeQuery(sql4);
while(rs4.next()){
prereq.add(ec.decrypt(ec.key, ec.initVector, rs4.getString("Subject_Code")));
}
//bago mo baguinpar eto yung nauna jusq grumaduate kanaman HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA
// subjectcur.put("prerequisite",prereq);
subjectcur.put("prerequisite",prereq);
sql4 = "SELECT case when if(Students_Grade_Grade is null,0,Students_Grade_Grade) not in (if(Students_Grade_Grade is null,'0','D''INC''not S')) then 'Cleared' else 'Not Cleared' end as stat FROM `t_student_taken_curriculum_subject` left join t_students_grade on Students_Grade_StudentTakenCurriculumSubjectID = Student_Taken_Curriculum_Subject_ID WHERE `Student_Taken_Curriculum_Subject_StudentAccountID` = '"+studaccid+"' and Student_Taken_Curriculum_Subject_SubjectID = '"+subid+"' ";
rs4 = stmnt4.executeQuery(sql4);
String status = "Not Cleared";
while(rs4.next()){
status = rs4.getString("stat");
}
subjectcur.put("status", status);
sql4 = "SELECT count(*) as cou FROM `t_student_taken_curriculum_subject` WHERE `Student_Taken_Curriculum_Subject_StudentAccountID` = '"+studaccid+"' and Student_Taken_Curriculum_Subject_SubjectID = '"+subid+"' and Student_Taken_Curriculum_Subject_Taken_Status = 'true' and Student_Taken_Curriculum_Subject_SemesterID = (SELECT Semester_ID FROM `r_semester` WHERE Semester_Active_Flag = 'Active' ) and Student_Taken_Curriculum_Subject_AcademicIYearID = (SELECT Academic_Year_ID FROM `r_academic_year` WHERE Academic_Year_Active_Flag = 'Present' ) ";
rs4 = stmnt4.executeQuery(sql4);
String estatus = "Not Enrolled";
while(rs4.next()){
if(!rs4.getString("cou").equals("0")) {
estatus = "Enrolled";
}
}
subjectcur.put("estatus", estatus);
sql4 = "SELECT * FROM `r_subject` AS T1 WHERE T1.Subject_Group = (SELECT T2.Subject_ID FROM r_subject AS T2 where T2.Subject_Code = '"+rs3.getString("Subject_Code")+"' )";
rs4 = stmnt4.executeQuery(sql4);
while(rs4.next()){
JSONObject group = new JSONObject();
group.put("code", ec.decrypt(ec.key, ec.initVector, rs4.getString("Subject_Code")));
group.put("desc", ec.decrypt(ec.key, ec.initVector, rs4.getString("Subject_Description")));
group.put("units", rs4.getString("Subject_Credited_Units"));
group.put("tuition", rs4.getString("Subject_Tuition_Hours"));
subid = rs4.getString("Subject_ID");
String sql5 = "SELECT * FROM r_prerequisite inner join r_subject on Prerequisite_Prequisite_SubjectID = Subject_ID where Prerequisite_Main_SubjectID = '"+subid+"' and Prerequisite_Display_Status = 'Active' ";
ResultSet rs5 = stmnt5.executeQuery(sql5);
JSONArray grpprereq = new JSONArray();
while(rs5.next()){
grpprereq.add(ec.decrypt(ec.key, ec.initVector, rs5.getString("Subject_Code")));
}
group.put("prerequisite", grpprereq);
sql5 = "SELECT case when if(Students_Grade_Grade is null,0,Students_Grade_Grade) not in (if(Students_Grade_Grade is null,'0','D''INC''not S')) then 'Cleared' else 'Not Cleared' end as stat FROM `t_student_taken_curriculum_subject` left join t_students_grade on Students_Grade_StudentTakenCurriculumSubjectID = Student_Taken_Curriculum_Subject_ID WHERE `Student_Taken_Curriculum_Subject_StudentAccountID` = '"+studaccid+"' and Student_Taken_Curriculum_Subject_SubjectID = '"+subid+"' ";
rs5 = stmnt5.executeQuery(sql5);
status = "Not Cleared";
while(rs5.next()){
status = rs5.getString("stat");
}
group.put("status", status);
sql5 = "SELECT count(*) as cou FROM `t_student_taken_curriculum_subject` WHERE `Student_Taken_Curriculum_Subject_StudentAccountID` = '"+studaccid+"' and Student_Taken_Curriculum_Subject_SubjectID = '"+subid+"' and Student_Taken_Curriculum_Subject_Taken_Status = 'true' and Student_Taken_Curriculum_Subject_SemesterID = (SELECT Semester_ID FROM `r_semester` WHERE Semester_Active_Flag = 'Active' ) and Student_Taken_Curriculum_Subject_AcademicIYearID = (SELECT Academic_Year_ID FROM `r_academic_year` WHERE Academic_Year_Active_Flag = 'Present' ) ";
rs5 = stmnt5.executeQuery(sql5);
estatus = "Not Enrolled";
while(rs5.next()){
if(!rs5.getString("cou").equals("0")) {
estatus = "Enrolled";
}
}
group.put("estatus", estatus);
grouplist.add(group);
}
subjectcur.put("group", grouplist);
subjectcurholder.add(subjectcur);
}
JSONObject curyearsem = new JSONObject();
curyearsem.put("yearlvl", peryearlvl);
curyearsem.put("semester", persem);
curyearsem.put("subject", subjectcurholder);
//out.print(curyearsem);
wholecurriculum.add(curyearsem);
}
}
out.print("\n"+wholecurriculum);
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.example.demo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
// @RestController annotation was created in order to simplify the creation of RESTful web services
@RestController
@RequestMapping(path = "api/tutorial/student")
public class StudentController {
private final StudentService StudentService;
@Autowired
public StudentController(com.example.demo.Student.StudentService studentService) {
StudentService = studentService;
}
//todo: Get -- expose end point which return array of student
@GetMapping
public List<Student> getStudentInfo(){
return StudentService.getStudentInfo();
}
@PostMapping
public void registerNewStudent(@RequestBody Student student){
StudentService.addNewStudent(student);
}
@DeleteMapping(path= "{studentId}")
public void deleteStudent(@PathVariable("studentId")Long studentId){
StudentService.deleteStudent(studentId);
}
@PutMapping(path = "{studentId}")
public void updateStudent(
@PathVariable("studentId")Long studentId,
@RequestParam(required = false) String name,
@RequestParam(required = false) String email
){
StudentService.updateStudent(studentId,name,email);
}
}
|
package pe.gob.sis;
import java.text.SimpleDateFormat;
import java.util.Hashtable;
import java.util.Vector;
import be.mxs.common.util.system.ScreenHelper;
public class Atencion extends SIS_Object{
public Atencion() {
super(85, "SIS_ATENCION");
}
public Atencion get(String uid){
return (Atencion)get(tableName,fields,uid);
}
public String getErrors(){
String errors = "";
for(int n=1;n<=fields;n++){
if(!isValid(n)){
if(errors.length()>0){
errors+=",";
}
errors+=n;
}
}
return errors;
}
public static Atencion getForFUA(String uid){
return (Atencion)get("SIS_ATENCION",85,uid);
}
boolean isValid(int fieldid){
if("*1*5*18*24*43*44*72*79*80*81*".contains("*"+fieldid+"*")){
return getValueInt(fieldid)>0;
}
else if("*2*3*4*6*7*8*14*17*20*21*28*31*32*33*34*35*36*42*45*74*".contains("*"+fieldid+"*")){
return getValueString(fieldid).length()>0;
}
else if("*10*".contains("*"+fieldid+"*")){
return "*S*N*".contains("*"+getValueString(fieldid).toUpperCase()+"*");
}
else if("*11*12*13*".contains("*"+fieldid+"*")){
return getValueString(10).equalsIgnoreCase("N") || getValueString(fieldid).length()>0;
}
else if("*25*".contains("*"+fieldid+"*")){
if(getValueInt(24)==1 || getValueInt(24)==4){
return getValueString(fieldid).length()==8;
}
else if(getValueInt(24)==2){
return true;
}
else if(getValueInt(24)==3){
return getValueString(fieldid).length()==9;
}
else if(getValueInt(24)==7){
return getValueString(fieldid).length()>0;
}
else if(getValueInt(24)==8){
return getValueString(fieldid).length()==10;
}
}
else if("*26*27*".contains("*"+fieldid+"*")){
return getValueString(27).length()>0 || getValueString(26).length()>0;
}
else if("*30*".contains("*"+fieldid+"*")){
return getValueDate(fieldid)!=null;
}
else if("*37*".contains("*"+fieldid+"*")){
if(getValueInt(36)==2 || getValueInt(36)==3 || getValueInt(36)==6){
return getValueString(fieldid).length()>0;
}
}
else if("*38*".contains("*"+fieldid+"*")){
if(getValueInt(36)==2 || getValueInt(36)==3 || getValueInt(36)==6){
return getValueDouble(fieldid)>0;
}
}
else if("*39*83*".contains("*"+fieldid+"*")){
return getValueDateTime(fieldid)!=null;
}
else if("*40*41*".contains("*"+fieldid+"*")){
return (getValueInt(34)!=2 || getValueInt(43)==3) || getValueString(fieldid).length()>0;
}
else if("*46*".contains("*"+fieldid+"*")){
return (!"*065*066*067*068*".contains("*"+getValueString(42)+"*") || (getValueDate(fieldid)!=null && getValueDate(39)!=null && !getValueDate(fieldid).after(getValueDate(39))));
}
else if("*47*".contains("*"+fieldid+"*")){
return (!"*065*066*067*068*".contains("*"+getValueString(42)+"*") || (getValueDate(fieldid)!=null && getValueDate(39)!=null && !getValueDate(fieldid).before(getValueDate(39))));
}
else if("*48*49*".contains("*"+fieldid+"*")){
if(getValueInt(45)>2 && getValueInt(45)<7){
return getValueString(fieldid).length()>0;
}
}
else if("*50*".contains("*"+fieldid+"*")){
if(getValueInt(35)==2){
return getValueDate(fieldid)!=null;
}
if(getValueInt(35)==0){
return getValueDate(fieldid)==null;
}
}
else if("*60*".contains("*"+fieldid+"*")){
return getValueInt(43)!=4 || getValueString(fieldid).length()>0;
}
else if("*65*".contains("*"+fieldid+"*")){
return getValueInt(45)!=9 || getValueString(fieldid).length()>0;
}
else if("*73*".contains("*"+fieldid+"*")){
if(getValueInt(72)==1){
return getValueString(fieldid).length()==8;
}
else if(getValueInt(72)==3){
return getValueString(fieldid).length()==9;
}
}
else if("*82*".contains("*"+fieldid+"*")){
if(getValueInt(81)==1){
return getValueString(fieldid).length()==8;
}
else if(getValueInt(81)==3){
return getValueString(fieldid).length()==9;
}
}
return true;
}
}
|
package com.prolific.vidmediaplayer.Fragments;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Intent;
import android.content.IntentSender;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaMetadataRetriever;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.formats.UnifiedNativeAd;
import com.prolific.vidmediaplayer.Activities.BaseActivity;
import com.prolific.vidmediaplayer.Activities.MainActivity;
import com.prolific.vidmediaplayer.Activities.SelectionActivity;
import com.prolific.vidmediaplayer.Activities.SettingActivity;
import com.prolific.vidmediaplayer.Activities.VideoPlayerActivity;
import com.prolific.vidmediaplayer.Adapter.VideoAdapter;
import com.prolific.vidmediaplayer.BuildConfig;
import com.prolific.vidmediaplayer.Models.MessageEvent;
import com.prolific.vidmediaplayer.Models.ModelClassForVideo;
import com.prolific.vidmediaplayer.Others.CustomTypefaceSpan;
import com.prolific.vidmediaplayer.R;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import static com.prolific.vidmediaplayer.Others.AdLoader.initInterstitialAds;
public class VideosFrag extends Fragment implements View.OnClickListener {
private ArrayList<ModelClassForVideo> arrayListVideosSearch;
private VideoAdapter mAdapter;
private RecyclerView mVideoRecyclerView;
private LinearLayout llEmpty;
public ArrayList<Object> videosArrayList, videoListWOLastPlay;
private ArrayList<Uri> videosUriList;
private String fileOriginalName;
private RecyclerView.LayoutManager mLayoutManager;
private int mPosition = 0;
private long totalSize = 0;
private int sortVal;
private boolean isLastPlayVisible;
private ModelClassForVideo latestVideoData;
private String str = "";
private boolean isAlreadyReverse = false;
private MainActivity mainActivity;
private ShimmerFrameLayout shimmerViewContainer;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setHasOptionsMenu(true);
}
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
View view = layoutInflater.inflate(R.layout.fragment_videos, viewGroup, false);
initView(view);
return view;
}
private void initView(View view) {
mainActivity = new MainActivity();
mVideoRecyclerView = view.findViewById(R.id.videosRecycler);
shimmerViewContainer = view.findViewById(R.id.shimmerViewContainer);
shimmerViewContainer.startShimmer();
llEmpty = view.findViewById(R.id.llEmpty);
videoListWOLastPlay = new ArrayList<>();
videosArrayList = new ArrayList<>();
videosUriList = new ArrayList<>();
// getAllVideos();
int viewTypeVal = ((MainActivity) requireActivity()).getIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_VIEW_AS);
if (viewTypeVal == 0) {
mLayoutManager = new LinearLayoutManager(getContext());
mVideoRecyclerView.setLayoutManager(mLayoutManager);
} else if (viewTypeVal == 1) {
mLayoutManager = new GridLayoutManager(getContext(), 2);
GridLayoutManager manager = (GridLayoutManager) mLayoutManager;
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int i) {
switch (i) {
case 0:
return 2;
default:
return 1;
}
}
});
mVideoRecyclerView.setLayoutManager(manager);
} else {
mLayoutManager = new LinearLayoutManager(getContext());
mVideoRecyclerView.addItemDecoration(new DividerItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL));
mVideoRecyclerView.setLayoutManager(mLayoutManager);
}
mVideoRecyclerView.setHasFixedSize(true);
new GetAllVideos().execute();
mAdapter = new VideoAdapter(getActivity(), videosArrayList, "main_list", VideosFrag.this::onClick);
mVideoRecyclerView.setAdapter(mAdapter);
}
@Override
public void onStart() {
super.onStart();
if (!EventBus.getDefault().isRegistered(this))
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe
public void OnMessageEvent(MessageEvent event) {
if (event.name.equalsIgnoreCase("RefreshVideo")) {
// new GetAllVideos().execute();
getAllVideos();
if (videosArrayList != null && videosArrayList.size() > 0) {
addRemoveLatestPlayData();
// loadNativeAds();
mVideoRecyclerView.setVisibility(View.VISIBLE);
llEmpty.setVisibility(View.GONE);
mAdapter.notifyDataSetChanged();
} else {
mVideoRecyclerView.setVisibility(View.GONE);
llEmpty.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onResume() {
super.onResume();
// ((MainActivity) getActivity()).restartApp();
addRemoveLatestPlayData();
}
private void addRemoveLatestPlayData() {
if(videosArrayList.size() > 0) {
isLastPlayVisible = ((MainActivity) requireActivity()).getBooleanPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_IS_LAST_PLAY_VISIBLE);
if (isLastPlayVisible) {
latestVideoData = ((MainActivity) requireActivity()).getLatestVideo(getActivity(), BaseActivity.PREF_LATEST_PLAY);
if (latestVideoData != null && latestVideoData.getSongPath() != null && !latestVideoData.getSongPath().equals("")) {
videosArrayList.set(0, latestVideoData);
mAdapter.notifyItemChanged(0);
}
} else {
mAdapter.notifyItemChanged(0);
}
}
}
private class GetAllVideos extends AsyncTask<Void, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("Tag", "---------[ OnPreExecute ]-----");
// addRemoveLatestPlayData();
}
@Override
protected String doInBackground(Void... voids) {
requireActivity().runOnUiThread(new Runnable() {
public void run() {
getAllVideos();
}
});
return "";
}
@Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
Log.e("Tag", "---------[ OnPostExecute ]-----");
if (videosArrayList != null && videosArrayList.size() > 0) {
addRemoveLatestPlayData();
// loadNativeAds();
mVideoRecyclerView.setVisibility(View.VISIBLE);
llEmpty.setVisibility(View.GONE);
shimmerViewContainer.stopShimmer();
shimmerViewContainer.setVisibility(View.GONE);
mAdapter.notifyDataSetChanged();
} else {
mVideoRecyclerView.setVisibility(View.GONE);
llEmpty.setVisibility(View.VISIBLE);
shimmerViewContainer.stopShimmer();
}
// mAdapter.notifyDataSetChanged();
}
}
private void getAllVideos() {
totalSize = 0;
videosArrayList.clear();
videoListWOLastPlay.clear();
videosUriList.clear();
sortVal = ((MainActivity) requireActivity()).getIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_SORT_BY);
if (sortVal == 0) {
str = "title ASC";
} else if (sortVal == 1) {
str = "_size ASC";
} else if (sortVal == 2) {
str = "duration ASC";
} else if (sortVal == 3) {
str = "date_modified DESC";
} else if (sortVal == 4) {
str = "date_modified ASC";
}
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] strArr = {"_data", "title", "bucket_display_name", "duration", "_size", "date_added", "date_modified"};//, "resolution" //,MediaStore.Video.VideoColumns.RESOLUTION
Cursor cursor = Objects.requireNonNull(getContext()).getContentResolver().query(uri, strArr, null, null, str);
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int vidSize = cursor.getColumnIndexOrThrow("_size");
String path = cursor.getString(cursor.getColumnIndexOrThrow("_data"));
ModelClassForVideo modelClassForVideo = new ModelClassForVideo();
modelClassForVideo.setBoolean_selected(false);
modelClassForVideo.setSongPath(path);
modelClassForVideo.setSongName(cursor.getString(cursor.getColumnIndexOrThrow("title")));
modelClassForVideo.setSongAlbum(cursor.getString(cursor.getColumnIndexOrThrow("bucket_display_name")));
modelClassForVideo.setSongThumb(path);
modelClassForVideo.setSongDuration(cursor.getInt(cursor.getColumnIndexOrThrow("duration")));
modelClassForVideo.setSongSize(cursor.getInt(vidSize));
modelClassForVideo.setDateAdded(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED)));
modelClassForVideo.setDateModified(cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED)));
modelClassForVideo.setTypeVal(1);
videosArrayList.add(modelClassForVideo);
Uri vidUri;
File f = new File(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
vidUri = FileProvider.getUriForFile(requireActivity(), BuildConfig.APPLICATION_ID + ".fileprovider", f);
} else {
vidUri = Uri.fromFile(f);
}
videosUriList.add(vidUri);
totalSize = totalSize + cursor.getInt(vidSize);
Log.e("TAG", "getMusic-path :" + path + "---- Count : " + cursor.getCount());
((MainActivity) requireActivity()).totalVidSize = totalSize;
}
if (videosArrayList.size() > 0) {
videoListWOLastPlay.addAll(videosArrayList);
if (((ModelClassForVideo)videosArrayList.get(0)).getTypeVal() != 0) {
ModelClassForVideo modelClassForVideo = new ModelClassForVideo();
modelClassForVideo.setBoolean_selected(false);
modelClassForVideo.setTypeVal(0);
videosArrayList.add(0, modelClassForVideo);
}
if (sortVal == 5) {
if (isAlreadyReverse) {
ModelClassForVideo data0 = (ModelClassForVideo)videosArrayList.get(0);
videosArrayList.remove(0);
Collections.reverse(videosArrayList);
Collections.reverse(videosUriList);
Collections.reverse(videoListWOLastPlay);
videosArrayList.add(0, data0);
isAlreadyReverse = true;
}
}
}
}
cursor.close();
}
private AdLoader adLoader;
private void loadNativeAds() {
AdLoader.Builder builder = new AdLoader.Builder(requireContext(), getString(R.string.app_nativeAd_id));
adLoader = builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
@Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// A native ad loaded successfully, check if the ad loader has finished loading
// and if so, insert the ads into the list.
if (!adLoader.isLoading()) {
insertAdsInMenuItems(unifiedNativeAd);
}
}
}).withAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(int errorCode) {
// A native ad failed to load, check if the ad loader has finished loading
// and if so, insert the ads into the list.
Log.e("TAG~~~", "Filed to load Native Ad : " + errorCode);
}
}).build();
// Load the Native ads.
adLoader.loadAds(new AdRequest.Builder().build(), 1);
}
private int c=0;
private void insertAdsInMenuItems(UnifiedNativeAd ad) {
if (ad == null) {
return;
}
int index = 2;
for (int i = 0; i < videosArrayList.size(); i++) {
c++;
if(c == 10){
//TODO: add logic to add unified ad to array
videosArrayList.add(i, ad);
c = 0;
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Log.e("TAG", "ResultCode = " + resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 20000) {//Rename in android 11 only
if (dRename != null && dRename.isShowing()) {
dRename.dismiss();
}
updateTag2(requireActivity());
} else if (requestCode == 10000) {//Delete in android 11 only
if (dDelete != null && dDelete.isShowing()) {
dDelete.dismiss();
}
deleteRecordAndNotify();
}
} else {
Toast.makeText(mainActivity, "error", Toast.LENGTH_SHORT).show();
}
}
private int updateRows;
private void updateTag2(Activity activity) {
updateRows = 0;
Uri uri = ((MainActivity) requireActivity()).getUriFromPath(from.getAbsolutePath(), requireActivity());
ContentValues values = new ContentValues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Video.Media.IS_PENDING, 1);
requireActivity().getContentResolver().update(uri, values, null, null);
values.put(MediaStore.Video.Media.IS_PENDING, 0);
values.put(MediaStore.Video.Media.DISPLAY_NAME, to.getName());
updateRows = requireActivity().getContentResolver().update(uri, values, null, null);
requireActivity().getContentResolver().notifyChange(uri, null);
} else {
updateRows = requireActivity().getContentResolver().update(uri, values, null, null);
values.put(MediaStore.Video.Media.DISPLAY_NAME, to.getName());
requireActivity().getContentResolver().notifyChange(uri, null);
}
MediaScannerConnection.scanFile(activity, new String[]{from.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "-> Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
if (updateRows > 0) {
notifyOtherTabData();
}
}
private File from, to;
private Dialog dRename;
private void renameFile() {
String path = ((ModelClassForVideo)videosArrayList.get(mPosition)).getSongPath();
dRename = new Dialog(requireActivity());
dRename.setContentView(R.layout.layout_rename);
dRename.getWindow().setLayout(-1, -2);
Button cancel = (Button) dRename.findViewById(R.id.btnCancel);
Button btnRename = (Button) dRename.findViewById(R.id.btnRename);
EditText editText = (EditText) dRename.findViewById(R.id.etRename);
editText.setHint("Please enter video name");
File oldFile = new File(path);
String name = oldFile.getName();
fileOriginalName = name;
String substring = name.substring(0, name.lastIndexOf("."));
fileOriginalName = substring;
editText.setText(substring);
editText.setSelection(0, editText.getText().length());
editText.setHighlightColor(ContextCompat.getColor(requireActivity(), R.color.colorAccent));
editText.requestFocus();
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {
}
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
if (editText.getText().toString().equals(fileOriginalName) || editText.getText().toString().equals("")) {
btnRename.setAlpha(0.4f);
btnRename.setEnabled(false);
return;
}
btnRename.setAlpha(1.0f);
btnRename.setEnabled(true);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dRename.dismiss();
}
});
btnRename.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String absolutePath = oldFile.getParentFile().getAbsolutePath();
String absolutePath2 = oldFile.getAbsolutePath();
String substring = absolutePath2.substring(absolutePath2.lastIndexOf("."));
File file = new File(absolutePath + "/" + editText.getText().toString() + substring);// + substring
if (oldFile.exists()) {
from = oldFile;
to = file;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
ArrayList<Uri> list = new ArrayList<>();
list.add(((MainActivity) requireActivity()).getUriFromPath(from.getAbsolutePath(), requireActivity()));
PendingIntent intent = MediaStore.createWriteRequest(requireActivity().getContentResolver(), list);
try {
startIntentSenderForResult(intent.getIntentSender(), 20000, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
if (oldFile.renameTo(file)) {
requireActivity().getApplicationContext().getContentResolver().delete(MediaStore.Files.getContentUri("external"), "_data=?", new String[]{oldFile.getAbsolutePath()});
Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
intent.setData(Uri.fromFile(file));
requireActivity().getApplicationContext().sendBroadcast(intent);
notifyOtherTabData();
} else {
Toast.makeText(requireActivity(), getResources().getString(R.string.rename_fail), Toast.LENGTH_SHORT).show();
dRename.dismiss();
}
}
} else {
Toast.makeText(requireActivity(), getResources().getString(R.string.rename_file_not_exist), Toast.LENGTH_SHORT).show();
}
}
});
dRename.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dRename.show();
}
public void notifyOtherTabData() {
new Handler().postDelayed(new Runnable() {
public void run() {
ModelClassForVideo modelClassForVideo = new ModelClassForVideo();
modelClassForVideo.setBoolean_selected(false);
modelClassForVideo.setSongPath(to.getAbsolutePath());
modelClassForVideo.setSongThumb(to.getAbsolutePath());
String name = to.getName();
if (name.contains(".")) {
String[] strName = name.split("\\.");
modelClassForVideo.setSongName(strName[0]);
} else {
modelClassForVideo.setSongName(name);
}
modelClassForVideo.setSongAlbum(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongAlbum());
modelClassForVideo.setSongDuration(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongDuration());
modelClassForVideo.setSongSize(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongSize());
modelClassForVideo.setDateAdded(((ModelClassForVideo)videosArrayList.get(mPosition)).getDateAdded());
modelClassForVideo.setDateModified(((ModelClassForVideo)videosArrayList.get(mPosition)).getDateModified());
BaseActivity.arrRecentList = BaseActivity.getRecentVideoList(requireActivity(), BaseActivity.PREF_RECENT_VIDEO_LIST);
for (int j = 0; j < BaseActivity.arrRecentList.size(); j++) {
if (((ModelClassForVideo)BaseActivity.arrRecentList.get(j)).getSongPath().equals(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongPath())) {
modelClassForVideo.setTypeVal(((ModelClassForVideo)BaseActivity.arrRecentList.get(j)).getTypeVal());
BaseActivity.arrRecentList.set(j, modelClassForVideo);
BaseActivity.setRecentVideoList(requireActivity(), BaseActivity.PREF_RECENT_VIDEO_LIST, BaseActivity.arrRecentList);
}
}
videosArrayList.set(mPosition, modelClassForVideo);
ModelClassForVideo latestData = ((MainActivity) requireActivity()).getLatestVideo(requireActivity(), BaseActivity.PREF_LATEST_PLAY);
if (latestData != null) {
if (latestData.getSongPath().equals(from.getAbsolutePath())) {
latestData.setBoolean_selected(false);
latestData.setSongPath(to.getAbsolutePath());
latestData.setSongThumb(to.getAbsolutePath());
name = to.getName();
if (name.contains(".")) {
String[] strName = name.split("\\.");
latestData.setSongName(strName[0]);
} else {
latestData.setSongName(name);
}
latestData.setSongAlbum(latestData.getSongAlbum());
latestData.setSongDuration(latestData.getSongDuration());
latestData.setSongSize(latestData.getSongSize());
latestData.setDateAdded(latestData.getDateAdded());
latestData.setDateModified(latestData.getDateModified());
latestData.setCurrDuration(latestData.getCurrDuration());
latestData.setDateModified(latestData.getDateModified());
latestData.setTypeVal(latestData.getTypeVal());
}
BaseActivity.setLatestVideo(requireActivity(), BaseActivity.PREF_LATEST_PLAY, latestData);
}
videoListWOLastPlay.clear();
videoListWOLastPlay.addAll(videosArrayList);
mAdapter.notifyDataSetChanged();
Toast.makeText(requireActivity(), getResources().getString(R.string.rename_success), Toast.LENGTH_SHORT).show();
dRename.dismiss();
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
}
}, 300);
}
private Dialog dDelete;
private void deleteFile() {
String path = ((ModelClassForVideo)videosArrayList.get(mPosition)).getSongPath();
dDelete = new Dialog(requireActivity());
dDelete.setContentView(R.layout.layout_delete);
dDelete.getWindow().setLayout(-1, -2);
Button btnCancel = (Button) dDelete.findViewById(R.id.btnCancel);
Button btnDelete = (Button) dDelete.findViewById(R.id.btnDelete);
TextView tvDeleteMsg = (TextView) dDelete.findViewById(R.id.tvDeleteMsg);
tvDeleteMsg.setText(getString(R.string.delete_msg) + " video file?");
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("TAG", path);
File vidFile = new File(path);
if (!vidFile.exists()) {
Toast.makeText(requireActivity(), getResources().getString(R.string.delete_file_not_exist), Toast.LENGTH_SHORT).show();
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
ArrayList<Uri> list = new ArrayList<>();
list.add(((MainActivity) requireActivity()).getUriFromPath(vidFile.getAbsolutePath(), requireActivity()));
PendingIntent intent = MediaStore.createDeleteRequest(requireActivity().getContentResolver(), list);
try {
startIntentSenderForResult(intent.getIntentSender(), 10000, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
vidFile.delete();
requireActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[]{vidFile.getAbsolutePath()});
requireActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + vidFile)));
deleteRecordAndNotify();
dDelete.dismiss();
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dDelete.dismiss();
}
});
// new MaterialAlertDialogBuilder(requireActivity())//, R.style.AlertDialogTheme
// .setTitle(getResources().getString(R.string.lbl_delete))
// .setMessage(getResources().getString(R.string.msg_delete))
// .setPositiveButton(getResources().getString(R.string.lbl_ok), new DialogInterface.OnClickListener() {//17039379
// public void onClick(DialogInterface dialogInterface, int i) {
// Log.e("TAG", path);
// File vidFile = new File(path);
// if (!vidFile.exists()) {
// Toast.makeText(requireActivity(), getResources().getString(R.string.delete_file_not_exist), Toast.LENGTH_SHORT).show();
// return;
// }
//
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// ArrayList<Uri> list = new ArrayList<>();
// list.add(((MainActivity) requireActivity()).getUriFromPath(vidFile.getAbsolutePath(), requireActivity()));
// PendingIntent intent = MediaStore.createDeleteRequest(requireActivity().getContentResolver(), list);
// try {
// startIntentSenderForResult(intent.getIntentSender(), 10000, null, 0, 0, 0, null);
// } catch (IntentSender.SendIntentException e) {
// e.printStackTrace();
// }
//
// } else {
//
// vidFile.delete();
// requireActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[]{vidFile.getAbsolutePath()});
// requireActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + vidFile)));
//
// deleteRecordAndNotify();
//
// }
// }
// })
// .setNegativeButton(getResources().getString(R.string.lbl_cancel), new DialogInterface.OnClickListener() {//17039369
// public void onClick(DialogInterface dialogInterface, int i) {
// dialogInterface.dismiss();
// }
// });
dDelete.show();
}
public void deleteRecordAndNotify() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
BaseActivity.arrRecentList = BaseActivity.getRecentVideoList(requireActivity(), BaseActivity.PREF_RECENT_VIDEO_LIST);
for (int j = 0; j < BaseActivity.arrRecentList.size(); j++) {
if (((ModelClassForVideo)BaseActivity.arrRecentList.get(j)).getSongPath().equals(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongPath())) {
BaseActivity.arrRecentList.remove(j);
BaseActivity.setRecentVideoList(requireActivity(), BaseActivity.PREF_RECENT_VIDEO_LIST, BaseActivity.arrRecentList);
break;
}
}
ModelClassForVideo latestData = ((MainActivity) requireActivity()).getLatestVideo(requireActivity(), BaseActivity.PREF_LATEST_PLAY);
if (latestData != null) {
if (latestData.getSongPath().equals(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongPath())) {
((MainActivity) requireActivity()).removePrefsByKey(requireActivity(), BaseActivity.PREF_LATEST_PLAY);
}
}
videosArrayList.remove(mPosition);
videoListWOLastPlay.clear();
videoListWOLastPlay.addAll(videosArrayList);
// mAdapter.notifyItemRemoved(mPosition);
mAdapter.notifyDataSetChanged();
Toast.makeText(requireActivity(), getResources().getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
}
}, 300);
}
private void shareFile() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, videosUriList.get(mPosition));
intent.setType("video/*");
startActivity(Intent.createChooser(intent, getResources().getString(R.string.lbl_share_using)));
}
@SuppressLint("SetTextI18n")
private void setDetails() {
try {
final Dialog dialog = new Dialog(requireActivity(), R.style.AlertDialogTheme1);//, R.style.AlertDialogTheme
dialog.setContentView(R.layout.layout_details);
dialog.getWindow().setLayout(-1, -2);
TextView tvNameVal = dialog.findViewById(R.id.tvNameVal);
TextView tvDurationVal = dialog.findViewById(R.id.tvDurationVal);
TextView tvSizeVal = dialog.findViewById(R.id.tvSizeVal);
TextView tvResolutionVal = dialog.findViewById(R.id.tvResolutionVal);
TextView tvFormatVal = dialog.findViewById(R.id.tvFormatVal);
TextView tvDateModified = dialog.findViewById(R.id.tvDateModified);
TextView tvPathVal = dialog.findViewById(R.id.tvPathVal);
Button btnOk = dialog.findViewById(R.id.btnOk);
String songPath = ((ModelClassForVideo)videosArrayList.get(mPosition)).getSongPath();
String format = songPath.substring(songPath.lastIndexOf(".") + 1, songPath.length());
Log.e("TAG--->", songPath);
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(songPath);
int width = Integer.parseInt(Objects.requireNonNull(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)));
int height = Integer.parseInt(Objects.requireNonNull(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)));
retriever.release();
tvResolutionVal.setText(width + " x " + height);
} catch (Exception e) {
e.printStackTrace();
Log.e("TAG - DETAILS", e.getMessage() + "");
tvResolutionVal.setText(0 + " x " + 0);
}
tvNameVal.setText(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongName());
tvDurationVal.setText(BaseActivity.convertDuration(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongDuration()));
tvSizeVal.setText(((BaseActivity) requireActivity()).readableFileSize(((ModelClassForVideo)videosArrayList.get(mPosition)).getSongSize()));
tvDateModified.setText(((BaseActivity) requireActivity()).changeMillisToDate(((ModelClassForVideo)videosArrayList.get(mPosition)).getDateModified(), "yyyy-MM-dd"));
tvPathVal.setText(songPath);
tvFormatVal.setText(format);
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
} catch (Exception e) {
e.printStackTrace();
Log.e("TAG", e.getMessage() + "");
}
}
public void loadInterstitialAds(int position) {
try {
if (com.prolific.vidmediaplayer.Others.AdLoader.getAd().isLoaded()) {
com.prolific.vidmediaplayer.Others.AdLoader.interstitialAd.show();
// new AdLoader.LoadingAds(context).execute();
com.prolific.vidmediaplayer.Others.AdLoader.getAd().setAdListener(new AdListener() {
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
Log.e("TAG", "FAIL AD LOAD : " + loadAdError);
initInterstitialAds();
loadLastPlay(position);
}
@Override
public void onAdClosed() {
super.onAdClosed();
initInterstitialAds();
loadLastPlay(position);
}
});
} else {
initInterstitialAds();
loadLastPlay(position);
}
} catch (Exception e) {
e.printStackTrace();
loadLastPlay(position);
}
}
public void loadLastPlay(int position){
latestVideoData = ((MainActivity) requireActivity()).getLatestVideo(requireActivity(), BaseActivity.PREF_LATEST_PLAY);
if (((ModelClassForVideo)videosArrayList.get(position)).getTypeVal() == 0) {
int pos = 0;
for (int j = 0; j < videoListWOLastPlay.size(); j++) {
if (latestVideoData.getSongPath().equals(((ModelClassForVideo)videoListWOLastPlay.get(j)).getSongPath())) {
pos = j;
break;
}
}
VideoPlayerActivity.mWhereFrom = 1;
((MainActivity) requireActivity()).playVideo(getActivity(), pos, videoListWOLastPlay, latestVideoData, "latestPlay", "", "");
} else {
for (int j = 0; j < videoListWOLastPlay.size(); j++) {
if (((ModelClassForVideo)videosArrayList.get(position)).getSongPath().equals(((ModelClassForVideo)videoListWOLastPlay.get(j)).getSongPath())) {
mPosition = j;
break;
}
}
VideoPlayerActivity.mWhereFrom = 1;
((MainActivity) requireActivity()).playVideo(getActivity(), mPosition, videoListWOLastPlay, ((ModelClassForVideo)videoListWOLastPlay.get(mPosition)), "", "", "");
}
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
int position;
switch (v.getId()) {
case R.id.cvMain:
position = (int) v.getTag();
loadInterstitialAds(position);
break;
case R.id.iv_more:
View moreView = (View) v.getTag(R.string.view);
position = (int) v.getTag(R.string.pos);
PopupMenu popup = new PopupMenu(getContext(), moreView);
popup.inflate(R.menu.menu_item_more);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionPlay:
latestVideoData = ((MainActivity) requireActivity()).getLatestVideo(requireActivity(), BaseActivity.PREF_LATEST_PLAY);
if (((ModelClassForVideo)videosArrayList.get(mPosition)).getTypeVal() == 0) {
for (int j = 0; j < videoListWOLastPlay.size(); j++) {
if (latestVideoData.getSongPath().equals(((ModelClassForVideo)videoListWOLastPlay.get(j)).getSongPath())) {
mPosition = j;
break;
}
}
VideoPlayerActivity.mWhereFrom = 1;
((MainActivity) requireActivity()).playVideo(getActivity(), mPosition, videoListWOLastPlay, latestVideoData, "latestPlay", "", "");
} else {
for (int j = 0; j < videoListWOLastPlay.size(); j++) {
if (((ModelClassForVideo)videosArrayList.get(mPosition)).getSongPath().equals(((ModelClassForVideo)videoListWOLastPlay.get(j)).getSongPath())) {
mPosition = j;
break;
}
}
VideoPlayerActivity.mWhereFrom = 1;
((MainActivity) requireActivity()).playVideo(getActivity(), mPosition, videoListWOLastPlay, (ModelClassForVideo)videoListWOLastPlay.get(mPosition), "", "", "");
}
break;
case R.id.actionRename:
mPosition = position;
renameFile();
break;
case R.id.actionDelete:
mPosition = position;
deleteFile();
break;
case R.id.actionShare:
mPosition = position;
shareFile();
break;
case R.id.actionDetails:
mPosition = position;
setDetails();
break;
default:
break;
}
return true;
}
});
popup.show();
break;
case R.id.actionLastPlay:
Toast.makeText(getActivity(), "Last Play Clicked", Toast.LENGTH_SHORT).show();
break;
}
}
public void onPrepareOptionsMenu(Menu menu) {
int customFontId = R.font.worksans_regular;
for (int i = 0; i < menu.size(); i++) {
MenuItem menuItem = menu.getItem(i);
String menuTitle = menuItem.getTitle().toString();
Typeface typeface = ResourcesCompat.getFont(requireActivity(), customFontId);
SpannableString spannableString = new SpannableString(menuTitle);
// For demonstration purposes only, if you need to support < API 28 just use the CustomTypefaceSpan class only.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
TypefaceSpan typefaceSpan = typeface != null ? new TypefaceSpan(typeface) : new TypefaceSpan("sans-serif");
spannableString.setSpan(typefaceSpan,
0,
menuTitle.length(),
Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
} else {
CustomTypefaceSpan customTypefaceSpan = typeface != null ? new CustomTypefaceSpan(typeface) : new CustomTypefaceSpan(Typeface.defaultFromStyle(Typeface.NORMAL));
spannableString.setSpan(customTypefaceSpan,
0,
menuTitle.length(),
Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
}
menuItem.setTitle(spannableString);
}
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_top_more, menu);//menu_top_more //custom_top_option
menu.findItem(R.id.actionRemoveAll).setVisible(false);
menu.findItem(R.id.actionViewAs).setVisible(false);
menu.findItem(R.id.actionSortBy).getSubMenu().findItem(R.id.actionDuration).setVisible(true);
menu.findItem(R.id.actionSortBy).getSubMenu().findItem(R.id.actionReverseAll).setVisible(false);
if (videoListWOLastPlay != null && videoListWOLastPlay.size() > 0) {
menu.findItem(R.id.actionSelect).setVisible(true);
} else {
menu.findItem(R.id.actionSelect).setVisible(false);
}
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.actionLastPlay:
int pos = 0;
latestVideoData = ((MainActivity) requireActivity()).getLatestVideo(requireActivity(), BaseActivity.PREF_LATEST_PLAY);
if (latestVideoData != null) {
for (int i = 0; i < videoListWOLastPlay.size(); i++) {
if (latestVideoData.getSongPath().equalsIgnoreCase(((ModelClassForVideo)videoListWOLastPlay.get(i)).getSongPath())) {
pos = i;
break;
}
}
VideoPlayerActivity.mWhereFrom = 1;
((MainActivity) requireActivity()).playVideo(getActivity(), pos, videoListWOLastPlay, latestVideoData, "latestPlay", "", "");
} else {
Toast.makeText(requireActivity(), getResources().getString(R.string.last_play_error), Toast.LENGTH_LONG).show();
}
MainActivity.currTab = 0;
break;
case R.id.actionSelect:
MainActivity.currTab = 0;
if (videosArrayList != null && videosArrayList.size() > 0) {
startActivity(new Intent(getActivity(), SelectionActivity.class));
} else {
Toast.makeText(requireActivity(), getResources().getString(R.string.lbl_select_not_found), Toast.LENGTH_SHORT).show();
}
break;
case R.id.actionList:
((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_VIEW_AS, 0);
MainActivity.currTab = 0;
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
case R.id.actionGrid:
((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_VIEW_AS, 1);
MainActivity.currTab = 0;
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
case R.id.actionFullTitle:
((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_VIEW_AS, 2);
MainActivity.currTab = 0;
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
case R.id.actionName:
((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_SORT_BY, 0);
MainActivity.currTab = 0;
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
case R.id.actionSize:
((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_SORT_BY, 1);
MainActivity.currTab = 0;
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
case R.id.actionDuration:
((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_SORT_BY, 2);
MainActivity.currTab = 0;
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
// case R.id.actionDate:
// ((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_SORT_BY, 3);
// MainActivity.currTab = 0;
//// ((BaseActivity) requireActivity()).notifyAllApp();
// EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
// EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
// EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
// break;
case R.id.actionNewToOld:
((BaseActivity) requireActivity()).setIntPrefs(requireActivity(), ((BaseActivity) requireActivity()).PREF_SORT_BY, 3);
MainActivity.currTab = 1;
// ((BaseActivity)requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
case R.id.actionOldToNew:
((BaseActivity) requireActivity()).setIntPrefs(requireActivity(), ((BaseActivity) requireActivity()).PREF_SORT_BY, 4);
MainActivity.currTab = 1;
// ((BaseActivity)requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
break;
case R.id.actionReverseAll:
((MainActivity) requireActivity()).setIntPrefs(requireActivity(), ((MainActivity) requireActivity()).PREF_SORT_BY, 5);
MainActivity.currTab = 0;
if (!isAlreadyReverse) {
// Collections.reverse(videosUriList);
// Collections.reverse(videosArrayList);
// Collections.reverse(videoListWOLastPlay);
// mAdapter.notifyDataSetChanged();
isAlreadyReverse = true;
} else {
isAlreadyReverse = false;
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
}
break;
case R.id.actionRefresh:
MainActivity.currTab = 0;
// ((MainActivity) getActivity()).restartApp();
// ((BaseActivity) requireActivity()).notifyAllApp();
EventBus.getDefault().post(new MessageEvent("RefreshVideo", ""));
EventBus.getDefault().post(new MessageEvent("RefreshFolder", ""));
EventBus.getDefault().post(new MessageEvent("RefreshRecent", ""));
new Handler().postDelayed(new Runnable() {
public void run() {
Toast.makeText(getActivity(), getResources().getString(R.string.msg_refresh), Toast.LENGTH_SHORT).show();
}
}, 100);
break;
case R.id.actionSetting:
startActivity(new Intent(getActivity(), SettingActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
}
|
/**
* Copyright (c) 2012 Vasile Popescu
*
* This file is part of HMC Software.
*
* HMC Software is distributed under NDA so it cannot be distributed
* and/or modified without prior written agreement of the author.
*/
package com.hmc.project.hmc.devices.interfaces;
import com.hmc.project.hmc.devices.implementations.HMCDevicesList;
// TODO: Auto-generated Javadoc
/**
* HMCServer class Models the HMCServer device operations.
*/
public interface HMCServerItf {
/** The Constant HMC_SERVER_INITIAL_COMMAND. */
static final int HMC_SERVER_INITIAL_COMMAND = HMCDeviceItf.HMC_DEVICE_LAST_COMMAND;
/** The Constant CMD_GET_LIST_OF_LOCAL_HMC_DEVICES. */
static final int CMD_GET_LIST_OF_LOCAL_HMC_DEVICES = HMC_SERVER_INITIAL_COMMAND + 1;
/** The Constant CMD_INTERCONNECTION_REQUEST. */
static final int CMD_INTERCONNECTION_REQUEST = HMC_SERVER_INITIAL_COMMAND + 2;
/** The Constant CMD_EXCHANGE_HMC_INFO. */
static final int CMD_EXCHANGE_HMC_INFO = HMC_SERVER_INITIAL_COMMAND + 3;
/** The Constant CMD_EXCHANGE_LISTS_OF_LOCAL_DEVICES. */
static final int CMD_EXCHANGE_LISTS_OF_LOCAL_DEVICES = HMC_SERVER_INITIAL_COMMAND + 4;
/** The Constant HMC_SERVER_LAST_COMMAND. */
static final int HMC_SERVER_LAST_COMMAND = CMD_EXCHANGE_LISTS_OF_LOCAL_DEVICES;
/**
* Get the new devices that were added to HMC while local device was offline.
* The parameter contains the hash of all devices that we have in the list now.
* If the hash is different of the hash that HMCServer has, then HMCServer replies
* with the complete list of devices (containing the new ones or missing the removed ones).
*
* @param hashOfMyListOfDevices the hash of my list of devices
* @return the list of new hmc devices
*/
void getListOfNewHMCDevices(String hashOfMyListOfDevices) ;
/**
* Removes the hmc device.
*/
void removeHMCDevice() ;
}
|
package com.mobei.jwt.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Map;
@Getter
@Setter
@ConfigurationProperties("jwt.config")
@Component
public class JwtUtils {
//签名私钥
private String key;
//签名的失效时间
private Long ttl;
/**
* 设置认证token
* @param id 登录用户id
* @param name 登录用户名
* @param map 其他参数
* @return token
*/
public String createJwt(String id, String name, Map<String, Object> map) {
//1.设置失效时间
long now = System.currentTimeMillis();//当前毫秒
long exp = now + ttl;
//2.创建JwtBuilder
JwtBuilder builder = Jwts.builder()
.setId(id)
.setSubject(name)
.setIssuedAt(new Date())//设置签名时间
.signWith(SignatureAlgorithm.HS256, key);//设置签名,防篡改:签名算法+私钥
//3.根据map设置claims
builder.setClaims(map);
//4.设置失效时间
builder.setExpiration(new Date(exp));
//4.创建token
String token = builder.compact();
System.out.println(token);
return token;
}
/**
* 解析token字符串获取claims
* @param token
* @return
*/
public Claims parseJwt(String token) {
Claims claims = Jwts.parser()
.setSigningKey(token)//解密需要设置签名的私钥
.parseClaimsJws(token)
.getBody();
return claims;
}
}
|
package com.webstore.shoppingcart.dto.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@JsonInclude(value = Include.NON_NULL)
public class ErrorResponseDTO {
private String field;
private String message;
public ErrorResponseDTO(String message) {
this.message = message;
}
}
|
package com.example.kantorapp;
import java.util.ArrayList;
import java.util.List;
public class Users {
private String id;
private String email, passwd;
private Balance accbalance;
private UserTransaction histTrans;
public Users(){
}
public Users(String id, String email, String passwd, Balance accbalance, UserTransaction histTrans) {
this.id = id;
this.email = email;
this.passwd = passwd;
this.accbalance = accbalance;
this.histTrans = histTrans;
}
public String getId() {
return id;
}
public String getEmail() {
return email;
}
public String getPasswd() {
return passwd;
}
public Balance getAccbalance() {
return accbalance;
}
public UserTransaction getHistTrans() {
return histTrans;
}
public void setId(String id) {
this.id = id;
}
public void setEmail(String email) {
this.email = email;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public void setAccbalance(Balance accbalance) {
this.accbalance = accbalance;
}
public void setHistTrans(UserTransaction histTrans) {
this.histTrans = histTrans;
}
}
|
package com.teneriaNoe.controller;
import com.teneriaNoe.ejb.ProveedorFacadeLocal;
import com.teneriaNoe.model.Proveedor;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
/**
*
* @author bfranco
*/
@Named
@ViewScoped
public class ProveedorController implements Serializable {
@EJB
private ProveedorFacadeLocal proveedorEJB;
private Proveedor proveedor;
private List<Proveedor> proveedores;
@PostConstruct
public void init() {
proveedor = new Proveedor();
proveedores=proveedorEJB.findAll();
}
public void registrar() {
try {
proveedorEJB.create(proveedor);
} catch (Exception e) {
e.printStackTrace();
}
}
//Getter y Setters
public Proveedor getProveedor() {
return proveedor;
}
public void setProveedor(Proveedor proveedor) {
this.proveedor = proveedor;
}
public List<Proveedor> getProveedores() {
return proveedores;
}
public void setProveedores(List<Proveedor> proveedores) {
this.proveedores = proveedores;
}
}
|
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by shibayu36 on 2016/12/25.
*/
public class IntQueue1Test {
@Test
public void queue() throws Exception {
IntQueue1 queue = new IntQueue1(3);
queue.enqueue(10);
queue.enqueue(5);
queue.enqueue(3);
assertEquals(10, queue.dequeue());
assertEquals(2, queue.getSize());
assertEquals(5, queue.dequeue());
assertEquals(1, queue.getSize());
queue.enqueue(4);
assertEquals(2, queue.getSize());
assertEquals(3, queue.dequeue());
assertEquals(1, queue.getSize());
assertEquals(4, queue.dequeue());
assertEquals(0, queue.getSize());
}
}
|
package com.alpha.toy.message.service;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alpha.toy.member.mapper.MemberSQLMapper;
import com.alpha.toy.message.mapper.MessageSQLMapper;
import com.alpha.toy.vo.MemberVo;
import com.alpha.toy.vo.MessageVo;
@Service
public class MessageServicelmpl {
@Autowired
private MessageSQLMapper messageSQLMapper;
@Autowired
private MemberSQLMapper memberSQLMapper;
public void writeMessage(MessageVo vo) {
int message_no = messageSQLMapper.createMessagePK();
vo.setMessage_no(message_no);
messageSQLMapper.writeMessage(vo);
};
public ArrayList<HashMap<String, Object>> getmessage(String member_name,String member_receive_name, int page_num) {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
ArrayList<MessageVo> messageList = messageSQLMapper.getmessage(member_name, member_receive_name, page_num);
for (MessageVo messageVo : messageList) {
int memberNo = messageVo.getMember_no();
MemberVo memberVo = memberSQLMapper.getMemberByNo(memberNo);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("memberVo", memberVo);
map.put("messageVo", messageVo);
list.add(map);
}
return list;
}
public ArrayList<HashMap<String, Object>> getsendmessage(String member_name,String member_send_name ,int page_num) {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
ArrayList<MessageVo> messageList = messageSQLMapper.getsendmessage(member_name, member_send_name, page_num);
for (MessageVo messageVo : messageList) {
int memberNo = messageVo.getMember_no();
MemberVo memberVo = memberSQLMapper.getMemberByNo(memberNo);
String member_id = messageVo.getMember_receive_name();
MemberVo messageName = messageSQLMapper.messageName(member_id);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("memberVo", memberVo);
map.put("messageVo", messageVo);
map.put("messageName", messageName);
list.add(map);
}
return list;
}
public int getContentCount(String member_id) {
int count = messageSQLMapper.getContentCount(member_id);
return count;
}
public HashMap<String, Object> getContent(int message_no) {
MessageVo messageVo = messageSQLMapper.getContentByNo(message_no);
// html escape
String content = messageVo.getMessage_content();
content = StringEscapeUtils.escapeHtml4(content);
content = content.replaceAll("\n", "<br>");
messageVo.setMessage_content(content);
int member_no = messageVo.getMember_no();
MemberVo memberVo = memberSQLMapper.getMemberByNo(member_no);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("memberVo", memberVo);
map.put("messageVo", messageVo);
return map;
}
public void increaseReadCount(int message_no) {
messageSQLMapper.increaseReadCount(message_no);
}
public void deleteMessage(int message_no) {
messageSQLMapper.deleteMessage(message_no);
}
public void increasesendMessage(int message_no) {
messageSQLMapper.increasesendMessage(message_no);
}
public void increasereceiveMessage(int message_no) {
messageSQLMapper.increasereceiveMessage(message_no);
}
}
|
package AIEvaluationFunctions;
import myGame.GameState;
//This evaluation function calculate
//the difference between the number of stones at all pits
//for amountStonesInPit = 4 -> [-48,48]
public class StonesDiff implements EvaluationFunction{
@Override
public int eval(GameState state) {
return (int)(
(state.stoneCount(6) - state.stoneCount(13))+ // Diff between the home pits
// Diff between the regular pits
((state.stoneCount(5) + state.stoneCount(4) + state.stoneCount(3) + state.stoneCount(2) + state.stoneCount(1) + state.stoneCount(0))
-(state.stoneCount(12) + state.stoneCount(11) + state.stoneCount(10) + state.stoneCount(9) + state.stoneCount(8) + state.stoneCount(7))
));
}
}
|
package ca.usask.cs.srlab.simclipse.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import ca.usask.cs.srlab.simclipse.SimClipseConstants;
public class PropertyUtil {
public static void addOrUpdateSimclipseProperties(IProject project, Object key, Object value) {
Map<Object, Object> properties = new HashMap<Object, Object>();
properties.put(key, value);
addOrUpdateSimClipseProperties(project, properties);
}
public static void addOrUpdateSimClipseProperties(IProject project, Map<Object, Object> propsMap) {
IPath simclipseDataFolder = project.getLocation().append(SimClipseConstants.SIMCLIPSE_DATA_FOLDER);
if(!simclipseDataFolder.toFile().exists())
simclipseDataFolder.toFile().mkdir();
Properties properties = new Properties();
try {
if (simclipseDataFolder.append(SimClipseConstants.SIMCLIPSE_SETTINGS_FILE).toFile().exists())
properties.load(new FileInputStream(simclipseDataFolder.append(SimClipseConstants.SIMCLIPSE_SETTINGS_FILE).toFile()));
properties.putAll(propsMap);
properties.store(new FileOutputStream(simclipseDataFolder.append(SimClipseConstants.SIMCLIPSE_SETTINGS_FILE)
.toFile()), "project specific settings for simclipse");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getSimClipsePropertyValue(IProject project, Object key) {
IPath simclipseDataFolder = project.getLocation().append(SimClipseConstants.SIMCLIPSE_DATA_FOLDER);
Properties properties = new Properties();
try {
if (simclipseDataFolder
.append(SimClipseConstants.SIMCLIPSE_SETTINGS_FILE)
.toFile().exists())
properties.load(new FileInputStream(simclipseDataFolder.append(
SimClipseConstants.SIMCLIPSE_SETTINGS_FILE).toFile()));
return properties.get(key)!=null? properties.get(key).toString():null;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
package memberInfo.dao;
import java.util.List;
import memberInfo.vo.memberInfoVO;
public interface ImemberInfodao {
// 검색 버튼을 누르면 정보가 다 나오는거
public List <memberInfoVO> getAllmember();
// 회원 수정
public int updateMember (memberInfoVO memVO);
// 블랙리스트
public int insertMember(memberInfoVO memVO);
// 삭제
public int deleteMember(String memId);
// 테이블에 정보 쀼려주는거
public List <memberInfoVO> tableview(String mem_id);
}
|
package com.example.controller.admin;
import com.example.dto.BrandDTO;
import com.example.service.IBrandService;
import com.example.utils.FileUtil;
import com.example.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Base64;
@Controller
@RequestMapping("/admin/brand")
public class BrandController {
@Autowired
private IBrandService brandService;
@Autowired
private FileUtil fileUtil;
@GetMapping
public String brandPage(Model model) {
String data = JsonUtil.listToJson(brandService.findAll());
model.addAttribute("brands", data);
return "admin/brand/brand";
}
@GetMapping("/add")
public String addPage(Model model, @RequestParam(name = "id", required = false) Long id) {
if (id != null) model.addAttribute("brand", brandService.findOneById(id));
else model.addAttribute("brand", new BrandDTO());
return "/admin/brand/add";
}
@PostMapping("/add")
public String postBrand(Model model, BrandDTO brandDTO, HttpServletRequest request) {
if (brandDTO.getBase64() != null && !brandDTO.getBase64().equals("")) {
byte[] bytes = Base64.getDecoder().decode(brandDTO.getBase64().split(",")[1]);
try {
brandDTO.setImage(fileUtil.uploadFile(bytes, brandDTO.getFileName()));
} catch (IOException e) {
e.printStackTrace();
}
}
BrandDTO dto = brandService.save(brandDTO);
if (dto == null) {
return "redirect:/admin/brand/add?errorSystem";
}
return "redirect:/admin/brand?success";
}
@GetMapping("/delete")
public String deleteBrands(long[] ids) {
brandService.delete(ids);
return "redirect:/admin/brand";
}
}
|
package game.core;
import java.util.concurrent.TimeUnit;
/**
* Registro de tiempo del juego.
*/
public class GameTracker {
/**
* Tiempo (en nanosegundos) de inicio del juego.
*/
private long startTime;
/**
* Tiempo estándar (en segundos) que transcurre entre cada actualización del juego.
*/
private float seconds;
/**
* Tiempo transcurrido (en nanosegundos) de la última llamada a {@link GameTracker#tick()}.
*/
private long lastTime;
/**
* Tiempo actual (en nanosegundos).
*/
private long currentTime;
/**
* Registro de la actualización del juego.
*
* @see TimeTracker.
*/
private TimeTracker updateTracker;
/**
* Registro del dibujo del juego.
*
* @see TimeTracker.
*/
private TimeTracker drawTracker;
public GameTracker() {
updateTracker = new TimeTracker("Updates-per-second: %.1f", 1000, TimeUnit.MILLISECONDS);
drawTracker = new TimeTracker("Draws-per-second: %.1f", 1000, TimeUnit.MILLISECONDS);
}
/**
* Establece el tiempo estándar que transcurre entre cada actualización del juego.
*
* @param nanosElapsed Nanosegundos estándar que transcurren entre cada actualización del juego.
*/
public void setElapsed(long nanosElapsed) {
seconds = (float) (nanosElapsed * 0.000000001);
}
/**
* Resetea el registro de tiempo.
*
* @return Tiempo actual (en nanosegundos).
*/
public long reset() {
long resetTime = System.nanoTime();
startTime = resetTime;
lastTime = resetTime;
currentTime = resetTime;
updateTracker.reset();
drawTracker.reset();
return (resetTime);
}
/**
* Obtiene el tiempo estándar (en segundos) que transcurre entre cada actualización del juego.
*
* @return
*/
public float getSeconds() {
return (seconds);
}
/**
* Actualiza el registro de tiempo.
*
* @return El tiempo transcurrido (en nanosegundos) desde la última llamada a esta operación.
*/
public long tick() {
lastTime = currentTime;
currentTime = System.nanoTime();
return (currentTime - lastTime);
}
/**
* Actualiza el registro de la actualización del juego.
*/
public void tickUpdate() {
updateTracker.tick();
}
/**
* Actualiza el registro del dibujo del juego.
*/
public void tickDraw() {
drawTracker.tick();
}
/**
* Obtiene el tiempo transcurrido (en nanosegundos) desde la última llamada a {@link GameTracker#tick()}.
*
* @return Tiempo transcurrido (en nanosegundos) desde la última llamada a {@link GameTracker#tick()}.
*/
public long getElapsedSinceTick() {
return (System.nanoTime() - currentTime);
}
}
|
package com.mobile.mobilehardware.applist;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* @author gunaonian
* @date 2018/5/10
*/
class ListAppInfo {
private static final String TAG = ListAppInfo.class.getSimpleName();
static List<JSONObject> getMobListApp(Context context) {
List<JSONObject> appLists = new ArrayList<>();
try {
PackageManager packageManager = context.getPackageManager();
List<PackageInfo> packageInfoList = packageManager.getInstalledPackages(0);
for (PackageInfo packageInfo : packageInfoList) {
ListAppBean listAppBean = new ListAppBean();
listAppBean.setPackageName(packageInfo.packageName);
listAppBean.setVersionName(packageInfo.versionName);
listAppBean.setVersionCode(packageInfo.versionCode + "");
if ((ApplicationInfo.FLAG_SYSTEM & packageInfo.applicationInfo.flags) == 0) {
listAppBean.setIsSystem("false");
} else {
listAppBean.setIsSystem("true");
}
appLists.add(listAppBean.toJSONObject());
}
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return appLists;
}
}
|
package EEV_v1;
public class Act {
int attackOrder;
double EEV;
public Act(int attackOrder) {
this.attackOrder = attackOrder;
}
public Act deepCopy() {
Act actCopy = new Act(attackOrder);
return actCopy;
}
}
|
package algorithms.kd;
import lombok.Getter;
/**
* @author lichen
* @date 2022-5-12 18:42
*/
public class Point {
@Getter
private final double[] coordinates;
private final String string;
private static final String SEP = ",";
public boolean equalsWithKey(Point p) {
return equalsWithKey(p.coordinates);
}
public boolean equalsWithKey(double[] keyVectorParam) {
if (keyVectorParam == null || keyVectorParam.length != coordinates.length) {
return false;
}
for (int i = 0; i < keyVectorParam.length; i++) {
if (keyVectorParam[i] != coordinates[i]) {
return false;
}
}
return true;
}
public Point(double[] coordinates) {
this.coordinates = coordinates;
StringBuilder sb = new StringBuilder();
for (double value : coordinates) {
sb.append(value).append(",");
}
String localString = sb.toString();
string = localString.substring(0, localString.length() - SEP.length());
}
public double getInDimension(int k) {
return coordinates[k];
}
public int getDimensions() {
return coordinates.length;
}
@Override
public String toString() {
return string;
}
}
|
package com.wxt.designpattern.factorymethod.test04;
/**
* @Auther: weixiaotao
* @ClassName Product
* @Date: 2018/10/22 15:23
* @Description:
*/
public interface Product {
void setProduct1(Product1 product1);
void setProduct2(Product2 product2);
}
|
package org.dbdoclet.tidbit.application;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JMenu;
import org.dbdoclet.jive.text.IConsole;
import org.dbdoclet.tidbit.common.Context;
import org.dbdoclet.tidbit.importer.ImportService;
import org.dbdoclet.tidbit.medium.Generator;
import org.dbdoclet.tidbit.medium.MediumService;
import org.dbdoclet.tidbit.perspective.Perspective;
import org.dbdoclet.tidbit.project.Project;
import org.dbdoclet.trafo.TrafoService;
public interface Application {
public void addGenerator(Generator generator);
public void addMenu(String string, JMenu menu);
public void addRecent(File file);
public void addToolBarButton(String id, AbstractAction action);
public Context getContext();
public List<ImportService> getImportServiceList();
public MediumService getMediumService(String string);
public TrafoService getTrafoService(String string);
public List<MediumService> getMediumServiceList();
public List<MediumService> getMediumServiceList(String category);
public Perspective getPerspective();
public List<Perspective> getPerspectiveList();
public Project getProject();
public void lock();
public AbstractAction newGenerateAction(IConsole console,
MediumService service, Perspective perspective) throws IOException;
public void refresh();
public void removeGenerator(Generator generator);
public void removeMenu(String string);
public void removeToolBarButton(String string);
public void reset();
public void setDefaultCursor();
public void setFrameTitle(String title);
public void setProject(Project project);
public void setWaitCursor();
public void shutdown();
public void unlock();
}
|
package org.kuali.ole.describe.controller;
import org.apache.log4j.Logger;
import org.kuali.ole.OLEConstants;
import org.kuali.ole.describe.form.CallNumberBrowseForm;
import org.kuali.ole.describe.service.CallNumberBrowseService;
import org.kuali.ole.describe.service.impl.CallNumberBrowseServiceImpl;
import org.kuali.ole.docstore.model.bo.WorkBibDocument;
import org.kuali.ole.describe.bo.OleLocation;
import org.kuali.rice.kim.api.permission.PermissionService;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.KRADServiceLocator;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.KRADConstants;
import org.kuali.rice.krad.web.controller.UifControllerBase;
import org.kuali.rice.krad.web.form.UifFormBase;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Controller
@RequestMapping(value = "/callnumberBrowseController")
public class CallNumberBrowseController extends UifControllerBase {
private static final Logger LOG = Logger.getLogger(CallNumberBrowseController.class);
private CallNumberBrowseService callNumberBrowseService;
public CallNumberBrowseService getCallNumberBrowseService() {
if (callNumberBrowseService == null)
callNumberBrowseService = new CallNumberBrowseServiceImpl();
return callNumberBrowseService;
}
@Override
protected UifFormBase createInitialForm(HttpServletRequest request) {
return new CallNumberBrowseForm();
}
private boolean performCallNumberBrowse(String principalId) {
PermissionService service = KimApiServiceLocator.getPermissionService();
return service.hasPermission(principalId, OLEConstants.CAT_NAMESPACE, OLEConstants.CALL_NUMBER_BROWSE);
}
@Override
@RequestMapping(params = "methodToCall=start")
public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Inside the start method");
CallNumberBrowseForm callNumberBrowseForm = (CallNumberBrowseForm) form;
boolean hasPermission = performCallNumberBrowse(GlobalVariables.getUserSession().getPrincipalId());
if (!hasPermission) {
GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_AUTHORIZATION);
return getUIFModelAndView(callNumberBrowseForm);
}
return super.start(callNumberBrowseForm, result, request, response);
}
@RequestMapping(params = "methodToCall=rowsBrowse")
public ModelAndView rowsBrowse(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Inside the browse method");
CallNumberBrowseForm callNumberBrowseForm = (CallNumberBrowseForm) form;
List<WorkBibDocument> workBibDocumentList = getCallNumberBrowseService().callNumberBrowse(callNumberBrowseForm);
callNumberBrowseForm.setWorkBibDocumentList(workBibDocumentList);
setPageNextPrevoiusAndEntriesIno(callNumberBrowseForm);
return getUIFModelAndView(callNumberBrowseForm, "CallNumberBrowseViewPage");
}
@RequestMapping(params = "methodToCall=browse")
public ModelAndView browse(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Inside the browse method");
String title = "";
CallNumberBrowseForm callNumberBrowseForm = (CallNumberBrowseForm) form;
boolean hasPermission = performCallNumberBrowse(GlobalVariables.getUserSession().getPrincipalId());
if (!hasPermission) {
GlobalVariables.getMessageMap().putInfo(KRADConstants.GLOBAL_INFO, OLEConstants.ERROR_AUTHORIZATION);
return getUIFModelAndView(callNumberBrowseForm);
}
//validate location at library level for call number browse results
String location = validateLocation(callNumberBrowseForm.getLocation());
callNumberBrowseForm.setLocation(location);
callNumberBrowseForm.setPageSize(10);
List<WorkBibDocument> workBibDocumentList = getCallNumberBrowseService().callNumberBrowse(callNumberBrowseForm);
//Validate title for left angle bracket display in results
for (WorkBibDocument workBibDocument : workBibDocumentList) {
List<String> values = new ArrayList<String>();
title = org.apache.commons.lang.StringEscapeUtils.escapeHtml(workBibDocument.getTitle());
values.add(title);
workBibDocument.setTitles(values);
}
callNumberBrowseForm.setWorkBibDocumentList(workBibDocumentList);
setPageNextPrevoiusAndEntriesIno(callNumberBrowseForm);
return getUIFModelAndView(callNumberBrowseForm, "CallNumberBrowseViewPage");
}
@RequestMapping(params = "methodToCall=previous")
public ModelAndView previous(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Inside the browse method");
CallNumberBrowseForm callNumberBrowseForm = (CallNumberBrowseForm) form;
List<WorkBibDocument> workBibDocumentList = getCallNumberBrowseService().callNumberBrowsePrev(callNumberBrowseForm);
callNumberBrowseForm.setWorkBibDocumentList(workBibDocumentList);
setPageNextPrevoiusAndEntriesIno(callNumberBrowseForm);
return getUIFModelAndView(callNumberBrowseForm, "CallNumberBrowseViewPage");
}
@RequestMapping(params = "methodToCall=next")
public ModelAndView next(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws Exception {
LOG.debug("Inside the browse method");
CallNumberBrowseForm callNumberBrowseForm = (CallNumberBrowseForm) form;
List<WorkBibDocument> workBibDocumentList = getCallNumberBrowseService().callNumberBrowseNext(callNumberBrowseForm);
callNumberBrowseForm.setWorkBibDocumentList(workBibDocumentList);
setPageNextPrevoiusAndEntriesIno(callNumberBrowseForm);
return getUIFModelAndView(callNumberBrowseForm, "CallNumberBrowseViewPage");
}
@RequestMapping(params = "methodToCall=clear")
public ModelAndView clear(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Inside the clear method");
CallNumberBrowseForm callNumberBrowseForm = (CallNumberBrowseForm) form;
callNumberBrowseForm.setMessage("");
callNumberBrowseForm.setInformation("");
callNumberBrowseForm.setWorkBibDocumentList(null);
callNumberBrowseForm.setPageSize(10);
callNumberBrowseForm.setPreviousFlag(false);
callNumberBrowseForm.setNextFlag(false);
callNumberBrowseForm.setCallNumberBrowseText("");
callNumberBrowseForm.setCloseBtnShowFlag(false);
return super.start(callNumberBrowseForm, result, request, response);
}
@RequestMapping(params = "methodToCall=close")
public ModelAndView close(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
LOG.debug("Inside the clear method");
return super.close(form, result, request, response);
}
public void setPageNextPrevoiusAndEntriesIno(CallNumberBrowseForm callNumberBrowseForm) {
callNumberBrowseForm.setPreviousFlag(callNumberBrowseService.getPreviosFlag());
callNumberBrowseForm.setNextFlag(callNumberBrowseService.getNextFlag());
callNumberBrowseForm.setPageShowEntries(callNumberBrowseService.getPageShowEntries());
}
public String validateLocation(String locationString) {
if (locationString != null) {
String[] arr = locationString.split("/");
for (String location : arr) {
if (isValidLibraryLevel(location)) {
return location;
}
}
}
return null;
}
public boolean isValidLibraryLevel(String location) {
boolean valid = false;
BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
Collection<OleLocation> oleLocationCollection = businessObjectService.findAll(OleLocation.class);
for (OleLocation oleLocation : oleLocationCollection) {
String locationCode = oleLocation.getLocationCode();
String levelCode = oleLocation.getOleLocationLevel().getLevelCode();
if ("LIBRARY".equals(levelCode) && (locationCode.equals(location))) {
valid = true;
return valid;
}
}
return valid;
}
}
|
package com.itheima.controller;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService service;
@RequestMapping("/login")
public String login(String username, String password, HttpSession session) {
User loginUser = service.login(username, password);
if (loginUser != null) { //如果查询结果不为空,说明登陆成功
//将用户信息存入session中
session.setAttribute("login_user", loginUser);
//跳转到查询所有信息
return "redirect:/user/findAll";
} else {
return "message";
}
}
@RequestMapping("/findAll")
public ModelAndView findAll() {
List<User> list = service.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("list", list);
mv.setViewName("user_list");
return mv;
}
}
|
package com.fest.pecfestBackend.controller;
import com.fest.pecfestBackend.request.TeamRegRequest;
import com.fest.pecfestBackend.response.WrapperResponse;
import com.fest.pecfestBackend.service.EventRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/pecfest-registration")
public class EventRegistrationController {
@Autowired
private EventRegistrationService eventRegService;
@PostMapping("/{event_id}/{team_name}")
public WrapperResponse registerTeamForAnEvent(@PathVariable("event_id") Long eventId, @RequestBody TeamRegRequest teamRegRequest, @RequestHeader("session_id") String sessionId,
@PathVariable(value = "team_name") String teamName){
return eventRegService.registerTeamForAnEvent(eventId,teamRegRequest,teamName,sessionId);
}
@PostMapping("/{event_id}")
public WrapperResponse registerIndividualForAnEvent(@PathVariable("event_id") Long eventId, @RequestHeader("session_id") String sessionId,@RequestBody TeamRegRequest teamRegRequest){
return eventRegService.registerAnIndividual(eventId,sessionId,teamRegRequest);
}
}
|
package com.t11e.discovery.datatool;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import org.dom4j.Document;
import org.junit.Test;
public class NullValuesTest
extends EndToEndTestBase
{
@Test
public void nulls()
{
final Document doc = assertChangeset("null_values", "", "snapshot",
Arrays.asList("1", "2", "3"),
Collections.<String> emptyList(),
false);
final String asXml = doc.asXML();
assertXpath("joseph", doc,
"/changeset/set-item[@id='1']/properties/struct/entry[@name='name']/string/text()");
assertXpath("21", doc,
"/changeset/set-item[@id='1']/properties/struct/entry[@name='age']/int/text()");
assertEquals(asXml, 1,
doc.selectNodes("/changeset/set-item[@id='1']/properties/struct/entry[@name='price']").size());
assertEquals(asXml, 0,
doc.selectNodes("/changeset/set-item[@id='3']/properties/struct/entry[@name='name']").size());
}
@Test
public void provdierNulls()
{
final Document doc = assertChangeset("null_values_provider", "", "snapshot", false);
final String asXml = doc.asXML();
assertEquals(asXml, 3, doc.selectNodes("/changeset/set-item").size());
assertEquals(asXml, 0, doc.selectNodes("/changeset/set-item[@id]").size());
assertEquals(asXml, 3, doc.selectNodes("/changeset/set-item[@locator and @provider and @kind]").size());
assertXpath("joseph", doc,
"/changeset/set-item[@locator='1']/properties/struct/entry[@name='name']/string/text()");
assertXpath("21", doc,
"/changeset/set-item[@locator='1']/properties/struct/entry[@name='age']/int/text()");
assertXpath(Collections.<String> emptyList(), doc,
"/changeset/set-item[@locator='1']/properties/struct/entry[@name='price']/text()");
assertEquals(asXml, 1,
doc.selectNodes("/changeset/set-item[@locator='1']/properties/struct/entry[@name='price']").size());
assertEquals(asXml, 0,
doc.selectNodes("/changeset/set-item[@locator='3']/properties/struct/entry[@name='name']").size());
}
}
|
package com.csalazar.formularioventas.modelo;
/**
* Created by csalazar on 2/10/2017.
*/
public class Imagen {
private int imagen;
public Imagen() {
}
public Imagen(int imagen) {
this.imagen = imagen;
}
public int getImagen() {
return imagen;
}
public void setImagen(int imagen) {
this.imagen = imagen;
}
}
|
/**
* Nathan West
* CSMC 256
* Project #1 - DigitalMediaTester
* Description: This class tests the set methods of the DigitalMedia class,
* validating the values that are passed to the setter methods
* Purpose: To test DigitalMedia object getter and setter methods
*/
// import static org.junit.Assert.*;
import java.awt.List;
import java.io.File;
import java.io.FileNotFoundException;
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class DigitalMediaTester {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
printHeading();
/*
* testing creation of constructor
*/
DigitalMedia tester = null;
try {
tester = new DigitalMedia("image.jpg", 9438976);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(tester); // printing newly created object, testing
// toString method
System.out.println("~~~~~~~~~~~~~~~~~~~");
/*
* testing setName of the tester DigitalMedia object
*/
try {
tester.setName(null); // testing null
} catch (NullPointerException e) {
System.out.println("setName(null): " + e);
}
try {
tester.setName(""); // testing empty string
} catch (NullPointerException e) {
System.out.println("setName(''): " + e);
}
try {
tester.setName("this.shouldfail.jpg"); // testing string with two
// dots
} catch (IllegalArgumentException e) {
System.out.println("setName(this.shouldfail.jpg): " + e);
}
try {
tester.setName("thiswillalsofailjpg"); // testing string with no
// dots
} catch (IllegalArgumentException e) {
System.out.println("setName(badfilejpg): " + e);
}
tester.setName("image.jpg"); // working string
System.out.print("setName(image.jpg) – Expected: image.jpg; Actual: ");
System.out.println(tester.getName());
System.out.println("~~~~~~~~~~~~~~~~~~~");
/*
* testing setSize of the tester DigitalMedia object
*/
try {
tester.setSize(-432354); // testing negative size value
} catch (IllegalArgumentException e) {
System.out.println("setSize(-432354): " + e);
}
tester.setSize(68372); // working size value
System.out.println("setSize(68372) - Expected: 68372 Actual; " + tester.getSize());
/*
* testing setDateModified of the tester DigitalMedia object
*/
System.out.println("~~~~~~~~~~~~~~~~~~~");
System.out.println("dateCreated: " + tester.getDateCreated().now()); // printed
// for
// viewing
// purposes
LocalDateTime newDate = LocalDateTime.of(2016, 12, 24, 8, 35);
try {
tester.setDateModified(newDate); // testing newDate with old year
} catch (NullPointerException e) {
System.out.println("setDateModifed(newDate): " + e);
}
newDate = LocalDateTime.of(2018, 2, 25, 11, 12, 57); // testing newDate
// with year
// after
// dateCreated
tester.setDateModified(newDate);
System.out.println("setDateModified(newDate): " + tester.getDateModified());
System.out.println("~~~~~~~~~~~~~~~~~~~");
/*
* testing the boolean equals method
*/
DigitalMedia tester2 = new DigitalMedia("image.jpg", 68372);
DigitalMedia tester3 = new DigitalMedia("picture.jpg", 342);
// testing for symmetry
boolean symmetric = tester.equals(tester2) && tester2.equals(tester);
System.out.println("Symmetric: " + symmetric);
// testing for transitive
boolean transitive = tester.equals(tester2) && tester2.equals(tester3) && tester.equals(tester3);
System.out.println("Transitive: " + transitive);
// testing for consistency
boolean consistency = tester.equals(tester2) && tester.equals(tester2);
System.out.println("Consistency: " + consistency);
System.out.println("~~~~~~~~~~~~~~~~~~~");
// // testing an algorithm theory
// DigitalMedia media = new DigitalMedia(null, 0);
// Song song = new Song(null, 0, null, null);
// Image image = new Image(null, 0, 0, 0);
//
// System.out.println("Enter the file name: ");
// Scanner input = new Scanner(System.in);
// String fileName = input.nextLine();
// File file = new File(fileName);
// ArrayList<DigitalMedia> collection = new ArrayList<DigitalMedia>();
//
// Scanner fileReader = null;
// fileReader = new Scanner(file);
// while (fileReader.hasNextLine()) {
// String line = fileReader.nextLine();
// if (line.charAt(0) == 'S') {
// String[] properties = line.split(":");
// String[] trimmed = new String[properties.length];
// for (int i = 0; i < properties.length; i++) {
// trimmed[i] = properties[i].trim();
// }
// song.setTitle(trimmed[1]);
// song.setArtist(trimmed[2]);
// song.setAlbum(trimmed[3]);
// String number = trimmed[4];
// number = number.replaceAll(",", "");
// long size = Long.parseLong(number);
// song.setSize(size);
// collection.add(song);
// song = new Song(null, 0, null, null);
// }
// if (line.charAt(0) == 'I') {
// String[] properties = line.split(":");
// String[] trimmed = new String[properties.length];
// for (int i = 0; i < properties.length; i++) {
// trimmed[i] = properties[i].trim();
// }
// image.setName(trimmed[1]);
// image.setWidth(Integer.parseInt(trimmed[2]));
// image.setHeight(Integer.parseInt(trimmed[3]));
// String number = trimmed[4];
// number = number.replaceAll(",", "");
// long size = Long.parseLong(number);
// song.setSize(size);
// collection.add(image);
// image = new Image(null, 0, 0, 0);
// }
// }
//
// // System.out.println(collection);
}
// print heading
public static void printHeading() {
System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" | Nathan West |");
System.out.println(" | @ CMSC 256 @ |");
System.out.println(" | Project #2 |");
System.out.println(" | Media List Application |");
System.out.println(" ~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
|
package com.esum.wp.ims.clusterinfo.base;
import com.esum.appframework.dmo.BaseDMO;
public class BaseClusterInfo extends BaseDMO {
public static String REF = "ClusterInfo";
public static String PROP_NODE_ID = "nodeId";
public static String PROP_USE_CLUSTER = "useCluster";
public static String PROP_CHECK_INTERVAL = "checkInterval";
public static String PROP_TARGET_NODE_ID = "targetNodeId";
public static String PROP_MOVE_CHANNEL_DATA_FLAG = "moveChannelDataFlag";
public static String PROP_HANG_CHECK_FLAG = "hangCheckFlag";
public static String PROP_HANG_CHECK_INTERVAL = "hangCheckInterval";
public static String PROP_HANG_ACTION = "hangAction";
public static String PROP_MEMORY_CHECK_FLAG = "memoryCheckFlag";
public static String PROP_MEMORY_CHECK_INTERVAL = "memoryCheckInterval";
public static String PROP_MEMORY_ACTION_LEVEL = "memoryActionLevel";
public static String PROP_MEMORY_ACTION = "memoryAction";
public static String PROP_LISTENER_CHECK_FLAG = "listenerCheckFlag";
public static String PROP_LISTENER_CHECK_INTERVAL = "listenerCheckInterval";
public static String PROP_LISTENER_ACTION = "listenerAction";
public static String PROP_REG_DATE = "regDate";
public static String PROP_MOD_DATE = "modDate";
public static String PROP_TARGET_QUEUE_CONFIG_PATH = "targetQueueConfigPath";
// constructors
public BaseClusterInfo() {
initialize();
}
/**
* Constructor for primary key
*/
public BaseClusterInfo(java.lang.String nodeId) {
this.setNodeId(nodeId);
initialize();
}
/**
* Constructor for required fields
*/
public BaseClusterInfo(java.lang.String nodeId,
java.lang.String useCluster,
java.lang.String regDate,
java.lang.String modDate) {
this.setNodeId(nodeId);
this.setUseCluster(useCluster);
this.setRegDate(regDate);
this.setModDate(modDate);
initialize();
}
protected void initialize() {
nodeId = "";
useCluster = "";
checkInterval = 0;
targetNodeId = "";
moveChannelDataFlag = "";
hangCheckFlag = "";
hangCheckInterval = 0;
hangAction = "";
memoryCheckFlag = "";
memoryCheckInterval = 0;
memoryActionLevel = 0;
memoryAction = "";
listenerCheckFlag = "";
listenerCheckInterval = 0;
listenerAction = "";
regDate = "";
modDate = "";
targetQueueConfigPath = "";
}
// primary key
protected java.lang.String nodeId;
// fields
protected java.lang.String useCluster;
protected java.lang.Integer checkInterval;
protected java.lang.String targetNodeId;
protected java.lang.String moveChannelDataFlag;
protected java.lang.String hangCheckFlag;
protected java.lang.Integer hangCheckInterval;
protected java.lang.String hangAction;
protected java.lang.String memoryCheckFlag;
protected java.lang.Integer memoryCheckInterval;
protected java.lang.Integer memoryActionLevel;
protected java.lang.String memoryAction;
protected java.lang.String listenerCheckFlag;
protected java.lang.Integer listenerCheckInterval;
protected java.lang.String listenerAction;
protected java.lang.String regDate;
protected java.lang.String modDate;
protected java.lang.String targetQueueConfigPath;
public java.lang.String getNodeId() {
return nodeId;
}
public void setNodeId(java.lang.String nodeId) {
this.nodeId = nodeId;
}
public java.lang.String getUseCluster() {
return useCluster;
}
public void setUseCluster(java.lang.String useCluster) {
this.useCluster = useCluster;
}
public java.lang.Integer getCheckInterval() {
return checkInterval;
}
public void setCheckInterval(java.lang.Integer checkInterval) {
this.checkInterval = checkInterval;
}
public java.lang.String getTargetNodeId() {
return targetNodeId;
}
public void setTargetNodeId(java.lang.String targetNodeId) {
this.targetNodeId = targetNodeId;
}
public java.lang.String getMoveChannelDataFlag() {
return moveChannelDataFlag;
}
public void setMoveChannelDataFlag(java.lang.String moveChannelDataFlag) {
this.moveChannelDataFlag = moveChannelDataFlag;
}
public java.lang.String getHangCheckFlag() {
return hangCheckFlag;
}
public void setHangCheckFlag(java.lang.String hangCheckFlag) {
this.hangCheckFlag = hangCheckFlag;
}
public java.lang.Integer getHangCheckInterval() {
return hangCheckInterval;
}
public void setHangCheckInterval(java.lang.Integer hangCheckInterval) {
this.hangCheckInterval = hangCheckInterval;
}
public java.lang.String getHangAction() {
return hangAction;
}
public void setHangAction(java.lang.String hangAction) {
this.hangAction = hangAction;
}
public java.lang.String getMemoryCheckFlag() {
return memoryCheckFlag;
}
public void setMemoryCheckFlag(java.lang.String memoryCheckFlag) {
this.memoryCheckFlag = memoryCheckFlag;
}
public java.lang.Integer getMemoryCheckInterval() {
return memoryCheckInterval;
}
public void setMemoryCheckInterval(java.lang.Integer memoryCheckInterval) {
this.memoryCheckInterval = memoryCheckInterval;
}
public java.lang.Integer getMemoryActionLevel() {
return memoryActionLevel;
}
public void setMemoryActionLevel(java.lang.Integer memoryActionLevel) {
this.memoryActionLevel = memoryActionLevel;
}
public java.lang.String getMemoryAction() {
return memoryAction;
}
public void setMemoryAction(java.lang.String memoryAction) {
this.memoryAction = memoryAction;
}
public java.lang.String getListenerCheckFlag() {
return listenerCheckFlag;
}
public void setListenerCheckFlag(java.lang.String listenerCheckFlag) {
this.listenerCheckFlag = listenerCheckFlag;
}
public java.lang.Integer getListenerCheckInterval() {
return listenerCheckInterval;
}
public void setListenerCheckInterval(java.lang.Integer listenerCheckInterval) {
this.listenerCheckInterval = listenerCheckInterval;
}
public java.lang.String getListenerAction() {
return listenerAction;
}
public void setListenerAction(java.lang.String listenerAction) {
this.listenerAction = listenerAction;
}
public java.lang.String getRegDate() {
return regDate;
}
public void setRegDate(java.lang.String regDate) {
this.regDate = regDate;
}
public java.lang.String getModDate() {
return modDate;
}
public void setModDate(java.lang.String modDate) {
this.modDate = modDate;
}
public java.lang.String getTargetQueueConfigPath() {
return targetQueueConfigPath;
}
public void setTargetQueueConfigPath(java.lang.String targetQueueConfigPath) {
this.targetQueueConfigPath = targetQueueConfigPath;
}
}
|
package com.example.sentinel.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ClassName: CommonResult
* @Description: 统一返回
* @Author: yongchen
* @Date: 2021/4/2 14:41
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommonResult<T> {
private T data;
private String msg;
private int code;
}
|
/**
* @author Brennan Ward
*
* Translates messages into braille.
* Only handles [A-Z] + [a-z]
*/
public class Braille {
static String[] braille = { "100000", "110000", "100100", "100110", "100010", "110100", "110110", "110010", "010100", "010110", "101000", "111000", "101100", "101110", "101010", "111100", "111110", "111010", "011100", "011110", "101001", "111001", "010111", "101101", "101111", "101011" };
public static String solution(String s) {
String out = "";
for (char c : s.toCharArray()) {
if (c == ' ') {
out += "000000";
continue;
}
if (Character.isUpperCase(c)) {
out += "000001";
c = Character.toLowerCase(c);
}
out += braille[c - 97];
}
return out;
}
}
|
import java.io.*;
import java.util.*;
class Graph {
private static int source;
private static int dest;
private static int V; //No of vertices
private static int sum0fDemands = 0;
private static int sumOfSupplies = 0;
private static boolean doDemandsMatchSupplies = true;
List<Edge> adjacency[]; // List of lists - Adjacency List
List<Integer> demand; // to store demand vertices
List<Integer> supply; // to store supply vertices
public static int getSource(){
return source;
}
public static void setSource(int source){
Graph.source = source;
}
public static int getDest(){
return dest;
}
public static void setDest(int dest){
Graph.dest = dest;
}
public static void setSum0fDemands(int sum0fDemands){
Graph.sum0fDemands = sum0fDemands;
}
public static int getSum0fDemands(){
return sum0fDemands;
}
public static int getV(){
return V;
}
public static int edgeCount =0;
public static void setV(int V){
if(V>=0)
{
Graph.V =V;
}
}
Graph(int source, int dest){
setSource(source);
setDest(dest);
}
@SuppressWarnings("unchecked")
Graph(String fileName) throws IOException{
int n =0;
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
//bufferedReader.readLine();
//bufferedReader.readLine();
while(bufferedReader.readLine() != null){
n++;
}
setV(n);
V = getV();
adjacency = new LinkedList[V];
int fromNode, toNode, e, weight;
String line; String[] parts;
String splits = " +"; // Multiple whitespace as delimiter.
bufferedReader = new BufferedReader(new FileReader(fileName));
//System.out.println("Reading edges from text file...\n");
for (int i = 0; i < V; i++) {
adjacency[i] = new LinkedList<>();
}
//bufferedReader.readLine();
//bufferedReader.readLine();
for(e = 0; e < V; ++e){
line = bufferedReader.readLine();
parts = line.split(splits);
fromNode = e;
for(int i =0; i<parts.length-1; i= i+2){
toNode = Integer.parseInt(parts[i]);
weight = Integer.parseInt(parts[i+1]);
//System.out.println("Edge from " + fromNode + " --(" + weight + ")-- " +toNode);
edgeCount++;
addEdge(fromNode, toNode, weight);
}
}
}
@SuppressWarnings("unchecked")
Graph(String fileName, int circ) throws IOException{ // For Circulation Graph
int numOfNodes =0; int sup_dem = 0; int v = 0;
int fromNode, toNode, e, weight;
demand = new LinkedList<>();
supply = new LinkedList<>();
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while(bufferedReader.readLine() != null){
numOfNodes++;
}
setV(numOfNodes + 2);
V = getV();
//System.out.println("Number of vertices: " +V);
adjacency = new LinkedList[V];
String line; String[] parts;
String splits = " +"; // Multiple whitespace as delimiter.
bufferedReader = new BufferedReader(new FileReader(fileName));
System.out.println("Reading edges from text file...\n");
for (v = 0; v < V; v++) {
adjacency[v] = new LinkedList<>();
}
for(e = 0; e < numOfNodes; ++e){
line = bufferedReader.readLine();
parts = line.split(splits);
fromNode = e;
//System.out.println("sup_dem print: " + parts[0]);
sup_dem = Integer.parseInt(parts[0]);
if(sup_dem > 0){
demand.add(sup_dem);
System.out.println("Edge from " + (fromNode+1) + " --(" + sup_dem + ")-- " + (V-1));
addEdge((fromNode+1), (V-1), sup_dem);
}
else if(sup_dem < 0){
supply.add(sup_dem);
System.out.println("Edge from " + 0 + " --(" + Math.abs(sup_dem) + ")-- " + (fromNode+1));
addEdge(0, fromNode+1, Math.abs(sup_dem));
}
for(int i = 1; i<parts.length-1; i = i+2){
toNode = Integer.parseInt(parts[i]);
weight = Integer.parseInt(parts[i+1]);
//System.out.println("Edge from " + (fromNode+1) + " --(" + weight + ")-- " + (toNode+1));
addEdge(fromNode+1, toNode+1, weight);
}
}
sum0fDemands = demand.stream().mapToInt(Integer::intValue).sum();
sumOfSupplies = supply.stream().mapToInt(Integer::intValue).sum();
setSum0fDemands(sum0fDemands);
if(sum0fDemands!=Math.abs(sumOfSupplies)){
doDemandsMatchSupplies = false;
System.out.println("Given graph doesn't contain circulation in it because sumOfSupplies " +Math.abs(sumOfSupplies) + " doesn't match to sumOfDemands " +sum0fDemands);
System.exit(0);
}
}
public void addEdge(int fromNode, int toNode, int weight)
{
adjacency[fromNode].add(new Edge(toNode, weight));
}
public void display(List<Edge> adjacency[]) {
int v;
for(v = 0; v < V; ++v) {
System.out.print("\nadj[" + v + "] ->" );
for (Edge edge: adjacency[v]){
System.out.print(" |" + edge.toNode + " | " + edge.weight + "| ->");
}
}
System.out.println("");
}
}
|
package com.android.oy.huarongroad;
import android.view.MotionEvent;
import org.cocos2d.actions.interval.CCFadeIn;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGRect;
public class ChooseLevelLayer extends CCLayer {
private int levelNum;
private CCSprite[] buttons;
private String button_path = "game/level_button";
private CGPoint[] positions;
private CCSprite chooseBack;
private float width, height, scaleX, scaleY;
private int CUR_TAG;
private String path;
public ChooseLevelLayer(String path, int levelNum) {
this.setIsTouchEnabled(true);
this.levelNum = levelNum;
this.path = path;
initPosition();
initSprite();
}
private void initPosition() {
width = CCDirector.sharedDirector().displaySize().width;
height = CCDirector.sharedDirector().displaySize().height;
scaleY = CCDirector.sharedDirector().displaySize().height / 1794;
scaleX = CCDirector.sharedDirector().displaySize().width / 1080;
int init_width = (int)width / 4;
int init_height = (int)height / 5;
positions = new CGPoint[levelNum];
positions[0] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width, init_height));
positions[1] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 2, init_height));
positions[2] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 3, init_height));
positions[3] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width, init_height * 2));
positions[4] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 2, init_height * 2));
positions[5] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 3, init_height * 2));
positions[6] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width, init_height * 3));
positions[7] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 2, init_height * 3));
positions[8] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 3, init_height * 3));
positions[9] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width, init_height * 4));
positions[10] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 2, init_height * 4));
positions[11] = CCDirector.sharedDirector().convertToGL(CGPoint.make(init_width * 3, init_height * 4));
}
private void initSprite() {
buttons = new CCSprite[levelNum];
chooseBack = new CCSprite("game/chooseBack.jpg");
chooseBack.setPosition(CCDirector.sharedDirector().convertToGL(CGPoint.make(width / 2, height / 2)));
chooseBack.setScaleX(1.05f / scaleX);
chooseBack.setScaleY(0.6f / scaleY);
addChild(chooseBack);
CCFadeIn fadeIn = CCFadeIn.action(0.2f);
chooseBack.runAction(fadeIn);
for (int i = 0; i < levelNum; i++) {
String current_path = button_path + (i + 1) + ".png";
buttons[i] = new CCSprite(current_path);
buttons[i].setPosition(positions[i]);
buttons[i].setScaleX(0.1f / scaleX);
buttons[i].setScaleY(0.04f / scaleY);
addChild(buttons[i], 1, i);
fadeIn = CCFadeIn.action(0.2f);
buttons[i].runAction(fadeIn);
}
}
@Override
public boolean ccTouchesBegan(MotionEvent event) {
CGPoint cgPoint = this.convertTouchToNodeSpace(event);
for (int i = 0; i < levelNum; i++) {
CGRect rect = buttons[i].getBoundingBox();
if (CGRect.containsPoint(rect, cgPoint)) {
CUR_TAG = i;
return super.ccTouchesBegan(event);
}
}
return super.ccTouchesBegan(event);
}
@Override
public boolean ccTouchesEnded(MotionEvent event) {
CGPoint cgPoint = this.convertTouchToNodeSpace(event);
for (int i = 0; i < levelNum; i++) {
CGRect rect = buttons[i].getBoundingBox();
if (CGRect.containsPoint(rect, cgPoint)) {
if (CUR_TAG == i) {
changeToGame(i);
}
return super.ccTouchesBegan(event);
}
}
return super.ccTouchesEnded(event);
}
private void changeToGame(int i) {
CCScene scene = CCScene.node();
scene.addChild(new WelcomeLayer(path, i, levelNum));
this.removeSelf();
CCDirector.sharedDirector().runWithScene(scene);
}
}
|
package com.git.cloud.common.mail;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* 邮件基础信息
* @author SunHailong
*/
public class EmailBean {
// 邮件体参数
private List<String> mailTo = new ArrayList<String>();// 收件人地址 (多个采用,隔开)
private String subject;// 邮件主题
private String msgContent;// 邮件内容
private List<String> mailccTo = new ArrayList<String>();//邮件抄送 (多个采用,隔开)
private Vector attachedFileList;//附件,待实现
private String messageContentMimeType = "text/html; charset=gbk";
public List<String> getMailTo() {
return mailTo;
}
public void setMailTo(List<String> mailTo) {
this.mailTo = mailTo;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMsgContent() {
return msgContent;
}
public void setMsgContent(String msgContent) {
this.msgContent = msgContent;
}
public List<String> getMailccTo() {
return mailccTo;
}
public void setMailccTo(List<String> mailccTo) {
this.mailccTo = mailccTo;
}
public Vector getAttachedFileList() {
return attachedFileList;
}
public void setAttachedFileList(Vector attachedFileList) {
this.attachedFileList = attachedFileList;
}
public String getMessageContentMimeType() {
return messageContentMimeType;
}
public void setMessageContentMimeType(String messageContentMimeType) {
this.messageContentMimeType = messageContentMimeType;
}
}
|
package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.extension.SPI;
//调用者监听器
@SPI
public interface InvokerListener {
//当服务引用完成
void referred(Invoker<?> invoker) throws RpcException;
//当服务销毁引用完成
void destroyed(Invoker<?> invoker);
}
|
package enshud.s1.lexer.lexer2;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import enshud.Pair;
import enshud.s1.lexer.TokenStruct;
public class TokenFinder {
public boolean annotate(String strToken, boolean isInAnnotation, TokenStruct outResult) {
outResult.type = TokenStruct.TOKEN_NOTFOUND;
Matcher matcher = null;
ArrayList<Pair<String, Integer>> patternMap = new ArrayList<Pair<String, Integer>>();
if(isInAnnotation) {
patternMap.add(LexerSetting.annotationContent);
patternMap.add(LexerSetting.annotationEnd);
} else {
patternMap.addAll(LexerSetting.tokens);
patternMap.add(LexerSetting.annotationStart);
patternMap.add(LexerSetting.annotation);
}
for(Pair<String, Integer> pair : patternMap) {
Pattern pattern = Pattern.compile(pair.first);
matcher = pattern.matcher(strToken);
// 文字列の先頭にマッチ
if(matcher.find() && matcher.start() == 0) {
outResult.type = pair.second;
break;
}
}
if(outResult.type == TokenStruct.TOKEN_NOTFOUND) {
outResult = null;
return isInAnnotation;
}
outResult.content = matcher.group();
if(outResult.type == LexerSetting.ANNOTATION_START)
return true;
else if(outResult.type == LexerSetting.ANNOTATION_END)
return false;
return isInAnnotation;
}
}
|
package com.windtalker.database;
import android.content.Context;
/**
* Created by jaapo on 26-10-2017.
*/
public interface IDatabase {
IDatabaseReference getReference(Context context);
void clear();
}
|
package org.softRoad.controllers;
import org.softRoad.models.*;
import org.softRoad.models.query.SearchCriteria;
import org.softRoad.services.ProcedureService;
import org.softRoad.utils.Diff;
import javax.enterprise.context.RequestScoped;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Set;
@Path("/procedures")
@RequestScoped
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ProcedureController {
private final ProcedureService procedureService;
public ProcedureController(ProcedureService procedureService) {
this.procedureService = procedureService;
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("create")
public Response create(@Valid Procedure procedure) {
return procedureService.create(procedure);
}
@PATCH
@Produces(MediaType.APPLICATION_JSON)
public Response update(@Diff Procedure procedure) {
return procedureService.update(procedure);
}
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}")
public Response delete(@PathParam("id") Integer id) {
return procedureService.delete(id);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("getAll")
public List<Procedure> getAll(@NotNull SearchCriteria searchCriteria) {
return procedureService.getAll(searchCriteria);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/cities/add")
public Response addCitiesToProcedure(@PathParam("id") Integer id, @NotNull List<Integer> cityIds) {
return procedureService.addCitiesToProcedure(id, cityIds);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/cities/remove")
public Response removeCitiesForProcedure(@PathParam("id") Integer id, @NotNull List<Integer> cityIds) {
return procedureService.removeCitiesForProcedure(id, cityIds);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/categories/add")
public Response addCategoriesToProcedure(@PathParam("id") Integer id, @NotNull List<Integer> categoryIds) {
return procedureService.addCategoriesToProcedure(id, categoryIds);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/categories/remove")
public Response removeCategoriesForProcedure(@PathParam("id") Integer id, @NotNull List<Integer> categoryIds) {
return procedureService.removeCategoriesForProcedure(id, categoryIds);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/tags/add")
public Response addTagsToProcedure(@PathParam("id") Integer id, @NotNull List<Integer> tagIds) {
return procedureService.addTagsToProcedure(id, tagIds);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/tags/remove")
public Response removeTagsForProcedure(@PathParam("id") Integer id, @NotNull List<Integer> tagIds) {
return procedureService.removeTagsForProcedure(id, tagIds);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("cities/{id}")
public List<Procedure> getProcedureForCity(@PathParam("id") Integer id, @NotNull SearchCriteria searchCriteria) {
return procedureService.getProceduresForCity(id, searchCriteria);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("categories/{id}")
public List<Procedure> getProcedureForCategory(@PathParam("id") Integer id,
@NotNull SearchCriteria searchCriteria) {
return procedureService.getProceduresForCategory(id, searchCriteria);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("cities/{cityId}/categories/{categoryId}")
public List<Procedure> getProcedureForCategoryInCity(@PathParam("cityId") Integer cityId,
@PathParam("categoryId") Integer categoryId, @NotNull SearchCriteria searchCriteria) {
return procedureService.getProceduresForCategoryInCity(cityId, categoryId, searchCriteria);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/updateRequests")
public Set<UpdateRequest> getUpdateRequestsOfProcedure(@PathParam("id") Integer id) {
return procedureService.getUpdateRequestsOfProcedure(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/steps")
public Set<Step> getStepsOfProcedure(@PathParam("id") Integer id) {
return procedureService.getStepsOfProcedure(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/comments")
public Set<Comment> getCommentsOfProcedure(@PathParam("id") Integer id) {
return procedureService.getCommentsOfProcedure(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/cities")
public Set<City> getCitiesOfProcedure(@PathParam("id") Integer id) {
return procedureService.getCitiesOfProcedure(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/categories")
public Set<Category> getCategoriesOfProcedure(@PathParam("id") Integer id) {
return procedureService.getCategoriesOfProcedure(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/tags")
public Set<Tag> getTagsOfProcedure(@PathParam("id") Integer id) {
return procedureService.getTagsOfProcedure(id);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/rate")
public Integer getRateOfProcedure(@PathParam("id") Integer id){
return procedureService.getRate(id);
}
}
|
package com.fanfte.concurrent.threadpool;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by dell on 2018/8/2
**/
public class ScheduleMain {
public static void main(String[] args) {
ScheduledThreadPoolExecutor service4 = (ScheduledThreadPoolExecutor) Executors
.newScheduledThreadPool(2);
// 如果前面的任务没有完成,则调度也不会启动
service4.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
// 如果任务执行时间大于间隔时间,那么就以执行时间为准(防止任务出现堆叠)。
Thread.sleep(10000);
System.out.println(System.currentTimeMillis() / 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}// initialDelay(初始延迟) 表示第一次延时时间 ; period 表示间隔时间
}, 0, 2, TimeUnit.SECONDS);
service4.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
System.out.println(System.currentTimeMillis() / 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}// initialDelay(初始延迟) 表示延时时间;delay + 任务执行时间 = 等于间隔时间 period
}, 0, 2, TimeUnit.SECONDS);
// 在给定时间,对任务进行一次调度
service4.schedule(new Runnable() {
@Override
public void run() {
System.out.println("5 秒之后执行 schedule");
}
}, 5, TimeUnit.SECONDS);
}
}
|
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class FindDAte {
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("dd:1-31");
int dd=in.nextInt();
System.out.println("mm:0-11");
int mm=in.nextInt();
System.out.println("yy:");
int yy=in.nextInt();
Date date=(new GregorianCalendar(dd,mm,yy)).getTime();
SimpleDateFormat sdf= new SimpleDateFormat("EEEE");
String day=sdf.format(date);
System.out.println(day);
}
}
|
/*
* 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.jclouds.openstack.heat.v1.options;
import java.util.Map;
import org.jclouds.javax.annotation.Nullable;
import org.jclouds.json.SerializedNames;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableMap;
/**
* Representation of updatable options
*/
@AutoValue
public abstract class UpdateStack {
/**
* @see Builder#template(String)
*/
@Nullable public abstract String getTemplate();
/**
* @see Builder#templateUrl(String)
*/
@Nullable public abstract String getTemplateUrl();
/**
* @see Builder#parameters(java.util.Map)
*/
@Nullable public abstract Map<String, Object> getParameters();
public static Builder builder() {
return new AutoValue_UpdateStack.Builder();
}
public abstract Builder toBuilder();
@SerializedNames({"template", "template_url", "parameters"})
private static UpdateStack create(@Nullable String template, @Nullable String templateUrl, @Nullable Map<String, Object> parameters) {
return builder()
.template(template)
.templateUrl(templateUrl)
.parameters(parameters).build();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder template(String template);
public abstract Builder templateUrl(String templateUrl);
public abstract Builder parameters(Map<String, Object> parameters);
abstract Map<String, Object> getParameters();
abstract UpdateStack autoBuild();
public UpdateStack build() {
parameters(getParameters() != null ? ImmutableMap.copyOf(getParameters()) : null);
return autoBuild();
}
}
}
|
package zhuoxin.com.viewpagerdemo.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
import zhuoxin.com.viewpagerdemo.R;
import zhuoxin.com.viewpagerdemo.activity.TitleActivity;
import zhuoxin.com.viewpagerdemo.adapter.TabStateLayoutAdapter;
import zhuoxin.com.viewpagerdemo.utils.sharedpres;
public class FragmentNews extends Fragment{
private ViewPager pager;
private List<Fragment> fragments;
private List<String> titles;
private TabLayout tabLayout;
private TabStateLayoutAdapter adapter;
private ImageView iv_add;
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_news,container,false);
}
public void onViewCreated(View view,Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initView();
addData();
}
public void initView() {
pager =(ViewPager)getActivity().findViewById(R.id.fragment_one_view_pager);
tabLayout=(TabLayout)getActivity().findViewById(R.id.fragment_one_tabLayout);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
public void onTabSelected(TabLayout.Tab tab) {
}
public void onTabUnselected(TabLayout.Tab tab) {
}
public void onTabReselected(TabLayout.Tab tab) {
}
});
iv_add=(ImageView)getActivity().findViewById(R.id.fragment_one_add);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);//模式//填充//滑动
iv_add.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(getActivity(), TitleActivity.class);
startActivityForResult(intent,100);
}
});
}
private void addData(){
fragments=new ArrayList<>();
if(titles!=null)
titles.clear();
fragments.clear();
titles=sharedpres.getLists(getActivity());
for (int i=0;i<titles.size();i++){
FragmentDemo fragmentDemo = new FragmentDemo();
Bundle bundle = new Bundle();
bundle.putString("title",titles.get(i));
fragmentDemo.setArguments(bundle);
fragments.add(fragmentDemo);
}
adapter=new TabStateLayoutAdapter(getChildFragmentManager(),fragments,titles);
pager.setAdapter(adapter);
pager.setOffscreenPageLimit(2);
tabLayout.setupWithViewPager(pager);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data!=null){if(resultCode==101){if(requestCode==100){
boolean flag = data.getBooleanExtra("flag",false);
if(flag){
addData();
}}}}}
}
|
package web.frontcontroller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import classes.util.Resultado;
import dominio.endereco.Locacao;
import dominio.evento.IDominio;
import dominio.produto.Fornecedor;
import dominio.produto.Produto;
import web.command.ICommand;
import web.command.impl.AlterarCommand;
import web.command.impl.ConsultarCommand;
import web.command.impl.ExcluirCommand;
import web.command.impl.SalvarCommand;
import web.viewhelper.IViewHelper;
import web.viewhelper.impl.EstoqueEventoVH;
import web.viewhelper.impl.EventoVH;
import web.viewhelper.impl.EventosParticipanteVH;
import web.viewhelper.impl.ItemProdutoVH;
import web.viewhelper.impl.LocacaoVH;
import web.viewhelper.impl.ParticipanteVH;
import web.viewhelper.impl.ParticipantesEventoVH;
import web.viewhelper.impl.ProdutoVH;
import web.viewhelper.impl.RateioProdutoVH;
import web.viewhelper.impl.RateioVH;
import web.viewhelper.impl.RelatoriosVH;
import web.viewhelper.impl.UsuarioVH;
/**
* Servlet implementation class Gestao
*/
@WebServlet("/Gestao")
public class Gestao extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Map<String, ICommand> commands;
private static Map<String, IViewHelper> vhs;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ConsultarCommand command = new ConsultarCommand();
Resultado rsProduto = command.execute(new Produto());
config.getServletContext().setAttribute("listaProdutos", rsProduto);
Resultado rsFornecedor = command.execute(new Fornecedor());
config.getServletContext().setAttribute("listaFornecedores", rsFornecedor);
Resultado rsLocacao = command.execute(new Locacao());
config.getServletContext().setAttribute("listaLocacoes", rsLocacao);
}
public Gestao() {
commands = new HashMap<String, ICommand>();
commands.put("SALVAR", new SalvarCommand());
commands.put("CONSULTAR", new ConsultarCommand());
commands.put("ATUALIZAR", new AlterarCommand());
commands.put("EXCLUIR", new ExcluirCommand());
vhs = new HashMap<String, IViewHelper>();
vhs.put("/gestao-eventos-web/login", new UsuarioVH());
vhs.put("/gestao-eventos-web/cadastrar", new UsuarioVH());
vhs.put("/gestao-eventos-web/sair", new UsuarioVH());
vhs.put("/gestao-eventos-web/evento/salvar", new EventoVH());
vhs.put("/gestao-eventos-web/evento/consultar", new EventoVH());
vhs.put("/gestao-eventos-web/evento/alterar", new EventoVH());
vhs.put("/gestao-eventos-web/evento/excluir", new EventoVH());
vhs.put("/gestao-eventos-web/evento/add-participante", new ParticipantesEventoVH());
vhs.put("/gestao-eventos-web/evento/participantes-evento", new ParticipantesEventoVH());
vhs.put("/gestao-eventos-web/evento/consultar-participantes", new ParticipantesEventoVH());
vhs.put("/gestao-eventos-web/evento/eventos-convidado", new EventosParticipanteVH());
vhs.put("/gestao-eventos-web/evento/lista-produtos-rateio", new RateioProdutoVH());
vhs.put("/gestao-eventos-web/evento/salvar-produtos-rateio", new RateioProdutoVH());
vhs.put("/gestao-eventos-web/evento/alterar-produtos-rateio", new RateioProdutoVH());
vhs.put("/gestao-eventos-web/evento/estoque-evento", new EstoqueEventoVH());
vhs.put("/gestao-eventos-web/evento/consultar-rateio", new RateioVH());
vhs.put("/gestao-eventos-web/participantes/salvar", new ParticipanteVH());
vhs.put("/gestao-eventos-web/participantes/consultar", new ParticipanteVH());
vhs.put("/gestao-eventos-web/participantes/alterar", new ParticipanteVH());
vhs.put("/gestao-eventos-web/participantes/excluir", new ParticipanteVH());
vhs.put("/gestao-eventos-web/produtos/salvar", new ProdutoVH());
vhs.put("/gestao-eventos-web/produtos/consultar", new ProdutoVH());
vhs.put("/gestao-eventos-web/produtos/alterar", new ProdutoVH());
vhs.put("/gestao-eventos-web/produtos/excluir", new ProdutoVH());
vhs.put("/gestao-eventos-web/estoque/salvar", new ItemProdutoVH());
vhs.put("/gestao-eventos-web/estoque/consultar", new ItemProdutoVH());
vhs.put("/gestao-eventos-web/estoque/alterar", new ItemProdutoVH());
vhs.put("/gestao-eventos-web/estoque/excluir", new ItemProdutoVH());
vhs.put("/gestao-eventos-web/locacoes/salvar", new LocacaoVH());
vhs.put("/gestao-eventos-web/locacoes/consultar", new LocacaoVH());
vhs.put("/gestao-eventos-web/locacoes/alterar", new LocacaoVH());
vhs.put("/gestao-eventos-web/locacoes/excluir", new LocacaoVH());
vhs.put("/gestao-eventos-web/relatorios/evento", new RelatoriosVH());
vhs.put("/gestao-eventos-web/relatorios/participante", new RelatoriosVH());
vhs.put("/gestao-eventos-web/relatorios/produto", new RelatoriosVH());
vhs.put("/gestao-eventos-web/relatorios/locacao", new RelatoriosVH());
}
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
String operacao = request.getParameter("operacao");
IViewHelper vh = vhs.get(uri);
IDominio entidade = vh.getData(request);
ICommand command = commands.get(operacao);
Resultado resultado = command.execute(entidade);
vh.formataView(resultado, request, response);
}
}
|
import java.util.*;
import java.io.*;
public class Boards
{
static InputStreamReader read=new InputStreamReader(System.in);
static BufferedReader in=new BufferedReader(read);
static int mm,t,ord,piz,code,size,number,flag,k;
static int gross; static String arr[]=new String[100]; static int j=0;
static void start()throws IOException
{
System.out.println("\f");
System.out.println(" ;^1f9 !9 ");
System.out.println(" -l<?35ku6s^!9u~ ");
System.out.println(" .*leu52UAuj?Ij1=19oI ");
System.out.println(" -*I326u6ZkZ?Lr1j^tjr11io5* ");
System.out.println(" 1ZVSu25o<<!11^<j^j^r999r!12I ");
System.out.println(" 98|L1^r1!^rIIr11t9j!!99rIi165* ");
System.out.println(" luorj9=19I99<9jtj9991t9r!^1I|A6|r9- ");
System.out.println(" 3e9I^==II19jt<j1ir99!=r<19=99?uUu52k?^_ ");
System.out.println(" j?1^r19I<9<!1r1919I<9^9j9I9<t!r17|aa2kuVuu^* ");
System.out.println(" !^1j9r^91t91j1!1<9=<191iI^tt9rtjt=9^^917uuUSVU2I* ");
System.out.println(" *i9j1!9r9r99<I!119<11I1^I911riI<<9191t9^919<tu$9u319 ");
System.out.println(" -^1j1<<irj!r!j999It19<9<1rI1j9^11<I^jr^jr9I9IjI9!1Iju5S6e_ ");
System.out.println(" ~9|2sj9r=r991t<^911!!9rI=t11111i111!I9=<tL|oeuoZ62u2e9<I9l!?; ");
System.out.println(" <u99ti1rI91rt^991tr<199r^^r<9iIr1e?|uo2Vkkk6kuUuSUAuk$2^j9r. ");
System.out.println(" _?S$u?I991999t9^919Iij^9jsjt5aZ5k2u66$uUk5V5V5$kVSVdu33ZZ1!~*- ");
System.out.println(" l7$S291!111jjI99911<?oeS52o3u$u6Uu$u2dokaoj?79l99*lll-- ");
System.out.println(" 1u263119j91!t<IL72oZu9kVko9*ll1uL=I!9;l_ ");
System.out.println(" lo6aL19991e1?ak6dV2uu8Z2L1l91|e* ");
System.out.println(" rk9Z79^I|uSSk2u28u6LI^9_ _jsoZ_ ");
System.out.println(" l36uo|ZZ6S6866|e9l_. _?e|o, ");
System.out.println(" lu26kkukk55?<l_ 9su1- l**9l9I?osjj_ l!1oj72I ");
System.out.println(" 5k$6k1r9: lj 3k2u6k62d6kVu 9o25$kk2Vo ");
System.out.println(" ll9* -_*l9l^Il9<9 !LkkeoI2uVus, ~u$uue998Z29 ");
System.out.println(" _!=I71Ill 1e *UVk$udk666$6l 72VSo ^kkV7* ?5ku ");
System.out.println(" *o6u2SVk56$97_ ek6l 9oj2|j=o$6d? 1k92V^ <dAuj l9o$U66^!!* ");
System.out.println(" 1kSdUSSukkAkkAk^ ?V82 ;ekuS^ 9o8$ksl 2$ud6386ko628d52: ");
System.out.println(" 12|ZdA^lto$66kku_ ?5U5^ _?2Skd= ~s686Ui Lu86d2u19 -l=*, ");
System.out.println(" *626: lekuUV1 tV266l 1V92uo- IVkuu5UV25eee|e-L??t~ ");
System.out.println(" l6k2Z 3$uSI 9k56S! 9kku68= lkd8uSUudV8822^* ");
System.out.println(" _k62u_ Lddk^ sudU7 -su82$2l -_ l_*~-*_**l,_ ");
System.out.println(" -kk2U2 9$2ut oU62 l6u2d25ukakd6uLe7!l^9ljuj - ");
System.out.println(" euk2Sl 92$2o j5k9 l8uu6VS68$5uA2kuSSku66$o1l lS2 ");
System.out.println(" =uu65| -!3d8u9 9? joZ?lll~*l9**l_l*99** 9$51 _- ");
System.out.println(" VkSk69_1LuSS1* l -9 *5ku*l^Iosej_ ");
System.out.println(" 7Vk5k?9uf|i* 32l luk_ _l_~96U56268|j9* ");
System.out.println(" -6d5u8* 7do l2A3 l-:dU862k6k3t9_ ");
System.out.println(" ju6621 ?kU1 |SkI ll^* I6Z l99k$6ul ");
System.out.println(" Vk6uu ^62k* l9ku9 956A9 lkuo -k6ur ");
System.out.println(" 9k685^ !5A2Z oUS29^ jk$e 7uSA< 1kV| ");
System.out.println(" Z2k5j 2uu6- ^5V6dor.ukVu 9|$2uul :66kl ");
System.out.println(" -6$U5l 1ud6Z^ro332k2di !kS61lo8S|k6k* lS6? ");
System.out.println(" ^6u5! :l19ZSAkA65dV$92u2k- k5uuuku69_U86l l7kul *, ");
System.out.println(" <6So lV68u5V6UU2Ae1*1k8d7 ud5dkkj* rA5_ ^2j ~_9;9999I9l9 ");
System.out.println(" l3L, -j2Zk6kd6|l- 2uukr 972o1l _9* <6<l9iir91rIIl** 999; ");
System.out.println(" kUuk| 9$2du *9<1j9^99199~- ,9r9l ");
System.out.println(" lA5SUI 926Ur *99!rI!1I!tr=_- ~9^l ");
System.out.println(" sSSUul !1l l9^9<1I1j91^l_- ");
System.out.println(" -d6k6e -~91999=9I!<9l_ ");
System.out.println(" ldS6Vl ~l9<I9j=tj9^*~ ");
System.out.println(" ?k3t _*9999^1r^jlll ");
System.out.println(" : -*^^<r<99j9r9l* ");
System.out.println(" *9^j^!I11^j99l* ");
System.out.println(" ;199<1t19<ll ");
try
{
Thread.sleep(4000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("\f");
}
static void main()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
mm=t=ord=piz=code=size=number=flag=k=gross=j=0;
for(int i=0;i<100;i++)
{
arr[i]="";
}
ob.start();
ob.main_menu();
}
static void main_menu()throws IOException //this isnt your MAIN METHOD!!!
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2014 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\tIndia's most trusted restaurant brand, Pizza Hut India offers exciting new range of fresh");
System.out.println("\t\t\t\t\tItalian cooking. With outlets in over 34 cities, we explore new dishes to leave you lip smacking.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tMAIN MENU");
System.out.println("\t\t\t\t\tHow shall we serve you today?");
System.out.println("\t\t\t\t\t1. ABOUT US");
System.out.println("\t\t\t\t\t2. ORDER");
System.out.println("\t\t\t\t\t3. OFFERS");
System.out.println("\t\t\t\t\t4. STORE LOCATIONS");
System.out.println("\t\t\t\t\t5. FEEDBACK");
System.out.println("\t\t\t\t\t6. EXIT");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
t=0;
while(true)
{
try
{
System.out.print("\t\t\t\t\tPlease Enter Your Choice -> ");
mm=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
switch(mm)
{
case 1:
ob.about_us();
break;
case 2:
ob.order();
break;
case 3:
ob.offers();
break;
case 4:
ob.store_locs();
break;
case 5:
ob.feedback();
break;
case 6:
ob.exit();
break;
default:
System.out.println("\t\t\t\t\tWrong Choice!");
t=1;
}
if(t==1)
continue;
else
break;
}
}
void about_us()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2014 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t***************************************************************************************************");
System.out.println("\t\t\t\t\t\t\t\t\t\t\tABOUT US");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\tIt was the summer of 1958 when Dan and Frank Carney decided to open a pizzeria. With mouth-watering");
System.out.println("\t\t\t\t\tpizzas prepared by the founders themselves, Pizza Hut soon became the most popular neighbourhood");
System.out.println("\t\t\t\t\trestaurant. From then to over 13,200 restaurants across the world today, we have come a long way.");
System.out.println("\t\t\t\t\tToday, Pizza Hut is about much more than pizzas. From freshly sauteed pastas & delicious appetizers");
System.out.println("\t\t\t\t\tto mocktails, desserts, soups and salads, we have a wide range for you to feast on. All this,");
System.out.println("\t\t\t\t\tcombined with the warm, inviting ambience and friendly service, will lead to endless conversations,");
System.out.println("\t\t\t\t\tlaughter and memories that you'll cherish forever. So, let your hair down and feel at ease.");
System.out.println("\t\t\t\t\tGo ahead and enjoy the All New Pizza Hut experience!");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t***************************************************************************************************");
while(true)
{
System.out.print("\t\t\t\t\tEnter \"back\" to return to the main menu -> ");
String t1=in.readLine();
if(t1.equalsIgnoreCase("back"))
ob.main_menu();
else
{
System.out.println("\t\t\t\t\tWrong Input!");
continue;
}
break;
}
}
static void order()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\tWhat Shall we bake for you today?");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tORDER MENU");
System.out.println("\t\t\t\t\t1. PIZZA....................enjoy from over 80 lip smacking varieties");
System.out.println("\t\t\t\t\t2. BIRIZZA..................the joy of biryani combined with the fun of pizza hut");
System.out.println("\t\t\t\t\t3. SIDES....................If you haven't had enough with just the pizzas");
System.out.println("\t\t\t\t\t4. DESSERTS AND DRINKS......Fresh from our ovens. And Blenders");
System.out.println("\t\t\t\t\t5. VALUE MEALS..............Our pizzas for your entire family at reasonable rates");
System.out.println("\t\t\t\t\t6. PROCEED TO CHECKOUT");
System.out.println("\t\t\t\t\t7. EXIT TO MAIN MENU");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
t=0;
while(true)
{
try
{
System.out.print("\t\t\t\t\tPlease Enter Your Choice -> ");
ord=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
switch(ord)
{
case 1:
ob.pizzas();
break;
case 2:
ob.birizza();
break;
case 3:
ob.sides();
break;
case 4:
ob.dessserts();
break;
case 5:
ob.meals();
break;
case 6:
if(code==0)
{
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\tError 404: It seems that You Haven't Ordered Anything With us yet.");
System.out.println("\t\t\t\t\t\tTo Indulge India's Most Loved Lip Smacking Pizzas, Start Ordering From Pizza Hut now!");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t**************************************************************************************************");
try
{
Thread.sleep(3000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
ob.order();
}
else
{
ob.bill();
}
break;
case 7:
ob.main_menu();
break;
default:
System.out.println("\t\t\t\t\tWrong Choice!");
t=1;
}
if(t==1)
continue;
else
break;
}
}
static void pizzas()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println(" .----------------. .----------------. .----------------. .----------------. .----------------. ");
System.out.println(" | .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |");
System.out.println(" | | ______ | || | _____ | || | ________ | || | ________ | || | __ | |");
System.out.println(" | | |_ __ \\ | || | |_ _| | || | | __ _| | || | | __ _| | || | / \\ | |");
System.out.println(" | | | |__) | | || | | | | || | |_/ / / | || | |_/ / / | || | / /\\ \\ | |");
System.out.println(" | | | ___/ | || | | | | || | .'.' _ | || | .'.' _ | || | / ____ \\ | |");
System.out.println(" | | _| |_ | || | _| |_ | || | _/ /__/ | | || | _/ /__/ | | || | _/ / \\ \\_ | |");
System.out.println(" | | |_____| | || | |_____| | || | |________| | || | |________| | || ||____| |____|| |");
System.out.println(" | | | || | | || | | || | | || | | |");
System.out.println(" | '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |");
System.out.println(" '----------------' '----------------' '----------------' '----------------' '----------------' ");
try
{
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\tOur World Famous thick crust pizzas-Baked to perfection to suit your taste.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tPIZZAS");
System.out.println("\t\t\t\t\t1. MAGIC PAN PIZZAS.........our signature Pizzas");
System.out.println("\t\t\t\t\t2. THE BIG PIZZAS...........for people who like it BIGGG");
System.out.println("\t\t\t\t\t3. SO CHEEZY PIZZAS.........Indias Cheeziest Pizzas");
System.out.println("\t\t\t\t\t4. EXIT TO ORDER MENU");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
t=0;
while(true)
{
try
{
System.out.print("\t\t\t\t\tPlease Enter Your Choice -> ");
piz=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
switch(piz)
{
case 1:
case 2:
case 3:
ob.piz_ch();
break;
case 4:
ob.order();
break;
default:
System.out.println("\t\t\t\t\tWrong Choice!");
t=1;
}
if(t==1)
continue;
else
break;
}
}
static void piz_ch()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
switch(piz)
{
case 1:
System.out.println("\t\t\t\t\tTastiest pizzas staring @ Rs.55*");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tMAGIC PAN PIZZAS");
System.out.println("\t\t\t\t\t\t\t\tVEG PIZZAS");
System.out.println("\t\t\t\t\t Name Personal Medium Family");
System.out.println("\t\t\t\t\tSIGNATURE");
System.out.println("\t\t\t\t\t1.TANDOORI PANEER....220 395 595 ");
System.out.println("\t\t\t\t\t(Paneer, onion, capsicum, red paprika and tomato.)");
System.out.println("\t\t\t\t\t2.VEGGIE LOVERS......220 395 595 ");
System.out.println("\t\t\t\t\t(Mushroom, onion, tomato and capsicum.)");
System.out.println("\t\t\t\t\t3.PANEER MAKHANI.....220 395 595 ");
System.out.println("\t\t\t\t\t(Paneer, capsicum, onion, and red paprika.)");
System.out.println("\t\t\t\t\t4.COUNTRY FEAST......220 395 595 ");
System.out.println("\t\t\t\t\t(Sweet corn, mushroom, tomato, onion and capsicum.)");
System.out.println("\t\t\t\t\tSUPREME");
System.out.println("\t\t\t\t\t5.FIERY RIDE.........260 470 695 ");
System.out.println("\t\t\t\t\t(Tomato, Onion, Capsicum, Sweet Corn , Olives , Jalapenos & Green Chillies.)");
System.out.println("\t\t\t\t\t6.PANEER VEGORAMA....260 470 695 ");
System.out.println("\t\t\t\t\t(Paneer, Onion, Capsicum, Sweet Corn, Red Capsicum, Black Olives, Red Paprika & Green Chillies.)");
System.out.println("\t\t\t\t\t7.VEGGIE SUPREME.....260 470 695 ");
System.out.println("\t\t\t\t\t(Mushroom, capsicum, onion, tomato, baby corn and olives.)");
System.out.println("\t\t\t\t\t8.EXOTICA............260 470 695 ");
System.out.println("\t\t\t\t\t(Red capsicum, baby corn, capsicum, olives and jalapenos.)");
System.out.println("\n\t\t\t\t\t\t\t\tNON-VEG PIZZAS");
System.out.println("\t\t\t\t\t Name Personal Medium Family");
System.out.println("\t\t\t\t\tSIGNATURE");
System.out.println("\t\t\t\t\t9.CHICKEN ITALIA........250 450 655 ");
System.out.println("\t\t\t\t\t(Chunks of chicken,cheese 'n' onion chicken sausage,sweet corn,olives and jalapenos.)");
System.out.println("\t\t\t\t\t10.CHICKEN TIKKA........250 450 655 ");
System.out.println("\t\t\t\t\t(Tandoori chicken, onion, tomato and green chillies.)");
System.out.println("\t\t\t\t\t11.KADAI CHICKEN....... 250 450 655 ");
System.out.println("\t\t\t\t\t(Kadai Chicken, onion, capsicum, red capsicum, green chillies, coriander and cheese.)");
System.out.println("\t\t\t\t\tSUPREME");
System.out.println("\t\t\t\t\t12.PEPPERONI............295 515 765 ");
System.out.println("\t\t\t\t\t(100% pork pepperoni.)");
System.out.println("\t\t\t\t\t13.TRIPLE CHICKEN FEAST.295 515 765 ");
System.out.println("\t\t\t\t\t(Mexican Chicken, Plain Chicken, Chicken Hot & Spicy, Onion, Capsicum, Sweet Corn & Green Chillies.)");
System.out.println("\t\t\t\t\t14.CHICKEN SUPREME......295 515 765 ");
System.out.println("\t\t\t\t\t(Chicken Hot 'n' Spicy, chicken tikka and chunky chicken.)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter 1 to order a pizza or 2 to go back to the order menu -> ");
flag=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(flag==1)
{
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the Item Code of Pizza you wish to have -> ");
//accept the input in a global variable, say code
code=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(code>14 || code<=0)
{
System.out.println("\t\t\t\t\tINVALID ITEM CODE! Please input a valid one.");
continue;
}
break;
}
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the size, i.e., 1 for Personal, 2 for Medium, 3 for Family -> ");
//accept the input in a global variable, say size
size=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(size>3 || size<=0)
{
System.out.println("\t\t\t\t\tINVALID SIZE CODE! Please input a valid one.");
continue;
}
break;
}
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the number of such pizzas you would like to order -> ");
//accept the input in a global variable, say number
number=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(number>20)
{
System.out.println("\t\t\t\t\tSorry, but our policy doesn't permit us bulk ordering above 20 pizzas in a single order.");
System.out.println("\t\t\t\t\tPlease consult our website for more information.");
continue;
}
if(number<0)
{
System.out.println("\t\t\t\t\tINVALID NUMBER OF ITEMS! Please input a valid one.");
continue;
}
if(number==0)
{
System.out.println("\t\t\t\t\tYou have to order more than one pizza!");
continue;
}
break;
}
}
else if(flag==2)
{
ob.order();
}
else
{
System.out.println("\t\t\t\t\tWrong choice!");
continue;
}
break;
}
break; //case 1 break
case 2:
System.out.println("\t\t\t\t\tBIG on size-BIG on Taste-BIG on Choice. Any BIG pizza for Rs.219");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\tTHE BIG PIZZA");
System.out.println("\n\t\t\t\t\t\t\tVEG PIZZAS");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t 1.FARM HUT..................219");
System.out.println("\t\t\t\t\t(Onion, Mushroom, Capsicum, Tomato & Cheese)");
System.out.println("\t\t\t\t\t 2.ITALIAN TREAT.............219");
System.out.println("\t\t\t\t\t(Capsicum, Black Olives, Tomato, Onion and Cheese)");
System.out.println("\n\t\t\t\t\t\t\tNON-VEG PIZZAS");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t3.CHICKEN MEXICANO.............219");
System.out.println("\t\t\t\t\t(Mexican Chicken, Onion, Capsicum, Sweet Corn & Cheese)");
System.out.println("\t\t\t\t\t4.SPICY CHICKEN MAGIC..........219");
System.out.println("\t\t\t\t\t(Chicken, Tomato, Onion, Green Chilies and Cheese)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter 1 to order a pizza or 2 to go back to the order menu -> ");
flag=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(flag==1)
{
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the Item Code of Pizza you wish to have -> ");
//accept the input in a global variable, say code
code=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(code>4 || code<=0)
{
System.out.println("\t\t\t\t\tINVALID ITEM CODE! Please input a valid one.");
continue;
}
break;
}
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the number of such pizzas you would like to order -> ");
//do the same as above,in say number
number=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(number>20)
{
System.out.println("\t\t\t\t\tSorry, but our policy doesn't permit us bulk ordering above 20 pizzas in a single order.");
System.out.println("\t\t\t\t\tPlease consult our website for more information.");
continue;
}
if(number<0)
{
System.out.println("\t\t\t\t\tINVALID NUMBER OF ITEMS! Please input a valid one.");
continue;
}
if(number==0)
{
System.out.println("\t\t\t\t\tYou have to order more than one pizza!");
continue;
}
break;
}
}
else if(flag==2)
{
ob.order();
}
else
{
System.out.println("\t\t\t\t\tWrong choice!");
continue;
}
break;
}
break; //case 2 break
case 3:
System.out.println("\t\t\t\t\tCheese Loaded in every bite-cheddar on the side,creamy in the middle and mozzarela on top.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\tSO CHEEZY PIZZAS");
System.out.println("\t\t\t\t\t\t\tVEG PIZZAS");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t 1.VEG TREAT...............449");
System.out.println("\t\t\t\t\t(Onion, Tomato, Capsicum, Sweet Corn, Jalapeno & Cheese)");
System.out.println("\t\t\t\t\t 2.SUPER VEG...............499");
System.out.println("\t\t\t\t\t(Mushroom, Capsicum, Onion, Sweet Corn, Red Paprika, Black Olives & Cheese)");
System.out.println("\n\t\t\t\t\t\t\tVEG PIZZAS");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t3.HOT'N'SPICY CHICKEN........499");
System.out.println("\t\t\t\t\t(Hot 'n' spicy Chicken, Mushroom, Tomato, Onion, Olives & Cheese)");
System.out.println("\t\t\t\t\t4.DOUBLE CHICKEN FEAST......569");
System.out.println("\t\t\t\t\t(Chicken Tikka, Chicken Plain, Red Paprika, Capsicum, Sweet Corn, Jalapeno & Cheese)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter 1 to order a pizza or 2 to go back to the order menu -> ");
flag=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(flag==1)
{
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the Item Code of Pizza you wish to have -> ");
//accept the input in a global variable, say code
code=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(code>4 || code<=0)
{
System.out.println("\t\t\t\t\tINVALID ITEM CODE! Please input a valid one.");
continue;
}
break;
}
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the number of such pizzas you would like to order -> ");
//do the same as above,in say number
number=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(number>20)
{
System.out.println("\t\t\t\t\tSorry, but our policy doesn't permit us bulk ordering above 20 pizzas in a single order.");
System.out.println("\t\t\t\t\tPlease consult our website for more information.");
continue;
}
if(number<0)
{
System.out.println("\t\t\t\t\tINVALID NUMBER OF ITEMS! Please input a valid one.");
continue;
}
if(number==0)
{
System.out.println("\t\t\t\t\tYou have to order more than one pizza!");
continue;
}
break;
}
}
else if(flag==2)
{
ob.order();
}
else
{
System.out.println("\t\t\t\t\tWrong choice!");
continue;
}
break;
}
break; //case 3 break
}
System.out.print("\f");
System.out.print("ORDERING ");
for(int i=0;i<=6;i++)
{
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.print(". "); k++;
if(k==5)
{
System.out.print("\f");
System.out.print("ORDERING ");
k=0;
}
}
k=0;
ob.calculate();
ob.order();
}
static void birizza()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println(" ,ggggggggggg, ");
System.out.println(" dP\"\"\"88\"\"\"\"\"\"Y8, ");
System.out.println(" Yb, 88 `8b ");
System.out.println(" `\" 88 ,8P gg gg ");
System.out.println(" 88aaaad8P\" \"\" \"\" ");
System.out.println(" 88\"\"\"\"Y8ba gg ,gggggg, gg ,gggg, ,gggg, ,gggg,gg ");
System.out.println(" 88 `8b 88 dP\"\"\"\"8I 88 d8\" Yb d8\" Yb dP\" \"Y8I");
System.out.println(" 88 ,8P 88 ,8\' 8I 88 dP dP dP dP i8\' ,8I ");
System.out.println(" 88_____,d8\'_,88,_,dP Y8,_,88,_,dP ,adP\' ,dP ,adP\' ,d8, ,d8b,");
System.out.println(" 88888888P\" 8P\"\"Y88P `Y88P\"\"Y88\" \"\"Y8d88\" \"\"Y8d8P\"Y8888P\"`Y8");
System.out.println(" ,d8I\' ,d8I\' ");
System.out.println(" ,dP\'8I ,dP\'8I ");
System.out.println(" ,8\" 8I ,8\" 8I ");
System.out.println(" I8 8I I8 8I ");
System.out.println(" `8, ,8I `8, ,8I ");
System.out.println(" `Y8P\" `Y8P\" ");
try
{
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\tA Delicious Masala rice sealed in Flavoured crust and served with tasty gravy.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tBIRIZZAS");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t1. VEGGIE..................109 ");
System.out.println("\t\t\t\t\t(Corn, Capsicum and Seasonal vegetables)");
System.out.println("\t\t\t\t\t2. PANEER..................145 ");
System.out.println("\t\t\t\t\t(Paneer cubes, Capsicum and Seasonal vegetables)");
System.out.println("\t\t\t\t\t3. CHICKEN..................165 ");
System.out.println("\t\t\t\t\t(Chicken and Seasonal Vegetables)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter 1 to order a birizza or 2 to go back to the order menu -> ");
flag=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(flag==1)
{
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the Item Code of birizza you wish to have -> ");
//accept the input in a global variable, say code
code=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(code>3 || code<=0)
{
System.out.println("\t\t\t\t\tINVALID ITEM CODE! Please input a valid one.");
continue;
}
break;
}
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the number of such birizzas you would like to order -> ");
//accept the input in a global variable, say number
number=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(number>20)
{
System.out.println("\t\t\t\t\tSorry, but our policy doesn't permit us bulk ordering above 20 birizzas in a single order.");
System.out.println("\t\t\t\t\tPlease consult our website for more information.");
continue;
}
if(number<0)
{
System.out.println("\t\t\t\t\tINVALID NUMBER OF ITEMS! Please input a valid one.");
continue;
}
if(number==0)
{
System.out.println("\t\t\t\t\tYou have to order more than one birizza!");
continue;
}
break;
}
}
else if(flag==2)
{
ob.order();
}
else
{
System.out.println("\t\t\t\t\tWrong choice!");
continue;
}
break;
}
System.out.print("\f");
System.out.print("ORDERING ");
for(int i=0;i<=6;i++)
{
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.print(". "); k++;
if(k==5)
{
System.out.print("\f");
System.out.print("ORDERING ");
k=0;
}
}
k=0;
ob.calculate();
ob.order();
}
static void sides()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println(" ad88888ba 88 88 ");
System.out.println("d8\" \"8b \"\" 88 ");
System.out.println("Y8, 88 ");
System.out.println("`Y8aaaaa, 88 ,adPPYb,88 ,adPPYba, ,adPPYba, ");
System.out.println(" `\"\"\"\"\"8b, 88 a8\" `Y88 a8P_____88 I8[ \"\" ");
System.out.println(" `8b 88 8b 88 8PP\"\"\"\"\"\"\" `\"Y8ba, ");
System.out.println("Y8a a8P 88 \"8a, ,d88 \"8b, ,aa aa ]8I ");
System.out.println(" \"Y88888P\" 88 `\"8bbdP\"Y8 `\"Ybbd8\"\' `\"YbbdP\"\' ");
try
{
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\tSavour the Side stories and compliment your meals if just the Pizzas aren't enough.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tSIDES");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t1. VEG BAKED PASTA...........125.00");
System.out.println("\t\t\t\t\t(Spicy Tomato Sauce with Mozzarella Cheese, Onion, Capsicum and Chopped Parsley mixed with Fussilli Pasta.)");
System.out.println("\t\t\t\t\t2. CHICKEN BAKED PASTA.......145.00");
System.out.println("\t\t\t\t\t(Spicy Tomato Sauce with Mozzarella Cheese, Onion, Capsicum and Chopped Parsley mixed with Fussilli Pasta.)");
System.out.println("\t\t\t\t\t3. CHICKEN WINGS.............149.00");
System.out.println("\t\t\t\t\t(6 piece of tender, juicy chicken wings tossed in spicy BBQ sauce.)");
System.out.println("\t\t\t\t\t4. GARLIC BREAD STIX..........99.00");
System.out.println("\t\t\t\t\t(Freshly Baked, Buttery Garlic Bread Sticks served with Cheese!)");
System.out.println("\t\t\t\t\t5. POTATO WEDGES..............89.00");
System.out.println("\t\t\t\t\t(Crispy potato wedges seasoned with a tinge of garlic!)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter 1 to order a side or 2 to go back to the order menu -> ");
flag=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(flag==1)
{
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the Item Code of the side you wish to have -> ");
//accept the input in a global variable, say code
code=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(code<1 || code>5)
{
System.out.println("\t\t\t\t\tINVALID ITEM CODE! Please input a valid one.");
continue;
}
break;
}
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the number of such items you would like to order -> ");
//accept the input in a global variable, say number
number=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(number>20)
{
System.out.println("\t\t\t\t\tSorry, but our policy doesn't permit us bulk ordering above 20 sides in a single order.");
System.out.println("\t\t\t\t\tPlease consult our website for more information.");
continue;
}
if(number<0)
{
System.out.println("\t\t\t\t\tINVALID NUMBER OF ITEMS! Please input a valid one.");
continue;
}
if(number==0)
{
System.out.println("\t\t\t\t\tYou have to order more than one item!");
continue;
}
break;
}
}
else if(flag==2)
{
ob.order();
}
else
{
System.out.println("\t\t\t\t\tWrong choice!");
continue;
}
break;
}
System.out.print("\f");
System.out.print("ORDERING ");
for(int i=0;i<=6;i++)
{
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.print(". "); k++;
if(k==5)
{
System.out.print("\f");
System.out.print("ORDERING ");
k=0;
}
}
k=0;
ob.calculate();
ob.order();
}
static void dessserts()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("oooooooooo. . ");
System.out.println("888\' `Y8b .o8 ");
System.out.println("888 888 .ooooo. .oooo.o .oooo.o .ooooo. oooo d8b .o888oo .oooo.o ");
System.out.println("888 888 d88\' `88b d88( \"8 d88( \"8 d88\' `88b `888\"\"8P 888 d88( \"8 ");
System.out.println("888 888 888ooo888 `\"Y88b. `\"Y88b. 888ooo888 888 888 `\"Y88b. ");
System.out.println("888 d88\' 888 .o o. )88b o. )88b 888 .o 888 888 . o. )88b ");
System.out.println("o888bood8P\' `Y8bod8P\' 8\"\"888P\' 8\"\"888P\' `Y8bod8P\' d888b \"888\" 8\"\"888P\' ");
try
{
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\tDessert-e-licious. Fresh from our ovens. And Blenders.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tDESSERTS & DRINKS");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t1. CHOCO MOUSSE................69.00");
System.out.println("\t\t\t\t\t(Alternating layers of choco creme and brownie, topped with fresh almonds)");
System.out.println("\t\t\t\t\t2. CHOCO TRUFFLE CAKE..........69.00");
System.out.println("\t\t\t\t\t(Sizzling hot chocolate over a perfectly baked brownie with choco chips on top)");
System.out.println("\t\t\t\t\t3. CHOCO CHIP LAVA.............30.00");
System.out.println("\t\t\t\t\t(Sizzling hot chocolate inside a thick crust cookie with choco chips on top)");
System.out.println("\t\t\t\t\t4. COKE/PEPSI/MIRINDA..........30.00");
System.out.println("\t\t\t\t\t(600 ml, Sold at MRP)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter 1 to order a Dessert or 2 to go back to the order menu -> ");
flag=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(flag==1)
{
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the Item Code of the Dessert you wish to have -> ");
//accept the input in a global variable, say code
code=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(code<1 || code>5)
{
System.out.println("\t\t\t\t\tINVALID ITEM CODE! Please input a valid one.");
continue;
}
break;
}
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the number of such items you would like to order -> ");
//accept the input in a global variable, say number
number=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(number>20)
{
System.out.println("\t\t\t\t\tSorry, but our policy doesn't permit us bulk ordering above 20 Desserts in a single order.");
System.out.println("\t\t\t\t\tPlease consult our website for more information.");
continue;
}
if(number<0)
{
System.out.println("\t\t\t\t\tINVALID NUMBER OF ITEMS! Please input a valid one.");
continue;
}
if(number==0)
{
System.out.println("\t\t\t\t\tYou have to order more than one item!");
continue;
}
break;
}
}
else if(flag==2)
{
ob.order();
}
else
{
System.out.println("\t\t\t\t\tWrong choice!");
continue;
}
break;
}
System.out.print("\f");
System.out.print("ORDERING ");
for(int i=0;i<=6;i++)
{
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.print(". "); k++;
if(k==5)
{
System.out.print("\f");
System.out.print("ORDERING ");
k=0;
}
}
k=0;
ob.calculate();
ob.order();
}
static void meals()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("ooo ooooo oooo ");
System.out.println("`88. .888\' `888 ");
System.out.println(" 888b d\'888 .ooooo. .oooo. 888 .oooo.o ");
System.out.println(" 8 Y88. .P 888 d88\' `88b `P )88b 888 d88( \"8 ");
System.out.println(" 8 `888\' 888 888ooo888 .oP\"888 888 `\"Y88b. ");
System.out.println(" 8 Y 888 888 .o d8( 888 888 o. )88b ");
System.out.println("o8o o888o `Y8bod8P\' `Y888\"\"8o o888o 8\"\"888P\' ");
try
{
Thread.sleep(1000); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2010 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\tOur pizzas for your entire family at reasonable rates.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t\t\t\t\tVALUE MEALS");
System.out.println("\t\t\t\t\t Name Price");
System.out.println("\t\t\t\t\t1. MEAL FOR 1..................199.00");
System.out.println("\t\t\t\t\t(Paneer Birizza + Plain Garlic Bread (2pc) + Pepsi)");
System.out.println("\t\t\t\t\t2. MEAL FOR 2..................449.00");
System.out.println("\t\t\t\t\t(1 Medium Pizza + 1 Garlic Bread + Pepsi)");
System.out.println("\t\t\t\t\t3. MEAL FOR 4..................799.00");
System.out.println("\t\t\t\t\t(2 Medium Pizzas + 1 Garlic Bread + 2 Desserts)");
System.out.println("\t\t\t\t\t\t\t\t\t\t COMBOS");
System.out.println("\t\t\t\t\t4. VEGGIE MAGIC DUO............275.00");
System.out.println("\t\t\t\t\t(Tomato and Corn,Green Capsicum and Corn Onion,Tomato and Green Chillies,Paneer and Green Capsicum)");
System.out.println("\t\t\t\t\t5. NON VEGGIE MAGIC DUO........355.00");
System.out.println("\t\t\t\t\t(Chicken and Green Capsicum,Onion Chicken and Green Chillies,Chicken and Corn, Chicken and Tomato)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter 1 to order a Meal or 2 to go back to the order menu -> ");
flag=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(flag==1)
{
while(true)
{
while(true)
{
try
{
System.out.print("\t\t\t\t\tEnter the Item Code of the Meal you wish to have -> ");
code=Integer.parseInt(in.readLine());
break;
}
catch(NumberFormatException ex)
{
System.out.println("\t\t\t\t\tError!");
System.out.println("\t\t\t\t\tPlease Enter A Valid Number.");
}
}
if(code<1 || code>5)
{
System.out.println("\t\t\t\t\tINVALID ITEM CODE! Please input a valid one.");
continue;
}
break;
}
}
else if(flag==2)
{
ob.order();
}
else
{
System.out.println("\t\t\t\t\tWrong choice!");
continue;
}
break;
}
System.out.print("\f");
System.out.print("ORDERING ");
for(int i=0;i<=6;i++)
{
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.print(". "); k++;
if(k==5)
{
System.out.print("\f");
System.out.print("ORDERING ");
k=0;
}
}
k=0;
number=1;
ob.calculate();
ob.order();
}
static void offers()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2014 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t***************************************************************************************************");
System.out.println("\t\t\t\t\t\t\t\t\t\t\tOFFERS");
System.out.println("\t\t\t\t\t---------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t OFFER COUPON CODE");
System.out.println("\t\t\t\t\tFREE PERSONAL PIZZA ON PURCHASE OF ANY MEDIUM PIZZA..................PHE05");
System.out.println("\t\t\t\t\t(**Offer vaid on Mondays only on Supreme and Signature range of Pizzas.)");
System.out.println("\t\t\t\t\t25% OFF ON BILL OF RS 400 & ABOVE....................................PHE77");
System.out.println("\t\t\t\t\t(**Offer vaid on Mondays only on A-la-cart order basis.)");
System.out.println("\t\t\t\t\tFREE PLAIN GARLIC BREAD ON ANOTHER MEDIUM PIZZA......................PHE76");
System.out.println("\t\t\t\t\t(**Offer vaid on Tuesdays only on Supreme and Signature range of Pizzas.");
System.out.println("\t\t\t\t\tBUY 1 GET 1 FREE ON ANY MEDIUM PIZZA.................................PHE01");
System.out.println("\t\t\t\t\t(**Offer vaid on Fridays and Weekends only on Supreme and Signature range of Pizzas.)");
System.out.println("\t\t\t\t\tBUY ANY MEDIUM PIZZA & GET 50% OFF ON ANOTHER MEDIUM PIZZA...........PHE07");
System.out.println("\t\t\t\t\t(**Offer vaid on Online Orders on Supreme and Signature range of Pizzas.)");
System.out.println("\t\t\t\t\t---------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t***************************************************************************************************");
while(true)
{
System.out.print("\t\t\t\t\tEnter \"back\" to return to the main menu -> ");
String t1=in.readLine();
if(t1.equalsIgnoreCase("back"))
ob.main_menu();
else
{
System.out.println("\t\t\t\t\tWrong Input!");
continue;
}
break;
}
}
static void calculate()throws IOException
{
Boards ob=new Boards();
switch(ord)//order menu choice-5
{
case 1: //pizzas
{
switch(piz)//pizza menu choice-3
{
case 1://magic pan pizzas
{
switch(code)//magic pan pizza choice-14
{
case 1: //TANDOORI PANEER
{
if(size==1)
{
gross+=number*220;
arr[j++]="\t\tTANDOORI PANEER[Personal] "+number+" 220 "+number*220;
}
else if(size==2)
{
gross+=number*395;
arr[j++]="\t\tTANDOORI PANEER[Medium] "+number+" 395 "+number*395;
}
else if(size==3)
{
gross+=number*595;
arr[j++]="\t\tTANDOORI PANEER[Family] "+number+" 595 "+number*595;
}
System.out.println(arr[j]);
}
break;
case 2: //VEGGIE LOVERS
{
if(size==1)
{
gross+=number*220;
arr[j++]="\t\tVEGGIE LOVERS[Personal] "+number+" 220 "+number*220;
}
else if(size==2)
{
gross+=number*395;
arr[j++]="\t\tVEGGIE LOVERS[Medium] "+number+" 395 "+number*395;
}
else if(size==3)
{
gross+=number*595;
arr[j++]="\t\tVEGGIE LOVERS[Family] "+number+" 595 "+number*595;
}
}
break;
case 3: //PANEER MAKHANI
{
if(size==1)
{
gross+=number*220;
arr[j++]="\t\tPANEER MAKHANI[Personal] "+number+" 220 "+number*220;
}
else if(size==2)
{
gross+=number*395;
arr[j++]="\t\tPANEER MAKHANI[Medium] "+number+" 395 "+number*395;
}
else if(size==3)
{
gross+=number*595;
arr[j++]="\t\tPANEER MAKHANI[Family] "+number+" 595 "+number*595;
}
}
break;
case 4: //COUNTRY FEAST
{
if(size==1)
{
gross+=number*220;
arr[j++]="\t\tCOUNTRY FEAST[Personal] "+number+" 220 "+number*220;
}
else if(size==2)
{
gross+=number*395;
arr[j++]="\t\tCOUNTRY FEAST[Medium] "+number+" 395 "+number*395;
}
else if(size==3)
{
gross+=number*595;
arr[j++]="\t\tCOUNTRY FEAST[Family] "+number+" 595 "+number*595;
}
}
break;
case 5: //FIERY RIDE
{
if(size==1)
{
gross+=number*260;
arr[j++]="\t\tFIERY RIDE[Personal] "+number+" 260 "+number*260;
}
else if(size==2)
{
gross+=number*470;
arr[j++]="\t\tFIERY RIDE[Medium] "+number+" 470 "+number*470;
}
else if(size==3)
{
gross+=number*695;
arr[j++]="\t\tFIERY RIDE[Family] "+number+" 695 "+number*695;
}
}
break;
case 6: //PANEER VEGORAMA
{
if(size==1)
{
gross+=number*260;
arr[j++]="\t\tPANEER VEGORAMA[Personal] "+number+" 260 "+number*260;
}
else if(size==2)
{
gross+=number*470;
arr[j++]="\t\tPANEER VEGORAMA[Medium] "+number+" 470 "+number*470;
}
else if(size==3)
{
gross+=number*695;
arr[j++]="\t\tPANEER VEGORAMA[Family] "+number+" 695 "+number*695;
}
}
break;
case 7: //VEGGIE SUPREME
{
if(size==1)
{
gross+=number*260;
arr[j++]="\t\tVEGGIE SUPREME[Personal] "+number+" 260 "+number*260;
}
else if(size==2)
{
gross+=number*470;
arr[j++]="\t\tVEGGIE SUPREME[Medium] "+number+" 470 "+number*470;
}
else if(size==3)
{
gross+=number*695;
arr[j++]="\t\tVEGGIE SUPREME[Family] "+number+" 695 "+number*695;
}
}
break;
case 8: //EXOTICA
{
if(size==1)
{
gross+=number*260;
arr[j++]="\t\tEXOTICA[Personal] "+number+" 260 "+number*260;
}
else if(size==2)
{
gross+=number*470;
arr[j++]="\t\tEXOTICA[Medium] "+number+" 470 "+number*470;
}
else if(size==3)
{
gross+=number*695;
arr[j++]="\t\tEXOTICA[Family] "+number+" 695 "+number*695;
}
}
break;
case 9: //CHICKEN ITALIA
{
if(size==1)
{
gross+=number*250;
arr[j++]="\t\tCHICKEN ITALIA[Personal] "+number+" 250 "+number*250;
}
else if(size==2)
{
gross+=number*450;
arr[j++]="\t\tCHICKEN ITALIA[Medium] "+number+" 450 "+number*450;
}
else if(size==3)
{
gross+=number*655;
arr[j++]="\t\tCHICKEN ITALIA[Family] "+number+" 655 "+number*655;
}
}
break;
case 10: //CHICKEN TIKKA
{
if(size==1)
{
gross+=number*250;
arr[j++]="\t\tCHICKEN TIKKA[Personal] "+number+" 250 "+number*250;
}
else if(size==2)
{
gross+=number*450;
arr[j++]="\t\tCHICKEN TIKKA[Medium] "+number+" 450 "+number*450;
}
else if(size==3)
{
gross+=number*655;
arr[j++]="\t\tCHICKEN TIKKA[Family] "+number+" 655 "+number*655;
}
}
break;
case 11: //KADAI CHICKEN
{
if(size==1)
{
gross+=number*250;
arr[j++]="\t\tKADAI CHICKEN[Personal] "+number+" 250 "+number*250;
}
else if(size==2)
{
gross+=number*450;
arr[j++]="\t\tKADAI CHICKEN[Medium] "+number+" 450 "+number*450;
}
else if(size==3)
{
gross+=number*655;
arr[j++]="\t\tKADAI CHICKEN[Family] "+number+" 655 "+number*655;
}
}
break;
case 12: //PEPPERONI
{
if(size==1)
{
gross+=number*295;
arr[j++]="\t\tPEPPERONI[Personal] "+number+" 295 "+number*295;
}
else if(size==2)
{
gross+=number*515;
arr[j++]="\t\tPEPPERONI[Medium] "+number+" 515 "+number*515;
}
else if(size==3)
{
gross+=number*765;
arr[j++]="\t\tPEPPERONI[Family] "+number+" 765 "+number*765;
}
}
break;
case 13: //TRIPLE CHICKEN FEAST
{
if(size==1)
{
gross+=number*295;
arr[j++]="\t\tTRIPLE CHICKEN FEAST[Personal] "+number+" 295 "+number*295;
}
else if(size==2)
{
gross+=number*515;
arr[j++]="\t\tTRIPLE CHICKEN FEAST[Medium] "+number+" 515 "+number*515;
}
else if(size==3)
{
gross+=number*765;
arr[j++]="\t\tTRIPLE CHICKEN FEAST[Family] "+number+" 765 "+number*765;
}
}
break;
case 14: //CHICKEN SUPREME
{
if(size==1)
{
gross+=number*295;
arr[j++]="\t\tCHICKEN SUPREME[Personal] "+number+" 295 "+number*295;
}
else if(size==2)
{
gross+=number*515;
arr[j++]="\t\tCHICKEN SUPREME[Medium] "+number+" 515 "+number*515;
}
else if(size==3)
{
gross+=number*765;
arr[j++]="\t\tCHICKEN SUPREME[Family] "+number+" 765 "+number*765;
}
}
break;
}
}//end of magic pan pizza - case 1
break;
case 2: //BIG PIZZA
{
switch(code)//big pizza choice-4
{
case 1: //FARM HUT
{
gross+=number*219;
arr[j++]="\t\tFARM HUT[Big Pizza] "+number+" 219 "+number*219;
}
break;
case 2: //ITALIAN TREAT
{
gross+=number*219;
arr[j++]="\t\tITALIAN TREAT[Big Pizza] "+number+" 219 "+number*219;
}
break;
case 3: //CHICKEN MEXICANO
{
gross+=number*219;
arr[j++]="\t\tCHICKEN MEXICANO[Big Pizza] "+number+" 219 "+number*219;
}
break;
case 4: //SPICY CHICKEN MAGIC
{
gross+=number*219;
arr[j++]="\t\tSPICY CHICKEN MAGIC[Big Pizza] "+number+" 219 "+number*219;
}
break;
}
}//end of big pizza - case 2
case 3: //SO CHEESY PIZZAS
{
switch(code)//SO CHEESY PIZZAS choice-4
{
case 1: //VEG TREAT
{
gross+=number*449;
arr[j++]="\t\tVEG TREAT[So Cheezy] "+number+" 449 "+number*449;
}
break;
case 2: //SUPER VEG
{
gross+=number*499;
arr[j++]="\t\tSUPER VEG[So Cheezy] "+number+" 499 "+number*499;
}
break;
case 3: //HOT'N'SPICY CHICKEN
{
gross+=number*499;
arr[j++]="\t\tHOT'N'SPICY CHICKEN[So Cheezy] "+number+" 499 "+number*499;
}
break;
case 4: //DOUBLE CHICKEN FEAST
{
gross+=number*569;
arr[j++]="\t\tDOUBLE CHICKEN FEAST[So Cheezy] "+number+" 569 "+number*569;
}
break;
}
}//end of so cheezy pizza - case 3
break;
}//end of pizza choice
}//end of pizzas
break;
case 2://BIRIZZAS
{
switch(code)//birizza choice-3
{
case 1: //VEGGIE
{
gross+=number*109;
arr[j++]="\t\tVEGGIE BIRIZZA "+number+" 109 "+number*109;
}
break;
case 2: //PANEER
{
gross+=number*145;
arr[j++]="\t\tPANEER BIRIZZA "+number+" 145 "+number*145;
}
break;
case 3: //CHICKEN
{
gross+=number*165;
arr[j++]="\t\tPANEER BIRIZZA "+number+" 165 "+number*165;
}
break;
}
}//end of birizzas
break;
case 3://SIDES
{
switch(code)//sides choice-5
{
case 1: //VEG BAKED PASTA
{
gross+=number*125;
arr[j++]="\t\tVEG BAKED PASTA "+number+" 125 "+number*125;
}
break;
case 2: //CHICKEN BAKED PASTA
{
gross+=number*145;
arr[j++]="\t\tCHICKEN BAKED PASTA "+number+" 145 "+number*145;
}
break;
case 3: //CHICKEN WINGS
{
gross+=number*149;
arr[j++]="\t\tCHICKEN WINGS "+number+" 149 "+number*149;
}
break;
case 4: //GARLIC BREAD STIX
{
gross+=number*99;
arr[j++]="\t\tGARLIC BREAD STIX "+number+" 99 "+number*99;
}
break;
case 5: //POTATO WEDGES
{
gross+=number*89;
arr[j++]="\t\tPOTATO WEDGES "+number+" 89 "+number*89;
}
break;
}
}//end of sides
break;
case 4: //Desserts
{
switch(code)//Desserts choice-4
{
case 1: //CHOCO MOUSSE
{
gross+=number*69;
arr[j++]="\t\tCHOCO MOUSSE "+number+" 69 "+number*69;
}
break;
case 2: //CHOCO TRUFFLE CAKE
{
gross+=number*69;
arr[j++]="\t\tCHOCO TRUFFLE CAKE "+number+" 69 "+number*69;
}
break;
case 3: //CHOCO CHIP LAVA
{
gross+=number*30;
arr[j++]="\t\tCHOCO CHIP LAVA "+number+" 30 "+number*30;
}
break;
case 4: //PEPSI
{
gross+=number*30;
arr[j++]="\t\tPEPSI[600 ml] "+number+" 30 "+number*30;
}
break;
}
}//end of desserts
break;
case 5: //Meals
{
switch(code)//meal choice-5
{
case 1: //MEAL FOR 1
{
gross+=number*199;
arr[j++]="\t\tMEAL FOR 1 "+number+" 199 "+number*199;
}
break;
case 2: //MEAL FOR 2
{
gross+=number*449;
arr[j++]="\t\tMEAL FOR 2 "+number+" 449 "+number*449;
}
break;
case 3: //MEAL FOR 4
{
gross+=number*799;
arr[j++]="\t\tMEAL FOR 4 "+number+" 799 "+number*799;
}
break;
case 4: //VEGGIE MAGIC DUO[combo]
{
gross+=number*275;
arr[j++]="\t\tVEGGIE MAGIC DUO[combo] "+number+" 275 "+number*275;
}
break;
case 5: //NON VEGGIE MAGIC DUO
{
gross+=number*355;
arr[j++]="\t\tNON VEGGIE MAGIC DUO[combo] "+number+" 355 "+number*355;
}
break;
}
}//End of meals
break;
}
}
static void bill()throws IOException
{
Boards ob=new Boards();
Date ob1=new Date();
double stax,vat,total,round;
stax=vat=total=round=0.0;
System.out.println("\f");
System.out.println("\t\t\t\t\tPIZZA HUT INDIA");
System.out.println("\t\t\t\t Devyani International Pvt. Ltd.");
System.out.println("\t\t\t\t\tCinewonder Mall, ");
System.out.println("\t\t\t\t Kapurbavdi,GhodBunder Road,");
System.out.println("\t\t\t\t\tThane (West)-400607.\n");
System.out.println("\t\t\t\t\t ORDER MEMO");
System.out.println("\t\t---------------------------------------------------------------");
System.out.println("\t\tTb1 16/1\t\t chk3000\t\t\t Gst 3");
System.out.println("\t\t\t\t"+ob1);
System.out.println("\t\t---------------------------------------------------------------");
System.out.println("\t\t\t\t\t***DINE IN***");
System.out.println("\t\t Item\t\t\t Quantity Price\t Total");
for(int i=0;i<j;i++)
{
System.out.println(arr[i]);
}
System.out.println("\t\t---------------------------------------------------------------");
System.out.println("\t\t\t\t\t\t SUBTOTAL\t\t"+gross+".00");
System.out.println("\t\t\t\t\tTotal Amount(Before Tax)\t"+gross+".00");
System.out.println("\t\tTax Details----------------------------------------------------");
vat=gross*0.125; vat=Math.rint(vat*100)/100;
System.out.println("\t\t VAT @ 12.5% \t\t\t\t\t"+vat);
System.out.println("\t\t\t\tTotal Amount\t\t\t\t"+(gross+vat));
System.out.println("\t\tService Tax Details--------------------------------------------");
stax=gross*0.05; stax=Math.rint(stax*100)/100;
total=stax+vat+gross;
System.out.println("\t\t Service tax @ 4.944% \t\t\t"+stax);
System.out.println("\t\t\t\tGross Amount\t\t\t\t"+(total));
if(Math.rint(total)>(total))
{
round=Math.rint(total)-total; round=Math.rint(round*100)/100;
System.out.println("\t\t\t\tRounded\t\t\t\t\t"+round);
}
else
{
round=total-Math.rint(total); round=Math.rint(round*100)/100;
System.out.println("\t\t\t\tRounded\t\t\t\t\t"+round);
}
System.out.println("\t\t\t\tBILL AMOUNT\t\t\t\t"+(Math.rint(total))+"0");
System.out.println("\t\t---------------------------------------------------------------\n");
System.out.println("\t\t\t\tEmail ID:devyani@dil-rjcorp.com");
System.out.println("\t\t\t\t Website:www.dil-rjcorp.com");
System.out.println("\t\t\t\t Tel No.:011-4170 6720");
System.out.println("\t\t\t\t Fax No.:011-2681 3665");
System.out.println("\t\t\t\t Thank you foor Choosing Pizza Hut");
System.out.println("\t\t\t\tSee us online at www.pizzahut.co.in");
System.out.println("\t\t\t\t\tHAVE A NICE DAY\n");
System.out.println("\t\t\t **Please collect your bill after payment**");
System.out.println("\t\t---------------------------------------------------------------");
System.out.println("\t\t\t**Take a Survey and Get 15% Off**");
System.out.println("\t\t1. VISIT www.feedPHback.co.in within the next 3 day");
System.out.println("\t\t2. Complete the survey. Use the unique survey ID below");
System.out.println("\t\t---------------------------------------------------------------");
System.out.println("\t\t\t\tDPIJ456-652998476552");
System.out.println("\t\t---------------------------------------------------------------");
System.out.println("\t\t3. Recieve Discount after survey**");
System.out.println("\t\t**Term and Conditions Apply");
System.out.println("\t\t---------------------------------------------------------------");
System.out.println("\t\t************************VISIT AGAIN****************************");
}
static void store_locs()throws IOException
{
Boards ob=new Boards();
System.out.print("\f");
System.out.print("FINDING YOUR LOCATION ");
for(int i=1;i<=5;i++)
{
System.out.print(". ");
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
System.out.print("\f");
System.out.print("COMPUTING STORES IN YOUR CITY - MUMBAI");
for(int i=0;i<=8;i++)
{
try
{
Thread.sleep(500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.out.print(". "); k++;
if(k==5)
{
System.out.print("\f");
System.out.print("COMPUTING STORES IN YOUR CITY - MUMBAI ");
k=0;
}
}
k=0;
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2014 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t***************************************************************************************************");
System.out.println("\t\t\t\t\t\t\t\t\t\tSTORE LOCATIONS");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t1. PH Kandivali ");
System.out.println("\t\t\t\t\t(17 thakur Cinema and welfare centre,Thakur village Kandivali east)");
System.out.println("\t\t\t\t\t2. PH RBD Andheri (E) ");
System.out.println("\t\t\t\t\t(Tandon Mall,Chakala Village, Andheri Kurla Road,Andhetri east)");
System.out.println("\t\t\t\t\t3. PH RBD Cinewonder ");
System.out.println("\t\t\t\t\t(Cinewonder Mall,Kapurbavdi,GhodBunder Road , Thane (West))");
System.out.println("\t\t\t\t\t4. PH RBD Lokhandwala");
System.out.println("\t\t\t\t\t(Grenville Apts,Lokhandwala , Andheri)");
System.out.println("\t\t\t\t\t5. PH RBD Mindspace ");
System.out.println("\t\t\t\t\t(Unit 1, Ground floor,Eureka Towers,Mindspace,malad (West))");
System.out.println("\t\t\t\t\t6. PH RBD Mulund ");
System.out.println("\t\t\t\t\t3rd Floor, Runwal Arcade,LBS Marg, Mulund(West)");
System.out.println("\t\t\t\t\t7. PH RBD Nirmal Mall ");
System.out.println("\t\t\t\t\t(Shop No 20,Ground floor,Nirmal Mall,LBS Marg,Mulund (West))");
System.out.println("\t\t\t\t\t8. PH RBD Powai ");
System.out.println("\t\t\t\t\t(Sentinel,Hiranandani Business Park, Powai)");
System.out.println("\t\t\t\t\t9. PH RBD Profit Centre ");
System.out.println("\t\t\t\t\t(Shop No G3, F2, Profit Centre,,120 feet road, Borsapada)");
System.out.println("\t\t\t\t\t10. PH RBD Sterling ");
System.out.println("\t\t\t\t\t(Elphiston house 17 murzban road,Opp sterling theatre VT)");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t***************************************************************************************************");
while(true)
{
System.out.print("\t\t\t\t\tEnter \"back\" to return to the main menu -> ");
String t1=in.readLine();
if(t1.equalsIgnoreCase("back"))
ob.main_menu();
else
{
System.out.println("\t\t\t\t\tWrong Input!");
continue;
}
break;
}
}
static void feedback()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2014 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t***************************************************************************************************");
System.out.println("\t\t\t\t\t\t\t\t\t\tFEEDBACK");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\tLET US KNOW ABOUT YOUR EXPERIENCE WITH PIZZA HUT.");
System.out.println("\t\t\t\t\tWe value your opinion and welcome your feedback. Kindly answer the following question.");
while(true)
{
System.out.print("\t\t\t\t\tWas your experience at Pizza Hut Satisfactory? yes/no -> ");
String fb=in.readLine();
if(fb.equals("no"))
{
System.out.println("\t\t\t\t\tThanks for your feedback. We are sorry for the unsatisfactory experience.");
System.out.println("\t\t\t\t\tWe will get back to you within 24 hours.");
}
else if(fb.equals("yes"))
{
System.out.println("\t\t\t\t\tThanks for your feedback. Keep Visiting Pizza hut for more good times!");
}
else
{
System.out.println("\t\t\t\t\tWrong Choice!");
continue;
}
break;
}
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t***************************************************************************************************");
while(true)
{
System.out.print("\t\t\t\t\tEnter \"back\" to return to the main menu -> ");
String t1=in.readLine();
if(t1.equalsIgnoreCase("back"))
ob.main_menu();
else
{
System.out.println("\t\t\t\t\tWrong Input!");
continue;
}
break;
}
}
static void exit()throws IOException
{
Boards ob=new Boards();
System.out.println("\f");
System.out.println("\n\n\n");
System.out.println("\t\t\t\t© 2014 Pizza Hut, Inc. All rights reserved. The Pizza Hut name, logos, and related marks are trademarks of Pizza Hut, Inc.\n");
System.out.println("\t\t\t\t\t**************************************************************************************************");
System.out.println("\t\t\t\t\t\t\t\t\t\tEXIT");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\tThanks For visiting.");
System.out.println("\t\t\t\t\tHope you enjoyed this unique experience with us.");
System.out.println("\t\t\t\t\tKeep visiting for more good times.");
System.out.println("\t\t\t\t\t--------------------------------------------------------------------------------------------------");
System.out.println("\t\t\t\t\t**************************************************************************************************");
try
{
Thread.sleep(1500); //1000 milliseconds is one second.
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
System.exit(0);
}
}
|
package com.gaoshin.cloud.web.xen;
/*
* Copyright (c) Citrix Systems, Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
import java.util.Map;
import com.xensource.xenapi.HostPatch;
/**
* The HostPatch.apply() method is deprecated. We'll try to use it. The test is that the
* program will compile, but the compiler will protest.
*/
public class DeprecatedMethod extends TestBase
{
public static void RunTest(ILog logger, TargetServer server) throws Exception
{
TestBase.logger = logger;
try
{
connect(server);
Map<HostPatch, HostPatch.Record> all_recs = HostPatch.getAllRecords(connection);
if (all_recs.size() > 0)
{
logln("Found HostPatches. Applying the first one...");
Map.Entry<HostPatch, HostPatch.Record> first = null;
for (Map.Entry<HostPatch, HostPatch.Record> entry : all_recs.entrySet())
{
first = entry;
break;
}
logln(first.getValue().toString());
first.getKey().apply(connection);
} else
{
logln("There aren't any HostPatches to be applied...");
}
} finally
{
disconnect();
}
}
}
|
/*
* $Id: Volume.java, v 0.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1; you may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is Volume.java
*
* The Initial Developer of the Original Code is PC Automation.
* Portions created by PC Automation are Copyright (C) 2003.
* All Rights Reserved.
*
* Contributor(s):
*
*/
package com.pcauto.util;
import java.util.Locale;
import java.math.BigDecimal;
/** <CODE>Volume</CODE> objects used to hold volume information. Objects
* <CODE>Volume</CODE> can only be instantiated using the {@link VolumeFormat}
* class. A <CODE>Volume</CODE> object's concept of unit is hidden from class
* users, and instead inferred from the formatter class at instantiation.
* <p>
* The baseUnit is used to store the unit with which <CODE>Volume</CODE>
* objects will be printed using the overrided toString() method.
* <p>
* A set of arithmetic operations have been included to compare, add, subtract,
* divide and multiply <CODE>Volume</CODE> objects. Arithmetic operations
* have been designed to be <CODE>null</CODE> safe.
*
* @author $Author: genec $
* @version $Revision: 1.2 $
*/
public class Volume extends Quantity {
protected static VolumeUnits baseUnit = VolumeUnits.CUBIC_METRE;
/** Gets base unit with which <CODE>this</CODE> volume is printed.
*
* @return <CODE>VolumeUnits</CODE> unit with which volumes are printed.
*/
public static VolumeUnits getBaseUnit() {
return baseUnit;
}
/** Sets the "toString" representation of any <CODE>Volume</CODE> objects
* to be of type <CODE>unit</CODE>.
*
* @param <CODE>VolumeUnits</CODE> unit base unit in which all <CODE>Volume</CODE>
* objects will be printed.
*/
public static void setBaseUnit(VolumeUnits unit) {
baseUnit = unit;
}
/** Instance of <CODE>Volume</CODE> with zero value.
*/
public static final Volume ZERO = new Volume(0, baseUnit);
/** Creates new <CODE>Volume</CODE> with an initial value <CODE>double</CODE>
* value and <CODE>VolumeUnits</CODE> unit.
*
* @param quantity <CODE>double</CODE> volume
* @param unit <CODE>VolumeUnits</CODE>
*/
protected Volume(double quantity, VolumeUnits unit){
super(quantity, unit);
setZERO(ZERO);
}
/** Creates new <CODE>Volume</CODE> identical to <CODE>this</CODE>
* <CODE>Volume</CODE>.
*
* @return new <CODE>Volume</CODE> object
*/
public Object clone() {
return new Volume(quantity, (VolumeUnits)unit);
}
/** Compares <CODE>this</CODE> <CODE>Volume</CODE> to the specified
* <CODE>Volume</CODE>.
* The result is <CODE>true</CODE> if and only if the argument is not
* <CODE>null</CODE> and is a <CODE>Volume</CODE> object that has the same
* value. <CODE>Null</CODE> parameter returns false.
*
* @return <CODE>true</CODE> if Volumes are equivalent;
* <CODE>false</CODE> othewise.
* @param quant <CODE>Volume</CODE> with which to compare
*/
public boolean equals(Volume quant) {
return super.equals(quant);
}
/** Compares <CODE>this</CODE> <CODE>Volume</CODE> with the specified
* <CODE>Volume</CODE>. <CODE>Null</CODE> parameter returns 1.
*
* @param quant <CODE>Volume</CODE> object with which to compare.
* @return 0 if they are equal. 1 if <CODE>this</CODE> <CODE>Volume</CODE> is
* larger. -1 if <CODE>this</CODE> <CODE>Volume</CODE> is smaller.
*/
public int compareTo(Volume quant){
return super.compareTo(quant);
}
/** Compares <CODE>this</CODE> <CODE>Volume</CODE> to the specified
* <CODE>Volume</CODE>.
*
* @param quant <CODE>Volume</CODE> object with which to compare.
* @return <CODE>true</CODE> if <CODE>this</CODE> is greater
* than <CODE>quant</CODE>;
* <CODE>false</CODE> otherwise
*/
public boolean greaterThan(Volume quant){
return super.greaterThan(quant);
}
/** Compares <CODE>this</CODE> <CODE>Volume</CODE> to the specified
* <CODE>Volume</CODE>.
*
* @param quant <CODE>Volume</CODE> object with which to compare.
* @return <CODE>true</CODE> if <CODE>this</CODE> is less
* than <CODE>quant</CODE>; <CODE>false</CODE> otherwise
*/
public boolean lessThan(Volume quant){
return super.lessThan(quant);
}
/** Determines if two <CODE>Volume</CODE> objects passed
* to the fuction are equal. Two <CODE>null</CODE> are considered equal.
*
* @param <CODE>Volume</CODE> val1 first value to be compared
* @param <CODE>Volume</CODE> val2 second value to be compared
* @return true if equal, false otherwise
*/
public static boolean areEqual(Volume quant1, Volume quant2){
return Quantity.areEqual(quant1,quant2);
}
/** Adds <CODE>this</CODE> <CODE>Volume</CODE> to the supplied
* <CODE>Volume</CODE>.
* <CODE>Null</CODE> parameter is considered equal to <CODE>Volume</CODE>
* with ZERO quantity.
*
* @param quant <CODE>Volume</CODE> object to add
* @return <CODE>Volume</CODE> object resulting from addition operation
*/
public Volume add(Volume quant){
return (Volume)super.add(quant);
}
/** Adds supplied <CODE>Volume</CODE> to other supplied
* <CODE>Volume</CODE>. <CODE>Null</CODE> parameter(s) is considered
* to be equal to ZERO quantity.
*
* @param a first <CODE>Volume</CODE> object
* @param b second <CODE>Volume</CODE> object
* @return <CODE>Volume</CODE> object resulting from addition of a
* and b in <CODE>Volume</CODE> a's unit
*/
public static Volume add( Volume a, Volume b ) {
Volume retVal = (Volume)Quantity.add(a,b);
if (retVal==null){
retVal=ZERO;
}
return retVal;
}
/** Subtracts supplied <CODE>Volume</CODE> from
* <CODE>this</CODE> <CODE>Volume</CODE>.
* <CODE>Null</CODE> parameter is considered equal to <CODE>Volume</CODE>
* with zero quantity
*
* @param quant <CODE>Volume</CODE> object to subtract
* @return <CODE>Volume</CODE> object resulting from subtraction
* operation in <CODE>this</CODE> unit
*/
public Volume subtract(Volume quant){
return (Volume)super.subtract(quant);
}
/** Divides <CODE>this</CODE> <CODE>Volume</CODE> by supplied
* <CODE>Volume</CODE>.
*
* @throws <CODE>ArithmeticException</CODE> on the attempt
* to divide by <CODE>null</CODE> or zero
* @param quant <CODE>Volume</CODE> object to divide by
* @return <CODE>BigDecimal</CODE> object resulting from division operation
*/
public BigDecimal divide(Volume quant){
return super.divide(quant);
}
/** Multiplies <CODE>this</CODE> <CODE>Volume</CODE> by supplied
* <CODE>BigDecimal</CODE>.
*
* @throws <CODE>ArithmeticException</CODE> on the
* attempt to multiply by <CODE>null</CODE>
* @param quant <CODE>BigDecimal</CODE> object to multiply by
* @return <CODE>Volume</CODE> object resulting from multiplication operation
*/
public Volume multiply(BigDecimal multiplier){
return (Volume)super.myMultiply(multiplier);
}
/** Divides <CODE>this</CODE> <CODE>Volume</CODE> by supplied
* <CODE>BigDecimal</CODE>.
*
* @throws <CODE>ArithmeticException</CODE> on the attempt
* to divide by <CODE>null</CODE> or zero
* @param quant <CODE>BigDecimal</CODE> object to devide by
* @return <CODE>Volume</CODE> object resulting from division operation
*/
public Volume divide(BigDecimal divisor){
return (Volume)super.myDivide(divisor);
}
}
|
package pl.weakpoint.library.controller;
public interface BookRequestMapping {
String BOOK_ROOT = "/book";
String GET_ALL = "/getAll.do";
}
|
package com.appspot.smartshop.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.appspot.smartshop.R;
import com.appspot.smartshop.dom.Attribute;
import com.appspot.smartshop.ui.product.ViewProductUserDefinedAttributeActivity;
import com.appspot.smartshop.utils.Utils;
public class AttributeAdapter extends ArrayAdapter<Attribute> {
public AttributeAdapter(Context context, int textViewResourceId,
Attribute[] objects) {
super(context, textViewResourceId, objects);
inflater = LayoutInflater.from(context);
}
private LayoutInflater inflater;
private static int ATTR_NAME_WIDTH = Utils.getScreenWidth() / 4;
private static int ATTR_VALUE_WIDTH = Utils.getScreenWidth() * 3 / 4;
public AttributeAdapter(Context context, int textViewResourceId,
List<Attribute> objects) {
super(context, textViewResourceId, objects);
inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.attribute_list_item, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
holder.txtValue = (EditText) convertView.findViewById(R.id.txtValue);
holder.txtName.setWidth(ATTR_NAME_WIDTH);
holder.txtValue.setWidth(ATTR_VALUE_WIDTH);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Attribute attr = (Attribute) getItem(position);
holder.txtName.setText(attr.name);
holder.txtValue.setText(attr.value);
// if(ViewProductUserDefinedAttributeActivity.canEdit==false){
// Utils.setEditableEditText(holder.txtValue, false);
//// holder.txtValue.setFilters(Global.uneditableInputFilters);
// }
return convertView;
}
public void addNewAtribute(Attribute attr) {
add(attr);
notifyDataSetChanged();
}
static class ViewHolder {
TextView txtName;
EditText txtValue;
}
}
|
package com.flyusoft.apps.jointoil.dao;
import java.util.Date;
import java.util.List;
import com.flyusoft.apps.jointoil.entity.MonitorData;
import com.flyusoft.apps.jointoil.entity.TwoScrewMachine;
import com.flyusoft.common.dao.BaseDao;
import com.flyusoft.common.orm.Page;
public interface TwoScrewMachineDao extends BaseDao<TwoScrewMachine, String> {
public TwoScrewMachine searchMonitorDataByLastTime(String compressorCode);
public List<TwoScrewMachine> searchDataByCompressorCodeAndTimeInterval(
String _compressorCode, Date _startDate, Date _endDate);
/**
* 取出该对象所有压缩机最后一条记录
*
* @param _compressorNum
* 压缩机数量
*/
public List<TwoScrewMachine> getAllLastTwoScrewMachines(int _compressorNum);
public Page<TwoScrewMachine> getTwoScrewMsg(
Page<TwoScrewMachine> pageMonitor, String compressorCode, Date start_date,
Date end_date);
}
|
package com.srividhyagk.Imdb;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/review")
public class ReviewController {
@Autowired
private ReviewRepository reviewrepo;
@Autowired
private MovieRepository movierepo;
@Autowired
private UserRepository userrepo;
@PostMapping(path = "/comment")
public @ResponseBody String addNewReview(@RequestParam(name = "movieid") int movie_id,
@RequestParam(name = "userid") int user_id, @RequestParam(name = "comment") String comment,
@RequestParam(name = "rating") int rating) {
Reviews r = new Reviews();
r.setMovie_id(movie_id);
r.setUser_id(user_id);
r.setComment(comment);
r.setRating(rating);
reviewrepo.save(r);
return "Saved Review";
}
@GetMapping(path = "/comment")
public @ResponseBody Iterable<Reviews> getAllReviews() {
return reviewrepo.findAll();
}
@GetMapping(path = "/getReview")
public @ResponseBody List<Reviews> getReviewByUsername(String username) {
User u = userrepo.findByUsername(username);
return reviewrepo.findByUser_id(u.getId());
}
@GetMapping(path = "/getReviewByMovieTitle")
public @ResponseBody List<Reviews> getReviewByTitle(String title) {
Movie m = movierepo.findByTitle(title);
return reviewrepo.findByMovie_id(m.getId());
}
@GetMapping(path = "/getReviewByRating")
public @ResponseBody List<Reviews> getReviewByRating(int rating) {
return reviewrepo.findByRating(rating);
}
@GetMapping(path = "/getReviewByCategory")
public @ResponseBody List<Movie> getReviewByCategory(String category) {
List<Movie> ml = movierepo.findByCategory(category);
return ml;
}
@DeleteMapping(path="/deleteReview")
public @ResponseBody String removeReview(int id)
{
reviewrepo.deleteById(id);
return "Review removed";
}
@PutMapping(path="/updateReview")
public ResponseEntity<Object> updateReview(@RequestParam(name="id")int id,@RequestParam(name = "movieid") int movie_id,
@RequestParam(name = "userid") int user_id, @RequestParam(name = "comment") String comment,
@RequestParam(name = "rating") int rating)
{
Optional<Reviews> updatedReview=reviewrepo.findById(id);
if(!updatedReview.isPresent())
{
return ResponseEntity.notFound().build();
}
Reviews r = new Reviews();
r.setMovie_id(movie_id);
r.setUser_id(user_id);
r.setComment(comment);
r.setRating(rating);
r.setId(id);
reviewrepo.save(r);
return ResponseEntity.noContent().build();
}
}
|
package rso.dfs.dummy.generated;
/**
* @generated
*
* */
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO: DELETE THIS SHIT
*
* @deprecated DELETE THIS SHIT
* @generated
*
* */
@Deprecated
public class StorageService {
public interface Iface {
public void putFile(int fileId, List<Byte> body)
throws org.apache.thrift.TException;
public List<Byte> getFile(int fileId)
throws org.apache.thrift.TException;
}
public interface AsyncIface {
public void putFile(int fileId, List<Byte> body,
org.apache.thrift.async.AsyncMethodCallback resultHandler)
throws org.apache.thrift.TException;
public void getFile(int fileId,
org.apache.thrift.async.AsyncMethodCallback resultHandler)
throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient
implements Iface {
public static class Factory implements
org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {
}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot,
org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot) {
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot,
org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public void putFile(int fileId, List<Byte> body)
throws org.apache.thrift.TException {
send_putFile(fileId, body);
recv_putFile();
}
public void send_putFile(int fileId, List<Byte> body)
throws org.apache.thrift.TException {
putFile_args args = new putFile_args();
args.setFileId(fileId);
args.setBody(body);
sendBase("putFile", args);
}
public void recv_putFile() throws org.apache.thrift.TException {
putFile_result result = new putFile_result();
receiveBase(result, "putFile");
return;
}
public List<Byte> getFile(int fileId)
throws org.apache.thrift.TException {
send_getFile(fileId);
return recv_getFile();
}
public void send_getFile(int fileId)
throws org.apache.thrift.TException {
getFile_args args = new getFile_args();
args.setFileId(fileId);
sendBase("getFile", args);
}
public List<Byte> recv_getFile() throws org.apache.thrift.TException {
getFile_result result = new getFile_result();
receiveBase(result, "getFile");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(
org.apache.thrift.TApplicationException.MISSING_RESULT,
"getFile failed: unknown result");
}
}
public static class AsyncClient extends
org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements
org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(
org.apache.thrift.async.TAsyncClientManager clientManager,
org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(
org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager,
transport);
}
}
public AsyncClient(
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.async.TAsyncClientManager clientManager,
org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void putFile(int fileId, List<Byte> body,
org.apache.thrift.async.AsyncMethodCallback resultHandler)
throws org.apache.thrift.TException {
checkReady();
putFile_call method_call = new putFile_call(fileId, body,
resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class putFile_call extends
org.apache.thrift.async.TAsyncMethodCall {
private int fileId;
private List<Byte> body;
public putFile_call(
int fileId,
List<Byte> body,
org.apache.thrift.async.AsyncMethodCallback resultHandler,
org.apache.thrift.async.TAsyncClient client,
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.transport.TNonblockingTransport transport)
throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.fileId = fileId;
this.body = body;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot)
throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(
"putFile",
org.apache.thrift.protocol.TMessageType.CALL, 0));
putFile_args args = new putFile_args();
args.setFileId(fileId);
args.setBody(body);
args.write(prot);
prot.writeMessageEnd();
}
public void getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(
getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client
.getProtocolFactory().getProtocol(memoryTransport);
(new Client(prot)).recv_putFile();
}
}
public void getFile(int fileId,
org.apache.thrift.async.AsyncMethodCallback resultHandler)
throws org.apache.thrift.TException {
checkReady();
getFile_call method_call = new getFile_call(fileId, resultHandler,
this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class getFile_call extends
org.apache.thrift.async.TAsyncMethodCall {
private int fileId;
public getFile_call(
int fileId,
org.apache.thrift.async.AsyncMethodCallback resultHandler,
org.apache.thrift.async.TAsyncClient client,
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.transport.TNonblockingTransport transport)
throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.fileId = fileId;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot)
throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(
"getFile",
org.apache.thrift.protocol.TMessageType.CALL, 0));
getFile_args args = new getFile_args();
args.setFileId(fileId);
args.write(prot);
prot.writeMessageEnd();
}
public List<Byte> getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(
getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client
.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_getFile();
}
}
}
public static class Processor<I extends Iface> extends
org.apache.thrift.TBaseProcessor<I> implements
org.apache.thrift.TProcessor {
private static final Logger LOGGER = LoggerFactory
.getLogger(Processor.class.getName());
public Processor(I iface) {
super(
iface,
getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(
I iface,
Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(
Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("putFile", new putFile());
processMap.put("getFile", new getFile());
return processMap;
}
public static class putFile<I extends Iface> extends
org.apache.thrift.ProcessFunction<I, putFile_args> {
public putFile() {
super("putFile");
}
public putFile_args getEmptyArgsInstance() {
return new putFile_args();
}
protected boolean isOneway() {
return false;
}
public putFile_result getResult(I iface, putFile_args args)
throws org.apache.thrift.TException {
putFile_result result = new putFile_result();
iface.putFile(args.fileId, args.body);
return result;
}
}
public static class getFile<I extends Iface> extends
org.apache.thrift.ProcessFunction<I, getFile_args> {
public getFile() {
super("getFile");
}
public getFile_args getEmptyArgsInstance() {
return new getFile_args();
}
protected boolean isOneway() {
return false;
}
public getFile_result getResult(I iface, getFile_args args)
throws org.apache.thrift.TException {
getFile_result result = new getFile_result();
result.success = iface.getFile(args.fileId);
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends
org.apache.thrift.TBaseAsyncProcessor<I> {
private static final Logger LOGGER = LoggerFactory
.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(
iface,
getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(
I iface,
Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> getProcessMap(
Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("putFile", new putFile());
processMap.put("getFile", new getFile());
return processMap;
}
public static class putFile<I extends AsyncIface> extends
org.apache.thrift.AsyncProcessFunction<I, putFile_args, Void> {
public putFile() {
super("putFile");
}
public putFile_args getEmptyArgsInstance() {
return new putFile_args();
}
public AsyncMethodCallback<Void> getResultHandler(
final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<Void>() {
public void onComplete(Void o) {
putFile_result result = new putFile_result();
try {
fcall.sendResponse(
fb,
result,
org.apache.thrift.protocol.TMessageType.REPLY,
seqid);
return;
} catch (Exception e) {
LOGGER.error(
"Exception writing to internal frame buffer",
e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
putFile_result result = new putFile_result();
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase) new org.apache.thrift.TApplicationException(
org.apache.thrift.TApplicationException.INTERNAL_ERROR,
e.getMessage());
}
try {
fcall.sendResponse(fb, msg, msgType, seqid);
return;
} catch (Exception ex) {
LOGGER.error(
"Exception writing to internal frame buffer",
ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(
I iface,
putFile_args args,
org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler)
throws TException {
iface.putFile(args.fileId, args.body, resultHandler);
}
}
public static class getFile<I extends AsyncIface>
extends
org.apache.thrift.AsyncProcessFunction<I, getFile_args, List<Byte>> {
public getFile() {
super("getFile");
}
public getFile_args getEmptyArgsInstance() {
return new getFile_args();
}
public AsyncMethodCallback<List<Byte>> getResultHandler(
final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new AsyncMethodCallback<List<Byte>>() {
public void onComplete(List<Byte> o) {
getFile_result result = new getFile_result();
result.success = o;
try {
fcall.sendResponse(
fb,
result,
org.apache.thrift.protocol.TMessageType.REPLY,
seqid);
return;
} catch (Exception e) {
LOGGER.error(
"Exception writing to internal frame buffer",
e);
}
fb.close();
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TBase msg;
getFile_result result = new getFile_result();
{
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TBase) new org.apache.thrift.TApplicationException(
org.apache.thrift.TApplicationException.INTERNAL_ERROR,
e.getMessage());
}
try {
fcall.sendResponse(fb, msg, msgType, seqid);
return;
} catch (Exception ex) {
LOGGER.error(
"Exception writing to internal frame buffer",
ex);
}
fb.close();
}
};
}
protected boolean isOneway() {
return false;
}
public void start(
I iface,
getFile_args args,
org.apache.thrift.async.AsyncMethodCallback<List<Byte>> resultHandler)
throws TException {
iface.getFile(args.fileId, resultHandler);
}
}
}
public static class putFile_args implements
org.apache.thrift.TBase<putFile_args, putFile_args._Fields>,
java.io.Serializable, Cloneable, Comparable<putFile_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"putFile_args");
private static final org.apache.thrift.protocol.TField FILE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(
"fileId", org.apache.thrift.protocol.TType.I32, (short) 1);
private static final org.apache.thrift.protocol.TField BODY_FIELD_DESC = new org.apache.thrift.protocol.TField(
"body", org.apache.thrift.protocol.TType.LIST, (short) 2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class,
new putFile_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new putFile_argsTupleSchemeFactory());
}
public int fileId; // required
public List<Byte> body; // required
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
FILE_ID((short) 1, "fileId"), BODY((short) 2, "body");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 1: // FILE_ID
return FILE_ID;
case 2: // BODY
return BODY;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId
+ " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __FILEID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(
_Fields.FILE_ID,
new org.apache.thrift.meta_data.FieldMetaData(
"fileId",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(
org.apache.thrift.protocol.TType.I32, "int")));
tmpMap.put(
_Fields.BODY,
new org.apache.thrift.meta_data.FieldMetaData(
"body",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.ListMetaData(
org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(
org.apache.thrift.protocol.TType.BYTE))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(
putFile_args.class, metaDataMap);
}
public putFile_args() {
}
public putFile_args(int fileId, List<Byte> body) {
this();
this.fileId = fileId;
setFileIdIsSet(true);
this.body = body;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public putFile_args(putFile_args other) {
__isset_bitfield = other.__isset_bitfield;
this.fileId = other.fileId;
if (other.isSetBody()) {
List<Byte> __this__body = new ArrayList<Byte>(other.body);
this.body = __this__body;
}
}
public putFile_args deepCopy() {
return new putFile_args(this);
}
@Override
public void clear() {
setFileIdIsSet(false);
this.fileId = 0;
this.body = null;
}
public int getFileId() {
return this.fileId;
}
public putFile_args setFileId(int fileId) {
this.fileId = fileId;
setFileIdIsSet(true);
return this;
}
public void unsetFileId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield,
__FILEID_ISSET_ID);
}
/**
* Returns true if field fileId is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetFileId() {
return EncodingUtils.testBit(__isset_bitfield, __FILEID_ISSET_ID);
}
public void setFileIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield,
__FILEID_ISSET_ID, value);
}
public int getBodySize() {
return (this.body == null) ? 0 : this.body.size();
}
public java.util.Iterator<Byte> getBodyIterator() {
return (this.body == null) ? null : this.body.iterator();
}
public void addToBody(byte elem) {
if (this.body == null) {
this.body = new ArrayList<Byte>();
}
this.body.add(elem);
}
public List<Byte> getBody() {
return this.body;
}
public putFile_args setBody(List<Byte> body) {
this.body = body;
return this;
}
public void unsetBody() {
this.body = null;
}
/**
* Returns true if field body is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetBody() {
return this.body != null;
}
public void setBodyIsSet(boolean value) {
if (!value) {
this.body = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case FILE_ID:
if (value == null) {
unsetFileId();
} else {
setFileId((Integer) value);
}
break;
case BODY:
if (value == null) {
unsetBody();
} else {
setBody((List<Byte>) value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case FILE_ID:
return Integer.valueOf(getFileId());
case BODY:
return getBody();
}
throw new IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case FILE_ID:
return isSetFileId();
case BODY:
return isSetBody();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof putFile_args)
return this.equals((putFile_args) that);
return false;
}
public boolean equals(putFile_args that) {
if (that == null)
return false;
boolean this_present_fileId = true;
boolean that_present_fileId = true;
if (this_present_fileId || that_present_fileId) {
if (!(this_present_fileId && that_present_fileId))
return false;
if (this.fileId != that.fileId)
return false;
}
boolean this_present_body = true && this.isSetBody();
boolean that_present_body = true && that.isSetBody();
if (this_present_body || that_present_body) {
if (!(this_present_body && that_present_body))
return false;
if (!this.body.equals(that.body))
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
@Override
public int compareTo(putFile_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(
other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetFileId()).compareTo(
other.isSetFileId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetFileId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(
this.fileId, other.fileId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetBody()).compareTo(
other.isSetBody());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetBody()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(
this.body, other.body);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot)
throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot)
throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("putFile_args(");
boolean first = true;
sb.append("fileId:");
sb.append(this.fileId);
first = false;
if (!first)
sb.append(", ");
sb.append("body:");
if (this.body == null) {
sb.append("null");
} else {
sb.append(this.body);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java
// serialization is wacky, and doesn't call the default
// constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class putFile_argsStandardSchemeFactory implements
SchemeFactory {
public putFile_argsStandardScheme getScheme() {
return new putFile_argsStandardScheme();
}
}
private static class putFile_argsStandardScheme extends
StandardScheme<putFile_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot,
putFile_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // FILE_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.fileId = iprot.readI32();
struct.setFileIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(
iprot, schemeField.type);
}
break;
case 2: // BODY
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list0 = iprot
.readListBegin();
struct.body = new ArrayList<Byte>(_list0.size);
for (int _i1 = 0; _i1 < _list0.size; ++_i1) {
byte _elem2;
_elem2 = iprot.readByte();
struct.body.add(_elem2);
}
iprot.readListEnd();
}
struct.setBodyIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(
iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot,
schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot,
putFile_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(FILE_ID_FIELD_DESC);
oprot.writeI32(struct.fileId);
oprot.writeFieldEnd();
if (struct.body != null) {
oprot.writeFieldBegin(BODY_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(
org.apache.thrift.protocol.TType.BYTE,
struct.body.size()));
for (byte _iter3 : struct.body) {
oprot.writeByte(_iter3);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class putFile_argsTupleSchemeFactory implements
SchemeFactory {
public putFile_argsTupleScheme getScheme() {
return new putFile_argsTupleScheme();
}
}
private static class putFile_argsTupleScheme extends
TupleScheme<putFile_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot,
putFile_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetFileId()) {
optionals.set(0);
}
if (struct.isSetBody()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetFileId()) {
oprot.writeI32(struct.fileId);
}
if (struct.isSetBody()) {
{
oprot.writeI32(struct.body.size());
for (byte _iter4 : struct.body) {
oprot.writeByte(_iter4);
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot,
putFile_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.fileId = iprot.readI32();
struct.setFileIdIsSet(true);
}
if (incoming.get(1)) {
{
org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(
org.apache.thrift.protocol.TType.BYTE,
iprot.readI32());
struct.body = new ArrayList<Byte>(_list5.size);
for (int _i6 = 0; _i6 < _list5.size; ++_i6) {
byte _elem7;
_elem7 = iprot.readByte();
struct.body.add(_elem7);
}
}
struct.setBodyIsSet(true);
}
}
}
}
public static class putFile_result implements
org.apache.thrift.TBase<putFile_result, putFile_result._Fields>,
java.io.Serializable, Cloneable, Comparable<putFile_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"putFile_result");
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class,
new putFile_resultStandardSchemeFactory());
schemes.put(TupleScheme.class,
new putFile_resultTupleSchemeFactory());
}
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
;
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId
+ " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(
putFile_result.class, metaDataMap);
}
public putFile_result() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public putFile_result(putFile_result other) {
}
public putFile_result deepCopy() {
return new putFile_result(this);
}
@Override
public void clear() {
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
}
throw new IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof putFile_result)
return this.equals((putFile_result) that);
return false;
}
public boolean equals(putFile_result that) {
if (that == null)
return false;
return true;
}
@Override
public int hashCode() {
return 0;
}
@Override
public int compareTo(putFile_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(
other.getClass().getName());
}
int lastComparison = 0;
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot)
throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot)
throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("putFile_result(");
boolean first = true;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class putFile_resultStandardSchemeFactory implements
SchemeFactory {
public putFile_resultStandardScheme getScheme() {
return new putFile_resultStandardScheme();
}
}
private static class putFile_resultStandardScheme extends
StandardScheme<putFile_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot,
putFile_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot,
schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot,
putFile_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class putFile_resultTupleSchemeFactory implements
SchemeFactory {
public putFile_resultTupleScheme getScheme() {
return new putFile_resultTupleScheme();
}
}
private static class putFile_resultTupleScheme extends
TupleScheme<putFile_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot,
putFile_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot,
putFile_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
}
}
}
public static class getFile_args implements
org.apache.thrift.TBase<getFile_args, getFile_args._Fields>,
java.io.Serializable, Cloneable, Comparable<getFile_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"getFile_args");
private static final org.apache.thrift.protocol.TField FILE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField(
"fileId", org.apache.thrift.protocol.TType.I32, (short) 1);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class,
new getFile_argsStandardSchemeFactory());
schemes.put(TupleScheme.class, new getFile_argsTupleSchemeFactory());
}
public int fileId; // required
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
FILE_ID((short) 1, "fileId");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 1: // FILE_ID
return FILE_ID;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId
+ " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __FILEID_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(
_Fields.FILE_ID,
new org.apache.thrift.meta_data.FieldMetaData(
"fileId",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(
org.apache.thrift.protocol.TType.I32, "int")));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(
getFile_args.class, metaDataMap);
}
public getFile_args() {
}
public getFile_args(int fileId) {
this();
this.fileId = fileId;
setFileIdIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public getFile_args(getFile_args other) {
__isset_bitfield = other.__isset_bitfield;
this.fileId = other.fileId;
}
public getFile_args deepCopy() {
return new getFile_args(this);
}
@Override
public void clear() {
setFileIdIsSet(false);
this.fileId = 0;
}
public int getFileId() {
return this.fileId;
}
public getFile_args setFileId(int fileId) {
this.fileId = fileId;
setFileIdIsSet(true);
return this;
}
public void unsetFileId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield,
__FILEID_ISSET_ID);
}
/**
* Returns true if field fileId is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetFileId() {
return EncodingUtils.testBit(__isset_bitfield, __FILEID_ISSET_ID);
}
public void setFileIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield,
__FILEID_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case FILE_ID:
if (value == null) {
unsetFileId();
} else {
setFileId((Integer) value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case FILE_ID:
return Integer.valueOf(getFileId());
}
throw new IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case FILE_ID:
return isSetFileId();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof getFile_args)
return this.equals((getFile_args) that);
return false;
}
public boolean equals(getFile_args that) {
if (that == null)
return false;
boolean this_present_fileId = true;
boolean that_present_fileId = true;
if (this_present_fileId || that_present_fileId) {
if (!(this_present_fileId && that_present_fileId))
return false;
if (this.fileId != that.fileId)
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
@Override
public int compareTo(getFile_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(
other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetFileId()).compareTo(
other.isSetFileId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetFileId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(
this.fileId, other.fileId);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot)
throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot)
throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("getFile_args(");
boolean first = true;
sb.append("fileId:");
sb.append(this.fileId);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java
// serialization is wacky, and doesn't call the default
// constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class getFile_argsStandardSchemeFactory implements
SchemeFactory {
public getFile_argsStandardScheme getScheme() {
return new getFile_argsStandardScheme();
}
}
private static class getFile_argsStandardScheme extends
StandardScheme<getFile_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot,
getFile_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // FILE_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.fileId = iprot.readI32();
struct.setFileIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(
iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot,
schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot,
getFile_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(FILE_ID_FIELD_DESC);
oprot.writeI32(struct.fileId);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class getFile_argsTupleSchemeFactory implements
SchemeFactory {
public getFile_argsTupleScheme getScheme() {
return new getFile_argsTupleScheme();
}
}
private static class getFile_argsTupleScheme extends
TupleScheme<getFile_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot,
getFile_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetFileId()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetFileId()) {
oprot.writeI32(struct.fileId);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot,
getFile_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.fileId = iprot.readI32();
struct.setFileIdIsSet(true);
}
}
}
}
public static class getFile_result implements
org.apache.thrift.TBase<getFile_result, getFile_result._Fields>,
java.io.Serializable, Cloneable, Comparable<getFile_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"getFile_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(
"success", org.apache.thrift.protocol.TType.LIST, (short) 0);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class,
new getFile_resultStandardSchemeFactory());
schemes.put(TupleScheme.class,
new getFile_resultTupleSchemeFactory());
}
public List<Byte> success; // required
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short) 0, "success");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new IllegalArgumentException("Field " + fieldId
+ " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(
_Fields.SUCCESS,
new org.apache.thrift.meta_data.FieldMetaData(
"success",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.ListMetaData(
org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(
org.apache.thrift.protocol.TType.BYTE))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(
getFile_result.class, metaDataMap);
}
public getFile_result() {
}
public getFile_result(List<Byte> success) {
this();
this.success = success;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public getFile_result(getFile_result other) {
if (other.isSetSuccess()) {
List<Byte> __this__success = new ArrayList<Byte>(other.success);
this.success = __this__success;
}
}
public getFile_result deepCopy() {
return new getFile_result(this);
}
@Override
public void clear() {
this.success = null;
}
public int getSuccessSize() {
return (this.success == null) ? 0 : this.success.size();
}
public java.util.Iterator<Byte> getSuccessIterator() {
return (this.success == null) ? null : this.success.iterator();
}
public void addToSuccess(byte elem) {
if (this.success == null) {
this.success = new ArrayList<Byte>();
}
this.success.add(elem);
}
public List<Byte> getSuccess() {
return this.success;
}
public getFile_result setSuccess(List<Byte> success) {
this.success = success;
return this;
}
public void unsetSuccess() {
this.success = null;
}
/**
* Returns true if field success is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetSuccess() {
return this.success != null;
}
public void setSuccessIsSet(boolean value) {
if (!value) {
this.success = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((List<Byte>) value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof getFile_result)
return this.equals((getFile_result) that);
return false;
}
public boolean equals(getFile_result that) {
if (that == null)
return false;
boolean this_present_success = true && this.isSetSuccess();
boolean that_present_success = true && that.isSetSuccess();
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (!this.success.equals(that.success))
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
@Override
public int compareTo(getFile_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(
other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(
other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(
this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot)
throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot)
throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("getFile_result(");
boolean first = true;
sb.append("success:");
if (this.success == null) {
sb.append("null");
} else {
sb.append(this.success);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out)
throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class getFile_resultStandardSchemeFactory implements
SchemeFactory {
public getFile_resultStandardScheme getScheme() {
return new getFile_resultStandardScheme();
}
}
private static class getFile_resultStandardScheme extends
StandardScheme<getFile_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot,
getFile_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list8 = iprot
.readListBegin();
struct.success = new ArrayList<Byte>(
_list8.size);
for (int _i9 = 0; _i9 < _list8.size; ++_i9) {
byte _elem10;
_elem10 = iprot.readByte();
struct.success.add(_elem10);
}
iprot.readListEnd();
}
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(
iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot,
schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot,
getFile_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.success != null) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(
org.apache.thrift.protocol.TType.BYTE,
struct.success.size()));
for (byte _iter11 : struct.success) {
oprot.writeByte(_iter11);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class getFile_resultTupleSchemeFactory implements
SchemeFactory {
public getFile_resultTupleScheme getScheme() {
return new getFile_resultTupleScheme();
}
}
private static class getFile_resultTupleScheme extends
TupleScheme<getFile_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot,
getFile_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
{
oprot.writeI32(struct.success.size());
for (byte _iter12 : struct.success) {
oprot.writeByte(_iter12);
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot,
getFile_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
{
org.apache.thrift.protocol.TList _list13 = new org.apache.thrift.protocol.TList(
org.apache.thrift.protocol.TType.BYTE,
iprot.readI32());
struct.success = new ArrayList<Byte>(_list13.size);
for (int _i14 = 0; _i14 < _list13.size; ++_i14) {
byte _elem15;
_elem15 = iprot.readByte();
struct.success.add(_elem15);
}
}
struct.setSuccessIsSet(true);
}
}
}
}
}
|
package com.metoo.foundation.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
* <p>
* Title: LuckyDrawInfo.java
* </p>
*
* <p>
* Description: 用户抽奖记录
* </p>
*
* @author Administrator
*
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "lucky_draw_log")
public class LuckyDrawLog extends IdEntity{
private Long user_id;// 用户Id
private String user_name;// 用户名称
private String name;// 奖品名称
private String message;// 奖品描述
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
private Accessory photo;// 奖品图片
public Long getUser_id() {
return user_id;
}
public void setUser_id(Long user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Accessory getPhoto() {
return photo;
}
public void setPhoto(Accessory photo) {
this.photo = photo;
}
}
|
package com.epam.university.spring.model;
import com.epam.university.spring.domain.Show;
import com.epam.university.spring.domain.User;
public interface DiscountStrategy {
Long execute(User user, Show show);
}
|
package inatel.br.nfccontrol.data.typeConverter;
import android.arch.persistence.room.TypeConverter;
import java.sql.Timestamp;
/**
* A Converter for DB to store correctly Timestamp
* Convert timestamp to long and long to timestamp to handle the db structure and app logic
* operations
*
* @author Guilherme Yabu <guilhermeyabu@inatel.br>
* @since 19/03/2018.
*/
public class TimestampTypeConverter {
@TypeConverter
public Long fromTimestamp(Timestamp value) {
return value == null ? null : value.getTime();
}
@TypeConverter
public Timestamp LongToTimestamp(Long value) {
if (value == null) {
return null;
} else {
return new Timestamp(value);
}
}
}
|
package io.core9.plugin.widgets.pagemodel;
import io.core9.core.PluginRegistry;
import io.core9.plugin.admin.AbstractAdminPlugin;
import io.core9.plugin.database.repository.CrudRepository;
import io.core9.plugin.database.repository.NoCollectionNamePresentException;
import io.core9.plugin.database.repository.RepositoryFactory;
import io.core9.plugin.server.HostManager;
import io.core9.plugin.server.VirtualHost;
import io.core9.plugin.server.request.Request;
import io.core9.plugin.widgets.exceptions.ComponentDoesNotExists;
import io.core9.plugin.widgets.widget.WidgetAdminPlugin;
import java.util.ArrayList;
import java.util.List;
import net.xeoh.plugins.base.Plugin;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.events.PluginLoaded;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
import org.apache.commons.lang3.ClassUtils;
@PluginImplementation
public class PageModelAdminPluginImpl extends AbstractAdminPlugin implements PageModelAdminPlugin {
private PluginRegistry registry;
private List<PageModel> codeModels = new ArrayList<PageModel>();
@InjectPlugin
private PageModelFactory factory;
@InjectPlugin
private HostManager hostManager;
private CrudRepository<PageModelImpl> repository;
@InjectPlugin
private WidgetAdminPlugin widgetAdmin;
@PluginLoaded
public void onRepositoryFactory(RepositoryFactory factory) throws NoCollectionNamePresentException {
this.repository = factory.getRepository(PageModelImpl.class);
}
@Override
public String getControllerName() {
return "pagemodel";
}
@Override
protected void process(Request request) {
switch(request.getMethod()) {
case POST:
VirtualHost vhost = request.getVirtualHost();
factory.clear(vhost);
factory.registerAll(vhost, codeModels);
factory.registerAll(vhost, getDataModels(vhost));
try {
factory.processVhost(vhost);
request.getResponse().end("Success");
} catch (ComponentDoesNotExists e) {
request.getResponse().setStatusCode(500);
request.getResponse().addValue("error", e.getMessage());
}
break;
default:
request.getResponse().setStatusCode(404);
request.getResponse().end();
}
}
@Override
protected void process(Request request, String type) {}
@Override
protected void process(Request request, String type, String id) {}
private List<? extends PageModel> getDataModels(VirtualHost vhost) {
return repository.getAll(vhost);
}
@Override
public void processPlugins() {
for(Plugin plugin : this.registry.getPlugins()) {
List<Class<?>> interfaces = ClassUtils.getAllInterfaces(plugin.getClass());
if(interfaces.contains(PageModelProvider.class)) {
codeModels.addAll(((PageModelProvider) plugin).getPageModels());
}
}
}
@Override
public void setRegistry(PluginRegistry registry) {
this.registry = registry;
}
@Override
public Integer getPriority() {
return 2520;
}
@Override
public void addVirtualHost(VirtualHost vhost) {
widgetAdmin.addVirtualHost(vhost);
factory.registerAll(vhost, codeModels);
factory.registerAll(vhost, getDataModels(vhost));
try {
factory.processVhost(vhost);
} catch (ComponentDoesNotExists e) {
e.printStackTrace();
}
}
@Override
public void removeVirtualHost(VirtualHost vhost) {
widgetAdmin.removeVirtualHost(vhost);
factory.clear(vhost);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.