text stringlengths 10 2.72M |
|---|
package mekfarm.capabilities;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
/**
* Created by CF on 2016-11-10.
*/
public interface IFilterHandler extends IItemHandler {
boolean acceptsFilter(int slot, ItemStack filter);
}
|
package tr.org.lkd.lyk2015.sampleservlet;
import java.io.IOException;
import java.util.Calendar;
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(urlPatterns = {"/test","/init"})
public class TestServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
Todo t1 = new Todo("test1","test1",Calendar.getInstance(),false);
Todo t2 = new Todo("test2","test2",Calendar.getInstance(),false);
Todo t3 = new Todo("test3","test3",Calendar.getInstance(),true);
Todo t4 = new Todo("test4","test4",Calendar.getInstance(),false);
Storage.getInstance().add(t1);
Storage.getInstance().add(t2);
Storage.getInstance().add(t3);
Storage.getInstance().add(t4);
System.out.println("test created");
resp.sendRedirect("list");
}
}
|
package com.bofsoft.laio.customerservice.DataClass.db;
import com.bofsoft.laio.data.BaseData;
/**
* 学员状态基础表
*
* @author admin
*/
public class StuStatusData extends BaseData {
public int Id;
public String MC; // 状态名称
public String Unit; // 展示单位
public int SeqType; // 展示顺序
public int IsDel;
public StuStatusData() {
}
public StuStatusData(int id, String mC, String unit, int seqType, int isDel) {
super();
Id = id;
MC = mC;
Unit = unit;
SeqType = seqType;
IsDel = isDel;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getMC() {
return MC;
}
public void setMC(String mC) {
MC = mC;
}
public String getUnit() {
return Unit;
}
public void setUnit(String unit) {
Unit = unit;
}
public int getSeqType() {
return SeqType;
}
public void setSeqType(int seqType) {
SeqType = seqType;
}
public int getIsDel() {
return IsDel;
}
public void setIsDel(int isDel) {
IsDel = isDel;
}
@Override
public String toString() {
return "StuStatusData [Id=" + Id + ", MC=" + MC + ", Unit=" + Unit + ", SeqType=" + SeqType
+ ", IsDel=" + IsDel + "]";
}
}
|
// Solution is based on binary search.
// I code didn't work, and this is closest to my code from discussion forums.
public class Solution {
public int mySqrt(int x) {
if (x == 0) return 0;
int left = 1, right = x;
while (true) {
int mid = left + (right - left)/2;
if (mid > x/mid) {
right = mid - 1;
} else {
if (mid + 1 > x/(mid + 1))
return mid;
left = mid + 1;
}
}
}
}
|
package views;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import connections.ClientServerConnection;
import listeners.InspectSubmitListener;
import listeners.NextButtonListener;
/**
* InspectionAuthenticationView will be displayed whenever the user tries to continue on to
* the next step of a POUI and the current step requires a level three inspection to be
* completed. Once inspection is completed the user will have to enter the identifying
* number assigned to them, which will be logged to the server and stored.
* @author jameschapman
*/
public class InspectionAuthenticationView {
/**
* The frame that will contain the pane to input identifying code
*/
private JFrame mainFrame;
/**
* Next button so that this view can initiate the changing of images once the user has entered
* their stamp ID
*/
private NextButtonListener nextListener;
/**
* A connection with the server for authenticate a user is allowed to perform a level 3 inspection.
*/
private ClientServerConnection connection;
/**
* The current step number that is being checked
*/
private int currentStep;
/**
* The product ID that the inspect is being authenticated for
*/
private String productID;
/**
* Creates new instance of the inspection view, and displays in in the middle of the display.
*/
public InspectionAuthenticationView(NextButtonListener nextListener, ClientServerConnection connection, int currentStep, String productID) {
this.nextListener = nextListener;
this.connection = connection;
this.currentStep = currentStep;
this.productID = productID;
mainFrame = new JFrame("Inspection");
mainFrame.add(createPanel());
mainFrame.pack();
mainFrame.setAlwaysOnTop(true);
mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
mainFrame.setLocation(dim.width/2-mainFrame.getSize().width/2, dim.height/2-mainFrame.getSize().height/2);
}
/**
* Creates the panel that will contain the text field and submit button for entering
* identifying number.
* @return The populated panel to be added to Frame and displayed.
*/
private JPanel createPanel() {
JPanel mainPanel = new JPanel();
JTextField stampField = new JTextField("Stamp ID");
stampField.addActionListener(new InspectSubmitListener(this, stampField, connection, currentStep, productID));
mainPanel.add(stampField);
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(new InspectSubmitListener(this, stampField, connection, currentStep, productID));
mainPanel.add(submitButton);
return mainPanel;
}
/**
* Displays the next image for the current POUI, if there is one.
*/
public void displayNext() {
this.nextListener.displayNext();
}
/**
* Displays the next image after the server inspection authentication
*/
public void displayNextAfterAuthentication() {
this.nextListener.displayNextAfterAuthentication();
}
public void setVisible() {
mainFrame.setVisible(true);
}
public void hideFrame() {
mainFrame.setVisible(false);
}
}
|
package github.dwstanle.tickets.search;
import github.dwstanle.tickets.SeatMap;
import github.dwstanle.tickets.model.Seat;
import org.springframework.stereotype.Component;
import java.util.Optional;
import java.util.Set;
@Component
public class SimpleTicketSearchEngine implements TicketSearchEngine {
@Override
public Optional<Set<Seat>> findBestAvailable(int requestedNumberOfSeats, SeatMap seatMap) {
Generator generate = new LeftFillGenerator(requestedNumberOfSeats, seatMap);
Evaluator evaluate = new SimpleEvaluator(requestedNumberOfSeats, seatMap);
return evaluate.findBest(generate.findAllSolutions());
}
@Override
public Optional<Set<Seat>> findFirstAvailable(int requestedNumberOfSeats, SeatMap seatMap) {
throw new UnsupportedOperationException("Placeholder. Not yet implemented.");
}
} |
package com.techelevator.npgeek.model.survey;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class IOStreamSurveyDAO implements SurveyDAO {
private SurveyDataStreamProvider dataStreamProvider;
@Autowired
public IOStreamSurveyDAO(SurveyDataStreamProvider dataStreamProvider) {
this.dataStreamProvider = dataStreamProvider;
}
@Override
public void saveAnswer(String answer) {
Map<String, Integer> records = getAllVotes();
try (PrintWriter writer = new PrintWriter(dataStreamProvider.getOutputStream())) {
if (records.containsKey(answer)) {
int count = records.get(answer);
records.put(answer, count + 1);
} else {
records.put(answer, 1);
}
for(String key : records.keySet()) {
writer.println(key + "|" + records.get(key));
}
}
}
@Override
public Map<String, Integer> getAllVotes() {
Map<String, Integer> results = new HashMap<>();
try(Scanner scanner = new Scanner(dataStreamProvider.getInputStream())) {
while(scanner.hasNextLine()) {
SurveyRecord record = new SurveyRecord(scanner.nextLine());
results.put(record.getAnswer(), record.getVoteCount());
}
}
return results;
}
}
|
package com.cbs.edu.spring.decoupled_spring;
public interface MessageProvider {
String getMessage();
}
|
package com.example.isufdeliu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class DataRegister extends Activity {
String selectedGender;
SQLiteDatabase mDb;
int mID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_register);
selectedGender = "Male";
fillSpinners();
// getting ID from previous Activity
Intent getId = getIntent();
mID = getId.getIntExtra("ID", 0);
createTable(mDb);
Button b = (Button) findViewById(R.id.bView);
b.setEnabled(false);
}
/*
* Saving state using shared preferences
*/
@Override
public void onPause() {
super.onPause();
SharedPreferences shPreference = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = shPreference.edit();
EditText _Name = (EditText) findViewById(R.id.etxtName);
EditText _Surname = (EditText) findViewById(R.id.etxtSurname);
EditText _Age = (EditText) findViewById(R.id.etxtAge);
EditText _Country = (EditText) findViewById(R.id.etxtCountry);
Spinner _Education = (Spinner) findViewById(R.id.Education);
Spinner _Status = (Spinner) findViewById(R.id.CheckStatus);
String Name = _Name.getText().toString();
String Surname = _Surname.getText().toString();
String Age = _Age.getText().toString();
String Country = _Country.getText().toString();
int Education = (int) _Education.getSelectedItemId();
int Status = (int) _Status.getSelectedItemId();
editor.putString("Name", Name);
editor.putString("Surname", Surname);
editor.putString("Age", Age);
editor.putString("Country", Country);
editor.putInt("Status", Status);
editor.putInt("Education", Education);
editor.commit();
}
/*
*
* Getting saved info.
*/
@Override
public void onResume() {
super.onResume();
SharedPreferences shPreference = PreferenceManager
.getDefaultSharedPreferences(this);
EditText _Name = (EditText) findViewById(R.id.etxtName);
EditText _Surname = (EditText) findViewById(R.id.etxtSurname);
EditText _Age = (EditText) findViewById(R.id.etxtAge);
EditText _Country = (EditText) findViewById(R.id.etxtCountry);
Spinner _Status = (Spinner) findViewById(R.id.CheckStatus);
Spinner _Education = (Spinner) findViewById(R.id.Education);
String Name = shPreference.getString("Name", "");
String Surname = shPreference.getString("Surname", "");
String Age = shPreference.getString("Age", "0");
String Country = shPreference.getString("Country", "");
int Status = shPreference.getInt("Status", 0);
int Education = shPreference.getInt("Education", 0);
_Name.setText(Name);
_Surname.setText(Surname);
_Age.setText(Age);
_Country.setText(Country);
_Status.setSelection(Status);
_Education.setSelection(Education);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.data_register, menu);
return true;
}
public void selectGender(View v) {
switch (v.getId()) {
case R.id.genderMale:
selectedGender = "Male";
break;
case R.id.genderFemale:
selectedGender = "Female";
break;
}
Toast.makeText(this, selectedGender, Toast.LENGTH_SHORT).show();
}
public void fillSpinners() {
String[] array_Status = new String[] { "Single", "Married", "Engaged",
"Divorced", "In a relationship" };
String[] array_Education = new String[] { "Primary school",
"High school", "Bachelor Studies", "Master Studies", "PhD" };
Spinner status = (Spinner) findViewById(R.id.CheckStatus);
Spinner education = (Spinner) findViewById(R.id.Education);
ArrayAdapter checkStatus = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_Status);
status.setAdapter(checkStatus);
ArrayAdapter fillEducation = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, array_Education);
education.setAdapter(fillEducation);
}
public void Save(View v) {
Button b = (Button) findViewById(R.id.bView);
b.setEnabled(true);
EditText _Name = (EditText) findViewById(R.id.etxtName);
EditText _Surname = (EditText) findViewById(R.id.etxtSurname);
EditText _Age = (EditText) findViewById(R.id.etxtAge);
EditText _Country = (EditText) findViewById(R.id.etxtCountry);
Spinner _Status = (Spinner) findViewById(R.id.CheckStatus);
Spinner _Education = (Spinner) findViewById(R.id.Education);
try {
String Name = _Name.getText().toString();
String Surname = _Surname.getText().toString();
String Status = _Status.getSelectedItem().toString();
String Education = _Education.getSelectedItem().toString();
String Country = _Country.getText().toString();
int Age = Integer.parseInt(_Age.getText().toString());
String saveQuery = "INSERT INTO tblInfo VALUES" + "(" + mID + ",'"
+ Name + "','" + Surname + "'," + Age + ",'"
+ selectedGender + "','" + Status + "','" + Education
+ "','" + Country + "')";
mDb = openOrCreateDatabase("registration.db", MODE_PRIVATE, null);
mDb.execSQL(saveQuery);
showAlertMessage("Dear " + _Name.getText()
+ " thank you for registration");
_Name.setText("");
_Surname.setText("");
_Age.setText("");
_Country.setText("");
Intent regCountry = new Intent(DataRegister.this, ShowResults.class);
startActivity(regCountry);
} catch (Exception ex) {
showAlertMessage(ex.getMessage());
}
}
public void createTable(SQLiteDatabase db) {
try {
db = openOrCreateDatabase("registration.db", MODE_PRIVATE, null);
String Query = "CREATE TABLE IF NOT EXISTS tblInfo("
+ "ID INT PRIMARY KEY,Name Varchar,Surname Varchar,"
+ "Age int,Gender Varchar,Status Varchar,Education Varchar"
+ ",Country Varchar)";
db.execSQL(Query);
} catch (Exception ex) {
showAlertMessage("Error: " + ex.getMessage());
}
}
public void showAlertMessage(String msg) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(msg);
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
public void Continue(View v) {
Intent goToReg = new Intent(DataRegister.this, ShowResults.class);
startActivity(goToReg);
}
} |
package com.example.iit.materialdesign.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.example.iit.materialdesign.model.Comment;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IIT on 4/8/2015.
*/
public class MyDB {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = {MySQLiteHelper.COLUMN_NAME, MySQLiteHelper.COLUMN_FLUX };
private String search;
Cursor cursor = null;
public MyDB(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Comment createComment(String name, String flux) {
Log.e("MyDB", name + " "+flux);
ContentValues values = new ContentValues();
// values.put(MySQLiteHelper.COLUMN_ID, i);
values.put(MySQLiteHelper.COLUMN_NAME, name);
values.put(MySQLiteHelper.COLUMN_FLUX, flux);
long insertId = database.insert(MySQLiteHelper.TABLE_FABOURITE, null,
values);
// Log
// String insertId
Cursor cursor = database.query(MySQLiteHelper.TABLE_FABOURITE,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Comment newComment = cursorToComment(cursor);
cursor.close();
return newComment;
}
public void deleteComment(String starName) {
database.delete(MySQLiteHelper.TABLE_FABOURITE, MySQLiteHelper.COLUMN_NAME
+ " = " + starName, null);
}
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
cursor = database.query(MySQLiteHelper.TABLE_FABOURITE,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
// comment.setId(cursor.getLong(0));
comment.setStarName(cursor.getString(0));
comment.setStarFlux(cursor.getString(1));
Log.e("CursortoComment", cursor.getString(1));
return comment;
}
// public Comment searchData(int id){
// search = "SELECT * FROM "+MySQLiteHelper.TABLE_FABOURITE +" WHERE " + MySQLiteHelper.COLUMN_ID + " = "
// Cursor cursor = database.query(MySQLiteHelper.TABLE_FABOURITE, MySQLiteHelper.COLUMN_ID
// + " = " + id, null);
// }
}
|
/**
* @Author: Mahmoud Abdelrahman
* Teacher Validator class is where the code responsible for implementing the teacher validator methods
* implemented.
* Extends the BaseValidator class.
*/
package com.easylearn.easylearn.validation;
import com.easylearn.easylearn.entity.Teacher;
import com.easylearn.easylearn.repository.TeacherRepository;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Log4j2
@Component
public class TeacherValidator extends BaseValidator<Teacher> {
private TeacherRepository teacherRepository;
@Autowired
public TeacherValidator(TeacherRepository teacherRepository) {
super(Teacher.class);
this.teacherRepository = teacherRepository;
}
}
|
// **********************************************************
// 1. 제 목:
// 2. 프로그램명: CommunityMsMenuBean.java
// 3. 개 요:
// 4. 환 경: JDK 1.3
// 5. 버 젼: 0.1
// 6. 작 성: Administrator 2003-08-29
// 7. 수 정:
//
// **********************************************************
package com.ziaan.community;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import com.ziaan.library.DBConnectionManager;
import com.ziaan.library.DataBox;
import com.ziaan.library.ErrorManager;
import com.ziaan.library.FormatDate;
import com.ziaan.library.ListSet;
import com.ziaan.library.RequestBox;
import com.ziaan.library.SQLString;
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window > Preferences > Java > Code Generation > Code and Comments
*/
public class CommunityMsMenuBean {
// private ConfigSet config;
// private static int row=10;
// private String v_type = "PQ";
// private static final String FILE_TYPE = "p_file"; // 파일업로드되는 tag name
// private static final int FILE_LIMIT = 1; // 페이지에 세팅된 파일첨부 갯수
public CommunityMsMenuBean() {
try {
// config = new ConfigSet();
// row = Integer.parseInt(config.getProperty("page.bulletin.row") ); // 이 모듈의 페이지당 row 수를 셋팅한다
// row = 10; // 강제로 지정
}
catch( Exception e ) {
e.printStackTrace();
}
}
/**
메뉴명 중복체크 조회
@param box receive from the form object and session
@return int row count
*/
public int selectCmuNmRowCnt(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
// ArrayList list = new ArrayList();
ListSet ls = null;
String sql = "";
int iRowCnt=0;
try {
connMgr = new DBConnectionManager();
sql = " select count(*) rowcnt"
+ " from tz_cmumenu "
+ " where cmuno = '" +box.getStringDefault("p_cmuno","") + "'"
+ " and brd_fg ='" +box.getStringDefault("p_brd_fg","") + "'"
+ " and title = " + SQLString.Format(box.getStringDefault("p_title",""))
;
ls = connMgr.executeQuery(sql);
System.out.println(sql);
while ( ls.next() ) {
iRowCnt = ls.getInt("rowcnt");
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return iRowCnt;
}
/**
* 커뮤니티 메뉴정보
* @param box receive from the form object and session
* @return ArrayList 커뮤니티 메뉴정보
* @throws Exception
*/
public String getSingleColumn(RequestBox box,String v_cmuno,String v_menuno,String v_column) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
// ArrayList list = new ArrayList();
String sql = "";
// DataBox dbox = null;
String v_ret = "";
try {
connMgr = new DBConnectionManager();
sql = "\n select " +v_column
+ "\n from tz_cmumenu"
+ "\n where cmuno = '" +v_cmuno + "'"
+ "\n and menuno = '" +v_menuno + "'";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
v_ret = ls.getString(1);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return v_ret;
}
/**
* 커뮤니티 메뉴테이블 칼럼정보
* @param box receive from the form object and session
* @return ArrayList 커뮤니티 메뉴테이블 칼럼정보
* @throws Exception
*/
public String getSingleColumn1(String v_cmuno,String v_menuno,String v_column) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
// ArrayList list = new ArrayList();
String sql = "";
// DataBox dbox = null;
String v_ret = "";
try {
connMgr = new DBConnectionManager();
sql = "\n select " +v_column
+ "\n from tz_cmumenu"
+ "\n where cmuno = '" +v_cmuno + "'"
+ "\n and menuno = '" +v_menuno + "'";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
v_ret = ls.getString(1);
}
}
catch ( Exception ex ) {
// ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return v_ret;
}
/**
* 커뮤니티 메뉴리스트
* @param box receive from the form object and session
* @return ArrayList 커뮤니티 메뉴리스트
* @throws Exception
*/
public ArrayList selectleftList(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = new ArrayList();
String sql = "";
// String sql1 = "";
// String sql2 = "";
DataBox dbox = null;
// String v_static_cmuno = box.getString("p_static_cmuno");
String v_cmuno = box.getString("p_cmuno");
String v_brd_fg = box.getStringDefault("p_brd_fg","2");
// String s_userid = box.getSession("userid");
// String s_name = box.getSession("name");
try {
connMgr = new DBConnectionManager();
// sql = "\n select a.*,rownum rowseq from ("
sql = "\n select cmuno, menuno, title, read_cd, write_cd, arrange, fileadd_fg,filecnt "
+ "\n , directory_FG, directory_memo,brd_fg, root, parent, lv, position,limit_list"
+ "\n , register_userid, register_dte, modifier_userid "
+ "\n , modifier_dte, del_fg "
+ "\n from tz_cmumenu "
+ "\n where cmuno = '" +v_cmuno + "'"
+ "\n and brd_fg = '" +v_brd_fg + "'"
+ "\n and del_fg ='N'"
+ "\n order by root asc,position asc, lv asc";
// + "\n ) a";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
* 커뮤니티 메뉴정보
* @param box receive from the form object and session
* @return ArrayList 커뮤니티 메뉴리정보
* @throws Exception
*/
public ArrayList selectSingleMenu(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = new ArrayList();
String sql = "";
// String sql1 = "";
// String sql2 = "";
DataBox dbox = null;
// String v_static_cmuno = box.getString("p_static_cmuno");
String v_cmuno = box.getString("p_cmuno");
String v_menuno = box.getString("p_menuno");
// String v_brd_fg = box.getStringDefault("p_brd_fg","2");
// String s_userid = box.getSession("userid");
// String s_name = box.getSession("name");
try {
connMgr = new DBConnectionManager();
sql = "\n select cmuno, menuno, title, read_cd, write_cd, arrange, fileadd_fg,filecnt "
+ "\n , directory_FG, directory_memo,brd_fg, root, parent, lv, position,limit_list"
+ "\n , register_userid, register_dte, modifier_userid "
+ "\n , modifier_dte, del_fg "
+ "\n from tz_cmumenu "
+ "\n where cmuno = '" +v_cmuno + "'"
+ "\n and menuno = '" +v_menuno + "'"
+ "\n and del_fg ='N'";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
* 커뮤니티 메뉴리스트
* @param box receive from the form object and session
* @return ArrayList 커뮤니티 메뉴리스트
* @throws Exception
*/
public ArrayList selectleftCbxList(String v_cmuno,String v_brd_fg) throws Exception {
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = new ArrayList();
String sql = "";
// String sql1 = "";
// String sql2 = "";
DataBox dbox = null;
try {
connMgr = new DBConnectionManager();
// sql = "\n select a.*,rownum rowseq from ( "
sql = "\n select cmuno, menuno, title, read_cd,read_cd readcd,write_cd, arrange, fileadd_fg,filecnt "
+ "\n , directory_FG, directory_memo,brd_fg, root, parent, lv, position,limit_list"
+ "\n , register_userid, register_dte, modifier_userid "
+ "\n , modifier_dte, del_fg "
+ "\n from tz_cmumenu "
+ "\n where cmuno = '" +v_cmuno + "'"
+ "\n and brd_fg = '" +v_brd_fg + "'"
+ "\n and del_fg ='N'"
+ "\n order by root asc,position asc, lv asc";
// + "\n ) a";
// System.out.println("=====커뮤니티 메뉴리스트========");
// System.out.println(sql);
// System.out.println("=======selectleftCbxList==============");
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
dbox = ls.getDataBox();
list.add(dbox);
}
}
catch ( Exception ex ) {
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return list;
}
/**
* 메뉴등록하기
* @param box receive from the form object and session
* @return isOk 1:insert success,0:insert fail
* @throws Exception
*/
public int insertMenu(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
String sql = "";
int isOk1 = 1;
int isOk2 = 1;
// int v_seq = 0;
int v_menuno = 0;
// String v_static_cmuno = box.getString("p_static_cmuno");
String v_cmuno = box.getString("p_cmuno");
String v_brd_fg = box.getStringDefault("p_brd_fg","1");
int v_ins_position = box.getInt("p_ins_position");
String s_userid = box.getSession("userid");
// String s_name = box.getSession("name");
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
sql =" update tz_cmumenu set position = position +1"
+ " where cmuno = ?"
+ " and brd_fg = ?"
+ " and position > ?"
;
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1, v_cmuno );
pstmt.setString(2, v_brd_fg );
pstmt.setInt (3, v_ins_position );
pstmt.executeUpdate();
if ( pstmt != null ) { pstmt.close(); }
sql = "select nvl(max(menuno), 0) from tz_cmumenu where cmuno = '" +v_cmuno + "'";
ls = connMgr.executeQuery(sql);
while ( ls.next() ) {
v_menuno = ls.getInt(1) + 1;
}
sql =" insert into tz_cmumenu ( cmuno ,menuno ,title ,read_cd "
+ " ,write_cd ,arrange ,fileadd_fg ,filecnt "
+ " ,directory_fg ,directory_memo ,brd_fg ,root ,parent "
+ " ,lv ,position ,limit_list ,register_userid,register_dte "
+ " ,modifier_userid,modifier_dte ,del_fg )"
+ " values (?,?,?,?"
+ " ,?,?,?,?"
+ " ,?,?,?,?,?"
+ " ,?,?,?,?,to_char(sysdate,'YYYYMMDDHH24MISS')"
+ " ,?,to_char(sysdate,'YYYYMMDDHH24MISS'),'N')"
;
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1 , v_cmuno );// 커뮤니팁먼호
pstmt.setInt (2 , v_menuno );// 메뉴일련번호
pstmt.setString(3 , box.getString("p_ins_title" ) );// 제목
pstmt.setString(4 , box.getString("p_ins_read_cd" ) );// 읽기권한
pstmt.setString(5 , box.getString("p_ins_write_cd" ) );// 쓰기권한
pstmt.setString(6 , "title" );// 정렬
pstmt.setString(7 , "N" );// 파일첨부구분
pstmt.setInt (8 , 0 );// 첨부파일갯수
pstmt.setString(9 , box.getString("p_ins_directory_fg") );// 디렉토리구분
pstmt.setString(10, box.getString("p_ins_directory_memo" ));
pstmt.setString(11, box.getString("p_brd_fg" ) );// 자료실구분
if ( box.getInt("p_lv" ) +1 == 1) {
pstmt.setInt (12, v_menuno );//
pstmt.setInt (13, v_menuno );//
} else {
pstmt.setInt (12, box.getInt("p_root" ) );//
pstmt.setInt (13, box.getInt("p_menuno" ) );//
}
pstmt.setInt (14, box.getInt("p_lv" ) +1 );//
pstmt.setInt (15, box.getInt("p_position" ) +1 );//
pstmt.setString (16, box.getString("p_ins_limit_list" ));//
pstmt.setString(17, s_userid);// 게시자
pstmt.setString(18, s_userid );// 수정자
isOk1 = pstmt.executeUpdate();
if ( pstmt != null ) { pstmt.close(); }
// String sql1 = "select directory_memo from tz_cmumenu where cmuno = '" +v_cmuno + "' and menuno =" +v_menuno;
// connMgr.setOracleCLOB(sql1, box.getString("p_ins_directory_memo" ));
// String sql2 = "select limit_list from tz_cmumenu where cmuno = '" +v_cmuno + "' and menuno =" +v_menuno;
// connMgr.setOracleCLOB(sql2, box.getString("p_ins_limit_list" ));
if ( isOk1 > 0 ) {
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk1*isOk2;
}
/**
* 메뉴수정하기
* @param box receive from the form object and session
* @return isOk 1:insert success,0:insert fail
* @throws Exception
*/
public int updateMenu(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
String sql = "";
int isOk1 = 1;
int isOk2 = 1;
// int v_seq = 0;
// String v_static_cmuno = box.getString("p_static_cmuno");
String v_cmuno = box.getString("p_cmuno");
int v_menuno = box.getInt("p_menuno");
// String v_brd_fg = box.getStringDefault("p_brd_fg","1");
// int v_ins_position = box.getInt("p_ins_position");
String s_userid = box.getSession("userid");
// String s_name = box.getSession("name");
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
sql =" update tz_cmumenu set write_cd =?"
+ " ,read_cd =?"
+ " ,arrange =?"
+ " ,fileadd_fg =?"
+ " ,filecnt =?"
+ " ,modifier_userid =?"
+ " ,modifier_dte=to_char(sysdate,'YYYYMMDDHH24MISS')"
+ " ,limit_list=?"
+ " ,title=?"
+ " where cmuno = ?"
+ " and menuno=?";
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1 , box.getString("p_write_cd" ) );// 쓰기권한
pstmt.setString(2 , box.getString("p_read_cd" ) );// 읽기권한
pstmt.setString(3 , box.getString("p_arrange" ) );// 정렬
pstmt.setString(4 , box.getStringDefault("p_fileadd_fg","N" ) );// 파일첨부구분
pstmt.setString(5 , box.getStringDefault("p_filecnt","0" ) );// 첨부파일갯수
pstmt.setString(6, s_userid );// 수정자
pstmt.setString(7, box.getString("p_limit_list" ));
pstmt.setString(8, box.getString("p_title" ));
pstmt.setString(9, v_cmuno );// 커뮤니팁먼호
pstmt.setInt (10, v_menuno );// 메뉴일련번호
isOk1 = pstmt.executeUpdate();
if ( pstmt != null ) { pstmt.close(); }
// String sql2 = "select limit_list from tz_cmumenu where cmuno = '" +v_cmuno + "' and menuno =" +v_menuno;
// connMgr.setOracleCLOB(sql2, box.getString("p_limit_list" ));
if ( isOk1 > 0 ) {
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk1*isOk2;
}
/**
* 메뉴삭제하기
* @param box receive from the form object and session
* @return isOk 1:insert success,0:insert fail
* @throws Exception
*/
public int deleteMenu(RequestBox box) throws Exception {
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
ListSet ls = null;
String sql = "";
int isOk1 = 1;
int isOk2 = 1;
// int v_seq = 0;
// int v_menuno = 0;
// String v_static_cmuno = box.getString("p_static_cmuno");
// String v_cmuno = box.getString("p_cmuno");
// String v_brd_fg = box.getStringDefault("p_brd_fg","1");
// int v_ins_position = box.getInt("p_ins_position");
String s_userid = box.getSession("userid");
// String s_name = box.getSession("name");
try {
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
sql =" update tz_cmumenu set del_fg ='Y'"
+ " ,modifier_userid =?"
+ " ,modifier_dte=to_char(sysdate,'YYYYMMDDHH24MISS')"
+ " where cmuno = ?"
+ " and menuno=?";
pstmt = connMgr.prepareStatement(sql);
pstmt.setString(1, s_userid );// 수정자
pstmt.setString(2 , box.getString("p_cmuno") );// 커뮤니팁먼호
pstmt.setInt (3 , box.getInt("p_menuno") );// 메뉴일련번호
isOk1 = pstmt.executeUpdate();
if ( pstmt != null ) { pstmt.close(); }
if ( isOk1 > 0 ) {
if ( connMgr != null ) { try { connMgr.commit(); } catch ( Exception e10 ) { } }
}
}
catch ( Exception ex ) {
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql - > " +FormatDate.getDate("yyyyMMdd") + sql + "\r\n" + ex.getMessage() );
}
finally {
if ( ls != null ) { try { ls.close(); } catch ( Exception e ) { } }
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e1 ) { } }
if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch ( Exception e10 ) { } }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch ( Exception e10 ) { } }
}
return isOk1*isOk2;
}
}
|
/* ServletOutputStreamWrapper.java
Purpose:
Description:
History:
Mon Jan 17 14:08:22 2005, Created by tomyeh
Copyright (C) 2005 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.web.servlet;
import java.io.Writer;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import org.zkoss.io.WriterOutputStream;
/**
* A facade of OutputStream for implementing ServletOutputStream.
*
* @author tomyeh
*/
public class ServletOutputStreamWrapper extends ServletOutputStream {
private final OutputStream _stream;
/** Returns a facade of the specified stream. */
public static ServletOutputStream getInstance(OutputStream stream) {
if (stream instanceof ServletOutputStream)
return (ServletOutputStream)stream;
return new ServletOutputStreamWrapper(stream);
}
/** Returns a facade of the specified writer.
*
* @param charset the charset. If null, "UTF-8" is assumed.
*/
public static ServletOutputStream getInstance(Writer writer, String charset) {
return new ServletOutputStreamWrapper(writer, charset);
}
private ServletOutputStreamWrapper(OutputStream stream) {
if (stream == null)
throw new IllegalArgumentException("null");
_stream = stream;
}
/**
* @param charset the charset. If null, "UTF-8" is assumed.
*/
public ServletOutputStreamWrapper(Writer writer, String charset) {
if (writer == null)
throw new IllegalArgumentException("null");
_stream = new WriterOutputStream(writer, charset);
}
public void write(int b) throws IOException {
_stream.write(b);
}
public void flush() throws IOException {
_stream.flush();
super.flush();
}
public void close() throws IOException {
_stream.close();
super.close();
}
}
|
package com.example.covidtracer;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.example.covidtracer.Model.UserModel;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import io.realm.Realm;
import io.realm.mongodb.App;
import io.realm.mongodb.AppConfiguration;
import io.realm.mongodb.Credentials;
import io.realm.mongodb.User;
import io.realm.mongodb.sync.SyncConfiguration;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class Register extends AppCompatActivity {
/**
* this class handles Realm initialization, registeration GUI,
* and the first realm object storage.
*/
Button register;
Realm realm;
String username;
boolean grantedPermissions = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
//Realm initialization and user authentication
super.onCreate(savedInstanceState);
boolean exists = false;
if (Realm.getDefaultConfiguration() == null) {
Realm.init(this);
String appID = "application-0-cvrjc";
App app = new App(new AppConfiguration.Builder(appID)
.build());
if (app.currentUser() == null) {
Credentials credentials = Credentials.anonymous();
app.loginAsync(credentials, result -> {
User user = app.currentUser();
String partitionValue = "_partition_key_none";
SyncConfiguration config = new SyncConfiguration.Builder(
user,
partitionValue)
.allowWritesOnUiThread(true)
.allowQueriesOnUiThread(true)
.build();
realm = Realm.getInstance(config);
//Setting this configuration as the default one that
//will be used later
Realm.setDefaultConfiguration(config);
});
} else {
User user = app.currentUser();
String partitionValue = "_partition_key_none";
SyncConfiguration config = new SyncConfiguration.Builder(
user,
partitionValue)
.allowWritesOnUiThread(true)
.allowQueriesOnUiThread(true)
.build();
realm = Realm.getInstance(config);
Realm.setDefaultConfiguration(config);
}
}
//Existing user check
if (read().length() > 1 && read() != null) {
UserModel user = realm.where(UserModel.class).equalTo("_id", read()).findFirst();
if (user != null) {
switchActivities(read());
exists = true;
}
}
//Permissions check
boolean location = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean readWrite = ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
//Permissions request
if (!location && !readWrite) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, 1);
} else {
grantedPermissions = true;
}
if (!exists) {
setContentView(R.layout.register);
register = findViewById(R.id.register_butotn);
EditText usernameField = findViewById(R.id.username_field);
usernameField.setOnClickListener(e -> {
usernameField.setText("");
});
usernameField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (grantedPermissions) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
userAndRealm(usernameField);
}
return false;
} else {
Toast.makeText(Register.this, "Permissions have not been granted", Toast.LENGTH_SHORT).show();
}
return false;
}
});
register.setOnClickListener(e -> {
if (grantedPermissions) {
userAndRealm(usernameField);
} else {
Toast.makeText(Register.this, "Permissions have not been granted", Toast.LENGTH_SHORT).show();
}
});
}
}
/**
* Creating a UserModel in realm
*
* @param usernameField the registration field
*/
private void userAndRealm(EditText usernameField) {
//User creation
username = usernameField.getText().toString();
if (username.length() < 5) {
Toast.makeText(this, "Username has to be more than 5 letters", Toast.LENGTH_SHORT).show();
} else if (username.length() > 24) {
Toast.makeText(this, "Username has to be less than 24 letters", Toast.LENGTH_SHORT).show();
} else {
try {
realm.executeTransaction(a -> {
AES encryptor = new AES();
Long creation = new Date().getTime();
//Username encryption
String encryptedUser = encryptor.encrypt(username);
UserModel user1 = realm.createObject(UserModel.class, encryptedUser);
usernameField.setText("");
user1.setWifis("null");
user1.setPositive(false);
user1.setCreated(creation);
user1.setNotification(0);
Toast.makeText(getApplicationContext(), "Registered Successfully", Toast.LENGTH_SHORT).show();
write(encryptedUser);
switchActivities(encryptedUser);
});
} catch (io.realm.exceptions.RealmPrimaryKeyConstraintException x) {
Toast.makeText(getApplicationContext(), "Username already exists", Toast.LENGTH_SHORT).show();
}
}
}
/**
* This method switches from this Actvity to the MainActivity
*
* @param username the username that will be sent to MainActivity
*/
private void switchActivities(String username) {
Intent switchActivityIntent = new Intent(this, MainActivity.class);
switchActivityIntent.putExtra("username", username);
startActivity(switchActivityIntent);
finish();
}
//Reading saved username
private String read() {
BufferedReader br = null;
String s = "";
try {
br = new BufferedReader(new FileReader(Register.this.getFilesDir() + "/text"));
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
//Writing username
private void write(String s) {
File file = new File(Register.this.getFilesDir(), "text");
try {
FileWriter usernameSave = new FileWriter(file);
usernameSave.append(s);
usernameSave.flush();
usernameSave.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
//This method creats a pop up that requests the user for location and storage permissions
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
grantedPermissions = grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED;
}
}
}
}
|
package com.wxt.designpattern.mediator.test02;
/**
* @Author: weixiaotao
* @ClassName SoundCard
* @Date: 2018/10/30 18:35
* @Description: 声卡类,一个同事类
*/
public class SoundCard extends Colleague{
public SoundCard(Mediator mediator) {
super(mediator);
}
/**
* 按照声频数据发出声音
* @param data 发出声音的数据
*/
public void soundData(String data){
System.out.println("声卡,发出声音:"+data);
}
} |
package com.bikchen.hiber;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.List;
@SpringBootApplication
public class HiberApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(HiberApplication.class, args);
UserService userService = applicationContext.getBean(UserService.class);
UserEntity user1 = userService.createUser("John", "Doe");
UserEntity user2 = userService.createUser("Jane", "Doe");
UserEntity user3 = userService.createUser("Obi-Wan", "Kenobi");
UserEntity user4 = userService.createUser("Plo", "Koon");
UserEntity user5 = userService.createUser("Otto", "Kombi");
System.out.println("Saved user: " + user1);
System.out.println("Saved user: " + user2);
System.out.println("Saved user: " + user3);
System.out.println("Saved user: " + user4);
System.out.println("Saved user: " + user5);
System.out.println("Fetching all users");
List<UserEntity> allUsers = userService.getAllUsers();
for (UserEntity user : allUsers) {
System.out.println(user);
}
System.out.println("Fetching by last name");
List<UserEntity> allDoes = userService.getUsersByLastName("Doe");
for (UserEntity user : allDoes) {
System.out.println(user);
}
System.out.println("Fetching by substring");
List<UserEntity> haveBi = userService.getUsersBySubstring("bi");
for (UserEntity user : haveBi) {
System.out.println(user);
}
}
}
|
package com.stepDefinition;
import com.steps.HomePageStep;
import com.steps.OfficePageStep;
import com.steps.PublicPlacePageStep;
import com.steps.TakeTheBusPageStep;
import com.steps.CommonPageStep;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import com.steps.AreYouGamePageStep;
import com.steps.BattleFieldGamePageStep;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import net.thucydides.core.annotations.Managed;
import net.thucydides.core.annotations.Steps;
public class CovidAreYouGameDefinition {
@Managed
WebDriver driver;
@Steps
HomePageStep homeStep;
@Steps
BattleFieldGamePageStep BattleFieldGameStep;
@Steps
AreYouGamePageStep AreYouGameStep;
@Steps
CommonPageStep commonStep;
@Steps
TakeTheBusPageStep takeTheBusStep;
@Steps
PublicPlacePageStep publicPlaceStep;
@Steps
OfficePageStep officeStep;
public void scrollToBottom() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)");
}
@Given("^user launch the webSite$")
public void user_launch_the_website() throws Throwable {
homeStep.lanuchBrowser();
}
@When("start the journey of correct answer as {string}")
public void start_the_journey_of_correct_answer_as(String string) {
scrollToBottom();
homeStep.startYourJourney("journal");
}
@Then("user landed on The Battlefield page")
public void user_landed_on_the_battlefield_page() {
BattleFieldGameStep.verifyBattlefieldPage();
}
@When("user start the game and provide correct answer")
public void user_start_the_game_and_provide_correct_answer() {
BattleFieldGameStep.startTheGame();
AreYouGameStep.playGameCorrectAnswer();
}
@Then("^successfully finish the game and navigated to leaderBoard page$")
public void successfully_finish_the_game_and_navigated_to_leaderboard_page() throws Throwable {
commonStep.leaderBoardPage();
}
@When("^start the journey of incorrect answer as \"([^\"]*)\"$")
public void start_the_journey_of_incorrect_answer_as_something(String strArg1) throws Throwable {
scrollToBottom();
homeStep.startYourJourney("Illuminate");
}
@When("user start the game and provide incorrect answer")
public void user_start_the_game_and_provide_incorrect_answer() {
BattleFieldGameStep.startTheGame();
AreYouGameStep.playGameInCorrectAnswer();
}
@Then("^Try again modal displayed$")
public void try_again_modal_displayed() throws Throwable {
commonStep.tryAgainModalDisplayed();
}
@When("^start the journey of incomplete game as \"([^\"]*)\"$")
public void start_the_journey_of_incomplete_game_as_something(String strArg1) throws Throwable {
scrollToBottom();
homeStep.startYourJourney("Reco");
}
@When("user start the game and provide no answer")
public void user_start_the_game_and_provide_no_answer() {
AreYouGameStep.playGameNoAnswer();
}
@Then("^TimeOut modal displayed$")
public void timeout_modal_displayed() throws Throwable {
commonStep.timeOutModalDisplayed();
}
@When("^start the journey of complete small game as \"([^\"]*)\"$")
public void start_the_journey_of_complete_small_game_as_something(String strArg1) throws Throwable {
scrollToBottom();
homeStep.startYourJourney("fantom");
}
@When("user start the all game and provide correct answer")
public void user_start_the_all_game_and_provide_correct_answer() {
BattleFieldGameStep.takeTheBus();
takeTheBusStep.playBusGameCorrectAnswer();
// commonStep.tryNextBattle();
publicPlaceStep.playPublicGameCorrectAnswer();
// commonStep.tryNextBattle();
officeStep.playOfficeGameCorrectAnswer();
}
@Then("^successfully finish each game and navigated to leaderBoard page$")
public void successfully_finish_each_game_and_navigated_to_leaderboard_page() throws Throwable {
commonStep.clickFinalScore();
commonStep.leaderBoardPage();
}
}
|
package com.yc.ssm_vote.web.action;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ModelDriven;
import com.yc.ssm_vote.entity.User;
import com.yc.ssm_vote.service.UserService;
import com.yc.ssm_vote.util.VoteData;
@Controller("userAction")
public class UserAction implements SessionAware,ModelDriven<User>,RequestAware {
@Autowired
private UserService userService;
private User user;
private Map<String, Object> session;
private Map<String, Object> request;
public String login() {
User loginUser = userService.login(user);
LogManager.getLogger().debug("登录后的用户:" + loginUser);
if(null == loginUser){
session.put(VoteData.ERROR_MSG, "用户名或密码错误!!!");
return "login";
}else{
session.put(VoteData.LOGIN_USER, loginUser);
return "loginSuccess";
}
}
public String register(){
try {
user = userService.register(user);
if (null != user) {
session.put("user", user);
return "regSuccess";
} else {
request.put("errMsg", "该用户已被注册!!!");
return "regFail";
}
} catch (Exception e) {
request.put("errMsg", "该用户已被注册!!!");
return "regFail";
}
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
@Override
public User getModel() {
user = new User();
return user;
}
@Override
public void setRequest(Map<String, Object> request) {
this.request = request;
}
}
|
package dreamcoderj.shiftarrays.com;
import java.util.Arrays;
public class ShiftingArrays {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] oldArray = {5,10,15,20,25};
int[] newArray = shiftArray(oldArray);
System.out.println("This is the old Array: " + Arrays.toString(oldArray));
System.out.println("This is the old Array: " + Arrays.toString(newArray));
}
public static int[] shiftArray(int[] array1) {
int[] array2 = new int[array1.length];
for(int i = 0; i < array1.length -1; i++) {
//Copy the i'th element from array1 to the i+1 element to array2
array2[i+1] = array1[i];
}
//Copy last element of array1 to the first element of array2
array2[0] = array1[array1.length - 1];
return array2;
}
}
|
package net.inveed.rest.jpa.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Entity of marked property will be serialized as JSON object (instead of entity ID)
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface JsonEmbeddedEntity {
int deep() default Integer.MAX_VALUE;
}
|
package com.anssy.ognl;
/**
* @author Mr.薛
* Java防止sql注入
*/
public class SqlIn {
public static void main(String[] args) {
String str = "script-8iashdansdtasdsql select * from sys_user";
System.out.println("原始字符:"+str+" 处理之后的字符串:"+new SqlIn().filterSQLInjection(str));
}
public final static String filterSQLInjection(String s) {
if (s == null || "".equals(s)) {
return "";
}
try {
s = s.trim().replaceAll("</?[s,S][c,C][r,R][i,I][p,P][t,T]>?", "");//script
s = s.trim().replaceAll("[a,A][l,L][e,E][r,R][t,T]\\(", "").replace("\"", "");// alert
s = s.trim().replace("\\.swf", "").replaceAll("\\.htc", "");
s = s.trim().replace("\\.php\\b", "").replaceAll("\\.asp\\b", "");
s = s.trim().replace("document\\.", "").replaceAll("[e,E][v,V][a,A][l,L]\\(", "");
s = s.trim().replaceAll("'", "").replaceAll(">", "");
s = s.trim().replaceAll("<", "").replaceAll("=", "");
s = s.trim().replaceAll(" [o,O][r,R]", "");
s = s.trim().replaceAll("etc/", "").replaceAll("cat ", "");
s = s.trim().replaceAll("/passwd ", "");
s = s.trim().replaceAll("sleep\\(", "").replaceAll("limit ", "").replaceAll("LIMIT ", "");
s = s.trim().replaceAll("[d,D][e,E][l,L][e,E][t,T][e,E] ", "");// delete
s = s.trim().replaceAll("[s,S][e,E][l,L][e,E][c,C][t,T] ", "");// select;
s = s.trim().replaceAll("[u,U][p,P][d,D][a,A][t,T][e,E] ", "");// update
s = s.trim().replaceAll("[d,D][e,E][l,L][a,A][y,Y] ", "").replaceAll("waitfor ", "");
s = s.trim().replaceAll("print\\(", "").replaceAll("md5\\(", "");
s = s.trim().replaceAll("cookie\\(", "").replaceAll("send\\(", "");
s = s.trim().replaceAll("response\\.", "").replaceAll("write\\(", "")
.replaceAll("&", "");
} catch (Exception e) {
e.printStackTrace();
return "";
}
return s;
}
}
|
import java.awt.*;
import javax.swing.*;
class Main {
public static void main(String[] args) {
//teste1();
JFrame f = new JFrame();
Reprodutor c = new Reprodutor();
f.setContentPane(c);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//teste2(c);
f.setSize(500,400);
f.setVisible(true);
}
static void teste2(Reprodutor quadro) {
Reproduzivel fig;
fig = new FigRetangulo(new Ponto(50,100),new Ponto(100,150));
quadro.addFig(fig);
fig = new FigRetangulo(new Ponto(150,100),new Ponto(200,150));
quadro.addFig(fig);
fig = new FigRetangulo(new Ponto(200,200),new Ponto(300,250));
quadro.addFig(fig);
fig = new FigCirculo(100,200,50);
quadro.addFig(fig);
quadro.repaint();
}
static void teste1() {
Deslocavel r = new Retangulo(new Ponto(30,40), new Ponto(100,80));
System.out.println("r = " + r);
r.deslocarX(12);
System.out.println("r = " + r);
Ponto a = new Circulo(3,4,20);
System.out.println("a = " + a);
a.deslocarX(20);
System.out.println("a = " + a);
//a.area();
Circulo s = new Circulo(33,40,50);
System.out.println("area("+ s +") = " + s.area());
}
}
|
package hw03.gizzon.battleship;
/**
*The enum below is used to know what state the game is currently in.
*@author Nicole Gizzo
*/
public enum BattleshipStates {
INIT, PLAYER1, PLAYER2, FINISHED;
}
|
package org.samsoft.qrator.leader.impl;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.samsoft.qrator.leader.Candidate;
import org.samsoft.qrator.leader.LeaderElectionListener;
/**
* @author kumarsambhav.jain
* @since 5/16/2017.
*/
class CandidateImpl extends LeaderSelectorListenerAdapter implements Candidate {
private final CuratorFramework curatorFrameWork;
private final String leaderRoot;
private final String resource;
private LeaderElectionListener listener;
public CandidateImpl(CuratorFramework curatorFrameWork, String leaderRoot, String resource) {
this.curatorFrameWork = curatorFrameWork;
this.leaderRoot = leaderRoot;
this.resource = resource;
}
@Override
public void applyForLeadership(boolean repeatedly, LeaderElectionListener listener) {
LeaderSelector leaderSelector = new LeaderSelector(curatorFrameWork, leaderRoot + "/" + this.resource, this);
if (repeatedly) {
leaderSelector.autoRequeue();
}
this.listener = listener;
leaderSelector.start();
}
@Override
public void close() {
this.listener.onElected();
}
@Override
public void takeLeadership(CuratorFramework client) {
this.listener.onElected();
}
}
|
package com.api.os.service;
import com.api.os.dominios.OrdemServico;
import com.api.os.enums.StatusOS;
import com.api.os.repository.OrdemServicoRepository;
import com.api.os.service.exception.ObjectNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.jms.core.JmsTemplate;
import java.util.Date;
import java.util.Optional;
@Service
public class OrdemServicoService {
@Autowired
private OrdemServicoRepository ordemServicoRepository;
@Autowired
private ClienteService clienteService;
@Autowired
private FuncionarioService funcionarioService;
@Autowired
private JmsTemplate jmsTemplate;
// Inserir uma OS
public OrdemServico insert(OrdemServico obj){
obj.setId(null); // para que seja realmente nova OS
OrdemServico ordemServico = ordemServicoRepository.save(obj);
jmsTemplate.convertAndSend("osQueue", obj);
return ordemServico;
}
// Buscar OS por id
public OrdemServico find(Integer id){
Optional<OrdemServico> obj = ordemServicoRepository.findById(id); // buscar objeto no banco
return obj.orElseThrow(() -> new ObjectNotFoundException(
"Objeto não encontrado! Id:" + id + ", Tipo: " + OrdemServico.class.getName()));
}
public void updateStatus (Integer id, OrdemServico os){
OrdemServico ordemServico = find(id);
ordemServico.setStatus(os.getStatus());
ordemServicoRepository.save(ordemServico);
}
}
|
/*package com.datayes.textmining.Utils;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.ansj.splitWord.Analysis;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.ansj.util.MyStaticValue;
import com.datayes.algorithm.textmining.anouncement.summary.utility.WordSegment;
public class WordSpliter_backup {
private Analysis udf;
private Pattern pattern;
private Pattern toDelType;
Set<String> stopwordSet;
public WordSpliter_backup() throws Exception {
// TODO Auto-generated constructor stub
pattern = Pattern.compile("(^(\\pP|\\pS)$)|(^\\d$)");
toDelType = Pattern.compile("^(null)");
HashMap<String, String> stopwordsDic = new HashMap<String, String>();
stopwordSet = new TreeSet<String>();
String stopwordsFile = "stopwords.txt";
MyStaticValue.userLibrary=ConfigFileLoader.userDefDicFile;
MyStaticValue.ambiguityLibrary = ConfigFileLoader.ambiguityFile;
FileReader frstop;
InputStream fstream = WordSegment.class
.getResourceAsStream("/stopwords.txt");
BufferedReader brstop = new BufferedReader(new InputStreamReader(
new DataInputStream(fstream), "UTF-8"));
String stopword;
while (brstop.ready()) {
stopword = brstop.readLine();
stopwordSet.add(stopword);
}
}
public List<String> splitSentence(String str)
{
List<String> dyTermSet = new ArrayList<String>();
udf = new ToAnalysis(new StringReader(str));
org.ansj.domain.Term term = null;
try {
while ((term = udf.next()) != null) {
String word = term.getName();
if (!isValid(word)) {
continue;
}
dyTermSet.add(word);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dyTermSet;
}
private static boolean isValid(String str) {
boolean res = true;
if (str.length() == 1) {
res = false;
return res;
}
if (StringUtility.containsDigit(str)) {
res = false;
return res;
}
if (StringUtility.isPunctuation(str)) {
res = false;
return res;
}
return res;
}
public static void main(String[] args) {
try {
ConfigFileLoader.initConf(args);
WordSpliter_backup aa = new WordSpliter_backup();
List<String> wds = aa.splitSentence("某公司审计报告");
for(String wd : wds)
{
System.out.println(wd);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
*/ |
package pl.olart.pmsuite.model;
import java.io.Serializable;
/**
* User: grp
* Date: 16.06.16
* Time: 16:43
*/
public class Wynik implements Serializable {
private String nazwa;
private Double wynik1 = 0d;
private Double wynik2 = 0d;
private Double wynik3 = 0d;
private Double wynik4 = 0d;
private Double wynik5 = 0d;
private Double wynik6 = 0d;
private Double wynik7 = 0d;
private Double wynik8 = 0d;
private Double wynik9 = 0d;
private Double wynik10 = 0d;
private Double wynik11 = 0d;
private Double wynik12 = 0d;
public Wynik(String nazwa) {
this.nazwa = nazwa;
}
public String getNazwa() {
return nazwa;
}
public void setNazwa(String nazwa) {
this.nazwa = nazwa;
}
public Double getWynik1() {
return wynik1;
}
public void setWynik1(Double wynik1) {
this.wynik1 = wynik1;
}
public Double getWynik2() {
return wynik2;
}
public void setWynik2(Double wynik2) {
this.wynik2 = wynik2;
}
public Double getWynik3() {
return wynik3;
}
public void setWynik3(Double wynik3) {
this.wynik3 = wynik3;
}
public Double getWynik4() {
return wynik4;
}
public void setWynik4(Double wynik4) {
this.wynik4 = wynik4;
}
public Double getWynik5() {
return wynik5;
}
public void setWynik5(Double wynik5) {
this.wynik5 = wynik5;
}
public Double getWynik6() {
return wynik6;
}
public void setWynik6(Double wynik6) {
this.wynik6 = wynik6;
}
public Double getWynik7() {
return wynik7;
}
public void setWynik7(Double wynik7) {
this.wynik7 = wynik7;
}
public Double getWynik8() {
return wynik8;
}
public void setWynik8(Double wynik8) {
this.wynik8 = wynik8;
}
public Double getWynik9() {
return wynik9;
}
public void setWynik9(Double wynik9) {
this.wynik9 = wynik9;
}
public Double getWynik10() {
return wynik10;
}
public void setWynik10(Double wynik10) {
this.wynik10 = wynik10;
}
public Double getWynik11() {
return wynik11;
}
public void setWynik11(Double wynik11) {
this.wynik11 = wynik11;
}
public Double getWynik12() {
return wynik12;
}
public void setWynik12(Double wynik12) {
this.wynik12 = wynik12;
}
public void dodaj(Wynik skladnik) {
setWynik1(getWynik1() + skladnik.getWynik1());
setWynik2(getWynik2() + skladnik.getWynik2());
setWynik3(getWynik3() + skladnik.getWynik3());
setWynik4(getWynik4() + skladnik.getWynik4());
setWynik5(getWynik5() + skladnik.getWynik5());
setWynik6(getWynik6() + skladnik.getWynik6());
setWynik7(getWynik7() + skladnik.getWynik7());
setWynik8(getWynik8() + skladnik.getWynik8());
setWynik9(getWynik9() + skladnik.getWynik9());
setWynik10(getWynik10() + skladnik.getWynik10());
setWynik11(getWynik11() + skladnik.getWynik11());
setWynik12(getWynik12() + skladnik.getWynik12());
}
public void przyjmijWartosci(Wynik wartosc) {
setWynik1(wartosc.getWynik1());
setWynik2(wartosc.getWynik2());
setWynik3(wartosc.getWynik3());
setWynik4(wartosc.getWynik4());
setWynik5(wartosc.getWynik5());
setWynik6(wartosc.getWynik6());
setWynik7(wartosc.getWynik7());
setWynik8(wartosc.getWynik8());
setWynik9(wartosc.getWynik9());
setWynik10(wartosc.getWynik10());
setWynik11(wartosc.getWynik11());
setWynik12(wartosc.getWynik12());
}
}
|
package Day4;
public class Learn {
public static void main(String args[]) {
}
}
|
package com.mmall.controller.portal;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.CartService;
import com.mmall.vo.CartVo;
/**
*
* 项目名称:mmall
* 类名称:CartController
* 类描述:购物车
* 创建人:xuzijia
* 创建时间:2017年10月18日 下午3:16:46
* 修改人:xuzijia
* 修改时间:2017年10月18日 下午3:16:46
* 修改备注:
* @version 1.0
*
*/
@Controller
@RequestMapping("/cart/")
public class CartController {
@Autowired
private CartService cartService;
@RequestMapping("add.do")
@ResponseBody
public ServerResponse<CartVo> addCart(HttpSession session,Integer productId,Integer count){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.add(user.getId(), productId, count);
}
@RequestMapping("list.do")
@ResponseBody
public ServerResponse<CartVo> list(HttpSession session){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.list(user.getId());
}
/**
*
* @Title: list
* @Description:修改购物车商品数量
* @param: @param session
* @param: @param productId
* @param: @param count
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月18日 下午7:22:43
* @throws
*/
@RequestMapping("update.do")
@ResponseBody
public ServerResponse<CartVo> list(HttpSession session,Integer productId,Integer count){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.add(user.getId(), productId, count);
}
/**
*
* @Title: deleteProduct
* @Description: 删除选择的购物商品
* @param: @param session
* @param: @param cartId
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月18日 下午7:49:01
* @throws
*/
@RequestMapping("delete.do")
@ResponseBody
public ServerResponse<CartVo> deleteCart(HttpSession session,Integer[] cartId){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.deleteByCart(cartId,user.getId());
}
/**
*
* @Title: clearCart
* @Description: 清空用户购物车
* @param: @param session
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月18日 下午7:48:49
* @throws
*/
@RequestMapping("clear_cart.do")
@ResponseBody
public ServerResponse<CartVo> clearCart(HttpSession session){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.clearCart(user.getId());
}
/**
* 全选
* @Title: selectAll
* @Description: TODO
* @param: @param session
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月19日 上午8:57:49
* @throws
*/
@RequestMapping("selectAll.do")
@ResponseBody
public ServerResponse<CartVo> selectAll(HttpSession session){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.selectOrUnSelect(user.getId(), null, Const.Cart.CHECKED);
}
/**
*
* @Title: unSelectAll
* @Description: 全反选
* @param: @param session
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月19日 上午8:59:40
* @throws
*/
@RequestMapping("unSelectAll.do")
@ResponseBody
public ServerResponse<CartVo> unSelectAll(HttpSession session){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.selectOrUnSelect(user.getId(), null, Const.Cart.UN_CHECKED);
}
/**
*
* @Title: unSelectAll
* @Description: 单选
* @param: @param session
* @param: @param productId
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月19日 上午9:01:57
* @throws
*/
@RequestMapping("select.do")
@ResponseBody
public ServerResponse<CartVo> select(HttpSession session,Integer productId){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.selectOrUnSelect(user.getId(), productId, Const.Cart.CHECKED);
}
/**
* 反选
* @Title: unSelect
* @Description: TODO
* @param: @param session
* @param: @param productId
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月19日 上午9:02:46
* @throws
*/
@RequestMapping("unSelect.do")
@ResponseBody
public ServerResponse<CartVo> unSelect(HttpSession session,Integer productId){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.selectOrUnSelect(user.getId(), productId, Const.Cart.UN_CHECKED);
}
/**
*
* @Title: getProductCount
* @Description: 获取购物车总商品数
* @param: @param session
* @param: @param productId
* @param: @return
* @return: ServerResponse<CartVo>
* @author: xuzijia
* @date: 2017年10月19日 上午9:13:06
* @throws
*/
@RequestMapping("get_product_count.do")
@ResponseBody
public ServerResponse<Integer> getProductCount(HttpSession session){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user == null) {
return ServerResponse.createByErrorMessage("用户未登陆,无法查询信息");
}
return cartService.selectCartCount(user.getId());
}
}
|
package edu.ycp.cs320.groupProject.webapp;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import edu.ycp.cs320.groupProject.webapp.UserPass;
import edu.ycp.cs320.groupProject.webapp.DatabaseProvider;
import edu.ycp.cs320.groupProject.webapp.IDatabase;
public class TitleQuery {
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
// Create the default IDatabase instance
InitDatabase.init(keyboard);
System.out.print("Enter a user: ");
String title = keyboard.nextLine();
IDatabase db = DatabaseProvider.getInstance();
List<UserPass> userList = db.findUserByUserId(title);
Iterator<UserPass> userItr = userList.iterator();
while (userItr.hasNext())
System.out.println(userItr.next());
}
}
|
package fr.doranco.designpattern.strategy;
public class OuvertureSecuriseStrategy extends OuvertureStrategy {
@Override
public void ouvrir() {
// Je pousse le bouchon puis je tourne.
}
}
|
package controller.mobile;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
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 configuration.EncryptandDecrypt;
import configuration.Fullname;
import connection.DBConfiguration;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Servlet implementation class TimeIn
*/
@WebServlet("/Mobile/GetStudentInformation")
public class GetStudentInformation extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetStudentInformation() {
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
EncryptandDecrypt ec = new EncryptandDecrypt();
DBConfiguration db = new DBConfiguration();
Connection conn = db.getConnection();
String StudentNumber = request.getParameter("StudentNumber");
//String StudentNumber = "2018-00001-CM-0";
Statement stmnt = null;
try {
stmnt = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cn = "";
String message = "";
String apikey = "TR-STUDE770480_PNV9P";
String type = "NORMAL";
String fullname = "";
String fname = "";
String mname = "";
String lname = "";
String sql = "SELECT * FROM t_student_account inner join r_student_profile on Student_Profile_ID = Student_Account_Student_Profile_ID where Student_Account_Student_Number = '"+StudentNumber+"'";
ResultSet rs;
try {
rs = stmnt.executeQuery(sql);
while(rs.next()){
fname = ec.decrypt(ec.key, ec.initVector, rs.getString("Student_Profile_First_Name"));
mname = ec.decrypt(ec.key, ec.initVector, rs.getString("Student_Profile_Middle_Name"));
lname = ec.decrypt(ec.key, ec.initVector, rs.getString("Student_Profile_Last_Name"));
Fullname fn = new Fullname();
fullname = fn.fullname(fname, mname, lname);
cn = rs.getString("Student_Profile_Guardian_Contact_Number");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat getmonth = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat gethour = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat getgreet = new SimpleDateFormat("a");
SimpleDateFormat getchour = new SimpleDateFormat("hh");
Date date = new Date();
String curtime = getgreet.format(date);
String curhour = getchour.format(date);
String greet = "";
if(curtime.equals("PM") && Integer.parseInt(curhour) < 5)
greet = "Afternoon";
else if(curtime.equals("PM"))
greet = "Evening";
else
greet = "Morning";
message = "Good "+ greet +", Student Named " + fullname + " is safely arrived in school today at " + gethour.format(date)+ " " + getmonth.format(date)+". This is a computer generated message do not reply.";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Mobile/TimeIn");
request.setAttribute("StudentNumber", message + cn);
dispatcher.include(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EncryptandDecrypt ec = new EncryptandDecrypt();
DBConfiguration db = new DBConfiguration();
Connection conn = db.getConnection();
String StudentNumber = request.getParameter("StudentNumber");
//String StudentNumber = "2018-00001-CM-0";
Statement stmnt = null;
try {
stmnt = conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String cn = "23";
String message = "";
String apikey = "TR-STUDE770480_PNV9P";
String type = "NORMAL";
String url = "https://www.itexmo.com/php_api/api.php";
//URL url = new URL("https://www.itexmo.com/php_api/api.php");
String fullname = "";
String fname = "qweqwe";
String mname = "";
String lname = "";
PrintWriter out = response.getWriter();
String sql = "SELECT *,ifnull(Student_Profile_Guardian_Contact_Number,0) as cn FROM t_student_account inner join r_student_profile on Student_Profile_ID = Student_Account_Student_Profile_ID where Student_Account_Student_Number = '"+StudentNumber+"'";
//out.print(sql);
ResultSet rs;
try {
rs = stmnt.executeQuery(sql);
while(rs.next()){
fname = ec.decrypt(ec.key, ec.initVector, rs.getString("Student_Profile_First_Name"));
mname = ec.decrypt(ec.key, ec.initVector, rs.getString("Student_Profile_Middle_Name"));
lname = ec.decrypt(ec.key, ec.initVector, rs.getString("Student_Profile_Last_Name"));
Fullname fn = new Fullname();
fullname = fn.fullname(fname, mname, lname);
cn = rs.getString("cn");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat getmonth = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat gethour = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat getgreet = new SimpleDateFormat("a");
SimpleDateFormat getchour = new SimpleDateFormat("hh");
SimpleDateFormat getcday = new SimpleDateFormat("E");
Date date = new Date();
String curtime = getgreet.format(date);
String curhour = getchour.format(date);
String getday = getcday.format(date);
String greet = "";
if(curtime.equals("PM") && Integer.parseInt(curhour) < 5)
greet = "Afternoon";
else if(curtime.equals("PM"))
greet = "Evening";
else
greet = "Morning";
message = "Good "+ greet +", Student Named " + fullname + " is safely arrived in school today at " + gethour.format(date);
/*
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("1", cn));
params.add(new BasicNameValuePair("2", message));
params.add(new BasicNameValuePair("3", apikey));
params.add(new BasicNameValuePair("5", type));
httpPost.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response2 = client.execute(httpPost);
PrintWriter out = response.getWriter();
out.print(EntityUtils.toString(((HttpResponse) response2).getEntity()));
client.close();
*/
JSONObject obj = new JSONObject();
obj.put("message", message);
obj.put("cn", cn);
out.print(obj);
/*
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// Create some NameValuePair for HttpPost parameters
List<NameValuePair> arguments = new ArrayList<>(3);
arguments.add(new BasicNameValuePair("1", cn));
arguments.add(new BasicNameValuePair("2", message));
arguments.add(new BasicNameValuePair("3", apikey));
arguments.add(new BasicNameValuePair("5", type));
try {
post.setEntity(new UrlEncodedFormEntity(arguments));
response = (HttpServletResponse) client.execute(post);
// Print out the response message
System.out.println(EntityUtils.toString(((HttpResponse) response).getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
//*
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
request.setAttribute("1", cn);
request.setAttribute("2", message);
request.setAttribute("3", apikey);
request.setAttribute("5", type);
dispatcher.include(request, response);
*/
}
}
|
package com.git.cloud.parame.model.po;
import com.git.cloud.common.model.base.BaseBO;
public class ParameterPo extends BaseBO {
private static final long serialVersionUID = 1L;
private String paramId;
private String paramName;
private String paramValue;
private String remark;
private String isActive;
private String isEncryption;
private String paramLogo;
public ParameterPo(String paramId, String paramName, String paramValue, String remark, String isActive,
String isEncryption, String paramLogo) {
super();
this.paramId = paramId;
this.paramName = paramName;
this.paramValue = paramValue;
this.remark = remark;
this.isActive = isActive;
this.isEncryption = isEncryption;
this.paramLogo = paramLogo;
}
public String getParamLogo() {
return paramLogo;
}
public void setParamLogo(String paramLogo) {
this.paramLogo = paramLogo;
}
public ParameterPo() {
super();
}
public String getParamId() {
return paramId;
}
public void setParamId(String paramId) {
this.paramId = paramId;
}
public String getParamName() {
return paramName;
}
public void setParamName(String paramName) {
this.paramName = paramName;
}
public String getParamValue() {
return paramValue;
}
public void setParamValue(String paramValue) {
this.paramValue = paramValue;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public String getIsEncryption() {
return isEncryption;
}
public void setIsEncryption(String isEncryption) {
this.isEncryption = isEncryption;
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
}
|
package searchandsort;
/**
* @author Nam Zeng
* @coding UTF-8
* @Date 2019/4/7
* @Description 插入排序
*/
public class InsertSort {
/**
* 利用插入排序法,将数组arr中[left,right]中的元素升序排列
* 算法步骤:
* 1.将第一个元素看做一个有序序列,把从第二个元素到最后一个元素当成是未排序序列。
* 2.从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。
* 如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。
*/
public static void insertSort(int[] arr, int left, int right) {
//从下标为1的元素开始插入到前面的有序序列中
for (int i = left+1; i <= right; i++) {
int temp = arr[i];
int j = i;
// 在有序序列中比较,找到插入位置
while(j > 0 && arr[j-1] > temp){
// 将大的元素向后移位
arr[j] = arr[j-1];
j--;
}
// 插入新元素
if(j != i) {
arr[j] = temp;
}
}
}
/**
* 优化:在查找时使用折半查找
* @param arr
*/
public static void binaryInsertSort(int[] arr){
for (int i = 1; i < arr.length; i++) {
int left = 0;
int right = i-1;
int mid = 0;
// 在有序序列中使用二分查找,获取插入位置
while(left <= right){
mid = (left + right) / 2;
if (arr[i] < arr[mid]) {
right = mid -1;
} else {
left = mid + 1;
}
}
int temp = arr[i];
// 移动有序列表, 在mid位置前插入新元素
for (int j = i-1 ; j >= mid; j--) {
arr[j+1] = arr[j];
}
arr[mid] = temp;
}
}
}
|
package com.restcode.restcode.service;
import com.restcode.restcode.domain.model.Sale;
import com.restcode.restcode.domain.model.SaleDetail;
import com.restcode.restcode.domain.repository.IRestaurantRepository;
import com.restcode.restcode.domain.repository.ISaleRepository;
import com.restcode.restcode.domain.service.ISaleService;
import com.restcode.restcode.exception.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@Service
public class SaleService implements ISaleService {
@Autowired
private ISaleRepository saleRepository;
@Autowired
private IRestaurantRepository restaurantRepository;
@Override
public Sale getSaleById(Long saleId) {
return saleRepository.findById(saleId).orElseThrow(
()-> new ResourceNotFoundException("Sale","Id",saleId)
);
}
@Override
public Sale createSale(Long restaurantId, Sale sale) {
return restaurantRepository.findById(restaurantId).map(restaurant -> {
sale.setRestaurant(restaurant);
return saleRepository.save(sale);
}).orElseThrow(() -> new ResourceNotFoundException(
"Restaurant", "Id", restaurantId));
}
@Override
public ResponseEntity<?> deleteSale(Long saleId) {
Sale sale=saleRepository.findById(saleId).orElseThrow(
()-> new ResourceNotFoundException("Sale","Id",saleId)
);
saleRepository.delete(sale);
return ResponseEntity.ok().build();
}
@Override
public Page<Sale> getAllSalesByRestaurantId(Long restaurantId, Pageable pageable) {
return saleRepository.findByRestaurantId(restaurantId, pageable);
}
//Its belong to the test
/*@Override
public Sale getSaleByClientFullname(String client_fullname) {
return saleRepository.findByClientFullname(client_fullname)
.orElseThrow(()->new ResourceNotFoundException("Sale","Client Fullname",client_fullname));
}*/
}
|
package com.yang.o2o.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.yang.o2o.entity.Area;
@Service
public interface AreaService {
List<Area> getAreaList();
}
|
package ar.edu.unlam.pb1.tp03.prueba;
import ar.edu.unlam.pb1.tp03.dominio.Punto;
public class PruebaPunto {
public static void main(String[] args) {
Punto punto1 = new Punto();
punto1.setCoordenadaX(10.0);
punto1.setCoordenadaY(5);
System.out.println("La coordenada x es: " + punto1.getCoordenadaX());
System.out.println("La coordenada y es: " + punto1.getCoordenadaY());
/* Comprobación coordenadas */
if (punto1.verificarOrigenCoordenadas() == false) {
System.out.println("El punto no se encuentra en el origen de coordenadas.");
} else {
System.out.println("El punto se encuentra en el origen de coordenadas.");
} // condicional Comprobación coordenadas
/* Comprobación punto sobre el eje de las X */
if (punto1.verificarPuntoEjeX() == false) {
System.out.println("El punto no se encuentra sobre el eje de las X");
} else {
System.out.println("El punto se encuentra sobre el eje de las X");
} // condicional Comprobación punto sobre el eje de las X
/* Comprobación punto sobre el eje de las Y */
if (punto1.verificarPuntoEjeY() == false) {
System.out.println("El punto no se encuentra sobre el eje de las Y");
} else {
System.out.println("El punto se encuentra sobre el eje de las Y");
} // condicional Comprobación punto sobre el eje de las Y
} // end main
}// end PruebaPunto
|
package com.programapprentice.app;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* User: program-apprentice
* Date: 8/23/15
* Time: 3:42 PM
*/
public class DecodeWays_Test {
DecodeWays_91 obj = new DecodeWays_91();
@Test
public void test1() {
String s = "10";
int expected= 1;
int actual = obj.numDecodings(s);
assertEquals(expected, actual);
}
@Test
public void test2() {
String s = "9371597631128776948387197132267188677349946742344217846154932859125134924241649584251978418763151253";
int expected= 3981312;
int actual = obj.numDecodings(s);
assertEquals(expected, actual);
}
}
|
package slimeknights.tconstruct.tools.modifiers;
import net.minecraft.nbt.NBTTagCompound;
import slimeknights.tconstruct.library.modifiers.ModifierAspect;
import slimeknights.tconstruct.library.tools.ToolNBT;
import slimeknights.tconstruct.library.utils.HarvestLevels;
import slimeknights.tconstruct.library.utils.TagUtil;
public class ModDiamond extends ToolModifier {
public ModDiamond() {
super("diamond", 0x8cf4e2);
addAspects(new ModifierAspect.SingleAspect(this), new ModifierAspect.DataAspect(this), ModifierAspect.freeModifier);
}
@Override
public void applyEffect(NBTTagCompound rootCompound, NBTTagCompound modifierTag) {
ToolNBT data = TagUtil.getToolStats(rootCompound);
data.durability += 500;
if(data.harvestLevel < HarvestLevels.OBSIDIAN) {
data.harvestLevel++;
}
data.attack += 1f;
data.speed += 0.5f;
TagUtil.setToolTag(rootCompound, data.get());
}
}
|
package com.example.isvirin.storeclient.data.entity.daoconverter;
import org.greenrobot.greendao.converter.PropertyConverter;
public class BrandTypeConverter implements PropertyConverter<BrandType, String>{
@Override
public BrandType convertToEntityProperty(String databaseValue) {
return BrandType.valueOf(databaseValue);
}
@Override
public String convertToDatabaseValue(BrandType entityProperty) {
return entityProperty.name();
}
}
|
package com.gsccs.sme.plat.rtable.model;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
public class EnergyMain {
private String mainId;
private Long corpid;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date startdate;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date enddate;
private String qyIndustry;
private String industryAll;
private String industryAdd;
private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String g;
private String h;
private String i;
private String header;
private String writer;
private String phone;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date bcTime;
private String bcTimestr;
private String reportid;
private String corptitle;
private String isattach;
private String startend;
public String getMainId() {
return mainId;
}
public void setMainId(String mainId) {
this.mainId = mainId == null ? null : mainId.trim();
}
public Long getCorpid() {
return corpid;
}
public void setCorpid(Long corpid) {
this.corpid = corpid;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
public String getQyIndustry() {
return qyIndustry;
}
public void setQyIndustry(String qyIndustry) {
this.qyIndustry = qyIndustry == null ? null : qyIndustry.trim();
}
public String getIndustryAll() {
return industryAll;
}
public void setIndustryAll(String industryAll) {
this.industryAll = industryAll == null ? null : industryAll.trim();
}
public String getIndustryAdd() {
return industryAdd;
}
public void setIndustryAdd(String industryAdd) {
this.industryAdd = industryAdd == null ? null : industryAdd.trim();
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a == null ? null : a.trim();
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b == null ? null : b.trim();
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c == null ? null : c.trim();
}
public String getD() {
return d;
}
public void setD(String d) {
this.d = d == null ? null : d.trim();
}
public String getE() {
return e;
}
public void setE(String e) {
this.e = e == null ? null : e.trim();
}
public String getF() {
return f;
}
public void setF(String f) {
this.f = f == null ? null : f.trim();
}
public String getG() {
return g;
}
public void setG(String g) {
this.g = g == null ? null : g.trim();
}
public String getH() {
return h;
}
public void setH(String h) {
this.h = h == null ? null : h.trim();
}
public String getI() {
return i;
}
public void setI(String i) {
this.i = i == null ? null : i.trim();
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header == null ? null : header.trim();
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer == null ? null : writer.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public Date getBcTime() {
return bcTime;
}
public void setBcTime(Date bcTime) {
this.bcTime = bcTime;
}
public String getReportid() {
return reportid;
}
public void setReportid(String reportid) {
this.reportid = reportid;
}
public String getCorptitle() {
return corptitle;
}
public void setCorptitle(String corptitle) {
this.corptitle = corptitle;
}
public String getIsattach() {
return isattach;
}
public void setIsattach(String isattach) {
this.isattach = isattach;
}
public String getStartend() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(null!=startdate&&null!=enddate)
return format.format(startdate)+"到"+format.format(enddate);
return startend;
}
public void setStartend(String startend) {
this.startend = startend;
}
public String getBcTimestr() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(null!=bcTime)
return format.format(bcTime);
return bcTimestr;
}
public void setBcTimestr(String bcTimestr) {
this.bcTimestr = bcTimestr;
}
} |
package randomData;
import buffer.LastOperation;
import javafx.beans.binding.NumberBinding;
import util.Util;
import java.lang.reflect.Array;
import java.util.Calendar;
import java.util.Random;
public class DataGeneration {
private Random rnd;
public DataGeneration() {
rnd = new Random();
}
public Byte[] getBytes(int length) {
if(length < 1)
throw new IllegalArgumentException();
byte[] bytes = new byte[length];
rnd.setSeed(Calendar.getInstance().getTimeInMillis());
rnd.nextBytes(bytes);
return Util.arrayWrapper(bytes);
}
public Double[] getDoubles(int length) {
if(length < 1)
throw new IllegalArgumentException();
rnd.setSeed(Calendar.getInstance().getTimeInMillis());
double[] doubles = rnd.doubles(length, Double.MIN_VALUE, Double.MAX_VALUE).toArray();
return Util.arrayWrapper(doubles);
}
public Integer[] getInts(int length) {
if(length < 1)
throw new IllegalArgumentException();
rnd.setSeed(Calendar.getInstance().getTimeInMillis());
int[] ints = rnd.ints(length).toArray();
return Util.arrayWrapper(ints);
}
public Long[] getLongs(int length) {
if(length < 1)
throw new IllegalArgumentException();
rnd.setSeed(Calendar.getInstance().getTimeInMillis());
long[] longs = rnd.longs(length).toArray();
return Util.arrayWrapper(longs);
}
}
|
package method0105;
import java.util.Scanner;
public class Method4 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("1번째 숫자 입력: ");
int num1 = s.nextInt();
System.out.print("2번째 숫자 입력: ");
int num2 = s.nextInt();
System.out.print("3번째 숫자 입력: ");
int num3 = s.nextInt();
mySort(num1, num2, num3);
}
public static void mySort(int a, int b, int c) {
if (a > b && b > c) { // a > b > c
System.out.println(a+"-"+b+"-"+c);
}
else if (a > c && c > b) {
System.out.println(a+"-"+c+"-"+b);
}
else if (b > a && a > c) {
System.out.println(b+"-"+a+"-"+c);
}
else if (b > c && c > a) {
System.out.println(b+"-"+c+"-"+a);
}
else if (c > b && b > a) {
System.out.println(c+"-"+b+"-"+a);
}
else if (c > a && a > b) {
System.out.println(a+"-"+c+"-"+b);
}
}
}
|
package core.heroes.original;
import core.heroes.skills.YuanShaoArrowSalvoHeroSkill;
public class YuanShao extends AbstractHero {
private static final long serialVersionUID = 1L;
public YuanShao() {
super(4, Faction.QUN, Gender.MALE, "Yuan Shao",
new YuanShaoArrowSalvoHeroSkill()
);
}
}
|
package cn.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import entityClass.CourseInfo;
import entityClass.SelectInfo;
import entityClass.SelectedCoursesInfo;
import entityClass.Syllabus;
import service.CourseService;
import tool.EncodingTool;
@Controller
public class CourseController {
CourseService courseService = new CourseService();
EncodingTool encodingTool = new EncodingTool();
@RequestMapping(value="/zxxk.html")
public String getCompulsoryCourseInfo(@RequestParam("userName") String userName, Model model) {
CourseInfo courseInfo = courseService.getCourseInfo(userName);
List<SelectInfo> selectInfos = courseService.getSelectInfo(userName);
model.addAttribute("selectInfos", selectInfos);
model.addAttribute("courseInfo", courseInfo);
model.addAttribute("studentId", userName);
return "/zxxk";
}
@RequestMapping(value="/xxxk.html")
public String getOptionalCourseInfo(@RequestParam("userName") String userName, Model model) {
CourseInfo courseInfo = courseService.getCourseInfo();
List<SelectInfo> selectInfos = courseService.getSelectInfo(userName);
model.addAttribute("selectInfos", selectInfos);
model.addAttribute("courseInfo", courseInfo);
model.addAttribute("studentId", userName);
return "/xxxk";
}
@RequestMapping(value="/zxxk_xk.html")
public String selectCompulsoryCourse(@RequestParam("courseId") Integer courseId, @RequestParam("studentId") String studentId, @RequestParam("selectedNum") Integer selectedNum, Model model) {
courseService.select(courseId, studentId, selectedNum);
model.addAttribute("msg", "选课成功!");
return getCompulsoryCourseInfo(studentId, model);
}
@RequestMapping(value="/xxxk_xk.html")
public String selectOptionalCourse(@RequestParam("courseId") Integer courseId, @RequestParam("studentId") String studentId, @RequestParam("selectedNum") Integer selectedNum, Model model) {
courseService.select(courseId, studentId, selectedNum);
model.addAttribute("msg", "选课成功!");
return getOptionalCourseInfo(studentId,model);
}
@RequestMapping(value="/zxxk_tk.html")
public String cancelSelectCompulsoryCourse(@RequestParam("courseId") Integer courseId, @RequestParam("studentId") String studentId, @RequestParam("selectedNum") Integer selectedNum, Model model) {
courseService.cancelSelect(courseId, studentId, selectedNum);
model.addAttribute("msg", "退课成功!");
return getCompulsoryCourseInfo(studentId, model);
}
@RequestMapping(value="/xxxk_tk.html")
public String cancelSelectOptionalCourse(@RequestParam("courseId") Integer courseId, @RequestParam("studentId") String studentId, @RequestParam("selectedNum") Integer selectedNum, Model model) {
courseService.cancelSelect(courseId, studentId, selectedNum);
model.addAttribute("msg", "退课成功!");
return getOptionalCourseInfo(studentId,model);
}
@RequestMapping(value="/yxkc.html")
public String getSelectedCourses(@RequestParam("userName") String studentId, Model model) {
SelectedCoursesInfo selectedCoursesInfo = courseService.getSelectCourses(studentId);
model.addAttribute("studentId", studentId);
model.addAttribute("selectedCoursesInfo", selectedCoursesInfo);
return "/yxkc";
}
@RequestMapping(value="/yxkc_tk.html")
public String cancel(@RequestParam("studentId") String studentId, @RequestParam("courseId") Integer courseId, @RequestParam("selectedNum")Integer selectedNum, Model model) {
courseService.cancelSelect(courseId, studentId, selectedNum);
model.addAttribute("msg", "退课成功!");
return getSelectedCourses(studentId, model);
}
@RequestMapping(value="/grkb.html")
public String getSyllabus(@RequestParam("userName")String studentId, Model model) {
SelectedCoursesInfo selectedCoursesInfo = courseService.getSelectCourses(studentId);
List<Syllabus> syllabus = courseService.setSyllabus(selectedCoursesInfo);
model.addAttribute("syllabus", syllabus);
model.addAttribute("studentId", studentId);
model.addAttribute("selectedCoursesInfo", selectedCoursesInfo);
return "/grkb";
}
@RequestMapping(value="/lxkc.html")
public String getFailedCourses(@RequestParam("userName") String studentId, Model model) {
SelectedCoursesInfo FailedCourseInfo = courseService.getFailedCourses(studentId);
model.addAttribute("studentId", studentId);
model.addAttribute("FailedCourseInfo", FailedCourseInfo);
return "/lxkc";
}
@RequestMapping(value="/search.html")
public String searchOptionalCourse(@RequestParam("content")String content, @RequestParam("userName")String userName, Model model) {
CourseInfo courseInfo = courseService.searchCourseInfo(encodingTool.encodeStr(content));
List<SelectInfo> selectInfos = courseService.getSelectInfo(userName);
model.addAttribute("selectInfos", selectInfos);
model.addAttribute("courseInfo", courseInfo);
model.addAttribute("studentId", userName);
return "/xxxk";
}
@RequestMapping(value="/searchM.html")
public String searchCompulsoryCourse(@RequestParam("content")String content, @RequestParam("userName")String userName, Model model) {
CourseInfo courseInfo = courseService.searchCourseInfo(userName, encodingTool.encodeStr(content));
List<SelectInfo> selectInfos = courseService.getSelectInfo(userName);
model.addAttribute("selectInfos", selectInfos);
model.addAttribute("courseInfo", courseInfo);
model.addAttribute("studentId", userName);
return "/zxxk";
}
}
|
package com.employee_recognition.Entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table (name="position")
public class Position {
@Id
@Column(name = "position_id")
private int position_id;
@Column(name = "position")
private String position;
public Position(String p, int i) {
position_id = i;
position = p;
}
public int getPosition_id() {
return position_id;
}
public void setPosition_id(int position_id) {
this.position_id = position_id;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
|
package com.ut.healthelink.model;
import com.ut.healthelink.validator.NoHtml;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Entity
@Table(name = "CONFIGURATIONTRANSPORTDETAILS")
public class configurationTransport {
@Transient
private List<configurationFormFields> fields = null;
@Transient
private List<configurationFTPFields> FTPfields = null;
@Transient
private List<configurationRhapsodyFields> rhapsodyFields = null;
@Transient
private List<configurationWebServiceFields> webServiceFields = null;
@Transient
private String delimChar = null;
@Transient
private boolean containsHeaderRow;
@Transient
private List<Integer> messageTypes = null;
@Transient
private CommonsMultipartFile ccdTemplatefile = null, hl7PDFTemplatefile = null;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false)
private int id;
@Column(name = "CONFIGID", nullable = false)
private int configId;
@Column(name = "TRANSPORTMETHODID", nullable = false)
private int transportMethodId;
@Column(name = "FILETYPE", nullable = true)
private int fileType = 1;
@Column(name = "FILEDELIMITER", nullable = true)
private int fileDelimiter = 2;
@Column(name = "STATUS", nullable = false)
private boolean status = true;
@NoHtml
@Column(name = "TARGETFILENAME", nullable = true)
private String targetFileName = null;
@Column(name = "APPENDDATETIME", nullable = false)
private boolean appendDateTime = false;
@Column(name = "MAXFILESIZE", nullable = false)
private int maxFileSize = 0;
@Column(name = "CLEARRECORDS", nullable = false)
private boolean clearRecords = false;
@Column(name = "FILELOCATION", nullable = true)
private String fileLocation = null;
@Column(name = "AUTORELEASE", nullable = false)
private boolean autoRelease = true;
@Column(name = "ERRORHANDLING", nullable = false)
private int errorHandling = 2;
@Column(name = "MERGEBATCHES", nullable = false)
private boolean mergeBatches = true;
@Column(name = "COPIEDTRANSPORTID", nullable = false)
private int copiedTransportId = 0;
@Column(name = "massTranslation", nullable = false)
private boolean massTranslation = false;
@Column(name = "lineTerminator", nullable = true)
private String lineTerminator = "\\n";
@NoHtml
@Column(name = "FILEEXT", nullable = false)
private String fileExt = null;
@Column(name = "encodingId", nullable = false)
private int encodingId = 1;
@Column(name = "ccdSampleTemplate", nullable = true)
private String ccdSampleTemplate = null;
@Column(name = "attachmentLimit", nullable = true)
private String attachmentLimit = "";
@Column(name = "attachmentRequired", nullable = false)
private Boolean attachmentRequired = false;
@Column(name = "attachmentNote", nullable = true)
private String attachmentNote = "";
@Column(name = "HL7PDFSampleTemplate", nullable = true)
private String HL7PDFSampleTemplate = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getconfigId() {
return configId;
}
public void setconfigId(int configId) {
this.configId = configId;
}
public int gettransportMethodId() {
return transportMethodId;
}
public void settransportMethodId(int transportMethodId) {
this.transportMethodId = transportMethodId;
}
public int getfileType() {
return fileType;
}
public void setfileType(int fileType) {
this.fileType = fileType;
}
public int getfileDelimiter() {
return fileDelimiter;
}
public void setfileDelimiter(int fileDelimiter) {
this.fileDelimiter = fileDelimiter;
}
public List<configurationFormFields> getFields() {
return fields;
}
public void setFields(List<configurationFormFields> fields) {
this.fields = fields;
}
public List<configurationFTPFields> getFTPFields() {
return FTPfields;
}
public void setFTPFields(List<configurationFTPFields> FTPFields) {
this.FTPfields = FTPFields;
}
public boolean getstatus() {
return status;
}
public void setstatus(boolean status) {
this.status = status;
}
public String gettargetFileName() {
return targetFileName;
}
public void settargetFileName(String targetFileName) {
this.targetFileName = targetFileName;
}
public boolean getappendDateTime() {
return appendDateTime;
}
public void setappendDateTime(boolean appendDateTime) {
this.appendDateTime = appendDateTime;
}
public int getmaxFileSize() {
return maxFileSize;
}
public void setmaxFileSize(int maxFileSize) {
this.maxFileSize = maxFileSize;
}
public boolean getclearRecords() {
return clearRecords;
}
public void setclearRecords(boolean clearRecords) {
this.clearRecords = clearRecords;
}
public String getfileLocation() {
return fileLocation;
}
public void setfileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
public boolean getautoRelease() {
return autoRelease;
}
public void setautoRelease(boolean autoRelease) {
this.autoRelease = autoRelease;
}
public int geterrorHandling() {
return errorHandling;
}
public void seterrorHandling(int errorHandling) {
this.errorHandling = errorHandling;
}
public boolean getmergeBatches() {
return mergeBatches;
}
public void setmergeBatches(boolean mergeBatches) {
this.mergeBatches = mergeBatches;
}
public List<Integer> getmessageTypes() {
return messageTypes;
}
public void setmessageTypes(List<Integer> messageTypes) {
this.messageTypes = messageTypes;
}
public int getcopiedTransportId() {
return copiedTransportId;
}
public void setcopiedTransportId(int copiedTransportId) {
this.copiedTransportId = copiedTransportId;
}
public String getDelimChar() {
return delimChar;
}
public void setDelimChar(String delimChar) {
this.delimChar = delimChar;
}
public boolean getContainsHeaderRow() {
return containsHeaderRow;
}
public void setContainsHeaderRow(boolean containsHeaderRow) {
this.containsHeaderRow = containsHeaderRow;
}
public String getfileExt() {
return fileExt;
}
public void setfileExt(String fileExt) {
this.fileExt = fileExt;
}
public int getEncodingId() {
return encodingId;
}
public void setEncodingId(int encodingId) {
this.encodingId = encodingId;
}
public List<configurationRhapsodyFields> getRhapsodyFields() {
return rhapsodyFields;
}
public void setRhapsodyFields(List<configurationRhapsodyFields> rhapsodyFields) {
this.rhapsodyFields = rhapsodyFields;
}
public List<configurationWebServiceFields> getWebServiceFields() {
return webServiceFields;
}
public void setWebServiceFields(
List<configurationWebServiceFields> webServiceFields) {
this.webServiceFields = webServiceFields;
}
public String getCcdSampleTemplate() {
return ccdSampleTemplate;
}
public void setCcdSampleTemplate(String ccdSampleTemplate) {
this.ccdSampleTemplate = ccdSampleTemplate;
}
public CommonsMultipartFile getCcdTemplatefile() {
return ccdTemplatefile;
}
public void setCcdTemplatefile(CommonsMultipartFile ccdTemplatefile) {
this.ccdTemplatefile = ccdTemplatefile;
}
public String getAttachmentLimit() {
return attachmentLimit;
}
public void setAttachmentLimit(String attachmentLimit) {
this.attachmentLimit = attachmentLimit;
}
public Boolean getAttachmentRequired() {
return attachmentRequired;
}
public void setAttachmentRequired(Boolean attachmentRequired) {
this.attachmentRequired = attachmentRequired;
}
public String getAttachmentNote() {
return attachmentNote;
}
public void setAttachmentNote(String attachmentNote) {
this.attachmentNote = attachmentNote;
}
public String getHL7PDFSampleTemplate() {
return HL7PDFSampleTemplate;
}
public void setHL7PDFSampleTemplate(String HL7PDFSampleTemplate) {
this.HL7PDFSampleTemplate = HL7PDFSampleTemplate;
}
public CommonsMultipartFile getHl7PDFTemplatefile() {
return hl7PDFTemplatefile;
}
public void setHl7PDFTemplatefile(CommonsMultipartFile hl7PDFTemplatefile) {
this.hl7PDFTemplatefile = hl7PDFTemplatefile;
}
public boolean isMassTranslation() {
return massTranslation;
}
public void setMassTranslation(boolean massTranslation) {
this.massTranslation = massTranslation;
}
public String getLineTerminator() {
return lineTerminator;
}
public void setLineTerminator(String lineTerminator) {
this.lineTerminator = lineTerminator;
}
}
|
package co.sblock.utilities;
import static org.junit.Assert.fail;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import org.bukkit.Material;
import org.junit.Test;
public class ItemNameTest {
@Test
public void testMaterialsPresent() {
HashMap<String, String> items = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/items.tsv"))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
continue;
}
String[] row = line.split("\t");
if (row.length != 5) {
fail("Row does not match format: " + line);
}
String id = row[1] + ":" + row[2];
items.put(id, row[3]);
}
} catch (IOException e) {
fail("Could not load items from items.tsv!");
}
for (Material material : Material.values()) {
String name = items.get(material.name() + ":0");
if (name == null) {
fail("Missing material data for " + material.name() + " in items.tsv");
}
}
}
}
|
package com.cheese.radio.util.calendarutils;
import android.content.Context;
import com.cheese.radio.ui.user.calendar.CalendarEntity;
import java.util.ArrayList;
import java.util.List;
public class CalendarUtil {
/**
* 获得当月显示的日期(上月 + 当月 + 下月)
*
* @param year 当前年份
* @param month 当前月份
* @return
*/
public static List<Day> getDays(int year, int month, int[] selectDay, List<CalendarEntity> tipsDays) {
List<Day> days = new ArrayList<>();
int week = SolarUtil.getFirstWeekOfMonth(year, month - 1);
int lastYear;
int lastMonth;
if (month == 1) {
lastMonth = 12;
lastYear = year - 1;
} else {
lastMonth = month - 1;
lastYear = year;
}
int lastMonthDays = SolarUtil.getMonthDays(lastYear, lastMonth);//上个月总天数
int currentMonthDays = SolarUtil.getMonthDays(year, month);//当前月总天数
int nextYear;
int nextMonth;
if (month == 12) {
nextMonth = 1;
nextYear = year + 1;
} else {
nextMonth = month + 1;
nextYear = year;
}
for (int i = 0; i < week; i++) {
days.add(initDay(selectDay, tipsDays, lastYear, lastMonth, lastMonthDays - week + 1 + i, 0));
}
for (int i = 0; i < currentMonthDays; i++) {
days.add(initDay(selectDay, tipsDays, year, month, i + 1, 1));
}
for (int i = 0; i < 7 * getMonthRows(year, month) - currentMonthDays - week; i++) {
days.add(initDay(selectDay, tipsDays, nextYear, nextMonth, i + 1, 2));
}
return days;
}
private static Day initDay(int[] selectDay, List<CalendarEntity> tipsDays, int year, int month, int day, int type) {
Day theDay = new Day();
theDay.setSolar(year, month, day);
String[] temp = LunarUtil.solarToLunar(year, month, day);
theDay.setLunar(new String[]{temp[0], temp[1]});
theDay.setType(type);
theDay.setTerm(LunarUtil.getTermString(year, month - 1, day));
theDay.setLunarHoliday(temp[2]);
if (type == 0) {
theDay.setSolarHoliday(SolarUtil.getSolarHoliday(year, month, day - 1));
} else {
theDay.setSolarHoliday(SolarUtil.getSolarHoliday(year, month, day));
}
if (selectDay != null && selectDay.length >= 3 && selectDay[0] == year && selectDay[1] == month && selectDay[2] == day) {
theDay.setChoose(true);
}
if (tipsDays != null) {
for (int i = 0; i < tipsDays.size(); i++) {
CalendarEntity tipsDay = tipsDays.get(i);
if (tipsDay != null) {
int[] theDay1 = tipsDay.getDays();
if (theDay1 != null && theDay1.length >= 3 && theDay1[0] == year && theDay1[1] == month && theDay1[2] == day) {
if (tipsDay.isBook()) {
theDay.setTipsType(1);//绿
break;
} else if (tipsDay.isCanBook()) {
theDay.setTipsType(2);//黄
} else if(theDay.getTipsType() == 0)theDay.setTipsType(3);//灰
}
}
}
}
return theDay;
}
// public static List<Day> getDays(int year, int month,int[] selectDay,List<TipsDay> tipsDays) {
// List<Day> days = new ArrayList<>();
// int week = SolarUtil.getFirstWeekOfMonth(year, month - 1);
//
// int lastYear;
// int lastMonth;
// if (month == 1) {
// lastMonth = 12;
// lastYear = year - 1;
// } else {
// lastMonth = month - 1;
// lastYear = year;
// }
// int lastMonthDays = SolarUtil.getMonthDays(lastYear, lastMonth);//上个月总天数
//
// int currentMonthDays = SolarUtil.getMonthDays(year, month);//当前月总天数
//
// int nextYear;
// int nextMonth;
// if (month == 12) {
// nextMonth = 1;
// nextYear = year + 1;
// } else {
// nextMonth = month + 1;
// nextYear = year;
// }
// for (int i = 0; i < week; i++) {
// days.add(initDay(selectDay,tipsDays,lastYear, lastMonth, lastMonthDays - week + 1 + i, 0));
// }
//
// for (int i = 0; i < currentMonthDays; i++) {
// days.add(initDay(selectDay,tipsDays,year, month, i + 1, 1));
// }
//
// for (int i = 0; i < 7 * getMonthRows(year, month) - currentMonthDays - week; i++) {
// days.add(initDay(selectDay,tipsDays,nextYear, nextMonth, i + 1, 2));
// }
//
// return days;
// }
//
// private static Day initDay(int[] selectDay,List<TipsDay> tipsDays,int year, int month, int day, int type) {
// Day theDay = new Day();
// theDay.setSolar(year, month, day);
//
// String[] temp = LunarUtil.solarToLunar(year, month, day);
//
// theDay.setLunar(new String[]{temp[0], temp[1]});
// theDay.setType(type);
// theDay.setTerm(LunarUtil.getTermString(year, month - 1, day));
// theDay.setLunarHoliday(temp[2]);
//
// if (type == 0) {
// theDay.setSolarHoliday(SolarUtil.getSolarHoliday(year, month, day - 1));
// } else {
// theDay.setSolarHoliday(SolarUtil.getSolarHoliday(year, month, day));
// }
// if(selectDay!=null&&selectDay.length>=3&&selectDay[0]==year&&selectDay[1]==month&&selectDay[2]==day){
// theDay.setChoose(true);
// }
//
// if (tipsDays!=null){
// for (int i=0;i<tipsDays.size();i++){
// TipsDay tipsDay=tipsDays.get(i);
// if (tipsDay!=null){
// int[] theDay1 =tipsDay.getDay();
// if (theDay1!=null&&theDay1.length>=3&&theDay1[0]==year&&theDay1[1]==month&&theDay1[2]==day){
// if (tipsDay.isSelect()) {
// theDay.setTipsType(1);
// }else{
// theDay.setTipsType(2);
// }
// break;
// }
// }
//
// }
// }
//
// return theDay;
// }
/**
* 计算当前月需要显示几行
*
* @param year
* @param month
* @return
*/
public static int getMonthRows(int year, int month) {
int items = SolarUtil.getFirstWeekOfMonth(year, month - 1) + SolarUtil.getMonthDays(year, month);
int rows = items % 7 == 0 ? items / 7 : (items / 7) + 1;
if (rows == 4) {
rows = 5;
}
return rows;
}
/**
* 根据ViewPager position 得到对应年月
*
* @param position
* @return
*/
public static int[] positionToDay(int position, int startY, int startM) {
int year = position / 12 + startY;
int month = position % 12 + startM;
if (month > 12) {
month = month % 12;
year = year + 1;
}
return new int[]{year, month};
}
/**
* 根据年月得到ViewPager position
*/
public static int dayToPosition(int year, int month, int startY, int startM) {
return (year - startY) * 12 + month - startM;
}
public static int getPxSize(Context context, int size) {
return size * context.getResources().getDisplayMetrics().densityDpi;
}
public static int getTextSize(Context context, int size) {
return (int) (size * context.getResources().getDisplayMetrics().scaledDensity);
}
}
|
package com.unicss.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.regex.Pattern;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
public class DateUtil {
public final static String diagonalFormatDefault = "MM/dd/yyyy";
public final static String diagonalFormatAll = "MM/dd/yyyy hh:mm:ss";
public final static String diagonalFormatExceptS = "MM/dd/yyyy hh:mm";
public final static String ORIGIN_DATE = "1970-01-01 00:00:00";
public final static String FORMAT_TYPE_ALL = "yyyy-MM-dd HH:mm:ss";
// add by jcy 20121019
public final static String LONG_PATTERN = "yyyyMMddHHmm";
// add by jcy 20130616
public final static String SHORT_PATTERN = "yyyyMMdd";
public final static String FULL_PATTERN = "yyyyMMddHHmmss";
// add by jcy 20121207
public final static String TIME_PATTERN = "HH:mm";
public final static String DEFAULT_PATTERN = "yyyy-MM-dd";
public final static String SHORT_TIME_PATTERN = "yyyy-MM-dd HH:mm";
public static final String MS_FULL_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
/**
* 格式化日期到字符串
*
* @param date
* Date
* @param formatStr
* 格式化字符串
* @return
*/
public static String dateFormat(Date date, String formatStr) {
SimpleDateFormat formater = null;
try {
formater = new SimpleDateFormat(formatStr);
} catch (Exception e) {
e.printStackTrace();
}
return formater.format(date);
}
/**
* add by jcy 20121207 获取当期日期是一个星期中的某天
*
* @return
*/
public static int dayOfWeek() {
return dayOfWeek(new Date());
}
/**
* add by jcy 20121207 根据日期获取当期日期是一个星期中的某天 星期一 星期二 星期三 ...星期日 1 2 3 ...7
*
* @param date
* @return
*/
public static int dayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (week < 0)
week = 7;
return week;
}
/**
* 获取 yyyy-MM-dd 格式时间
*
* @param date
* @return
*/
public static String getDate2Default(Date date) {
String dateStr = new SimpleDateFormat(DateUtil.DEFAULT_PATTERN)
.format(date);
return dateStr;
}
/**
* add by jcy 20121020 将yyyy-MM-dd HH 格式转换为 yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String beginHour(String date) {
return date.trim() + ":00:00";
}
/**
* add by jcy 20121022 将yyyy-MM-dd HH格式转换为 yyyy-MM-dd HH:mm:ss.999
*
* @param date
* @return
*/
public static String endHour(String date) {
return date.trim() + ":59:59.999";
}
/**
* add by jcy 20121124 将yyyy-MM-dd 格式转换为 yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String endTime(String date) {
return date.trim() + " 23:59:59";
}
public static String timeFomart(long duration) {
int hour = (int) (duration / (1000 * 60 * 60));
int time = (int) duration - hour * (1000 * 60 * 60);
int minute = (int) time / (1000 * 60);
time = time - minute * (1000 * 60);
int second = (int) time / 1000;
time = time - second * 1000;
String result = StringUtil.leftJoin(hour, 2, "0") + ":"
+ StringUtil.leftJoin(minute, 2, "0") + ":"
+ StringUtil.leftJoin(second, 2, "0");
return result;
}
public static Long timeToLong(String time) {
try {
String[] timeArray = time.split(":");
Long hour = 1000 * 60 * 60 * Long.parseLong(timeArray[0]);
Long minute = 1000 * 60 * Long.parseLong(timeArray[1]);
Long second = 1000 * Long.parseLong(timeArray[2]);
return hour + minute + second;
} catch (Exception e) {
return 0L;
}
}
/**
* 分钟转为毫秒
*
* @param time
* @return
*/
public static Long minute2Millisecond(String time) {
try {
Long m = Long.parseLong(time);
return m * 60 * 1000;
} catch (Exception e) {
return 0L;
}
}
public static Long timeToSec(String time) {
try {
String[] timeArray = time.split(":");
Long hour = 60 * 60 * Long.parseLong(timeArray[0]);
Long minute = 60 * Long.parseLong(timeArray[1]);
Long second = Long.parseLong(timeArray[2]);
return hour + minute + second;
} catch (Exception e) {
return 0L;
}
}
/**
* 将字符串转化为Date
*
* @param date字符串
* @param formatStr
* 字符串格式
* @return
*/
public static Date getDate(String date, String formatStr) {
try {
SimpleDateFormat formater = new SimpleDateFormat(formatStr);
return formater.parse(date);
} catch (Exception e) {
return new Date();
}
}
/**
* zkevin 将yyyy-MM-dd格式转换为 yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String beginDay(String date) {
return date.trim() + " 00:00:00";
}
/**
* 获取当天凌晨时间
*
* @param end
*/
public static Date getStartDate(Date end) {
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(end);
Date startDate = null;
try {
startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(dateStr + " 00:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
return startDate;
}
/**
* zkevin 将yyyy-MM-dd格式转换为 yyyy-MM-dd HH:mm:ss.999
*
* @param date
* @return
*/
public static String endDay(String date) {
return date.trim() + " 23:59:59.999";
}
public static boolean isMatchDate(String dateStr) {
String datePattern = "^(?:([0-9]{4}-(?:(?:0?[1,3-9]|1[0-2])-(?:29|30)|"
+ "((?:0?[13578]|1[02])-31)))|"
+ "([0-9]{4}-(?:0?[1-9]|1[0-2])-(?:0?[1-9]|1\\d|2[0-8]))|"
+ "(((?:(\\d\\d(?:0[48]|[2468][048]|[13579][26]))|"
+ "(?:0[48]00|[2468][048]00|[13579][26]00))-0?2-29)))$";
Pattern p = Pattern.compile(datePattern);
return p.matcher(dateStr).matches();
}
/**
* 将传入的日期+-指定的月份,即变更时间的月份
*
* @param date
* @param month
* @return
*/
public static Date changeMonth(Date date, int month) {
Calendar cal = Calendar.getInstance();
cal.setTime(null != date ? date : new Date());
cal.add(Calendar.MONTH, month);
return cal.getTime();
}
public static long diff(String end, String start) {
DateFormat df = new SimpleDateFormat(FORMAT_TYPE_ALL);
long diff = 0;
try {
Date de = df.parse(end);
Date ds = df.parse(start);
diff = (de.getTime() - ds.getTime()) / 1000;
} catch (Exception e) {
e.printStackTrace();
}
return diff;
}
public static Long second2Millisecond(String time) {
try {
Long m = Long.parseLong(time);
return m * 1000;
} catch (Exception e) {
return 0L;
}
}
public static Date getStr2Date(String str, String format) {
DateFormat df = new SimpleDateFormat(format);
Date strDate = null;
try {
strDate = df.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}
public static String addSecond(String strDate) {
Date date1 = getDate(strDate, DateUtil.FORMAT_TYPE_ALL);
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.add(Calendar.SECOND, 1);
Date date2 = cal.getTime();
return dateFormat(date2, DateUtil.FORMAT_TYPE_ALL);
}
public static XMLGregorianCalendar convertDateToXMLGregorianCalendar(Date date) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
XMLGregorianCalendar gc = null;
try {
gc = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
} catch (Exception e) {
e.printStackTrace();
}
return gc;
}
public static Date getDateByAazaon(XMLGregorianCalendar cal){
if(null != cal){
GregorianCalendar ca = cal.toGregorianCalendar();
return ca.getTime();
}else{
return null;
}
}
/**
* 获取amazon订单查询结束时间
* @param date
* @return
*/
public static Date getAmazonEndDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MINUTE, -5);
return cal.getTime();
}
//由于本地服务器时间比正常时间快,所以oracle采购单结束同步时间为当前时间减去30秒
public static Date getOraclePurEndDate(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, -30);
return cal.getTime();
}
}
|
import java.io.*;
import java.lang.*;
import java.util.*;
// #!/usr/bin/python -O
// #include <stdio.h>
// #include <stdlib.h>
// #include <string.h>
// #include<stdbool.h>
// #include<limits.h>
// #include<iostream>
// #include<algorithm>
// #include<string>
// #include<vector>
// using namespace std;
/*
# Author : @RAJ009F
# Topic or Type : GFG/String
# Problem Statement : Longest Common SubString
# Description :
# Complexity :
=======================
#sample output
----------------------
=======================
*/
class LCS
{
public static void printLCS(char A[], char B[])
{
int m = A.length;
int n = B.length;
int[][] L=new int[m+1][n+1];
int i;
int j;
for(i=0; i<=m; i++)
{
for(j=0; j<=n; j++)
{
if(i==0||j==0)
L[i][j]=0;
else if(A[i-1]==B[j-1])
L[i][j] = L[i-1][j-1]+1;
else
L[i][j] = Math.max(Math.max(L[i-1][j], L[i][j-1]),L[i-1][j-1]);
}
}
System.out.println(L[m][n]);
i = m;
j = n;
while(i>0&&j>0)
{
if(A[i-1]==B[j-1])
{
System.out.print(A[i-1]);
i--;
j--;
}
else if(L[i-1][j]>L[i][j-1])
{
i--;
}else
j--;
}
}
public static void main(String args[])
{
String A = "AEDFHR";
String B = "ABCDGH";
printLCS(A.toCharArray(), B.toCharArray());
}
} |
package com.bedroom.common;
/**
* ajax返回类型
*/
public class AjaxResult {
/**状态码,默认操作成功true;失败设置为error*/
private String status = "true";
/**返回信息,返回前端操作的文字结果*/
private String msg = "操作成功";
/**操作成功与否,默认为成功*/
private Boolean success = true;
/**返回的结果集,返回后台的对象*/
private Object object;
//构造函数
public AjaxResult(String status) {
super();
this.status = status;
}
public AjaxResult(String status, String msg) {
super();
this.status = status;
this.msg = msg;
}
public AjaxResult(String status, Object object) {
super();
this.status = status;
this.object = object;
}
public AjaxResult() {
super();
}
//返回的信息集合函数
public static AjaxResult oK() {
return new AjaxResult("true");
}
public static AjaxResult oK(Object object) {
return new AjaxResult("true",object);
}
public static AjaxResult error() {
return new AjaxResult("error");
}
public static AjaxResult error(String msg) {
return new AjaxResult("error",msg);
}
//get和set方法
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
|
package lk.ac.mrt.cse.mscresearch.persistance.dao;
import java.util.List;
import java.util.stream.Collectors;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lk.ac.mrt.cse.mscresearch.persistance.entities.ClassIndex;
import lk.ac.mrt.cse.mscresearch.persistance.entities.MethodIndex;
@Component
public class ClassDAO extends AbstractDAO<ClassIndex> {
@Autowired
private MethodDAO methodDao;
@Override
public ClassIndex save(ClassIndex entity, Session session) {
List<MethodIndex> saved = methodDao.saveAll(entity.getMethods(), session);
entity.setMethods(saved.stream().collect(Collectors.toSet()));
return super.save(entity, session);
}
@Override
public Class<ClassIndex> getEntityClass() {
return ClassIndex.class;
}
@Override
protected String getHashQuarryValueField() {
return "classHash";
}
@Override
protected String getHashQuarryValue(ClassIndex entity) {
return entity.getClassHash();
}
}
|
package com.wrathOfLoD.Utility;
import java.util.List;
/**
* Created by Mitchell on 4/7/2016.
*/
public enum Direction {
DOWN(0, 0, 0, -1),
DOWN_NORTH(0, -1, 1, -1),
DOWN_NORTH_EAST(1, -1, 0, -1),
DOWN_SOUTH_EAST(1, 0, -1, -1),
DOWN_SOUTH(0, 1, -1, -1),
DOWN_SOUTH_WEST(-1, 1, 0, -1),
DOWN_NORTH_WEST(-1, 0, 1, -1),
CENTER(0, 0, 0, 0), //the useless direction that I want to put there anyway
NORTH(0, -1, 1, 0),
NORTH_EAST(1, -1, 0, 0),
SOUTH_EAST(1, 0, -1, 0),
SOUTH(0, 1, -1, 0),
SOUTH_WEST(-1, 1, 0, 0),
NORTH_WEST(-1, 0, 1, 0),
UP(0, 0, 0, 1),
UP_NORTH(0, -1, 1, 1),
UP_NORTH_EAST(1, -1, 0, 1),
UP_SOUTH_EAST(1, 0, -1, 1),
UP_SOUTH(0, 1, -1, 1),
UP_SOUTH_WEST(-1, 1, 0, 1),
UP_NORTH_WEST(-1, 0, 1, 1);
private int qMod;
private int rMod;
private int sMod;
private int hMod;
Direction(int qMod, int rMod, int sMod, int hMod){
this.qMod = qMod;
this.rMod = rMod;
this.sMod = sMod;
this.hMod = hMod;
}
public boolean matches(int matchQ, int matchR, int matchS, int matchH){
return (this.qMod == matchQ) &&
(this.rMod == matchR) &&
(this.sMod == matchS) &&
(this.hMod == matchH);
}
public Position getPosVector(){
return new Position(this.qMod, this.rMod, this.sMod, this.hMod);
}
// for less breakable solution:
// http://www.redblobgames.com/grids/hexagons/#rotation
// http://stackoverflow.com/a/7888655
public Direction clockwise(){
int clockQ = -1 * this.sMod;
int clockR = -1 * this.qMod;
int clockS = -1 * this.rMod;
int clockH = this.hMod;
for(Direction dir : values()){
if(dir.matches(clockQ, clockR, clockS, clockH)){
return dir;
}
}
throw new EnumConstantNotPresentException(Direction.class, "Could not find clockwise of " + this.name());
}
public Direction counterClockwise(){
int cClockQ = -1 * this.rMod;
int cClockR = -1 * this.sMod;
int cClockS = -1 * this.qMod;
int cClockH = this.hMod;
for(Direction dir : values()){
if(dir.matches(cClockQ, cClockR, cClockS, cClockH)){
return dir;
}
}
throw new EnumConstantNotPresentException(Direction.class, "Could not find counterClockwise of " + this.name());
}
public Direction above(){
int aboveQ = this.sMod;
int aboveR = this.qMod;
int aboveS = this.rMod;
int aboveH = Math.min(this.hMod + 1, 1);
for(Direction dir : values()){
if(dir.matches(aboveQ, aboveR, aboveS, aboveH)){
return dir;
}
}
throw new EnumConstantNotPresentException(Direction.class, "Could not find above of " + this.name());
}
public Direction below(){
int belowQ = this.sMod;
int belowR = this.qMod;
int belowS = this.rMod;
int belowH = Math.max(this.hMod - 1, -1);
for(Direction dir : values()){
if(dir.matches(belowQ, belowR, belowS, belowH)){
return dir;
}
}
throw new EnumConstantNotPresentException(Direction.class, "Could not find below of " + this.name());
}
public Direction planar(){
int planarQ = this.qMod;
int planarR = this.rMod;
int planarS = this.sMod;
int planarH = 0;
for(Direction dir : values()){
if(dir.matches(planarQ, planarR, planarS, planarH)){
return dir;
}
}
throw new EnumConstantNotPresentException(Direction.class, "Could not find planar of " + this.name());
}
public Direction inversePlanar(){
int iPQ = -1 * this.sMod;
int iPR = -1 * this.qMod;
int iPS = -1 * this.rMod;
int iPH = this.hMod;
for(Direction dir : values()){
if(dir.matches(iPQ, iPR, iPS, iPH)){
return dir;
}
}
throw new EnumConstantNotPresentException(Direction.class, "Could not find inversePlanar of " + this.name());
}
public Direction inverseSpatial(){
int iSQ = -1 * this.sMod;
int iSR = -1 * this.qMod;
int iSS = -1 * this.rMod;
int iSH = -1 * this.hMod;
for(Direction dir : values()){
if(dir.matches(iSQ, iSR, iSS, iSH)){
return dir;
}
}
throw new EnumConstantNotPresentException(Direction.class, "Could not find inverseSpatial of " + this.name());
}
}
|
package com.izasoft.jcart.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.izasoft.jcart.domain.Permission;
public interface PermissionRepository extends JpaRepository<Permission, Integer> {
}
|
package weather;
public class Grapher {
private final WeatherUtil data;
private String[] stringOfYears = new String[18];
private double[][] data_array = new double[18][4];
private double minOfMaxTemps = 10000;
private double minOfMinTemps = 10000;
public Grapher(WeatherUtil data) {
if ( data == null) {
throw new IllegalArgumentException();
}
this.data = data;
}
public String[] stringYears() {
String[] stringOfYears = new String[18];
for (int i = 0; i < 18; i++) {
String stringYear = Integer.toString((2002 + i));
stringOfYears[i] = stringYear;
}
return stringOfYears;
}
public double[][] makeAnArray() {
for ( int i = 0; i < 18; i++) {
int j = 0;
int year = 2002 + i;
data_array[i][j] = year;
j++;
data_array[i][j] = data.getYearData(year).getAvgTempHigh();
j++;
data_array[i][j] = data.getYearData(year).getAvgPrecipitation();
j++;
data_array[i][j] = data.getYearData(year).getAvgTempLow();
}
this.deltaMax();
this.deltaMin();
return data_array;
}
private void deltaMax() {
for ( int i = 0; i < 18; i++) {
if ( data_array[i][1] < minOfMaxTemps) {
minOfMaxTemps = data_array[i][1];
}
}
for (int j = 0; j < 18; j++) {
data_array[j][1] = (data_array[j][1] - minOfMaxTemps);
}
}
private void deltaMin() {
for ( int i = 0; i < 18; i++) {
if ( data_array[i][3] < minOfMinTemps) {
minOfMinTemps = data_array[i][3];
}
}
for (int j = 0; j < 18; j++) {
data_array[j][3] = (data_array[j][3] - minOfMinTemps);
}
}
public double getMinOfMaxTemps() {
return Math.round(minOfMaxTemps);
}
public double getMinOfMinTemps() {
return Math.round(minOfMinTemps);
}
public double getMaxSlope() {
int index = 1;
double sum = 0;
for (int i = 0; i < 17; i++) {
sum = sum + Math.abs((data_array[i + 1][index] - data_array[i][index]));
}
return (double)Math.round((sum / 17) * 100.0) / 100.0;
}
public double getPrecipitationSlope() {
int index = 2;
double sum = 0;
double[] delta = new double[17];
for (int i = 0; i < 17; i++) {
delta[i] = Math.abs((data_array[i + 1][index] - data_array[i][index]));
}
for( int j = 0; j < 16; j++) {
sum = sum + Math.abs((delta[j+1] - delta[j]));
}
return (double)Math.round((sum / 16) * 100.0) / 100.0;
}
public double getMinSlope() {
int index = 3;
double sum = 0;
for (int i = 0; i < 17; i++) {
sum = sum + Math.abs((data_array[i + 1][index] - data_array[i][index]));
}
return (double)Math.round((sum / 17) * 100.0) / 100.0;
}
}
|
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
Scanner myInput = new Scanner( System.in );
int t = myInput.nextInt();
while(t>0)
{
Queue<Long> q = new LinkedList<Long>();
long a=1,b=2;
q.add(a);q.add(b);
t--;
int n = myInput.nextInt();
long num=1;;
while(n>0)
{
num = q.remove();
n--;
q.add(num*10+1);
q.add(num*10+2);
//System.out.printf("%d ",num);
}
System.out.println(num);
}
}
}
|
package com.example.kimnamgil.testapplication.data;
import android.graphics.drawable.Drawable;
/**
* Created by kimnamgil on 2016. 7. 16..
*/
public class Person {
private String email;
private String name;
private Drawable photo;
//Construct
public Person() {}
public Person(String name, String email, Drawable photo)
{
this.name = name;
this.email = email;
this.photo = photo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Drawable getPhoto() {
return photo;
}
public void setPhoto(Drawable photo) {
this.photo = photo;
}
}
|
package drivetrain.unused;
import drivetrain.DriveControl;
public class AntiTipDriveControl extends DriveControl {//not currently in use
//this is a form of drive control that will be called when we start tipping
private static AntiTipDriveControl antitipdrivecontrol;
private AntiTipDriveControl() {
}
public static AntiTipDriveControl getInstance(){
if(antitipdrivecontrol == null) {
antitipdrivecontrol = new AntiTipDriveControl();
}
return antitipdrivecontrol;
}
public void execute(double x1, double y1, double x2){
//TODO: Make sure these are supposed to be negative
super.execute(-1, -1, 0, 0); //ignore the inputs and run with anti-tip values
}
}
|
package connectfour;
import java.util.ArrayList;
import processing.core.*;
/**
* Connect Four
*
* User chooses red or black.
* Plays against simple AI that drops tokens at strategic locations.
* User has the option to play another game upon completion.
*
* @author Julian Hinsch
*/
public class ConnectFour extends PApplet {
private PFont f;
private String usercolor;
private String compcolor;
private String gamestage;
private Board board;
private Token redtoken;
private Token blacktoken;
/**
* Initializes the background, text, color choice tokens, and gamestage.
*/
public void setup() {
size(720, 480);
background(139,189,255);
displayBoardText();
noLoop();
redtoken = new Token(this, width/2-25, height/2+10, "red", false);
blacktoken = new Token(this, width/2+25, height/2+10, "black", false);
gamestage = "colorchoice";
redraw();
}
/**
* Displays various objects and text depending on the current game stage.
*/
public void draw() {
switch(gamestage) {
case "colorchoice":
displayChoiceText();
redtoken.display();
blacktoken.display();
break;
case "userturn":
board.display();
break;
case "compturn":
board.display();
break;
case "userwin":
board.display();
displayUserWinText();
break;
case "compwin":
board.display();
displayCompWinText();
break;
case "fullboard":
board.display();
displayBoardFullText();
break;
default:
break;
}
}
/**
* Executes different code depending on the current game stage.
*/
public void mouseClicked() {
switch(gamestage) {
case "colorchoice":
if (redtoken.mouseWithin()) {
//user chose red
usercolor = "red";
compcolor = "black";
board = new Board(this);
board.initializeTokenArray();
redraw();
gamestage = "userturn";
break;
} else if (blacktoken.mouseWithin()) {
//user chose black
usercolor = "black";
compcolor = "red";
board = new Board(this);
board.initializeTokenArray();
redraw();
gamestage = "userturn";
break;
}
break;
case "userturn":
boolean usermoved = false;
for (int x = 0; x < 7; x++) {
for (int y = 0; y < 6; y++) {
//determine which token (if any) the mouse is above
if (board.tokenarray[x][y].mouseWithin()) {
//make sure the column isn't full
if (board.tokenarray[x][5].getColor().equals("blue")) {
executeMove(x, y, usercolor);
usermoved = true;
redraw();
}
}
}
}
if(usermoved == false) {
break;
} else if (board.testWin(usercolor)) {
gamestage = "userwin";
redraw();
break;
} else {
gamestage = "compturn";
//wait for 1 second - not necessary but better for UX
try {
Thread.sleep(1000);
} catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
//computer moves
compMove();
redraw();
if (board.testWin(compcolor)) {
gamestage = "compwin";
redraw();
usermoved = false;
break;
} else if (board.getNumTokens() == 42) {
//computer filled the board
gamestage = "fullboard";
redraw();
usermoved = false;
break;
} else {
//return control to user
gamestage = "userturn";
redraw();
usermoved = false;
break;
}
}
case "compturn":
break;
case "userwin":
gamestage = "colorchoice";
board.hide();
redraw();
break;
case "compwin":
gamestage = "colorchoice";
board.hide();
redraw();
break;
case "fullboard":
gamestage = "colorchoice";
board.hide();
redraw();
break;
default:
break;
}
}
/**
* Place a token in the most strategic column.
*/
private void compMove() {
int x = findBestMove();
executeMove(x, 5, compcolor);
}
/**
* Sets token color at lowest possible row.
*
* @param x, the selected column.
* @param maxY, the desired row selected by user (computer always selects top row).
* @param color, the color to change the token to.
*/
private void executeMove(int x,int maxY,String color){
for (int y = 0; y <= maxY; y++) {
//iterate up column
if (board.tokenarray[x][y].getColor().equals("blue")) {
//execute move - only once
board.tokenarray[x][y].setColor(color);
board.setNumTokens(board.getNumTokens()+1);
return;
}
}
}
/**
* Find Best Move Method
*
* There are never more than 7 possible moves.
* A score is calculated for each move based on its neighbors.
* The move with the best score is returned.
* If there are multiple possible moves with the same score,
* one is chosen randomly.
*/
private int findBestMove() {
int[] moveScores = {0,0,0,0,0,0,0};
for (int x = 0; x < 7; x++) {
for (int y = 0; y<6; y++) {
if (board.tokenarray[x][y].getColor().equals("blue")) {
//check if this move can be made
//due to 'gravity', move must be on floor or above a previously placed token
if (y==0 || !board.tokenarray[x][y-1].getColor().equals("blue")) {
moveScores[x]=calculateMoveScore(x,y);
break;
}
}
}
}
//iterate over moveScores
//find the best score, and store all moves with this score
int bestScore = 0;
ArrayList<Integer> bestMoves = new ArrayList<Integer>();
//pick the best move in the list
for (int x = 0; x < 7; x++) {
if (moveScores[x]==bestScore) {
//move is equivalent to moves already in bestMoves
bestMoves.add(x);
} else if (moveScores[x]>bestScore) {
//reinitialize bestMoves with only this move
bestMoves = new ArrayList<Integer>();
bestMoves.add(x);
//this move had the best score so far
bestScore = moveScores[x];
}
}
//randomly select a move from bestMoves
int randomindex = (int)(Math.random() * bestMoves.size());
return bestmoves.get(randomindex);
}
/**
* Calculates a score (0-4) for a possible move based on neighboring tokens.
*
* @param x, the x position of the move to be considered
* @param y, the y position of the move to be considered
*/
private int calculateMoveScore(int x,int y) {
int hzontaluser=min(3,(countNeighborsDirection(x,y,usercolor,1,0)+countNeighborsDirection(x,y,usercolor,-1,0)));
int vticaluser=countNeighborsDirection(x,y,usercolor,0,-1);
int rdiaguser=min(3,(countNeighborsDirection(x,y,usercolor,1,1)+countNeighborsDirection(x,y,usercolor,-1,-1)));
int ldiaguser=min(3,(countNeighborsDirection(x,y,usercolor,-1,1)+countNeighborsDirection(x,y,usercolor,1,-1)));
int maxuserneighbors=max(max(hzontaluser,vticaluser),max(rdiaguser,ldiaguser));
int hzontalcomp = min(3,(countNeighborsDirection(x,y,compcolor,1,0)+countNeighborsDirection(x,y,compcolor,-1,0)));
int vticalcomp = countNeighborsDirection(x,y,compcolor,0,-1);
int rdiagcomp = min(3,(countNeighborsDirection(x,y,compcolor,1,1)+countNeighborsDirection(x,y,compcolor,-1,-1)));
int ldiagcomp = min(3,(countNeighborsDirection(x,y,compcolor,-1,1)+countNeighborsDirection(x,y,compcolor,1,-1)));
int maxcompneighbors = max(max(hzontalcomp,vticalcomp),max(rdiagcomp,ldiagcomp));
if (maxcompneighbors == 3) {
//this is a winning move for the computer
return 4;
} else {
return max(maxuserneighbors,maxcompneighbors);
}
}
/**
* Look for user tokens near the move to be considered,
* in a direction specified by parameters xiter and yiter.
*
* Returns the number of tokens in that direction (0, 1, 2, or 3).
*
* @param x, the x position of the move to be considered
* @param y, the y position of the move to be considered
* @param color, the color of the tokens to look for
* @param xiter, the direction to iterate the x-coordinate
* @param yiter, the direction to iterate the y-coordinate
*/
private int countNeighborsDirection(int x, int y, String color, int xiter, int yiter) {
int count=0;
for (int i = 1; i <= 3; i++) {
//x is out of bounds
if(x+(xiter*i)>6 || x+(xiter*i)<0 ) {
break;
//y is out of bounds
} else if(y+(yiter*i)>5 || y+(yiter*i)<0 ) {
break;
} else if (!board.tokenarray[x+(xiter*i)][y+(yiter*i)].getColor().equals(color)) {
break;
} else {
count++;
}
}
return count;
}
/**
* Displays "Board is full!", "Click anywhere to play again."
*/
private void displayBoardFullText() {
fill(255);
textAlign(CENTER);
f = createFont("Helvetica-Bold",20,true);
textFont(f);
text("Board is full!",width/2,height/2+180);
text("Click anywhere to play again.",width/2,height/2+200);
}
/**
* Displays "Connect Four", "Copyright Julian Hinsch 2017"
*/
private void displayBoardText(){
fill(255);
textAlign(CENTER);
f = createFont("Helvetica-Bold",48,true);
textFont(f);
text("Connect Four",width/2,65);
f = createFont("Helvetica-Bold",15,true);
textFont(f);
text("\u00a9 2017 Julian Hinsch",width/2,470);
}
/**
* Displays "Choose black or red: "
*/
private void displayChoiceText() {
fill(255);
textAlign(CENTER);
f = createFont("Helvetica-Bold",24,true);
textFont(f);
text("Choose red or black:",width/2,height/2-30);
}
/**
* Displays "You lost!", "Click anywhere to play again."
*/
private void displayCompWinText() {
fill(255);
textAlign(CENTER);
f = createFont("Helvetica-Bold",20,true);
textFont(f);
text("You lost!",width/2,height/2+180);
text("Click anywhere to play again.",width/2,height/2+200);
}
/**
* Displays "You won!", "Click anywhere to play again."
*/
private void displayUserWinText() {
fill(255);
textAlign(CENTER);
f = createFont("Helvetica-Bold",20,true);
textFont(f);
text("You won!",width/2,height/2+180);
text("Click anywhere to play again.",width/2,height/2+200);
}
}
|
package hadoop.inputformat;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.net.InetAddress;
public class WordCountReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
InetAddress addr = null;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
addr = InetAddress.getLocalHost();
context.getCounter("r","WordCountReducer.setup." + addr).increment(1);
}
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int maxValue = Integer.MIN_VALUE;
Integer count = 0;
for(IntWritable v : values){
count += v.get() ;
}
context.write(key,new IntWritable(count));
}
@Override
protected void cleanup(Context context) throws IOException, InterruptedException {
context.getCounter("r","WordCountReducer.cleanup." + addr).increment(1);
}
}
|
package raig.org.states;
public interface State {
void quarterInserted();
void turnsCrank();
void gumballsFinished();
void dispense();
String statetoString();
void gumballsNotFinished();
}
|
public class Main {
public static void main(String[] args) {
String[] raduga = {"Красный", "Оранжевый", "Желтый", "Зеленый", "Голубой", "Синий", "Фиолетовый"};
for (int i = 0; i < raduga.length; i++) {
System.out.print(raduga[i] + " ");
}
int middleOfArray = (raduga.length+1)/2;
for (int i = 0; i < raduga.length/2 ; i++) {
String temp = raduga[i];
raduga[i] = raduga[(middleOfArray +2)-i];
raduga[(middleOfArray +2)-i] = temp;
}
System.out.println("");
for (int i = 0; i < raduga.length; i++) {
System.out.print(raduga[i] + " ");
}
}
}
|
package com.seleniumpom.tests.framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by bbeck on 7/29/2016.
*/
public class BrowserUtil {
// Changed enum to uppercase, so it's easier to convert a string to a enum
public enum BrowserType
{
FIREFOX, CHROME, INTERNET_EXPLORER, EDGE, HTML_UNIT_DRIVER
}
public enum DriverType
{
LOCAL, REMOTE
}
public WebDriver GetWebDriver(DriverType driverType, BrowserType browser)
{
switch(driverType){
case LOCAL:
return getLocalDriver(browser);
case REMOTE:
return getRemoteDriver(browser);
default:
throw new RuntimeException("Unexpected webdriver type " + driverType.toString());
}
}
private WebDriver getLocalDriver(BrowserType browser){
//We can include all this in a try catch if we find that the test harness has issues with binding
try {
switch(browser)
{
case CHROME:
System.setProperty("webdriver.chrome.driver", getDriverPath("chromedriver.exe"));
return new ChromeDriver();
case FIREFOX:
return new FirefoxDriver();
case INTERNET_EXPLORER:
return new InternetExplorerDriver();
case EDGE:
return new EdgeDriver();
case HTML_UNIT_DRIVER:
return new HtmlUnitDriver();
default:
return new FirefoxDriver(); //Arbitrarily choosing FIREFOX as default choice
}
}
catch(Exception e)
{
throw new RuntimeException("Couldn't find appropriate executable with which to build webdriver");
}
}
private WebDriver getRemoteDriver(BrowserType browser){
TestConfiguration testConfiguration = TestConfiguration.getInstance();
String gridUrl = testConfiguration.getSeleniumGridURL();
DesiredCapabilities desiredCapabilities = null;
switch (browser){
case CHROME:
desiredCapabilities = DesiredCapabilities.chrome();
break;
case EDGE:
desiredCapabilities = DesiredCapabilities.edge();
break;
case FIREFOX:
desiredCapabilities = DesiredCapabilities.firefox();
break;
case HTML_UNIT_DRIVER:
desiredCapabilities = DesiredCapabilities.htmlUnitWithJs();
break;
case INTERNET_EXPLORER:
desiredCapabilities = DesiredCapabilities.internetExplorer();
break;
}
try {
return new RemoteWebDriver(new URL(testConfiguration.getSeleniumGridURL()), desiredCapabilities);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
private String getDriverPath(String driverExecutableName)
{
try {
File file = new File(getClass().getClassLoader().getResource(driverExecutableName).getFile());
Runtime.getRuntime().exec(file.getAbsolutePath());
return file.getAbsolutePath();
}
catch (IOException exception)
{
System.out.println("Failed to find driver executable: " + driverExecutableName +" Exception: " + exception.toString());
}
return null;
}
public String getFilePath(String fileName)
{
try {
File file = new File(getClass().getClassLoader().getResource(fileName).getFile());
return file.getAbsolutePath();
}
catch (Exception exception)
{
System.out.println("Failed to find file: " + fileName +" Exception: " + exception.toString());
}
return null;
}
} |
package com.example.canyetismis.runningtracker;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "trackerDB", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE myList(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"avgSpeed FLOAT, "+
"maxSpeed FLOAT, "+
"totalDistance VARCHAR(128)," +
"totalDuration VARCHAR(128)," +
"date VARCHAR(128)," +
"time INTEGER" +
");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS myList");
onCreate(db);
}
}
|
/*
runtime O(n^2) = (n to iterate each start) * (n to iterate each end)
space O(n) = queue
*/
public boolean wordBreak(String s, List<String> wordDict){
Set<String> dictionary = new HashSet<>(wordDict);
Queue<Integer> startIndices = new LinkedList<>();
boolean[] visited = new boolean[s.length()];
startIndices.offer(0);
while(!startIndices.isEmpty()){
int start = startIndices.poll();
if(!visited[start]){
for(int end = start + 1; end <= s.length(); end++){
if(dictionary.contains(s.substring(start, end))){
if(end == s.length()){
return true;
}
startIndices.offer(end);
}
}
visited[start] = true;
}
}
return false;
} |
package com.example.ecommerce;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import com.example.ecommerce.Prevalent.Prevalent;
import com.example.ecommerce.databinding.ActivityConfirmFinalOrderBinding;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class ConfirmFinalOrderActivity extends AppCompatActivity {
ActivityConfirmFinalOrderBinding activityConfirmFinalOrderBinding;
private ClickHandler clickHandler;
private String totalAmount = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityConfirmFinalOrderBinding = DataBindingUtil.setContentView(this,R.layout.activity_confirm_final_order);
totalAmount = getIntent().getStringExtra("Total Price");
totalAmount.replaceAll("[^\\d.-]", "");
clickHandler = new ClickHandler(this);
activityConfirmFinalOrderBinding.setClickHandler(clickHandler);
activityConfirmFinalOrderBinding.buttonConfirmFinalOrder.setOnClickListener(view ->{
Check();
});
}
private void Check() {
if(TextUtils.isEmpty(activityConfirmFinalOrderBinding.editTextNameFinalOrder.getText().toString())){
Toast.makeText(this, "Please Provide your full name", Toast.LENGTH_SHORT).show();
}else if(TextUtils.isEmpty(activityConfirmFinalOrderBinding.editTextPhoneNumberFinalOrder.getText().toString()) || Integer.parseInt(activityConfirmFinalOrderBinding.editTextPhoneNumberFinalOrder.getText().toString()) < 10){
Toast.makeText(this, "Please Provide your phone number.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(activityConfirmFinalOrderBinding.editTextAddressFinalOrder.getText().toString())){
Toast.makeText(this, "Please Provide your address.", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(activityConfirmFinalOrderBinding.editTextCityFinalOrder.getText().toString())){
Toast.makeText(this, "Please Provide your city name", Toast.LENGTH_SHORT).show();
}else{
ConfirmOrder();
}
}
private void ConfirmOrder() {
final String saveCurrentDate, saveCurrentTime;
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy");
saveCurrentDate = currentDate.format(calForDate.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("h:mm a");
saveCurrentTime = currentTime.format(calForDate.getTime());
final DatabaseReference ordersRef = FirebaseDatabase.getInstance().getReference().child("Orders")
.child(Prevalent.currentUserOnline.getPhoneNumber());
final HashMap<String, Object> ordersMap = new HashMap<>();
ordersMap.put("totalAmount", totalAmount);
ordersMap.put("name", activityConfirmFinalOrderBinding.editTextNameFinalOrder.getText().toString());
ordersMap.put("phone", activityConfirmFinalOrderBinding.editTextPhoneNumberFinalOrder.getText().toString());
ordersMap.put("address", activityConfirmFinalOrderBinding.editTextAddressFinalOrder.getText().toString());
ordersMap.put("city", activityConfirmFinalOrderBinding.editTextCityFinalOrder.getText().toString());
ordersMap.put("date", saveCurrentDate);
ordersMap.put("time", saveCurrentTime);
ordersMap.put("state", "not shipped");
ordersRef.updateChildren(ordersMap).addOnCompleteListener(task -> {
if(task.isSuccessful()){
FirebaseDatabase.getInstance().getReference()
.child("Cart List")
.child("User View")
.child(Prevalent.currentUserOnline.getPhoneNumber())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(ConfirmFinalOrderActivity.this, "Your order has been placed", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ConfirmFinalOrderActivity.this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);// stop user going back
startActivity(intent);
}
}
});
}
});
}
public class ClickHandler {
private Context context;
public ClickHandler(Context context) {
this.context = context;
}
}
}
|
package com.cheese.radio.ui.media.anchor.entity.description;
import android.databinding.ObservableField;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.ProgressBar;
import com.binding.model.model.ModelView;
import com.binding.model.model.ViewModel;
import com.cheese.radio.R;
import com.cheese.radio.databinding.FragmentAnchorMsgBinding;
import com.cheese.radio.ui.Constant;
import com.cheese.radio.util.MyBaseUtil;
import javax.inject.Inject;
/**
* Created by 29283 on 2018/3/24.
*/
@ModelView(R.layout.fragment_anchor_msg)
public class DescriptionFragmentModel extends ViewModel<DescriptionFragment,FragmentAnchorMsgBinding> {
private WebView webView;
private ProgressBar progressBar;
@Inject DescriptionFragmentModel(){}
public ObservableField<String> descriptionText = new ObservableField<>();
@Override
public void attachView(Bundle savedInstanceState, DescriptionFragment fragment) {
super.attachView(savedInstanceState, fragment);
Bundle bundle=fragment.getArguments();
if (bundle!=null){
descriptionText.set(bundle.getString(Constant.description));
}
webView = getDataBinding().webview;
webView.loadData(descriptionText.get(),"text/html", "utf-8");
// MyBaseUtil.setWeb(webView,descriptionText.get());
}
}
|
package com.karya.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="accprofitlossstatement001mb")
public class AccountProfitLossStatement001MB implements Serializable{
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "aplsId")
private int aplsId;
@Column(name="company")
private String company;
@Column(name="startYear")
private String startYear;
@Column(name="endYear")
private String endYear;
@Column(name="periodicity")
private String periodicity;
@Column(name="account")
private String account;
@Column(name="costcenter")
private String costcenter;
@Column(name="projectname")
private String projectname;
@Column(name="jan")
private String jan;
@Column(name="feb")
private String feb;
@Column(name="mar")
private String mar;
@Column(name="apr")
private String apr;
@Column(name="may")
private String may;
@Column(name="jun")
private String jun;
@Column(name="jul")
private String jul;
@Column(name="aug")
private String aug;
@Column(name="sep")
private String sep;
@Column(name="oct")
private String oct;
@Column(name="nov")
private String nov;
@Column(name="dece")
private String dece;
public int getAplsId() {
return aplsId;
}
public void setAplsId(int aplsId) {
this.aplsId = aplsId;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getStartYear() {
return startYear;
}
public void setStartYear(String startYear) {
this.startYear = startYear;
}
public String getEndYear() {
return endYear;
}
public void setEndYear(String endYear) {
this.endYear = endYear;
}
public String getPeriodicity() {
return periodicity;
}
public void setPeriodicity(String periodicity) {
this.periodicity = periodicity;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getCostcenter() {
return costcenter;
}
public void setCostcenter(String costcenter) {
this.costcenter = costcenter;
}
public String getProjectname() {
return projectname;
}
public void setProjectname(String projectname) {
this.projectname = projectname;
}
public String getJan() {
return jan;
}
public void setJan(String jan) {
this.jan = jan;
}
public String getFeb() {
return feb;
}
public void setFeb(String feb) {
this.feb = feb;
}
public String getMar() {
return mar;
}
public void setMar(String mar) {
this.mar = mar;
}
public String getApr() {
return apr;
}
public void setApr(String apr) {
this.apr = apr;
}
public String getMay() {
return may;
}
public void setMay(String may) {
this.may = may;
}
public String getJun() {
return jun;
}
public void setJun(String jun) {
this.jun = jun;
}
public String getJul() {
return jul;
}
public void setJul(String jul) {
this.jul = jul;
}
public String getAug() {
return aug;
}
public void setAug(String aug) {
this.aug = aug;
}
public String getSep() {
return sep;
}
public void setSep(String sep) {
this.sep = sep;
}
public String getOct() {
return oct;
}
public void setOct(String oct) {
this.oct = oct;
}
public String getNov() {
return nov;
}
public void setNov(String nov) {
this.nov = nov;
}
public String getDece() {
return dece;
}
public void setDece(String dece) {
this.dece = dece;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
package practice;
import java.util.Scanner;
public class FactorialSum {
static int factorial;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a number:");
int n = s.nextInt();
s.close();
int sum = 0, f;
System.out.println("-------------------");
System.out.printf("%7s %11s%n", "Number", "Factorial");
System.out.println("-------------------");
for (int i = 1; i <= n; i++) {
factorial = 1;
f = getFactorial(i);
System.out.printf("%4d %9d%n", i, f);
sum = sum + f;
}
System.out.println("-------------------");
System.out.printf("%4s %2s %7d%n", "Sum", "=", sum);
System.out.println("-------------------");
}
static int getFactorial(int num) {
for (int i = num; i > 1; i--) {
factorial = factorial * i;
}
return factorial;
}
}
|
package com.sapl.retailerorderingmsdpharma.observer;
/**
* Created by JARVIS on 19-Feb-18.
*/
public interface Observable <T> {
void register(T observer);
void unregister(T observer);
}
|
package edu.washington.echee.intentsandextras;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.HashMap;
public class SecondActivity extends ActionBarActivity {
HashMap<String, String> map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
createOverviewData();
Intent whoCalledMe = getIntent();
if (whoCalledMe != null) {
String topic = whoCalledMe.getStringExtra("myString"); // math
String myString2 = whoCalledMe.getStringExtra("myString2");
int num = whoCalledMe.getIntExtra("myInt", 0);
Log.i("SecondActivity" , topic + myString2 + num);
// Loads QuestionFragment
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Bundle topicBundle = new Bundle();
topicBundle.putString("topicName", "Math");
topicBundle.putInt("topicName", 32);
topicBundle.putString("topicOverview", "I am done with this math");
QuestionFragment questionFragment = new QuestionFragment();
questionFragment.setArguments(topicBundle);
ft.add(R.id.container, questionFragment); // where , what
ft.commit();
}
}
public void loadAnswerFrag() {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Bundle topicBundle = new Bundle();
topicBundle.putString("topicName", "Math");
topicBundle.putInt("topicName", 32);
topicBundle.putString("topicOverview", "I am done with this math");
AnswerFragment questionFragment = new AnswerFragment();
questionFragment.setArguments(topicBundle);
ft.add(R.id.container, questionFragment); // where , what
ft.commit();
}
public void loadOverFrag() {
}
private void createOverviewData() {
this.map = new HashMap<String, String>();
this.map.put("Physics", "ballkajfdlakjflajwljart");
this.map.put("Math", "ballkajfdlakjflajwljart");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
return true;
}
@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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package util;
import java.time.LocalTime;
public class TotalTimeCalculator {
private static int toSeconds(String time) throws Exception {
String[] s = time.split("\\.");
if (s.length != 3)
throw new Exception("Syntax error!");
int t = 0;
for (int i = 0; i < 3; ++i)
t = t * 60 + Integer.parseInt(s[i]);
return t;
}
public static String computeDifference(String start, String finish) {
try {
int startSeconds = toSeconds(start);
int finishSeconds = toSeconds(finish);
int diffSeconds = finishSeconds - startSeconds;
if (diffSeconds < 0)
throw new Exception("Negative!");
int[] time = secondsToTime(diffSeconds);
return String.format("%02d.%02d.%02d", time[0], time[1], time[2]);
} catch (Exception e) {
return "--.--.--";
}
}
private static int[] secondsToTime(int seconds) {
int[] time = new int[3];
time[2] = seconds % 60;
time[1] = (seconds / 60) % 60;
time[0] = (seconds / (60 * 60)) % 60;
return time;
}
public static boolean isCorrectFormat(String input) {
try {
timeFormatter(input);
return true;
} catch (Exception e) {
return false;
}
}
public static String timeFormatter(String input) throws Exception {
int tempSeconds = toSeconds(input);
int[] time = secondsToTime(tempSeconds);
return String.format("%02d.%02d.%02d", time[0], time[1], time [2]);
}
public static boolean possibleTotalTime(String start, String finish) {
if (start.length() == 0 || finish.length() == 0) return true;
try {
int s = toSeconds(start);
int f = toSeconds(finish);
int d = f - s;
if (d < 15 * 60) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}
public static String getCurrentTime() {
LocalTime currentTime = LocalTime.now();
String hour = String.format("%02d", currentTime.getHour());
String minute = String.format("%02d", currentTime.getMinute());
String second = String.format("%02d", currentTime.getSecond());
return hour + "." + minute + "." + second;
}
}
|
package br.unibh.loja.negocio;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import br.unibh.loja.entidades.Categoria;
import br.unibh.loja.entidades.Cliente;
import br.unibh.loja.entidades.Produto;
import br.unibh.loja.util.Resources;
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TesteServicoCliente {
@Deployment
public static Archive<?> createTestArchive() {
// Cria o pacote que vai ser instalado no Wildfly para realizacao dos testes
return ShrinkWrap.create(WebArchive.class, "testeloja.war")
.addClasses(Categoria.class, Cliente.class, Produto.class, Resources.class, DAO.class,
ServicoCliente.class)
.addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
// Realiza as injecoes com CDI
@Inject
private Logger log;
@Inject
private ServicoCliente sc;
@Test
public void teste01_inserirSemErro() throws Exception {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date dataN = (Date) formatter.parse("26/12/1994");
Date dataC = (Date) formatter.parse("10/05/2018");
log.info("============> Iniciando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
Cliente o = new Cliente(1L, "Guilherme Barreto", "gbbastos", "teste", "Standard", "07685836670", "(31)98472-7667",
"gbbastos1994@gmail.com", dataN, dataC);
sc.insert(o);
Cliente aux = (Cliente) sc.findByName("gbbastos").get(0);
assertNotNull(aux);
log.info("============> Finalizando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
}
@Test
public void teste02_inserirComErro() throws Exception {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date dataN = (Date) formatter.parse("26/12/1994");
Date dataC = (Date) formatter.parse("10/05/2018");
log.info("============> Iniciando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
try {
Cliente o = new Cliente(1L, "Guilherme Barreto@", "gbbastos", "teste", "Standard", "07685836670",
"(31)98472-7667", "gbbastos1994@gmail.com", dataN, dataC);
sc.insert(o);
} catch (Exception e) {
assertTrue(checkString(e, "Caracteres permitidos: letras, espašos, ponto e aspas simples"));
}
log.info("============> Finalizando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
}
@Test
public void teste03_atualizar() throws Exception {
log.info("============> Iniciando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
Cliente o = (Cliente) sc.findByName("gbbastos").get(0);
o.setLogin("gbbastos1994");
sc.update(o);
Cliente aux = (Cliente) sc.findByName("gbbastos1994").get(0);
assertNotNull(aux);
log.info("============> Finalizando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
}
@Test
public void teste04_excluir() throws Exception {
log.info("============> Iniciando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
Cliente o = (Cliente) sc.findByName("gbbastos").get(0);
sc.delete(o);
assertEquals(0, sc.findByName("gbbastos1994").size());
log.info("============> Finalizando o teste " + Thread.currentThread().getStackTrace()[1].getMethodName());
}
private boolean checkString(Throwable e, String str) {
if (e.getMessage().contains(str)) {
return true;
} else if (e.getCause() != null) {
return checkString(e.getCause(), str);
}
return false;
}
} |
package com.acewill.ordermachine.pos;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.acewill.ordermachine.activity.WshCreateDeal;
import com.acewill.ordermachine.common.Common;
import com.acewill.ordermachine.model.LoginRep;
import com.acewill.ordermachine.model.LoginReqModel;
import com.acewill.ordermachine.model.StoreInfoResp;
import com.acewill.ordermachine.model.StringResp;
import com.acewill.ordermachine.util.SharedPreferencesUtil;
import com.acewill.ordermachine.util_new.PrintFile;
import com.acewill.ordermachine.util_new.ToastUtils;
import com.acewill.paylibrary.PayReqModel;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.GenericsCallback;
import com.zhy.http.okhttp.callback.StringCallback;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import okhttp3.Call;
import static com.zhy.http.okhttp.OkHttpUtils.post;
public class NewPos {
// public static String BASE_URL_SZ = "http://43.241.226.10:18080/";
// public static String BASE_URL = "http://www.smarant.com:8080/";
// public static String BASE_URL = "http://sz.canxingjian.com/";
private boolean isDebug = false;
public static String BASE_URL = "";
private static final String TAG = "NewPos";
public static String loginUrl = "/api/terminal/login";
public static String paytypesUrl = "/api/terminal/paytypes";
public static String bindUrl = "/api/terminal/bind";
public static String unbindUrl = "/api/terminal/unbind";
public static String store_operation = "/api/store_operation";
private static String memberUrl = "public/members/getMemberInfo";
private static String printListUrl = "api/kichenStalls/getPrinters";
private static String storeConfigurationUrl = "api/store_operation/getStoreConfiguration";
private static String historyOrderUrl = "api/terminal/getOrderHistoryByDate";
private static String dailyReportUrl = "api/report/daily";
private static String endDailyBusinessUrl = "api/orders/endDailyBusiness";
public static String token = "";
public static boolean HAVA_WX;
public static boolean HAVA_ALI;
public static boolean HAVA_SWIFTPASS;
public static boolean HAVA_CASH;
public static final int WX_PAY = 2;
public static final int ALI_PAY = 1;
public static final int HY_PAY = 6;
public static final int SWIFTPASS_PAY = -8;//威富通支付
private static NewPos mInstance;
private String openWorkShiftUrl = "/api/store_operation/work_shifts";
private String workShiftUrl = "api/store_operation/work_shift_definition";
private String startWorkShiftUrl = "/api/store_operation/work_shifts_dc";
private String endWordShiftUrl = "/api/store_operation/end_work_shifts_dc";
private String workShiftsStore = "/api/store_operation/work_shifts_store";
private String workShiftReportUrl = "/api/report/workShift";
private String validateURL = "/management/user/sendValidateCode";
private String forgetPwdUrl = "/management/user/forgetPwd";
public String dishMenuUrl = "/api/terminal/dishmenu/sku?token=";
public String dishKindUrl = "/api/terminal/dishKind?token=";
private String FaceToFacePayment = "alipay/FaceToFacePayment";
private String queryAlipayResult = "alipay/queryAlipayResult";
public static NewPos getInstance(Context context) {
if (mInstance == null) {
mInstance = new NewPos();
}
return mInstance;
}
public static String getBaseUrl() {
return "http://" + BASE_URL;
}
public String userLoginUrl = "api/terminal/userlogin";
public String getDishMenuUrl() {
return getBaseUrl() + dishMenuUrl + token;
}
public String getDishKindUrl() {
return getBaseUrl() + dishKindUrl + token;
}
private String getOpenWorkShiftUrl() {
return getBaseUrl() + openWorkShiftUrl;
}
private String getWorkShiftUrl() {
return getBaseUrl() + workShiftUrl;
}
private String getHistoryOrderUrl() {
return getBaseUrl() + historyOrderUrl;
}
private String getDailyReportUrl() {
return getBaseUrl() + dailyReportUrl;
}
private String getEndDailyBusinessUrl() {
return getBaseUrl() + endDailyBusinessUrl;
}
private String startWorkShiftUrl() {
return getBaseUrl() + startWorkShiftUrl;
}
private String getWorkShiftsStoreUrl() {
return getBaseUrl() + workShiftsStore;
}
private String getWorkShiftReportUrl() {
return getBaseUrl() + workShiftReportUrl;
}
private String getStoreConfigurationUrl() {
return getBaseUrl() + storeConfigurationUrl;
}
/**
* 获取门店设置信息
*
* @return
*/
public void getStoreConfiguration() {
OkHttpUtils.post().url(getStoreConfigurationUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.build().execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
e.printStackTrace();
}
@Override
public void onResponse(String response, int id) {
Log.e(TAG, "response>>" + response);
}
});
}
/**
* 获取交接班报表数据,用来打印的
*
* @return
*/
public void workShiftReport(String workShiftId, String endWorkAmount, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.get().url(getWorkShiftReportUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("workShiftId", workShiftId)
.addParams("endWorkAmount", endWorkAmount)
.build().execute(callback);
}
/**
* 获取日结报表,用来打印的
*
* @return
*/
public void dailyReport(com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.get().url(getDailyReportUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("brandId", LoginReqModel.brandid)
.build().execute(callback);
}
/**
* 日结
*
* @return
*/
public void endDailyBusiness(com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.post().url(getEndDailyBusinessUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("brandId", LoginReqModel.brandid)
.build().execute(callback);
}
/**
* 获取历史订单
*
* @return
*/
public void getHistoryOrder(String startDate, String endDate, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.post().url(getHistoryOrderUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("startDate", startDate)
.addParams("endDate", endDate)
.addParams("token", token)
.build().execute(callback);
}
/**
* 获取交接班记录
*
* @return
*/
public void getWorkShiftStore(String startTime, String endTime, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.get().url(getWorkShiftsStoreUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("startTime", startTime)
.addParams("endTime", endTime).build().execute(callback);
}
/**
* 开启一个班次
*
* @return
*/
public void startWorkShift(String workShift, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.post().url(startWorkShiftUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("workShift", workShift).build().execute(callback);
}
/**
* 检测当前是否有未交的班次
*
* @return
*/
public void getOpenWorkShift(com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.get().url(getOpenWorkShiftUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("terminalId", Common.SHOP_INFO.terminalid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("userName", Common.SHOP_INFO.userphone).build().execute(callback);
}
/**
* 获取后台定义的班次信息
*
* @return
*/
public void getWorkShift(com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.get().url(getWorkShiftUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("storeId", LoginReqModel.storeid)
.build().execute(callback);
}
public String getUserLoginUrl() {
return getBaseUrl() + userLoginUrl;
}
public void userLogin(String phone, String pwd, StringCallback callback) {
OkHttpUtils
.post()
.url(getUserLoginUrl())
.addParams("username", phone)
.addParams("pwd", pwd)
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.build()
.execute(callback);
}
public String getPrintListUrlUrl() {
return getBaseUrl() + printListUrl;
}
public void getPrintList(StringCallback callback) {
OkHttpUtils
.post()
.url(getPrintListUrlUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.build()
.execute(callback);
}
public String checkUserAuthorityUrl = "/api/terminal/checkUserAuthority";
public String getRefundReasonUrl() {
return getBaseUrl() + refundReasonUrl;
}
public String refundReasonUrl = "/api/orders/reason";
public void getRefundReason(StringCallback callback) {
OkHttpUtils
.get()
.url(getRefundReasonUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.build()
.execute(callback);
}
public void checkAthourity(String username, String pwd, String authroityid, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getCheckAthroityUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("username", username)
.addParams("pwd", pwd)
.addParams("authroityid", authroityid)
.build()
.execute(callback);
}
private String getCheckAthroityUrl() {
return getBaseUrl() + checkUserAuthorityUrl;
}
/**
* 交班
*
* @param workShiftId
* @param workShift
* @param callback
*/
public void endWorkShift(long workShiftId, String workShift, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getEndWordShiftUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("id", workShiftId + "")
.addParams("workShift", workShift)
.build()
.execute(callback);
}
private String getEndWordShiftUrl() {
return getBaseUrl() + endWordShiftUrl;
}
public boolean isDebug() {
return isDebug;
}
public void sendValidateMsg(String phone, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.post().url(getValidateURL()).addParams("username", phone)
.addParams("isLogin", "true").build().execute(callback);
}
private String getValidateURL() {
return getBaseUrl() + validateURL;
}
private String getForgetPwdUrl() {
return getBaseUrl() + forgetPwdUrl;
}
public void forgetPwd(String user, String pwd, StringCallback callback) {
OkHttpUtils.post().url(getForgetPwdUrl()).addParams("username", user)
.addParams("validateCode", pwd).build().execute(callback);
}
private String backoutUrl = "/api/orders/backout";
private String getBackOutUrl() {
return getBaseUrl() + backoutUrl;
}
public void backOut(String cost, String payNo, String paymentTypeId, StringCallback callback) {
OkHttpUtils
.post()
.url(getBackOutUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("total_fee", cost)
.addParams("paymentNo", payNo)
.addParams("paymentTypeId", paymentTypeId)
.addParams("returnUserName", LoginReqModel.tname)
.addParams("token", token)
.build()
.execute(callback);
}
public interface Callback<T> {
void onError(Call call, Exception e, int id);
void onResponse(T response, int id);
}
public interface LoginCallback {
void onError(Call call, Exception e, int id);
void onResponse(LoginRep response, int id);
}
private Callback callback;
public static String getLoginUrl() {
return getBaseUrl() + loginUrl;
}
public static String getStoreOperationUrl() {
return getBaseUrl() + store_operation;
}
public static String getPaytypesUrl() {
return getBaseUrl() + paytypesUrl;
}
public static String getBindUrl() {
return getBaseUrl() + bindUrl;
}
public static String getUnbindUrl() {
return getBaseUrl() + unbindUrl;
}
public void bind(String code, final Callback<StoreInfoResp> callback) {
// S77149026
OkHttpUtils
.post()
.url(getBindUrl())
.addParams("terminalMac", code)
.addParams("terminalType", "0")
.build()
.execute(
new GenericsCallback<StoreInfoResp>(
new JsonGenericsSerializator()) {
@Override
public void onError(Call call, Exception e,
int id) {
e.printStackTrace();
callback.onError(call, e, id);
}
@Override
public void onResponse(StoreInfoResp response,
int id) {
if (response.result == 0) {
System.out.println("bind succ");
LoginReqModel.appid = response.content.appid;
LoginReqModel.brandid = response.content.brandid;
LoginReqModel.storeid = response.content.storeid;
} else {
System.out.println("bind err");
}
callback.onResponse(response, id);
}
});
}
public void unbind(Context context, String code, final Callback callback) {
post()
.url(getUnbindUrl())
.addParams("terminalMac", code)
.addParams("token", token)
.build()
.execute(
new GenericsCallback<StringResp>(
new JsonGenericsSerializator()) {
@Override
public void onError(Call call, Exception e,
int id) {
e.printStackTrace();
callback.onError(call, e, id);
}
@Override
public void onResponse(StringResp response,
int id) {
callback.onResponse(response, id);
}
});
}
/**
* appid登录
*
* @param callback
*/
public void terminalLogin(final com.zhy.http.okhttp.callback.Callback callback) {
post()
.url(NewPos.getLoginUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("tname", LoginReqModel.tname)
.addParams("terminalmac", Common.SHOP_INFO.terminalMac)
.addParams("receiveNetOrder", "0")
.addParams("longitute", "0")
.addParams("latitute", "0")
.addParams("description", "")
.addParams("currentVersion", "1")
.addParams("versionid", "pos_canteen")
.build()
.execute(callback);
}
private static NewPos.Callback mCallback;
private static String getCommitWshDealUrl() {
return getBaseUrl() + commitWshDealUrl;
}
private String refundUrl = "api/orders/refund";
public String getRefundUrl() {
return getBaseUrl() + refundUrl;
}
public void refund(String orderId, String reasonId, String userName, String returnUserName, String authUserName, boolean returnMoney, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getRefundUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("orderId", orderId)
.addParams("reasonId", reasonId)
.addParams("userName", userName)//登录名
.addParams("returnUserName", returnUserName)//真实姓名
.addParams("authUserName", authUserName)
.addParams("returnMoney", returnMoney + "")
.addParams("token", token)
.build()
.execute(callback);
}
private String orderIdUrl = "api/orders/nextOrderId";
public String getOrderIdUrl() {
return getBaseUrl() + orderIdUrl;
}
public void getOrderId(int index, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.get()
.url(getOrderIdUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("token", token)
.id(index)
.build()
.execute(callback);
}
public String orderUrl = "/api/orders?token=";
public String getOrderUrl() {
return getBaseUrl() + orderUrl + token;
// +"&appId="+LoginReqModel.appid+"&brandId="+LoginReqModel.brandid+"&storeId="+LoginReqModel.storeid;
}
public void pushOrder(int index, String jsondata, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.post().url(getOrderUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("order", jsondata)
.id(index)
.build().execute(callback);
}
private static String commitWshDealUrl = "public/members/commitDeal";
public void memberLogin(String account, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.get()
.url(getMemberUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("account", account)
.addParams("token", token)
.build()
.execute(callback);
}
private static String createDealUrl = "public/members/createDealDCJ";
private String getCreateDealUrl() {
return getBaseUrl() + createDealUrl;
}
/**
* okHttp post同步请求
*/
public void createDeal(final WshCreateDeal.Request wshRequest, com.zhy.http.okhttp.callback.Callback callback) {
String params = new Gson().toJson(wshRequest);
OkHttpUtils.post()
.url(getCreateDealUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("token", token)
.addParams("deal", params).build().execute(callback);
}
public String getMemberUrl() {
return getBaseUrl() + memberUrl;
}
public static void commitWshDeal(String bizId, String verifySms, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getCommitWshDealUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("brandId", LoginReqModel.brandid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("bizId", bizId)
.addParams("verifySms", verifySms)
.build()
.execute(callback);
}
public void getPayment(com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils.post()
.url(NewPos.getPaytypesUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("terminalid", Common.SHOP_INFO.terminalid)
.build()
.execute(callback);
}
public String getSwiftPassPayUrl() {
return getBaseUrl() + swiftpassUrl;
}
public String getSwiftPassPayResultUrl() {
return getBaseUrl() + swiftpassQueryUrl;
}
/**
* 方法 :威富通下单之后 查询订单是否成功
* <p>
* out_trade_no 订单号 5位数以上
*
* @param callback
*/
public void getSwiftPassPayResult(String out_trade_no, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getSwiftPassPayResultUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("out_trade_no", out_trade_no)
.addParams("token", token)
.build()
.execute(callback);
}
private String swiftpassQueryUrl = "api/swiftpass/query";
private String swiftpassUrl = "api/swiftpass/gateway";
public void swiftPassPay(String code, String body, String mch_create_ip, String total_fee, String out_trade_no, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getSwiftPassPayUrl())
.addParams("appId", LoginReqModel.appid)
.addParams("storeId", LoginReqModel.storeid)
.addParams("auth_code", code)
.addParams("mch_create_ip", mch_create_ip)
.addParams("body", body)
.addParams("total_fee", total_fee)
.addParams("out_trade_no", out_trade_no)
.addParams("token", token)
.build()
.connTimeOut(300000)
.execute(callback);
}
public String uploadLogUrl = "/api/terminal/uploadLog?token=";
public String getUploadLogUrl() {
return getBaseUrl() + uploadLogUrl + token;
}
public void uploadLog(final File file,
final Context context) {
if (file == null) {
return;
}
OkHttpUtils
.post()
.addFile("file", file.getName(), file)
.url(getUploadLogUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("tname", Common.SHOP_INFO.tname)
.addParams("terminalid", Common.SHOP_INFO.terminalid)
.build()
.writeTimeOut(120 * 1000)
.execute(
new GenericsCallback<LoginRep>(
new JsonGenericsSerializator()) {
@Override
public void onError(Call call, Exception e, int id) {
ToastUtils.showToast(context, "网络异常!");
PrintFile.printResult2("日志上传失败--失败原因:\n" + e.getMessage() + "\n");
}
@Override
public void onResponse(LoginRep response, int id) {
ToastUtils.showToast(context, "日志上传成功");
PrintFile.printResult2("日志上传成功");
}
});
}
public void uploadLog2(final File file,
final Context context) {
if (file == null) {
return;
}
OkHttpUtils
.post()
.addFile("file", file.getName(), file)
.url(getUploadLogUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("tname", Common.SHOP_INFO.tname)
.addParams("terminalid", Common.SHOP_INFO.terminalid)
.build()
.writeTimeOut(120 * 1000)
.execute(
new GenericsCallback<LoginRep>(
new JsonGenericsSerializator()) {
@Override
public void onError(Call call, Exception e, int id) {
ToastUtils.showToast(context, "网络异常!");
PrintFile.printResult2("日志上传失败2--失败原因:\n" + e.getMessage() + "\n");
}
@Override
public void onResponse(LoginRep response, int id) {
String today = new SimpleDateFormat("yyyy-MM-dd")
.format(new Date());
SharedPreferencesUtil.setLastUploadTime(context, today);
PrintFile.printResult2("日志上传成功2");
}
});
}
public void getKind(com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getDishKindUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("terminalid", Common.SHOP_INFO.terminalid)
.addParams("sourcetype", "1")//堂食还是外带
.build()
.connTimeOut(300000)
.execute(callback);
}
public void getDish(com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getDishMenuUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("terminalid", Common.SHOP_INFO.terminalid)
.addParams("sourcetype", "1")
.build()
.connTimeOut(300000)
.execute(callback);
}
public void aliFaceToFacePay(PayReqModel model, com.zhy.http.okhttp.callback.Callback callback) {
String subject = "";
if (TextUtils.isEmpty(LoginReqModel.sname)) {
subject = "未知商品信息";
} else
subject = LoginReqModel.sname;
OkHttpUtils
.post()
.url(getAliFaceToFaceUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("outTradeNo", model.orderNo)
.addParams("authCode", model.authCode)
.addParams("subject", subject)
.addParams("totalAmount", model.totalAmount)
.addParams("timeoutExpress", "1")
.addParams("paymentStr", model.sPaymentInfo)
.build()
.execute(callback);
}
private String getAliFaceToFaceUrl() {
return getBaseUrl() + FaceToFacePayment;
}
public void queryAlipayResult(PayReqModel model, com.zhy.http.okhttp.callback.Callback callback) {
OkHttpUtils
.post()
.url(getqueryAlipayResultUrl())
.addParams("appid", LoginReqModel.appid)
.addParams("brandid", LoginReqModel.brandid)
.addParams("storeid", LoginReqModel.storeid)
.addParams("outTradeNo", model.orderNo)
.addParams("paymentStr", model.sPaymentInfo)
.build()
.execute(callback);
}
private String getqueryAlipayResultUrl() {
return getBaseUrl() + queryAlipayResult;
}
}
|
package com.example.demo.test;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
/**
* Created By RenBin6 on 2020/9/4 .
*/
public class SnakeCaseStrategyTest {
public static void main(String[] args) {
PropertyNamingStrategy.SnakeCaseStrategy snakeCaseStrategy = new PropertyNamingStrategy.SnakeCaseStrategy();
String iputStreamBuilder = snakeCaseStrategy.translate("iputStreamBuilder");
System.out.println(iputStreamBuilder);
}
}
|
/*Objective:
* 1.Client gives the Roll No and it gets the all details of that student from database.
* 2.Insert new Student in database with given RollNo and then print Complete students Details from database
The Database activities are separated into DAO1 class
*/
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class student{
int rollno;
String firstName;
String lastName;
int age;
public student()
{
}
public student(int rollno, String firstName, String lastName, int age) {
super();
this.rollno = rollno;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public int getRollno() {
return rollno;
}
public void setRollno(int rollno) {
this.rollno = rollno;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName= firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "student [rollno=" + rollno + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age
+ "]";
}
}
class DAO1{
String url = "jdbc:mysql://localhost:3306/student_details";
String username = "root";
String password ="root";
Connection con = null;
void connectToDatabase() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver"); // For old version , you can use - Class.forName("com.mysql.cj.jdbc.Driver")
con = (Connection) DriverManager.getConnection(url, username, password);
}
void closeConnection() throws SQLException {
con.close();
}
student getDetails(int rollno) throws Exception {
String query = "select * from student where rollno=" + rollno;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query); //Execute query to fetch details
rs.next();
//Prepare student object
student s = new student();
s.setRollno(rollno);
s.setFirstName(rs.getString(2));
s.setLastName(rs.getString(3));
s.setAge(rs.getInt(4));
st.close(); //close connection
//return these details to client
return s;
}
int addNewStudentToDatabase(student s) throws Exception {
String query = "insert into student values (?,?,?,?)";
PreparedStatement st = con.prepareStatement(query);
st.setInt(1, s.getRollno());
st.setString(2,s.getFirstName());
st.setString(3, s.getLastName());
st.setInt(4, s.getAge());
//Execute query
int rowsAffected = st.executeUpdate();
st.close(); //close connection
return rowsAffected;
}
List<student> getAllStudentsDetails() throws Exception{
String query = "select * from student";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query); //DQL
List<student> stu = new ArrayList<student>();
while(rs.next()) {
stu.add(new student(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4)));
}
st.close(); //close connection
return stu;
}
}
//Client
public class DAO_GetDetails {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter roll no of student whose Details you want: ");
int rollno = sc.nextInt();
DAO1 d1 = new DAO1();
d1.connectToDatabase();
//Fetch details from Database
student student1 = d1.getDetails(rollno);
//Print details of this student
student1.toString();
//Now Insert new Student in database and then print Complete students Details from database
student student2 = new student();
System.out.println("\nEnter New student Details you want to Add in Database: ");
System.out.println("Enter rollno ");
student2.setRollno(sc.nextInt());
sc.nextLine();
System.out.println("Enter First name ");
student2.setFirstName(sc.nextLine());
System.out.println("Enter Last Name ");
student2.setLastName(sc.nextLine());
System.out.println("Enter Age ");
student2.setAge(sc.nextInt());
int rowsAffected = d1.addNewStudentToDatabase(student2);
if (rowsAffected > 0)
System.out.println("Details Updated in Database successfully");
else {
System.out.println("Error in Details Updation!!");
}
//Show Complete Students details from Database
List<student> list = d1.getAllStudentsDetails();
System.out.println("\n*******Students Details*****");
for (student student : list) {
System.out.println(student.toString());
}
sc.close(); //close the scanner
d1.closeConnection(); //Close Database connection
}
}
|
package com.zxt.compplatform.formengine.service.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.struts2.ServletActionContext;
import org.springframework.jdbc.core.JdbcTemplate;
import com.zxt.compplatform.formengine.constant.Constant;
import com.zxt.compplatform.formengine.dao.ComponentsDao;
import com.zxt.compplatform.formengine.dao.ComponentsTreeDao;
import com.zxt.compplatform.formengine.entity.dataset.FieldDefVO;
import com.zxt.compplatform.formengine.entity.view.Button;
import com.zxt.compplatform.formengine.entity.view.EditColumn;
import com.zxt.compplatform.formengine.entity.view.EditPage;
import com.zxt.compplatform.formengine.entity.view.Event;
import com.zxt.compplatform.formengine.entity.view.ListPage;
import com.zxt.compplatform.formengine.entity.view.Param;
import com.zxt.compplatform.formengine.entity.view.TextColumn;
import com.zxt.compplatform.formengine.entity.view.ViewColumn;
import com.zxt.compplatform.formengine.entity.view.ViewPage;
import com.zxt.compplatform.formengine.service.ComponentsService;
import com.zxt.compplatform.formengine.service.ComponentsTreeService;
import com.zxt.compplatform.formengine.util.EditColumnUtil;
import com.zxt.compplatform.formengine.util.StrTools;
import com.zxt.compplatform.formengine.util.WorkFlowDataStautsXmlUtil;
import com.zxt.compplatform.workflow.dao.impl.TijiaoWorkFlowDaoImpl;
import com.zxt.compplatform.workflow.entity.WorkFlowDataStauts;
import com.zxt.framework.common.util.RandomGUID;
import com.zxt.framework.dictionary.entity.DataDictionary;
import com.zxt.framework.dictionary.service.IDataDictionaryService;
/**
* 表单控件业务实现
*
* @author 007
*/
public class ComponentsServiceImpl implements ComponentsService {
private static final Logger log = Logger
.getLogger(ComponentsServiceImpl.class);
/**
* 表单组件持久化接口
*/
private ComponentsDao componentsDao;
/**
* 组件树持久化接口
*/
private ComponentsTreeDao componentsTreeDao;
/**
* 数据字典业务操作接口
*/
private IDataDictionaryService iDataDictionaryService;
/**
* 树控件操作接口
*/
private ComponentsTreeService componentsTreeService;
/**
* 工作流提交实现
*/
private TijiaoWorkFlowDaoImpl tijiaoWorkFlowDaoImpl;
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#queryByDataSource(java.lang.String, java.lang.String, java.lang.Object[])
*/
public List queryByDataSource(String dataSourceId, String querySql,
Object[] conditions) {
DataSource ds = componentsDao.queryForDataSource(dataSourceId);
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(ds);
List list = new ArrayList();
list = jt.queryForList(querySql, conditions);
List queryList = new ArrayList();
if (list != null && list.size() != 0) {
for (int i = 0; i < list.size(); i++) {
Map rec = new HashMap();
Map map = (Map) list.get(i);
Set keys = map.keySet();
Iterator it = keys.iterator();
String key = it.next().toString();
rec.put("key", map.get(key));
key = it.next().toString();
rec.put("value", map.get(key));
queryList.add(rec);
}
}
return queryList;
}
/**
* 获取人员树控件列表数据
*
* @param orgid
* @return
*/
public List queryForHumanList(String orgid, String dictionaryID,
String state) {
String sql = "";
if ("open".equals(state) || "closed".equals(state)) {
sql = "select userid as id,uname as text,oid as parent_i_d,oname from user_union_view where oid in (select t.oid as oid from t_organization t left join t_org_org t_o on t.oid = t_o.downid where t_o.UPID = '"
+ orgid + "')";
} else {
sql = "select userid as id,uname as text,oid as parent_i_d,oname from user_union_view where oid in (select t.oid as oid from t_organization t left join t_org_org t_o on t.oid = t_o.downid where t.OID = '"
+ orgid + "')";
}
DataDictionary dataDictionary = iDataDictionaryService
.findById(dictionaryID);
List list = componentsTreeDao.treeOrgData(sql, componentsDao
.queryForDataSource(dataDictionary.getDataSource().getId()));
return list;
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#deleteData(com.zxt.compplatform.formengine.entity.view.ListPage, javax.servlet.http.HttpServletRequest)
*/
public int deleteData(ListPage listPage, HttpServletRequest request) {
// TODO Auto-generated method stub
String sql = StringUtils.EMPTY;
if (StringUtils.equals("on", listPage.getIsPseudoDeleted())) {
sql = " update " + listPage.getKeyTable()
+ " set IS_PSEUDO_DELETED='1' where 1=1 ";
} else {
sql = " DELETE FROM " + listPage.getKeyTable() + " WHERE 1=1 ";
}
String[] parmers = null;
Event event = null;
Button button = null;
Param param = null;
/**
* 封装过滤条件
*/
if (listPage != null) {
if (listPage.getRowButton() != null) {
for (int i = 0; i < listPage.getRowButton().size(); i++) {
button = ((Button) listPage.getRowButton().get(i));
if (Constant.DELETEOPERATOR.equals(button.getButtonName())) {
event = (Event) button.getEvent().get(0);
param = (Param) event.getParas().get(0);
parmers = param.getValue().split(",");
break;
}
}
}
}
/**
* 拼接sql 封装参数值
*
*/
if (parmers != null) {
for (int j = 0; j < parmers.length; j++) {
sql = sql + " and " + parmers[j] + "=? ";
parmers[j] = request.getParameter(parmers[j].trim());
parmers[j] = StrTools.charsetFormat(parmers[j], "ISO8859-1",
"UTF-8");
}
}
return componentsDao.deleteData(sql, parmers, listPage);
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#dynamicSave(javax.servlet.http.HttpServletRequest, com.zxt.compplatform.formengine.entity.view.EditPage, com.zxt.compplatform.workflow.entity.WorkFlowDataStauts)
*/
public int dynamicSave(HttpServletRequest request, EditPage editPage,
WorkFlowDataStauts workFlowDataStautsAdd) {
// TODO Auto-generated method stub
/**
* 获取 xml生成的 insert原始sql,定义参数数组(参数顺序从sql中获取)
*/
String sql = "";
String[] endParmer = null;
String key = "";// 参数名
String value = "";// 参数值
Param param = null;// 参数实体
String type = "";// 参数类型
String method = request.getParameter("method");
Map<String, EditColumn> editColumnMap = EditColumnUtil
.transformEditCloumnListToMap(editPage);// 数据字段名
// 获取editcolumn的map
Map map = null;//
List<Param> list = null;//
List<EditColumn> editColumnList = editPage.getEditColumn();
if (Constant.FORM_STATUS_ADD
.equals(request.getParameter("opertorType"))) {
String[] idParmer = null;
sql = editPage.getInsertSql();
List keyList = editPage.getKeyList();
if (keyList != null) {
idParmer = new String[keyList.size()];
for (int i = 0; i < keyList.size(); i++) {
FieldDefVO f = (FieldDefVO) keyList.get(i);
idParmer[i] = f.getToFieldName();
}
}
if (editPage.getInsertParams() != null) {
EditColumn editColumn = null;
for (int i = 0; i < editPage.getInsertParams().size(); i++) {
map = (Map) (editPage.getInsertParams().get(i));
list = (List) map.get(editPage.getInsertTableName());
endParmer = new String[list.size()];
/**
* 设置参数 end
*/
boolean flag = true;
for (int j = 0; j < list.size(); j++) {
flag = true;
param = list.get(j);
type = param.getType();
key = param.getKey();
/**
* 判断是否是主键
*/
for (int k = 0; k < idParmer.length; k++) {
if (idParmer[k].equals(key)) {
if ("int".equals(type)) {
Random random=new Random();
endParmer[j] =random.nextInt()+"";
}else if("numeric".equals(type)) {
Random random=new Random();
endParmer[j] =random.nextInt(999999999)+"";
}else if("bigint".equals(type)) {
Random random=new Random();
endParmer[j] =random.nextInt(999999999)+"";
}else{
endParmer[j] = RandomGUID.geneGuid();
}
flag = false;
// for (int k2 = 0; k2 <
// editPage.getEditColumn().size(); k2++) {
// editColumn=(EditColumn)editPage.getEditColumn().get(k2);
// if (editColumn.getName().equals(key)) {
// if
// ("NUMBER".equals(editColumn.getFieldDataType()))
// {
// endParmer[j]=new
// java.util.Date().getTime()+new
// Random().nextInt(9999)+"";
// }
// }
// }
break;
}
}
/**
* 非主键
*
*/
if (flag) {
/**
* 设置工作流字段
*/
if (key.equals("ENV_DATAMETER")) {
endParmer[j] = WorkFlowDataStautsXmlUtil
.workFlowDataStautsToXml(workFlowDataStautsAdd);
} else if (key.equals("ENV_DATASTATE")) {
endParmer[j] = workFlowDataStautsAdd
.getToTransferDefStauts_text()
+ "";
} else {
value = EditColumnUtil.cloumnSetValue(request,
editColumnMap, key);
endParmer[j] = value;
}
}
}
break;
/**
* 设置参数 end
*/
}
}
} else if (Constant.FORM_STATUS_EDIT.equals(request
.getParameter("opertorType"))) {
/**
* 工作流处理
*/
WorkFlowDataStauts workFlowDataStauts = new WorkFlowDataStauts();
workFlowDataStauts.setProcessDefId(request
.getParameter("processDefId"));
workFlowDataStauts.setMid(request.getParameter("mid"));
workFlowDataStauts.setActivityDefId(request
.getParameter("activityDefId"));
if (request.getParameter("toTransferDefStautsText") != null) {
workFlowDataStauts.setToTransferDefStautsText(StrTools
.charsetFormat(request
.getParameter("toTransferDefStautsText"),
"ISO8859-1", "UTF-8"));
} else {
workFlowDataStauts.setToTransferDefStautsText(request
.getParameter("ENV_DATASTATE"));
}
workFlowDataStauts.setToTransferDefStautsValue(request
.getParameter("toTransferDefStautsValue"));
if (request.getParameter("status_text") != null) {
workFlowDataStauts.setToTransferDefStauts_text(StrTools
.charsetFormat(request.getParameter("status_text"),
"ISO8859-1", "UTF-8"));
}
String envDataState = request.getParameter("ENV_DATASTATE");
if (Constant.WORKFLOW_QIDONG_STATE.equals(envDataState)) {
workFlowDataStauts = workFlowDataStautsAdd;
}
/**
* 修改数据
*/
sql = editPage.getUpdateSql();
for (int i = 0; i < editPage.getUpdateParams().size(); i++) {
map = (Map) editPage.getUpdateParams().get(i);
list = (List) map.get(editPage.getUpdataTableName());
endParmer = new String[list.size()];
for (int j = 0; j < list.size(); j++) {
param = list.get(j);
key = param.getKey();
value = request.getParameter(key);
/**
* 设置工作流字段
*/
if (key.equals("ENV_DATAMETER")) {
if ((workFlowDataStauts.getMid() != null)
&& (!"".equals(workFlowDataStauts.getMid()))) {
endParmer[j] = WorkFlowDataStautsXmlUtil
.workFlowDataStautsToXml(workFlowDataStauts);
} else {
endParmer[j] = value;
}
} else if (key.equals("ENV_DATASTATE")) {
if ((workFlowDataStauts.getToTransferDefStauts_text() != null)
&& (!"".equals(workFlowDataStauts
.getToTransferDefStauts_text()))) {
endParmer[j] = workFlowDataStauts
.getToTransferDefStauts_text()
+ "";
} else {
endParmer[j] = value;
}
} else {
endParmer[j] = EditColumnUtil.cloumnSetValue(request,
editColumnMap, key);
}
}
break;
}
}
int result=0;
//是复制功能
if ("copy".equals(method)) {
int batchsize=Integer.parseInt(request.getParameter("batchsize"));//在复制功能中:批量添加记录 数。
System.out.println("---->批量添加条数:"+batchsize);
for(int i=0;i<batchsize;i++){
result = dynamicSaveCopy(sql,endParmer,editPage,map,list,param,key,type,workFlowDataStautsAdd,request,value,editColumnMap);
}
System.out.println("---->批量添加条数:"+batchsize+"------------------->结束");
}else {
result = componentsDao.dynamicSave(sql, endParmer, editPage,editColumnMap, list);
}
/**
* 工作流提交
*/
String REC_ID = "";
EditColumn editColumn;
TextColumn textColumn;
for (int i = 0; i < editColumnList.size(); i++) {
editColumn = editColumnList.get(i);
textColumn = editColumn.getTextColumn();
if ("true".equals(textColumn.getIsworkflow())) {
REC_ID = request.getParameter(editColumn.getName());
break;
}
}
// 这个REC_ID 是用作标识某个节点的参与者,可以选择人员、角色或者组织机构
String[][] obj = new String[3][2];
obj[0][0] = "APP_ID";
obj[0][1] = request.getParameter("APP_ID");
obj[1][0] = Constant.DEFAULT_WORKFLOW_PARMER_KEY;
obj[1][1] = request.getParameter(Constant.DEFAULT_WORKFLOW_PARMER_KEY)
+ "";
obj[2][0] = "REC_ID";
obj[2][1] = REC_ID;
try {
String mainTable = request.getParameter("MAIN_APP_ID");// 主表业务主键
if (request.getSession().getAttribute("userId") != null) {
if ((request.getParameter("workitemId") != null)
&& (!"".equals(request.getParameter("workitemId")))) {
String userId = request.getSession().getAttribute("userId")
.toString();
int workitemId = Integer.parseInt(request
.getParameter("workitemId"));
if ((mainTable != null) && (!"".equals(mainTable))) {
if (mainTable.equals(request.getParameter("APP_ID"))) {
if (Constant.FORM_STATUS_EDIT.equals(request
.getParameter("opertorType"))) {
tijiaoWorkFlowDaoImpl.wancheng(userId, obj,
workitemId);
}
}
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
// return 0;
}
/***
* 复制 批量添加
* dynamicSaveCopy
*/
public int dynamicSaveCopy(String sql,String[] endParmer,EditPage editPage,Map map,List<Param> list,Param param,String key,String type,
WorkFlowDataStauts workFlowDataStautsAdd,HttpServletRequest request,String value,Map<String, EditColumn> editColumnMap){
String[] idParmer = null;
sql = editPage.getInsertSql();
List keyList = editPage.getKeyList();
if (keyList != null) {
idParmer = new String[keyList.size()];
for (int i = 0; i < keyList.size(); i++) {
FieldDefVO f = (FieldDefVO) keyList.get(i);
idParmer[i] = f.getToFieldName();
}
}
if (editPage.getInsertParams() != null) {
EditColumn editColumn = null;
for (int i = 0; i < editPage.getInsertParams().size(); i++) {
map = (Map) (editPage.getInsertParams().get(i));
list = (List) map.get(editPage.getInsertTableName());
endParmer = new String[list.size()];
/**
* 设置参数 end
*/
boolean flag = true;
for (int j = 0; j < list.size(); j++) {
flag = true;
param = list.get(j);
type = param.getType();
key = param.getKey();
/**
* 判断是否是主键
*/
for (int k = 0; k < idParmer.length; k++) {
if (idParmer[k].equals(key)) {
endParmer[j] = RandomGUID.geneGuid();
flag = false;
// for (int k2 = 0; k2 <
// editPage.getEditColumn().size(); k2++) {
// editColumn=(EditColumn)editPage.getEditColumn().get(k2);
// if (editColumn.getName().equals(key)) {
// if
// ("NUMBER".equals(editColumn.getFieldDataType()))
// {
// endParmer[j]=new
// java.util.Date().getTime()+new
// Random().nextInt(9999)+"";
// }
// }
// }
break;
}
}
/**
* 非主键
*
*/
if (flag) {
/**
* 设置工作流字段
*/
if (key.equals("ENV_DATAMETER")) {
endParmer[j] = WorkFlowDataStautsXmlUtil
.workFlowDataStautsToXml(workFlowDataStautsAdd);
} else if (key.equals("ENV_DATASTATE")) {
endParmer[j] = workFlowDataStautsAdd
.getToTransferDefStauts_text()
+ "";
} else if ((request.getParameter(key) == null)
|| ("".equals(request.getParameter(key)))) {
if ("datetime".equals(type)) {
endParmer[j] = "";
} else {
endParmer[j] = Constant.DB_FIELD_DEFAULT_VALUE;
}
if ("numeric".equals(type)) {
endParmer[j] = "0";
} else {
endParmer[j] = Constant.DB_FIELD_DEFAULT_VALUE;
}
if ("decimal".equals(type)) {
endParmer[j] = "0";
} else {
endParmer[j] = Constant.DB_FIELD_DEFAULT_VALUE;
}
} else {
value = request.getParameter(key);
endParmer[j] = value;
}
}
}
break;
/**
* 设置参数 end
*/
}
}
return componentsDao.dynamicSave(sql, endParmer, editPage,
editColumnMap, list);
}
/**
*
*/
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#loadEditPage(com.zxt.compplatform.formengine.entity.view.EditPage, java.lang.String[])
*/
public EditPage loadEditPage(EditPage editPage, String[] parmerNameArray) {
// TODO Auto-generated method stub
editPage = componentsDao.loadEditPage(editPage, parmerNameArray);
/**
* 加载数据字典值
*
*/
int columnType = -1;
EditColumn editColumn = null;
Map dictionartData = null;
EditColumn temColumn = null;
String viewData = "";// 显示值
String[] checkBoxValues;
for (int i = 0; i < editPage.getEditColumn().size(); i++) {
editColumn = (EditColumn) editPage.getEditColumn().get(i);
/**
* 设置默认控件类型值
*/
if ("".equals(editColumn.getType())
|| (editColumn.getType() == null)) {
columnType = Constant.FORM_FIELD_TYPE_TEXT;
} else {
columnType = Integer.parseInt(editColumn.getType());
}
switch (columnType) {
case Constant.FORM_FIELD_TYPE_SELECT:
dictionartData = update_Dictionary(editColumn.getDictionaryID());
((EditColumn) editPage.getEditColumn().get(i))
.setDictionaryData(dictionartData);
break;
case Constant.FORM_FIELD_TYPE_AJAXBOX_TREE:
String[] array = loadTreeData(editColumn.getDictionaryID(),
editColumn.getData());
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setJsonTreeData(array[0]);
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setConversionDataValue(array[1]);
break;
case Constant.FORM_FIELD_TYPE_RADIO:
dictionartData = update_Dictionary(editColumn.getDictionaryID());
((EditColumn) editPage.getEditColumn().get(i))
.setDictionaryData(dictionartData);
break;
case Constant.FORM_FIELD_TYPE_CHECKBOX:
dictionartData = update_Dictionary(editColumn.getDictionaryID());
Set<String> key = dictionartData.keySet();
String dictionartDataValue="";
if (dictionartData != null) {
checkBoxValues = editColumn.getData().split(",");
for (int j = 0; j < checkBoxValues.length; j++) {
for (Iterator it = key.iterator(); it.hasNext();) {
String s = (String) it.next();
dictionartDataValue=dictionartData.get(s)+"";
if (dictionartDataValue.equals(checkBoxValues[j])) {
dictionartData.put(s, "checked");
break;
}
}
}
((EditColumn) editPage.getEditColumn().get(i))
.setDictionaryData(dictionartData);
}
break;
case Constant.FORM_FIELD_TYPE_TEXT:
dictionartData = update_Dictionary(editColumn.getDictionaryID());
((EditColumn) editPage.getEditColumn().get(i))
.setDictionaryData(dictionartData);
/**
* 设置文本框显示值
*/
String data = editColumn.getData();
boolean flag = false;
if (dictionartData != null && StringUtils.isNotBlank(data)) {
if (StringUtils.contains(data, ",")) {
String[] datas = data.split(",");
String temdata = StringUtils.EMPTY;
for (int j = 0; j < datas.length; j++) {
if (dictionartData.get(datas[j]) != null) {
String thisdata = dictionartData.get(datas[j])
.toString();
temdata += thisdata + ",";
}
}
if (StringUtils.isNotBlank(temdata)) {
data = temdata.substring(0, temdata.length() - 1);
flag = true;
}
} else {
if (dictionartData.get(data) != null) {
data = dictionartData.get(data).toString();
flag = true;
}
}
if(flag&&editColumn!=null&&editColumn.getTextColumn()!=null&&editColumn.getTextColumn().getIs_listPageForvalue()){
if(editColumn.getTextColumn().getIs_listPageForvalue()){
editColumn.getDictionary().setDictionaryName(data);
break;
}
}else if (flag) {
// 保存数据字典value temColumn
temColumn = new EditColumn();
temColumn.setName(editColumn.getName());
temColumn.setData(editColumn.getData());
temColumn.setType(Constant.FORM_FIELD_TYPE_HIDDEN + "");
temColumn.setTextColumn(editColumn.getTextColumn());
// 显示数据字典text
editColumn.setData(data);
editColumn.setName(editColumn.getName()
+ "_ENV_DIC_VIEWDATA");
editPage.getEditColumn().add(temColumn);
}
}
break;
case Constant.FORM_FIELD_TYPE_AJAXBOX_TREE_ORG:
String oid = "1";
String selfoid = "";
HttpServletRequest request = ServletActionContext.getRequest();
Object obj = request.getSession().getAttribute("oid");
if (obj != null) {
selfoid = obj.toString();
}
String isselforg = ((EditColumn) editPage.getEditColumn()
.get(i)).getTextColumn().getIsselforg();
String orgid = ((EditColumn) editPage.getEditColumn().get(i))
.getTextColumn().getOrgid();
if (orgid != null && !"".equals(orgid)) {
selfoid = orgid;
}
if ("true".equals(isselforg)) {
oid = selfoid;
}
String[] obj_array = loadTreeOrgData(editColumn
.getDictionaryID(), editColumn.getData(), oid);
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setJsonTreeData(obj_array[0]);
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setConversionDataValue(
obj_array[1]);
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setIsCheckBox(
(Boolean.valueOf(((EditColumn) editPage
.getEditColumn().get(i))
.getTextColumn().getIsmultipart())));
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setOnlyLeafCheck(
(Boolean.valueOf(((EditColumn) editPage
.getEditColumn().get(i))
.getTextColumn().getIsleafcheck())));
break;
case Constant.FORM_FIELD_TYPE_AJAXBOX_TREE_ORG_HUMAN:
String human_oid = "1";
Object human_obj = ServletActionContext.getRequest()
.getSession().getAttribute("oid");
String human_orgid = ((EditColumn) editPage.getEditColumn()
.get(i)).getTextColumn().getOrgidhuman();
if (human_orgid != null && !"".equals(human_orgid)) {
human_oid = human_orgid;
} else {
human_oid = human_obj.toString();
}
String[] human_obj_array = loadTreeHumanData(editColumn
.getDictionaryID(), editColumn.getData(), human_oid);
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents()
.setJsonTreeData(human_obj_array[0]);
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setConversionDataValue(
human_obj_array[1]);
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents().setDictionaryID(
editColumn.getDictionaryID());
((EditColumn) editPage.getEditColumn().get(i))
.getTreeComponents()
.setIsCheckBox(
(Boolean.valueOf(((EditColumn) editPage
.getEditColumn().get(i))
.getTextColumn().getIsmultiparthuman())));
break;
case Constant.FORM_FIELD_TYPE_LISTPAGE:
dictionartData = update_Dictionary(editColumn.getDictionaryID());
editColumn= (EditColumn)editPage.getEditColumn().get(i);
if (dictionartData!=null&&dictionartData.get(editColumn.getData())!=null) {
String textString=dictionartData.get(editColumn.getData()).toString();
}
((EditColumn) editPage.getEditColumn().get(i))
.setDictionaryData(dictionartData);
break;
default:
break;
}
}
return editPage;
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#loadViewPage(com.zxt.compplatform.formengine.entity.view.ViewPage, javax.servlet.http.HttpServletRequest)
*/
public ViewPage loadViewPage(ViewPage viewPage, HttpServletRequest request) {
// TODO Auto-generated method stub
String sql = viewPage.getFindSql();
boolean flag = true;
String[] parmer = null;
Param param = null;
String key = "";
String value = "";
if (viewPage.getViewPageParams() != null) {
parmer = new String[viewPage.getViewPageParams().size()];
for (int j = 0; j < viewPage.getViewPageParams().size(); j++) {
param = (Param) viewPage.getViewPageParams().get(j);
key = param.getKey().trim();
value = request.getParameter(key);
value = StrTools.charsetFormat(value, "ISO8859-1", "UTF-8");
if ((value == null) || "".equals(value)) {
flag = false;
break;
}
parmer[j] = value;
}
}
if (flag) {
viewPage = componentsDao.loadViewPage(sql, parmer, viewPage);
ViewColumn viewColumn = null;
String data = "";
if (viewPage.getViewColumn() != null) {
for (int i = 0; i < viewPage.getViewColumn().size(); i++) {
viewColumn = (ViewColumn) (viewPage.getViewColumn().get(i));
if (!"".equals(viewColumn.getDictionaryID())) {
// 单选框null值判断
if (viewColumn.getData() == null) {
continue;
}
String dictionaryID = viewColumn.getDictionaryID();
Map map = load_Dictionary(dictionaryID);
data = viewColumn.getData();
if (map != null) {
if (StringUtils.contains(data, ",")) {
String[] datas = data.split(",");
String temdata = StringUtils.EMPTY;
for (int j = 0; j < datas.length; j++) {
if (map.get(datas[j]) != null) {
String thisdata = map.get(datas[j])
.toString();
temdata += thisdata + ",";
}
}
data = temdata.substring(0,
temdata.length() - 1);
} else {
if (map.get(data) != null) {
data = map.get(data).toString();
}
}
((ViewColumn) (viewPage.getViewColumn().get(i)))
.setData(data);
}
}
}
}
}
return viewPage;
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#load_Dictionary(java.lang.String)
*/
public Map load_Dictionary(String dictionaryID) {
// TODO Auto-generated method stub
String[] array = null;
String[] mapString = null;
Map map = new HashMap();
DataDictionary dictionary = null;
/**
* 静态数据字典 拆分表达式 ;返回map
*/
try {
dictionary = iDataDictionaryService.findById(dictionaryID);
if (dictionary.getType().equals(Constant.DICTIONARY_STATIC)) {
array = dictionary.getExpression().split(",");
for (int i = 0; i < array.length; i++) {
mapString = array[i].split("=");
map.put(mapString[0], mapString[1]);
}
} else if (dictionary.getType().equals(Constant.DICTIONARY_DYNAMIC)) {
map = componentsDao.loadDynamicDictionary(dictionary
.getExpression(), dictionary.getDataSource().getId());
}
} catch (Exception e) {
// TODO: handle exception
log.error("static dictionary or dynamic dictionary is turn.. ");
e.printStackTrace();
}
return map;
}
/**
* @GUOWEIXIN
* 数据字典中 设置动态SQL语句的解析和查询功能。
* 例如:[]在request范围中取。{}在session范围中取。
* select * from TableName where first='[first]' and second='{second}'
*/
public Map load_Dictionary(String dictionaryID,HttpServletRequest request) {
// TODO Auto-generated method stub
String[] array = null;
String[] mapString = null;
Map map = new HashMap();
DataDictionary dictionary = null;
/**
* 静态数据字典 拆分表达式 ;返回map
*/
try {
dictionary = iDataDictionaryService.findById(dictionaryID);
if (dictionary.getType().equals(Constant.DICTIONARY_STATIC)) {
array = dictionary.getExpression().split(",");
for (int i = 0; i < array.length; i++) {
mapString = array[i].split("=");
map.put(mapString[0], mapString[1]);
}
} else if (dictionary.getType().equals(Constant.DICTIONARY_DYNAMIC)) {
map = componentsDao.loadDynamicDictionary(dictionary
.getExpression(), dictionary.getDataSource().getId(),request);
}
} catch (Exception e) {
// TODO: handle exception
log.error("static dictionary or dynamic dictionary is turn.. ");
}
return map;
}
public ComponentsTreeService getComponentsTreeService() {
return componentsTreeService;
}
public void setComponentsTreeService(
ComponentsTreeService componentsTreeService) {
this.componentsTreeService = componentsTreeService;
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#loadTreeData(java.lang.String, java.lang.String)
*/
public String[] loadTreeData(String dictionaryID, String defalutValue) {
// TODO Auto-generated method stub
String json = "";
DataDictionary dataDictionary = null;
String[] array = null;
dataDictionary = iDataDictionaryService.findById(dictionaryID);
if (Constant.DICTIONARY_DYNAMIC.equals(dataDictionary.getType())) {
try {
/**
* 返回封装后 初始化的树形结构 json和 业务数据id 对应的 name
*/
array = componentsTreeService.treeData(dataDictionary,
defalutValue);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
return array;
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#loadTreeData(java.lang.String, java.lang.String, java.lang.String)
*/
public String[] loadTreeData(String dictionaryID, String defalutValue,
String parentId) {
String json = "";
DataDictionary dataDictionary = null;
String[] array = null;
dataDictionary = iDataDictionaryService.findById(dictionaryID);
if (Constant.DICTIONARY_DYNAMIC.equals(dataDictionary.getType())) {
try {
/**
* 返回封装后 初始化的树形结构 json和 业务数据id 对应的 name
*/
array = componentsTreeService.treeData(dataDictionary,
defalutValue, parentId);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
return array;
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#loadTreeOrgData(java.lang.String, java.lang.String, java.lang.String)
*/
public String[] loadTreeOrgData(String dictionaryID, String defalutValue,
String oid) {
// TODO Auto-generated method stub
String json = "";
DataDictionary dataDictionary = null;
String[] array = null;
dataDictionary = iDataDictionaryService.findById(dictionaryID);
if (Constant.DICTIONARY_DYNAMIC.equals(dataDictionary.getType())) {
try {
/**
* 返回封装后 初始化的树形结构 json和 业务数据id 对应的 name
*/
array = componentsTreeService.treeOrgData(dataDictionary,
defalutValue, oid);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
/**
* 返回封装后 初始化的树形结构 json和 业务数据id 对应的 name
*/
return array;
}
/**
* 加载treejson
*/
public String[] loadTreeHumanData(String dictionaryID, String defalutValue,
String oid) {
// TODO Auto-generated method stub
String json = "";
DataDictionary dataDictionary = null;
String[] array = null;
dataDictionary = iDataDictionaryService.findById(dictionaryID);
if (Constant.DICTIONARY_DYNAMIC.equals(dataDictionary.getType())) {
try {
/**
* 返回封装后 初始化的树形结构 json和 业务数据id 对应的 name
*/
array = componentsTreeService.treeHumanData(dataDictionary,
defalutValue, oid);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
/**
* 返回封装后 初始化的树形结构 json和 业务数据id 对应的 name
*/
return array;
}
public String[] load_XMLConfig() {
// TODO Auto-generated method stub
return componentsDao.load_XMLConfig();
}
public ComponentsDao getComponentsDao() {
return componentsDao;
}
public void setComponentsDao(ComponentsDao componentsDao) {
this.componentsDao = componentsDao;
}
public IDataDictionaryService getIDataDictionaryService() {
return iDataDictionaryService;
}
public void setIDataDictionaryService(
IDataDictionaryService dataDictionaryService) {
iDataDictionaryService = dataDictionaryService;
}
public String load_validate(String id) {
// TODO Auto-generated method stub
return componentsDao.serchValidate(id);
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#bulkDelete(com.zxt.compplatform.formengine.entity.view.ListPage, javax.servlet.http.HttpServletRequest)
*/
public String bulkDelete(ListPage listPage, HttpServletRequest request) {
// TODO Auto-generated method stub
Button button = null;
Event event = null;
Param param = null;
String[] parmers = null;
if (listPage != null) {
if (listPage.getRowButton() != null) {
for (int i = 0; i < listPage.getRowButton().size(); i++) {
button = ((Button) listPage.getRowButton().get(i));
if (Constant.DELETEOPERATOR.equals(button.getButtonName())) {
event = (Event) button.getEvent().get(0);
param = (Param) event.getParas().get(0);
parmers = param.getValue().split(",");
break;
}
}
}
}
String value = "";
String[] valueParmers = null;
String sql = StringUtils.EMPTY;
if (StringUtils.equals("on", listPage.getIsPseudoDeleted())) {
sql = " update " + listPage.getKeyTable()
+ " set IS_PSEUDO_DELETED='1' where 1=1 ";
} else {
sql = " DELETE FROM " + listPage.getKeyTable() + " WHERE 1=1 ";
}
int length = 0;
if (parmers != null) {
if (parmers.length == 1) {// 单主键
value = StrTools.charsetFormat(request.getParameter(parmers[0]
.trim()), "ISO8859-1", "UTF-8");
valueParmers = value.split(",");
sql = sql + " and " + parmers[0] + " in (";
for (int j = 0; j < valueParmers.length; j++) {
if (j == 0) {
sql = sql + "?";
} else {
sql = sql + ",? ";
}
}
sql = sql + ")";
componentsDao.deleteData(sql, valueParmers, listPage);
} else if (parmers.length > 1) {// 多主键
value = StrTools.charsetFormat(request.getParameter(parmers[0]
.trim()), "ISO8859-1", "UTF-8");
valueParmers = value.split(",");
length = valueParmers.length;// 删除数据条数
sql = sql + " and (";
for (int i = 0; i < length; i++) {
if (i == 0) {
sql = sql + "(";
} else {
sql = sql + " or (";
}
/**
* 每条记录联合主键的拼接
*
*/
for (int j = 0; j < parmers.length; j++) {
value = StrTools.charsetFormat(request
.getParameter(parmers[j].trim()), "ISO8859-1",
"UTF-8");
valueParmers = value.split(",");
if (j == 0) {
sql = sql + parmers[j] + "= '" + valueParmers[i]
+ "'";
} else {
sql = sql + " and " + parmers[j] + "= '"
+ valueParmers[i] + "'";
}
}
/**
*
*/
sql = sql + ")";
}
sql = sql + " )";
componentsDao.deleteData(sql, null, listPage);
log.info(sql);
}
}
return null;
}
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#update_Dictionary(java.lang.String)
*/
public Map update_Dictionary(String dictionaryID) {
// TODO Auto-generated method stub
String[] array = null;
String[] mapString = null;
Map map = new HashMap();
DataDictionary dictionary = null;
/**
* 静态数据字典 拆分表达式 ;返回map
*/
try {
dictionary = iDataDictionaryService.findById(dictionaryID);
if (dictionary.getType().equals(Constant.DICTIONARY_STATIC)) {
array = dictionary.getExpression().split(",");
for (int i = 0; i < array.length; i++) {
mapString = array[i].split("=");
map.put(mapString[0], mapString[1]);
}
} else if (dictionary.getType().equals(Constant.DICTIONARY_DYNAMIC)) {
map = componentsDao.loadDynamicDictionary(dictionary
.getExpression(), dictionary.getDataSource().getId());
}
} catch (Exception e) {
// TODO: handle exception
log.error("static dictionary or dynamic dictionary is turn.. ");
}
return map;
}
/**
* @GUOWEIXIN
* 数据字典中 设置动态SQL语句的解析和查询功能。
* 例如:[]在request范围中取。{}在session范围中取。
* select * from TableName where first='[first]' and second='{second}'
*/
public Map update_Dictionary(String dictionaryID,HttpServletRequest request) {
// TODO Auto-generated method stub
String[] array = null;
String[] mapString = null;
Map map = new HashMap();
DataDictionary dictionary = null;
/**
* 静态数据字典 拆分表达式 ;返回map
*/
try {
dictionary = iDataDictionaryService.findById(dictionaryID);
if (dictionary.getType().equals(Constant.DICTIONARY_STATIC)) {
array = dictionary.getExpression().split(",");
for (int i = 0; i < array.length; i++) {
mapString = array[i].split("=");
map.put(mapString[0], mapString[1]);
}
} else if (dictionary.getType().equals(Constant.DICTIONARY_DYNAMIC)) {
map = componentsDao.loadDynamicDictionary(dictionary
.getExpression(), dictionary.getDataSource().getId(),request);
}
} catch (Exception e) {
// TODO: handle exception
log.error(e.getMessage()+"static dictionary or dynamic dictionary is turn.. ");
//e.printStackTrace();
}
return map;
}
public TijiaoWorkFlowDaoImpl getTijiaoWorkFlowDaoImpl() {
return tijiaoWorkFlowDaoImpl;
}
public void setTijiaoWorkFlowDaoImpl(
TijiaoWorkFlowDaoImpl tijiaoWorkFlowDaoImpl) {
this.tijiaoWorkFlowDaoImpl = tijiaoWorkFlowDaoImpl;
}
/**
* 菜单过滤数据
*/
/* (non-Javadoc)
* @see com.zxt.compplatform.formengine.service.ComponentsService#findMenuFilter(java.lang.String, java.util.List)
*/
public List findMenuFilter(String menuId, List initList) {
// TODO Auto-generated method stub
// b7ecb012fea167f799c27756bc3f2f66 工单受理
String[] paramFilter = new String[2];
paramFilter[0] = "ENV_DATAMETER";
if ("b7ecb012fea167f799c27756bc3f2f66".equals(menuId)) {
paramFilter[1] = "1";// 工单受理
} else if ("f3ad34d954c81340aca62c3255302581".equals(menuId)) {
paramFilter[1] = "2";// 拣送
} else if ("687d333133d5a79993475746367f6e8d".equals(menuId)) {
paramFilter[1] = "5";// 回访
}
List list = new ArrayList();
Map temMap = null;
String paramValue = "";
for (int i = 0; i < initList.size(); i++) {
temMap = (Map) initList.get(i);
if (temMap.get(paramFilter[0]) == null) {
list.add(initList.get(i));
} else {
paramValue = temMap.get(paramFilter[0]).toString();
try {
WorkFlowDataStauts workFlowDataStauts = WorkFlowDataStautsXmlUtil
.xmlToWorkFlowDataStauts(paramValue);
if ("5".equals(paramFilter[1])) {
if (!"1".equals(workFlowDataStauts
.getToTransferDefStautsValue())
&& (!"2".equals(workFlowDataStauts
.getToTransferDefStautsValue()))) {
list.add(initList.get(i));
continue;
}
}
if (paramFilter[1].equals(workFlowDataStauts
.getToTransferDefStautsValue())) {
list.add(initList.get(i));
}
} catch (Exception e) {
// TODO: handle exception
list.add(initList.get(i));
}
// if (paramFilter[1].equals(paramValue)) {
// list.add(initList.get(i));
// }
}
}
return list;
}
/**
* 设置导出到的excel的样式
*
* @param wb
* @return
*/
public static HSSFCellStyle contentStyle(HSSFWorkbook wb) {
HSSFCellStyle style = wb.createCellStyle();
HSSFFont f = wb.createFont();
f.setFontHeightInPoints((short) 11);// 字号
f.setColor(HSSFColor.BLACK.index);
f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style.setFont(f);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setWrapText(true);
return style;
}
/**
* 导出数据
*/
public InputStream exportForListPage(String formId, ListPage listPage,
HttpServletRequest request, String[] selectColumns) {
String sql = listPage.getSql();
String[] conditions = new String[] {};
List list = componentsDao.queryForExport(formId, sql, conditions,
listPage, request);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCellStyle headStyle = contentStyle(wb);
HSSFSheet sheet = wb.createSheet();
sheet.setDefaultColumnWidth(26);
wb.setSheetName(0, "数据列表");
HSSFRow row = sheet.createRow(0);// 行
row.setHeight((short) 450);
HSSFCell cell;// 单元格
// 写表头
List headKeys = new ArrayList();
for (int i = 0; i < selectColumns.length; i++) {
headKeys.add(selectColumns[i].split("&#")[0]);
cell = row.createCell(i);
cell
.setCellValue(selectColumns[i].split("&#").length > 1 ? selectColumns[i]
.split("&#")[1]
: "");
cell.setCellStyle(headStyle);
}
HSSFCellStyle contentStyle = contentStyle(wb);
// 写内容
for (int k = 0; k < list.size(); k++) {
Map taskMap = (Map) list.get(k);// 获取到map之后,利用headkey得到此map的值,写入excel
row = sheet.createRow(k + 1);// 从第二行开始写
row.setHeight((short) 400);
for (int m = 0; m < headKeys.size(); m++) {
cell = row.createCell(m);
cell.setCellValue(taskMap.get(headKeys.get(m)) + "");
cell.setCellStyle(contentStyle);
}
}
// 将流读到内存里面,在内存里构造好一个输入输出流,直接传到浏览器端,不会生成临时文件
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
wb.write(os);
} catch (IOException e) {
e.printStackTrace();
}
byte[] content = os.toByteArray();
InputStream is = null;
is = new ByteArrayInputStream(content);
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
public ComponentsTreeDao getComponentsTreeDao() {
return componentsTreeDao;
}
public void setComponentsTreeDao(ComponentsTreeDao componentsTreeDao) {
this.componentsTreeDao = componentsTreeDao;
}
} |
import java.io.*;
import java.util.*;
class fact1
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int a=s.nextInt();
if((a==0)||(a==1))
{
System.out.print("1");
}
else
{
int mul=1;
for(int i=1;i<=a;i++)
{
mul=mul*i;
}
System.out.print(mul);
}
}
}
|
package ua.siemens.dbtool.service;
import ua.siemens.dbtool.model.entities.Profile;
import java.util.Collection;
/**
* Service interface for {@link Profile}
*
* @author Perevoznyk Pavlo
* creation date 29 August 2017
* @version 1.0
*/
public interface ProfileService {
void save(Profile profile);
void update(Profile profile);
void delete(Long id);
Profile findById(Long id);
Collection<Profile> findAll();
}
|
package com.gxtc.huchuan.bean;
import java.io.Serializable;
/**
* Created by Gubr on 2017/3/20.
* 关注 人数 用这个对象
*/
public class PersonCountBean implements Serializable{
private String name;
private String headPic;
private String shareCount;
private String call; //这个是称呼
public String getCall() {
return call;
}
public void setCall(String call) {
this.call = call;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeadPic() {
return headPic;
}
public void setHeadPic(String headPic) {
this.headPic = headPic;
}
public PersonCountBean(String name, String headPic, String shareCount, String call) {
this.name = name;
this.headPic = headPic;
this.shareCount = shareCount;
this.call = call;
}
public PersonCountBean(String name, String headPic) {
this.name = name;
this.headPic = headPic;
}
public String getShareCount() {
return shareCount;
}
public void setShareCount(String shareCount) {
this.shareCount = shareCount;
}
}
|
package org.vincent.stream;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
/**
* @author PengRong
* @package org.vincent.stream
* @ClassName ConsumerTest.java
* @date 2020/6/6 - 10:35
* @ProjectName JavaAopLearning
* @Description: Consumer 接口是用于 在流中使用最多的地方就是 forEach。用于遍历每个元素时候Cousumer消费每个元素,对每个元素特殊处理。
*/
public class ConsumerTest {
public static void main(String[] args) {
testConsumer();
testAndThen();
List<String> strings= Arrays.asList("asdf","1234123sdf","asdfasdf","oqwrtuqwe23423alsdfk");
/** 函数式接口Consumer 有四种实现方式*/
/** 第一种写法 内部类形式 */
strings.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
/** 第二种写法 lambda */
strings.forEach(x-> System.out.println(x));
/** 函数式接口 变量名 = 类实例::方法名” 的方式对该方法进行引用,将方法引用赋值给一个函数式接口*/
/** 将一个方法实现赋值给函数式接口 Consumer ,然后对流中元素遍历时候对每个元素 执行accept 方法时候执行的具体逻辑是 函数式接口引用
* 将方法复制给Consumer 接口引用有个前提就是,方法引用必须是Consumer
* */
/** 第三种写法: 方法引用*/
Consumer<String> consumer = System.out::println;
strings.forEach(consumer);
/** 第四种写法: 函数式接口,使用自定义方法 */
consumer = new A()::xx;
strings.forEach(consumer);
consumer = new A()::yy;
strings.forEach(consumer);
/** 复制给 consumer 函数接口引用的方法参数必须是 Consumer 接口操作参数数据类型,方法入参只能只有一个。*/
//consumer = new A()::yyb;/** 报错 */
}
public static class A{
public void yyb(String yy,int b){
System.out.println(yy);
}
public void yy(String yy){
System.out.println(yy);
}
public int xx(String aa){
if (StringUtils.isNotBlank(aa)){
System.out.println(aa.length());
return aa.length();
}else {
return 0;
}
}
}
/**
* 定义3个Consumer并按顺序进行调用andThen方法
*/
private static void testAndThen() {
Consumer<Integer> consumer1 = x -> {
System.out.println("first");
System.out.println("当前输入值 input :" + x);
};
Consumer<Integer> consumer2 = x -> {
System.out.println("second");
System.out.println("相加 :" + (x + x));
};
Consumer<Integer> consumer3 = x -> {
System.out.println("third");
System.out.println("相乘 :" + (x * x));
};
System.out.println("-----------------");
/** 最后输入 10,然后从 consumer1,consumer2,consumer3 顺序消费,每个消费器都是获得输入值 10 */
consumer1.andThen(consumer2).andThen(consumer3).accept(10);
System.out.println("-----------------");
}
private static void testConsumer() {
Consumer<Integer> square = x -> {
System.out.println("print square : " + x * x);
System.out.println("print max : " + x * x * x);
return;
};
/** accept */
square.accept(2);
}
}
|
package com.asgab.service.account;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.asgab.entity.Account;
import com.google.common.base.Objects;
public class ShiroDbRealm extends AuthorizingRealm {
protected AccountService accountService;
// public static final List<String> adminGroupIds = Lists.newArrayList("414");
/**
* 认证回调函数,登录时调用.
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
if (!"15242227799".equals(token.getUsername()) && !"18521351960".equals(token.getUsername())) {
throw new LockedAccountException();
}
Account account = accountService.get(token.getUsername());
if (account == null) {
throw new UnknownAccountException();// 没找到帐号
}
token.setPassword(token.getPassword());
return new SimpleAuthenticationInfo(new ShiroUser(account.getUsername()), account.getPassword(), getName());
}
/**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
return info;
}
/**
* 设定Password校验的Hash算法与迭代次数.
*/
@PostConstruct
public void initCredentialsMatcher() {
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(AccountService.HASH_ALGORITHM);
setCredentialsMatcher(matcher);
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
/**
* 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.
*/
public static class ShiroUser implements Serializable {
private static final long serialVersionUID = -1373760761780840081L;
public String loginName;
public ShiroUser(String loginName) {
this.loginName = loginName;
}
/**
* 本函数输出将作为默认的<shiro:principal/>输出.
*/
@Override
public String toString() {
return loginName;
}
/**
* 重载hashCode,只计算loginName;
*/
@Override
public int hashCode() {
return Objects.hashCode(loginName);
}
/**
* 重载equals,只计算loginName;
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ShiroUser other = (ShiroUser) obj;
if (loginName == null) {
if (other.loginName != null) {
return false;
}
} else if (!loginName.equals(other.loginName)) {
return false;
}
return true;
}
}
}
|
import Staff.TechStaff.DbAdmin;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class DbAdminTest {
DbAdmin dbAdmin;
@Before
public void before(){
dbAdmin = new DbAdmin("Miss Brahms", "GB654321", 15000);
}
@Test
public void canRaiseSalary(){
dbAdmin.raiseSalary(1000);
assertEquals(16000, dbAdmin.getSalary(), 0.01);
}
@Test
public void canPayBonus(){
assertEquals(150, dbAdmin.payBonus(), 0.01);
}
@Test
public void canGetName(){
assertEquals("Miss Brahms", dbAdmin.getName());
}
@Test
public void canGetNatInsNum(){
assertEquals("GB654321", dbAdmin.getNatInsNum());
}
@Test
public void cannotHaveNegativeRaise(){
dbAdmin.raiseSalary(-1000);
assertEquals(15000, dbAdmin.getSalary(), 0.01);;
}
@Test
public void canChangeName(){
dbAdmin.setName("Mr Anderson");
assertEquals("Mr Anderson", dbAdmin.getName());
}
@Test
public void cannotSetNullName(){
dbAdmin.setName(null);
assertEquals("Miss Brahms", dbAdmin.getName());
}
}
|
/*
* WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized
* by MyEclipse Hibernate tool integration.
*
* Created Sat Nov 13 13:09:55 CST 2004 by MyEclipse Hibernate Tool.
*/
package com.aof.component.helpdesk;
import java.io.Serializable;
/**
* A class that represents a row in the ACTION_TYPE table.
* You can customize the behavior of this class by editing the class, {@link ActionType()}.
* WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized * by MyEclipse Hibernate tool integration.
*/
public abstract class AbstractActionType
implements Serializable
{
/** The cached hash code value for this instance. Settting to 0 triggers re-calculation. */
private int hashValue = 0;
/** The composite primary key value. */
private java.lang.Integer actionid;
/** The value of the simple actiondesc property. */
private java.lang.String actiondesc;
private boolean actiondisabled;
/** The value of the callType association. */
private CallType callType;
/**
* Simple constructor of AbstractActionType instances.
*/
public AbstractActionType()
{
}
/**
* Constructor of AbstractActionType instances given a simple primary key.
* @param actionid
*/
public AbstractActionType(java.lang.Integer actionid)
{
this.setActionid(actionid);
}
/**
* Return the simple primary key value that identifies this object.
* @return java.lang.Integer
*/
public java.lang.Integer getActionid()
{
return actionid;
}
/**
* Set the simple primary key value that identifies this object.
* @param actionid
*/
public void setActionid(java.lang.Integer actionid)
{
this.hashValue = 0;
this.actionid = actionid;
}
/**
* Return the value of the ActionDesc column.
* @return java.lang.String
*/
public java.lang.String getActiondesc()
{
return this.actiondesc;
}
/**
* Set the value of the ActionDesc column.
* @param actiondesc
*/
public void setActiondesc(java.lang.String actiondesc)
{
this.actiondesc = actiondesc;
}
public boolean getActiondisabled() {
return actiondisabled;
}
public void setActiondisabled(boolean actiondisabled) {
this.actiondisabled = actiondisabled;
}
/**
* Return the value of the status_type column.
* @return CallType
*/
public CallType getCallType()
{
return this.callType;
}
/**
* Set the value of the status_type column.
* @param callType
*/
public void setCallType(CallType callType)
{
this.callType = callType;
}
/**
* Implementation of the equals comparison on the basis of equality of the primary key values.
* @param rhs
* @return boolean
*/
public boolean equals(Object rhs)
{
if (rhs == null)
return false;
if (! (rhs instanceof ActionType))
return false;
ActionType that = (ActionType) rhs;
if (this.getActionid() != null && that.getActionid() != null)
{
if (! this.getActionid().equals(that.getActionid()))
{
return false;
}
}
return true;
}
/**
* Implementation of the hashCode method conforming to the Bloch pattern with
* the exception of array properties (these are very unlikely primary key types).
* @return int
*/
public int hashCode()
{
if (this.hashValue == 0)
{
int result = 17;
int actionidValue = this.getActionid() == null ? 0 : this.getActionid().hashCode();
result = result * 37 + actionidValue;
this.hashValue = result;
}
return this.hashValue;
}
}
|
package com.miyatu.tianshixiaobai.activities.Others;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.toast.ToastUtils;
import com.miyatu.tianshixiaobai.MyApp;
import com.miyatu.tianshixiaobai.R;
import com.miyatu.tianshixiaobai.activities.BaseActivity;
import com.miyatu.tianshixiaobai.entity.BaseResultEntity;
import com.miyatu.tianshixiaobai.entity.WeChatRequestEntity;
import com.miyatu.tianshixiaobai.http.api.MarketApi;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import org.greenrobot.eventbus.EventBus;
import java.util.HashMap;
import java.util.Map;
import static com.miyatu.tianshixiaobai.utils.ThirdUtils.aliPay;
import static com.miyatu.tianshixiaobai.utils.ThirdUtils.wxPay;
public class PayActivity extends BaseActivity implements HttpOnNextListener {
private RelativeLayout relZhiFuBao;
private RelativeLayout relWeiXin;
private TextView tvOrderSN;
private TextView tvPrice;
private String orderSN;
private String price;
private HttpManager manager;
private MarketApi marketApi;
private Map<String, Object> params;
private void initAliPayRequest() {
params = new HashMap<>();
params.put("order_id", orderSN);
manager = new HttpManager(this,(RxAppCompatActivity)this);
marketApi = new MarketApi(MarketApi.ALI_PAY);
marketApi.setParams(params);
manager.doHttpDeal(marketApi);
}
private void initWxPayRequest() {
params = new HashMap<>();
params.put("order_id", orderSN);
manager = new HttpManager(this,(RxAppCompatActivity)this);
marketApi = new MarketApi(MarketApi.WEI_XIN_PAY);
marketApi.setParams(params);
manager.doHttpDeal(marketApi);
}
public static void startActivity(Activity activity, String orderSN, String price){
Intent intent = new Intent(activity, PayActivity.class);
intent.putExtra("orderSN", orderSN);
intent.putExtra("price", price);
activity.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_pay;
}
@Override
protected void initView() {
relZhiFuBao = findViewById(R.id.relZhiFuBao);
relWeiXin = findViewById(R.id.relWeiXin);
tvOrderSN = findViewById(R.id.tvOrderSN);
tvPrice = findViewById(R.id.tvPrice);
}
@Override
protected void initData() {
orderSN = getIntent().getStringExtra("orderSN");
price = getIntent().getStringExtra("price");
tvOrderSN.setText(orderSN);
tvPrice.setText(price);
}
@Override
protected void initEvent() {
}
@Override
protected void updateView() {
relZhiFuBao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initAliPayRequest();
}
});
relWeiXin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initWxPayRequest();
}
});
}
@Override
public void initTitle() {
super.initTitle();
setTitleCenter("支付");
}
@Override
public void onNext(String resulte, String mothead) {
if (mothead.equals(MarketApi.ALI_PAY)) {
BaseResultEntity<String> baseResultEntity = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity<String>>(){}.getType());
if (baseResultEntity.getStatus().equals("200")) { //成功
aliPay(PayActivity.this, baseResultEntity.getData());
return;
}
ToastUtils.show(baseResultEntity.getMsg());
}
if (mothead.equals(MarketApi.WEI_XIN_PAY)) {
BaseResultEntity<WeChatRequestEntity> baseResultEntity = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity<WeChatRequestEntity>>(){}.getType());
if (baseResultEntity.getStatus().equals("200")) { //成功
wxPay(baseResultEntity.getData());
return;
}
ToastUtils.show(baseResultEntity.getMsg());
}
}
@Override
public void onError(ApiException e) {
}
@Override
public void onEvent(Object object) {
if(object instanceof BaseResp){
BaseResp resp = (BaseResp)object;
if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
if (resp.errCode == 0) {
ToastUtils.show("支付成功");
EventBus.getDefault().post(MyApp.myDemandRefresh);
finish();
} else if (resp.errCode == -2) {
ToastUtils.show("取消支付");
} else {
ToastUtils.show("参数错误");
}
}
}else {
Map<String, String> result = (Map<String, String>) object;
//9000 订单支付成功
//8000 正在处理中
//4000 订单支付失败
//6001 用户中途取消
//6002 网络连接出错
String status = result.get("resultStatus");
if (status.equals("9000")) {
ToastUtils.show("支付成功");
EventBus.getDefault().post(MyApp.myDemandRefresh);
finish();
}
if (status.equals("8000")) {
ToastUtils.show("正在处理中");
}
if (status.equals("4000")) {
ToastUtils.show("订单支付失败");
}
if (status.equals("6001")) {
ToastUtils.show("取消支付");
}
if (status.equals("6002")) {
ToastUtils.show("网络连接出错");
}
}
}
}
|
package com.example.prog3.alkasaffollowup;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.prog3.alkasaffollowup.Adapters.ContractInfoGridAdapter;
import com.example.prog3.alkasaffollowup.Adapters.ProjectsSpinnerAdapter;
import com.example.prog3.alkasaffollowup.Data.UrlPath;
import com.example.prog3.alkasaffollowup.Model.ClientsScreens;
import com.example.prog3.alkasaffollowup.Model.Project;
import com.example.prog3.alkasaffollowup.Services.ProjectsInterface;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class FinancialFollowupActivity extends AppCompatActivity {
private Spinner projectsspinner;
GridView grid;
private Integer sn;
private String guid;
private String ref;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_financial_followup);
guid = getIntent().getExtras().getString("guid");
projectsspinner=findViewById(R.id.projectsspinner);
grid = findViewById(R.id.grid);
mProgressBar=findViewById(R.id.progress_bar);
if(isNetworkAvailable()){
//Toast.makeText(this,"Internet Exists!",Toast.LENGTH_LONG).show();
fetchAllProjects(guid);
/*
SharedPreferences.Editor prefsEditor = sharedpreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(projects);
prefsEditor.putString("projlist", json);
prefsEditor.commit();
*/
}else{
// Toast.makeText(this,"Internet Not Exists!",Toast.LENGTH_LONG).show();
/*
Gson gson = new Gson();
String json = sharedpreferences.getString("projlist", "");
List<Project> projs = Collections.singletonList(gson.fromJson(json, Project.class));
viewAllPersons(projs);
*/
//List<Project> projects = getIntent().getExtras().getParcelable("projects");
// ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("projects");
List<Project> projects = (List<Project>) getIntent().getSerializableExtra("projects");
/*
for(int i=0;i<projects.size();i++){
Project project = projects.get(i);
String projName = project.getProjName();
String projRef = project.getProjRef();
Integer sn = project.getSn();
Toast.makeText(ContractingInfoActivity.this,projName+"-"+projRef+"-"+sn,Toast.LENGTH_LONG).show();
}
*/
viewAllPersons(projects);
}
ContractInfoGridAdapter adp = new ContractInfoGridAdapter(this, viewAllContractInformatios());
grid.setAdapter(adp);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ClientsScreens c = (ClientsScreens) parent.getItemAtPosition(position);
switch (c.getName()){
case "Progress Stage":
Intent i=new Intent(FinancialFollowupActivity.this,ProgressSteage.class);
i.putExtra("guid",guid);
i.putExtra("sn",sn);
startActivity(i);
break;
case "Payments and Conditions":
Intent i2=new Intent(FinancialFollowupActivity.this,PaymentsAndConditions.class);
i2.putExtra("guid",guid);
i2.putExtra("sn",sn);
startActivity(i2);
break;
case "Invoices":
Intent i3=new Intent(FinancialFollowupActivity.this,ProjInvoicesFollowup.class);
i3.putExtra("guid",guid);
i3.putExtra("sn",sn);
i3.putExtra("ref",ref);
startActivity(i3);
break;
case "Collected":
Intent i4=new Intent(FinancialFollowupActivity.this,ProjCollectedFollowup.class);
i4.putExtra("guid",guid);
i4.putExtra("sn",sn);
i4.putExtra("ref",ref);
startActivity(i4);
break;
case "Balance":
Intent i5=new Intent(FinancialFollowupActivity.this,ProjBalance.class);
i5.putExtra("guid",guid);
i5.putExtra("sn",sn);
startActivity(i5);
break;
}
}
});
}
private void fetchAllProjects(String guid) {
String url= UrlPath.path;
Retrofit.Builder builder=new Retrofit.Builder();
builder.baseUrl(url).addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
ProjectsInterface projectsInterface = retrofit.create(ProjectsInterface.class);
Call<List<Project>> allProjectsByClient = projectsInterface.getAllProjectsByClient(guid);
allProjectsByClient.enqueue(new Callback<List<Project>>() {
@Override
public void onResponse(Call<List<Project>> call, Response<List<Project>> response) {
List<Project> projects = response.body();
viewAllPersons(projects);
}
@Override
public void onFailure(Call<List<Project>> call, Throwable t) {
Toast.makeText(FinancialFollowupActivity.this,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
private void viewAllPersons(final List<Project> projects) {
ProjectsSpinnerAdapter adp=new ProjectsSpinnerAdapter(FinancialFollowupActivity.this,projects);
projectsspinner.setAdapter(adp);
projectsspinner.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
projectsspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//String country= projectsspinner.getItemAtPosition(projectsspinner.getSelectedItemPosition()).toString();
//Toast.makeText(getApplicationContext(),country,Toast.LENGTH_LONG).show();
Project project = projects.get(position);
sn = project.getSn();
ref = project.getProjRef();
//Toast.makeText(ContractingInfoActivity.this,Id.toString(),Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public List<ClientsScreens> viewAllContractInformatios() {
List<ClientsScreens> screens = new ArrayList<>();
screens.add(new ClientsScreens(R.drawable.prog, "Progress Stage"));
screens.add(new ClientsScreens(R.drawable.pay, "Payments and Conditions"));
screens.add(new ClientsScreens(R.drawable.invoice, "Invoices"));
screens.add(new ClientsScreens(R.drawable.col, "Collected"));
screens.add(new ClientsScreens(R.drawable.bal, "Balance"));
return screens;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean b;
if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){
b=true;
}else {
b=false;
}
return b;
}
}
|
package lab12;
import java.io.File;
import java.util.Scanner;
/**
* Created by ran on 4/6/16.
*
* Heap sort, Quick sort & Merge sort
*
*/
public class Lab {
public static void main(String[] args) throws Exception{
Scanner w = new Scanner(System.in);
w.nextLine();
//prepare file
String file = "src/lab12/students-32768.dat";
Scanner sc = new Scanner(new File(file));
Student[] s = new Student[32768];
Student[] t = new Student[32768];
Student[] d = new Student[32768];
//load file to array
long startTime = System.nanoTime();
int i = 0;
while (sc.hasNext()){
String temp = sc.nextLine();
String[] temps = temp.split(" ");
s[i] = new Student(temps[0], temps[1], temps[2], Long.parseLong(temps[3]));
i++;
}
long finishTime = System.nanoTime();
long elapsedTime = finishTime - startTime;
sc.close();
System.out.println("Load file to array takes " + elapsedTime / 1E9 + " seconds");
long heapTime, quickTime, mergeTime;
heapTime = quickTime = mergeTime = 0;
// run 10 times
for (i = 0; i < 10; i++) {
//// do Heap sort
System.arraycopy(s, 0, t, 0, s.length);
try {
Thread.sleep(1000); //sleep
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
startTime = System.nanoTime();
heapSort(t);
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
heapTime = heapTime + elapsedTime;
System.out.println("Heap sort of data file takes " + elapsedTime / 1E9 + " seconds");
// //do Quick sort
System.arraycopy(s, 0, t, 0, s.length);
try {
Thread.sleep(1000); //sleep
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
startTime = System.nanoTime();
quickSort(t, 0, t.length - 1);
//sort1(t, 0, t.length);
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
quickTime = quickTime + elapsedTime;
System.out.println("Quick sort of data file takes " + elapsedTime / 1E9 + " seconds");
//do Merge sort
System.arraycopy(s, 0, t, 0, s.length);
System.arraycopy(s, 0, d, 0, s.length);
try {
Thread.sleep(1000); //sleep
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
startTime = System.nanoTime();
mergeSort(t, d, 0, t.length);
finishTime = System.nanoTime();
elapsedTime = finishTime - startTime;
mergeTime = mergeTime + elapsedTime;
System.out.println("Merge sort of data file takes " + elapsedTime / 1E9 + " seconds");
}
System.out.println("Run 10 times. heap: " + heapTime / 1E9 + " seconds, quick: " + quickTime / 1E9 + " seconds, merge: " + mergeTime /1E9 + "seconds");
// for (Student c : t) {System.out.println(c.toString());}
}
// swap
private static void swap(Student[] arr, int a, int b) {
Student tmp = new Student(arr[a].lastname, arr[a].firstname, arr[a].middlename, arr[a].id);
arr[a] = new Student(arr[b].lastname, arr[b].firstname, arr[b].middlename, arr[b].id);
arr[b] = new Student(tmp.lastname, tmp.firstname, tmp.middlename, tmp.id);
}
// heapify
private static void heapify(Student[] o, int i, int total) {
int left = i * 2;
int right = left + 1;
int great = i;
if (left <= total && o[left].compareTo(o[great]) > 0) {
great = left;
}
if (right <= total && o[right].compareTo(o[great]) > 0) {
great = right;
}
if (great != i) {
swap(o, i, great);
heapify(o, great, total);
}
}
// Heap sort
private static void heapSort(Student[] o) {
int total = o.length - 1;
for (int i = (total >> 1); i >= 0; i--) {
heapify(o, i, total);
}
for (int i = total; i > 0; i--) {
swap(o, 0, i);
total--;
heapify(o, 0, total);
}
}
// Merge sort
private static void mergeSort(Student[] src, Student[] dest, int low, int high) {
int length = high - low;
if (length < 7) {
for (int i = low; i < high; i++) {
for (int j = i; j > low && dest[j-1].compareTo(dest[j]) > 0; j--) {
swap(dest, j, j-1);
}
}
return;
}
int mid = (low + high) >> 1;
mergeSort (dest, src, low, mid);
mergeSort (dest, src, mid, high);
if ((src[mid-1]).compareTo(src[mid]) <= 0) {
System.arraycopy (src, low, dest, low, length);
return;
}
for (int i = low, p = low, q = mid; i < high; i++) {
if (q >= high || (p < mid && src[p].compareTo(src[q]) <= 0)) {
dest[i] = src[p++];
} else {
dest[i] = src[q++];
}
}
}
// Quick sort
private static void quickSort(Student a[], int left, int right) {
// System.out.println(left + " " + right);
if (left < right) {
int newPivotIndex = partition(a, left, right, medianOfThree(a, left, right));//((left + right) >> 1));//medianOfThree(a, left, right));
quickSort(a, left, newPivotIndex-1);
quickSort(a, newPivotIndex+1, right);
}
// System.out.println(left + " " + right);
}
private static int medianOfThree(Student[] a, int left, int right) {
int mid = ((left + right) >> 1);
// 1st way to mot
// if (a[right].compareTo(a[left]) < 0) {
// swap(a, left, right);
// }
// if (a[mid].compareTo(a[left]) < 0) {
// swap(a, mid, right);
// }
// if (a[right].compareTo(a[mid]) < 0) {
// swap(a, right, mid);
// }
// return mid;
// 2nd way to mot
if ((a[right].compareTo(a[left]) <= 0 && a[right].compareTo(a[mid]) >= 0) || (a[right].compareTo(a[left]) >= 0 && a[right].compareTo(a[mid]) <= 0)) {
return right;
}
if ((a[left].compareTo(a[right]) <= 0 && a[left].compareTo(a[mid]) >= 0) || (a[left].compareTo(a[right]) >= 0 && a[left].compareTo(a[mid]) <= 0)) {
return left;
}
return mid;
}
private static int partition(Student a[], int left, int right, int pivotIndex) {
swap(a, pivotIndex, right); //move pivot to right
int storeIndex = left;
for (int i = left; i < right; i++) {
if (a[i].compareTo(a[right]) < 0) //if current < pivot
{
swap(a, i, storeIndex);
storeIndex++; //the index of (the last founded less than pivot object) + 1
}
}
swap(a, right, storeIndex); //swap pivot and storeIndex
return storeIndex;
}
// quick sort from book
private static int med3(Student x[], int a, int b, int c) {
return (x[a].compareTo(x[b]) < 0 ?
(x[b].compareTo(x[c]) < 0 ? b : x[a].compareTo(x[c]) < 0 ? c : a) :
(x[b].compareTo(x[c]) > 0 ? b : x[a].compareTo(x[c]) > 0 ? c : a));
} // method med3
private static void sort1(Student[] x, int off, int len) {
// Insertion sort on smallest arrays
if (len < 7) {
for (int i=off; i<len+off; i++)
for (int j=i; j>off && x[j-1].compareTo(x[j]) > 0; j--)
swap(x, j, j-1);
return;
}
// Choose a partition element, v
int m = off + (len >> 1);
if (len > 7) {
int l = off;
int n = off + len - 1;
if (len > 40) {
// Small arrays, middle element
// Big arrays, pseudomedian of 9
int s = len/8;
l = med3(x, l, l+s, l+2*s);
m = med3(x, m-s, m, m+s);
n = med3(x, n-2*s, n-s, n);
}
m = med3(x, l, m, n); // Mid-size, med
}
Student v=x[m]; //v is the pivot
// Establish Invariant: = v; < v; > v; =
int a = off, b = a, c = off + len - 1, d =c;
while (true) {
while (b <= c && x[b].compareTo(v) <= 0) {
if (x[b] == v)
swap(x, a++, b);
b++;
}
while (c >= b && x[c].compareTo(v) >= 0) {
if (x[c] == v)
swap(x, c, d--);
c--;
}
if (b > c)
break;
swap(x, b++, c--);
}
// Swap partition elements back to middle
int s, n = off + len;
s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s);
s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s);
// Recursively sort
if ((s = b-a) > 1)
sort1(x, off, s);
if ((s = d-c) > 1)
sort1(x, n-s, s);
}
private static void vecswap(Student x[], int a, int b, int n) {
for (int i=0; i<n; i++, a++, b++)
swap(x, a, b);
} // method vecswap
}
|
package com.alibaba.druid.bvt.pool;
import java.sql.SQLException;
import com.alibaba.druid.PoolTestCase;
import org.junit.Assert;
import junit.framework.TestCase;
import com.alibaba.druid.filter.FilterAdapter;
import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.GetConnectionTimeoutException;
import com.alibaba.druid.proxy.jdbc.ConnectionProxy;
public class DruidConnectionHolderTest2 extends PoolTestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
super.setUp();
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setTestOnBorrow(false);
dataSource.setPoolPreparedStatements(true);
dataSource.getProxyFilters().add(new FilterAdapter() {
public int connection_getTransactionIsolation(FilterChain chain, ConnectionProxy connection)
throws SQLException {
throw new SQLException();
}
});
}
protected void tearDown() throws Exception {
dataSource.close();
super.tearDown();
}
public void test_mysqlSyntaxError() throws Exception {
Exception error = null;
try {
dataSource.getConnection(100);
} catch (GetConnectionTimeoutException e) {
error = e;
}
Assert.assertNotNull(error);
}
}
|
package GUI.controller;
import java.io.IOException;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import javax.xml.bind.ValidationException;
import exceptions.FormatacaoInvalidaException;
import exceptions.ProdutoJaExisteException;
import exceptions.ProdutoNaoExisteException;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import negocios.PanelaFit;
import negocios.beans.Produto;
public class ProdutoPaneController {
private PanelaFit panelaFit;
@FXML
Button butCadastrar;
@FXML
private Label lblMensagem;
@FXML
private TextField txtNomeProduto;
@FXML
private TextField txtPesoProduto;
@FXML
private TextField txtCaloriasProduto;
@FXML
private TextField txtCodigoProduto;
@FXML
private TextField txtQuantEstoqueProduto;
@FXML
private TextField txtPrecoProduto;
@FXML
private TextField txtDataFab;
@FXML
private TextField txtDataVal;
@FXML
private TableView<Produto> tabelaProdutos;
@FXML
TableColumn<Produto, String> colunaNome;
@FXML
TableColumn<Produto, String> colunaCodigo;
@FXML
TableColumn<Produto, String> colunaPeso;
@FXML
TableColumn<Produto, String> colunaCalorias;
@FXML
TableColumn<Produto, String> colunaQuantEstoque;
@FXML
TableColumn<Produto, String> colunaPreco;
@FXML
TableColumn<Produto, String> colunaDataFab;
@FXML
TableColumn<Produto, String> colunaDataVal;
public DateTimeFormatter DATE_FORMAT = new DateTimeFormatterBuilder().appendPattern("dd/MM/yyyy").toFormatter();
private ObservableList<Produto> data;
public void sair(ActionEvent event) {
((Node) event.getSource()).getScene().getWindow().hide();
}
public void voltarMenuPrincipal(ActionEvent event) {
((Node) event.getSource()).getScene().getWindow().hide();
Parent parent;
try {
parent = FXMLLoader.load(getClass().getResource("/GUI/view/PanelaFit.fxml"));
Stage stage3 = new Stage();
Scene cena = new Scene(parent);
stage3.setScene(cena);
stage3.show();
} catch (IOException e) {
lblMensagem.setText(e.getMessage());
}
}
public void cadastrarProduto() throws ValidationException, IOException {
if (validateFields()) {
try {
String nome;
Integer codigo = new Integer(txtCodigoProduto.getText());
Integer calorias = new Integer(txtCaloriasProduto.getText());
Integer quantEstoque = new Integer(txtQuantEstoqueProduto.getText());
Float peso = new Float(txtPesoProduto.getText().replace("K", "").replace("G", ""));
Double preco = new Double(txtPrecoProduto.getText().replace("R", "").replace("$", ""));
LocalDate dataFab = LocalDate.parse(txtDataFab.getText(), DATE_FORMAT);
LocalDate dataVal = LocalDate.parse(txtDataVal.getText(), DATE_FORMAT);
nome = txtNomeProduto.getText();
Produto aux = new Produto(nome, peso, calorias, codigo, quantEstoque, preco, dataFab, dataVal);
validateAttributes(aux);
panelaFit.cadastrarProduto(aux);
refreshTable();
limparForm();
lblMensagem.setText("Produto Cadastrado");
} catch (FormatacaoInvalidaException e) {
lblMensagem.setText(e.getMessage());
} catch (ProdutoJaExisteException e) {
lblMensagem.setText(e.getMessage());
} catch (DateTimeException e) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
txtDataFab.setStyle("-fx-background-color: red;");
txtDataVal.setStyle("-fx-background-color: red;");
}
}
}
public void removerProduto() throws FormatacaoInvalidaException, ProdutoNaoExisteException, IOException {
Produto produtoSelecionado = tabelaProdutos.getSelectionModel().getSelectedItem();
try {
if (produtoSelecionado != null) {
Integer codig = new Integer(produtoSelecionado.getCodigo());
if (panelaFit.existeProduto(codig)) {
panelaFit.removerProduto(produtoSelecionado);
tabelaProdutos.getItems().remove(tabelaProdutos.getSelectionModel().getSelectedIndex());
limparForm();
refreshTable();
lblMensagem.setText("Produto Removido");
}
} else {
Integer code = new Integer(txtCodigoProduto.getText());
if (panelaFit.existeProduto(code)) {
Produto aux = panelaFit.buscarProduto(code);
panelaFit.removerProduto(aux);
refreshTable();
limparForm();
lblMensagem.setText("Produto Removido");
}
}
} catch (ProdutoNaoExisteException e) {
lblMensagem.setText(e.getMessage());
} catch (NumberFormatException e) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
}
}
public void alterarProduto()
throws ProdutoNaoExisteException, FormatacaoInvalidaException, ValidationException, IOException {
if (validateFields()) {
try {
String nome;
Integer codigo = new Integer(txtCodigoProduto.getText());
Integer calorias = new Integer(txtCaloriasProduto.getText());
Integer quantEstoque = new Integer(txtQuantEstoqueProduto.getText());
Float peso = new Float(txtPesoProduto.getText().replace("K", "").replace("G", ""));
Double preco = new Double(txtPrecoProduto.getText().replace("R", "").replace("$", ""));
LocalDate dataFab = LocalDate.parse(txtDataFab.getText(), DATE_FORMAT);
LocalDate dataVal = LocalDate.parse(txtDataVal.getText(), DATE_FORMAT);
nome = txtNomeProduto.getText();
Produto aux = new Produto(nome, peso, calorias, codigo, quantEstoque, preco, dataFab, dataVal);
validateAttributes(aux);
panelaFit.alterarProduto(aux);
refreshTable();
limparForm();
lblMensagem.setText("Produto alterado");
} catch (FormatacaoInvalidaException e) {
lblMensagem.setText(e.getMessage());
} catch (ProdutoNaoExisteException e) {
lblMensagem.setText(e.getMessage());
} catch (NumberFormatException e) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
} catch (DateTimeException e) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
txtDataFab.setStyle("-fx-background-color: red;");
txtDataVal.setStyle("-fx-background-color: red;");
}
}
}
public void setDados(ObservableList<Produto> dadosProduto) {
tabelaProdutos.setItems(dadosProduto);
}
@FXML
private void initialize() {
panelaFit = PanelaFit.getInstance();
colunaNome.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getNome()));
colunaCalorias.setCellValueFactory(new PropertyValueFactory<Produto, String>("Calorias"));
colunaCodigo.setCellValueFactory(new PropertyValueFactory<Produto, String>("Codigo"));
colunaPeso.setCellValueFactory(new PropertyValueFactory<Produto, String>("Peso"));
colunaPreco.setCellValueFactory(new PropertyValueFactory<Produto, String>("Preco"));
colunaQuantEstoque.setCellValueFactory(new PropertyValueFactory<Produto, String>("QuantEstoque"));
colunaDataFab.setCellValueFactory(new PropertyValueFactory<Produto, String>("DataFabricacao"));
colunaDataVal.setCellValueFactory(new PropertyValueFactory<Produto, String>("DataValidade"));
data = FXCollections.observableArrayList();
data.addAll(panelaFit.listarProdutos());
tabelaProdutos.setItems(data);
}
@FXML
public void limparForm() {
txtNomeProduto.clear();
txtPesoProduto.clear();
txtCaloriasProduto.clear();
txtPrecoProduto.clear();
txtQuantEstoqueProduto.clear();
txtDataFab.clear();
txtDataVal.clear();
txtCodigoProduto.clear();
txtCodigoProduto.editableProperty().set(true);
txtCodigoProduto.setStyle(null);
txtNomeProduto.setStyle(null);
txtCaloriasProduto.setStyle(null);
txtQuantEstoqueProduto.setStyle(null);
txtDataFab.setStyle(null);
txtDataVal.setStyle(null);
lblMensagem.setText(null);
tabelaProdutos.getSelectionModel().clearSelection();
}
private void validateAttributes(Produto produto) throws ValidationException {
String returnMs = "";
Integer codigo = produto.getCodigo();
Float peso = produto.getPeso();
Integer calorias = produto.getCalorias();
Integer quantEstoque = produto.getQuantEstoque();
Double preco = produto.getPreco();
if (produto.getNome() == null || produto.getNome().isEmpty()) {
returnMs += "'Nome' ";
}
if (peso.toString() == null || peso.toString().isEmpty()) {
returnMs += "'Peso' ";
}
if (calorias.toString() == null || calorias.toString().isEmpty()) {
returnMs += "'Calorias '";
}
if (quantEstoque.toString() == null || quantEstoque.toString().isEmpty()) {
returnMs += "'QuantidadeEstoque' ";
}
if (preco.toString() == null || preco.toString().isEmpty()) {
returnMs += "'Preco' ";
}
if (codigo.toString() == null || codigo.toString().isEmpty()) {
returnMs += "'Codigo' ";
}
if (produto.getDataFabricacao() == null) {
returnMs += "'DataFabricacao' ";
}
if (produto.getDataValidade() == null) {
returnMs += "'DataValidade' ";
}
if (!returnMs.isEmpty()) {
throw new ValidationException(
String.format("Os arumentos[%s] obrigatorios estao nulos ou com valores invalidos", returnMs));
}
}
private boolean validateFields() throws IOException {
boolean validate = false;
try {
if ((txtNomeProduto.getText().isEmpty() || !txtNomeProduto.getText().matches("[a-z A-Z]+"))
|| (txtCodigoProduto.getText().isEmpty()
|| !txtCodigoProduto.getText().matches("[0-9][0-9][0-9][0-9][0-9]"))
|| (txtPesoProduto.getText().isEmpty() || !txtPesoProduto.getText().matches("[0-9][0-9][0-9]G"))
|| (txtCaloriasProduto.getText().isEmpty() || !txtCaloriasProduto.getText().matches("[0-9]+"))
|| (txtPrecoProduto.getText().isEmpty()
|| !txtPrecoProduto.getText().matches("[R][$][0-9][0-9][0-9]"))
|| (txtQuantEstoqueProduto.getText().isEmpty()
|| !txtQuantEstoqueProduto.getText().matches("[0-9]+"))
|| (txtDataFab.getText().isEmpty()
|| !txtDataFab.getText().matches("[0-9][0-9][/][0-9][0-9][/][0-9][0-9][0-9][0-9]"))
|| (txtDataVal.getText().isEmpty()
|| !txtDataVal.getText().matches("[0-9][0-9][/][0-9][0-9][/][0-9][0-9][0-9][0-9]"))) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
if (txtNomeProduto.getText().isEmpty() || !txtNomeProduto.getText().matches("[a-z A-Z]+")) {
txtNomeProduto.setStyle("-fx-background-color: red;");
}
if (txtCaloriasProduto.getText().isEmpty() || !txtCaloriasProduto.getText().matches("[0-9]+")) {
txtCaloriasProduto.setStyle("-fx-background-color: red;");
}
if (txtQuantEstoqueProduto.getText().isEmpty() || !txtQuantEstoqueProduto.getText().matches("[0-9]+")) {
txtQuantEstoqueProduto.setStyle("-fx-background-color: red;");
}
} else {
validate = true;
}
} catch (NumberFormatException e) {
e.getMessage();
}
return validate;
}
@FXML
private void refreshTable() {
data = FXCollections.observableArrayList();
data.addAll(panelaFit.listarProdutos());
tabelaProdutos.setItems(data);
}
@FXML
public void selecionarProduto(MouseEvent arg0) {
if (!tabelaProdutos.getSelectionModel().isEmpty()) {
Produto produtoSelecionado = tabelaProdutos.getSelectionModel().getSelectedItem();
Integer codigo = produtoSelecionado.getCodigo();
Integer calorias = produtoSelecionado.getCalorias();
Integer quantEstoque = produtoSelecionado.getQuantEstoque();
Float peso = produtoSelecionado.getPeso();
Double preco = produtoSelecionado.getPreco();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
txtDataFab.setText(formatter.format(produtoSelecionado.getDataFabricacao()));
txtDataVal.setText(formatter.format(produtoSelecionado.getDataValidade()));
txtNomeProduto.setText(produtoSelecionado.getNome());
txtCodigoProduto.setText(codigo.toString());
txtCaloriasProduto.setText(calorias.toString());
txtQuantEstoqueProduto.setText(quantEstoque.toString());
txtPesoProduto.setText(peso.toString());
char[] a = txtPesoProduto.getText().toCharArray();
String pesoPesado = "";
for (int i = 0; i < a.length; i++) {
if (i == 4) {
pesoPesado += a[i] + "G";
} else {
pesoPesado += a[i];
}
}
txtPesoProduto.setText(pesoPesado);
preco.toString();
txtPrecoProduto.setText(String.format("%.0f", preco));
char[] b = txtPrecoProduto.getText().toCharArray();
String price = "";
for (int i = 0; i < b.length; i++) {
if (i == 0) {
price += "R$" + b[i];
} else {
price += b[i];
}
}
txtPrecoProduto.setText(price);
txtCodigoProduto.editableProperty().set(false);
txtCodigoProduto.setStyle("-fx-background-color: gray;");
}
}
@FXML
public void buscarProduto() throws ProdutoNaoExisteException, IOException {
Produto p;
try {
Integer code = new Integer(txtCodigoProduto.getText());
p = panelaFit.buscarProduto(code);
Integer codigo = p.getCodigo();
Integer calorias = p.getCalorias();
Integer quantEstoque = p.getQuantEstoque();
Float peso = p.getPeso();
Double preco = p.getPreco();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
txtDataFab.setText(formatter.format(p.getDataFabricacao()));
txtDataVal.setText(formatter.format(p.getDataValidade()));
txtNomeProduto.setText(p.getNome());
txtCodigoProduto.setText(codigo.toString());
txtCaloriasProduto.setText(calorias.toString());
txtQuantEstoqueProduto.setText(quantEstoque.toString());
txtPesoProduto.setText(peso.toString());
char[] a = txtPesoProduto.getText().toCharArray();
String pesoPesado = "";
for (int i = 0; i < a.length; i++) {
if (i == 4) {
pesoPesado += a[i] + "G";
} else {
pesoPesado += a[i];
}
}
txtPesoProduto.setText(pesoPesado);
preco.toString();
txtPrecoProduto.setText(String.format("%.0f", preco));
char[] b = txtPrecoProduto.getText().toCharArray();
String price = "";
for (int i = 0; i < b.length; i++) {
if (i == 0) {
price += "R$" + b[i];
} else {
price += b[i];
}
}
txtPrecoProduto.setText(price);
txtCodigoProduto.editableProperty().set(false);
txtCodigoProduto.setStyle("-fx-background-color: gray;");
} catch (NumberFormatException e) {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/GUI/view/PopUpTela.fxml"));
Parent root1 = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UNDECORATED);
stage.setTitle("Panela Fit");
stage.setScene(new Scene(root1));
stage.show();
} catch (ProdutoNaoExisteException e) {
lblMensagem.setText(e.getMessage());
}
}
}
|
package com.acewill.ordermachine.dialog;
import android.view.View;
import com.acewill.ordermachine.R;
/**
* Author:Anch
* Date:2017/12/25 14:56
* Desc:
*/
public class ChangeLanguageDialog extends BaseDialog implements View.OnClickListener {
/**
* @return
*/
public static ChangeLanguageDialog newInstance() {
ChangeLanguageDialog fragment = new ChangeLanguageDialog();
return fragment;
}
@Override
public View getView() {
View view = View.inflate(mcontext, R.layout.dialog_changelanguage, null);
view.findViewById(R.id.zhongwen).setOnClickListener(this);
view.findViewById(R.id.yingwen).setOnClickListener(this);
return view;
}
private OnLanguageSelectListener mListener;
public void setOnLanguageSelectListener(OnLanguageSelectListener listener) {
this.mListener = listener;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.zhongwen:
if (mListener != null)
mListener.onLanguageSelect(0);
dismiss();
break;
case R.id.yingwen:
if (mListener != null)
mListener.onLanguageSelect(1);
dismiss();
break;
}
}
public interface OnLanguageSelectListener {
void onLanguageSelect(int position);
}
@Override
public float getSize() {
return 0.5f;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gtree;
import java.util.ArrayList;
/**
*
* @author grostirolla
*/
public class Tree {
private Node root;
private int count;
private int DEFROOTX = 100;
private int DEFROOTY = 70;
private int SPACEX = 100;
private int SPACEY = 75;
private double dimensionX = 0;
private double dimensionY = 0;
public double getDimensionX() {
return dimensionX;
}
public double getDimensionY() {
return dimensionY;
}
public Tree(String element) {
root = new Node(null, element, DEFROOTX, DEFROOTY);
this.count = 1;
}
public Tree(String element, double rootX, double rootY) {
root = new Node(null, element, rootX, rootY);
this.count = 1;
}
public Position root() {
return this.root;
}
public Position parent(Position pos) throws Exception {
Node n = (Node) pos;
if (!isRoot(n)) {
return (Position) n.getParentNode();
} else {
throw new Exception("root node");
}
}
public ArrayList<Position> children(Position pos) throws Exception {
Node n = (Node) pos;
if (n.getChildren() != null) {
ArrayList<Position> positions = new ArrayList<Position>();
for (Node i : n.getChildren()) {
positions.add(i);
}
return positions;
} else {
throw new Exception("no children");
}
}
public boolean isRoot(Position pos) {
if ((Node) pos == root) {
return true;
} else {
return false;
}
}
public boolean isExternal(Position pos) {
Node n = (Node) pos;
try {
if (n.getChildren().size() > 0) {
return false;
} else {
return true;
}
} catch (Exception e) {
e.printStackTrace();
return true;
}
}
public boolean isInternal(Position pos) {
Node n = (Node) pos;
try {
n.getChildren();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public int size() {
return this.count;
}
public ArrayList<String> elements() {
Node n = root;
ArrayList<String> elements = new ArrayList<String>();
recGetElements(n, elements);
return elements;
}
public ArrayList<Position> positions() {
Node n = root;
ArrayList<Position> positions = new ArrayList<Position>();
recGetPositions(n, positions);
return positions;
}
public void swapElements(Position p1, Position p2) {
String aux;
aux = ((Node) p1).getElement();
((Node) p1).setElement(((Node) p2).getElement());
((Node) p2).setElement(aux);
}
public String replaceElement(Position pos, String element) {
Node n = (Node) pos;
String previous = n.getElement();
n.setElement(element);
return previous;
}
public Position addChild(Position pos, String element) {
/*
* Node n = (Node) pos; Node child = new Node(n, element);
* ArrayList<Node> children = n.getChildren(); children.add(child);
* n.setChildren(children); count++; return child;
*/
//System.out.println("PARENT OF "+((Node)pos)+" is "+((Node)pos).getParentNode().getClass());
Node n = (Node) pos;
int multiplier = n.getChildren().size();
if ((n.getX() + SPACEX) > dimensionX) {
dimensionX = n.getX() + SPACEX;
}
if ((n.getY() + SPACEY * multiplier) > dimensionY) {
dimensionY = n.getY() + SPACEY * multiplier;
}
Node child = new Node(n, element, n.getX() + SPACEX, n.getY() + SPACEY * multiplier);
ArrayList<Node> children = n.getChildren();
children.add(child);
n.setChildren(children);
count++;
return child;
}
public void removeExternal(Position pos) throws Exception {
Node n = (Node) pos;
Node father = n.getParentNode();
if (isExternal(pos) && !isRoot(pos)) {
for (int i = 0; i < father.getChildren().size(); i++) {
if (father.getChildren().get(i) == n) {
father.getChildren().remove(father.getChildren().get(i));
count--;
break;
}
}
} else {
throw new Exception("This node is not External");
}
}
private ArrayList<String> recGetElements(Node n, ArrayList<String> array) {
array.add(n.getElement());
if (n.getChildren().size() > 0) {
for (int i = 0; i < n.getChildren().size(); i++) {
recGetElements(n.getChildren().get(i), array);
}
}
return array;
}
private ArrayList<Position> recGetPositions(Node n, ArrayList<Position> array) {
array.add((Position) n);
if (n.getChildren().size() > 0) {
for (int i = 0; i < n.getChildren().size(); i++) {
recGetPositions(n.getChildren().get(i), array);
}
}
return array;
}
}
|
package g350;
/**
* @author 方康华
* @title PowerOfFore
* @projectName leetcode
* @description No.342 Easy
* @date 2019/7/22 20:50
*/
public class PowerOfFour {
// 三个要求:大于0,是2的幂,唯一一个"1"在奇数为上
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num & 0xAAAAAAAA) == 0;
}
}
|
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int n = in.nextInt();
int lastLeft = 0;
int lastRight = 0;
for (int i = 0; i < n; i++) {
int input = in.nextInt();
if (input == 0) {
lastLeft = i + 1;
} else {
lastRight = i + 1;
}
}
out.println(Math.min(lastLeft, lastRight));
in.close();
out.close();
}
} |
// Command.java
package org.google.code.netapps.scriptrunner;
/**
* This interface is a wrapper for command definitions.
*
* @version 1.0 05/16/2001
* @author Alexander Shvets
*/
public interface Command {
public static final String PROMOTE = "promote";
public static final String GET = "get";
public static final String SCRIPT = "script";
}
|
package za.ac.cput.chapter5assignment.facadepattern;
/**
* Created by student on 2015/03/12.
*/
public class Boat implements Vehicle {
@Override
public String getWhereItMoves() {
return "Boat moves on water";
}
}
|
package com.takipi.tests.counters.immutables;
//immutableOrder
public final class Order {
private final int id;
public Order(int id) {
this.id = id;
}
public int getId() {
return id;
}
}
|
package com.example.forcatapp.util;
import java.util.List;
public class SessionControl {
static public HttpClient httpclient = null;
public static HttpClient getHttpclient() {
if (httpclient == null) {
HttpClient http = new HttpClient();
SessionControl.setHttpclient(http);
}
return httpclient;
}
public static void setHttpclient(HttpClient httpclient) {
SessionControl.httpclient = httpclient;
}
}
|
package org.valdi.entities;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.ServicePriority;
import org.bukkit.plugin.java.JavaPlugin;
import org.valdi.entities.api.DisguiseAPI;
import org.valdi.entities.api.DisguiseEvent;
import org.valdi.entities.api.EntityDisguiseEvent;
import org.valdi.entities.api.EntityUndisguiseEvent;
import org.valdi.entities.api.OfflinePlayerDisguiseEvent;
import org.valdi.entities.api.OfflinePlayerUndisguiseEvent;
import org.valdi.entities.api.UndisguiseEvent;
import org.valdi.entities.disguise.AgeableDisguise;
import org.valdi.entities.disguise.CreeperDisguise;
import org.valdi.entities.disguise.Disguise;
import org.valdi.entities.disguise.DisguiseType;
import org.valdi.entities.disguise.EndermanDisguise;
import org.valdi.entities.disguise.FallingBlockDisguise;
import org.valdi.entities.disguise.ItemDisguise;
import org.valdi.entities.disguise.MobDisguise;
import org.valdi.entities.disguise.ObjectDisguise;
import org.valdi.entities.disguise.OcelotDisguise;
import org.valdi.entities.disguise.OutdatedServerException;
import org.valdi.entities.disguise.ParrotDisguise;
import org.valdi.entities.disguise.PigDisguise;
import org.valdi.entities.disguise.PlayerDisguise;
import org.valdi.entities.disguise.RabbitDisguise;
import org.valdi.entities.disguise.SheepDisguise;
import org.valdi.entities.disguise.SizedDisguise;
import org.valdi.entities.disguise.Subtypes;
import org.valdi.entities.disguise.VillagerDisguise;
import org.valdi.entities.disguise.WolfDisguise;
import org.valdi.entities.disguise.Disguise.Visibility;
import org.valdi.entities.disguise.DisguiseType.Type;
import org.valdi.entities.io.Configuration;
import org.valdi.entities.io.Language;
import org.valdi.entities.io.SLAPI;
import org.valdi.entities.io.UpdateCheck;
import org.valdi.entities.management.DisguiseManager;
import org.valdi.entities.management.ProfileHelper;
import org.valdi.entities.management.Sounds;
import org.valdi.entities.management.VersionHelper;
//import org.valdi.entities.management.channel.ChannelInjector;
import org.valdi.entities.management.hooks.ScoreboardHooks;
import org.valdi.entities.management.util.EntityIdList;
import org.valdi.entities.packets.PacketOptions;
import org.valdi.entities.packets.ProtocolLibPacketsManager;
import org.valdi.st.CustomSkins;
import org.valdi.st.Main;
import org.valdi.st.ParseCommand;
import de.robingrether.util.ObjectUtil;
import de.robingrether.util.RandomUtil;
import de.robingrether.util.StringUtil;
import de.robingrether.util.Validate;
public class iDisguise extends JavaPlugin {
private static iDisguise instance;
private EventListener listener;
private Configuration configuration;
private Language language;
private boolean enabled = false;
public iDisguise() { instance = this; new Main(this); new CustomSkins(this); }
public void onLoad() {
Main.getInstance().onLoad();
}
public void onEnable() {
boolean debugMode = checkDirectory();
if(!VersionHelper.init(debugMode)) {
getLogger().log(Level.SEVERE, String.format("%s is not compatible with your server version!", getFullName()));
getServer().getPluginManager().disablePlugin(this);
return;
}
if(debugMode) {
getLogger().log(Level.INFO, "Debug mode is enabled!");
}
listener = new EventListener(this);
configuration = new Configuration(this);
language = new Language(this);
loadConfigFiles();
if(configuration.KEEP_DISGUISE_SHUTDOWN) {
loadDisguises();
}
getServer().getPluginManager().registerEvents(listener, this);
getServer().getServicesManager().register(DisguiseAPI.class, getAPI(), this, ServicePriority.Normal);
if(configuration.UPDATE_CHECK) {
getServer().getScheduler().runTaskLaterAsynchronously(this, new UpdateCheck(this, getServer().getConsoleSender(), configuration.UPDATE_DOWNLOAD), 20L);
}
Calendar today = Calendar.getInstance();
if(today.get(Calendar.MONTH) == Calendar.NOVEMBER && today.get(Calendar.DAY_OF_MONTH) == 6) {
getLogger().log(Level.INFO, String.format("YAAAY!!! Today is my birthday! I'm %s years old now.", today.get(Calendar.YEAR) - 2012));
}
getLogger().log(Level.INFO, String.format("%s enabled!", getFullName()));
enabled = true;
for(Player player : Bukkit.getOnlinePlayers()) {
// EntityIdList.addPlayer(player);
ProfileHelper.getInstance().registerGameProfile(player);
}
// ChannelInjector.injectOnlinePlayers();
DisguiseManager.resendPackets();
if(getServer().getPluginManager().getPlugin("iDisguiseAdditions") != null) {
int version = Integer.parseInt(getServer().getPluginManager().getPlugin("iDisguiseAdditions").getDescription().getVersion().replace("-SNAPSHOT", "").replace(".", ""));
if(version < 13) {
getLogger().log(Level.SEVERE, "You use an outdated version of iDisguiseAdditions! Please update to the latest version otherwise the plugin won't work properly.");
}
}
if(getServer().getPluginManager().getPlugin("iDisguiseWG") != null) {
int version = Integer.parseInt(getServer().getPluginManager().getPlugin("iDisguiseWG").getDescription().getVersion().replace("-SNAPSHOT", "").replace(".", ""));
if(version < 12) {
getLogger().log(Level.SEVERE, "You use an outdated version of iDisguiseWG! Please update to the latest version otherwise the plugin won't work properly.");
}
}
ParseCommand cmd = new ParseCommand(this);
this.getCommand("parsedisrange").setExecutor(cmd);
this.getCommand("parsedisrange").setTabCompleter(cmd);
Main.getInstance().onEnable();
CustomSkins.getInstance().onEnable();
new ProtocolLibPacketsManager(this);
}
public void onDisable() {
if(!enabled) {
return;
}
getServer().getScheduler().cancelTasks(this);
if(configuration.KEEP_DISGUISE_SHUTDOWN) {
saveDisguises();
}
// ChannelInjector.removeOnlinePlayers();
getLogger().log(Level.INFO, String.format("%s disabled!", getFullName()));
enabled = false;
Main.getInstance().onDisable();
}
public void onReload() {
if(!enabled) {
return;
}
if(configuration.KEEP_DISGUISE_SHUTDOWN) {
saveDisguises();
}
enabled = false;
loadConfigFiles();
if(configuration.KEEP_DISGUISE_SHUTDOWN) {
loadDisguises();
}
enabled = true;
DisguiseManager.resendPackets();
}
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if(StringUtil.equalsIgnoreCase(command.getName(), "disguise", "odisguise")) {
if(args.length == 0) {
sendHelpMessage(sender, command, alias);
} else if(args[0].equalsIgnoreCase("reload")) {
if(sender.hasPermission("iDisguise.reload")) {
onReload();
sender.sendMessage(language.RELOAD_COMPLETE);
} else {
sender.sendMessage(language.NO_PERMISSION);
}
} else {
Object disguisable = null;
boolean disguiseSelf;
if(command.getName().equalsIgnoreCase("disguise")) {
if(sender instanceof Player) {
disguisable = sender;
disguiseSelf = true;
} else {
sender.sendMessage(language.CONSOLE_USE_OTHER_COMMAND);
return true;
}
} else if(args.length > 1) {
if(sender.hasPermission("iDisguise.others")) {
if(args[0].matches("<[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}>")) {
disguisable = getServer().getOfflinePlayer(UUID.fromString(args[0].substring(1, 37)));
} else if(args[0].matches("\\[[0-9]+\\]")) {
disguisable = EntityIdList.getEntityByEntityId(Integer.parseInt(args[0].substring(1, args[0].length() - 1)));
if(disguisable == null) {
sender.sendMessage(language.CANNOT_FIND_ENTITY.replace("%id%", args[0]));
return true;
}
} else if(args[0].matches("\\{[A-Za-z0-9_]{1,16}\\}")) {
disguisable = getServer().getOfflinePlayer(args[0].substring(1, args[0].length() - 1));
} else if(getServer().getPlayerExact(args[0]) != null) {
disguisable = getServer().getPlayerExact(args[0]);
} else if(getServer().matchPlayer(args[0]).size() == 1) {
disguisable = getServer().matchPlayer(args[0]).get(0);
} else {
sender.sendMessage(language.CANNOT_FIND_PLAYER.replace("%player%", args[0]));
return true;
}
disguiseSelf = false;
args = Arrays.copyOfRange(args, 1, args.length);
} else {
sender.sendMessage(language.NO_PERMISSION);
return true;
}
} else {
sendHelpMessage(sender, command, alias);
return true;
}
if(args[0].equalsIgnoreCase("help")) {
sendHelpMessage(sender, command, alias);
} else if(StringUtil.equalsIgnoreCase(args[0], "player", "p")) {
if(args.length < 2) {
sender.sendMessage(language.WRONG_USAGE_NO_NAME);
} else {
String skinName = args.length == 2 ? args[1].replaceAll("&[0-9a-fk-or]", "") : args[1], displayName = args.length == 2 ? ChatColor.translateAlternateColorCodes('&', args[1]) : ChatColor.translateAlternateColorCodes('&', args[2].replace("\\s", " "));
if(!Validate.minecraftUsername(skinName)) {
sender.sendMessage(language.INVALID_NAME);
} else {
PlayerDisguise disguise = new PlayerDisguise(skinName, displayName);
if(hasPermission(sender, disguise)) {
if(disguisable instanceof OfflinePlayer) {
OfflinePlayer player = (OfflinePlayer)disguisable;
if(player.isOnline()) {
DisguiseEvent event = new DisguiseEvent(player.getPlayer(), disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(player, disguise);
sender.sendMessage((disguiseSelf ? language.DISGUISE_PLAYER_SUCCESS_SELF : language.DISGUISE_PLAYER_SUCCESS_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()).replace("%name%", disguise.getDisplayName()));
}
} else {
OfflinePlayerDisguiseEvent event = new OfflinePlayerDisguiseEvent(player, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(player, disguise);
sender.sendMessage((disguiseSelf ? language.DISGUISE_PLAYER_SUCCESS_SELF : language.DISGUISE_PLAYER_SUCCESS_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()).replace("%name%", disguise.getDisplayName()));
}
}
} else {
LivingEntity livingEntity = (LivingEntity)disguisable;
EntityDisguiseEvent event = new EntityDisguiseEvent(livingEntity, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(livingEntity, disguise);
sender.sendMessage(language.DISGUISE_PLAYER_SUCCESS_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]").replace("%type%", disguise.getType().toString()).replace("%name%", disguise.getDisplayName()));
}
}
} else {
sender.sendMessage(language.NO_PERMISSION);
}
}
}
} else if(args[0].equalsIgnoreCase("random")) {
if(sender.hasPermission("iDisguise.random")) {
Disguise disguise = (RandomUtil.nextBoolean() ? DisguiseType.random(Type.MOB) : DisguiseType.random(Type.OBJECT)).newInstance();
if(disguisable instanceof OfflinePlayer) {
OfflinePlayer player = (OfflinePlayer)disguisable;
if(player.isOnline()) {
DisguiseEvent event = new DisguiseEvent(player.getPlayer(), disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(player, disguise);
sender.sendMessage((disguiseSelf ? language.DISGUISE_SUCCESS_SELF : language.DISGUISE_SUCCESS_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()));
}
} else {
OfflinePlayerDisguiseEvent event = new OfflinePlayerDisguiseEvent(player, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(player, disguise);
sender.sendMessage((disguiseSelf ? language.DISGUISE_SUCCESS_SELF : language.DISGUISE_SUCCESS_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()));
}
}
} else {
LivingEntity livingEntity = (LivingEntity)disguisable;
EntityDisguiseEvent event = new EntityDisguiseEvent(livingEntity, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(livingEntity, disguise);
sender.sendMessage(language.DISGUISE_SUCCESS_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]").replace("%type%", disguise.getType().toString()));
}
}
} else {
sender.sendMessage(language.NO_PERMISSION);
}
} else if(StringUtil.equalsIgnoreCase(args[0], "status", "state", "stats")) {
if(disguisable instanceof OfflinePlayer) {
OfflinePlayer player = (OfflinePlayer)disguisable;
if(DisguiseManager.isDisguised(player)) {
if(DisguiseManager.getDisguise(player) instanceof PlayerDisguise) {
PlayerDisguise disguise = (PlayerDisguise)DisguiseManager.getDisguise(player);
sender.sendMessage((disguiseSelf ? language.STATUS_PLAYER_SELF : language.STATUS_PLAYER_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()).replace("%name%", disguise.getDisplayName()));
sender.sendMessage(language.STATUS_SUBTYPES.replace("%subtypes%", disguise.toString()));
} else {
Disguise disguise = DisguiseManager.getDisguise(player);
sender.sendMessage((disguiseSelf ? language.STATUS_SELF : language.STATUS_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()));
sender.sendMessage(language.STATUS_SUBTYPES.replace("%subtypes%", disguise.toString()));
}
} else {
sender.sendMessage((disguiseSelf ? language.STATUS_NOT_DISGUISED_SELF : language.STATUS_NOT_DISGUISED_OTHER).replace("%player%", player.getName()));
}
} else {
LivingEntity livingEntity = (LivingEntity)disguisable;
if(DisguiseManager.isDisguised(livingEntity)) {
if(DisguiseManager.getDisguise(livingEntity) instanceof PlayerDisguise) {
PlayerDisguise disguise = (PlayerDisguise)DisguiseManager.getDisguise(livingEntity);
sender.sendMessage(language.STATUS_PLAYER_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]").replace("%type%", disguise.getType().toString()).replace("%name%", disguise.getDisplayName()));
sender.sendMessage(language.STATUS_SUBTYPES.replace("%subtypes%", disguise.toString()));
} else {
Disguise disguise = DisguiseManager.getDisguise(livingEntity);
sender.sendMessage(language.STATUS_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]").replace("%type%", disguise.getType().toString()));
sender.sendMessage(language.STATUS_SUBTYPES.replace("%subtypes%", disguise.toString()));
}
} else {
sender.sendMessage((disguiseSelf ? language.STATUS_NOT_DISGUISED_SELF : language.STATUS_NOT_DISGUISED_OTHER).replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]"));
}
}
} else if(StringUtil.equalsIgnoreCase(args[0], "seethrough", "see-through")) {
if(sender.hasPermission("iDisguise.see-through")) {
if(disguisable instanceof OfflinePlayer) {
OfflinePlayer player = (OfflinePlayer)disguisable;
if(args.length < 2) {
sender.sendMessage((DisguiseManager.canSeeThrough(player) ? disguiseSelf ? language.SEE_THROUGH_STATUS_ON_SELF : language.SEE_THROUGH_STATUS_ON_OTHER : disguiseSelf ? language.SEE_THROUGH_STATUS_OFF_SELF : language.SEE_THROUGH_STATUS_OFF_OTHER).replace("%player%", player.getName()));
} else if(StringUtil.equalsIgnoreCase(args[1], "on", "off")) {
boolean seeThrough = args[1].equalsIgnoreCase("on");
DisguiseManager.setSeeThrough(player, seeThrough);
sender.sendMessage((seeThrough ? disguiseSelf ? language.SEE_THROUGH_ENABLE_SELF : language.SEE_THROUGH_ENABLE_OTHER : disguiseSelf ? language.SEE_THROUGH_DISABLE_SELF : language.SEE_THROUGH_DISABLE_OTHER).replace("%player%", player.getName()));
} else {
sender.sendMessage(language.WRONG_USAGE_SEE_THROUGH.replace("%argument%", args[1]));
}
} else {
sender.sendMessage(language.SEE_THROUGH_ENTITY);
}
} else {
sender.sendMessage(language.NO_PERMISSION);
}
} else {
Disguise disguise = disguisable instanceof OfflinePlayer ? DisguiseManager.isDisguised((OfflinePlayer)disguisable) ? DisguiseManager.getDisguise((OfflinePlayer)disguisable).clone() : null : DisguiseManager.isDisguised((LivingEntity)disguisable) ? DisguiseManager.getDisguise((LivingEntity)disguisable).clone() : null;
boolean match = false;
List<String> unknown_args = new ArrayList<String>(Arrays.asList(args));
for(Iterator<String> iterator = unknown_args.iterator(); iterator.hasNext(); ) {
DisguiseType type = DisguiseType.fromString(iterator.next());
if(type != null) {
if(match) {
sender.sendMessage(language.WRONG_USAGE_TWO_DISGUISE_TYPES);
return true;
}
try {
disguise = type.newInstance();
match = true;
iterator.remove();
} catch(OutdatedServerException e) {
sender.sendMessage(language.OUTDATED_SERVER);
return true;
// } catch(UnsupportedOperationException e) {
// sendHelpMessage(sender, command, alias);
// return true;
}
}
}
if(disguise != null) {
for(Iterator<String> iterator = unknown_args.iterator(); iterator.hasNext(); ) {
if(Subtypes.applySubtype(disguise, iterator.next())) {
match = true;
iterator.remove();
}
}
}
if(match) {
if(hasPermission(sender, disguise)) {
if(disguisable instanceof OfflinePlayer) {
OfflinePlayer player = (OfflinePlayer)disguisable;
if(player.isOnline()) {
DisguiseEvent event = new DisguiseEvent(player.getPlayer(), disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(player, disguise);
sender.sendMessage((disguiseSelf ? language.DISGUISE_SUCCESS_SELF : language.DISGUISE_SUCCESS_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()));
}
} else {
OfflinePlayerDisguiseEvent event = new OfflinePlayerDisguiseEvent(player, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(player, disguise);
sender.sendMessage((disguiseSelf ? language.DISGUISE_SUCCESS_SELF : language.DISGUISE_SUCCESS_OTHER).replace("%player%", player.getName()).replace("%type%", disguise.getType().toString()));
}
}
} else {
LivingEntity livingEntity = (LivingEntity)disguisable;
EntityDisguiseEvent event = new EntityDisguiseEvent(livingEntity, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.disguise(livingEntity, disguise);
sender.sendMessage(language.DISGUISE_SUCCESS_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]").replace("%type%", disguise.getType().toString()));
}
}
} else {
sender.sendMessage(language.NO_PERMISSION);
}
}
if(!unknown_args.isEmpty()) {
sender.sendMessage(language.WRONG_USAGE_UNKNOWN_ARGUMENTS.replace("%arguments%", StringUtil.join(", ", unknown_args.toArray(new String[0]))));
}
}
}
} else if(command.getName().equalsIgnoreCase("undisguise")) {
if(args.length == 0) {
if(sender instanceof Player) {
if(DisguiseManager.isDisguised((Player)sender)) {
if(!configuration.UNDISGUISE_PERMISSION || sender.hasPermission("iDisguise.undisguise")) {
UndisguiseEvent event = new UndisguiseEvent((Player)sender, DisguiseManager.getDisguise((Player)sender), false);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.undisguise((Player)sender);
sender.sendMessage(language.UNDISGUISE_SUCCESS_SELF);
}
} else {
sender.sendMessage(language.NO_PERMISSION);
}
} else {
sender.sendMessage(language.UNDISGUISE_NOT_DISGUISED_SELF);
}
} else {
sender.sendMessage(language.UNDISGUISE_CONSOLE);
}
} else if(args[0].startsWith("*")) {
args[0] = args[0].toLowerCase(Locale.ENGLISH);
if(sender.hasPermission("iDisguise.undisguise.all")) {
if(args[0].matches("\\*[eop]?")) {
boolean entities, players, offline;
entities = players = offline = true;
if(args[0].length() == 2) {
switch(args[0].charAt(1)) {
case 'e':
players = offline = false;
break;
case 'o':
offline = false;
case 'p':
entities = false;
break;
}
}
if(args.length > 1 && args[1].equalsIgnoreCase("ignore")) {
Set<Object> disguisedEntities = DisguiseManager.getDisguisedEntities();
int[] share = {0, 0, 0}, total = {0, 0, 0};
for(Object disguisable : disguisedEntities) {
if(disguisable instanceof OfflinePlayer) {
if(!players) continue;
OfflinePlayer offlinePlayer = (OfflinePlayer)disguisable;
if(offlinePlayer.isOnline()) {
total[1]++;
DisguiseManager.undisguise(offlinePlayer);
share[1]++;
} else {
if(!offline) continue;
total[2]++;
DisguiseManager.undisguise(offlinePlayer);
share[2]++;
}
} else {
if(!entities) continue;
total[0]++;
LivingEntity livingEntity = (LivingEntity)disguisable;
DisguiseManager.undisguise(livingEntity);
share[0]++;
}
}
if(players)
sender.sendMessage(language.UNDISGUISE_SUCCESS_ALL_ONLINE.replace("%share%", Integer.toString(share[1])).replace("%total%", Integer.toString(total[1])));
if(offline)
sender.sendMessage(language.UNDISGUISE_SUCCESS_ALL_OFFLINE.replace("%share%", Integer.toString(share[2])).replace("%total%", Integer.toString(total[2])));
if(entities)
sender.sendMessage(language.UNDISGUISE_SUCCESS_ALL_ENTITIES.replace("%share%", Integer.toString(share[0])).replace("%total%", Integer.toString(total[0])));
} else {
Set<Object> disguisedEntities = DisguiseManager.getDisguisedEntities();
int[] share = {0, 0, 0}, total = {0, 0, 0};
for(Object disguisable : disguisedEntities) {
if(disguisable instanceof OfflinePlayer) {
if(!players) continue;
OfflinePlayer offlinePlayer = (OfflinePlayer)disguisable;
if(offlinePlayer.isOnline()) {
total[1]++;
UndisguiseEvent event = new UndisguiseEvent(offlinePlayer.getPlayer(), DisguiseManager.getDisguise(offlinePlayer), true);
getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()) {
DisguiseManager.undisguise(offlinePlayer);
share[1]++;
}
} else {
if(!offline) continue;
total[2]++;
OfflinePlayerUndisguiseEvent event = new OfflinePlayerUndisguiseEvent(offlinePlayer, DisguiseManager.getDisguise(offlinePlayer), true);
getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()) {
DisguiseManager.undisguise(offlinePlayer);
share[2]++;
}
}
} else {
if(!entities) continue;
total[0]++;
LivingEntity livingEntity = (LivingEntity)disguisable;
EntityUndisguiseEvent event = new EntityUndisguiseEvent(livingEntity, DisguiseManager.getDisguise(livingEntity), true);
getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()) {
DisguiseManager.undisguise(livingEntity);
share[0]++;
}
}
}
if(players)
sender.sendMessage(language.UNDISGUISE_SUCCESS_ALL_ONLINE.replace("%share%", Integer.toString(share[1])).replace("%total%", Integer.toString(total[1])));
if(offline)
sender.sendMessage(language.UNDISGUISE_SUCCESS_ALL_OFFLINE.replace("%share%", Integer.toString(share[2])).replace("%total%", Integer.toString(total[2])));
if(entities)
sender.sendMessage(language.UNDISGUISE_SUCCESS_ALL_ENTITIES.replace("%share%", Integer.toString(share[0])).replace("%total%", Integer.toString(total[0])));
}
} else {
sender.sendMessage(language.WRONG_USAGE_UNKNOWN_ARGUMENTS.replace("%arguments%", args[0]));
}
} else {
sender.sendMessage(language.NO_PERMISSION);
}
} else {
if(sender.hasPermission("iDisguise.undisguise.others")) {
Object disguisable = null;
if(args[0].matches("<[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}>")) {
disguisable = getServer().getOfflinePlayer(UUID.fromString(args[0].substring(1, 37)));
} else if(args[0].matches("\\[[0-9]+\\]")) {
disguisable = EntityIdList.getEntityByEntityId(Integer.parseInt(args[0].substring(1, args[0].length() - 1)));
if(disguisable == null) {
sender.sendMessage(language.CANNOT_FIND_ENTITY.replace("%id%", args[0]));
return true;
}
} else if(args[0].matches("\\{[A-Za-z0-9_]{1,16}\\}")) {
disguisable = getServer().getOfflinePlayer(args[0].substring(1, args[0].length() - 1));
} else if(getServer().getPlayerExact(args[0]) != null) {
disguisable = getServer().getPlayerExact(args[0]);
} else if(getServer().matchPlayer(args[0]).size() == 1) {
disguisable = getServer().matchPlayer(args[0]).get(0);
} else {
sender.sendMessage(language.CANNOT_FIND_PLAYER.replace("%player%", args[0]));
return true;
}
if(disguisable instanceof OfflinePlayer) {
OfflinePlayer player = (OfflinePlayer)disguisable;
if(DisguiseManager.isDisguised(player)) {
if(args.length > 1 && args[1].equalsIgnoreCase("ignore")) {
DisguiseManager.undisguise(player);
sender.sendMessage(language.UNDISGUISE_SUCCESS_OTHER.replace("%player%", player.getName()));
} else {
if(player.isOnline()) {
UndisguiseEvent event = new UndisguiseEvent(player.getPlayer(), DisguiseManager.getDisguise(player), false);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.undisguise(player);
sender.sendMessage(language.UNDISGUISE_SUCCESS_OTHER.replace("%player%", player.getName()));
}
} else {
OfflinePlayerUndisguiseEvent event = new OfflinePlayerUndisguiseEvent(player, DisguiseManager.getDisguise(player), false);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.undisguise(player);
sender.sendMessage(language.UNDISGUISE_SUCCESS_OTHER.replace("%player%", player.getName()));
}
}
}
} else {
sender.sendMessage(language.UNDISGUISE_NOT_DISGUISED_OTHER.replace("%player%", player.getName()));
}
} else {
LivingEntity livingEntity = (LivingEntity)disguisable;
if(DisguiseManager.isDisguised(livingEntity)) {
if(args.length > 1 && args[1].equalsIgnoreCase("ignore")) {
DisguiseManager.undisguise(livingEntity);
sender.sendMessage(language.UNDISGUISE_SUCCESS_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]"));
} else {
EntityUndisguiseEvent event = new EntityUndisguiseEvent(livingEntity, DisguiseManager.getDisguise(livingEntity), false);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
sender.sendMessage(language.EVENT_CANCELLED);
} else {
DisguiseManager.undisguise(livingEntity);
sender.sendMessage(language.UNDISGUISE_SUCCESS_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]"));
}
}
} else {
sender.sendMessage(language.UNDISGUISE_NOT_DISGUISED_OTHER.replace("%player%", livingEntity.getType().name() + " [" + livingEntity.getEntityId() + "]"));
}
}
} else {
sender.sendMessage(language.NO_PERMISSION);
}
}
}
return true;
}
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
List<String> completions = new ArrayList<String>();
if(command.getName().equalsIgnoreCase("disguise")) {
if(sender instanceof Player) {
Player player = (Player)sender;
if(args.length < 2) {
completions.addAll(Arrays.asList("help", "player", "status"));
if(sender.hasPermission("iDisguise.random")) {
completions.add("random");
}
if(sender.hasPermission("iDisguise.reload")) {
completions.add("reload");
}
if(sender.hasPermission("iDisguise.see-through")) {
completions.add("see-through");
}
for(DisguiseType type : DisguiseType.values()) {
if(type.isAvailable() && !type.isPlayer()) {
completions.add(type.getCustomCommandArgument());
}
}
}
Disguise disguise = DisguiseManager.isDisguised(player) ? DisguiseManager.getDisguise(player).clone() : null;
for(String argument : args) {
DisguiseType type = DisguiseType.fromString(argument);
if(type != null) {
try {
disguise = type.newInstance();
break;
} catch(OutdatedServerException e) {
} catch(UnsupportedOperationException e) {
}
}
}
if(disguise != null) {
completions.addAll(Subtypes.listSubtypeArguments(disguise, args.length > 0 ? args[args.length - 1].contains("=") : false));
}
} else {
completions.add("reload");
}
} else if(command.getName().equalsIgnoreCase("odisguise")) {
if(args.length < 2) {
if(sender.hasPermission("iDisguise.reload")) {
completions.add("reload");
}
if(sender.hasPermission("iDisguise.others")) {
for(Player player : Bukkit.getOnlinePlayers()) {
completions.add("{" + player.getName() + "}");
}
if(sender instanceof Player) {
for(Entity entity : ((Player)sender).getNearbyEntities(5.0, 5.0, 5.0)) {
if(entity instanceof LivingEntity) {
completions.add("[" + entity.getEntityId() + "]");
}
}
}
}
} else if(sender.hasPermission("iDisguise.others")) {
Object disguisable = null;
if(args[0].matches("<[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}>")) {
disguisable = getServer().getOfflinePlayer(UUID.fromString(args[0].substring(1, 37)));
} else if(args[0].matches("\\[[0-9]+\\]")) {
disguisable = EntityIdList.getEntityByEntityId(Integer.parseInt(args[0].substring(1, args[0].length() - 1)));
} else if(args[0].matches("\\{[A-Za-z0-9_]{1,16}\\}")) {
disguisable = getServer().getOfflinePlayer(args[0].substring(1, args[0].length() - 1));
} else if(getServer().getPlayerExact(args[0]) != null) {
disguisable = getServer().getPlayerExact(args[0]);
} else if(getServer().matchPlayer(args[0]).size() == 1) {
disguisable = getServer().matchPlayer(args[0]).get(0);
}
if(disguisable != null) {
if(args.length < 3) {
completions.addAll(Arrays.asList("help", "player", "status"));
if(sender.hasPermission("iDisguise.random")) {
completions.add("random");
}
if(sender.hasPermission("iDisguise.see-through") && disguisable instanceof OfflinePlayer) {
completions.add("see-through");
}
for(DisguiseType type : DisguiseType.values()) {
if(!type.isPlayer() && type.isAvailable() && hasPermission(sender, type.newInstance())) {
completions.add(type.getCustomCommandArgument());
}
}
}
Disguise disguise = disguisable instanceof OfflinePlayer ? DisguiseManager.isDisguised((OfflinePlayer)disguisable) ? DisguiseManager.getDisguise((OfflinePlayer)disguisable).clone() : null : DisguiseManager.isDisguised((LivingEntity)disguisable) ? DisguiseManager.getDisguise((LivingEntity)disguisable).clone() : null;
for(String argument : args) {
DisguiseType type = DisguiseType.fromString(argument);
if(type != null) {
try {
disguise = type.newInstance();
break;
} catch(OutdatedServerException e) {
} catch(UnsupportedOperationException e) {
}
}
}
if(disguise != null) {
completions.addAll(Subtypes.listSubtypeArguments(disguise, args.length > 0 ? args[args.length - 1].contains("=") : false));
}
}
}
} else if(command.getName().equalsIgnoreCase("undisguise")) {
if(args.length < 2) {
if(sender.hasPermission("iDisguise.undisguise.all")) {
completions.addAll(Arrays.asList("*", "*e", "*o", "*p"));
}
if(sender.hasPermission("iDisguise.undisguise.others")) {
for(Player player : Bukkit.getOnlinePlayers()) {
if(DisguiseManager.isDisguised(player)) {
completions.add("{" + player.getName() + "}");
}
}
if(sender instanceof Player) {
for(Entity entity : ((Player)sender).getNearbyEntities(5.0, 5.0, 5.0)) {
if(entity instanceof LivingEntity && DisguiseManager.isDisguised((LivingEntity)entity)) {
completions.add("[" + entity.getEntityId() + "]");
}
}
}
}
} else {
completions.add("ignore");
}
}
if(args.length > 0) {
for(int i = 0; i < completions.size(); i++) {
if(!StringUtil.startsWithIgnoreCase(completions.get(i).replace("{", ""), args[args.length - 1])) {
completions.remove(i);
i--;
}
}
}
return completions;
}
private void sendHelpMessage(CommandSender sender, Command command, String alias) {
if(!sender.hasPermission("iDisguise.help")) {
sender.sendMessage(language.NO_PERMISSION);
return;
}
alias = alias.toLowerCase(Locale.ENGLISH);
boolean self = command.getName().equalsIgnoreCase("disguise");
String disguiseCommand = "/" + (self ? alias : alias + " <target>");
String undisguiseCommand = "/" + alias.replaceAll("o?disguise$", "undisguise").replaceAll("o?dis$", "undis").replaceAll("o?d$", "ud");
sender.sendMessage(language.HELP_INFO.replace("%name%", "iDisguise").replace("%version%", getVersion()));
Calendar today = Calendar.getInstance();
if(today.get(Calendar.MONTH) == Calendar.NOVEMBER && today.get(Calendar.DAY_OF_MONTH) == 6) {
sender.sendMessage(language.EASTER_EGG_BIRTHDAY.replace("%age%", Integer.toString(today.get(Calendar.YEAR) - 2012)));
}
sender.sendMessage(language.HELP_BASE.replace("%command%", disguiseCommand + " help").replace("%description%", language.HELP_HELP));
if(sender.hasPermission("iDisguise.player.display-name")) {
sender.sendMessage(language.HELP_BASE.replace("%command%", disguiseCommand + " player [skin] <name>").replace("%description%", self ? language.HELP_PLAYER_SELF : language.HELP_PLAYER_OTHER));
} else {
sender.sendMessage(language.HELP_BASE.replace("%command%", disguiseCommand + " player <name>").replace("%description%", self ? language.HELP_PLAYER_SELF : language.HELP_PLAYER_OTHER));
}
if(sender.hasPermission("iDisguise.random")) {
sender.sendMessage(language.HELP_BASE.replace("%command%", disguiseCommand + " random").replace("%description%", self ? language.HELP_RANDOM_SELF : language.HELP_RANDOM_OTHER));
}
if(sender.hasPermission("iDisguise.reload")) {
sender.sendMessage(language.HELP_BASE.replace("%command%", "/" + alias + " reload").replace("%description%", language.HELP_RELOAD));
}
if(sender.hasPermission("iDisguise.see-through")) {
sender.sendMessage(language.HELP_BASE.replace("%command%", "/" + alias + " see-through [on/off]").replace("%description%", self ? language.HELP_SEE_THROUGH_SELF : language.HELP_SEE_THROUGH_OTHER));
}
sender.sendMessage(language.HELP_BASE.replace("%command%", disguiseCommand + " status").replace("%description%", self ? language.HELP_STATUS_SELF : language.HELP_STATUS_OTHER));
if(self) {
sender.sendMessage(language.HELP_BASE.replace("%command%", undisguiseCommand).replace("%description%", language.HELP_UNDISGUISE_SELF));
}
if(sender.hasPermission("iDisguise.undisguise.all")) {
sender.sendMessage(language.HELP_BASE.replace("%command%", undisguiseCommand + " <*/*o/*p/*e> [ignore]").replace("%description%", language.HELP_UNDISGUISE_ALL_NEW));
}
if(sender.hasPermission("iDisguise.undisguise.others")) {
sender.sendMessage(language.HELP_BASE.replace("%command%", undisguiseCommand + " <target> [ignore]").replace("%description%", language.HELP_UNDISGUISE_OTHER));
}
sender.sendMessage(language.HELP_BASE.replace("%command%", disguiseCommand + " [subtype] <type> [subtype]").replace("%description%", self ? language.HELP_DISGUISE_SELF : language.HELP_DISGUISE_OTHER));
sender.sendMessage(language.HELP_BASE.replace("%command%", disguiseCommand + " <subtype>").replace("%description%", language.HELP_SUBTYPE));
if(!self) {
for(String message : new String[] {language.HELP_TARGET_TITLE, language.HELP_TARGET_UID, language.HELP_TARGET_EID, language.HELP_TARGET_NAME_EXACT, language.HELP_TARGET_NAME_MATCH}) {
sender.sendMessage(message);
}
}
StringBuilder builder = new StringBuilder();
String color = ChatColor.getLastColors(language.HELP_TYPES);
for(DisguiseType type : DisguiseType.values()) {
if(!type.isPlayer()) {
String format = !type.isAvailable() ? language.HELP_TYPES_NOT_SUPPORTED : hasPermission(sender, type) ? language.HELP_TYPES_AVAILABLE : language.HELP_TYPES_NO_PERMISSION;
if(format.contains("%type%")) {
builder.append(format.replace("%type%", type.getCustomCommandArgument()));
builder.append(color + ", ");
}
}
}
if(builder.length() > 2) {
sender.sendMessage(language.HELP_TYPES.replace("%types%", builder.substring(0, builder.length() - 2)));
}
}
private boolean hasPermission(CommandSender sender, DisguiseType type) {
if(type.isMob()) return sender.hasPermission("iDisguise.mob." + type.name().toLowerCase(Locale.ENGLISH));
if(type.isObject()) return sender.hasPermission("iDisguise.object." + type.name().toLowerCase(Locale.ENGLISH));
return false;
}
private boolean hasPermission(CommandSender sender, Disguise disguise) {
if(ObjectUtil.equals(disguise.getVisibility(), Visibility.ONLY_LIST, Visibility.NOT_LIST) && !sender.hasPermission("iDisguise.visibility.list")) return false;
if(ObjectUtil.equals(disguise.getVisibility(), Visibility.ONLY_PERMISSION, Visibility.NOT_PERMISSION) && !sender.hasPermission("iDisguise.visibility.permission")) return false;
if(disguise instanceof PlayerDisguise) {
PlayerDisguise playerDisguise = (PlayerDisguise)disguise;
return (sender.hasPermission("iDisguise.player.name.*") || sender.hasPermission("iDisguise.player.name." + playerDisguise.getSkinName())) && (isPlayerDisguisePermitted(playerDisguise.getSkinName()) || sender.hasPermission("iDisguise.player.prohibited")) && (playerDisguise.getSkinName().equalsIgnoreCase(playerDisguise.getDisplayName()) || sender.hasPermission("iDisguise.player.display-name"));
} else if(hasPermission(sender, disguise.getType())) {
if(disguise instanceof MobDisguise) {
MobDisguise mobDisguise = (MobDisguise)disguise;
if(mobDisguise.getCustomName() != null && !mobDisguise.getCustomName().isEmpty() && !sender.hasPermission("iDisguise.mob.custom-name")) return false;
if(disguise instanceof AgeableDisguise) {
if(((AgeableDisguise)disguise).isAdult() || sender.hasPermission("iDisguise.mob.baby")) {
switch(disguise.getType()) {
case OCELOT:
return sender.hasPermission("iDisguise.mob.ocelot.type." + ((OcelotDisguise)disguise).getCatType().name().toLowerCase(Locale.ENGLISH).replaceAll("_.*", ""));
case PIG:
return !((PigDisguise)disguise).isSaddled() || sender.hasPermission("iDisguise.mob.pig.saddled");
case RABBIT:
return sender.hasPermission("iDisguise.mob.rabbit.type." + ((RabbitDisguise)disguise).getRabbitType().name().toLowerCase(Locale.ENGLISH).replace("_and_", "-").replace("the_killer_bunny", "killer"));
case SHEEP:
return sender.hasPermission("iDisguise.mob.sheep.color." + ((SheepDisguise)disguise).getColor().name().toLowerCase(Locale.ENGLISH).replace('_', '-'));
case VILLAGER:
return sender.hasPermission("iDisguise.mob.villager.profession." + ((VillagerDisguise)disguise).getProfession().name().toLowerCase(Locale.ENGLISH));
case WOLF:
return sender.hasPermission("iDisguise.mob.wolf.collar." + ((WolfDisguise)disguise).getCollarColor().name().toLowerCase(Locale.ENGLISH).replace('_', '-')) && (!((WolfDisguise)disguise).isTamed() || sender.hasPermission("iDisguise.mob.wolf.tamed")) && (!((WolfDisguise)disguise).isAngry() || sender.hasPermission("iDisguise.mob.wolf.angry"));
default:
return true;
}
}
} else {
switch(disguise.getType()) {
case CREEPER:
return (!((CreeperDisguise)disguise).isPowered() || sender.hasPermission("iDisguise.mob.creeper.powered"));
case ENDERMAN:
return (((EndermanDisguise)disguise).getBlockInHand().equals(Material.AIR) || sender.hasPermission("iDisguise.mob.enderman.block"));
case MAGMA_CUBE:
return (((SizedDisguise)disguise).getSize() < 5 || sender.hasPermission("iDisguise.mob.magma_cube.giant"));
case PARROT:
return sender.hasPermission("iDisguise.mob.parrot.variant." + ((ParrotDisguise)disguise).getVariant().name().toLowerCase(Locale.ENGLISH));
case SLIME:
return (((SizedDisguise)disguise).getSize() < 5 || sender.hasPermission("iDisguise.mob.slime.giant"));
default:
return true;
}
}
} else if(disguise instanceof ObjectDisguise) {
ObjectDisguise objectDisguise = (ObjectDisguise)disguise;
if(objectDisguise.getCustomName() != null && !objectDisguise.getCustomName().isEmpty() && !sender.hasPermission("iDisguise.object.custom-name")) return false;
switch(disguise.getType()) {
case FALLING_BLOCK:
return sender.hasPermission("iDisguise.object.falling_block.material." + ((FallingBlockDisguise)disguise).getMaterial().name().toLowerCase(Locale.ENGLISH).replace('_', '-'));
case ITEM:
return sender.hasPermission("iDisguise.object.item.material." + ((ItemDisguise)disguise).getMaterial().name().toLowerCase(Locale.ENGLISH).replace('_', '-'));
default:
return true;
}
}
}
return false;
}
/**
* Checks if the plugin directory (= data folder) exists and creates such a directory if not.
*
* @return <code>true</code> if a file named 'debug' exists in that directory (which means that debug mode shall be enabled), <code>false</code> otherwise
*/
private boolean checkDirectory() {
if(!getDataFolder().exists()) {
getDataFolder().mkdirs();
}
return new File(getDataFolder(), "debug").isFile();
}
private void loadConfigFiles() {
// reload config
configuration.loadData();
configuration.saveData();
// reload language file
language.loadData();
language.saveData();
// reset config values
/*PacketHandler.showOriginalPlayerName = configuration.NAME_TAG_SHOWN;
PacketHandler.modifyPlayerListEntry = configuration.MODIFY_PLAYER_LIST_ENTRY;
PacketHandler.modifyScoreboardPackets = configuration.MODIFY_SCOREBOARD_PACKETS;
PacketHandler.replaceSoundEffects = configuration.REPLACE_SOUND_EFFECTS;
PacketHandler.bungeeCord = configuration.BUNGEE_CORD;*/
PacketOptions.showOriginalPlayerName = configuration.NAME_TAG_SHOWN;
PacketOptions.modifyPlayerListEntry = configuration.MODIFY_PLAYER_LIST_ENTRY;
PacketOptions.modifyScoreboardPackets = configuration.MODIFY_SCOREBOARD_PACKETS;
PacketOptions.replaceSoundEffects = configuration.REPLACE_SOUND_EFFECTS;
PacketOptions.bungeeCord = configuration.BUNGEE_CORD;
// setup hooks
if(configuration.MODIFY_SCOREBOARD_PACKETS) {
ScoreboardHooks.setup();
}
// load disguise aliases
try {
for(DisguiseType type : DisguiseType.values()) {
if(!type.isPlayer()) {
String value = (String)Language.class.getDeclaredField("DISGUISE_ALIAS_" + type.name()).get(language);
if(StringUtil.isNotBlank(value)) {
String[] aliases = value.split("\\s*,\\s*");
for(String alias : aliases) {
if(StringUtil.isNotBlank(alias) && alias.matches("!?[A-Za-z0-9-_]+")) {
if(alias.startsWith("!"))
type.setCustomCommandArgument(alias.substring(1));
else
type.addCustomCommandArgument(alias);
}
}
}
}
}
} catch(Exception e) { // fail silently
}
}
private void loadDisguises() {
File dataFile = new File(getDataFolder(), "disguises.dat");
if(dataFile.exists()) {
DisguiseManager.updateDisguises(SLAPI.loadMap(dataFile));
}
}
private void saveDisguises() {
File dataFile = new File(getDataFolder(), "disguises.dat");
SLAPI.saveMap(DisguiseManager.getDisguises(), dataFile);
}
public DisguiseAPI getAPI() {
return new DisguiseAPI() {
public boolean disguise(OfflinePlayer offlinePlayer, Disguise disguise) {
return disguise(offlinePlayer, disguise, true);
}
public boolean disguise(Player player, Disguise disguise) {
return disguise(player, disguise, true);
}
public boolean disguise(LivingEntity livingEntity, Disguise disguise) {
return disguise(livingEntity, disguise, true);
}
public boolean disguise(OfflinePlayer offlinePlayer, Disguise disguise, boolean fireEvent) {
if(offlinePlayer.isOnline()) {
return disguise(offlinePlayer.getPlayer(), disguise, fireEvent);
}
if(fireEvent) {
OfflinePlayerDisguiseEvent event = new OfflinePlayerDisguiseEvent(offlinePlayer, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
return false;
} else {
DisguiseManager.disguise(offlinePlayer, disguise);
return true;
}
} else {
DisguiseManager.disguise(offlinePlayer, disguise);
return true;
}
}
public boolean disguise(Player player, Disguise disguise, boolean fireEvent) {
if(fireEvent) {
DisguiseEvent event = new DisguiseEvent(player, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
return false;
} else {
DisguiseManager.disguise(player, disguise);
return true;
}
} else {
DisguiseManager.disguise(player, disguise);
return true;
}
}
public boolean disguise(LivingEntity livingEntity, Disguise disguise, boolean fireEvent) {
if(livingEntity instanceof Player) {
return disguise((Player)livingEntity, disguise, fireEvent);
}
if(fireEvent) {
EntityDisguiseEvent event = new EntityDisguiseEvent(livingEntity, disguise);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
return false;
} else {
DisguiseManager.disguise(livingEntity, disguise);
return true;
}
} else {
DisguiseManager.disguise(livingEntity, disguise);
return true;
}
}
public boolean undisguise(OfflinePlayer offlinePlayer) {
return undisguise(offlinePlayer, true);
}
public boolean undisguise(Player player) {
return undisguise(player, true);
}
public boolean undisguise(LivingEntity livingEntity) {
return undisguise(livingEntity, true);
}
public boolean undisguise(OfflinePlayer offlinePlayer, boolean fireEvent) {
if(offlinePlayer.isOnline()) {
return undisguise(offlinePlayer.getPlayer(), fireEvent);
}
if(!isDisguised(offlinePlayer)) return false;
if(fireEvent) {
OfflinePlayerUndisguiseEvent event = new OfflinePlayerUndisguiseEvent(offlinePlayer, getDisguise(offlinePlayer), false);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
return false;
} else {
DisguiseManager.undisguise(offlinePlayer);
return true;
}
} else {
DisguiseManager.undisguise(offlinePlayer);
return true;
}
}
public boolean undisguise(Player player, boolean fireEvent) {
if(!isDisguised(player)) return false;
if(fireEvent) {
UndisguiseEvent event = new UndisguiseEvent(player, getDisguise(player), false);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
return false;
} else {
DisguiseManager.undisguise(player);
return true;
}
} else {
DisguiseManager.undisguise(player);
return true;
}
}
public boolean undisguise(LivingEntity livingEntity, boolean fireEvent) {
if(livingEntity instanceof Player) {
return undisguise((Player)livingEntity, fireEvent);
}
if(!isDisguised(livingEntity)) return false;
if(fireEvent) {
EntityUndisguiseEvent event = new EntityUndisguiseEvent(livingEntity, getDisguise(livingEntity), false);
getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
return false;
} else {
DisguiseManager.undisguise(livingEntity);
return true;
}
} else {
DisguiseManager.undisguise(livingEntity);
return true;
}
}
public void undisguiseAll() {
DisguiseManager.undisguiseAll();
}
public boolean isDisguised(OfflinePlayer offlinePlayer) {
return DisguiseManager.isDisguised(offlinePlayer);
}
public boolean isDisguised(Player player) {
return DisguiseManager.isDisguised(player);
}
public boolean isDisguised(LivingEntity livingEntity) {
return DisguiseManager.isDisguised(livingEntity);
}
public boolean isDisguisedTo(OfflinePlayer offlinePlayer, Player observer) {
return DisguiseManager.isDisguisedTo(offlinePlayer, observer);
}
public boolean isDisguisedTo(Player player, Player observer) {
return DisguiseManager.isDisguisedTo(player, observer);
}
public boolean isDisguisedTo(LivingEntity livingEntity, Player observer) {
return DisguiseManager.isDisguisedTo(livingEntity, observer);
}
public Disguise getDisguise(OfflinePlayer offlinePlayer) {
return DisguiseManager.isDisguised(offlinePlayer) ? DisguiseManager.getDisguise(offlinePlayer).clone() : null;
}
public Disguise getDisguise(Player player) {
return DisguiseManager.isDisguised(player) ? DisguiseManager.getDisguise(player).clone() : null;
}
public Disguise getDisguise(LivingEntity livingEntity) {
return DisguiseManager.isDisguised(livingEntity) ? DisguiseManager.getDisguise(livingEntity).clone() : null;
}
public int getNumberOfDisguisedPlayers() {
return DisguiseManager.getNumberOfDisguisedPlayers();
}
public Sounds getSoundsForEntity(DisguiseType type) {
return Sounds.getSoundsForEntity(type);
}
public boolean setSoundsForEntity(DisguiseType type, Sounds sounds) {
return Sounds.setSoundsForEntity(type, sounds);
}
public boolean isSoundsEnabled() {
return PacketOptions.replaceSoundEffects;
}
public void setSoundsEnabled(boolean enabled) {
PacketOptions.replaceSoundEffects = enabled;
}
public boolean hasPermission(Player player, DisguiseType type) {
return iDisguise.this.hasPermission(player, type);
}
public boolean hasPermission(Player player, Disguise disguise) {
return iDisguise.this.hasPermission(player, disguise);
}
public boolean canSeeThrough(OfflinePlayer player) {
return DisguiseManager.canSeeThrough(player);
}
public void setSeeThrough(OfflinePlayer player, boolean seeThrough) {
DisguiseManager.setSeeThrough(player, seeThrough);
}
public Set<Object> getDisguisedEntities() {
return DisguiseManager.getDisguisedEntities();
}
};
}
public String getVersion() {
return getDescription().getVersion();
}
public String getFullName() {
return "iDisguise " + getVersion();
}
public File getPluginFile() {
return getFile();
}
public Configuration getConfiguration() {
return configuration;
}
public Language getLanguage() {
return language;
}
public boolean isPlayerDisguisePermitted(String name) {
return !getConfiguration().RESTRICTED_PLAYER_NAMES.contains(name);
}
public boolean enabled() {
return enabled;
}
public static iDisguise getInstance() {
return instance;
}
} |
package com.emc.netty.server;
import com.alibaba.fastjson.JSON;
import com.emc.netty.client.CommType;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author NieYinjun
* @date 2018/11/29 13:54
* @tag
*/
@Component
@Slf4j
public class ChannelManagement {
private static ConcurrentHashMap<String,TopicsToChannel> map = new ConcurrentHashMap<>();
/**
* 检查连接通道是否已经注册
* @param ctx 通道对象
* @return 是否注册
*/
public boolean checkCtx(ChannelHandlerContext ctx) {
for (String key : map.keySet()) {
if(map.get(key).getCtx().equals(ctx)) {
return true;
}
}
return false;
}
/**
* 发送消息到客户端
* @param clientId 客户端唯一标识ID
* @param topic 主题(产品ID)
* @param msg 消息集合
* @return 处理结果
*/
public String sendMessage(String clientId,String topic,Object msg){
TopicsToChannel topicsToChannel=map.get(clientId);
if(topicsToChannel==null){
//没有连接
return "400";
}else if(!topicsToChannel.getTopics().contains(topic)){
//没有订阅
return "300";
}else {
try{
topicsToChannel.getCtx().writeAndFlush(JSON.toJSONString(new CommDTO().setType(CommType.C).setData(msg))+"$$");
return "200";
}catch (Exception e){
return "500";
}
}
}
/**
* 添加通道
* @param clientId 客户端唯一标识ID,如果已经存在该用户通道,则关闭第一个
* @param topics 订阅主题(订阅产品ID下的设备发送的消息),可以有多个
* @param ctx 通道对象
*/
public void addCtx(String clientId,Set<String> topics,ChannelHandlerContext ctx){
if(map.containsKey(clientId)&& !map.get(clientId).getCtx().equals(ctx)){
map.remove(clientId).getCtx().close();
}
map.put(clientId,new TopicsToChannel().setCtx(ctx).setTopics(topics));
}
/**
* @param ctx 通道对象
*/
public void removeCtx(ChannelHandlerContext ctx) {
for (String key : map.keySet()) {
if(map.get(key).getCtx().equals(ctx)) {
map.remove(key);
ctx.close();
log.info("【{}】已经断开连接!", key);
break;
}
}
}
@Data
@Accessors(chain = true)
private class TopicsToChannel{
private Set<String> topics;
private ChannelHandlerContext ctx;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.