text
stringlengths 10
2.72M
|
|---|
package spring.security.userdetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import spring.security.domain.Account;
import spring.security.repository.AccountRepository;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private AccountRepository accountRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Account account = accountRepository.findByUsername(username);
if (account == null) {
throw new UsernameNotFoundException(username);
}
return new UserDetailsImpl(account);
}
}
|
package com.show.ppx.cloud.impl;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.show.comm.utils.IPUtils;
import com.show.comm.utils.StringUtils;
import com.show.ppx.cloud.Scheduler;
/**
* 云调度处理
*
* @author heyuhua
* @date 2018年3月22日
*/
@Service
@EnableScheduling
public class SchedulerImpl implements Scheduler {
/** 日志 */
private static final Logger LOG = LoggerFactory.getLogger(SchedulerImpl.class);
/** Redis 调度服务hash key */
private static final byte[] REDIS_SCHEDULE_SERV = "cloud:schedule:serv".getBytes();
/** Redis 调度任务hash key */
private static final byte[] REDIS_SCHEDULE_TASK = "cloud:schedule:task".getBytes();
/** 服务器失效移除延时(2分钟) */
private static final long RMV_DELAY = 1000 * 60 * 2;
/** 服务器时间异常误差(20秒) */
private static final long RMV_ERROR = -1000 * 20;
/** 服务器心跳延时 */
private static final long ACT_DELAY = 1000 * 30;
/** 本服务器(IP地址+应用) */
private String server;
/** 本服务器(IP地址+应用) */
private byte[] serverBs;
@Value("${spring.application.name}")
private String app;
@Autowired
private RedisTemplate<byte[], byte[]> redis;
/** Redis hash 操作 */
private HashOperations<byte[], byte[], byte[]> hash;
@PostConstruct
public void start() {
server = IPUtils.localIp() + ":" + app;
serverBs = server.getBytes();
hash = redis.opsForHash();
active();
}
/** 激活当前服务器 */
@Scheduled(fixedDelay = ACT_DELAY, initialDelay = ACT_DELAY)
public void active() {
hash.put(REDIS_SCHEDULE_SERV, serverBs, String.valueOf(System.currentTimeMillis()).getBytes());
LOG.info("Cloud schedule active “" + server + "”.");
}
@PreDestroy
public void destroy() {
hash.delete(REDIS_SCHEDULE_SERV, serverBs);
LOG.info("Cloud schedule remove “" + server + "”.");
}
@Override
public boolean run(String taskName) {
return runAtCurrentServer(app + "." + taskName);
}
private boolean runAtCurrentServer(String task) {
byte[] srv = hash.get(REDIS_SCHEDULE_TASK, task.getBytes());
if (null == srv) {
hash.put(REDIS_SCHEDULE_TASK, task.getBytes(), serverBs);// 设置为当前服务器调度
LOG.info("Cloud schedule task “" + task + "”. (put to “" + server + "”)");
return true;
}
String srvs = new String(srv);
if (server.equals(srvs)) {
LOG.info("Cloud schedule task “" + task + "”. (current “" + server + "”)");
return true;// 当前服务器
}
long amt = 0L;
byte[] ams = hash.get(REDIS_SCHEDULE_SERV, srv);// 服务器活动时间
if (null != ams) {
amt = StringUtils.toLong(new String(ams), 0L);
}
long set = System.currentTimeMillis() - amt;
if (set > RMV_DELAY || set < RMV_ERROR) {
hash.delete(REDIS_SCHEDULE_SERV, srv);// 移除失效服务器
hash.put(REDIS_SCHEDULE_TASK, task.getBytes(), serverBs);// 设置为当前服务器调度
LOG.info("Cloud schedule task “" + task + "”. (rmv from “" + srvs + "” and put to “" + server + "”)");
return true;
}
return false;
}
}
|
import java.util.*;
public class Test {
public static void main(String[] args)
{
String str = readFromUser();
System.out.println(shortestSubstring(str));
}
public static String readFromUser()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string => ");
String str = scanner.nextLine();
return str;
}
public static char[] elementsOfString(String letter)
{
ArrayList<Character> list = new ArrayList<Character>();
for(int i = 0 ; i < letter.length();i++)
{
list.add(letter.charAt(i));
}
int a=0;
while(a < list.size())
{
char temp = list.get(a);
for(int b = a+1; b < list.size();b++)
{
if(temp == list.get(b))
{
list.remove(b);
b--;
}
else
{
continue;
}
}
a++;
}
char array[] = new char[list.size()];
for(int k = 0 ; k < array.length ; k++)
{
array[k] = list.get(k);
}
return array;
}
public static int shortestSubstring(String str)
{
char arr[] = elementsOfString(str);
int start = 0;
int uniqueCounter = 0;
int patLen = arr.length;
String result = "";
char headChar;
Map<Character, Integer> map = new HashMap<>();
for (char c : arr)
{
map.put(c, 0);
}
for (int i = start; i < str.length(); i++)
{
char c = str.charAt(i);
if (map.containsKey(c) == false)
{
continue;
}
int charCount = map.get(c);
if (charCount == 0)
{
uniqueCounter = uniqueCounter + 1;
}
map.put(c, map.get(c) + 1);
while (uniqueCounter == patLen)
{
int tempLength = i - start + 1;
if (tempLength == patLen)
{
System.out.println(str.substring(start, i+1));
return str.substring(start, i+1).length();
}
if(result == "" || tempLength < result.length())
{
result = str.substring(start, i+1);
}
headChar=str.charAt(start);
int headCount=map.get(headChar)-1;
if(headCount==0)
{
break;
}
map.put(headChar,headCount);
start++;
}
}
System.out.println(result);
return result.length();
}
}
|
package com.markfeldman.recyclerview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
String[]teamNames, teamLocations;
int [] imgResources = {R.drawable.bruins,R.drawable.canadiens, R.drawable.lightning, R.drawable.maple_leafs,
R.drawable.panthers, R.drawable.red_wings,R.drawable.sabres,R.drawable.senators};
ArrayList<DataProvider> arrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
teamNames = getResources().getStringArray(R.array.team_names);
teamLocations = getResources().getStringArray(R.array.team_locations);
for (int i = 0; i < teamNames.length; i++ ){
DataProvider dataProvider = new DataProvider(imgResources[i],teamNames[i],teamLocations[i]);
arrayList.add(dataProvider);
}
adapter = new RecyclerAdapter(arrayList);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
public void popUpMessage(){
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_LONG).show();
}
public void newFunction(){
}
public void newFunction2(){
}
}
|
package com.springboot.connector;
import com.springboot.pojo.Employee;
import com.springboot.pojo.Login;
import com.springboot.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/system")
public class AdminController {
@Autowired
private AdminService service;
public AdminController() {
System.out.println("inside constructor of" + getClass().getName());
}
@GetMapping("/welcome")
public String showwelcome() {
System.out.println("in welcome form ");
return "welcome";
}
@GetMapping("/register")
public String showRegForm(Employee m) {
System.out.println("in show registration");
return "register";
}
@PostMapping("/register")
public String processRegForm(Employee m, RedirectAttributes flashMap, Model map) {
System.out.println("in process reg detail form " + m);
flashMap.addFlashAttribute("status", service.registerUser(m));
map.addAttribute("member_list", service.listEmployee());
return "memberlogin";
}
@GetMapping("/member")
public String showSocietyMember(Employee m, RedirectAttributes flashMap, Model map) {
/*System.out.println("in society detail "+member);
return "member";*/
System.out.println("display member details " + m);
flashMap.addFlashAttribute("status", service.registerUser(m));
map.addAttribute("society_list", service.listEmployee());
return "/member";
}
@GetMapping("/logout")
public String adminLogout(HttpSession hs) {
System.out.println("in logout");
hs.invalidate();
return "redirect:login";
}
@GetMapping("/login")
public String showLoginForm() {
System.out.println("In show login form");
return "/login";
}
@PostMapping("/login")
public String processLoginForm(@RequestParam String username, @RequestParam String password, Model map, HttpSession hs, RedirectAttributes flashMap) {
System.out.println("in process login form " + username + " " + password);
Login l = null;
try {
l = service.authenticateUser(username, password);
//valid login
if (l.getUsername().equals("admin")) {
//add validated user dtls under session scope
hs.setAttribute("admin_dtls", l);//v ---DETACHED
flashMap.addFlashAttribute("status", "admin Login Successful");
return "/welcome";
}
//hs.setAttribute("user_dtls", l);//v ---DETACHED
//flashMap.addFlashAttribute("status","user Login Successful");
return "welcome";
} catch (Exception e) {
map.addAttribute("status", "Invalid Login , Please try again..");
return "login";
}
}
}
|
package com.gagetalk.gagetalkcustomer.api;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.gagetalk.gagetalkcommon.constant.ConstPrefValue;
import com.gagetalk.gagetalkcommon.util.MyLog;
/**
* Created by hyochan on 7/20/15.
*/
public class CustomerFunction {
private static final String TAG = "CustomerNetwork";
private static CustomerFunction customerFunction;
private SharedPreferences sharedPreferences;
private Context context;
private String chatRoom;
private String notiRoom;
private CustomerFunction(Context context) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
this.context = context;
}
public static CustomerFunction getInstance(Context context) {
if (customerFunction == null) customerFunction = new CustomerFunction(context);
return customerFunction;
}
public String getChatRoom(){
return this.chatRoom;
}
public void setChatRoom(String chatRoom){
this.chatRoom = chatRoom;
}
public void deleteChatRoom(){
this.chatRoom = null;
}
public String getNotiRoom(){
return this.notiRoom;
}
public void setNotiRoom(String notiRoom){
this.notiRoom = notiRoom;
}
public void cusLogin(String id, String name, String pw) {
SharedPreferences pref =
context.getSharedPreferences(ConstPrefValue.CUS_LOGIN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(ConstPrefValue.ID, id);
editor.putString(ConstPrefValue.NAME, name);
editor.putString(ConstPrefValue.PASSWORD, pw);
MyLog.d(TAG, "### cusLogin - LOGIN DATA ###");
MyLog.d(TAG, "id : " + id);
MyLog.d(TAG, "name : " + name);
MyLog.d(TAG, "pw : " + pw);
editor.commit();
// CustomToast.getInstance(context).createToast(context.getResources().getString(R.string.login_success));
}
public boolean isCusLocallyLoggedIn(){
boolean result = false;
if (getCusID() != null) {
result = true;
}
MyLog.d(TAG, "customer locally logged in : " + result);
return result;
}
public String getCusID(){
SharedPreferences pref = context.getSharedPreferences(ConstPrefValue.CUS_LOGIN, Context.MODE_PRIVATE);
return pref.getString(ConstPrefValue.ID, null);
}
public String getCusPW(){
SharedPreferences pref = context.getSharedPreferences(ConstPrefValue.CUS_LOGIN, Context.MODE_PRIVATE);
return pref.getString(ConstPrefValue.PASSWORD, null);
}
public String getCusName(){
SharedPreferences pref = context.getSharedPreferences(ConstPrefValue.CUS_LOGIN, Context.MODE_PRIVATE);
return pref.getString(ConstPrefValue.NAME, null);
}
public void setCusName(String name){
SharedPreferences pref =
context.getSharedPreferences(ConstPrefValue.CUS_LOGIN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(ConstPrefValue.NAME, name);
MyLog.i(TAG, "name : " + name);
editor.commit();
}
}
|
package com.bbn.sd2;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.json.JSONObject;
public class MappingFailureEntry {
private String experiment;
private String lab;
private String item;
private String status;
private String itemId;
private String itemType;
private Date lastNotificationTime;
private SimpleDateFormat dateFormatter;
private int row;
private final String statusDatePrefix = "Notification sent at ";
private boolean notified;
private boolean valid;
private final String experimentColumnTag = "Experiment/Run";
private final String labColumnTag = "Lab";
private final String itemColumnTag = "Item Name";
private final String itemIdColumnTag = "Item ID";
private final String itemTypeColumnTag = "Item Type (Strain or Reagent Tab)";
private final String statusColumnTag = "Status";
MappingFailureEntry(Map<String, String> rowEntries, int row) throws IOException {
this.status = "";
this.valid = true;
this.lastNotificationTime = null;
this.dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
this.row = row + 1; // Index from 1 instead of 0
this.notified = false;
itemType = rowEntries.get(itemTypeColumnTag);
experiment = rowEntries.get(experimentColumnTag);
if(experiment == null) {
experiment = "";
}
lab = rowEntries.get(labColumnTag);
if(lab == null) {
lab = "";
}
item = rowEntries.get(itemColumnTag);
if(item == null) {
item = "";
}
itemId = rowEntries.get(itemIdColumnTag);
if(itemId == null) {
itemId = "";
}
if(experiment.length() == 0) {
status = "Missing " + experimentColumnTag + " value";
valid = false;
return;
}
if(item.length() == 0) {
status = "Missing " + itemColumnTag + " value";
valid = false;
return;
}
if(lab.length() == 0) {
status = "Missing " + labColumnTag + " value";
valid = false;
return;
}
if(itemId.length() == 0) {
status = "Missing " + itemIdColumnTag + " value";
valid = false;
return;
}
String statusString = rowEntries.get(statusColumnTag);
if(statusString == null) {
statusString = "";
}
// Parse status field
String[] statusFields = statusString.split(",");
for(String statusField : statusFields) {
if(statusField.startsWith(statusDatePrefix)) {
String dateString = statusField.substring(statusDatePrefix.length());
try {
lastNotificationTime = dateFormatter.parse(dateString);
} catch(ParseException e) {
throw new IOException("Failed to parse status date");
}
}
}
}
public String getExperiment() {
return experiment;
}
public String getLab() {
return lab;
}
public String getItem() {
return item;
}
public String getItemId() {
return itemId;
}
public String getItemType() {
return itemType;
}
public String getStatus() {
if(!valid) {
return status;
}
String newStatusString = "";
if(lastNotificationTime != null) {
newStatusString = statusDatePrefix;
newStatusString += dateFormatter.format(lastNotificationTime);
}
return newStatusString;
}
public int getRow() {
return row;
}
public void decrementRow(int delta) {
row -= delta;
}
public boolean getNotified() {
return notified;
}
public void setLastNotificationTime(Date lastEmailDate) {
this.lastNotificationTime = lastEmailDate;
this.notified = true;
}
public long secondsSinceLastNotification(Date date) {
if(lastNotificationTime == null) {
return date.getTime() / 1000L;
}
return (date.getTime() - lastNotificationTime.getTime()) / 1000L;
}
public boolean getValid() {
return valid;
}
JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put(experimentColumnTag, experiment);
jo.put(itemColumnTag, item);
jo.put(labColumnTag, lab);
jo.put(itemIdColumnTag, itemId);
if(itemType != null) {
jo.put(itemTypeColumnTag, itemType);
}
return jo;
}
}
|
import java.util.Scanner;
class SuperA {//суперкласс
public int InPole; //открытое целочисленное поле
//конструктор с параметром
SuperA (int n) {
InPole=n;
}
//метод с параметром
void SetInPole (int m) {
InPole=m;
}
public String toString() {
String ClassNameAndFieldValue;
ClassNameAndFieldValue = "super:" +
" Class name: " + this.getClass().getSimpleName() +";"+
" InPole=" + this.InPole+" -целочисленное поле";
return ClassNameAndFieldValue ;
}
}
class SubB extends SuperA {//подкласс суперкласса
public char CharPole; //открытое символьное поле
//конструктор с параметрами
SubB (int n, char ch) {
super(n);
CharPole=ch;
}
//метод с параметрами
void SetInPole (int m, char cha) {
super.SetInPole(m);
CharPole=cha;
}
public String toString() {
String ClassNameAndFieldValue;
ClassNameAndFieldValue = "sub:" +
" Class name: " + this.getClass().getSimpleName() + ";"+
" InPole=" + this.InPole+" -целочисленное поле"+";"+
" CharPole="+this.CharPole+" -символьное поле";
return ClassNameAndFieldValue ;
}
}
class SubC extends SubB {//подкласс подкласса
public String StrPole; //открытое текстовое поле
//конструктор с параметрами
SubC (int n, char ch, String st) {
super(n,ch);
StrPole=st;
}
//метод с параметрами
void SetInPole (int m, char cha, String strin) {
super.SetInPole(m, cha);
StrPole=strin;
}
public String toString() {
String ClassNameAndFieldValue;
ClassNameAndFieldValue = "sub sub:" +
" Class name: " + this.getClass().getSimpleName() + ";" +
" InPole=" + this.InPole+" -целочисленное поле"+";"+
" CharPole="+this.CharPole+" -символьное поле"+";"+
" StrPole="+this.StrPole+" -текстовое поле";
return ClassNameAndFieldValue ;
}
}
public class example32_03 {
public static void main(String[] args) {
try {
Scanner in = new Scanner(System.in); //сканнер для символа
Scanner numb = new Scanner(System.in); //сканнер для чисел
Scanner st = new Scanner(System.in); //сканнер для текста
System.out.println("*************Проверка конструктора:******************");
//конструктор суперкласса
SuperA objA=new SuperA (1);
System.out.println(objA.toString());
System.out.println("-----------------------------------------------------");
//конструтор подкласса суперкласса
SubB objB=new SubB (2,'B');
System.out.println(objB.toString());
System.out.println("-----------------------------------------------------");
//конструтор подкласса подкласса
SubC objC=new SubC (3,'C',"задано конструктором");
System.out.println(objC.toString());
System.out.println("-----------------------------------------------------");
System.out.println("*************Проверка методов:******************");
System.out.println("Введите число для проверки метода с целочисленным аргументом:");
int num=numb.nextInt();
objA.SetInPole(num); //метод с целочисленным аргументом
System.out.println(objA.toString());
System.out.println("-----------------------------------------------------");
System.out.println("Введите число для проверки метода с целочисленным аргументом и символом:");
num=numb.nextInt();
System.out.println("Введите символ для проверки метода с целочисленным аргументом и символом:");
char c=in.next().charAt(0);
objB.SetInPole(num, c); //метод с целочисленным аргументом и символом
System.out.println(objB.toString());
System.out.println("-----------------------------------------------------");
System.out.println("Введите число для проверки метода с целочисленным аргументом, символом и текстом:");
num=numb.nextInt();
System.out.println("Введите символ для проверки метода с целочисленным аргументом, символом и текстом:");
c=in.next().charAt(0);
System.out.println("Введите текст для проверки метода с целочисленным аргументом, символом и текстом:");
String Str=st.nextLine();
objC.SetInPole(num, c, Str);
System.out.println(objC.toString());
}
catch (Exception error) { System.out.println("При обработке данных произошла ошибка!"); //обработка исключения
}
}
}
|
package com.aman.shoppers;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import Adapters.ShopAdapter;
public class ShopsListActivity extends AppCompatActivity {
private ListView shopListView;
private static Keys keys = Keys.getInstance();
private ServerClient client = new ServerClient();
private Context context = ShopsListActivity.this;
private ArrayList<String> shopName = new ArrayList<String>();
private ArrayList<String> shopId = new ArrayList<String>();
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shops_list);
shopListView = (ListView) findViewById(R.id.shop_listView);
sharedPreferences = getSharedPreferences(keys.SHARED_USERNAME, Context.MODE_PRIVATE);
getShopData();
}
private void getShopData() {
if (sharedPreferences.contains(keys.KEY_USERNAME)) {
String username = sharedPreferences.getString(keys.KEY_USERNAME, null);
// parameters for server call
JSONObject params = new JSONObject();
try {
params.put(keys.KEY_USERNAME,username);
} catch (JSONException e) {
e.printStackTrace();
}
client.HTTPRequestGET(this, keys.SHOP_LIST_URL, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
int status = response.getInt("status");
String message;
if (status == keys.STATUS_OK) {
// parsing JSON data
JSONObject data = response.getJSONObject("data");
JSONArray list = data.getJSONArray("shop_list");
for(int i = 0; i < list.length(); i++) {
JSONObject detail = list.getJSONObject(i);
String id = detail.getString(keys.KEY_SHOP_ID);
String name = detail.getString(keys.KEY_SHOP_NAME);
shopId.add(id);
shopName.add(name);
}
setShopData();
} else {
message = response.getString("message");
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
private void setShopData() {
// Adapter for listview
ShopAdapter adapter = new ShopAdapter(this, shopName, shopId);
shopListView.setAdapter(adapter);
}
public void didSelectRowAtPosition(int position) {
// called when row is tapped
String id = shopId.get(position);
Intent intent = new Intent(context, EmployeeListActivity.class);
intent.putExtra(keys.KEY_SHOP_ID, id);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.user_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.profile_item:
if (sharedPreferences.contains(keys.KEY_USERNAME)) {
Intent intent = new Intent(context, ProfileActivity.class);
startActivity(intent);
}
return true;
case R.id.logout_item:
keys.logout(this, this);
finish();
return true;
default:super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}
}
|
/*
* Copyright (C) 2000 - 2022 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://www.silverpeas.org/docs/core/legal/floss_exception.html"
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.silverpeas.looks.aurora;
/**
* Created by Nicolas on 12/06/2017.
*/
public class BodyPartSettings {
private String domainsBarParams;
private String mainPartURL;
private boolean hideMenu = false;
public String getDomainsBarParams() {
return domainsBarParams;
}
void setDomainsBarParams(final String domainsBarParams) {
this.domainsBarParams = domainsBarParams;
}
public String getMainPartURL() {
return mainPartURL;
}
void setMainPartURL(final String mainPartURL) {
this.mainPartURL = mainPartURL;
}
public boolean isHideMenu() {
return hideMenu;
}
void setHideMenu(final boolean hideMenu) {
this.hideMenu = hideMenu;
}
}
|
package com.metoo.module.app.manage.buyer.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.metoo.core.annotation.SecurityMapping;
import com.metoo.core.mv.JModelAndView;
import com.metoo.core.tools.CommUtil;
import com.metoo.core.tools.Md5Encrypt;
import com.metoo.core.tools.WebForm;
import com.metoo.foundation.domain.Area;
import com.metoo.foundation.domain.Document;
import com.metoo.foundation.domain.Favorite;
import com.metoo.foundation.domain.FootPoint;
import com.metoo.foundation.domain.GoodsCart;
import com.metoo.foundation.domain.GoodsVoucherLog;
import com.metoo.foundation.domain.IntegralLog;
import com.metoo.foundation.domain.OrderForm;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.domain.VerifyCode;
import com.metoo.foundation.service.IAreaService;
import com.metoo.foundation.service.IDocumentService;
import com.metoo.foundation.service.IFavoriteService;
import com.metoo.foundation.service.IFootPointService;
import com.metoo.foundation.service.IGoodsCartService;
import com.metoo.foundation.service.IGoodsVoucherLogService;
import com.metoo.foundation.service.IIntegralLogService;
import com.metoo.foundation.service.IOrderFormService;
import com.metoo.foundation.service.ISysConfigService;
import com.metoo.foundation.service.IUserConfigService;
import com.metoo.foundation.service.IUserService;
import com.metoo.foundation.service.IVerifyCodeService;
import com.metoo.module.app.buyer.domain.Result;
import com.metoo.module.app.view.web.tool.AppCartViewTools;
import com.metoo.module.app.view.web.tool.AppobileTools;
import com.metoo.msg.MsgTools;
@Controller
@RequestMapping("/app/v1/")
public class AppAccountBuyerAction {
@Autowired
private ISysConfigService configService;
@Autowired
private IVerifyCodeService mobileverifycodeService;
@Autowired
private IUserConfigService userConfigService;
@Autowired
private IUserService userService;
@Autowired
private MsgTools msgTools;
@Autowired
private IFavoriteService favoriteService;
@Autowired
private IFootPointService footPointService;
@Autowired
private IOrderFormService orderFormService;
@Autowired
private IGoodsCartService goodsCartService;
@Autowired
private AppCartViewTools mCartViewTools;
@Autowired
private AppobileTools mobileTools;
@Autowired
private IAreaService areaService;
@Autowired
private IIntegralLogService intergralLogService;
@Autowired
private IDocumentService documentService;
@Autowired
private IGoodsVoucherLogService goodsVoucherLogService;
@SecurityMapping(title = "个人信息", value = "/buyer_account.json*", rtype = "buyer", rname = "用户中心", rcode = "user_center", rgroup = "用户中心")
@RequestMapping(value = "account.json", method = RequestMethod.POST)
public void account(HttpServletRequest request, HttpServletResponse response, String token) {
Result result = new Result();
Map<String, Object> map = new HashMap<String, Object>();
if(token.equals("")){
result = new Result(-100,"token Invalidation");
}else{
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if(user == null){
result = new Result(-100,"token Invalidation");
} else{
Map<String, Object> userMap = new HashMap<String, Object>();
userMap.put("TrueName", user.getTrueName());
userMap.put("Sex", user.getSex());
userMap.put("Email", user.getEmail());
userMap.put("Telephone", user.getTelephone());
userMap.put("Mobile", user.getMobile());
userMap.put("Birthday", user.getBirthday());
List<Area> areas = this.areaService.query(
"select obj from Area obj where obj.parent.id is null", null, -1, -1);
List<Map<String, Object>> areaList = new ArrayList<Map<String, Object>>();
for (Area area : areas) {
Map<String, Object> areaMap = new HashMap<String, Object>();
areaMap.put("id", area.getId());
areaMap.put("areaName", area.getAreaName());
areaList.add(areaMap);
map.put("areaMap", areaList);
}
map.put("userMap", userMap);
result = new Result(4200, "Success" ,map);
}
}
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
@SecurityMapping(title = "个人信息保存", value = "/buyer_account_save.htm*", rtype = "buyer", rname = "用户中心", rcode = "user_center", rgroup = "用户中心")
@RequestMapping(value = "accountSave.json", method = RequestMethod.POST)
public void account_save(HttpServletRequest request, HttpServletResponse response, String area_id, String birthday,
String token) {
Result result = null;
WebForm wf = new WebForm();
if(token.equals("")){
result = new Result(-100, "token Invalidation");
}else{
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if(user == null){
result = new Result(-100, "token Invalidation");
}else{
user = (User) wf.toPo(request, this.userService
.getObjById(user.getId()));
if (area_id != null && !area_id.equals("")) {
Area area = this.areaService
.getObjById(CommUtil.null2Long(area_id));
}
if (birthday != null && !birthday.equals("")) {
String y[] = birthday.split("-");
Calendar calendar = new GregorianCalendar();
int years = calendar.get(Calendar.YEAR) - CommUtil.null2Int(y[0]);
user.setYears(years);
}
if(this.userService.update(user)){
result = new Result(4200, "Success");
}else{
result = new Result(1, "Error");
}
}
}
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
@SecurityMapping(title = "密码修改保存", value = "/buyer_account_password_save.htm*", rtype = "buyer", rname = "用户中心", rcode = "user_center", rgroup = "用户中心")
@RequestMapping(value = "accountPassword.json", method = RequestMethod.POST)
public void account_password_save(HttpServletRequest request, HttpServletResponse response, String old_password,
String new_password, String token) {
Result result = new Result();
if(token.equals("")){
result = new Result(-100,"token Invalidation");
}else{
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if(user == null){
result = new Result(-100,"token Invalidation");
}else{
//获取当前登录用户数据库密码,比较用户输入密码加密 (md5)if-true 对新的密码加密
if(user.getPassword().equals(
Md5Encrypt.md5(old_password).toLowerCase())){
user.setPassword(Md5Encrypt.md5(new_password).toLowerCase());
boolean pwd = this.userService.update(user);
if(pwd){
/* String content1 = "尊敬的"
+ user.getUserName()
+ "您好,您于" + CommUtil.formatLongDate(new Date())
+ "修改密码成功,新密码为:" + new_password + ",请妥善保管。["
+ this.configService.getSysConfig().getTitle() + "]";
*/ String content = "Hi,dear customer "
+ user.getUserName()
+ ". you have success changed your password on : "
+ CommUtil.formatLongDate(new Date())
+ ". Your new password is: "
+ new_password
+ ",Please keep it safe. [Soarmall.com]";
try {
this.msgTools.sendSMS(user.getMobile(), content);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = new Result(0, content, pwd);
}
}else{
result = new Result(1, "PassWord Error");
}
}
}
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
@SecurityMapping(title = "邮箱修改保存", value = "/buyer_account_email_save.htm*", rtype = "buyer", rname = "用户中心", rcode = "user_center", rgroup = "用户中心")
@RequestMapping(value = "accountEmail.json", method = RequestMethod.POST)
public void account_email_save(HttpServletRequest request, HttpServletResponse response, String password,
String email, String token) {
Result result = null;
if(CommUtil.null2String(token).equals("")){
result = new Result(-100,"token Invalidation");
}else{
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if(user == null){
result = new Result(-100, "token Invalidation");
}else{
if(user.getPassword().equals(Md5Encrypt.md5(password).toLowerCase())){
user.setEmail(email);
if(this.configService.getSysConfig().isIntegral()){
user.setIntegral(this.configService.getSysConfig().getMemberEmail());
IntegralLog integralLog = new IntegralLog();
integralLog.setAddTime(new Date());
integralLog.setContent("用户"+new Date()+"完善邮箱增加" + this.configService.getSysConfig().getMemberEmail() + "分");
integralLog.setIntegral(this.configService.getSysConfig().getMemberEmail());
integralLog.setIntegral_user(user);
integralLog.setType("Add");
integralLog.setIntegral_from("登录");
this.intergralLogService.save(integralLog);
}
if(this.userService.update(user)){
result = new Result(4200, "Success");
}else{
result = new Result(1, "Error");
}
}else{
result = new Result(1, "PassWord Error");
}
}
}
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
/**
*
* @description 手机短信发送
* @param request
* @param response
* @param type
* @throws UnsupportedEncodingException
*/
@SecurityMapping(title = "手机短信发送", value = "/buyer/account_mobile_sms.htm*", rtype = "buyer", rname = "用户中心", rcode = "user_center", rgroup = "用户中心")
@RequestMapping(value = "accountSendSms.json", method = RequestMethod.POST)
public void account_mobile_sms(HttpServletRequest request, HttpServletResponse response, String type, String mobile,
String token) throws UnsupportedEncodingException {
Map params = new HashMap();
Result result = null;
if (token.equals("")) {
result = new Result(-100, "token Invalidation");
} else {
params.put("app_login_token", token);
List<User> users = this.userService.query(
"select obj from User obj where obj.app_login_token=:app_login_token order by obj.addTime desc",
params, -1, -1);
if (users.isEmpty()) {
result = new Result(-100, "token Invalidation");
} else {
User user = users.get(0);
int ret = 0;
if (type.equals("mobile_vetify_code")) {
String code = CommUtil.randomString(4).toUpperCase();
String content = "尊敬的" + user.getUserName() + "您好,您在试图修改"
+ this.configService.getSysConfig().getWebsiteName() + "用户绑定手机,手机验证码为:" + code + "。["
+ this.configService.getSysConfig().getTitle() + "]";
if (this.configService.getSysConfig().isSmsEnbale()) {
boolean ret1 = this.msgTools.sendSMS(mobile, content);
if (ret1) {
VerifyCode mvc = this.mobileverifycodeService.getObjByProperty(null, "mobile", mobile);
if (mvc == null) {
mvc = new VerifyCode();
}
mvc.setAddTime(new Date());
mvc.setCode(code);
mvc.setMobile(mobile);
this.mobileverifycodeService.update(mvc);
} else {
ret = 1;
}
} else {
ret = 2;
}
result = new Result(ret);
}
}
}
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
/**
* @description 手机号修改保存
* @param request
* @param response
* @param mobile_verify_code
* @param mobile
* @param token
* @throws Exception
*/
@SecurityMapping(title = "手机号码保存", value = "/buyer/account_mobile_save.htm*", rtype = "buyer", rname = "用户中心", rcode = "user_center", rgroup = "用户中心")
@RequestMapping(value = "accountMobile.json", method = RequestMethod.POST)
public void account_mobile_save(HttpServletRequest request, HttpServletResponse response, String mobile_verify_code,
String mobile, String token) throws Exception {
Result result = null;
if (token.equals("")) {
result = new Result(-100, "token Invalidation");
} else {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user == null) {
result = new Result(-100, "token Invalidation");
} else {
VerifyCode mvc = this.mobileverifycodeService.getObjByProperty(null, "mobile",
this.mobileTools.mobile(mobile).get("areaMobile").toString());
if (mvc != null && mvc.getCode().equalsIgnoreCase(mobile_verify_code)) {
user.setMobile(mobile);
this.userService.update(user);
this.mobileverifycodeService.delete(mvc.getId());
// 绑定成功后发送手机短信提醒
String content = "尊敬的" + user.getUserName() + "您好,您于" + CommUtil.formatLongDate(new Date())
+ "绑定手机号成功。[" + this.configService.getSysConfig().getTitle() + "]";
this.msgTools.sendSMS(user.getMobile(), content);
result = new Result(4200, "Success");
} else {
String content = "Verification code error, phone binding failed";
result = new Result(1, "error", content);
}
}
}
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
/**
* @description app获取邀请码
* @param request
* @param response
* @param token
*/
@RequestMapping(value = "invitation.json", method = RequestMethod.GET)
public void invitation(HttpServletRequest request, HttpServletResponse response, String token) {
Result result = null;
if (CommUtil.null2String(token).equals("")) {
result = new Result(-100, "token Invalidation");
} else {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user == null) {
result = new Result(-100, "token Invalidation");
} else {
String code = "";
if (user.getCode() == null || user.getCode().equals("")) {
code = CommUtil.randomLowercase(4);
} else {
code = user.getCode();
}
user.setCode(code);
this.userService.update(user);
Map<String, String> map = new HashMap<String, String>();
map.put("code", code);
result = new Result(4200, "Success", map);
}
}
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
/**
* @description 用户中心
* @param request
* @param response
* @param token
*/
@RequestMapping(value = "userCenter.json")
public void system(HttpServletRequest request, HttpServletResponse response, String token, String visitor_id) {
int code = -1;
String msg = "";
Result result = null;
Map<String, Object> data = new HashMap<String, Object>();
User user = null;
if (!token.equals("")) {
user = this.userService.getObjByProperty(null, "app_login_token", token);
}
String cart_session_id = "";
if (null != visitor_id && !"".equals(visitor_id)) {
cart_session_id = visitor_id;
} else {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("cart_session_id")) {
cart_session_id = CommUtil.null2String(cookie.getValue());
}
}
}
}
if (null != cart_session_id && cart_session_id.equals("")) {
cart_session_id = UUID.randomUUID().toString();
Cookie cookie = new Cookie("cart_session_id", cart_session_id);
cookie.setDomain(CommUtil.generic_domain(request));
response.addCookie(cookie);
}
if (null == user && !"".equals(visitor_id)) {
cart_session_id = visitor_id;
}
List<GoodsCart> goodsCarts = this.mCartViewTools.cartListCalc(request, user, cart_session_id);
if (null != user) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("type", 0);
params.put("user_id", user.getId());
List<Favorite> favorites = this.favoriteService.query(
"select obj from Favorite obj where obj.type=:type and obj.user_id=:user_id", params, -1, -1);
params.clear();
params.put("fp_user_id", user.getId());
List<FootPoint> footPoints = this.footPointService.query(
"select new FootPoint(id) from FootPoint obj where obj.fp_user_id=:fp_user_id", params, -1, -1);
/*
* params.clear(); params.put("user_id", user.getId());
* params.put("cart_status", 0); List<GoodsCart> goodsCarts =
* this.goodsCartService.query(
* "select obj from GoodsCart obj where obj.user.id=:user_id and obj.cart_status=:cart_status "
* , params, -1, -1);
*/
params.clear();
params.put("order_status", 30);
params.put("user_id", user.getId().toString());
List<OrderForm> shippeds = this.orderFormService.query(
"select obj from OrderForm obj where obj.order_status=:order_status and obj.user_id=:user_id",
params, -1, -1);
params.put("order_status", 40);
List<OrderForm> reviews = this.orderFormService.query(
"select obj from OrderForm obj where obj.order_status=:order_status and obj.user_id=:user_id",
params, -1, -1);
List<Integer> status = new ArrayList<Integer>();
status.add(16);
status.add(20);
params.put("order_status", status);
List<OrderForm> pendings = this.orderFormService.query(
"select obj from OrderForm obj where obj.order_status in(:order_status) and obj.user_id=:user_id",
params, -1, -1);
params.put("order_status", 10);
List<OrderForm> unpaid = this.orderFormService.query(
"select obj from OrderForm obj where obj.order_status in(:order_status) and obj.user_id=:user_id",
params, -1, -1);
// 查询抵用券获取总数量(未读)
params.clear();
params.put("user_id", user.getId());
params.put("log_read", 0);
List<GoodsVoucherLog> goodsVoucherLogs = this.goodsVoucherLogService
.query("SELECT new GoodsVoucherLog(id, addTime, status, log_read, price, user_id) "
+ "FROM GoodsVoucherLog obj WHERE obj.user_id=:user_id AND obj.log_read=:log_read ORDER BY obj.addTime DESC", params, -1, -1);
data.put("read", goodsVoucherLogs.size());
data.put("favorite", favorites.size() <= 0 ? 0 : favorites.size());
data.put("footPoint", footPoints.size() <= 0 ? 0 : footPoints.size());
data.put("shippeds", shippeds.size() <= 0 ? 0 : shippeds.size());
data.put("reviews", reviews.size() <= 0 ? 0 : reviews.size());
data.put("pendings", pendings.size() <= 0 ? 0 : pendings.size());
data.put("unpaid", unpaid.size() <= 0 ? 0 : unpaid.size());
code = 4200;
msg = "Success";
} else {
code = -100;
}
String language = CommUtil.language(request);
List<Document> documents = null;
Map params = new HashMap();
if(language.equals("sa")){
// 系统文章
documents = this.documentService.query("SELECT new Document(title, title_sa, mark) FROM Document obj", params, -1, -1);
}else{
documents = this.documentService.query("SELECT new Document(title, mark) FROM Document obj", params, -1, -1);
}
data.put("document", documents);
data.put("goodsCarts", goodsCarts.size() <= 0 ? 0 : goodsCarts.size());
data.put("visitor_id", cart_session_id);
result = new Result(code, msg, data);
this.send_json(Json.toJson(result, JsonFormat.compact()), response);
}
@RequestMapping("editUserMbile.json")
public void editUserMobile(HttpServletRequest request, HttpServletResponse response) {
Map params = new HashMap();
List<User> users = this.userService.query("select obj from User obj where obj.mobile is not null ", params, -1,
-1);
for (User user : users) {
String mobile = user.getMobile();
if (!CommUtil.null2String(mobile).equals("") && mobile.substring(0, 1).equals("0")) {
user.setTelephone(mobile.substring(1, mobile.length() - 1));
this.userService.update(user);
}
}
}
private void send_json(String json, HttpServletResponse response) {
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter writer;
try {
writer = response.getWriter();
writer.print(json);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package tests.android;
import baseplatformANDROID.BaseTest;
import objects.android.MainViewDR;
import objects.android.popupmenus.PopUpMenuOfStopDisplayButtonDR;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class StopDisplayingYesTest extends BaseTest {
private MainViewDR mv;
private PopUpMenuOfStopDisplayButtonDR popUp;
@BeforeClass
public void setUp() {
mv = new MainViewDR(driver);
popUp = new PopUpMenuOfStopDisplayButtonDR(driver);
}
@Parameters({"riderName"})
@Test(invocationCount = 5)
public void stopDisplayingPopUpMenuTest(String riderName){
mv.inputNameIntoField(riderName);
mv.displayNowTap();
mv.stopDisplayTap();
//verify all the text in the menu presented
popUp.stopDisplayYesTap();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package paddleexperience;
import DBAcess.ClubDBAccess;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Pattern;
import javafx.scene.control.TextField;
import model.Member;
/**
*
* @author luukmaas
*/
public class RegisterValidator {
private final String name;
private final String surname;
private final String telephone;
private final String login;
private final String password;
private final String creditcard;
private final String svc;
private final String passwordConfirmation;
public RegisterValidator(Member m, String passConf) {
this.name = m.getName();
this.surname = m.getSurname();
this.telephone = m.getTelephone();
this.login = m.getLogin();
this.password = m.getPassword();
this.creditcard = m.getCreditCard();
this.svc = m.getSvc();
this.passwordConfirmation = passConf;
}
public ArrayList<String> validate() {
ArrayList<String> errors = new ArrayList<>();
//Validate name is not empty or bigger than 50 chars.
if (this.name.length() > 50) {
errors.add("Name cannot be longer than 50 characters");
} else if (this.name.isEmpty()) {
errors.add("Name cannot be empty");
} else {
errors.add("");
}
//Validate surname is not empty or bigger than 50 chars.
if (this.surname.length() > 50) {
errors.add("Surname cannot be longer than 50 characters");
} else if (this.surname.isEmpty()) {
errors.add("Surname cannot be empty");
} else {
errors.add("");
}
//Validate telephone is not empty, only contains numbers and is not longer than 15 chars.
if (this.telephone.isEmpty()) {
errors.add("Telephone number cannot be empty");
} else if (this.telephone.length() > 15 || this.telephone.length() < 8) {
errors.add("Telephone number must be between 8 and 15 numbers.");
} else {
try {
Long.parseLong(this.telephone);
errors.add("");
} catch (Exception e) {
errors.add("Telephone number can only contain numbers");
}
}
//Validate username is not empty, only contains alphanumeric characters and is between 8-20 chars.
//Also, check if username is unique (i.e. no other use with the same username exists)
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
if (this.login.isEmpty()) {
errors.add("Username cannot be empty");
} else if (this.login.length() > 20 || this.login.length() < 8) {
errors.add("Username must be between 8 and 20 characters");
} else if (p.matcher(this.login).find()) {
errors.add("Username can only contain letters and numbers");
} else if (this.usernameExists(this.login)) {
errors.add("Username already exists. Please choose another one.");
} else {
errors.add("");
}
//Validate password is not empty, between 8-20 characters
if (this.password.isEmpty()) {
errors.add("Password cannot be empty.");
} else if (this.password.length() < 8 || this.password.length() > 30) {
errors.add("Password must be between 8 and 30 characters");
} else {
errors.add("");
}
//Validate password matches password confirmation (to avoid type-errors in password)
if (!this.password.equals(this.passwordConfirmation)) {
errors.add("The entered passwords do not match.");
} else {
errors.add("");
}
//Validate that if creditcard number has been entered, it must be 15 or 16 digits.
if (!this.creditcard.isEmpty() && (this.creditcard.length() < 15 || this.creditcard.length() > 16)) {
errors.add("Creditcard number must be 15 or 16 numbers");
} else if (this.creditcard.isEmpty()) {
errors.add("");
} else {
try {
Long.parseLong(this.creditcard);
errors.add("");
} catch (Exception e) {
errors.add("Creditcard number can only contain numbers");
}
}
//Validate that if creditcard number has been entered, a 3-digit SVC has also been entered.
if (!this.creditcard.isEmpty() && this.svc.isEmpty()) {
errors.add("You need to enter your SVC code if you want to add your creditcard");
} else if (!this.creditcard.isEmpty() && this.svc.length() != 3) {
errors.add("Your SVC code must be 3 digits.");
} else if (this.creditcard.isEmpty() && this.svc.isEmpty()) {
errors.add("");
} else {
try {
Integer.parseInt(this.svc);
errors.add("");
} catch (Exception e) {
errors.add("SVC code can only contain numbers");
}
}
return errors;
}
public boolean isValid() {
for (int i = 0; i<this.validate().size(); i++) {
if (!"".equals(this.validate().get(i))) {
return false;
}
}
return true;
}
//Function to check if username already exists
public boolean usernameExists(String username) {
ClubDBAccess db = ClubDBAccess.getSingletonClubDBAccess();
ArrayList<Member> allMembers = db.getMembers();
ArrayList<String> allUsernames = new ArrayList<>();
Iterator<Member> it = allMembers.iterator();
while (it.hasNext()) {
Member m = it.next();
allUsernames.add(m.getLogin());
}
return allUsernames.contains(username);
}
}
|
package com.kinsella.people.unit.business.service;
import com.kinsella.people.business.service.PersonService;
import com.kinsella.people.business.service.impl.PersonServiceImpl;
import com.kinsella.people.data.entity.Address;
import com.kinsella.people.data.entity.Person;
import com.kinsella.people.data.repository.PersonRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
public class PersonServiceTest {
@TestConfiguration
static class PersonServiceTestContextConfiguration {
@Bean
public PersonService personService() {
return new PersonServiceImpl();
}
}
@Autowired
private PersonService personService;
@MockBean
private PersonRepository personRepository;
@Before
public void setUp() {
Person test = new Person(1,"Test", "Person");
Mockito.when(personRepository.findById(1L))
.thenReturn(Optional.of(test));
Mockito.when(personRepository.existsById(1L))
.thenReturn(true);
}
@Test
public void testGetPersonReturnsPersonById() {
Optional<Person> testInDatabase = personService.get(1);
assertThat(testInDatabase.isPresent()).isEqualTo(true);
}
@Test(expected = NullPointerException.class)
public void testCreatePersonDoesNotAllowNullFirstName() {
Person person = new Person(2,null, "Test");
personService.create(person);
}
@Test(expected = NullPointerException.class)
public void testCreatePersonDoesNotAllowNullLastName() {
Person person = new Person(2,"Test", null);
personService.create(person);
}
@Test
public void testCreatePersonDoesNotAllowDupes() {
Person dupeIdPerson = new Person(1,"Test", "Person");
Optional<Person> shouldBeEmpty = personService.create(dupeIdPerson);
assertThat(shouldBeEmpty.isEmpty()).isEqualTo(true);
}
@Test
public void testAddressCannotBeAlteredDirectly() {
Optional<Person> testPerson = personService.get(1L);
testPerson.get().getAddresses().add(new Address());
assertThat(testPerson.get().getAddresses().size()).isEqualTo(0);
}
}
|
/**
* MIT License
* <p>
* Copyright (c) 2019-2022 nerve.network
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package network.nerve.converter.storage.impl;
import io.nuls.base.data.NulsHash;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.exception.NulsException;
import io.nuls.core.rockdb.model.Entry;
import io.nuls.core.rockdb.service.RocksDBService;
import network.nerve.converter.constant.ConverterDBConstant;
import network.nerve.converter.model.bo.Chain;
import network.nerve.converter.model.po.ProposalPO;
import network.nerve.converter.storage.ProposalVotingStorageService;
import network.nerve.converter.utils.ConverterUtil;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author: Loki
* @date: 2020/5/13
*/
@Component
public class ProposalVotingStorageServiceImpl implements ProposalVotingStorageService {
@Override
public boolean save(Chain chain, ProposalPO po) {
if (null == po) {
return false;
}
try {
return RocksDBService.put(ConverterDBConstant.DB_PROPOSAL_VOTING_PREFIX + chain.getChainId(), po.getHash().getBytes(), po.serialize());
} catch (Exception e) {
chain.getLogger().error(e);
return false;
}
}
@Override
public ProposalPO find(Chain chain, NulsHash hash) {
byte[] bytes = RocksDBService.get(ConverterDBConstant.DB_PROPOSAL_VOTING_PREFIX + chain.getChainId(),
hash.getBytes());
if (null == bytes || bytes.length == 0) {
return null;
}
ProposalPO po = new ProposalPO();
try {
po.parse(bytes, 0);
po.setHash(hash);
return po;
} catch (NulsException e) {
chain.getLogger().error(e);
}
return null;
}
@Override
public boolean delete(Chain chain, NulsHash hash) {
if (null == hash || hash.isBlank()) {
chain.getLogger().error("proposalTxHash key is null");
return false;
}
try {
return RocksDBService.delete(ConverterDBConstant.DB_PROPOSAL_VOTING_PREFIX + chain.getChainId(), hash.getBytes());
} catch (Exception e) {
chain.getLogger().error(e);
return false;
}
}
@Override
public Map<NulsHash, ProposalPO> findAll(Chain chain) {
List<Entry<byte[], byte[]>> listEntry = RocksDBService.entryList(ConverterDBConstant.DB_PROPOSAL_VOTING_PREFIX + chain.getChainId());
if(null == listEntry){
return null;
}
Map<NulsHash, ProposalPO> map = new HashMap<>();
try {
for(Entry<byte[], byte[]> entry : listEntry){
ProposalPO vbd = ConverterUtil.getInstance(entry.getValue(), ProposalPO.class);
map.put(vbd.getHash(), vbd);
}
} catch (NulsException e) {
chain.getLogger().error(e);
}
return map;
}
}
|
package com.cg.bo.model.bussiness;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "members")
public class Member {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long member_id;
private String member_name;
private String phone;
private String email;
@OneToMany
@JoinColumn(name = "visit_id")
private List<Visit> visits;
@OneToMany
@JoinColumn(name = "order_id")
private List<Order> orders;
@ManyToOne
@JoinColumn(name = "class_id")
private Class aClass;
}
|
package com.dian.diabetes.request;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import android.content.Context;
import com.dian.diabetes.db.AlarmBo;
import com.dian.diabetes.tool.Preference;
import com.dian.diabetes.utils.ContantsUtil;
import com.dian.diabetes.utils.HttpServiceUtil;
import com.dian.diabetes.utils.HttpServiceUtil.CallBack;
/**
* 登录注册API的请求包装类
*
* @author Chanjc@ifenguo.com
* @createDate 2014年7月22日
*
*/
public class LoginRegisterAPI {
/**
* http请求:发送手机验证码
*
* @param map
* @param callBack
*/
public static void genCode(Map<String, Object> map, CallBack callBack) {
HttpServiceUtil.request(ContantsUtil.HOST + HttpContants.URL_GEN_CODE,
HttpContants.REQUEST_MOTHOD, map, callBack);
}
/**
* http请求:注册
*
* @param map
* @param callBack
*/
public static void register(Map<String, Object> map, CallBack callBack) {
HttpServiceUtil.request(ContantsUtil.HOST + HttpContants.URL_REGISTER,
HttpContants.REQUEST_MOTHOD, map, callBack);
}
/**
* http请求:登录
* @param map
* @param callBack
*/
public static void login(Map<String, Object> map, CallBack callBack) {
HttpServiceUtil.request(ContantsUtil.HOST + HttpContants.URL_LOGIN,
HttpContants.REQUEST_MOTHOD, map, callBack);
}
/**
* http请求:注销
* @param map
* @param callBack
*/
public static void logout(Map<String, Object> map, Context context, CallBack callBack) {
String sessionId = Preference.instance(context).getString(ContantsUtil.USER_SESSIONID);
map = HttpUtil.putHeader(map,sessionId);
HttpServiceUtil.request(ContantsUtil.HOST + HttpContants.URL_LOGOUT,
HttpContants.REQUEST_MOTHOD, HttpUtil.putHeader(map,sessionId), callBack);
new AlarmBo(context).disableAlert();
}
/**
* http请求:修改密码-验证码
* @param map
* @param callBack
*/
public static void pswGenCode(Map<String, Object> map , CallBack callBack) {
HttpServiceUtil.request(ContantsUtil.HOST + HttpContants.URL_PSW_GENCODE,
HttpContants.REQUEST_MOTHOD, map, callBack);
}
/**
* http请求:修改密码-更改密码
* @param map
* @param callBack
*/
public static void change(Map<String, Object> map, CallBack callBack) {
HttpServiceUtil.request(ContantsUtil.HOST + HttpContants.URL_CHANGE_PSW,
HttpContants.REQUEST_MOTHOD, map, callBack);
}
}
|
package com.web.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.web.entity.User;
@Mapper
public interface UserMapper {
Integer deleteByPrimaryKey(Integer id);
Integer insert(User record);
Integer insertSelective(User record);
User selectByPrimaryKey(Integer id);
Integer updateByPrimaryKeySelective(User record);
Integer updateByPrimaryKey(User record);
User login(User user);
User selectByAccount(User user);
List<User> getUsers();
}
|
package com.gxc.stu.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxc.stu.mapper.SpecialtyMapper;
import com.gxc.stu.pojo.Specialty;
import com.gxc.stu.service.SpecialtyService;
import pojo.ChartBean;
import utils.Page;
@Service
public class SpecialtyServiceImpl implements SpecialtyService {
@Autowired
SpecialtyMapper specialtyMapper;
/**
* 添加专业
*/
@Override
public void addSpecialty(Specialty specialty) {
specialty.setCreateDate(new Date());
specialtyMapper.addSpecialty(specialty);
}
/**
* 根据部门ID查询专业
*/
@Override
public List<Specialty> findSpeListByDeptId(Integer deptId) {
List<Specialty> list = specialtyMapper.findSpeListByDeptId(deptId);
return list;
}
/**
* 查询所有专业
*/
@Override
public List<Specialty> findAllSpeList() {
List<Specialty> list = specialtyMapper.findAllSpeList();
return list;
}
/**
* 根据ID查询专业
*/
@Override
public Specialty findSpeBySpeId(Integer speId) {
return specialtyMapper.findSpeBySpeId(speId);
}
/**
* 更新专业
*/
@Override
public void updateSpe(Specialty specialty) {
specialtyMapper.updateSpe(specialty);
}
/**
* 根据部门查询专业(分页)
*/
@Override
public Page<Specialty> findSpeListByDeptIdAndPage(Integer deptId, Integer page, Integer size) {
PageHelper.startPage(page, size);
Page<Specialty> pageBean = new Page<>();
//查询列表
List<Specialty> speList = specialtyMapper.findSpeListByDeptId(deptId);
//获取总条数
PageInfo<Specialty> pageInfo = new PageInfo<>(speList);
long total = pageInfo.getTotal();
//封装Page
pageBean.setPage(page);
pageBean.setSize(size);
pageBean.setTotal((int)total);
pageBean.setRows(speList);
return pageBean;
}
/**
* 查询所有专业(分页)
*/
@Override
public Page<Specialty> findAllSpeListByPage(Integer page, Integer size) {
PageHelper.startPage(page, size);
Page<Specialty> pageBean = new Page<>();
//查询列表
List<Specialty> speList = specialtyMapper.findAllSpeList();
//获取总条数
PageInfo<Specialty> pageInfo = new PageInfo<>(speList);
long total = pageInfo.getTotal();
//封装Page
pageBean.setPage(page);
pageBean.setSize(size);
pageBean.setTotal((int)total);
pageBean.setRows(speList);
return pageBean;
}
/**
* 统计专业人数
*/
@Override
public List<ChartBean> findSpeStuCount() {
List<ChartBean> list = specialtyMapper.findDeptStuCount();
return list;
}
}
|
package com.example.demo.models.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "estado_solicitudes")
public class EstadoSolicitud implements Serializable {
@EmbeddedId
private EstadoSolicitudPK idEstadoSolicitud;
private String descripcion;
@Temporal(TemporalType.DATE)
private Date fecha;
@PrePersist
public void prePersist() {
fecha = new Date();
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public EstadoSolicitudPK getIdEstadoSolicitud() {
return idEstadoSolicitud;
}
public void setIdEstadoSolicitud(EstadoSolicitudPK idEstadoSolicitud) {
this.idEstadoSolicitud = idEstadoSolicitud;
}
private static final long serialVersionUID = 1L;
}
|
package com.gxc.stu.back.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.ResponseBody;
import com.gxc.stu.pojo.Accessdetail;
import com.gxc.stu.pojo.User;
import com.gxc.stu.service.AccessDetailService;
import utils.MyResult;
import utils.Page;
@Controller
public class AccessDetailController {
@Autowired
private AccessDetailService accessDetailService;
/**
* 条件查询,分页
* @param accessDetail
* @param model
* @param page
* @param size
* @return
*/
@RequestMapping("/back/accessList")
public String accessList(
Accessdetail accessDetail, Model model,
@RequestParam(defaultValue="1")Integer page,
@RequestParam(defaultValue="20")Integer size,
HttpServletRequest request){
//更新专业前,判断是否为登录状态
User user = (User)request.getAttribute("user");
//1.如果不是登录状态,提示暂无权限,请登录
if(user == null){
return "noAccess";
}
//2.如果是登录状态,判断user的权限,如果权限不够,提示暂无权限更新
if(user.getRole() == 2){
return "noAccess";
}
//根据条件查询
Page<Accessdetail> pageList = accessDetailService.findAccessDetailListByCondition(accessDetail,page,size);
//不要忘记数据回显
model.addAttribute("page", pageList);
model.addAttribute("search", accessDetail);
return "accessList";
}
/**
* 删除
* @param id
* @return
*/
@RequestMapping("/back/deleteAccess")
@ResponseBody
public MyResult deleteAccess(Integer id){
accessDetailService.deleteAccessDetailById(id);
return MyResult.ok();
}
}
|
package com.haku.light.input.event;
public abstract class InputEvent {
@Override
public String toString() {
return this.getClass().getSimpleName();
}
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object other);
}
|
package by.orion.onlinertasks.data.models.profile.reviews;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.SerializedName;
@AutoValue
public abstract class Rating {
@SerializedName("politeness")
public abstract Integer politeness();
@SerializedName("quality")
public abstract Integer quality();
@SerializedName("punctuality")
public abstract Integer punctuality();
public static TypeAdapter<Rating> typeAdapter(Gson gson) {
return new AutoValue_Rating.GsonTypeAdapter(gson);
}
}
|
/**
* Author: Dustin Mao
*/
package com.mfg;
import org.springframework.web.bind.annotation.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
@RestController
@RequestMapping(value="/api/good")
public class GoodController {
// hello world test
@RequestMapping("/hello")
public String getHello() {
return "Hello World";
}
@Autowired
GoodDataService goodDataService;
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public Good getGood(@PathVariable Long id) {
return goodDataService.get(id);
}
@RequestMapping(method=RequestMethod.GET)
public Map<String, Object> getAllGoods() {
List<Good> goods = goodDataService.getAll();
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put("totalGoods", goods.size());
response.put("goods", goods);
return response;
}
@RequestMapping(method=RequestMethod.POST)
public Map<String, Object> createGood(@RequestBody Map<String, Object> goodMap) {
Good good = goodDataService.create(goodMap);
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put("message", "Good created successfully");
response.put("good", good);
return response;
}
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public Map<String, Object> createGood(@PathVariable Long id, @RequestBody Map<String, Object> goodMap) {
Good good = goodDataService.update(id, goodMap);
Map<String, Object> response = new LinkedHashMap<String, Object>();
response.put("message", "Good updated successfully");
response.put("good", good);
return response;
}
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public Map<String, String> deleteGood(@PathVariable Long id) {
goodDataService.delete(id);
Map<String, String> response = new LinkedHashMap<String, String>();
response.put("message", "Good deleted successfully");
return response;
}
}
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class from1 extends JFrame implements ActionListener
{
JPanel p1;
JLabel l1,l2;
JPasswordField t2;
JTextField t1;
JButton b1,b2;
String uname=new String();
String upass=new String();
public void de()
{
p1=new JPanel();
l1=new JLabel("USER NAME");
l2=new JLabel("PASSWORD");
t1=new JTextField();
t2=new JPasswordField();
b1=new JButton("OK");
b2=new JButton("CENCLE");
setBackground(Color.GREEN);
setLayout(null);
p1.setBackground(Color.getHSBColor(234.0f,128.7f,76.8f));
p1.setBounds(10,10,280,180);
l1.setBounds(15,20,100,30);
t1.setBounds(120,10,120,30);
l2.setBounds(15,50,100,30);
t2.setBounds(120,50,120,30);
b1.setBounds(15,120,80,20);
b2.setBounds(170,120,80,20);
p1.setLayout(null);
add(p1);
p1.add(l1);
p1.add(l2);
p1.add(t1);
p1.add(t2);
p1.add(b1);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setBounds(10,10,320,240);
show();
setTitle("Login Form");
}//close of de()
public void actionPerformed(ActionEvent ae)
{
uname=(t1.getText());
upass=(t2.getText());
if(ae.getSource()==b1)
{
if(uname.equals("AMRESH")&&upass.equals("9570918106"))
{
tol f2=new tol();
f2.setVisible(true);
f2.tool();
setVisible(false);
}
}
if(ae.getSource()==b2)
{
System.exit(0);
}
}
}
//class fromm
//{
// public static void main (String args[]) {
// from1 f=new from1();
// f.de();
//}
//}
|
package com.oracle.service;
import com.oracle.vo.Item;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
//生产备选对象的工厂!!!!!!!!!
//0702 服务降级 放的是自己定义的接口
@Component
public class ItemFallBackFactory implements FallbackFactory<ItemHandlerService> {
//接口里又多少方法,这个工厂里就有多少个方法,都是备选方法!!!!!!!!!
//备选方法
@Override
public ItemHandlerService create(Throwable throwable) {
//匿名内部类,重写ItemHandlerService了接口的两个方法
return new ItemHandlerService() {
@Override
public Item getItem(Integer itemNo) {
return new Item(0,"服务器停止响应test",0,0);
}
@Override
public Item save(Item item) {
return null;
}
};
}
}
|
package com.gaoshin.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import common.util.reflection.ReflectionUtil;
@MappedSuperclass
public class GenericEntity implements Serializable {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public GenericEntity() {
}
public GenericEntity(Object bean) {
copyFrom(bean);
id = null;
}
public void copyFrom(Object bean) {
Long tmp = id;
ReflectionUtil.copyPrimeProperties(this, bean);
id = tmp;
}
public <T> T getBean(Class<T> beanClass) {
try {
T bean = beanClass.newInstance();
ReflectionUtil.copyPrimeProperties(bean, this);
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}
|
package aula_0406.armazem_p2;
public class ClienteFiel extends Cliente {
private static final double VALOR_ADICIONAL = 500.0;
public ClienteFiel(String nome, int idade, double renda, boolean isEstudante) {
super(nome, idade, renda, isEstudante);
}
public double financiamentoMaximo() {
return getRenda() + VALOR_ADICIONAL;
}
}
|
package be.kdg.fastrada.exceptions;
/**
* Custom exception for password repeat.
*/
public class PasswordRepeatException extends Exception {
public PasswordRepeatException(String message) {
super(message);
}
}
|
package gamePackage;
import gamePackage.myFrame;
import gamePackage.commonTopPanel;
import gamePackage.gameMenuEvent;
import gamePackage.aProposEvent;
import gamePackage.commonParameter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
public class menuPanel
{
public JPanel topPanel = new JPanel();
public JPanel centerPanel = new JPanel();
public JPanel bottomPanel = new JPanel();
public JPanel rightPanel = new JPanel();
public JPanel leftPanel = new JPanel();
private commonParameter singleton = commonParameter.getInstance();
public menuPanel(myFrame mainFrame)
{
mainFrame.myPanel = new JPanel();
JButton gameButton = new JButton("Commencer partie");
gameButton.setPreferredSize(new Dimension(300,50));
gameButton.addActionListener(new gameMenuEvent(mainFrame));
JButton aproposButton = new JButton("A propos de ce jeu");
aproposButton.setPreferredSize(new Dimension(300,50));
aproposButton.addActionListener(new aProposEvent(mainFrame, false));
JButton endButton = new JButton("Fin du jeu");
endButton.setPreferredSize(new Dimension(300,50));
endButton.addActionListener(new aProposEvent(mainFrame, true));
mainFrame.myPanel.setBackground(singleton.myColor);
topPanel.setBackground(singleton.myColor);
bottomPanel.setBackground(singleton.myColor);
centerPanel.setBackground(singleton.myColor);
leftPanel.setBackground(singleton.myColor);
rightPanel.setBackground(singleton.myColor);
mainFrame.myPanel.setLayout(new BorderLayout());
mainFrame.myPanel.add(topPanel, BorderLayout.NORTH);
mainFrame.myPanel.add(centerPanel, BorderLayout.CENTER);
mainFrame.myPanel.add(bottomPanel, BorderLayout.SOUTH);
mainFrame.myPanel.add(rightPanel, BorderLayout.EAST);
mainFrame.myPanel.add(leftPanel, BorderLayout.WEST);
topPanel.setPreferredSize(new Dimension(100,250));
bottomPanel.setPreferredSize(new Dimension(100,100));
centerPanel.setPreferredSize(new Dimension(100,400));
leftPanel.setPreferredSize(new Dimension(200,100));
rightPanel.setPreferredSize(new Dimension(200,100));
centerPanel.add(gameButton);
centerPanel.add(aproposButton);
centerPanel.add(endButton);
commonTopPanel myCommonTopPanel = new commonTopPanel(topPanel);
mainFrame.setContentPane(mainFrame.myPanel);
mainFrame.setVisible(true);
}
}
|
package cn.swsk.rgyxtqapp;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.swsk.rgyxtqapp.adapter.DrawPersonLvAdapter;
import cn.swsk.rgyxtqapp.bean.DrawPerson;
import cn.swsk.rgyxtqapp.custom.LVDialog;
/**
* Created by apple on 16/2/23.
*/
public class DrawActivity extends AnquanguanliBaseActivity implements View.OnClickListener {
private ListView lv;
private Button confirm;
private DrawPersonLvAdapter dapter;
public void preCreate(){
this.resid=R.layout.draw_activity;
}
public void anaCreate(){
lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(dapter = new DrawPersonLvAdapter(this));
confirm= (Button)findViewById(R.id.confirm);
confirm.setOnClickListener(this);
dapter.addInfo(DrawPerson.getDefault());
}
@Override
public void onClick(View v) {
int id=v.getId();
final View vg=v;
final List<Map<String,String>> list=new ArrayList<Map<String,String>>();
if(v==confirm){
dapter.addInfo(DrawPerson.getDefault());
return ;
}else if(id==R.id.identity){
Map<String,String> map=new HashMap<String, String>();
map.put("name", "identity");
list.add(map);
list.add(map);
list.add(map);
}
String title=((TextView) ((ViewGroup) v).getChildAt(0)).getText().toString();
LVDialog.getLvDialogNShow(this, list, title.substring(0, title.length() - 1), new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
((TextView) ((ViewGroup) vg).getChildAt(1)).setText(list.get(position).get("name"));
}
});
}
}
|
import java.net.ServerSocket;
import java.net.Socket;
import lejos.utility.Delay;
import java.io.*;
public class SocketClient {
public static void main(String[] args) throws IOException {
System.out.println("Program started");
ServerSocket serv = new ServerSocket(1111);
Socket s = serv.accept(); //Wait for Laptop to connect
DataInputStream in = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
System.out.println("Socket connected");
//Test msg from laptop
try {
System.out.println(in.readChar());
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Did not receive message from server");
e.printStackTrace();
}
// Wait in order to see the message on the display
Delay.msDelay(10000);
};
};
|
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author husan
* @Date 2013-9-26
* @description:jdk动态代理,需要实现接口
*
*/
public class JdkProxy implements InvocationHandler{
private Object target;
public JdkProxy(Object target){
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
//System.out.print(proxy);
String name = method.getName();
if(!name.startsWith("do")){
Object ret = method.invoke(target, args);
return ret;
}
Object ret = method.invoke(target, args);
System.out.print("log:methodName"+method.getName()+";");
System.out.println("result:"+ret);
return ret;
}
public static Object getProxy(Object target){
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new JdkProxy(target));
}
public static void main(String[] args) {
IObject proxy = (IObject)getProxy(new RealObject());
proxy.getName("husan");
}
}
|
package Model;
import java.io.Serializable;
public class Course implements Serializable {
private String subjectName;
private String subjectId;
private int year;
private int semester;
private String difficultyLevel;
public Course(String subjectName, String subjectId, int year, int semester, String level) {
this.subjectName = subjectName;
this.subjectId = subjectId;
this.year = year;
this.semester = semester;
this.difficultyLevel = level;
}
public String getSubjectName() {
return subjectName;
}
public String getSubjectId() {
return subjectId;
}
public String getDifficultyLevel() {
return difficultyLevel;
}
public int getYear() {
return year;
}
public int getSemester() {
return semester;
}
public boolean isPassed(){
return true;
}
@Override
public String toString() {
return "Subject Id='" + subjectId + '\'' +
" Subject Name='" + subjectName + '\'' +
" year=" + year +
" semester=" + semester +
" difficultyLevel='" + difficultyLevel + '\'' +
"\n";
}
}
|
package Model.DAO;
import Model.Game;
import Model.GameSession;
import Model.PlaySession;
import java.util.List;
public interface GameSessionDAO {
void startNewGameSession(PlaySession sessionId, Game game, String gameSelectionType);
List<GameSession> getGameSessionByGame(Game game);
List<GameSession> getGameSessionBySelectionType(String gameSelectionType);
void updateGameSession(GameSession gameSession);
void deleteGameSession(GameSession gameSession);
}
|
package com.codecool.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
@WebServlet(name = "WebShopServlet", urlPatterns = {"/"}, loadOnStartup = 1)
public class Webshop extends HttpServlet {
public void init() {
ItemStore.listOfItems.add(new Item("Asus laptop",1500));
ItemStore.listOfItems.add(new Item("Plazma tv",1200));
ItemStore.listOfItems.add(new Item("retek",100));
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
StringBuffer buffer = new StringBuffer();
if (request.getParameterNames().hasMoreElements()) {
String method = request.getParameter("method").equals("add") ? "added":"removed";
buffer.append("You have "+ method+ "this item : " + request.getParameter("name"));
if (request.getParameter("method").equals("add")) {
ShoppingCart.addItem(new Item(request.getParameter("name"),Double.parseDouble(request.getParameter("price"))));
}
if (request.getParameter("method").equals("remove")) {
Iterator<Item> iterator = ShoppingCart.cart.iterator();
while (iterator.hasNext()) {
if (iterator.next().name.equals(request.getParameter("name"))) {
iterator.remove();
break;
}
}
}
}
String title = " items in our shop";
out.println("<html>\n"+
"<head><title>" + title + "</head></title>\n"+
"<body>\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
out.println(buffer.toString() +
"ul\n");
for (Item item : ItemStore.listOfItems) {
out.println("<li><b></b>: "+ item.id + " " + item.name + " " + item.price + " " +
"<form action=\"/\" method=\"GET\"><input type=\"hidden\" name=\"name\" value=\"" +
item.name + "\"><input type=\"hidden\" name=\"price\" value=\"" +
item.price + " \"><button type=\"submit\" name=\"method\" value=\"add\">ADD</button><button type=\"submit\" name=\"method\" value=\"remove\">REMOVE</button>" +
"</form>");
}
out.println(
"<a href=\"/cart\">SHOPPING CART</a></body></html>"
);
}
}
|
// Austin Hall
// CSCD 300
// 5/16/19
public class LinkedStack {
private class Node {
private Object data;
private Node next;
public Node(Object e, Node n) {
this.data = e;
this.next = n;
}
}
private Node top;
private int size;
public LinkedStack() {
this.top = null;
this.size = 0;
}
public int size() {
return this.size;
}
public boolean isEmpty() {
return this.top == null || this.size == 0;
}
public void push(Object elm) { //Equivalent to addFirst
Node nn = new Node(elm, this.top);
this.top = nn;
this.size++;
}
public Object pop() throws EmptyStackException {
if(isEmpty()) {
throw new EmptyStackException("Stack is empty");
}
Object temp = this.top.data;
this.top = this.top.next;
this.size--;
return temp;
}
public Object top() {
if(isEmpty()) {
throw new EmptyStackException("Stack is empty");
}
return this.top.data;
}
public void clearStack() {
if(!isEmpty()) {
this.top = null;
}
}
class EmptyStackException extends RuntimeException {
public EmptyStackException(String err) {
super(err);
}
}
}
|
package com.example.awesoman.owo2_comic.model;
import java.util.List;
/**
* Created by Awesome on 2017/6/1.
*/
public class ComicBookResult {
int total ;
int limit;
List<HttpComicInfo> bookList ;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public List<HttpComicInfo> getBookList() {
return bookList;
}
public void setBookList(List<HttpComicInfo> bookList) {
this.bookList = bookList;
}
}
|
package net.kkolyan.elements.engine.core.templates;
/**
* @author nplekhanov
*/
public class MutableDouble {
private double value;
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public MutableDouble add(double value) {
this.value += value;
return this;
}
public double abs() {
return Math.abs(value);
}
}
|
package com.yc.education.controller.sale;
import com.github.pagehelper.PageInfo;
import com.yc.education.controller.BaseController;
import com.yc.education.controller.stock.SaleOutboundOrderController;
import com.yc.education.model.DataSetting;
import com.yc.education.model.sale.*;
import com.yc.education.model.stock.StockOutSaleProductProperty;
import com.yc.education.service.DataSettingService;
import com.yc.education.service.sale.*;
import com.yc.education.util.StageManager;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
/**
* 销货单导入 -- 查询
*/
@Controller
public class SaleGoodsImportController extends BaseController implements Initializable {
@Autowired ISaleGoodsService iSaleGoodsService;
@Autowired ISaleGoodsProductService iSaleGoodsProductService;
@Autowired DataSettingService iDataSettingService;
@FXML VBox menu_first; // 第一页
@FXML VBox menu_prev; // 上一页
@FXML VBox menu_next; // 下一页
@FXML VBox menu_last; // 最后一页
@FXML CheckBox che_recently; // 最近单据
@FXML CheckBox che_audit; // 已审核
@FXML TextField num; // 数量
@FXML
Button client_sure;
@FXML TableView tab_order;
@FXML TableColumn col_order_id;
@FXML TableColumn col_order_no;
@FXML TableColumn col_order_date;
@FXML TableColumn col_order_category; //客户类型
@FXML TableColumn col_order_customer_no;
@FXML TableColumn col_order_customer_name;
@FXML TableColumn col_order_status;
@FXML TableView tab_product;
@FXML TableColumn tab_product_che;
@FXML TableColumn tab_product_id;
@FXML TableColumn tab_product_no;
@FXML TableColumn tab_product_name;
@FXML TableColumn tab_product_num;
@FXML TableColumn tab_product_unit;
@FXML TableColumn tab_product_price;
@FXML TableColumn tab_product_remark;
// 订单编号
private static String orderid = "";
// 查询订单中产品
ObservableList<SaleGoodsProductProperty> importData = FXCollections.observableArrayList();
// 导入选中的产品--销售退货单
ObservableList<SaleReturnGoodsProductProperty> importPurchaseData = FXCollections.observableArrayList();
// 导入选中的产品--销货出库单
ObservableList<StockOutSaleProductProperty> importOutboundData = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
setMenuValue(1);
importData.clear();
importPurchaseData.clear();
importOutboundData.clear();
}
/**
* @Description 模糊查询
* @Author BlueSky
* @Date 12:00 2019/4/11
**/
@FXML
public void textQuery(){
setMenuValue(1);
}
/**
* 给翻页菜单赋值
* @param page
*/
private void setMenuValue(int page){
int rows = pageRows(che_recently,num);
boolean audit = che_audit.isSelected();
List<SaleGoods> saleGoodsList = iSaleGoodsService.listSaleGoodsByPage("",audit?"1":"",page, rows);
if(saleGoodsList != null && saleGoodsList.size() >0){
PageInfo<SaleGoods> pageInfo = new PageInfo<>(saleGoodsList);
menu_first.setUserData(pageInfo.getFirstPage());
menu_prev.setUserData(pageInfo.getPrePage());
menu_next.setUserData(pageInfo.getNextPage());
menu_last.setUserData(pageInfo.getLastPage());
initData(saleGoodsList);
}else {
tab_order.setItems(null);
}
}
/**
* 分页
* @param event
*/
public void pages(MouseEvent event){
Node node =(Node)event.getSource();
if(node.getUserData() != null){
int page =Integer.parseInt(String.valueOf(node.getUserData()));
setMenuValue(page);
}
}
/**
* 关闭导入窗口
*/
@FXML
public void closeImprotWin(){
Stage stage=(Stage)client_sure.getScene().getWindow();
StageManager.CONTROLLER.remove("SaleReturnControllerImport");
StageManager.CONTROLLER.remove("SaleOutboundOrderControllerImport");
importData.clear();
importPurchaseData.clear();
importOutboundData.clear();
stage.close();
}
/**
* 确认按钮-关闭窗口
*/
@FXML
public void sureCloseImportWin(){
if(orderid != null && !"".equals(orderid)){
int rows = 1;
// 销售 - 销售退货单
SaleReturnController orderController = (SaleReturnController) StageManager.CONTROLLER.get("SaleReturnControllerImport");
if(orderController != null){
SaleGoods saleGoods = iSaleGoodsService.selectByKey(Long.valueOf(orderid));
if(!saleGoods.getOrderAudit()){
alert_informationDialog("该单据未审核或已作废暂无法进行导出");
return;
}
// 把选中订单数据加载到退货订单上
orderController.setBasicImportVal(saleGoods);
orderController.relation.setBeRelationId(saleGoods.getId());
orderController.relation.setBeRelationName("销货单");
// 把销货订单中的选中产品加载到销售退货单中的退货产品中
for (SaleGoodsProductProperty k : importData) {
if(k.isChecked() && k.getId() != null && k.getId()>0){
SaleGoodsProduct p = iSaleGoodsProductService.selectByKey(k.getId());
totalCost(p.getNum()==null?0:p.getNum(),p.getMoney()==null?new BigDecimal("0.00"):p.getMoney(),saleGoods.getTax(), orderController.total_num, orderController.total_tax, orderController.total_loan, orderController.total_money);
importPurchaseData.add(new SaleReturnGoodsProductProperty( rows++, p.getProductNo(), p.getProductName(), p.getCategory(), p.getNum(), p.getUnit(), p.getPricing(), p.getPrice(), p.getMoney(),"销货单" , saleGoods.getSaleNo(),p.getWarehousePosition() , p.getFloor(),p.getRemark() ));
}
}
if(importPurchaseData != null){
orderController.generalProductTab(importPurchaseData);
}
orderController.setControllerUse();
}
// 库存 - 销货出库单
SaleOutboundOrderController saleOutboundOrderController = (SaleOutboundOrderController) StageManager.CONTROLLER.get("SaleOutboundOrderControllerImport");
if(saleOutboundOrderController != null){
SaleGoods saleGoods = iSaleGoodsService.selectByKey(Long.valueOf(orderid));
if(!saleGoods.getOrderAudit()){
alert_informationDialog("该单据未审核或已作废暂无法进行导出");
return;
}
// 把选中订单数据加载到销货出库订单上
saleOutboundOrderController.setSaleGoodsBasicVal(saleGoods);
saleOutboundOrderController.relation.setBeRelationId(saleGoods.getId());
saleOutboundOrderController.relation.setBeRelationName("销货单");
// 把销货单中的选中产品加载到销货出库单的出货产品中
for (SaleGoodsProductProperty k : importData) {
if(k.isChecked() && k.getId() != null && k.getId()>0){
SaleGoodsProduct p = iSaleGoodsProductService.selectByKey(k.getId());
importOutboundData.add(new StockOutSaleProductProperty( 0L, rows++,0L,"销货单", saleGoods.getSaleNo(), p.getProductNo(), p.getProductName(), p.getCategory(), p.getNum(), p.getUnit(), p.getPrice(), p.getWarehousePosition(), p.getFloor(), p.getRemark()));
}
}
if(importOutboundData != null){
saleOutboundOrderController.generalProductTab(importOutboundData);
}
saleOutboundOrderController.setControllerUse();
}
}
closeImprotWin();
}
/**
* 初始化销货单信息
*/
private void initData(List<SaleGoods> list){
if(list != null){
list.forEach(p->{
p.setCreateDateStr(new SimpleDateFormat("yyyy-MM-dd").format(p.getCreateDate()));
if(p.getOrderAudit() != null && p.getOrderAudit()){
p.setAuditStatus("已审核");
}else{
p.setAuditStatus("未审核");
}
});
}
// 查询客户集合
final ObservableList<SaleGoods> data = FXCollections.observableArrayList(list);
col_order_id.setCellValueFactory(new PropertyValueFactory("id"));
col_order_no.setCellValueFactory(new PropertyValueFactory("saleNo"));
col_order_date.setCellValueFactory(new PropertyValueFactory("createDateStr"));
col_order_category.setCellValueFactory(new PropertyValueFactory("customerCategory"));
col_order_customer_no.setCellValueFactory(new PropertyValueFactory("customerNo"));
col_order_customer_name.setCellValueFactory(new PropertyValueFactory("customerNoStr"));
col_order_status.setCellValueFactory(new PropertyValueFactory("auditStatus"));
tab_order.setItems(data);
// 选择行 查询数据
tab_order.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<SaleGoods>() {
@Override
public void changed(ObservableValue<? extends SaleGoods> observableValue, SaleGoods oldItem, SaleGoods newItem) {
if(newItem.getId() != null && !"".equals(newItem.getId()) && newItem.getSaleNo() != null && !"".equals(newItem.getSaleNo())){
SaleGoodsImportController.orderid = newItem.getId().toString();
List<SaleGoodsProduct> productList = iSaleGoodsProductService.listSaleGoodsProduct(newItem.getId().toString());
importData.clear();
tab_product.setEditable(true);
tab_product_che.setCellFactory(CheckBoxTableCell.forTableColumn(tab_product_che));
tab_product_che.setCellValueFactory(new PropertyValueFactory("checked"));
tab_product_id.setCellValueFactory(new PropertyValueFactory("id"));
tab_product_no.setCellValueFactory(new PropertyValueFactory("productNo"));
tab_product_name.setCellValueFactory(new PropertyValueFactory("productName"));//映射
tab_product_num.setCellValueFactory(new PropertyValueFactory("num"));
tab_product_unit.setCellValueFactory(new PropertyValueFactory("unit"));
tab_product_price.setCellValueFactory(new PropertyValueFactory("price"));
tab_product_remark.setCellValueFactory(new PropertyValueFactory("remark"));
try {
for (SaleGoodsProduct p : productList) {
importData.add(new SaleGoodsProductProperty(p.getId(), p.getProductNo(), p.getProductName(), p.getCategory(), p.getNum(), p.getUnit(), p.getPricing(),p.getDiscount()+"" ,p.getPrice() ,p.getMoney() , newItem.getSaleNo() , "销货单",p.getRemark(),false));
}
}catch (Exception e){
e.printStackTrace();
}
tab_product.setItems(importData);
}
}
});
// 设置选择多行
tab_product.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
}
}
|
package com.maxdota.wifiparty;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.net.NetworkInfo;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.maxdota.maxhelper.MaxHelper;
import com.maxdota.maxhelper.base.BaseActivity;
import com.maxdota.maxhelper.base.BaseApplication;
import com.maxdota.maxhelper.base.BaseFragment;
import com.maxdota.maxhelper.model.MaxAudioData;
import com.maxdota.wifiparty.adhoc.ChatAcceptThread;
import com.maxdota.wifiparty.adhoc.ChatSocketThread;
import com.maxdota.wifiparty.adhoc.SongAcceptThread;
import com.maxdota.wifiparty.adhoc.SongSocketThread;
import com.maxdota.wifiparty.adhoc.WiFiDirectBroadcastReceiver;
import com.maxdota.wifiparty.fragment.ChatFragment;
import com.maxdota.wifiparty.fragment.InfoFragment;
import com.maxdota.wifiparty.fragment.PartyPagerAdapter;
import com.maxdota.wifiparty.fragment.PlaylistFragment;
import com.maxdota.wifiparty.fragment.PrivateChatFragment;
import com.maxdota.wifiparty.model.ChatData;
import com.maxdota.wifiparty.model.LikeData;
import com.maxdota.wifiparty.model.MessageData;
import com.maxdota.wifiparty.model.NameListData;
import com.maxdota.wifiparty.model.PlaylistData;
import com.maxdota.wifiparty.model.PrivateChatData;
import com.maxdota.wifiparty.model.ReceivingSong;
import com.maxdota.wifiparty.model.SimpleMessage;
import com.maxdota.wifiparty.model.SongData;
import com.maxdota.wifiparty.model.SongPlayData;
import com.maxdota.wifiparty.model.SongRemoveData;
import com.maxdota.wifiparty.view.AddSongDialog;
import com.maxdota.wifiparty.view.PeerListAdapter;
import com.maxdota.wifiparty.view.RecyclerViewOnItemClickListener;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends BaseActivity implements WifiP2pManager.PeerListListener,
WifiP2pManager.ConnectionInfoListener, AddSongDialog.AddSongDialogListener,
MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, SensorEventListener {
public static final String ENCODING = "UTF-8";
public static final int BUFFER_SIZE = 7 * 1024;
public static final int CHAT_SOCKET_PORT = 8885;
public static final int SONG_SOCKET_PORT = 8865;
private static final int CONNECTION_TIMEOUT = 60000;
private static final int REQUEST_CODE_AUDIO_PICKER = 101;
private static final int REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSION = 102;
private static final int APP_STATUS_ADD_AUDIO = 1;
private static final float SHAKE_THRESHOLD = 5;
private static final int DANCING_TIME_INTERVAL = 7000;
private static final int SENSOR_TIME_INTERVAL = 100;
private static final int DANCING_CHECK_NUMBER = 6;
private String mWifiNamePrefix;
private String mWifiNameDivider;
private int mNextSongId;
private boolean mIsUserLeave;
private boolean mIsDestroyed;
private int mAppStatus;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
boolean isWifiP2pEnabled;
private ArrayList<WifiP2pDevice> mPeers;
private FloatingActionButton mCreateFab;
private View mMainContainer;
private View mConnectionContainer;
private RecyclerView mPeerList;
private View mPartyContainer;
private View mEmptyText;
private View mOutBackground;
private View mInBackground;
private PeerListAdapter mPeerListAdapter;
private boolean mIsInParty;
private boolean mIsHost;
private String mHostAddress;
private final Object mChatSocketsLock = new Object();
private ArrayList<ChatSocketThread> mChatSocketThreads;
private Handler mHandler;
private ChatSocketThread mHostChatSocketThread;
private boolean mIsRegisteringReceiver;
private ChatFragment mChatFragment;
private PlaylistFragment mPlaylistFragment;
private InfoFragment mInfoFragment;
private PartyPagerAdapter mPartyPagerAdapter;
private AddSongDialog mAddSongDialog;
private MaxAudioData mTempAudioData;
private MediaPlayer mMediaPlayer;
private final Object mQueuingAddSongsLock = new Object();
private ArrayList<SongData> mPendingSongs = new ArrayList<>();
private ArrayList<ReceivingSong> mQueueingAddedSongs = new ArrayList<>();
private HashMap<Long, SongData> mSongs;
private ArrayList<Long> mPlaylist;
private ReceivingSong mReceivingSong;
private SongAcceptThread mSongAcceptThread;
private long mTimeDifferenceWithHost;
private ChatAcceptThread mChatAcceptThread;
private PlaylistData mPlaylistData;
private Runnable mConnectionTimeoutCallback;
public String mDeviceName;
private SongSocketThread.SongSocketListener mSongSocketListener;
private final Object mUserNameLock = new Object();
private ArrayList<String> mUserNames;
private SensorManager mSensorManager;
private Sensor mSensor;
private long mLastSensorTime;
private float mLastX;
private float mLastY;
private float mLastZ;
private boolean mIsDancing;
private int mMovingCheck;
private long mMovingCheckAnchorTime;
private MenuItem mIndicatorItem;
private MenuItem mLeaveItem;
private TabLayout mTabLayout;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initUi();
initSensor();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mCreateFab = (FloatingActionButton) findViewById(R.id.create_fab);
mCreateFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name;
if (mDeviceName == null) {
name = "Unknown";
} else {
name = mDeviceName;
}
mMaxHelper.showInputDialog(MainActivity.this, "Create Room", "Enter room name", name,
new MaxHelper.InputDialog() {
@Override
public void onInput(final String text) {
String wifiName = getWifiName(text);
log("Wifi name: " + wifiName);
updateWifiName(wifiName, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
mDeviceName = text;
createParty();
}
@Override
public void onFailure(int reason) {
toast("Update name fails. Is it too long?");
}
});
}
@Override
public void onCancel() {
}
});
}
});
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), new WifiP2pManager.ChannelListener() {
@Override
public void onChannelDisconnected() {
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
}
});
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
}
private void initSensor() {
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
private void initData() {
if (MainApplication.IS_DEBUGGING) {
mMaxHelper.setLogLevel(MaxHelper.LogLevel.E);
}
mPrivateChatFragments = new ArrayList<>();
mWifiNamePrefix = getString(R.string.wifi_name_prefix);
mWifiNameDivider = getString(R.string.wifi_name_divider);
mNextSongId = 1;
mPeers = new ArrayList<>();
mHandler = new Handler();
mChatSocketThreads = new ArrayList<>();
mChatFragment = new ChatFragment();
mPlaylistFragment = new PlaylistFragment();
mInfoFragment = new InfoFragment();
mSongs = mPlaylistFragment.getSongs();
mPlaylist = mPlaylistFragment.getPlaylist();
mPlaylistData = new PlaylistData(mPlaylist);
mUserNames = new ArrayList<>();
mFragments = new ArrayList<>();
mFragments.add(mPlaylistFragment);
mFragments.add(mChatFragment);
mFragments.add(mInfoFragment);
mUpdateSongProgressRunnable = new Runnable() {
@Override
public void run() {
log("test 1: " + mMediaPlayer);
if (mMediaPlayer == null || mMediaPlayer != mCurrentTrackingProgress
|| !mMediaPlayer.isPlaying()) {
log("test return");
return;
}
mPlaylistFragment.updateSongProgress(mMediaPlayer.getCurrentPosition());
scheduleUpdateSongProgress();
log("schedule next");
}
};
}
private ArrayList<BaseFragment> mFragments;
private void initUi() {
mCircleLoader = findViewById(R.id.circle_loader);
mInBackground = findViewById(R.id.in_background);
mOutBackground = findViewById(R.id.out_background);
mPartyPagerAdapter = new PartyPagerAdapter(getSupportFragmentManager(), mFragments);
mViewPager = (ViewPager) findViewById(R.id.party_pager);
mTabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.setAdapter(mPartyPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setupWithViewPager(mViewPager);
mConnectionContainer = findViewById(R.id.connection_container);
mEmptyText = findViewById(R.id.empty_text);
mPartyContainer = findViewById(R.id.party_container);
mPeerList = (RecyclerView) findViewById(R.id.peer_list);
mMainContainer = findViewById(R.id.main_container);
mPeerListAdapter = new PeerListAdapter(mPeers, new RecyclerViewOnItemClickListener() {
@Override
public void onItemClicked(int position) {
connect(mPeers.get(position));
}
});
mPeerList.setLayoutManager(new LinearLayoutManager(this));
mPeerList.setAdapter(mPeerListAdapter);
}
private void goToPartyScreen(String hostAddress) {
log("go to party screen");
// current user is the host
if (hostAddress == null) {
openChatSocketAndWait();
mIsHost = true;
addUserName(mDeviceName);
} else {
mHostAddress = hostAddress;
connectToChatSocket();
mIsHost = false;
}
showParty();
}
// return false if duplicated
private boolean addUserName(String userName) {
synchronized (mUserNameLock) {
if (mUserNames.contains(userName)) {
return false;
}
mUserNames.add(userName);
mInfoFragment.addUser(userName);
return true;
}
}
public void discoverPeer() {
log("try to discover peer");
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
}
@Override
public void onFailure(int reasonCode) {
toast("Cannot see surrounding parties. Error " + reasonCode);
}
});
}
private void connect(WifiP2pDevice device) {
log("try to connect");
showCircleLoader();
addConnectionTimeout();
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
toast("Connecting to the party");
}
@Override
public void onFailure(int reason) {
hideCircleLoader();
toast("Connection failed. Error " + reason);
}
});
}
public void createParty() {
log("create party");
mManager.createGroup(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
toast("Create party success.");
goToPartyScreen(null);
}
@Override
public void onFailure(int reason) {
log("P2P group creation failed. Error " + reason);
}
});
}
public void removeParty() {
log("remove party");
mIsUserLeave = true;
mManager.removeGroup(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
toast("Leave party success.");
}
@Override
public void onFailure(int reason) {
log("P2P removal failed. Error " + reason);
}
});
hideParty();
}
@Override
protected void onResume() {
super.onResume();
mPeers.clear();
if (!mIsInParty) {
toggleWifiReceiver(true);
}
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
toggleWifiReceiver(false);
mSensorManager.unregisterListener(this);
super.onPause();
}
@Override
protected void onDestroy() {
log("onDestroy");
mIsDestroyed = true;
if (mIsInParty) {
clearConnections();
if (mManager != null) {
mManager.removeGroup(mChannel, null);
}
}
super.onDestroy();
}
private void clearConnections() {
if (mChatAcceptThread != null) {
mChatAcceptThread.closeSocket();
mChatAcceptThread = null;
if (mChatSocketThreads != null) {
synchronized (mChatSocketsLock) {
for (ChatSocketThread socketThread : mChatSocketThreads) {
socketThread.closeSocket();
}
mChatSocketThreads.clear();
}
}
}
if (mHostChatSocketThread != null) {
mHostChatSocketThread.write(new SimpleMessage(MessageData.MESSAGE_TYPE_LEAVE).toString());
mHostChatSocketThread.closeSocket();
mHostChatSocketThread = null;
}
if (mSongAcceptThread != null) {
mSongAcceptThread.closeSocket();
mSongAcceptThread = null;
}
}
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
Collection<WifiP2pDevice> refreshedPeers = peers.getDeviceList();
log("peers available: " + refreshedPeers.size());
if (!refreshedPeers.equals(mPeers)) {
mPeers.clear();
for (WifiP2pDevice peer : refreshedPeers) {
log("peer name: " + peer.deviceName);
String name = getNameFromWifiName(peer.deviceName);
if (name != null) {
peer.deviceName = name;
mPeers.add(peer);
}
}
mPeerListAdapter.notifyDataSetChanged();
}
if (mPeers.size() == 0) {
mEmptyText.setVisibility(View.VISIBLE);
mPeerList.setVisibility(View.GONE);
} else {
mEmptyText.setVisibility(View.GONE);
mPeerList.setVisibility(View.VISIBLE);
}
}
public void setWifiP2pEnabled(boolean wifiP2pEnabled) {
isWifiP2pEnabled = wifiP2pEnabled;
if (wifiP2pEnabled) {
log("Wifi P2P is enabled");
discoverPeer();
} else {
toast("Please enable Wifi and try again");
}
}
@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_main, menu);
mIndicatorItem = menu.getItem(0);
mLeaveItem = menu.getItem(1);
mLeaveItem.setVisible(mIsInParty);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_leave_party) {
removeParty();
return true;
} else if (id == R.id.action_indicator) {
mMaxHelper.showExplanationDialog(this, "Let's dance!");
return true;
}
return super.onOptionsItemSelected(item);
}
public void toast(final int resId) {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, resId, Toast.LENGTH_SHORT).show();
}
});
}
public void toast(final String message) {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
private void updateWifiName(String newName, WifiP2pManager.ActionListener listener) {
try {
log("Updating name: " + newName);
Class[] paramTypes = new Class[3];
paramTypes[0] = WifiP2pManager.Channel.class;
paramTypes[1] = String.class;
paramTypes[2] = WifiP2pManager.ActionListener.class;
Method setDeviceName = mManager.getClass().getMethod("setDeviceName", paramTypes);
setDeviceName.setAccessible(true);
Object arglist[] = new Object[3];
arglist[0] = mChannel;
arglist[1] = newName;
arglist[2] = listener;
setDeviceName.invoke(mManager, arglist);
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
@Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
log("onConnectionInfoAvailable");
if (!mIsInParty) {
if (info.isGroupOwner) {
String name = getNameFromWifiName(mDeviceName);
if (name == null) {
updateWifiName(getWifiName(mDeviceName), null);
}
goToPartyScreen(null);
} else {
if (info.groupOwnerAddress != null) {
goToPartyScreen(info.groupOwnerAddress.getHostAddress());
}
}
}
}
public void requestConnectionInfo(Intent intent) {
if (mManager == null) {
return;
}
log("requestConnectionInfo");
NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
mManager.requestConnectionInfo(mChannel, this);
}
}
private void addConnectionTimeout() {
mConnectionTimeoutCallback = new Runnable() {
@Override
public void run() {
if (!mIsInParty) {
mManager.removeGroup(mChannel, null);
hideCircleLoader();
mMaxHelper.showErrorDialog(MainActivity.this, "You are not authorised to join this party");
}
}
};
mHandler.postDelayed(mConnectionTimeoutCallback, CONNECTION_TIMEOUT);
}
private void connectToChatSocket() {
log("connectToChatSocket");
mHostChatSocketThread = new ChatSocketThread(mHostAddress);
mHostChatSocketThread.setOnChangesListener(new ChatSocketThread.OnChangesListener() {
@Override
public void onConnectionEstablished() {
showInputUserNameDialog();
}
@Override
public void onDataReceived(String data) {
processData(mHostChatSocketThread, data);
}
@Override
public void onConnectionLost() {
log("onConnectionLost");
resetPlaylistAndShowReconnectDialog();
}
});
mHostChatSocketThread.start();
hideCircleLoader();
}
private void resetPlaylistAndShowReconnectDialog() {
if (mIsDestroyed || mIsUserLeave) {
return;
}
resetMediaPlayer();
mPlaylistFragment.reset();
mMaxHelper.showYesNoDialog(this, "Cannot connect to the host", "Try Again",
"Leave", new MaxHelper.YesNoDialog() {
@Override
public void onSelected(boolean isYes) {
if (isYes) {
showCircleLoader();
connectToChatSocket();
} else {
removeParty();
}
}
});
}
private void openChatSocketAndWait() {
log("openChatSocketAndWait");
mChatAcceptThread = new ChatAcceptThread(new ChatAcceptThread.ConnectionListener() {
@Override
public void onNewConnection(Socket socket) {
final ChatSocketThread chatSocketThread = new ChatSocketThread(socket);
chatSocketThread.setOnChangesListener(new ChatSocketThread.OnChangesListener() {
@Override
public void onConnectionEstablished() {
synchronized (mChatSocketsLock) {
mChatSocketThreads.add(chatSocketThread);
}
chatSocketThread.write(new SimpleMessage(MessageData.MESSAGE_TYPE_INIT_TIME,
System.currentTimeMillis()).toString());
chatSocketThread.write(mPlaylistData.toString());
for (SongData song : mSongs.values()) {
chatSocketThread.write(song.toString());
}
}
@Override
public void onDataReceived(String data) {
processData(chatSocketThread, data);
}
@Override
public void onConnectionLost() {
log("onConnectionLost");
if (mSongAcceptThread != null && chatSocketThread.getIpAddress().equals(mSongAcceptThread.mIpAddress)) {
mSongAcceptThread.closeSocket();
mReceivingSong = null;
}
synchronized (mChatSocketsLock) {
mChatSocketThreads.remove(chatSocketThread);
sendMessageDataToAll(new SimpleMessage(MessageData.MESSAGE_TYPE_REMOVE_NAME,
chatSocketThread.mName));
}
Log.e("remove user", "user: " + chatSocketThread.mName);
synchronized (mUserNameLock) {
mUserNames.remove(chatSocketThread.mName);
}
mInfoFragment.removeUser(chatSocketThread.mName);
}
});
chatSocketThread.start();
}
});
mChatAcceptThread.start();
}
private void processData(ChatSocketThread socketThread, String rawData) {
MessageData messageData = MessageData.parseData(rawData);
if (messageData == null) {
return;
}
if (messageData instanceof ChatData) {
updateChatText((ChatData) messageData);
updateMessageToOthers(socketThread, rawData);
} else if (messageData instanceof SongData) {
final SongData songData = (SongData) messageData;
switch (songData.getMessageType()) {
case MessageData.MESSAGE_TYPE_ADD_SONG:
if (checkSongExistence(socketThread, songData)) {
if (!mIsHost && mMediaPlayer == null) {
mHostChatSocketThread.write(new SimpleMessage(MessageData.MESSAGE_TYPE_REQUEST_CURRENT_PLAYING).toString());
}
return;
}
if (mIsHost) {
// update song id
songData.mId = mNextSongId++;
mPlaylist.add(songData.mId);
socketThread.write(mPlaylistData.toString());
socketThread.write(new SongData(MessageData.MESSAGE_TYPE_UPDATE_SONG_ID, songData).toString());
}
// add an empty song holder
mPlaylistFragment.addSong(songData);
synchronized (mQueuingAddSongsLock) {
mQueueingAddedSongs.add(new ReceivingSong(socketThread.getIpAddress(),
songData));
checkToReceiveNextSong(socketThread);
}
break;
case MessageData.MESSAGE_TYPE_READY_RECEIVE_SONG:
log("request songId: " + songData.mId);
SongData requestSong = mSongs.get(songData.mId);
if (requestSong == null || requestSong.mPath == null) {
toast("Song is no longer valid");
socketThread.write(new SimpleMessage(MessageData.MESSAGE_TYPE_CLOSE_SONG_SOCKET).toString());
} else {
if (mSongSocketListener == null) {
mSongSocketListener = new SongSocketThread.SongSocketListener() {
@Override
public void onError(final String ipAddress, final String filePath) {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new SongSocketThread(ipAddress, filePath, mSongSocketListener).start();
}
}, 2000);
}
};
}
new SongSocketThread(socketThread.getIpAddress(),
requestSong.mPath, mSongSocketListener).start();
}
break;
case MessageData.MESSAGE_TYPE_UPDATE_SONG_ID:
final SongData song = SongData.findExactSongWithoutId(mPendingSongs, songData);
if (song == null) {
log("Cannot find song to update id");
} else {
song.mId = songData.mId;
mSongs.put(song.mId, song);
log("update songId: " + songData.mId);
mPlaylistFragment.refresh();
}
break;
}
} else if (messageData instanceof SimpleMessage) {
switch (messageData.getMessageType()) {
case MessageData.MESSAGE_TYPE_KICK:
toast("Unfortunately, you are kicked out of the party");
removeParty();
break;
case MessageData.MESSAGE_TYPE_CLOSE_SONG_SOCKET:
toast("Song is no longer valid");
mSongAcceptThread.closeSocket();
break;
case MessageData.MESSAGE_TYPE_REQUEST_CURRENT_PLAYING:
SongData songData = mPlaylistFragment.getSelectedSong();
if (songData != null && mMediaPlayer != null) {
socketThread.write(new SongPlayData(MessageData.MESSAGE_TYPE_CURRENT_PLAYING_SONG,
songData, mMediaPlayer.isPlaying(),
System.currentTimeMillis() - mMediaPlayer.getCurrentPosition()).toString());
}
break;
case MessageData.MESSAGE_TYPE_INIT_TIME:
SimpleMessage simpleMessage = (SimpleMessage) messageData;
mTimeDifferenceWithHost = simpleMessage.mExtraLong - System.currentTimeMillis();
break;
case MessageData.MESSAGE_TYPE_PAUSE_SONG:
if (mMediaPlayer != null) {
mMediaPlayer.pause();
}
break;
case MessageData.MESSAGE_TYPE_RESUME_SONG:
if (mMediaPlayer != null) {
mMediaPlayer.start();
scheduleUpdateSongProgress();
}
break;
case MessageData.MESSAGE_TYPE_INIT_NAME:
SimpleMessage nameMessage = (SimpleMessage) messageData;
if (mIsHost) {
if (addUserName(nameMessage.mExtraString)) {
updateMessageToOthers(socketThread, rawData);
socketThread.write(new NameListData(mUserNames).toString());
socketThread.mName = nameMessage.mExtraString;
} else {
socketThread.write(new SimpleMessage(MessageData.MESSAGE_TYPE_DUPLICATE_NAME).toString());
}
} else {
addUserName(nameMessage.mExtraString);
}
break;
case MessageData.MESSAGE_TYPE_DUPLICATE_NAME:
showInputUserNameDialog();
hideCircleLoader();
mMaxHelper.showErrorDialog(MainActivity.this, "Name already existed. Please choose another.");
break;
case MessageData.MESSAGE_TYPE_LEAVE:
log("closing left user socket");
socketThread.closeSocket();
break;
case MessageData.MESSAGE_TYPE_REMOVE_NAME:
SimpleMessage removeMessage = (SimpleMessage) messageData;
synchronized (mUserNames) {
mUserNames.remove(removeMessage.mExtraString);
}
mInfoFragment.removeUser(removeMessage.mExtraString);
break;
case MessageData.MESSAGE_TYPE_REARRANGE_PLAYLIST:
SimpleMessage rearrangeMessage = (SimpleMessage) messageData;
rearrangePlaylist(rearrangeMessage.mExtraInt, rearrangeMessage.mExtraBoolean);
break;
}
} else if (messageData instanceof SongPlayData) {
log("Update current playing song");
mHandler.removeCallbacks(mUpdateSongProgressRunnable);
SongPlayData songPlayData = (SongPlayData) messageData;
if (songPlayData.mIsPlaying) {
}
mPlaylistFragment.playSong(songPlayData);
} else if (messageData instanceof PlaylistData) {
PlaylistData playlistData = (PlaylistData) messageData;
mPlaylist.clear();
mPlaylist.addAll(playlistData.mPlaylist);
} else if (messageData instanceof SongRemoveData) {
SongRemoveData songRemoveData = (SongRemoveData) messageData;
if (mPlaylist.get(songRemoveData.mIndex) == songRemoveData.mId) {
mPlaylistFragment.removeSong(songRemoveData.mId, songRemoveData.mIndex);
}
} else if (messageData instanceof NameListData) {
NameListData nameListData = (NameListData) messageData;
mUserNames.clear();
mUserNames.addAll(nameListData.mNames);
mInfoFragment.setUserNames(mUserNames);
Log.e("name", mUserNames.toString());
hideCircleLoader();
} else if (messageData instanceof LikeData) {
LikeData likeData = (LikeData) messageData;
SongData songData = mSongs.get(likeData.getSongId());
songData.updateLike(likeData.isLike());
mPlaylistFragment.notifyAdapterChanges();
if (mIsHost) {
sendMessageDataToAll(likeData);
}
} else if (messageData instanceof PrivateChatData) {
PrivateChatData privateChatData = (PrivateChatData) messageData;
if (privateChatData.mTarget.equals(mDeviceName)) {
int fragmentIndex = findChatTabByName(privateChatData.mOwner);
PrivateChatFragment fragment;
if (fragmentIndex == -1) {
fragment = addTab(privateChatData.mOwner, false);
} else {
fragment = mPrivateChatFragments.get(fragmentIndex);
}
fragment.addChat(privateChatData.mOwner, privateChatData.mChat);
} else {
if (mIsHost) {
updateMessageToOthers(socketThread, rawData);
}
}
}
}
private void showInputUserNameDialog() {
mMaxHelper.showInputDialog(MainActivity.this, "Enter your name", "",
mDeviceName, new MaxHelper.InputDialog() {
@Override
public void onInput(String text) {
showCircleLoader();
mHostChatSocketThread
.write(new SimpleMessage(MessageData.MESSAGE_TYPE_INIT_NAME,
text).toString());
mDeviceName = text;
updateWifiName(text, null);
}
@Override
public void onCancel() {
removeParty();
}
});
}
// return true if the song exists
private boolean checkSongExistence(ChatSocketThread socketThread, final SongData songData) {
File file = new File(String.format(Locale.US, "%s/%s", SongAcceptThread.getDirPath(),
maxAudioFileName(songData.mTitle, songData.mArtist, songData.mExtension)));
if (file.exists()) {
log("song already existed, adding to the playlist");
songData.mPath = file.getPath();
if (mIsHost) {
songData.mId = mNextSongId++;
mPlaylist.add(songData.mId);
sendMessageData(mPlaylistData);
updateMessageToOthers(socketThread, songData.toString());
socketThread.write(new SongData(MessageData.MESSAGE_TYPE_UPDATE_SONG_ID, songData).toString());
}
mPlaylistFragment.addSong(songData);
return true;
}
return false;
}
private ChatSocketThread findChatSocketThread(String ipAddress) {
synchronized (mChatSocketsLock) {
for (ChatSocketThread socketThread : mChatSocketThreads) {
if (socketThread.getIpAddress().equals(ipAddress)) {
return socketThread;
}
}
}
return null;
}
private ChatSocketThread findChatSocketThreadByName(String name) {
synchronized (mChatSocketsLock) {
for (ChatSocketThread socketThread : mChatSocketThreads) {
if (socketThread.mName.equals(name)) {
return socketThread;
}
}
}
return null;
}
private void openSongSocketAndNotifySender(final ReceivingSong receivingSong) {
log("waiting for song");
mReceivingSong = receivingSong;
final ChatSocketThread socketThread;
if (mIsHost) {
socketThread = findChatSocketThread(mReceivingSong.mIpAddress);
if (socketThread == null) {
return;
}
} else {
socketThread = mHostChatSocketThread;
}
mSongAcceptThread = new SongAcceptThread(this, mReceivingSong.mSongData,
socketThread.getIpAddress(),
new SongAcceptThread.ConnectionListener() {
@Override
public void onFileReceived(final SongData song) {
log("Empty receiving song");
mReceivingSong = null;
checkToReceiveNextSong(socketThread);
if (mIsHost) {
updateMessageToOthers(socketThread, mPlaylistData.toString());
updateMessageToOthers(socketThread, song.toString());
}
mPlaylistFragment.refresh();
}
@Override
public void onSocketClosed(SongData song) {
if (mReceivingSong != null && mReceivingSong.mSongData.mId == song.mId) {
mReceivingSong = null;
checkToReceiveNextSong(socketThread);
}
}
});
mSongAcceptThread.start();
// send confirm ready to receive song message
socketThread.write(new SongData(MessageData.MESSAGE_TYPE_READY_RECEIVE_SONG,
mReceivingSong.mSongData).toString());
}
private void checkToReceiveNextSong(ChatSocketThread socketThread) {
synchronized (mQueuingAddSongsLock) {
if (mQueueingAddedSongs.size() > 0) {
log("Processing next song");
ReceivingSong receivingSong = mQueueingAddedSongs.get(0);
if (checkSongExistence(socketThread, receivingSong.mSongData)) {
mQueueingAddedSongs.remove(0);
checkToReceiveNextSong(socketThread);
} else {
// only receive next song when there is no receiving in progress
if (mReceivingSong == null) {
mReceivingSong = receivingSong;
mQueueingAddedSongs.remove(0);
openSongSocketAndNotifySender(mReceivingSong);
}
}
} else {
if (!mIsHost && mMediaPlayer == null) {
mHostChatSocketThread.write(new SimpleMessage(MessageData.MESSAGE_TYPE_REQUEST_CURRENT_PLAYING).toString());
}
}
}
}
private void updateMessageToOthers(ChatSocketThread exception, String data) {
synchronized (mChatSocketsLock) {
for (ChatSocketThread socketThread : mChatSocketThreads) {
if (socketThread != exception) {
socketThread.write(data + MessageData.MESSAGE_SUFFIX);
}
}
}
}
private void showParty() {
if (mConnectionTimeoutCallback != null) {
mHandler.removeCallbacks(mConnectionTimeoutCallback);
mConnectionTimeoutCallback = null;
}
hideCircleLoader();
if (mLeaveItem != null) {
mLeaveItem.setVisible(true);
}
mPlaylistFragment.tryToUpdateViews();
mInfoFragment.tryToUpdateViews();
mPartyContainer.setVisibility(View.VISIBLE);
mConnectionContainer.setVisibility(View.GONE);
mCreateFab.setVisibility(View.GONE);
mOutBackground.setVisibility(View.GONE);
mInBackground.setVisibility(View.VISIBLE);
mIsUserLeave = false;
mIsInParty = true;
toggleWifiReceiver(false);
}
private void hideParty() {
mReceivingSong = null;
clearConnections();
// reset device name to normal
if (mIsHost) {
if (mDeviceName != null) {
updateWifiName(mDeviceName, null);
}
}
deletePersistentGroups();
synchronized (mUserNameLock) {
mUserNames.clear();
}
mInfoFragment.clearUsers();
mHandler.post(new Runnable() {
@Override
public void run() {
if (mLeaveItem != null) {
mLeaveItem.setVisible(false);
}
resetMediaPlayer();
mChatFragment.clearChat();
synchronized (mPrivateChatFragmentsLock) {
for (int i = 0; i < mPrivateChatFragments.size(); i++) {
mPartyPagerAdapter.remove(i + 3);
}
mPrivateChatFragments.clear();
}
mViewPager.setCurrentItem(0);
mPlaylistFragment.reset();
mPartyContainer.setVisibility(View.GONE);
mConnectionContainer.setVisibility(View.VISIBLE);
mCreateFab.setVisibility(View.VISIBLE);
mOutBackground.setVisibility(View.VISIBLE);
mInBackground.setVisibility(View.GONE);
mIsInParty = false;
toggleWifiReceiver(true);
}
});
}
private void resetMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
log("test remove call back");
mHandler.removeCallbacks(mUpdateSongProgressRunnable);
}
}
private void toggleWifiReceiver(boolean isRegister) {
if (isRegister && !mIsRegisteringReceiver) {
log("registerReceiver");
registerReceiver(mReceiver, mIntentFilter);
mIsRegisteringReceiver = true;
} else if (!isRegister && mIsRegisteringReceiver) {
log("unregisterReceiver");
unregisterReceiver(mReceiver);
mIsRegisteringReceiver = false;
}
}
public void updateChatText(final ChatData data) {
mChatFragment.addChat(data.getOwner(), data.getMessage());
}
public void sendChat(String message) {
if (!mIsInParty || TextUtils.isEmpty(message)) {
return;
}
ChatData chatData = new ChatData(message, 1, mDeviceName);
sendMessageData(chatData);
updateChatText(chatData);
}
private void sendMessageDataToAll(MessageData messageData) {
synchronized (mChatSocketsLock) {
for (ChatSocketThread socketThread : mChatSocketThreads) {
socketThread.write(messageData.toString());
}
}
}
private void sendMessageData(MessageData messageData) {
if (mIsHost) {
sendMessageDataToAll(messageData);
} else {
sendDataToHost(messageData);
}
}
private void sendDataToHost(MessageData messageData) {
if (mHostChatSocketThread != null) {
mHostChatSocketThread.write(messageData.toString());
}
}
public void tryToAddSong() {
if (mMaxHelper.checkAndRequestPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE,
"The app needs to read your external storage to allow you to add song.\nPlease grant the permission.",
REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSION)) {
addSong();
} else {
mAppStatus = APP_STATUS_ADD_AUDIO;
}
}
private void addSong() {
mMaxHelper.showAudioPicker(this, REQUEST_CODE_AUDIO_PICKER);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (mAppStatus == APP_STATUS_ADD_AUDIO) {
if (mMaxHelper.onRequestPermissionsResult(requestCode, grantResults,
REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSION)) {
addSong();
} else {
toast("Permission denied. Cannot add song");
}
mAppStatus = -1;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE_AUDIO_PICKER) {
String path = mMaxHelper.getAudioPath(this, data.getData());
if (path != null) {
try {
MaxAudioData audioData = mMaxHelper.retrieveAudioData(path);
if (mAddSongDialog == null) {
mAddSongDialog = new AddSongDialog(this, this);
}
updateAudioDataFromFileName(audioData, path);
mTempAudioData = audioData;
mAddSongDialog.display(audioData);
} catch (RuntimeException ex) {
toast("Invalid file data. Unable to read.");
}
}
}
}
}
public String maxAudioFileName(String title, String artist, String extension) {
return String.format("%s - %s%s", title, artist, extension);
}
// return new file
public File renameFile(File file, String parentDir, String title, String artist, String extension,
String durationTime) {
String newName = maxAudioFileName(title, artist, extension);
String newPath = String.format(Locale.US, "%s/%s", parentDir, newName);
File renamedFile = new File(newPath);
file.renameTo(renamedFile);
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.DATA, newPath);
values.put(MediaStore.Audio.Media.TITLE, title);
values.put(MediaStore.Audio.Media.ARTIST, artist);
values.put(MediaStore.Audio.Media.DURATION, durationTime);
ContentResolver contentResolver = getContentResolver();
int updatedRows = contentResolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
values,
MediaStore.Images.Media.DATA + "=?",
new String[]{file.getPath()});
if (updatedRows == 0) {
values.put(MediaStore.Audio.Media.ALBUM, BaseApplication.sAppName);
contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
}
return renamedFile;
}
private void updateAudioDataFromFileName(MaxAudioData audioData, String path) {
String fileName = path.substring(path.lastIndexOf('/') + 1);
int dividerIndex = fileName.indexOf(" - ");
int extensionIndex = fileName.indexOf('.');
if (dividerIndex != -1 && extensionIndex != -1 && dividerIndex < extensionIndex) {
String title = fileName.substring(0, dividerIndex);
String artist = fileName.substring(dividerIndex + 3, extensionIndex);
audioData.setTitle(title);
audioData.setArtist(artist);
}
}
@Override
public void onSongAdded(String songName, String artist) {
File songFile = new File(mTempAudioData.getPath());
String extension = SongData.getFileExtension(songFile.getName());
if (!songName.equals(mTempAudioData.getTitle()) || !artist.equals(mTempAudioData.getArtist())) {
mTempAudioData.setTitle(songName);
mTempAudioData.setArtist(artist);
songFile = renameFile(songFile, songFile.getParent(), songName, artist, extension,
mTempAudioData.getDurationTimeString());
mTempAudioData.setPath(songFile.getPath());
try {
AudioFile f = AudioFileIO.read(songFile);
Tag tag = f.getTag();
if (tag == null) {
toast("Invalid media data. Cannot update song info.");
} else {
tag.setField(FieldKey.TITLE, songName);
tag.setField(FieldKey.ARTIST, artist);
f.commit();
}
} catch (CannotReadException | TagException |
CannotWriteException | IOException | ReadOnlyFileException e) {
log("read error: " + e.getMessage());
} catch (InvalidAudioFrameException e) {
toast("Invalid media data. Cannot update song info.");
}
}
SongData song = new SongData(MessageData.MESSAGE_TYPE_ADD_SONG, mTempAudioData, extension);
if (mIsHost) {
song.mId = mNextSongId++;
mPlaylistFragment.addNewSong(song);
sendMessageData(mPlaylistData);
} else {
mPendingSongs.add(song);
}
sendMessageData(song);
}
public void onSongRemoved(long songId, int songIndex) {
SongRemoveData songRemoveData = new SongRemoveData(songId, songIndex);
sendMessageDataToAll(songRemoveData);
}
@Override
public void onCompletion(MediaPlayer mp) {
if (mMediaPlayer != null && mMediaPlayer == mp) {
mPlaylistFragment.playNextSong();
}
}
// return true if that song is played
public boolean songSelected(SongData song) {
if (!mIsHost) {
return false;
}
if (!song.isReady()) {
toast("Song is not ready yet");
return false;
}
playSong(song);
SongPlayData songPlayData = new SongPlayData(MessageData.MESSAGE_TYPE_CURRENT_PLAYING_SONG, song);
sendMessageDataToAll(songPlayData);
return true;
}
// return song current time progress
public int playSong(SongData song, long startedAt) {
if (song.mPath == null) {
toast("Song is not ready yet");
return -1;
}
final int startTime = startedAt == -1 ? 0 : (int) (getHostCurrentTime() - startedAt);
MediaPlayer.OnPreparedListener completionListener = new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mp == mMediaPlayer) {
log("on prepare complete " + mp);
mp.seekTo(startTime);
mp.start();
scheduleUpdateSongProgress();
}
}
};
mMediaPlayer = mMaxHelper.prepareAudio(song.mPath, completionListener, this, this);
mCurrentTrackingProgress = mMediaPlayer;
log("set current tracking: " + mCurrentTrackingProgress);
if (mMediaPlayer == null) {
mPlaylistFragment.handleSongError();
}
return startTime;
}
// startAt = -1 means playing the song from the beginning
// return song start time
public int prepareSong(SongData song, long startedAt) {
if (song.mPath == null) {
toast("Song is not ready yet");
return -1;
}
final int startTime = (int) (getHostCurrentTime() - startedAt);
mMediaPlayer = mMaxHelper.prepareAudio(song.mPath, new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mp == mMediaPlayer) {
mp.seekTo(startTime);
mCurrentTrackingProgress = mMediaPlayer;
scheduleUpdateSongProgress();
}
}
}, this, this);
if (mMediaPlayer == null) {
mPlaylistFragment.handleSongError();
}
return startTime;
}
private MediaPlayer mCurrentTrackingProgress;
private Runnable mUpdateSongProgressRunnable;
private void scheduleUpdateSongProgress() {
mHandler.postDelayed(mUpdateSongProgressRunnable, 200);
}
public void playSong(SongData song) {
playSong(song, -1);
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (mMediaPlayer == mp) {
mPlaylistFragment.handleSongError();
resetMediaPlayer();
}
return true;
}
public void onPlaylistEnded() {
toast("End of the playlist");
resetMediaPlayer();
}
public void onPlayControlClicked() {
boolean isPlaying = false;
if (mMediaPlayer == null) {
if (mPlaylist.isEmpty()) {
toast("No song to play. Please add a song");
} else {
mPlaylistFragment.onSongSelected(0);
return;
}
} else {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
sendMessageData(new SimpleMessage(MessageData.MESSAGE_TYPE_PAUSE_SONG));
} else {
mMediaPlayer.start();
scheduleUpdateSongProgress();
isPlaying = true;
sendMessageData(new SimpleMessage(MessageData.MESSAGE_TYPE_RESUME_SONG));
}
}
mPlaylistFragment.updatePlayControl(isPlaying);
}
public void onReceiveDeviceName(String deviceName) {
if (mDeviceName != null) {
return;
}
String name = getNameFromWifiName(deviceName);
if (name == null) {
name = deviceName;
} else {
updateWifiName(name, null);
}
mDeviceName = name;
}
public long getHostCurrentTime() {
return System.currentTimeMillis() + mTimeDifferenceWithHost;
}
public boolean isHost() {
return mIsHost;
}
private String getWifiName(String name) {
return getString(R.string.wifi_name_format, SecurityHelper.encode(name), name);
}
// return null if deviceName does not fit the pattern
private String getNameFromWifiName(String deviceName) {
if (deviceName.startsWith(mWifiNamePrefix)) {
int dividerIndex = deviceName.indexOf(mWifiNameDivider, mWifiNamePrefix.length());
if (dividerIndex != -1) {
String name;
if (dividerIndex + 1 < deviceName.length()) {
name = deviceName.substring(dividerIndex + 1);
} else {
name = "";
}
if (getWifiName(name).equals(deviceName)) {
return name;
}
}
}
return null;
}
// this method is used to forget all wifi-direct connections
// in order to show request dialog again
// http://stackoverflow.com/questions/15152817/can-i-change-the-group-owner-in-a-persistent-group-in-wi-fi-direct/26242221#26242221
private void deletePersistentGroups() {
try {
Method[] methods = WifiP2pManager.class.getMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals("deletePersistentGroup")) {
// Delete any persistent group
// Maximum remembered group is 32
for (int netId = 0; netId < 32; netId++) {
methods[i].invoke(mManager, mChannel, netId, null);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];
long sensorTime = System.currentTimeMillis();
if (mLastSensorTime == 0) {
// init time for the 1st time
mLastSensorTime = sensorTime;
mMovingCheckAnchorTime = sensorTime;
}
if (sensorTime - mLastSensorTime < SENSOR_TIME_INTERVAL) {
return;
}
if (sensorTime - mMovingCheckAnchorTime > DANCING_TIME_INTERVAL) {
if (mMovingCheck < DANCING_CHECK_NUMBER) {
mIsDancing = false;
updateDancingIndicator();
}
// reset
mMovingCheck = 0;
mMovingCheckAnchorTime = sensorTime;
} else {
long diffTime = (sensorTime - mLastSensorTime);
mLastSensorTime = sensorTime;
float speed = Math.abs(x + y + z - mLastX - mLastY - mLastZ) / diffTime * SENSOR_TIME_INTERVAL;
if (speed > SHAKE_THRESHOLD) {
mMovingCheck++;
if (mMovingCheck == DANCING_CHECK_NUMBER) {
mIsDancing = true;
updateDancingIndicator();
}
}
}
mLastX = x;
mLastY = y;
mLastZ = z;
mLastSensorTime = sensorTime;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void updateDancingIndicator() {
if (mIndicatorItem != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
mIndicatorItem.setIcon(mIsDancing ? R.drawable.ic_dancing : R.drawable.ic_standing);
}
});
}
}
public void sendLikeData(SongData song, boolean isLike) {
if (isLike && !mIsDancing) {
mMaxHelper.showErrorDialog(this, "You need to dance in order to vote for a song");
return;
}
song.mIsLiked = isLike;
mPlaylistFragment.notifyAdapterChanges();
sendDataToHost(new LikeData(mDeviceName, isLike, song.mId));
}
public void rearrangePlaylist(int position, boolean isUp) {
int selected = mPlaylistFragment.getSelectedIndex();
int swapPosition = isUp ? position - 1 : position + 1;
if (swapPosition < 0 || swapPosition >= mPlaylist.size()) {
return;
}
// swapping 2 song ids
long tempId = mPlaylist.get(position);
mPlaylist.set(position, mPlaylist.get(swapPosition));
mPlaylist.set(swapPosition, tempId);
// update current playing song ui
if (selected == swapPosition) {
selected = position;
} else if (selected == position) {
selected = swapPosition;
}
mPlaylistFragment.updateRearrangedPlaylist(selected);
if (mIsHost) {
sendMessageDataToAll(new SimpleMessage(MessageData.MESSAGE_TYPE_REARRANGE_PLAYLIST,
position, isUp));
}
}
private final Object mPrivateChatFragmentsLock = new Object();
private ArrayList<PrivateChatFragment> mPrivateChatFragments;
private int findChatTabByName(String name) {
synchronized (mPrivateChatFragmentsLock) {
for (int i = 0; i < mPrivateChatFragments.size(); i++) {
PrivateChatFragment fragment = mPrivateChatFragments.get(i);
if (fragment.getName().equals(name)) {
return i;
}
}
return -1;
}
}
public void checkAndAddTab(String userName) {
int tabIndex = findChatTabByName(userName);
if (tabIndex == -1) {
// add tab if not existed
addTab(userName, true);
} else {
// ignore 3 default tabs
mViewPager.setCurrentItem(tabIndex + 3);
}
}
private PrivateChatFragment addTab(String userName, final boolean isSwitchToTab) {
final PrivateChatFragment fragment = new PrivateChatFragment();
fragment.setData(userName);
mHandler.post(new Runnable() {
@Override
public void run() {
synchronized (mPrivateChatFragmentsLock) {
mPrivateChatFragments.add(fragment);
mPartyPagerAdapter.addFragment(fragment);
}
if (isSwitchToTab) {
// the last tab is this newly added one
mViewPager.setCurrentItem(mPartyPagerAdapter.getCount() - 1);
}
}
});
return fragment;
}
public void sendPrivateChat(final PrivateChatFragment fragment, String message) {
String target = fragment.getName();
boolean isExist = false;
synchronized (mUserNameLock) {
for (String userName : mUserNames) {
if (userName.equals(target)) {
isExist = true;
break;
}
}
}
if (!isExist) {
mMaxHelper.showYesNoDialog(this, "User is no longer in room", "Remove conversation",
"Leave it be", new MaxHelper.YesNoDialog() {
@Override
public void onSelected(boolean isYes) {
if (isYes) {
synchronized (mPrivateChatFragmentsLock) {
int fragmentIndex = mPrivateChatFragments.indexOf(fragment);
mPrivateChatFragments.remove(fragmentIndex);
mPartyPagerAdapter.remove(fragmentIndex);
mViewPager.setCurrentItem(0);
}
}
}
});
return;
}
PrivateChatData chatData = new PrivateChatData(message, 1, mDeviceName, target);
sendMessageData(chatData);
fragment.addChat(chatData.mOwner, chatData.mChat);
}
public void kickUser(String name) {
final ChatSocketThread socket = findChatSocketThreadByName(name);
if (socket != null) {
socket.write(new SimpleMessage(MessageData.MESSAGE_TYPE_KICK).toString());
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
socket.closeSocket();
}
}, 2000);
synchronized (mUserNameLock) {
mUserNames.remove(name);
mInfoFragment.removeUser(name);
}
}
}
}
|
package com.it306.test;
/**
* This is the chance cell. More methods and arguments to be added.
* @author Amith Kini
*
*/
public class ChanceCell extends Cell {
public ChanceCell(int pos) {
setPosition(pos);
setName("Chance");
setBuyable(false);
setColourGroup("None");
setChance(true);
}
}
|
/**
* @author xinjian.ai
* @desc 可重入锁测试
* @date 2021-03-08 17:22:56
*/
public class ReentrantLockTest {
}
|
package lka.wine.jdbc;
import java.util.ArrayList;
import java.util.List;
import lka.wine.dao.WineCellar;
public class WineCellarQuery implements Restable<WineCellar> {
@Override
public List<WineCellar> select() throws Exception {
List<WineCellar> wineCellars = new ArrayList<WineCellar>();
WineCellar wineCellar = new WineCellar();
wineCellar.setBrands(new BrandsTable().select());
wineCellar.setLocations(new LocationsTable().select());
wineCellar.setLocationTypes(new LocationTypesTable().select());
wineCellar.setPurchases(new PurchasesTable().select());
wineCellar.setRegions(new RegionsTable().select());
wineCellar.setTastingNotes(new TastingNotesTable().select());
wineCellar.setVarietals(new VarietalsTable().select());
wineCellar.setVineyards(new VineyardsTable().select());
wineCellar.setWines(new WinesTable().select());
wineCellars.add(wineCellar);
return wineCellars;
}
@Override
public WineCellar select(int id) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public int insert(WineCellar obj) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public int update(WineCellar obj) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public int delete(WineCellar obj) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public int delete(int id) throws Exception {
throw new UnsupportedOperationException();
}
}
|
public class Driver {
public static void main(String[] args) {
LinkedCircList<String> L1 = new LinkedCircList<>();
L1.insert("jim");
L1.insert("jane");
L1.insert("jack");
L1.insert("june");
L1.insert("jason");
L1.insert("jean");
L1.insert("joe");
L1.insert("jeremy");
L1.insert("janelle");
System.out.println(Josephus.count_off(L1, 5));
}
}
|
package com.krixon.ecosystem.authservice.domain;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import java.util.HashMap;
import java.util.Map;
public class StandardTokenEnhancer implements TokenEnhancer
{
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication)
{
Map<String, Object> additionalInfo = new HashMap<>();
Object principal = authentication.getPrincipal();
if (principal instanceof User) {
additionalInfo.put("username", ((User) principal).getUsername());
additionalInfo.put("roles", ((User) principal).getAuthorities().stream().map(Object::toString));
}
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
}
|
package meli.tmr.solarsystem;
import meli.tmr.solarsystem.daos.implementations.WeatherReportDAOImpl;
import meli.tmr.solarsystem.daos.interfaces.DayWeatherDAO;
import meli.tmr.solarsystem.exceptions.SolarSystemException;
import meli.tmr.solarsystem.exceptions.YearsException;
import meli.tmr.solarsystem.models.*;
import meli.tmr.solarsystem.services.CalculatorUtil;
import meli.tmr.solarsystem.services.WeatherService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Arrays;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
@SpringBootTest
public class TestSolarSystem {
@Mock
private DayWeatherDAO dayWeatherDAO;
@Mock
private WeatherReportDAOImpl weatherReportDAO;
@Autowired
@InjectMocks
private WeatherService weatherService;
@Autowired
private CalculatorUtil calculatorUtil;
@Test
void testGetReportMoreThan10YearsException() {
SolarSystem solarSystem = new SolarSystem(AppInitializator.buildPlanetList());
Assertions.assertThrows(YearsException.class, () -> weatherService.getWeatherReport(solarSystem, 99));
}
@Test
void testGetReportLessThan1YearException() {
SolarSystem solarSystem = new SolarSystem(AppInitializator.buildPlanetList());
Assertions.assertThrows(YearsException.class, () -> weatherService.getWeatherReport(solarSystem, -1));
}
@Test
void testCreateSolarSystemWithTwoPlanetsException() {
Planet planet1 = new Planet("planet1", 1,1,true);
Planet planet2 = new Planet("planet2", 1,1,true);
Assertions.assertThrows(SolarSystemException.class, () -> new SolarSystem(Arrays.asList(planet1, planet2)));
}
@Test
void testAddPlanetsToSolarSystemException() {
Planet planet1 = new Planet("planet1", 1,1,true);
Planet planet2 = new Planet("planet2", 1,1,true);
Planet planet3 = new Planet("planet3", 1,1,true);
Planet planet4 = new Planet("planet4", 1,1,true);
SolarSystem solarSystem = new SolarSystem();
solarSystem.addPlanet(planet1);
solarSystem.addPlanet(planet2);
solarSystem.addPlanet(planet3);
Assertions.assertThrows(SolarSystemException.class, () -> solarSystem.addPlanet(planet4));
}
@Test
void testWeatherIn10Years() {
doNothing().when(dayWeatherDAO).save(any(DayWeather.class));
doNothing().when(weatherReportDAO).save(any(WeatherReport.class));
SolarSystem solarSystem = new SolarSystem(AppInitializator.buildPlanetList());
WeatherReport reporte = weatherService.getWeatherReport(solarSystem,10);
Assertions.assertEquals(40 ,reporte.getDiasDeSequia(),0.01);
Assertions.assertEquals(1188 ,reporte.getDiasDeLluvia(),0.01);
Assertions.assertEquals(72 ,reporte.getDiaDeMayorLluvia(),0.01);
Assertions.assertEquals(204 ,reporte.getDiasOptimos(),0.01);
}
@Test
void testCalculatorUtilCos90(){
Assertions.assertEquals(0, CalculatorUtil.getCos(90),0.01);
}
@Test
void testCalculatorUtilSin90(){
Assertions.assertEquals(1, CalculatorUtil.getSin(90),0.01);
}
@Test
void testCalculatorUtilCos80(){
Assertions.assertEquals(0.17, CalculatorUtil.getCos(80),0.01);
}
@Test
void testAreInline(){
Assertions.assertTrue(calculatorUtil.areInline(new Position(2, 4), new Position(4,6), new Position(6,8)));
}
}
|
/**
* This is a chat bot that interacts with the user. By asking question
* and using the scanner object, the program is able to get user input
* and do other actions based on the input.
*
* @author Collin Wen
* @version 1.0
*/
import java.util.Scanner;
public class ChatBot {
/*
This is the main method that the java interpreter calls
@param args This is a command line argument
*/
public static void main(String[] args) {
//construct/create a new Scanner object
Scanner kb = new Scanner(System.in);
//find name
System.out.println("enter name");
String input = kb.nextLine();
checkBye(input);
String name = input;
//how are you doing today?
System.out.println("hi " + name + "! How are you doing today?");
input = kb.nextLine();
checkBye(input);
//how old are you?
System.out.println("Your answer is " + input);
System.out.println("How old are you?");
input = kb.nextLine();
checkBye(input);
int age = Integer.parseInt(input);
if(age > 30) {
System.out.println(name + ", you are old!");
} else {
System.out.println("nice!");
}
//how tall are you
System.out.println("How tall are you? ");
input = kb.nextLine();
double height = Double.parseDouble(input);
if(height > 6.0) {
System.out.println(name + ", you are tall!");
} else if(height > 5.0) {
System.out.println("not bad, " + name);
} else {
System.out.println(name + ", you're short");
}
//favorite color
System.out.print("What is your fav color?");
String color = kb.nextLine();
checkBye(color);
System.out.println(color + " is your fave!");
//story
System.out.println("Tell me what you did today! Type 'done' when your finished.");
while(true) {
input = kb.nextLine();
checkBye(input);
if(input.equals("done")) {
System.out.println("Interesting! Thanks for sharing!");
break;
}
System.out.println("Really! Tell me more!");
}
}
/**
* This method checks if a string equals "bye" or "Bye" and then
* quits the program if true.
*
* @param input The string that you want to check
* @return nothing
*/
public static void checkBye(String input) {
if(input.equals("bye") || input.equals("Bye")) {
System.exit(0);
}
}
}
|
package quick;
public class QuickSort {
public static void quickSort(int[] array, int left, int right) {
// 前提是left < right
if(left < right) {
int i = left;
int j = right;
// x暂时取第一个值
int x = array[i];
while(i < j) {
while(i < j && x < array[j]) {
j--;
}
if(i < j) {
array[i++] = array[j];
}
while(i < j && array[i] < x) {
i++;
}
if(i < j) {
array[j--] = array[i];
}
}
array[i] = x;
// 递归
quickSort(array, left, i - 1);
quickSort(array, i + 1, right);
}
}
public static void main(String[] args) {
int[] array = {2,1,2,3};
for(int a : array) {
System.out.print(a + " ");
}
quickSort(array, 0, array.length - 1);
System.out.println();
for(int a : array) {
System.out.print(a + " ");
}
}
}
|
package io.gtrain.domain.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.StringJoiner;
/**
* @author William Gentry
*/
@Document(collection = "verification")
public class Verification {
@Id
private String id;
@Indexed(unique = true)
private final String username;
@PersistenceConstructor
public Verification(String username) {
this.username = username;
}
// Convenience constructor for testing
public Verification(String id, String username) {
this.id = id;
this.username = username;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
@Override
public String toString() {
return new StringJoiner(", ", Verification.class.getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("username='" + username + "'")
.toString();
}
}
|
package com.fbzj.track.model;
import java.util.Date;
/**
* 令牌
*/
public class Token {
/**
* 访问令牌
*/
private String accessToken;
/**
* 有效期,单位秒
*/
private int expiresIn;
/**
* 创建时间
*/
private Date time;
public Token(){
this.accessToken = "";
this.expiresIn = 0;
this.time = new Date();
}
public Token(String accessToken,int expiresIn ){
this.accessToken = accessToken;
this.expiresIn = expiresIn;
this.time = new Date();
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
|
package DataStructure.Tree;
public class BinarySearchTree {
Node root; // variable define will initailised when object is created with default constructor
BinarySearchTree() {
root = null;
}
/*
8
/\
4 12
/\ /\
1 7 9 14
*/
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insertNode(8);
tree.insertNode(4);
tree.insertNode(1);
tree.insertNode(12);
tree.insertNode(9);
tree.insertNode(7);
tree.insertNode(14);
// System.out.println("Data you are looking for ::"+tree.search(tree.root,1));
tree.deleteKey(12);
}
private void deleteKey(int key) {
root = deleteNode(root, key);
}
private Node deleteNode(Node root, int key) {
if (root == null) return root;
if (key < root.key) {
root.left = deleteNode(root.left, key);
}
else if (key > root.key) {
root.right = deleteNode(root.right, key);
}else {
if(root.left==null && root.right==null){
return null;
}else if( root.left ==null){
return root.right;
}else if( root.right ==null){
return root.left;
} else {
int minVal= minValue(root.right);
root.key=minVal;
root.right=deleteNode(root.right,minVal);
}
}
}
private void insertNode(int key) {
root = insertHelper(root, key);
}
Node insertHelper(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.key) {
root.left = insertHelper(root.left, key);
} else if (key > root.key) {
root.right = insertHelper(root.right, key);
}
return root;
}
}
|
package mc.kurunegala.bop.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
@Controller
public class HelloController extends AbstractController {
@RequestMapping("/welcome")
protected ModelAndView handleRequestInternal(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
return new ModelAndView("hello");
}
}
|
package com.cd.hrm.mapper;
import com.cd.hrm.domain.CourseType;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* 课程目录 Mapper 接口
* </p>
*
* @author cd
* @since 2019-09-01
*/
public interface CourseTypeMapper extends BaseMapper<CourseType> {
}
|
import javax.swing.*;
import java.awt.*;
import static java.lang.Thread.sleep;
public class XOGame extends JFrame {
Result result;
BattleMap battleMap;
Setting settingWindow;
public XOGame() {
setBounds(300, 200, 600, 630);
setTitle("XOGame");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
result = new Result(500, 300);
battleMap = new BattleMap();
add(battleMap, BorderLayout.CENTER);
JLabel infoLabel = new JLabel();
infoLabel.setFont(new Font("Arial", Font.BOLD, 24));
infoLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(infoLabel, BorderLayout.NORTH);
JPanel downPanel = new JPanel();
downPanel.setLayout(new GridLayout(1, 1));
JButton btnExit = new JButton("Exit");
btnExit.setBackground(Color.pink);
downPanel.add(btnExit);
add(downPanel, BorderLayout.SOUTH);
btnExit.addActionListener(e -> System.exit(0));
settingWindow = new Setting(500,300);
while (true) {
while (result.isVisible()){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (!result.isVisible()) {
settingWindow.setVisible(true);
while (settingWindow.isVisible()){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
setVisible(true);
infoLabel.setText("You need aline "+settingWindow.dotsToWin +" X or O to win" );
start(settingWindow.size, settingWindow.dotsToWin);
}
}
}
public void start(int size, int dotsToWin) {
Logic.SIZE = size;
Logic.DOTS_TO_WIN = dotsToWin;
Logic.initMap();
battleMap.repaintMap(size);
Logic.printMap();
printMap(Logic.SIZE);
System.out.println("start...");
while (true) {
do {
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!Logic.playerOneFinished);
Logic.playerOneFinished = false;
Logic.printMap();
printMap(Logic.SIZE);
if (Logic.checkWin(Logic.playerOne)) {
System.out.println("Игрок победил!!!");
showResult("You won!!!");
return;
}
if (Logic.isFull()) {
System.out.println("Ничья, не осталось места ходить!");
showResult("Dead heat, the map is full");
return;
}
Logic.aiTurn();
Logic.printMap();
printMap(Logic.SIZE);
if (Logic.checkWin(Logic.playerTwo)) {
System.out.println("Компьютер победил!!!");
showResult("Artificial intelligence has won");
return;
}
if (Logic.isFull()) {
System.out.println("Ничья, не осталось места ходить!");
showResult("Dead heat, the map is full");
return;
}
}
}
public void printMap(int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
battleMap.btns[i][j].setText("" + Logic.map[i][j]);
}
}
}
void showResult(String text) {
result.setText(text);
result.setVisible(true);
}
}
|
/**
* Sencha GXT 3.0.1 - Sencha for GWT
* Copyright(c) 2007-2012, Sencha, Inc.
* licensing@sencha.com
*
* http://www.sencha.com/products/gxt/license/
*/
package com.sencha.gxt.examples.test.client;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBean.PropertyName;
import com.google.web.bindery.autobean.shared.AutoBeanFactory;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.data.client.loader.HttpProxy;
import com.sencha.gxt.data.client.loader.XmlReader;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.data.shared.PropertyAccess;
import com.sencha.gxt.data.shared.loader.ListLoadResultBean;
import com.sencha.gxt.data.shared.loader.ListLoadConfig;
import com.sencha.gxt.data.shared.loader.ListLoadResult;
import com.sencha.gxt.data.shared.loader.ListLoader;
import com.sencha.gxt.data.shared.loader.LoadResultListStoreBinding;
import com.sencha.gxt.widget.core.client.FramedPanel;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.BoxLayoutContainer.BoxLayoutPack;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
public class XmlGridTest implements EntryPoint {
interface XmlAutoBeanFactory extends AutoBeanFactory {
static XmlAutoBeanFactory instance = GWT.create(XmlAutoBeanFactory.class);
AutoBean<EmailCollection> items();
AutoBean<ListLoadConfig> loadConfig();
}
public interface Email {
@PropertyName("Name")
String getName();
@PropertyName("Email")
String getEmail();
@PropertyName("Phone")
String getPhone();
@PropertyName("State")
String getState();
@PropertyName("Zip")
String getZip();
}
interface EmailCollection {
@PropertyName("record")
List<Email> getValues();
}
interface EmailProperties extends PropertyAccess<Email> {
ValueProvider<Email, String> name();
ValueProvider<Email, String> email();
ValueProvider<Email, String> phone();
ValueProvider<Email, String> state();
ValueProvider<Email, String> zip();
}
@Override
public void onModuleLoad() {
String path = "data/data.xml";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, path);
HttpProxy<ListLoadConfig> proxy = new HttpProxy<ListLoadConfig>(builder);
XmlReader<ListLoadResult<Email>, EmailCollection> reader = new XmlReader<ListLoadResult<Email>, EmailCollection>(
XmlAutoBeanFactory.instance, EmailCollection.class) {
protected com.sencha.gxt.data.shared.loader.ListLoadResult<Email> createReturnData(Object loadConfig,
EmailCollection records) {
return new ListLoadResultBean<Email>(records.getValues());
};
};
ListStore<Email> store = new ListStore<Email>(new ModelKeyProvider<Email>() {
@Override
public String getKey(Email item) {
return item.getEmail() + item.getName();
}
});
final ListLoader<ListLoadConfig, ListLoadResult<Email>> loader = new ListLoader<ListLoadConfig, ListLoadResult<Email>>(
proxy, reader);
loader.useLoadConfig(XmlAutoBeanFactory.instance.create(ListLoadConfig.class).as());
loader.addLoadHandler(new LoadResultListStoreBinding<ListLoadConfig, Email, ListLoadResult<Email>>(store));
EmailProperties props = GWT.create(EmailProperties.class);
ColumnConfig<Email, String> cc1 = new ColumnConfig<Email, String>(props.name(), 100, "Sender");
ColumnConfig<Email, String> cc2 = new ColumnConfig<Email, String>(props.email(), 165, "Email");
ColumnConfig<Email, String> cc3 = new ColumnConfig<Email, String>(props.phone(), 100, "Phone");
ColumnConfig<Email, String> cc4 = new ColumnConfig<Email, String>(props.state(), 50, "State");
ColumnConfig<Email, String> cc5 = new ColumnConfig<Email, String>(props.zip(), 65, "Zip Code");
List<ColumnConfig<Email, ?>> l = new ArrayList<ColumnConfig<Email, ?>>();
l.add(cc1);
l.add(cc2);
l.add(cc3);
l.add(cc4);
l.add(cc5);
ColumnModel<Email> cm = new ColumnModel<Email>(l);
Grid<Email> view = new Grid<Email>(store, cm);
view.getView().setForceFit(true);
view.setBorders(true);
view.setLoadMask(true);
view.setLoader(loader);
FramedPanel cp = new FramedPanel();
cp.setHeadingText("Xml Grid Example");
cp.setWidget(view);
cp.setPixelSize(500, 400);
cp.setCollapsible(true);
cp.setAnimCollapse(true);
cp.addStyleName("margin-10");
cp.setButtonAlign(BoxLayoutPack.CENTER);
cp.addButton(new TextButton("Load Xml", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
loader.load();
}
}));
RootPanel.get().add(cp);
}
}
|
package kr.ac.kopo.project02.vo;
public class ClientVO {
private String id;
private String pw;
private String name;
private String birth_dt;
private String regist_dt;
private String lac_dt;
public ClientVO(String id, String pw, String name, String birth_dt, String regist_dt, String lac_dt) {
this.id = id;
this.pw = pw;
this.name = name;
this.birth_dt = birth_dt;
this.regist_dt = regist_dt;
this.setLac_dt(lac_dt);
}
public ClientVO() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirth_dt() {
return birth_dt;
}
public void setBirth_dt(String birth_dt) {
this.birth_dt = birth_dt;
}
public String getRegist_dt() {
return regist_dt;
}
public void setRegist_dt(String regist_dt) {
this.regist_dt = regist_dt;
}
@Override
public String toString() {
return "ClientVO [id=" + id + ", name=" + name + ", birth_dt=" + birth_dt + ", regist_dt=" + regist_dt + "]";
}
public String getLac_dt() {
return lac_dt;
}
public void setLac_dt(String lac_dt) {
this.lac_dt = lac_dt;
}
}
|
package studio.visualdust.product.screendark.illegalClass;
import studio.visualdust.product.gztwigets.GButton;
import studio.visualdust.product.screendark.gui.UITheme;
import studio.visualdust.product.screendark.gui.widgets.console.DPositionChooseFrame;
import studio.visualdust.product.screendark.gui.widgets.console.PositionChoosePanel;
import studio.visualdust.product.screendark.method.EventRW;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Test_DPChoosePanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
new UITheme(frame);
new DPositionChooseFrame(frame, "为CG选择一个位置");
}
}
|
package com.kg.synth;
import com.kg.SequencerData;
import java.util.Arrays;
public abstract class Sequencer {
public static double bpm = 0.0D;
public double vol = 0f;
private BasslinePattern bassline;
public int[][] rhythm;
public boolean shuffle;
public int samplesPerSequencerUpdate;
public int tick = 0;
public int step = 0;
public boolean sixteenth_note = true;
public int patternLength = 16;
public int pitch_offset;
public BasslinePattern getBassline() {
return bassline;
}
public void setBassline(BasslinePattern bassline) {
this.bassline = bassline;
}
public int[][] getRhythm() {
return rhythm;
}
public void setRhythm(int[][] rhythm) {
this.rhythm = rhythm;
}
public abstract void tick();
public abstract void reset();
public void setVolume(double vol) {
this.vol = vol;
}
public double getVolume() {
return vol;
}
public double getBpm() {
return bpm;
}
public void setBpm(double bpm) {
this.bpm = bpm;
}
public abstract void randomizeSequence();
public abstract void randomizeRhythm();
public void setSequence(SequencerData sd) {
if (this instanceof RhythmSequencer){
if (sd.rhythm!=null){
this.setRhythm(Arrays.stream(sd.rhythm).map(int[]::clone).toArray(int[][]::new));
}
}
else {
if (sd.note!=null){
BasslinePattern bp = new BasslinePattern(sd.note.length);
bp.accent = sd.accent.clone();
bp.note = sd.note.clone();
bp.pause = sd.pause.clone();
bp.slide = sd.slide.clone();
this.setBassline(bp);
}
}
}
}
|
package comp1110.ass2.controller;
import comp1110.ass2.RailroadInk;
import comp1110.ass2.gui.Viewer;
import comp1110.ass2.model.Board;
import comp1110.ass2.model.EnumTypePlayer;
import comp1110.ass2.model.Player;
import comp1110.ass2.model.PositionPoint;
import comp1110.ass2.util.PlacementUtil;
import comp1110.ass2.util.StageManager;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
/**
* User:
* Mirhady Dorodjatun (uid: u6474009)
* Yue Zhang (uid: u6797258)
* Zhehao_Chang (uid: u6613739)
*/
public class GameStageController implements Initializable {
@FXML private GridPane gridPane_special;
@FXML private GridPane gridPane_dice;
@FXML private GridPane gridPane_board;
@FXML private Label num_remainST;
@FXML private Label num_player;
@FXML public Label name_player;
@FXML public Label player_type;
@FXML private Label num_round;
@FXML private Label num_remainDT;
@FXML private Label warning;
@FXML private Button btn_takeBack;
public static int totalPlayerNum=1;
public int currentPlayer=1;
public int round=1;
String playerType;
public String boardString;
public String roundString;
public int roundST;
public int remainSTile=3;
public int remainDTile=4;
public String diceRoll;
private final double UNPLACED_TILE_SQUARE_SIZE = 59.5;
private final double SQUARE_SIZE = 60;
private String currentTurnBoardString = "";
private int tilesPlacedThisTurn = 0;
private String imageURLPrefix = "assets/";
private String imageURLSuffix = ".jpg";
private String remainingDiceRoll;
private String defaultWarning = "Drag the available tiles to the board, then click End Turn button to end your turn.";
private String invalidPlacementWarning = "Invalid tile placement.";
private String specialTileTurnLimitWarning = "You can only use Special Tile once per turn.";
private String specialTileGameLimitWarning = "You can only use 3 Special Tiles in one game.";
private String diceNotPlacedWarning = "You need to put all 4 Regular Tiles on the board first.";
private String noTilesPlacedWarning = "You have not put any tile this turn";
private String noMoreMoveAvailableWarning = "No more Regular Tile can be placed, you are now allowed to click Next Turn";
/* initialize game board */
private Board board = new Board();
public class TileImage extends ImageView {
TileImage(){
this.setFitHeight(UNPLACED_TILE_SQUARE_SIZE);
this.setFitWidth(UNPLACED_TILE_SQUARE_SIZE);
}
}
/**
DraggableTile includes 4 normal tiles (decide by the dice) and all the special tiles (which haven't been used yet)/
A DraggableTile can be dragged and rotate. All tiles all treated as draggable until they are placed on the board.
Extends from TileImage class, which is just an extension of imageView with fixed size.
*/
public class DraggableTile extends TileImage {
int homeCol; int homeRow; // its original position on gridPane (as row and col)
int rotate; // the rotation (last int of a 5 bit tilePlacementString)
double mouseX; double mouseY; // the mouse position (as coordinate x,y. used for comparing)
double homeX; double homeY; // the original position (as coordinate x,y)
String tileName; // like A1, B2, S0
DraggableTile(int homeCol, int homeRow){
this.homeCol=homeCol;
this.homeRow=homeRow;
// when mouse is pressed, it records current position unless it is against the rules.
// displays appropriate warning for several situations.
setOnMousePressed(event -> {
displayWarning(defaultWarning);
System.out.println("recording mouse coordinate");
System.out.println("home :"+event.getSceneX() + ", " + event.getSceneY());
// if the number of special tiles used in this turn is not zero, display warning
if (roundST!=0 && this.tileName.substring(0,1).equals("S")){
displayWarning(specialTileTurnLimitWarning);
}
// if the all 3 special tiles are used, display warning
else if (remainSTile==0 && this.tileName.substring(0,1).equals("S")){
displayWarning(specialTileGameLimitWarning);
}
// if no invalid move, display warning but still allow dragging so the player can check
// (not that important but might be more natural/easy for the player)
else if ( ! isAbleToMove() && ( ! this.tileName.substring(0,1).equals("S"))) {
displayWarning(noMoreMoveAvailableWarning);
mouseX = event.getSceneX();
mouseY = event.getSceneY();
homeX = event.getSceneX();
homeY = event.getSceneY();
}
// else, just record position and display default green warning
else {
displayWarning(defaultWarning);
mouseX = event.getSceneX();
mouseY = event.getSceneY();
homeX = event.getSceneX();
homeY = event.getSceneY();
}
});
// when mouse is dragged, it drags the tile accordingly
// displays appropriate warning for several situations
// some may seem to be redundant with above, but if removed, there will be bugs when tested
setOnMouseDragged(event -> {
if (roundST!=0 && this.tileName.substring(0,1).equals("S")){
displayWarning(specialTileTurnLimitWarning);
}
else if (remainSTile==0 && this.tileName.substring(0,1).equals("S")){
displayWarning(specialTileGameLimitWarning);
}
// else runs the drag method
else {
this.toFront();
this.drag();
mouseX = event.getSceneX();
mouseY = event.getSceneY();
}
});
// when mouse is released, it will snap to nearest square in board, or return to original position if the placement is invalid.
// displays appropriate warning for several situations.
// some may seem to be redundant with above, but if removed, there will be bugs when tested.
setOnMouseReleased(event -> {
if (roundST!=0 && this.tileName.substring(0,1).equals("S")){
displayWarning(specialTileTurnLimitWarning);
}
else if (remainSTile==0 && this.tileName.substring(0,1).equals("S")){
displayWarning(specialTileGameLimitWarning);
}
else if ( ! isAbleToMove() && ( ! this.tileName.substring(0,1).equals("S"))) {
displayWarning(noMoreMoveAvailableWarning);
this.moveToHome();
}
// if the tile is on the board, place it on the nearest square in board using displayTileOnBoard.
// judges onBoard using other method, and utilizes methods in Board class for the underlying calculation
else if (onBoard()) {
this.setOpacity(1);
int boardCol = (int) (mouseX - gridPane_board.getLayoutX()) / (int) SQUARE_SIZE;
int boardRow = (int) (mouseY - gridPane_board.getLayoutY()) / (int) SQUARE_SIZE;
String boardSquareName = board.getBoardSquareNameFromPosition(boardCol, boardRow);
String placementString = this.tileName + boardSquareName + this.rotate;
if (board.isValidPlacement(board.getSquareFromSquareString(placementString))) {
board.putPlacementStringToMap(placementString);
System.out.println("displaying boardString: "+getCurrentPlayer().getBoardString());
board.printMap();
getCurrentPlayer().appendBoardString(placementString);
displayTileToBoard(boardCol, boardRow, this.rotate, this.getImage());
tilesPlacedThisTurn++;
useDiceRoll(this.tileName);
if (tileName.charAt(0) == 'S') {
roundST=1;
gridPane_special.getChildren().remove(this);
num_remainST.setText(String.valueOf(remainSTile-1));
}
else {
gridPane_dice.getChildren().remove(this);
remainDTile--;
num_remainDT.setText(String.valueOf(remainDTile));
}
}
else {
this.moveToHome();
displayWarning(invalidPlacementWarning);
}
}
else {
this.moveToHome();
displayWarning(invalidPlacementWarning);
}
});
setOnMouseClicked(event -> {
// if not right click ,return.
if(event.getButton()!= MouseButton.SECONDARY)
{
return;
}
System.out.println("right mouse click");
if(rotate<7){rotate++;}
else if (rotate==7){rotate=0;}
this.setRotate((rotate % 4) * 90);
this.setScaleX((rotate) < 4 ? 1 : - 1);
displayWarning(defaultWarning);
event.consume();
});
}
// moves the tile while dragged, according to the difference between mouse position and its original position
private void drag() {
setLayoutX(mouseX - homeX);
setLayoutY(mouseY - homeY);
this.setTranslateX(getLayoutX());
this.setTranslateY(getLayoutY());
this.setOpacity(0.5);
this.toFront();
}
// returns to original position.
private void moveToHome() {
this.setTranslateX(0.0);
this.setTranslateY(0.0);
this.setOpacity(1);
this.toFront();
}
// determines if the tile is dropped on the board (excluding the walls and exits area).
private boolean onBoard() {
return mouseX > (gridPane_board.getLayoutX() + UNPLACED_TILE_SQUARE_SIZE)
&& mouseX < (gridPane_board.getLayoutX() + gridPane_board.getWidth() - UNPLACED_TILE_SQUARE_SIZE)
&& mouseY > (gridPane_board.getLayoutY() + UNPLACED_TILE_SQUARE_SIZE)
&& mouseY < (gridPane_board.getLayoutY() + gridPane_board.getHeight() - UNPLACED_TILE_SQUARE_SIZE);
}
public void setTileName(String tileName) {
this.tileName = tileName;
}
public void setRotateToZero(){
this.rotate=0;
this.setRotate((rotate % 4) * 90);
this.setScaleX((rotate) < 4 ? 1 : - 1);
}
}
/**
* It would generate a new dice roll and place corresponding tiles on the gridPaneDice
*/
private void setDiceRoll(){
DraggableTile dice_1=new DraggableTile(0,0);
DraggableTile dice_2=new DraggableTile(1,0);
DraggableTile dice_3=new DraggableTile(0,1);
DraggableTile dice_4=new DraggableTile(1,1);
diceRoll=RailroadInk.generateDiceRoll();
Image d1 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(0,2)+".jpg");
dice_1.setImage(d1);
Image d2 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(2,4)+".jpg");
dice_2.setImage(d2);
Image d3 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(4,6)+".jpg");
dice_3.setImage(d3);
Image d4 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(6,8)+".jpg");
dice_4.setImage(d4);
dice_1.setRotateToZero();
dice_2.setRotateToZero();
dice_3.setRotateToZero();
dice_4.setRotateToZero();
dice_1.setTileName(diceRoll.substring(0,2));
dice_2.setTileName(diceRoll.substring(2,4));
dice_3.setTileName(diceRoll.substring(4,6));
dice_4.setTileName(diceRoll.substring(6,8));
if (gridPane_dice.getChildren().size()>0){
Node grid = gridPane_dice.getChildren().get(0);
gridPane_dice.getChildren().clear();
gridPane_dice.getChildren().add(grid);
}
gridPane_dice.add(dice_1,0,0);
gridPane_dice.add(dice_2,1,0);
gridPane_dice.add(dice_3,0,1);
gridPane_dice.add(dice_4,1,1);
StageManager.diceRollList.add(diceRoll);
remainingDiceRoll = diceRoll;
}
/**
* without changing the dice string, put the 4 normal Tiles to the gridPane again
*/
void setDTileAgain(){
DraggableTile dice_1=new DraggableTile(0,0);
DraggableTile dice_2=new DraggableTile(1,0);
DraggableTile dice_3=new DraggableTile(0,1);
DraggableTile dice_4=new DraggableTile(1,1);
Image d1 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(0,2)+".jpg");
dice_1.setImage(d1);
Image d2 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(2,4)+".jpg");
dice_2.setImage(d2);
Image d3 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(4,6)+".jpg");
dice_3.setImage(d3);
Image d4 = new Image(Viewer.class.getResource("")+"assets/"+diceRoll.substring(6,8)+".jpg");
dice_4.setImage(d4);
dice_1.setRotateToZero();
dice_2.setRotateToZero();
dice_3.setRotateToZero();
dice_4.setRotateToZero();
dice_1.setTileName(diceRoll.substring(0,2));
dice_2.setTileName(diceRoll.substring(2,4));
dice_3.setTileName(diceRoll.substring(4,6));
dice_4.setTileName(diceRoll.substring(6,8));
if (gridPane_dice.getChildren().size()>0){
Node grid = gridPane_dice.getChildren().get(0);
gridPane_dice.getChildren().clear();
gridPane_dice.getChildren().add(grid);
}
gridPane_dice.add(dice_1,0,0);
gridPane_dice.add(dice_2,1,0);
gridPane_dice.add(dice_3,0,1);
gridPane_dice.add(dice_4,1,1);
}
/**
* when the user clicks the "take back" button, all the tiles placed by the current player in this round
* would go back to home.
* then, adjusts the game parameters accordingly
*/
@FXML
void btn_takeBack_click() {
if (tilesPlacedThisTurn == 0) {
displayWarning(noTilesPlacedWarning);
}
else {
if (roundST==1){
roundST=0;
num_remainST.setText(String.valueOf(remainSTile));
}
remainDTile=4;
num_remainDT.setText(String.valueOf(4));
takeBackTilesPlacedThisTurn();
setSTiles();
setDTileAgain();
remainingDiceRoll = diceRoll;
}
}
/**
* When click the "end turn" button, if the user have placed all 4 regular tiles, the game would
* go to next player or(and) next round. If not, it won't be allowed and would show waring message.
* The only exception is that the remaining regular tile is not able to be placed on board according to the rules.
* @param event mouse click
* @throws IOException
*/
@FXML
void btn_endTurn_click(MouseEvent event) throws IOException
{
if (roundST==1){
StageManager.playerList.get(currentPlayer-1).usedSpeicalTile++;
roundST=0;
}
if (remainDTile>0 && getCurrentPlayer().playerType==EnumTypePlayer.HUMAN && isAbleToMove()){
displayWarning(diceNotPlacedWarning);
}
else {
tilesPlacedThisTurn=0;
roundST=0;
remainDTile=4;
num_remainDT.setText("4");
remainingDiceRoll = diceRoll;
displayWarning(defaultWarning);
if (round==7 && totalPlayerNum==currentPlayer){
//todo: open the window(stage) of ending OR(And) show the scores
StageManager.isShownBestScore = false;
Stage curr = StageManager.stageMap.get("gameStage");
curr.hide();
Stage scoreFormStage = new Stage();
Parent root = FXMLLoader.load(ClassLoader.getSystemResource("resource/ScoreForm.fxml"));
Scene scene = new Scene(root);
scoreFormStage.setScene(scene);
scoreFormStage.setTitle("ScoreForm");
scoreFormStage.show();
StageManager.stageMap.put("ScoreFormStage",scoreFormStage);
}
else if (totalPlayerNum>currentPlayer){
currentPlayer++;
num_player.setText(Integer.toString(currentPlayer));
name_player.setText(StageManager.playerList.get(currentPlayer-1).getPlayerName());
remainSTile=3-StageManager.playerList.get(currentPlayer-1).usedSpeicalTile;
num_remainST.setText(String.valueOf(remainSTile));
player_type.setText(getCurrentPlayer().getPlayerType());
toggleTakeBackButton();
setDTileAgain();
setSTiles();
removeBoardDisplay();
loadPlayerBoard();
displayPlayerBoard();
}
else if (totalPlayerNum==currentPlayer){
currentPlayer=1;
num_player.setText(Integer.toString(currentPlayer));
round++;
setSTiles();
StageManager.playerList.get(currentPlayer-1).round++;
num_round.setText(String.valueOf(round));
name_player.setText(StageManager.playerList.get(currentPlayer-1).getPlayerName());
remainSTile=3-StageManager.playerList.get(currentPlayer-1).usedSpeicalTile;
num_remainST.setText(String.valueOf(remainSTile));
player_type.setText(getCurrentPlayer().getPlayerType());
setDiceRoll();
toggleTakeBackButton();
removeBoardDisplay();
loadPlayerBoard();
displayPlayerBoard();
}
}
}
/**
* when there are still unplaced regular tiles, determines if there is no valid placement that can be made
* using generateMove method in RailroadInk class (task 10).
* @return true if there is still a valid placement
*/
private boolean isAbleToMove() {
return ( ! RailroadInk.generateMove(getCurrentPlayer().getBoardString(), remainingDiceRoll).equals(""));
}
private void useDiceRoll(String dice) {
int usedDice = 0;
String newDiceRoll = remainingDiceRoll;
if ( ! dice.substring(0,1).equals("S")) {
for (int i=0; i<remainingDiceRoll.length() && usedDice == 0; i+=2) {
String diceInDiceRoll = remainingDiceRoll.substring(i, i+2);
if (diceInDiceRoll.equals(dice)) {
String frontPart = remainingDiceRoll.substring(0, i);
String rearPart = remainingDiceRoll.substring(i+2);
newDiceRoll = frontPart + rearPart;
usedDice++;
}
}
}
remainingDiceRoll = newDiceRoll;
}
/**
* sets the take back button disabled (for AI player) or not (for human player)
*/
private void toggleTakeBackButton() {
if (getCurrentPlayer().playerType == EnumTypePlayer.AI) {
btn_takeBack.setDisable(true);
} else {
btn_takeBack.setDisable(false);
}
}
/**
* displays a tile on the gridPane board using the parameters of a placementString
*/
private void displayTileToBoard(int col, int row, int rotation, Image image) {
TileImage tile = new TileImage();
tile.setFitHeight(SQUARE_SIZE);
tile.setFitWidth(SQUARE_SIZE);
tile.setImage(image);
tile.setRotate((rotation % 4) * 90);
tile.setScaleX((rotation < 4) ? 1 : -1);
gridPane_board.add(tile, col, row);
}
/**
* displays warning message to make it easy for the player to follow what is happening in the game.
* background is green for default message, otherwise red (to indicate real warning message).
*/
private void displayWarning(String message) {
warning.setText(message);
if (message.equals(defaultWarning)) warning.setStyle("-fx-border-color: green; -fx-border-width: 2px; -fx-background-color: palegreen");
else warning.setStyle("-fx-border-color: red; -fx-border-width: 2px; -fx-background-color: lightpink");
}
/**
* displays walls and exits to gridPane board
*/
private void displayWallsAndExits() {
Image wallImage = new Image(Viewer.class.getResource("")+imageURLPrefix+"WALL"+imageURLSuffix);
Image railwayExitImage = new Image(Viewer.class.getResource("")+imageURLPrefix+"RailExit"+imageURLSuffix);
Image highwayExitImage = new Image(Viewer.class.getResource("")+imageURLPrefix+"HighExit"+imageURLSuffix);
for (int row=0; row<9; row++) {
for (int col=0; col<9; col++) {
if (col == 0) {
if (row == 2 || row == 6) {
displayTileToBoard(col, row, 3, railwayExitImage);
}
else if (row == 4) {
displayTileToBoard(col, row, 3, highwayExitImage);
}
else {
displayTileToBoard(col, row, 0, wallImage);
}
}
if (col == 8) {
if (row == 2 || row == 6) {
displayTileToBoard(col, row, 1, railwayExitImage);
}
else if (row == 4) {
displayTileToBoard(col, row, 1, highwayExitImage);
}
else {
displayTileToBoard(col, row, 0, wallImage);
}
}
if (row == 0) {
if (col == 2 || col == 6) {
displayTileToBoard(col, row, 0, highwayExitImage);
}
else if (col == 4) {
displayTileToBoard(col, row, 0, railwayExitImage);
}
else {
displayTileToBoard(col, row, 0, wallImage);
}
}
if (row == 8) {
if (col == 2 || col == 6) {
displayTileToBoard(col, row, 2, highwayExitImage);
}
else if (col == 4) {
displayTileToBoard(col, row, 2, railwayExitImage);
}
else {
displayTileToBoard(col, row, 0, wallImage);
}
}
}
}
}
/**
* returns current player.
*/
private Player getCurrentPlayer() {
return StageManager.playerList.get(currentPlayer-1);
}
/**
* used when user clicks take back button. it removes the tiles placed this turn, both from the display
* and the underlying board (using methods in Board class).
*/
private void takeBackTilesPlacedThisTurn() {
String boardString = getCurrentPlayer().getBoardString();
String removedPlacementString = boardString.substring(boardString.length() - (tilesPlacedThisTurn * 5));
String newBoardString = boardString.substring(0, boardString.length() - (tilesPlacedThisTurn * 5));
getCurrentPlayer().setBoardString(newBoardString);
removeBoardDisplay();
board.removeBoardStringFromBoard(removedPlacementString);
displayPlayerBoard();
tilesPlacedThisTurn = 0;
}
/**
* used when user clicks end turn. removes all tiles from the gridPane board.
*/
private void removeBoardDisplay() {
Node grid = gridPane_board.getChildren().get(0);
Node rectangle = gridPane_board.getChildren().get(1);
gridPane_board.getChildren().clear();
gridPane_board.getChildren().add(grid);
gridPane_board.getChildren().add(rectangle);
displayWallsAndExits();
}
/**
* removes all tiles from the gridPane for regular and special tiles.
*/
private void removeUnplacedTileDisplay() {
Node gridForDice = gridPane_dice.getChildren().get(0);
Node gridForSpecial = gridPane_special.getChildren().get(0);
gridPane_dice.getChildren().clear();
gridPane_special.getChildren().clear();
gridPane_dice.getChildren().add(gridForDice);
gridPane_special.getChildren().add(gridForSpecial);
}
/**
* used when user clicks end turn (player switch) or take back button. returns the player's board.
*/
private void loadPlayerBoard() {
board = getCurrentPlayer().getBoard();
}
/**
* displays the current player's board. if player type is AI, also displays all the AI's movement using PlacementUtil class
*/
private void displayPlayerBoard() {
Player player = getCurrentPlayer();
String playerBoardString = player.getBoardString();
System.out.println("displaying boardString :"+getCurrentPlayer().getBoardString());
if(player.playerType== EnumTypePlayer.AI)
{
String diceRoll = StageManager.diceRollList.get(StageManager.diceRollList.size()-1);
String aiPlacement = PlacementUtil.getResults(playerBoardString,diceRoll,player);
playerBoardString += aiPlacement;
removeUnplacedTileDisplay();
}
for (int i=0; i<playerBoardString.length(); i+=5) {
String placementString = playerBoardString.substring(i, i+5);
PositionPoint pp = board.getPositionFromPlacementString(placementString);
int rotation = Integer.parseInt(placementString.substring(4));
Image image = new Image(Viewer.class.getResource("")+imageURLPrefix+placementString.substring(0,2)+imageURLSuffix);
displayTileToBoard(pp.getY(), pp.getX(), rotation, image);
}
board.putPlacementStringToMap(playerBoardString);
player.setBoardString(playerBoardString);
board.printMap();
}
/**
* place the special tiles that can be used by the current player
*/
void setSTiles(){
Node grid = gridPane_special.getChildren().get(0);
gridPane_special.getChildren().clear();
gridPane_special.getChildren().add(grid);
DraggableTile tile_s0=new DraggableTile(0,0);
DraggableTile tile_s1=new DraggableTile(1,0);
DraggableTile tile_s2=new DraggableTile(0,1);
DraggableTile tile_s3=new DraggableTile(1,1);
DraggableTile tile_s4=new DraggableTile(0,2);
DraggableTile tile_s5=new DraggableTile(1,2);
Image s0 = new Image(Viewer.class.getResource("")+"assets/S0.jpg");
Image s1 = new Image(Viewer.class.getResource("")+"assets/S1.jpg");
Image s2 = new Image(Viewer.class.getResource("")+"assets/S2.jpg");
Image s3 = new Image(Viewer.class.getResource("")+"assets/S3.jpg");
Image s4 = new Image(Viewer.class.getResource("")+"assets/S4.jpg");
Image s5 = new Image(Viewer.class.getResource("")+"assets/S5.jpg");
tile_s0.setImage(s0);
tile_s1.setImage(s1);
tile_s2.setImage(s2);
tile_s3.setImage(s3);
tile_s4.setImage(s4);
tile_s5.setImage(s5);
tile_s0.setTileName("S0");
tile_s1.setTileName("S1");
tile_s2.setTileName("S2");
tile_s3.setTileName("S3");
tile_s4.setTileName("S4");
tile_s5.setTileName("S5");
gridPane_special.add(tile_s0,0,0);
gridPane_special.add(tile_s1,1,0);
gridPane_special.add(tile_s2,0,1);
gridPane_special.add(tile_s3,1,1);
gridPane_special.add(tile_s4,0,2);
gridPane_special.add(tile_s5,1,2);
String boardString = getCurrentPlayer().getBoardString();
List<String> list = new ArrayList<>();
int num = boardString.length();
for (int i=0;i<num;i+=5){
list.add(boardString.substring(i,i+2));
}
if (list.contains("S0")){
gridPane_special.getChildren().remove(tile_s0);
}
if (list.contains("S1")){
gridPane_special.getChildren().remove(tile_s1);
}
if (list.contains("S2")){
gridPane_special.getChildren().remove(tile_s2);
}
if (list.contains("S3")){
gridPane_special.getChildren().remove(tile_s3);
}
if (list.contains("S4")){
gridPane_special.getChildren().remove(tile_s4);
}
if (list.contains("S5")){
gridPane_special.getChildren().remove(tile_s5);
}
}
public void initialize(URL location, ResourceBundle resources){
//set name, round and player No. and place the tiles
num_player.setText(String.valueOf(currentPlayer));
String name = StageManager.playerList.get(currentPlayer-1).playerName;
this.name_player.setText(name);
num_round.setText(String.valueOf(round));
player_type.setText(getCurrentPlayer().getPlayerType());
toggleTakeBackButton();
setDiceRoll();
setSTiles();
displayWallsAndExits();
displayPlayerBoard();
displayWarning(defaultWarning);
gridPane_dice.toFront();
gridPane_special.toFront();
System.out.println(gridPane_special.getChildren());
// if the first player is an AI , not place the draggable Tiles
if (StageManager.playerList.get(currentPlayer-1).playerType==EnumTypePlayer.AI){
removeUnplacedTileDisplay();
}
}
}
|
package labrom.litlbro.util;
import labrom.litlbro.L;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class Wallpaper {
public static Drawable get(Context ctx) {
try {
Class<?> wallpaperManagerClass = Class.forName("android.app.WallpaperManager");
Object mgr = wallpaperManagerClass.getDeclaredMethod("getInstance", Context.class).invoke(null, ctx);
return (Drawable)wallpaperManagerClass.getDeclaredMethod("getFastDrawable").invoke(mgr);
} catch(Exception e) {
Log.w(L.TAG, "WallpaperManager not available: " + e.getMessage());
}
return null;
}
}
|
package sr.hakrinbank.intranet.api.controller;
import org.apache.commons.codec.binary.Base64;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import sr.hakrinbank.intranet.api.dto.NewsHrmDto;
import sr.hakrinbank.intranet.api.dto.ResponseDto;
import sr.hakrinbank.intranet.api.model.News;
import sr.hakrinbank.intranet.api.model.NewsHrm;
import sr.hakrinbank.intranet.api.service.NewsHrmService;
import sr.hakrinbank.intranet.api.util.Constant;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by clint on 5/29/17.
*/
@RestController
@RequestMapping(value = "/api/newshrm")
public class NewsHrmController {
@Autowired
private NewsHrmService newsHrmService;
//-------------------Retrieve All NewsHrm--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listAllNewsHrm() {
List<NewsHrm> newsHrm = newsHrmService.findAllActiveNewsHrm();
if(newsHrm.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) , HttpStatus.NO_CONTENT);
}
return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(newsHrm), null), HttpStatus.OK);
}
//-------------------Retrieve All NewsHrm By Search--------------------------------------------------------
@RequestMapping(value = "search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> listNewsHrmBySearchQuery(@RequestParam String qry) {
List<NewsHrm> newsHrm = newsHrmService.findAllActiveNewsHrmBySearchQuery(qry);
if(newsHrm.isEmpty()){
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_NO_RESULTS) ,HttpStatus.NO_CONTENT);
}
return new ResponseEntity<ResponseDto>(new ResponseDto(mapModelToDto(newsHrm), mapModelToDto(newsHrm).size() + Constant.RESPONSE_MESSAGE_AMOUNT_RESULTS_FOUND), HttpStatus.OK);
}
//-------------------Retrieve All NewsHrm With Pagination--------------------------------------------------------
// @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
// public ResponseEntity<Page<NewsHrm>> listAllNewsHrm(Pageable pageable) {
// Page<NewsHrm> newsHrm = newsHrmService.findAllNewsHrmByPage(pageable);
// return new ResponseEntity<Page<NewsHrm>>(newsHrm, HttpStatus.OK);
// }
//-------------------Retrieve Single NewsHrm--------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<NewsHrm> getNewsHrm(@PathVariable("id") long id) {
System.out.println("Fetching NewsHrm with id " + id);
NewsHrm newsHrm = newsHrmService.findById(id);
if (newsHrm == null) {
System.out.println("NewsHrm with id " + id + " not found");
return new ResponseEntity<NewsHrm>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<NewsHrm>(newsHrm, HttpStatus.OK);
}
//-------------------Create a NewsHrm--------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> createNewsHrm(@RequestBody NewsHrmDto newsHrmBasisDto) throws IOException {
System.out.println("Creating NewsHrm with description " + newsHrmBasisDto.getDescription());
if (newsHrmBasisDto.getId() != null) {
System.out.println("A NewsHrm with id " + newsHrmBasisDto.getId() + " already exist");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "A NewsHrm with id " + newsHrmBasisDto.getId() + " already exist"), HttpStatus.CONFLICT);
}
mapAndUpdateNewsHrm(newsHrmBasisDto);
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_SAVED), HttpStatus.CREATED);
}
//------------------- Update a NewsHrm --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseDto> updateNewsHrm(@PathVariable("id") long id, @RequestBody NewsHrmDto newsHrmBasisDto) throws IOException {
System.out.println("Updating NewsHrm " + id);
NewsHrm currentNewsHrm = newsHrmService.findById(id);
if (currentNewsHrm == null) {
System.out.println("NewsHrm with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "NewsHrm with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
mapAndUpdateNewsHrm(newsHrmBasisDto);
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_UPDATED), HttpStatus.OK);
}
//------------------- Delete a NewsHrm --------------------------------------------------------
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<ResponseDto> deleteNewsHrm(@PathVariable("id") long id) {
System.out.println("Fetching & Deleting NewsHrm with id " + id);
NewsHrm newsHrm = newsHrmService.findById(id);
if (newsHrm == null) {
System.out.println("Unable to delete. NewsHrm with id " + id + " not found");
return new ResponseEntity<ResponseDto>(new ResponseDto(null, "Unable to delete. NewsHrm with id " + id + " not found"), HttpStatus.NOT_FOUND);
}
newsHrm.setDeleted(true);
newsHrmService.updateNewsHrm(newsHrm);
return new ResponseEntity<ResponseDto>(new ResponseDto(null, Constant.RESPONSE_MESSAGE_DELETED), HttpStatus.OK);
}
//------------------- HELPER METHODS --------------------------------------------------------
public List<NewsHrmDto> mapModelToDto(List<NewsHrm> newsHrm) {
List<NewsHrmDto> newsHrmBasisDtoList = new ArrayList<>();
ModelMapper modelMapper = new ModelMapper();
for(News newsHrmItem: newsHrm){
if(newsHrmItem instanceof NewsHrm) {
NewsHrmDto newsHrmBasisDto = modelMapper.map(newsHrmItem, NewsHrmDto.class);
newsHrmBasisDtoList.add(newsHrmBasisDto);
}
}
return newsHrmBasisDtoList;
}
private void mapAndUpdateNewsHrm(NewsHrmDto newsHrmBasisDto) throws IOException {
ModelMapper modelMapper = new ModelMapper();
NewsHrm newsHrm = modelMapper.map(newsHrmBasisDto, NewsHrm.class);
if(newsHrmBasisDto.getAttachement() == "" || newsHrmBasisDto.getAttachement() == null || newsHrmBasisDto.getAttachement().isEmpty() || newsHrmBasisDto.getAttachement().contentEquals("")) {
if(newsHrm.getId() != null) {
NewsHrm newsHrm1 = newsHrmService.findById(newsHrm.getId());
newsHrm.setAttachement(newsHrm1.getAttachement());
newsHrm.setAttachementName(newsHrm1.getAttachementName());
}else{
newsHrm.setAttachement(null);
newsHrm.setAttachementName(null);
}
}else{
String imageDataBytes = newsHrmBasisDto.getAttachement().substring(newsHrmBasisDto.getAttachement().indexOf(Constant.STRING_COMMA_SUBSTRING) + 1);
newsHrm.setAttachement(Base64.decodeBase64(imageDataBytes));
}
newsHrmService.updateNewsHrm(newsHrm);
}
}
|
package com.ilecreurer.drools.samples.sample2.service;
/**
* CollisionServiceException class.
* @author ilecreurer.
*/
public class CollisionServiceException extends Exception {
/**
* Serial.
*/
private static final long serialVersionUID = 1L;
public CollisionServiceException() {
}
public CollisionServiceException(final String message) {
super(message);
}
public CollisionServiceException(final Throwable cause) {
super(cause);
}
public CollisionServiceException(final String message, final Throwable cause) {
super(message, cause);
}
public CollisionServiceException(final String message,
final Throwable cause,
final boolean enableSuppression,
final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
package com.test;
import java.util.Arrays;
import com.test.base.Solution;
/**
* 第一层n遍历,第二次夹逼原则,将两级遍历变成一级
*
* 算法复杂度:n*log(n) + n*n = n*n
*
* @author YLine
*
* 2018年8月13日 下午3:01:08
*/
public class SolutionA implements Solution
{
@Override
public int threeSumClosest(int[] nums, int target)
{
int result = Integer.MAX_VALUE, minDiff = Integer.MAX_VALUE;
// 传入数据 违规
if (null == nums || nums.length < 3)
{
return result;
}
Arrays.sort(nums);
int length = nums.length;
int one = 0, two, three, tempTraget;
while (length - one > 2)
{
two = one + 1;
three = length - 1;
while (two < three)
{
tempTraget = nums[one] + nums[two] + nums[three];
if (tempTraget == target)
{
return target;
}
else if (tempTraget < target)
{
if (minDiff > target - tempTraget)
{
minDiff = target - tempTraget;
result = tempTraget;
}
two++;
}
else
{
if (minDiff > tempTraget - target)
{
minDiff = tempTraget - target;
result = tempTraget;
}
three--;
}
}
one++;
while (length > one && nums[one] == nums[one - 1])
{
one++;
}
}
return result;
}
}
|
package com.example.ahmadrizaldi.traveloka_retrofit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ahmadrizaldi.traveloka_retrofit.API.APIDataPenerbangan;
import com.example.ahmadrizaldi.traveloka_retrofit.API.ApiClient;
import com.example.ahmadrizaldi.traveloka_retrofit.API.ApiInterface;
import com.example.ahmadrizaldi.traveloka_retrofit.CRUDUser.CRUDDataPenerbangan;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class InsertDataPenerbangan extends AppCompatActivity {
EditText flight_id, darimana, kemana, harga;
Button tambahDataPenerbangan;
APIDataPenerbangan mApiInterface;;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_data_penerbangan);
flight_id = (EditText)findViewById(R.id.edt_flightid);
darimana = (EditText)findViewById(R.id.edt_darimana);
kemana = (EditText)findViewById(R.id.edt_kemana);
harga = (EditText)findViewById(R.id.edt_harga);
mApiInterface = ApiClient.getClient().create(APIDataPenerbangan.class);
tambahDataPenerbangan = (Button)findViewById(R.id.btn_tambahpenerbangan);
tambahDataPenerbangan.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Call<CRUDDataPenerbangan> postPembelianCall =
mApiInterface.postmaskapai(flight_id.getText().toString().trim(),darimana.getText().toString().trim(), kemana.getText().toString().trim(), harga.getText().toString().trim(), "1");
postPembelianCall.enqueue(new Callback<CRUDDataPenerbangan>() {
@Override
public void onResponse(Call<CRUDDataPenerbangan> call, Response<CRUDDataPenerbangan> response) {
pesansukses();
}
@Override
public void onFailure(Call<CRUDDataPenerbangan> call, Throwable t) {
}
});
}
});
}
private void pesansukses(){
Toast.makeText(this, "Insert Sukses",Toast.LENGTH_SHORT).show();
}
}
|
package com.eussi._01_jca_jce.securitypkg;
import org.junit.Test;
import java.security.*;
import java.util.Arrays;
/**
* Created by wangxueming on 2019/3/28.
*/
public class _08_KeyPairGenerator {
@Test
public void test() {
//实例化
try {
//实例化KeyPairGenerator
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
//初始化对象
keyPairGenerator.initialize(1024);
//生成KeyPair
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println("public:" + Arrays.toString(publicKey.getEncoded()));
System.out.println("private:" + Arrays.toString(privateKey.getEncoded()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
|
package sub_day0225;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ListGUI extends JFrame {
JLabel num,name,kor,eng,math,unum,uname,ukor,ueng,umath;
JButton back,exit;
JPanel jp1,jp2,jp3,jp4,jp5;
String bname;
String lName,lNum;
int[] score = new int[3];
int total,aver;
ListGUI(ListVO vo){
lNum =vo.getNum();
lName =vo.getName();
score =vo.getScore();
total =vo.getTotal();
aver = vo.getAver();
jp1= new JPanel();
jp2= new JPanel();
jp3= new JPanel();
jp4= new JPanel();
jp5= new JPanel();
unum = new JLabel("학번 : ");
uname = new JLabel("이름 : ");
ukor = new JLabel("국어 : ");
ueng = new JLabel("영어 : ");
umath = new JLabel("수학 : ");
num = new JLabel(lNum);
name = new JLabel(lName);
kor = new JLabel(Integer.toString(score[0]));
eng = new JLabel(Integer.toString(score[1]));
math = new JLabel(Integer.toString(score[2]));
jp1.add(unum); jp1.add(num);
jp2.add(uname); jp2.add(name);
jp3.add(ukor); jp3.add(kor);
jp4.add(ueng); jp4.add(eng);
jp5.add(umath); jp5.add(math);
setLayout(new GridLayout(5,1));
add(jp1);
add(jp2);
add(jp3);
add(jp4);
add(jp5);
setSize(300,300);
setVisible(true);
}
class EventObject extends WindowAdapter implements ActionListener{
public void actionPerformed(ActionEvent e) {
}
}
}
|
package tftp.transfer;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import tftp.packets.DataPacket;
public class FileTransfer extends Observable {
protected final String filename;
protected final InetAddress address;
protected final int connectionPort;
protected final List<DataPacket> packets;
public FileTransfer(String filename, InetAddress address, int connectionPort) {
this.filename = filename;
this.address = address;
this.connectionPort = connectionPort;
this.packets = new ArrayList<>();
}
public void notifyNewMessage(String message) {
setChanged();
notifyObservers(message);
}
}
|
package me.ewriter.art_chapter11;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleThreads();
}
private void scheduleThreads() {
runAsyncTask();
runIntentService();
runThreadPool();
}
private void runThreadPool() {
Runnable command = new Runnable() {
@Override
public void run() {
SystemClock.sleep(2000);
}
};
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
fixedThreadPool.execute(command);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(command);
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(4);
// 2000ms 后执行 command
scheduledExecutorService.schedule(command, 2000, TimeUnit.MILLISECONDS);
// 延迟 10ms 后,每隔 1000ms执行一次 command
scheduledExecutorService.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(command);
}
private void runIntentService() {
Intent service = new Intent(this, LocalIntentService.class);
service.putExtra("task_action", "com.ryg.action.TASK1");
startService(service);
service.putExtra("task_action", "com.ryg.action.TASK2");
startService(service);
service.putExtra("task_action", "com.ryg.action.TASK3");
startService(service);
}
private void runAsyncTask() {
try {
new DownloadFilesTask().execute(new URL("http://www.baidu.com"),
new URL("http://www.renyugang.cn"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
@Override
protected Long doInBackground(URL... params) {
int count = params.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
publishProgress((int) ((i / (float) count) * 100));
if (isCancelled())
break;
}
return totalSize;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
}
}
}
|
package com.bistel.mq;
public interface Messaging {
public void publishMessage(ExchangeInfo exchange, MessageInfo message) throws MessagingException;
}
|
package video.api.android.sdk.infrastructure;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import video.api.android.sdk.domain.Token;
public class TokenJsonSerializer implements JsonSerializer<Token> {
public Token deserialize(JSONObject response) throws JSONException {
Token token = new Token();
token.setToken(response.getString("token"));
return token;
}
public List<Token> deserialize(JSONArray data) {
throw new RuntimeException("Not supported");
}
public JSONObject serialize(Token object) {
throw new RuntimeException("Not supported");
}
}
|
package org.garret.perst.impl;
import java.io.*;
import java.util.*;
import org.garret.perst.*;
/**
* Class for exporting the whole database or pert of the database in XML format.
* Exported data can be used later by XMLImporter to perform recover or conversion of
* database or be used by some other data consumer.
* This class should be used in this way:
* Writer writer = new BufferedWriter(new FileWriter("dump.xml"));
* XMLExporter exporter = new XMLExporter(db, writer);
* exporter.exportDatabase();
* writer.close();
*/
public class XMLExporter
{
/**
* Constructor of XML exporter
* @param storage source storage
* @param writer XML writer
*/
public XMLExporter(Storage storage, Writer writer) {
this.storage = (StorageImpl)storage;
this.writer = writer;
}
/**
* Export all objects from the database
*/
public void exportDatabase()
{
exportCluster(storage.getRoot());
}
/**
* Export all objects referenced from the specified root object
* @param root root of the object cluster
*/
public void exportCluster(IPersistent root)
{
try {
if (storage.encoding != null) {
writer.write("<?xml version=\"1.0\" encoding=\"" + storage.encoding + "\"?>\n");
} else {
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
}
if (root == null || root.getOid() == 0) {
writer.write("<database root=\"0\"/>");
return;
}
int rootOid = root.getOid();
writer.write("<database root=\"" + rootOid + "\">\n");
exportedBitmap = new int[(storage.currIndexSize + 31) / 32];
markedBitmap = new int[(storage.currIndexSize + 31) / 32];
markedBitmap[rootOid >> 5] |= 1 << (rootOid & 31);
int nExportedObjects;
XMLOutputStream out = new XMLOutputStream();
do {
nExportedObjects = 0;
for (int i = 0; i < markedBitmap.length; i++) {
int mask = markedBitmap[i];
if (mask != 0) {
for (int j = 0, bit = 1; j < 32; j++, bit <<= 1) {
if ((mask & bit) != 0) {
int oid = (i << 5) + j;
exportedBitmap[i] |= bit;
markedBitmap[i] &= ~bit;
try {
IPersistent obj = storage.getObjectByOID(oid);
if (obj instanceof BtreeCompoundIndex) {
exportCompoundIndex(oid, (BtreeCompoundIndex)obj);
} else if (obj instanceof Btree) {
exportIndex(oid, (Btree)obj);
} else {
String className = exportIdentifier(obj.getClass().getName());
writer.write(" <" + className + " id=\"" + oid + "\">\n");
out.reset();
obj.writeObject(out);
writer.write(" </" + className + ">\n");
}
nExportedObjects += 1;
} catch (StorageError x) {
if (storage.listener != null) {
storage.listener.objectNotExported(oid, x);
} else {
System.err.println("XML export failed for object " + oid + ": " + x);
}
}
}
}
}
}
} while (nExportedObjects != 0);
writer.write("</database>\n");
writer.flush(); // writer should be closed by calling code
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
final String exportIdentifier(String name) {
return name.replace('$', '-');
}
final void exportIndex(int oid, Btree index) throws IOException
{
String name = index.getClass().getName();
writer.write(" <" + name + " id=\"" + index.getOid() + "\" unique=\"" + (index.unique ? '1' : '0')
+ "\" type=\"" + index.type + "\">\n");
exportTree(index);
writer.write(" </" + name + ">\n");
}
final void exportCompoundIndex(int oid, BtreeCompoundIndex index) throws IOException
{
String name = index.getClass().getName();
writer.write(" <" + name + " id=\"" + index.getOid() + "\" unique=\"" + (index.unique ? '1' : '0') + "\"");
compoundKeyTypes = index.types;
for (int i = 0; i < compoundKeyTypes.length; i++) {
writer.write(" type" + i + "=\"" + compoundKeyTypes[i] + "\"");
}
writer.write(">\n");
exportTree(index);
compoundKeyTypes = null;
writer.write(" </" + name + ">\n");
}
final int exportKey(byte[] body, int offs, int size, int type) throws IOException
{
switch (type) {
case Types.Boolean:
writer.write(body[offs++] != 0 ? '1' : '0');
break;
case Types.Byte:
writer.write(Integer.toString(body[offs++]));
break;
case Types.Char:
writer.write(Integer.toString((char)Bytes.unpack2(body, offs)));
offs += 2;
break;
case Types.Short:
writer.write(Integer.toString(Bytes.unpack2(body, offs)));
offs += 2;
break;
case Types.Int:
case Types.Object:
writer.write(Integer.toString(Bytes.unpack4(body, offs)));
offs += 4;
break;
case Types.Long:
writer.write(Long.toString(Bytes.unpack8(body, offs)));
offs += 8;
break;
case Types.Float:
writer.write(Float.toString(Float.intBitsToFloat(Bytes.unpack4(body, offs))));
offs += 4;
break;
case Types.Double:
writer.write(Double.toString(Double.longBitsToDouble(Bytes.unpack8(body, offs))));
offs += 8;
break;
case Types.String:
for (int i = 0; i < size; i++) {
exportChar((char)Bytes.unpack2(body, offs));
offs += 2;
}
break;
case Types.ArrayOfByte:
for (int i = 0; i < size; i++) {
byte b = body[offs++];
writer.write(hexDigit[(b >>> 4) & 0xF]);
writer.write(hexDigit[b & 0xF]);
}
break;
case Types.Date:
{
long msec = Bytes.unpack8(body, offs);
offs += 8;
if (msec >= 0) {
writer.write(new Date(msec).toString());
} else {
writer.write("null");
}
break;
}
default:
Assert.that(false);
}
return offs;
}
final void exportCompoundKey(byte[] body, int offs, int size, int type) throws IOException
{
Assert.that(type == Types.ArrayOfByte);
int end = offs + size;
for (int i = 0; i < compoundKeyTypes.length; i++) {
type = compoundKeyTypes[i];
if (type == Types.ArrayOfByte) {
size = Bytes.unpack4(body, offs);
offs += 4;
} else if (type == Types.String) {
size = Bytes.unpack2(body, offs);
offs += 2;
}
writer.write(" key" + i + "=\"");
offs = exportKey(body, offs, size, type);
writer.write("\"");
}
Assert.that(offs == end);
}
final void exportAssoc(int oid, byte[] body, int offs, int size, int type) throws IOException
{
writer.write(" <ref id=\"" + oid + "\"");
if ((exportedBitmap[oid >> 5] & (1 << (oid & 31))) == 0) {
markedBitmap[oid >> 5] |= 1 << (oid & 31);
}
if (compoundKeyTypes != null) {
exportCompoundKey(body, offs, size, type);
} else {
writer.write(" key=\"");
exportKey(body, offs, size, type);
writer.write("\"");
}
writer.write("/>\n");
}
final void exportChar(char ch) throws IOException {
switch (ch) {
case '<':
writer.write("<");
break;
case '>':
writer.write(">");
break;
case '&':
writer.write("&");
break;
case '"':
writer.write(""");
break;
case '\'':
writer.write("'");
break;
default:
writer.write(ch);
}
}
final void exportDate(Date date) throws IOException {
writer.write(date == null ? "null" : "\"" + date + "\"");
}
final void exportString(String s) throws IOException {
if (s == null) {
writer.write("null");
} else {
writer.write("\"");
for (int i = 0, n = s.length(); i < n; i++) {
exportChar(s.charAt(i));
}
writer.write("\"");
}
}
static final char hexDigit[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
final void exportBinary(byte[] value) throws IOException {
if (value == null) {
writer.write("null");
} else {
writer.write('\"');
for (int i = 0; i < value.length; i++) {
byte b = value[i];
writer.write(hexDigit[(b >>> 4) & 0xF]);
writer.write(hexDigit[b & 0xF]);
}
writer.write('\"');
}
}
final void exportRef(IPersistent obj) throws IOException {
if (obj == null) {
writer.write("null");
} else {
int oid = obj.getOid();
if (obj instanceof PersistentStub) {
writer.write("<ref id=\"" + oid + "\"/>");
} else {
writer.write("<ref id=\"" + oid + "\" type=\"" + exportIdentifier(obj.getClass().getName()) + "\"/>");
}
if (oid != 0 && (exportedBitmap[oid >> 5] & (1 << (oid & 31))) == 0) {
markedBitmap[oid >> 5] |= 1 << (oid & 31);
}
}
}
class XMLOutputStream implements IOutputStream {
int columnNo;
int nestingLevel;
public void reset() {
columnNo = 0;
nestingLevel = 0;
}
public OutputStream getOutputStream() {
return null;
}
private final void beginColumn(int type) throws IOException {
if (nestingLevel != 0) {
writer.write(" <object type=\"" + type + "\">");
} else {
writer.write(" <column no=\"" + (++columnNo) + "\" type=\"" + type + "\">");
}
}
private final void endColumn() throws IOException {
writer.write(nestingLevel != 0 ? "</object>\n" : "</column>\n");
}
public void writeByte(byte v) {
try {
beginColumn(Types.Byte);
writer.write(Integer.toString(v));
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeBoolean(boolean v) {
try {
beginColumn(Types.Boolean);
writer.write(v ? '1' : '0');
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeChar(char v) {
try {
beginColumn(Types.Char);
writer.write(Integer.toString(v));
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeShort(short v) {
try {
beginColumn(Types.Short);
writer.write(Integer.toString(v));
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeInt(int v) {
try {
beginColumn(Types.Int);
writer.write(Integer.toString(v));
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeLong(long v) {
try {
beginColumn(Types.Long);
writer.write(Long.toString(v));
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeFloat(float v) {
try {
beginColumn(Types.Float);
writer.write(Float.toString(v));
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeDouble(double v) {
try {
beginColumn(Types.Double);
writer.write(Double.toString(v));
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeString(String s) {
try {
beginColumn(Types.String);
exportString(s);
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeDate(Date v) {
try {
beginColumn(Types.Date);
exportDate(v);
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeObject(IPersistent obj) {
try {
beginColumn(Types.Object);
exportRef(obj);
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeLink(Link v) {
try {
beginColumn(Types.Link);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.size(); i < n; i++) {
writer.write(" <element index=\"" + i + "\">");
exportRef(v.getRaw(i));
writer.write("</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeVector(Vector v) {
try {
beginColumn(Types.Vector);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
nestingLevel += 1;
for (int i = 0, n = v.size(); i < n; i++) {
writer.write(" <element index=\"" + i + "\">");
write(v.elementAt(i));
writer.write(" </element>\n");
}
writer.write(" ");
nestingLevel -= 1;
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void write(Object v) {
if (v == null) {
try {
beginColumn(Types.Null);
writer.write("null");
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
} else if (v instanceof IPersistent) {
writeObject((IPersistent)v);
} else if (v instanceof String) {
writeString((String)v);
} else if (v instanceof Integer) {
writeInt(((Integer)v).intValue());
} else if (v instanceof Long) {
writeLong(((Long)v).longValue());
} else if (v instanceof Byte) {
writeByte(((Byte)v).byteValue());
} else if (v instanceof Short) {
writeShort(((Short)v).shortValue());
} else if (v instanceof Character) {
writeChar(((Character)v).charValue());
} else if (v instanceof Boolean) {
writeBoolean(((Boolean)v).booleanValue());
} else if (v instanceof Float) {
writeFloat(((Float)v).floatValue());
} else if (v instanceof Double) {
writeDouble(((Double)v).doubleValue());
} else if (v instanceof Date) {
writeDate((Date)v);
} else if (v instanceof Link) {
writeLink((Link)v);
} else if (v instanceof boolean[]) {
writeArrayOfBoolean((boolean[])v);
} else if (v instanceof byte[]) {
writeArrayOfByte((byte[])v);
} else if (v instanceof char[]) {
writeArrayOfChar((char[])v);
} else if (v instanceof short[]) {
writeArrayOfShort((short[])v);
} else if (v instanceof int[]) {
writeArrayOfInt((int[])v);
} else if (v instanceof long[]) {
writeArrayOfLong((long[])v);
} else if (v instanceof float[]) {
writeArrayOfFloat((float[])v);
} else if (v instanceof double[]) {
writeArrayOfDouble((double[])v);
} else if (v instanceof String[]) {
writeArrayOfString((String[])v);
} else if (v instanceof Date[]) {
writeArrayOfDate((Date[])v);
} else if (v instanceof IPersistent[]) {
writeArrayOfObject((IPersistent[])v);
} else {
throw new StorageError(StorageError.UNSUPPORTED_TYPE);
}
}
public void writeHashtable(Hashtable v) {
try {
beginColumn(Types.Hashtable);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
nestingLevel += 1;
Enumeration e = v.keys();
while (e.hasMoreElements()) {
Object key = e.nextElement();
Object value = v.get(key);
writer.write(" <entry>\n");
writer.write(" <key>\n");
write(key);
writer.write(" </key>\n");
writer.write(" <value>\n");
write(value);
writer.write(" </value>\n");
writer.write(" </entry>\n");
}
writer.write(" ");
nestingLevel -= 1;
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfBoolean(boolean[] v) {
try {
beginColumn(Types.ArrayOfBoolean);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">");
writer.write(v[i] ? '1' : '0');
writer.write(" </element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfByte(byte[] v) {
try {
beginColumn(Types.ArrayOfByte);
exportBinary(v);
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfShort(short[] v) {
try {
beginColumn(Types.ArrayOfShort);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">" + Integer.toString(v[i]) + "</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfChar(char[] v) {
try {
beginColumn(Types.ArrayOfChar);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">" + Integer.toString(v[i]) + "</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfInt(int[] v) {
try {
beginColumn(Types.ArrayOfInt);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">" + Integer.toString(v[i]) + "</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfLong(long[] v) {
try {
beginColumn(Types.ArrayOfLong);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">" + Long.toString(v[i]) + "</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfFloat(float[] v) {
try {
beginColumn(Types.ArrayOfFloat);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">" + Float.toString(v[i]) + "</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfDouble(double[] v) {
try {
beginColumn(Types.ArrayOfDouble);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">" + Double.toString(v[i]) + "</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfString(String[] v) {
try {
beginColumn(Types.ArrayOfString);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">");
exportString(v[i]);
writer.write("</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfDate(Date[] v) {
try {
beginColumn(Types.ArrayOfDate);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">");
exportDate(v[i]);
writer.write("</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
public void writeArrayOfObject(IPersistent[] v) {
try {
beginColumn(Types.ArrayOfObject);
if (v == null) {
writer.write("null");
} else {
writer.write('\n');
for (int i = 0, n = v.length; i < n; i++) {
writer.write(" <element index=\"" + i + "\">");
exportRef(v[i]);
writer.write("</element>\n");
}
writer.write(" ");
}
endColumn();
} catch (IOException x) {
throw new StorageError(StorageError.IO_EXCEPTION, x);
}
}
}
private final void exportTree(Btree tree) throws IOException
{
if (tree.root != 0) {
exportPage(tree.root, tree.type, tree.height);
}
}
private final void exportPage(int pageId, int type, int height) throws IOException
{
Page pg = storage.getPage(pageId);
try {
int i, n = BtreePage.getnItems(pg);
if (--height != 0) {
if (type == Types.String || type == Types.ArrayOfByte) { // page of strings
for (i = 0; i <= n; i++) {
exportPage(BtreePage.getKeyStrOid(pg, i), type, height);
}
} else {
for (i = 0; i <= n; i++) {
exportPage(BtreePage.getReference(pg, BtreePage.maxItems-i-1), type, height);
}
}
} else {
if (type == Types.String || type == Types.ArrayOfByte) { // page of strings
for (i = 0; i < n; i++) {
exportAssoc(BtreePage.getKeyStrOid(pg, i),
pg.data,
BtreePage.firstKeyOffs + BtreePage.getKeyStrOffs(pg, i),
BtreePage.getKeyStrSize(pg, i),
type);
}
} else {
for (i = 0; i < n; i++) {
exportAssoc(BtreePage.getReference(pg, BtreePage.maxItems-1-i),
pg.data,
BtreePage.firstKeyOffs + i*ClassDescriptor.sizeof[type],
ClassDescriptor.sizeof[type],
type);
}
}
}
} finally {
storage.pool.unfix(pg);
}
}
private StorageImpl storage;
private Writer writer;
private int[] markedBitmap;
private int[] exportedBitmap;
private int[] compoundKeyTypes;
}
|
package DataStructures.hashing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
a)
S: "barfoothefoobarman"
L: ["foo", "bar"]
You should return the indices: [0,9].
b)
S: "lingmindraboofooowingdingbarrwingmonkeypoundcake"
L: ["fooo","barr","wing","ding", "wing"]
you should return the index : [13].
*/
public class SubstrWithConcatenationOfAllWords {
public List<Integer> findSubstring(String s, String[] words) {
ArrayList<Integer> result = new ArrayList<>();
if(s==null||s.length()==0||words==null||words.length==0){
return result;
}
//frequency of words
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(String w: words){
if(map.containsKey(w)){
map.put(w, map.get(w)+1);
}else{
map.put(w, 1);
}
}
int len = words[0].length();
for(int j=0; j<len; j++){
HashMap<String, Integer> currentMap = new HashMap<String, Integer>();
int start = j;//start index of start
int count = 0;//count total qualified words so far
for(int i=j; i<=s.length()-len; i=i+len){
String sub = s.substring(i, i+len);
if(map.containsKey(sub)){
//set frequency in current map
if(currentMap.containsKey(sub)){
currentMap.put(sub, currentMap.get(sub)+1);
}else{
currentMap.put(sub, 1);
}
count++;
while(currentMap.get(sub)>map.get(sub)){
String left = s.substring(start, start+len);
currentMap.put(left, currentMap.get(left)-1);
count--;
start = start + len;
}
if(count==words.length){
result.add(start); //add to result
//shift right and reset currentMap, count & start point
String left = s.substring(start, start+len);
currentMap.put(left, currentMap.get(left)-1);
count--;
start = start + len;
}
} else {
currentMap.clear();
start = i+len;
count = 0;
}
}
}
return result;
}
public static void main(String a[]) {
SubstrWithConcatenationOfAllWords sw = new SubstrWithConcatenationOfAllWords();
//sw.findSubstring("barfoothefoobarman", new String[]{"foo", "bar"});
sw.findSubstring("lingmindraboofooowingwingdingbarrwingmonkeypoundcake",
new String[]{"fooo", "barr", "wing", "ding"/*, "wing"*/});
}
}
|
package com.BrowserAutomation;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirefoxBrowser {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\\\Users\\\\new\\\\eclipse-workspace\\\\BrowserAutomation\\\\DriverFiles\\\\geckodriver.exe");
FirefoxDriver d=new FirefoxDriver();
d.get("http://facebook.com");
d.getTitle();
d.close();
}
}
|
package com.cs.administration.promotion;
import com.cs.promotion.Promotion;
import org.springframework.data.domain.Page;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;
/**
* @author Omid Alaepour
*/
@XmlRootElement
@XmlAccessorType(FIELD)
public class PromotionPageableDto {
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
@XmlElement
@Nonnull
private List<PromotionDto> promotions;
@XmlElement
@Nonnull
private Long count;
@SuppressWarnings("UnusedDeclaration")
public PromotionPageableDto() {
}
public PromotionPageableDto(@Nonnull final Page<Promotion> promotions) {
this.promotions = new ArrayList<>(promotions.getSize());
for (final Promotion promotion : promotions) {
this.promotions.add(new PromotionDto(promotion));
}
count = promotions.getTotalElements();
}
}
|
/*
* Created on 22/08/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.entity.pl;
import java.util.Date;
import com.citibank.ods.entity.pl.valueobject.TplProdAssetTypeEntityVO;
/**
* @author rcoelho
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class TplProdAssetTypeEntity extends BaseTplProdAssetTypeEntity
{
/**
* Construtor padrão - sem argumentos
*/
public TplProdAssetTypeEntity()
{
m_data = new TplProdAssetTypeEntityVO();
}
/**
* Construtor - Carrega os atributos com os atributos do movimento
*/
public TplProdAssetTypeEntity( TplProdAssetTypeMovEntity tplProdAssetTypeMovEntity_,
Date lastAuthDate_, String lastAuthUserId_,
String recStatCode_ )
{
m_data = new TplProdAssetTypeEntityVO();
m_data.setProdAssetTypeCode(tplProdAssetTypeMovEntity_.getData().getProdAssetTypeCode());
m_data.setProdSubAssetCode(tplProdAssetTypeMovEntity_.getData().getProdSubAssetCode());
m_data.setProdAssetTypeText(tplProdAssetTypeMovEntity_.getData().getProdAssetTypeText());
m_data.setAssetTypeCustRptOrderNbr(tplProdAssetTypeMovEntity_.getData().getAssetTypeCustRptOrderNbr());
m_data.setLastUpdDate(tplProdAssetTypeMovEntity_.getData().getLastUpdDate());
m_data.setLastUpdUserId(tplProdAssetTypeMovEntity_.getData().getLastUpdUserId());
((TplProdAssetTypeEntityVO)m_data).setLastAuthDate(lastAuthDate_);
((TplProdAssetTypeEntityVO)m_data).setLastAuthUserId(lastAuthUserId_);
((TplProdAssetTypeEntityVO)m_data).setRecStatCode(recStatCode_);
}
}
|
package com.citibank.ods.modules.client.relationeg.functionality.valueobject;
/**
* @author leonardo.nakada
*
*/
public class RelationEgMovementDetailFncVO extends BaseRelationEgDetailFncVO
{
private String m_opernCode;
public RelationEgMovementDetailFncVO()
{
//
}
/**
* @return Returns the opernCode.
*/
public String getOpernCode()
{
return m_opernCode;
}
/**
* @param opernCode_ The opernCode to set.
*/
public void setOpernCode( String opernCode_ )
{
m_opernCode = opernCode_;
}
}
|
package prj.designpatterns.strategy.prototype;
/**
* 具体策略
*
* @author LuoXin
*
*/
public class ConcreteStrategyB implements IStrategy {
@Override
public void operate() {
System.out.println("我是策略B");
}
}
|
package com.oleksii.arrmy.CrewPortal.dao;
import com.oleksii.arrmy.CrewPortal.model.Worker;
import java.util.HashMap;
import java.util.List;
public interface WorkerDAO {
int save(Worker worker);
Worker get(int id);
void delete(int id);
void update(int id, Worker worker);
List<Worker> list();
}
|
package demo.wssec.common;
import java.util.Map;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.w3c.dom.Document;
import com.apigee.flow.execution.ExecutionContext;
import com.apigee.flow.execution.ExecutionResult;
import com.apigee.flow.execution.spi.Execution;
import com.apigee.flow.message.Message;
import com.apigee.flow.message.MessageContext;
public class SignAndEncrypt extends WsSecCalloutBase implements Execution {
public SignAndEncrypt(Map properties) {
super(properties);
}
@Override
public ExecutionResult execute(MessageContext msgCtxt, ExecutionContext execCtxt) {
try {
Message msg = msgCtxt.getMessage();
String msgContent = msg.getContent();
SignatureEncryptionTest signatureEncryptionTest = new SignatureEncryptionTest();
Document encryptedDoc = signatureEncryptionTest.testSignatureEncryptionOutbound(msgContent);
String signedMessage = XmlUtil.toString(encryptedDoc);
msgCtxt.setVariable("message.content", signedMessage);
}
catch (Exception e) {
//System.out.println(ExceptionUtils.getStackTrace(e));
String error = e.getCause().toString();
msgCtxt.setVariable("wssec_exception", error);
int ch = error.lastIndexOf(':');
if (ch >= 0) {
msgCtxt.setVariable("wssec_exception", error.substring(ch+2).trim());
}
else {
msgCtxt.setVariable("wssec_exception", error);
}
msgCtxt.setVariable("wssec_stacktrace", ExceptionUtils.getStackTrace(e));
return ExecutionResult.ABORT;
}
return ExecutionResult.SUCCESS;
}
}
|
package at.ac.tuwien.sepm.groupphase.backend.service;
import at.ac.tuwien.sepm.groupphase.backend.entity.Cart;
import at.ac.tuwien.sepm.groupphase.backend.entity.CartItem;
import at.ac.tuwien.sepm.groupphase.backend.exception.NotFoundException;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.UUID;
public interface CartService {
/**
* Counts the Items of a cart by the sessionId assigned to the client session.
*
* @param sessionId the id of the client session
* @return The count of the cart items
* @throws NotFoundException is thrown if the specified cart does not exists
* @throws RuntimeException upon encountering errors with the database
*/
long countCartItemInCartUsingSessionId(UUID sessionId);
/**
* Creates a new empty cart with a sessionId assigned to the client session.
*
* @param sessionId the id of the client session
* @return The cart entity added to the database
* @throws RuntimeException upon encountering errors with the database
*/
Cart createEmptyCart(UUID sessionId);
/**
* Adds a new cartItem to a new created cart with a sessionId assigned to the client session.
*
* @param sessionId the id of the client session
* @param item The cart entity to with the new cartItem
* @return The new cart entity added to the database
* @throws RuntimeException upon encountering errors with the database
*/
Cart addCartItemToNewCart(UUID sessionId, CartItem item);
/**
* Adds a new cartItem to the cart with a sessionId assigned to the client session.
*
* @param sessionId the id of the client session
* @param item The cart entity to with the new cartItem
* @return The new cart entity added to the database
* @throws RuntimeException upon encountering errors with the database
*/
Cart addCartItemToCart(UUID sessionId, CartItem item);
/**
* Find a single cart entry which is assigned to the client session.
*
* @param sessionId The sessionId assigned to the session
* @return cart entity
* @throws NotFoundException is thrown if the specified cart does not exists
* @throws RuntimeException upon encountering errors with the database
*/
Cart findCartBySessionId(UUID sessionId);
/**
* Updates a cartItem of a cart which is assigned to the client session.
*
* @param cart The cart entity which is assigned to the session
* @param item The cartItem to be updated
* @return The updated cart entity
* @throws RuntimeException upon encountering errors with the database
*/
Cart updateCart(Cart cart, CartItem item);
/**
* Find a single cart entry which is assigned to the client session.
*
* @param sessionId the sessionId of the session
* @return true if sessionId is already in the database
* @throws RuntimeException when no cart with the sessionId is found
*/
boolean sessionIdExists(UUID sessionId);
/**
* Validates a single cart entry which is assigned to the client session.
*
* @param sessionId the sessionId of the session
* @return true if session is valid
* @throws RuntimeException when no cart with the sessionId is found
*/
boolean validateSession(UUID sessionId);
/**
* Deletes a single cartItem by id.
*
* @param id the id of the cart item
* @throws RuntimeException when no cart with the sessionId is found
*/
void deleteCartItemById(Long id);
/**
* Deletes carts after a certain time.
* Will be every 5 hours.
*/
@Scheduled(cron = "0 0 0/5 * * ?")
void deleteCartAfterDuration();
}
|
package interfaces;
/**
* @author dylan
*
*/
public interface AdvancedMediaPlayer {
/**
* @param fileName
*/
public void playVlc(String fileName);
/**
* @param fileName
*/
public void playMp4(String fileName);
}
|
package com.abt.recycler.Live;
import android.databinding.BaseObservable;
import com.abt.basic.arch.mvvm.IViewModel;
import java.lang.ref.WeakReference;
/**
* @描述: @直播VM
* @作者: @黄卫旗
* @创建时间: @2018-03-05
*/
public class LiveViewModel extends BaseObservable
implements IViewModel<LiveNavigator> {
private static final String TAG = "LiveViewModel";
private WeakReference<LiveNavigator> mPreviewNavigator;
private LiveActivity mPreviewActivity;
public LiveViewModel() {
}
@Override
public void initialize() {
}
public void setContext(LiveActivity activity) {
mPreviewActivity = activity;
}
@Override
public void setNavigator(LiveNavigator navigator) {
mPreviewNavigator = new WeakReference<LiveNavigator>(navigator);
}
}
|
package com.example.rihaf.diabetesdietexpert;
/**
* Created by rihaf on 12/29/2016.
*/
public class dataProviderJournal {
private String waktumakan;
private String jenismakan;
private String porsimakan;
private Double kalorimakan;
private String qty;
private Double total;
public String getWaktumakan() {
return waktumakan;
}
public void setWaktumakan(String waktumakan) {
this.waktumakan = waktumakan;
}
public String getJenismakan() {
return jenismakan;
}
public void setJenismakan(String jenismakan) {
this.jenismakan = jenismakan;
}
public String getPorsimakan() {
return porsimakan;
}
public void setPorsimakan(String porsimakan) {
this.porsimakan = porsimakan;
}
public Double getKalorimakan() {
return kalorimakan;
}
public void setKalorimakan(Double kalorimakan) {
this.kalorimakan = kalorimakan;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public dataProviderJournal(String waktumakan, String jenismakan, String porsimakan, Double kalorimakan, String qty, Double total)
{
this.waktumakan =waktumakan;
this.jenismakan =jenismakan;
this.porsimakan =porsimakan;
this.kalorimakan =kalorimakan;
this.qty =qty;
this.total =total;
}
}
|
package com.mitobit.camel.component.nexmo;
import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.spi.UriParam;
import com.nexmo.messaging.sdk.NexmoSmsClient;
import com.nexmo.messaging.sdk.NexmoSmsClientSSL;
/**
* Represents a Nexmo endpoint.
*/
public class NexmoEndpoint extends DefaultEndpoint {
private SmsBinding binding;
@UriParam
private String apiKey;
@UriParam
private String apiSecret;
@UriParam
private String from;
@UriParam
private String to;
@UriParam
private boolean ssl = true;
public NexmoEndpoint() {
}
public NexmoEndpoint(String uri, NexmoComponent component) {
super(uri, component);
}
@Override
public Producer createProducer() throws Exception {
return new NexmoProducer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
throw new UnsupportedOperationException("Nexmo endpoints are not meant to be consumed from.");
}
@Override
public boolean isSingleton() {
return true;
}
public NexmoSmsClient createSmsClient() {
NexmoSmsClient client;
try {
if (ssl) {
client = new NexmoSmsClientSSL(apiKey, apiSecret);
} else {
client = new NexmoSmsClient(apiKey, apiSecret);
}
} catch (Exception e) {
throw new RuntimeCamelException("Failed to instanciate a Nexmo Client", e);
}
return client;
}
// Properties
// -------------------------------------------------------------------------
public SmsBinding getBinding() {
if (binding == null) {
binding = new SmsBinding();
}
return binding;
}
public void setBinding(SmsBinding binding) {
this.binding = binding;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiSecret() {
return apiSecret;
}
public void setApiSecret(String apiSecret) {
this.apiSecret = apiSecret;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
}
|
package com.citibank.ods.modules.product.product.form;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.form.BaseForm;
import com.citibank.ods.common.util.ODSValidator;
import com.citibank.ods.entity.pl.BaseTplProductEntity;
import com.citibank.ods.modules.product.product.functionality.valueobject.BaseProductDetailFncVO;
/**
* @author leonardo.nakada
*
*/
public class BaseProductListForm extends BaseForm implements ProductSearchable,
ProductDetailable
{
// Codigo do Produto.
private String m_prodCodeSrc = "";
//Descricao do Produto
private String m_prodTextSrc = "";
// Codigo da Familia de Produtos (redundante seguindo atributo existente no
// BG)
private String m_prodFamlCodeSrc = "";
// Nome do Produto
private String m_prodNameSrc = "";
// Codigo de Qualificacao do Prod uto Private
private String m_prodQlfyCodeSrc = "";
// Codigo da Categoria de Risco Private.
private String m_prodRiskCatCodeSrc = "";
// Codigo da Sub-Familia de Produtos.
private String m_prodSubFamlCodeSrc = "";
//Codigo do Sistema
private String m_sysCodeSrc = "";
//Codigo do Segmento
private String m_sysSegCodeSrc = "";
private String m_selectedProdCode = "";
private String m_selectedSysCode = "";
private String m_selectedSysSegCode = "";
private DataSet m_results = null;
private DataSet m_prodQlfyCodeDomain;
private DataSet m_prodFamlCodeDomain;
private DataSet m_prodRiskCodeDomain;
private DataSet m_prodSubFamlCodeDomain;
private String m_lastUpdUserIdSrc = "";
private ArrayList m_listProduct;
/**
* @return Returns lastUpdUserId.
*/
public String getLastUpdUserIdSrc()
{
return m_lastUpdUserIdSrc;
}
/**
* @param lastUpdUserId_ Field lastUpdUserId to be setted.
*/
public void setLastUpdUserIdSrc( String lastUpdUserIdSrc_ )
{
m_lastUpdUserIdSrc = lastUpdUserIdSrc_;
}
/**
* @return Returns prodSubFamlCodeDomain.
*/
public DataSet getProdSubFamlCodeDomain()
{
return m_prodSubFamlCodeDomain;
}
/**
* @param prodSubFamlCodeDomain_ Field prodSubFamlCodeDomain to be setted.
*/
public void setProdSubFamlCodeDomain( DataSet prodSubFamlCodeDomain_ )
{
m_prodSubFamlCodeDomain = prodSubFamlCodeDomain_;
}
/**
* @return Returns prodFamlCodeDomain.
*/
public DataSet getProdFamlCodeDomain()
{
return m_prodFamlCodeDomain;
}
/**
* @param prodFamlCodeDomain_ Field prodFamlCodeDomain to be setted.
*/
public void setProdFamlCodeDomain( DataSet prodFamlCodeDomain_ )
{
m_prodFamlCodeDomain = prodFamlCodeDomain_;
}
/**
* @return Returns prodQlfCodeDomain.
*/
public DataSet getProdQlfyCodeDomain()
{
return m_prodQlfyCodeDomain;
}
/**
* @param prodQlfCodeDomain_ Field prodQlfCodeDomain to be setted.
*/
public void setProdQlfyCodeDomain( DataSet prodQlfyCodeDomain_ )
{
m_prodQlfyCodeDomain = prodQlfyCodeDomain_;
}
/**
* @return Returns prodRiskCodeDomain.
*/
public DataSet getProdRiskCodeDomain()
{
return m_prodRiskCodeDomain;
}
/**
* @param prodRiskCodeDomain_ Field prodRiskCodeDomain to be setted.
*/
public void setProdRiskCodeDomain( DataSet prodRiskCodeDomain_ )
{
m_prodRiskCodeDomain = prodRiskCodeDomain_;
}
/**
* @return Returns the prodCodeSrc.
*/
public String getProdCodeSrc()
{
return m_prodCodeSrc;
}
/**
* @param prodCodeSrc_ The prodCodeSrc to set.
*/
public void setProdCodeSrc( String prodCodeSrc_ )
{
m_prodCodeSrc = prodCodeSrc_;
}
/**
* @return Returns the prodFamlCodeSrc.
*/
public String getProdFamlCodeSrc()
{
return m_prodFamlCodeSrc;
}
/**
* @param prodFamlCodeSrc_ The prodFamlCodeSrc to set.
*/
public void setProdFamlCodeSrc( String prodFamlCodeSrc_ )
{
m_prodFamlCodeSrc = prodFamlCodeSrc_;
}
/**
* @return Returns the prodNameSrc.
*/
public String getProdNameSrc()
{
return m_prodNameSrc;
}
/**
* @param prodNameSrc_ The prodNameSrc to set.
*/
public void setProdNameSrc( String prodNameSrc_ )
{
m_prodNameSrc = prodNameSrc_;
}
/**
* @return Returns the prodQlfyCodeSrc.
*/
public String getProdQlfyCodeSrc()
{
return m_prodQlfyCodeSrc;
}
/**
* @param prodQlfyCodeSrc_ The prodQlfyCodeSrc to set.
*/
public void setProdQlfyCodeSrc( String prodQlfyCodeSrc_ )
{
m_prodQlfyCodeSrc = prodQlfyCodeSrc_;
}
/**
* @return Returns the prodRiskCatCodeSrc.
*/
public String getProdRiskCatCodeSrc()
{
return m_prodRiskCatCodeSrc;
}
/**
* @param prodRiskCatCodeSrc_ The prodRiskCatCodeSrc to set.
*/
public void setProdRiskCatCodeSrc( String prodRiskCatCodeSrc_ )
{
m_prodRiskCatCodeSrc = prodRiskCatCodeSrc_;
}
/**
* @return Returns the prodSubFamlCodeSrc.
*/
public String getProdSubFamlCodeSrc()
{
return m_prodSubFamlCodeSrc;
}
/**
* @param prodSubFamlCodeSrc_ The prodSubFamlCodeSrc to set.
*/
public void setProdSubFamlCodeSrc( String prodSubFamlCodeSrc_ )
{
m_prodSubFamlCodeSrc = prodSubFamlCodeSrc_;
}
/**
* @return Returns the prodTextSrc.
*/
public String getProdTextSrc()
{
return m_prodTextSrc;
}
/**
* @param prodTextSrc_ The prodTextSrc to set.
*/
public void setProdTextSrc( String prodTextSrc_ )
{
m_prodTextSrc = prodTextSrc_;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#setSelectedProdCode(java.lang.String)
*/
public void setSelectedProdCode( String selectedProdCode_ )
{
setProdCodeSrc( selectedProdCode_ );
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#getSelectedProdCode()
*/
public String getSelectedProdCode()
{
return m_selectedProdCode;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#setSelectedSysCode(java.lang.String)
*/
public void setSelectedSysCode( String selectedSysCode_ )
{
setSysCodeSrc( selectedSysCode_ );
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#getSelectedSysCode()
*/
public String getSelectedSysCode()
{
return m_selectedSysCode;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#setSelectedSysSegCode(java.lang.String)
*/
public void setSelectedSysSegCode( String selectedSysSegCode_ )
{
setSysSegCodeSrc( selectedSysSegCode_ );
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#getSelectedSysSegCode()
*/
public String getSelectedSysSegCode()
{
return m_selectedSysSegCode;
}
/**
* @return Returns the results.
*/
public DataSet getResults()
{
return m_results;
}
/**
* @param results_ The results to set.
*/
public void setResults( DataSet results_ )
{
m_results = results_;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#setSysCodeSrc(java.lang.String)
*/
public void setSysCodeSrc( String selectedSysCode_ )
{
m_sysCodeSrc = selectedSysCode_;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#getSysCodeSrc()
*/
public String getSysCodeSrc()
{
return m_sysCodeSrc;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#setSysSegCodeSrc(java.lang.String)
*/
public void setSysSegCodeSrc( String selectedSysSegCode_ )
{
m_sysSegCodeSrc = selectedSysSegCode_;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.modules.product.product.form.ProductSearchable#getSysSegCodeSrc()
*/
public String getSysSegCodeSrc()
{
return m_sysSegCodeSrc;
}
public ActionErrors validate( ActionMapping actionMapping_,
HttpServletRequest request_ )
{
ActionErrors errors = new ActionErrors();
ODSValidator.validateMaxLength(
BaseProductDetailFncVO.C_SYS_CODE_DESCRIPTION,
m_sysCodeSrc,
BaseTplProductEntity.C_SYS_CODE_SIZE,
errors );
ODSValidator.validateMaxLength(
BaseProductDetailFncVO.C_PROD_FAML_CODE_DESCRIPTION,
m_prodFamlCodeSrc,
BaseTplProductEntity.C_PROD_FAML_NAME_SIZE,
errors );
ODSValidator.validateMaxLength(
BaseProductDetailFncVO.C_PROD_CODE_DESCRIPTION,
m_prodCodeSrc,
BaseTplProductEntity.C_PROD_CODE_SIZE,
errors );
ODSValidator.validateMaxLength(
BaseProductDetailFncVO.C_PROD_NAME_DESCRIPTION,
m_prodNameSrc,
BaseTplProductEntity.C_PROD_NAME_SIZE,
errors );
return errors;
}
/**
* @return
*/
public ArrayList getListProduct() {
return m_listProduct;
}
/**
* @param list
*/
public void setListProduct(ArrayList m_listProduct_) {
m_listProduct = m_listProduct_;
}
}
|
package com.oheers.fish.events;
import com.gmail.nossr50.events.McMMOReplaceVanillaTreasureEvent;
import com.gmail.nossr50.events.skills.fishing.McMMOPlayerFishingTreasureEvent;
import com.oheers.fish.EvenMoreFish;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
public class McMMOTreasureEvent implements Listener {
@EventHandler
public void mcmmoTreasure(McMMOReplaceVanillaTreasureEvent event) {
if (EvenMoreFish.mainConfig.disableMcMMOTreasure()) {
if (EvenMoreFish.mainConfig.isCompetitionUnique()) {
if (EvenMoreFish.active != null) {
event.setReplacementItemStack(event.getOriginalItem().getItemStack());
}
} else {
event.setReplacementItemStack(event.getOriginalItem().getItemStack());
}
}
}
@EventHandler
public void mcmmoTreasure(McMMOPlayerFishingTreasureEvent event) {
if (EvenMoreFish.mainConfig.disableMcMMOTreasure()) {
if (EvenMoreFish.mainConfig.isCompetitionUnique()) {
if (EvenMoreFish.active != null) {
event.setTreasure(null);
}
} else {
event.setTreasure(null);
}
}
}
}
|
package br.com.projetointegrador.controles;
import java.util.ArrayList;
import java.util.List;
import br.com.projetointegrador.entidades.Produto;
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;
public class ControleProduto {
private static final String NOME_BANCO = "HJVendas";
private static final String NOME_TABELA = "produto";
protected SQLiteDatabase db;
public ControleProduto(Context ctx) {
db = ctx.openOrCreateDatabase(NOME_BANCO, Context.MODE_PRIVATE, null);
}
public long salvar(Produto produto) {
long id = produto.getId();
if (id != 0) {
atualizar(produto);
} else {
id = inserir(produto);
}
return id;
}
public long inserir(Produto produto) {
ContentValues valores = new ContentValues();
valores.put(Produto.colunas[1], produto.getDescMaterial());
valores.put(Produto.colunas[2], produto.getDuracao());
valores.put(Produto.colunas[3], produto.getNome());
valores.put(Produto.colunas[4], produto.getNumero());
valores.put(Produto.colunas[5], produto.getProduto());
valores.put(Produto.colunas[6], produto.getTamanho()); // acessorio
valores.put(Produto.colunas[7], produto.getTamanhoSalto());
valores.put(Produto.colunas[8], produto.getTempoDuracao());
valores.put(Produto.colunas[9], produto.getValor());
valores.put(Produto.colunas[10], produto.getVolume());
valores.put(Produto.colunas[11], produto.getVolumeCosmetico());
valores.put(Produto.colunas[12], produto.getCor().getId());
valores.put(Produto.colunas[13], produto.getFornecedor().getId());
valores.put(Produto.colunas[14], produto.getParteDoCorpo().getId());
valores.put(Produto.colunas[15], produto.getGenero().getId());
valores.put(Produto.colunas[16], produto.getTipoProduto().getId());
long id = inserir(valores);
return id;
}
public long inserir(ContentValues v) {
long id = db.insert(NOME_TABELA, "", v);
return id;
}
public int atualizar(Produto produto) {
ContentValues valores = new ContentValues();
valores.put(Produto.colunas[1], produto.getDescMaterial());
valores.put(Produto.colunas[2], produto.getDuracao());
valores.put(Produto.colunas[3], produto.getNome());
valores.put(Produto.colunas[4], produto.getNumero());
valores.put(Produto.colunas[5], produto.getProduto());
valores.put(Produto.colunas[6], produto.getTamanho());
valores.put(Produto.colunas[7], produto.getTamanhoSalto());
valores.put(Produto.colunas[8], produto.getTempoDuracao());
valores.put(Produto.colunas[9], produto.getValor());
valores.put(Produto.colunas[10], produto.getVolume());
valores.put(Produto.colunas[11], produto.getVolumeCosmetico());
valores.put(Produto.colunas[12], produto.getCor().getId());
valores.put(Produto.colunas[13], produto.getFornecedor().getId());
valores.put(Produto.colunas[14], produto.getParteDoCorpo().getId());
valores.put(Produto.colunas[15], produto.getGenero().getId());
valores.put(Produto.colunas[16], produto.getTipoProduto().getId());
String _id = String.valueOf(produto.getId());
String where = "produto.id =?";
String[] whereArgs = new String[] { _id };
int count = atualizar(valores, where, whereArgs);
return count;
}
public int atualizar(ContentValues v, String where, String[] whereArgs) {
int count = db.update(NOME_TABELA, v, where, whereArgs);
return count;
}
public int deletar(long id) {
String _id = String.valueOf(id);
String where = "produto.id =?";
String[] whereArgs = new String[] { _id };
int count = deletar(where, whereArgs);
return count;
}
public int deletar(String where, String[] whereArgs) {
int count = db.delete(NOME_TABELA, where, whereArgs);
return count;
}
public List<Produto> listarProdutos() {
Cursor c = getCursor();
List<Produto> lista = new ArrayList<Produto>();
if (c.moveToFirst()) {
do {
Produto proximo = new Produto();
proximo.setId(c.getLong(0));
proximo.setNome(c.getString(3));
proximo.setProduto(c.getString(5));
proximo.setValor(c.getDouble(9));
lista.add(proximo);
}while (c.moveToNext());
}
return lista;
}
public Cursor getCursor(){
try {
return db.query(NOME_TABELA, Produto.colunas, null, null, null, null, null);
} catch (SQLException e){
Log.e("Controle Produto", "Erro ao buscar todas os Produto, execeção: " + e.toString());
return null;
}
}
public List<Produto> autoCompleta(CharSequence texto){
List<Produto> lista = new ArrayList<Produto>();
Cursor c = db.rawQuery("" +
"select id, nome, valor, produto from Produto where nome like '%" + texto + "%'", null);
if (c.moveToFirst()) {
do {
Produto proximo = new Produto();
proximo.setId(c.getLong(0));
proximo.setNome(c.getString(1));
proximo.setValor(c.getDouble(2));
proximo.setProduto(c.getString(3));
lista.add(proximo);
}while (c.moveToNext());
}
return lista;
}
public void fechar() {
if (db != null) {
db.close();
}
}
public Produto buscarProduto(long id, Context context) {
Cursor c = db.query(true, NOME_TABELA, Produto.colunas, " Produto.id ="
+ id, null, null, null, null, null);
if (c.getCount() > 0) {
c.moveToFirst();
Produto busca = new Produto();
busca.setId(c.getLong(0));
busca.setDescMaterial(c.getString(1));
busca.setDuracao(c.getLong(2));
busca.setNome(c.getString(3));
busca.setNumero(c.getLong(4));
busca.setProduto(c.getString(5));
busca.setTamanho(c.getString(6));
busca.setTamanhoSalto(c.getLong(7));
busca.setTempoDuracao(c.getString(8));
busca.setValor(c.getDouble(9));
busca.setVolume(c.getLong(10));
busca.setVolumeCosmetico(c.getString(11));
busca.setCor(new ControleCorProduto(context).buscarCorProduto(c.getLong(12)));
busca.setFornecedor(new ControleFornecedor(context).buscarFornecedor(c.getLong(13), context));
busca.setParteDoCorpo(new ControleParteDoCorpo(context).buscarParteDoCorpo(c.getLong(14)));
busca.setGenero(new ControleGeneroProduto(context).buscarGeneroProduto(c.getLong(15)));
busca.setTipoProduto(new ControleTipoProduto(context).buscarTipoProduto(c.getLong(16)));
return busca;
}
return null;
}
}
|
package demo;
import java.util.Scanner;
public class Weather {
public static void main(String[] args) {
final int NUMBER_OF_DAYS = 10;
final int NUMBER_OF_HOURS = 24;
double[][][] data = new double [NUMBER_OF_DAYS][NUMBER_OF_HOURS][2];
Scanner input = new Scanner(System.in);
for (int k = 0 ; k < NUMBER_OF_DAYS * NUMBER_OF_HOURS ; k++) {
int day = input.nextInt();
int hour = input.nextInt();
double temperature = input.nextDouble();
double humidity = input.nextDouble();
data [day-1][hour-1][0] = temperature;
data [day-1][hour-1][0] = humidity;
}
for (int i = 0 ; i < NUMBER_OF_DAYS ; i++) {
double totalDailyTemp = 0;
double totalDailyHum = 0;
for( int j = 0 ; j < NUMBER_OF_HOURS ; j++) {
totalDailyTemp += data[i][j][0];
totalDailyHum += data[i][j][1];
}
System.out.println("Average daily temp is " + totalDailyTemp/NUMBER_OF_HOURS);
System.out.println("Average daily humidity is " + totalDailyHum/NUMBER_OF_HOURS);
}
input.close();
}
}
|
package ru.otus.sua.L07.atm.staff;
public class ImpossibleDischarging extends Exception {
public ImpossibleDischarging(String message) {
super(message);
}
}
|
package e250;
import java.util.BitSet;
/**
* @author 方康华
* @title CountPrimes
* @projectName leetcode
* @description No.204 Easy
* @date 2019/9/1 19:50
*/
public class CountPrimes {
// 筛法求质数
public int countPrimes(int n) {
boolean[] flags = new boolean[n];
for(int i = 0; i < n; i++) {
flags[i] = true;
}
int count = 0;
for(int i = 2; i < n; i++) {
if(flags[i]) count++;
for(int j = i + i; j < n; j += i){
flags[j] = false;
}
}
return count;
}
// 方法2
public int countPrimes2(int n) {
BitSet s = new BitSet(n);
for(int i = 0; i < n; i++) {
s.set(i);
}
int count = 0;
for(int i = 2; i < n; i++) {
if(s.get(i)) count++;
for(int j = i + i; j < n; j += i){
s.clear(j);
}
}
return count;
}
public static void main(String[] args) {
new CountPrimes().countPrimes2(10);
}
}
|
package com.buddybank.mdw.dataobject.narayana;
import java.io.Serializable;
import org.jboss.narayana.compensations.api.CompensationScoped;
@CompensationScoped
public class NarayanaData implements Serializable {
private static final long serialVersionUID = -752668644374140827L;
private String narayanaField;
public String getNarayanaField() {
return narayanaField;
}
public void setNarayanaField(String narayanaField) {
this.narayanaField = narayanaField;
}
}
|
package pp.model.comparators;
import pp.model.xml.CGlad;
import java.util.Comparator;
/**
* Created by IntelliJ IDEA.
* User: alsa
* Date: 07.12.11
* Time: 16:46
* To change this template use File | Settings | File Templates.
*/
public class CombinationComparator implements Comparator<CGlad> {
private Comparator<CGlad>[] comparators;
public CombinationComparator(Comparator<CGlad> ... comparators) {
this.comparators = comparators;
}
@Override
public int compare(CGlad o1, CGlad o2) {
int result = 0;
for (Comparator<CGlad> comparator : comparators) {
result = comparator.compare(o1, o2);
if (result != 0) break;
}
return result;
}
}
|
package com.factory.factoryupdatedetails.service;
import com.factory.factoryupdatedetails.model.ApplicationModel;
/**
* Author: Amit
* Date: 03-01-2020
*/
public interface ApplicationUpdateService {
public int getUpdateApplicationDetailsById(ApplicationModel applicationModel);
}
|
package ciclos;
public class EjemploDoWhile {
public static void main(String[] args) {
// TODO Auto-generated method stub
int b = 10;
do {System.out.println("el valor de B es:" +b);
b++;
}while(b<20);
}
}
|
package com.alibaba.druid.sql.dialect.mysql.ast;
/**
* @author lijun.cailj 2018/8/14
*/
public enum FullTextType {
CHARFILTER,
TOKENIZER,
TOKENFILTER,
ANALYZER,
DICTIONARY
}
|
/**
*
*/
package analysis;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JPopupMenu.Separator;
import drugbank.Drug;
import drugbank.DrugBank;
import drugbank.Partner;
import drugbank.Species;
import drugbank.TargetRelation;
import goa.GoAnnotation;
import gogogo.GoGoGoDataset;
/**
* @author Samuel Croset
*
*/
public class DrugBankContent {
private DrugBank drugBank;
private GoGoGoDataset data;
public void setData(GoGoGoDataset data) {
this.data = data;
}
public GoGoGoDataset getData() {
return data;
}
public void setDrugBank(DrugBank drugBank) {
this.drugBank = drugBank;
}
public DrugBank getDrugBank() {
return drugBank;
}
public DrugBankContent() throws FileNotFoundException, IOException, ClassNotFoundException {
this.setData(new GoGoGoDataset("data/dataset-filtered.ser"));
this.setDrugBank(this.getData().getDrugbank());
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
DrugBankContent analysis = new DrugBankContent();
// analysis.GroupsDistribution();
// analysis.TypesDistributionForNonExperimentalDrugs();
// analysis.targetTypesDistributionFor("biotech");
// analysis.targetTypesDistributionFor("small molecule");
// analysis.targetTypesNonProteinDistribution("biotech");
// analysis.targetTypesNonProteinDistribution("small molecule");
// analysis.NonExperimentalDrugsWithAnnotatedPartners();
}
private void NonExperimentalDrugsWithAnnotatedPartners() {
ArrayList<Drug> relevantDrugs = new ArrayList<Drug>();
ArrayList<Drug> nonAnnotatedDrugs = new ArrayList<Drug>();
for (Drug drug : this.getDrugBank().getNonExperimentalDrugs()) {
boolean hasAnAnnotationAtLeast = false;
for (TargetRelation relation : drug.getTargetRelations()) {
int partnerId = relation.getPartnerId();
Partner partner = this.getDrugBank().getPartner(partnerId);
if(partner.getNonIEAAnnotations() != null && partner.getNonIEAAnnotations().size() > 0){
hasAnAnnotationAtLeast = true;
if(!relevantDrugs.contains(drug)){
relevantDrugs.add(drug);
}
}
}
if(hasAnAnnotationAtLeast == false){
nonAnnotatedDrugs.add(drug);
}
}
System.out.println("Number of relevant: " + relevantDrugs.size()
+ " Total: " + this.getDrugBank().getNonExperimentalDrugs().size()
+ " Non-Annotated: " + nonAnnotatedDrugs.size()
);
for (Drug drug : nonAnnotatedDrugs) {
System.out.println(drug.getId());
}
}
private void targetTypesNonProteinDistribution(String type) {
Distribution<String> distribution = new Distribution<String>();
for (Drug drug : this.getDrugBank().getDrugs()) {
if(drug.getType().equals(type) && drug.isExperimental() == false){
for (Partner partner : this.getDrugBank().getPartners(drug.getId())) {
if(partner.getUniprotIdentifer() == null){
distribution.add(partner.getName());
}
}
}
}
distribution.printReport();
}
private void targetTypesDistributionFor(String type) {
Distribution<String> distribution = new Distribution<String>();
for (Drug drug : this.getDrugBank().getDrugs()) {
if(drug.getType().equals(type) && drug.isExperimental() == false){
for (Partner partner : this.getDrugBank().getPartners(drug.getId())) {
if(partner.getUniprotIdentifer() != null){
distribution.add("gene-product");
}else{
distribution.add("other");
}
}
}
}
distribution.printReport();
}
private void TypesDistributionForNonExperimentalDrugs() {
Distribution<String> distribution = new Distribution<String>();
for (Drug drug : this.getDrugBank().getDrugs()) {
if(drug.isExperimental() == false){
distribution.add(drug.getType());
}
}
distribution.printReport();
}
private void GroupsDistribution() {
Distribution<String> distribution = new Distribution<String>();
for (Drug drug : this.getDrugBank().getDrugs()) {
distribution.add(drug.getGroups().toString());
}
distribution.printReport();
}
}
|
import java.util.Random;
public class Shuffle {
public static void shuffle(int[] cards, int n) {
Random rand = new Random();
for(int i = 0; i < n; i++) {
swap(cards, i, (Math.abs(rand.nextInt()) % (n - i)) + i);
}
}
public static void swap(int[] arr, int a, int b) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
public static void main(String[] args) {
int[] cards = new int[52];
for(int i = 0; i < 52; i++)
cards[i] = i + 1;
for(int i = 0; i < 52; i++)
System.out.print(cards[i] + " ");
System.out.println();
shuffle(cards, 52);
for(int i = 0; i < 52; i++)
System.out.print(cards[i] + " ");
System.out.println();
}
}
|
import java.awt.Color;
import javax.swing.JFrame;
public class GuessingGameApplication {
protected TreeFileReader fileReader;
//dimensions of the JFrame
protected static final int HEIGHT= 700;
protected static final int WIDTH = 600;
/**
* creates a JFrame for the IceCreamMaker and sets the size of the window
*/
public GuessingGameApplication(){
fileReader= new TreeFileReader();
JFrame Frame = new JFrame ("20 Questions game");
Frame.setSize(WIDTH,HEIGHT);
Color light_blue= new Color(51, 204, 255);
//JFrame.getContentPanel().setBackground(light_blue);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(new GuessingGame());
Frame.setVisible(true);
}
/**
* main method starts the game
*/
public static void main(java.lang.String[] args){
new GuessingGameApplication();
}
}
|
package ex0428;
public class SCVO {
private String scode;
private String sname;
private String sdept;
private int year;
public String getScode() {
return scode;
}
public void setScode(String scode) {
this.scode = scode;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSdept() {
return sdept;
}
public void setSdept(String sdept) {
this.sdept = sdept;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.