text
stringlengths 10
2.72M
|
|---|
public class Solution {
public int reverse(int x) {
long result = 0; //data type is long not int. But why???
while(x!=0){
result = result*10 + x%10;
x /= 10;
if(result >= Integer.MAX_VALUE || result <= Integer.MIN_VALUE) //prevent integer overflows
return 0;
}
return (int)result;
}
}
|
package BIO;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class TCPClient {
public static void main(String[] args) throws Exception{
while (true){
Socket s=new Socket("127.0.0.1",9999);
//取出输出流发消息
OutputStream os=s.getOutputStream();
System.out.println("请输入");
Scanner sc=new Scanner(System.in);
String msg=sc.nextLine();
os.write(msg.getBytes());
//取出输入流发消息
InputStream is=s.getInputStream();
byte[]b=new byte[20];
is.read(b);
System.out.println("老板说:"+new String(b).trim());
s.close();
}
}
}
|
package com.laiweifeng.launcher.widget;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.laiweifeng.launcher.R;
public class AppImageView extends RelativeLayout {
private ImageView iv_app;
private ImageView iv_status;
public static final int DEFAULT=-1;
public static final int TOPPING=0;
public static final int DELETE=1;
private int mStatus=DEFAULT;
private OnAppClickListener onAppClickListener;
private View rootview;
private OnAppFocusChangeListener onAppFocusChangeListener;
public AppImageView(Context context) {
this(context,null);
}
public AppImageView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public AppImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
View.inflate(context, R.layout.widget_app_image,this);
rootview = findViewById(R.id.rootview);
iv_app = findViewById(R.id.iv_app);
iv_status = findViewById(R.id.iv_status);
rootview. setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
if(onAppFocusChangeListener!=null){
Object tag = rootview.getTag();
int position=-1;
if(tag!=null){
position=(int)tag;
}
onAppFocusChangeListener.onFocusChange(position);
}
if(mStatus==TOPPING){
iv_status.setVisibility(View.VISIBLE);
iv_status.setImageResource(R.drawable.icon_dingzhi);
}else if(mStatus==DELETE){
iv_status.setVisibility(View.VISIBLE);
iv_status.setImageResource(R.drawable.delete_icon);
}else{
iv_status.setVisibility(View.GONE);
}
zoomInView(AppImageView.this);
}else{
iv_status.setVisibility(View.GONE);
zoomOutView(AppImageView.this);
}
}
});
rootview.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(onAppClickListener!=null){
Object tag = rootview.getTag();
int position=-1;
if(tag!=null){
position=(int)tag;
}
onAppClickListener.onAppClick(position);
}
}
});
}
private void zoomInView(View v){
AnimatorSet animSet = new AnimatorSet();
float[] values = new float[] { 1.0f ,1.18f };
animSet.playTogether(ObjectAnimator.ofFloat(v, "scaleX", values),
ObjectAnimator.ofFloat(v, "scaleY", values));
animSet.setDuration(300).start();
}
private void zoomOutView(View v){
AnimatorSet animSet = new AnimatorSet();
float[] values = new float[] { 1.18f ,1.0f };
animSet.playTogether(ObjectAnimator.ofFloat(v, "scaleX", values),
ObjectAnimator.ofFloat(v, "scaleY", values));
animSet.setDuration(300).start();
}
public void setAppIcon(String iconPath){
Bitmap bitmap = BitmapFactory.decodeFile(iconPath);
iv_app.setImageBitmap(bitmap);
}
public void setPosition(int position){
rootview.setTag(position);
}
public void setStatus(int status){
this.mStatus=status;
}
public void setOnAppClickListener(OnAppClickListener listener){
this.onAppClickListener=listener;
}
public interface OnAppClickListener{
void onAppClick(int position);
}
public void setOnAppFocusChangeListener(OnAppFocusChangeListener listener){
this.onAppFocusChangeListener=listener;
}
public interface OnAppFocusChangeListener{
void onFocusChange(int position);
}
}
|
package com.imooc.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/*
* 备选课程类
*/
public class ListTest {
/*
* 用于存放备选课程的list
*/
public List coursesToSelect;
//创建构造方法实例化coursesToSelect
public ListTest(){
this.coursesToSelect = new ArrayList();
//实例化coursesToSelect,List是接口,只能用ArryList
}
/*
* 用于往coursesToSelect中添加备选课程
*/
public void testAdd(){
//创建一个课程对象,并通过add方法添加到备选课程List中
Course cr1 = new Course("1", "数据结构");
coursesToSelect.add(cr1);
//也可以这样写,两种写法
coursesToSelect.add(new Course("1", "数据结构"));
Course temp = (Course) coursesToSelect.get(0);
System.out.println("添加了课程:\n" + temp.id + ":" + temp.name);
/*
* 需要取出元素进行输出
* 但对象存入集合中都会变成object类型
* 取出时需要类型转换
*/
//也可以把数据插在指定位置
coursesToSelect.add(0,new Course("2", "替换算法"));
Course temp2 = (Course) coursesToSelect.get(0);
System.out.println("添加了课程:\n" + temp2.id + ":" + temp2.name);
// 该方法会抛出数组下标越界异常,只能插当前元素后面
// Course cr3 = new Course("3", "test");
// coursesToSelect.add(4,cr3);
Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")};
coursesToSelect.addAll(Arrays.asList(course));
//通过该方法可以把数组插入list
Course temp3 = (Course) coursesToSelect.get(3);
Course temp4 = (Course) coursesToSelect.get(4);
System.out.println("添加了两门课程:\n" + temp3.id + ":" + temp3.name
+ ";" + temp4.id + ":" + temp4.name);
//方法一样,也可以把数组插在指定位置,不再写后面代码
// Course[] course2 = {new Course("5","高等数学"),new Course("6","大学英语")};
// coursesToSelect.addAll(2,Arrays.asList(course));
}
public void testGet(){
int size = coursesToSelect.size();
System.out.println("有以下课程可待选:");
for(int i = 0 ; i <size ; i++){
Course cr = (Course) coursesToSelect.get(i);
System.out.println("课程:" + cr.id + ";" + cr.name);
}
}
//list的元素是可重复添加,并且有序的
//通过迭代器遍历list
public void testIterator(){
Iterator it = coursesToSelect.iterator();
System.out.println("有以下课程可待选(通过迭代器访问):");
while(it.hasNext()){
Course cr = (Course) it.next();
System.out.println("课程:" + cr.id + ";" + cr.name);
}
}
//通过foreach遍历list,属于迭代器简写版
public void testForEach(){
System.out.println("有以下课程可待选(通过ForEach访问):");
for(Object oj : coursesToSelect){
Course cr = (Course) oj;
System.out.println("课程:" + cr.id + ";" + cr.name);
}
}
//课程修改
public void testModify(){
coursesToSelect.set(1, new Course("2","C语言"));
}
//课程删除
public void testRemove(){
Course cr = (Course) coursesToSelect.get(4);
System.out.println("我是课程:" + cr.id + ";" + cr.name + ",我即将被删除");
coursesToSelect.remove(cr);
//也可以这样写,但不知道具体元素,存在误删
// coursesToSelect.remove(4);
System.out.println("成功删除");
testForEach();
}
public void testRemoveAll(){
System.out.println("即将删除1和2位置上的课程!");
Course[] courses = {(Course) coursesToSelect.get(1) , (Course) coursesToSelect.get(2)};
coursesToSelect.removeAll(Arrays.asList(courses));
System.out.println("成功删除");
testForEach();
}
public static void main(String[] args) {
ListTest lt = new ListTest();
lt.testAdd();
lt.testGet();
lt.testIterator();
lt.testForEach();
lt.testModify();
lt.testForEach();
lt.testRemove();
lt.testRemoveAll();
}
}
|
package LinkRecursiveAction;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.concurrent.CopyOnWriteArrayList;
public class TreeNode {
private CopyOnWriteArrayList<Node> allNode;
private Node parent;
public TreeNode() {
this.allNode = new CopyOnWriteArrayList<Node>();
}
public TreeNode(Node parent) {
this.allNode = new CopyOnWriteArrayList<Node>();
this.parent = parent;
allNode.add(parent);
}
public Node getNode(Node node) {
for (Node n : allNode
) {
if (n.equals(node)) {
return node;
}
}
return null;
}
public boolean contains(Node node) {
return allNode.contains(node);
}
public void add(Node node) {
allNode.add(node);
}
public Node get(int i) {
return allNode.get(i);
}
public int size() {
return allNode.size();
}
public void printTreeNode(CopyOnWriteArrayList<Node> nodes, String tab) {
// System.out.println(allNode.get(0).getListChild());
for (Node n : nodes
) {
System.out.println(tab + n.getData());
if (n.isParent()) {
printTreeNode(n.getListChild(), "\t" + tab);
}
}
}
public void writeTreeNode(Node parent, String tab) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("site_map_node.txt"/*, true*/)))) {
System.out.println(parent.getData());
out.println(parent.getData());
writeNodes(parent, tab, out);
} catch (Exception e) {
e.printStackTrace();
}
}
private void writeNodes(Node parent, String tab, PrintWriter out) {
for (Node n : parent.getListChild()
) {
System.out.println(tab + n.getData());
out.println(tab + n.getData());
if (n.isParent()) {
writeNodes(n, "\t" + tab,out);
}
}
}
private void writeString(String s){
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("site_map_node.txt"/*, true*/)))){
out.println(s);
}catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.aktway.services.profile.resource;
import com.aktway.services.profile.api.response.*;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.inject.Inject;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
@RestController
@Produces(MediaType.APPLICATION_JSON)
public class ServiceResource {
@Inject
FollowersProfileData followersProfileData;
@Inject
FollowingProfileData followingProfileData;
@Inject
FolloweesPostData followeesPostData;
@Inject
MyPublicPostData myPublicPostData;
@Inject
MyPrivatePostData myPrivatePostData;
private static final Logger LOGGER = Logger.getLogger(ServiceResource.class.getName());
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/followersprofile")
public List<FollowersProfileData> getFollowersProfileData(@RequestParam("accessToken") String accessToken) {
List<FollowersProfileData> result = new ArrayList<>();
followersProfileData.setProfileName("Narendra Manam");
followersProfileData.setFollowersCount(10);
followersProfileData.setFollowingCount(8);
followersProfileData.isFollwing();
followersProfileData.isFriend();
followersProfileData.setGender("M");
followersProfileData.setProfilePicture("../../../assets/images/mockData/narendra_manam.jpg");
result.add(followersProfileData);
return result;
}
@RequestMapping("/followingprofile")
public List<FollowingProfileData> getFollowingProfileData(@RequestParam("accessToken") String accessToken) {
List<FollowingProfileData> result = new ArrayList<>();
followingProfileData.setProfileName("Narendra Manam");
followingProfileData.setFollowersCount(10);
followingProfileData.setFollowingCount(8);
followingProfileData.isFriend();
followingProfileData.setGender("M");
followingProfileData.setProfilePicture("../../../assets/images/mockData/narendra_manam.jpg");
result.add(followingProfileData);
return result;
}
@RequestMapping("/followeespost")
public List<FolloweesPostData> getFolloweesPostData(@RequestParam("accessToken") String accessToken) {
List<FolloweesPostData> result = new ArrayList<>();
followeesPostData.setPostName("My new car");
followeesPostData.setTagList(Arrays.asList("#Bangalore"));
followeesPostData.setPostedBy("Narendra");
followeesPostData.setGender("M");
followeesPostData.setLikeCount(12);
followeesPostData.setCommentCount(21);
followeesPostData.setTagCount(5);
followeesPostData.isLiked();
followeesPostData.setPostId("A0001");
followeesPostData.setPostedDate("Mon Jun 10 2019 13:45:44 GMT+0530 (India Standard Time)");
followeesPostData.setUserProfilePic("../../../assets/images/mockData/narendra_manam.jpg");
followeesPostData.setPostPicture("../../../assets/images/mockData/posts/car_image-2.jpg");
result.add(followeesPostData);
return result;
}
@RequestMapping("/publicpost")
public List<MyPublicPostData> getMyPublicPostData(@RequestParam("accessToken") String accessToken) {
List<MyPublicPostData> result = new ArrayList<>();
myPublicPostData.setPostName("Beautiful bird");
myPublicPostData.setLikeCount(16392);
myPublicPostData.setCommentCount(2051);
myPublicPostData.setTagCount(5895);
myPublicPostData.setPostId("MPUA0010");
myPublicPostData.setPostedDate("Sun Feb 24 2019 17:15:44 GMT+0530 (India Standard Time)");
myPublicPostData.setPostPicture("../../../assets/images/mockData/posts/post_bird-1.jpg");
result.add(myPublicPostData);
return result;
}
@RequestMapping("/privatepost")
public List<MyPrivatePostData> getMyPrivatePostData(@RequestParam("accessToken") String accessToken) {
List<MyPrivatePostData> result = new ArrayList<>();
myPrivatePostData.setPostName("Nice building");
myPrivatePostData.setTagList(Arrays.asList("#Malaysia"));
myPrivatePostData.setPostId("MPRA0006");
myPrivatePostData.setPostedDate("Tue Jan 01 2019 12:00:44 GMT+0530 (India Standard Time)");
myPrivatePostData.setPostPicture("../../../assets/images/mockData/posts/post_location-1.jpg");
result.add(myPrivatePostData);
return result;
}
}
|
package java2.businesslogic.announcementcreation;
import java2.businesslogic.ValidationError;
import java2.database.AnnouncementDatabase;
import java2.database.UserDatabase;
import java2.domain.Announcement;
import java2.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
//@Component
public class AddAnnouncementValidator {
@Autowired private AnnouncementDatabase announcementDatabase;
@Autowired private UserDatabase userDatabase;
public List<ValidationError> validate(String login, String title, String description) {
List<ValidationError> errors = new ArrayList<>();
Optional<ValidationError> emptyLoginError = validateLogin(login);
emptyLoginError.ifPresent(error -> errors.add(error));
Optional<ValidationError> emptyTitleError = validateTitle(title);
emptyTitleError.ifPresent(error -> errors.add(error));
validateDescription(description).ifPresent(error -> errors.add(error));
if(!emptyLoginError.isPresent()) {
validateUserPresence(login).ifPresent(errors::add);
}
if(!emptyTitleError.isPresent()) {
validateDuplicateTitle(title).ifPresent(errors::add);
}
return errors;
}
private Optional<ValidationError> validateLogin(String login) {
if(login == null || login.isEmpty()) {
return Optional.of(new ValidationError("login", "Must not be empty!"));
} else {
return Optional.empty();
}
}
private Optional<ValidationError> validateTitle(String title) {
if(title == null || title.isEmpty()) {
return Optional.of(new ValidationError("title", "Must not be empty!"));
} else {
return Optional.empty();
}
}
private Optional<ValidationError> validateDescription(String description) {
if(description == null || description.isEmpty()) {
return Optional.of(new ValidationError("description", "Must not be empty!"));
} else {
return Optional.empty();
}
}
private Optional<ValidationError> validateDuplicateTitle(String title) {
if(title != null && !title.isEmpty()) {
Optional<Announcement> announcementOpt = announcementDatabase.findByTitle(title);
if(announcementOpt.isPresent()) {
return Optional.of(new ValidationError("title", "Must not be repeated!"));
}
}
return Optional.empty();
}
private Optional<ValidationError> validateUserPresence(String login) {
Optional<User> userFound = userDatabase.findByLogin(login);
if(!userFound.isPresent()) {
return Optional.of(new ValidationError("login", "User not found!"));
} else {
return Optional.empty();
}
}
}
|
package com.example.a.projectcompanyhdexpertiser.Controller;
import android.content.Context;
import android.telephony.SmsManager;
import android.widget.Toast;
public class SMSMailer {
public void sendSMS(final Context context, String phone, String message) {
try {
Toast.makeText(context, "Đang gủi tin nhắn số điện thoại:" + phone + "\n" + "Nội dung tin nhắn:" + message, Toast.LENGTH_SHORT).show();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phone, null, message, null, null);
Toast.makeText(context, "Thành Công....", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Toast.makeText(context, "SMS thất bại, vui lòng thử lại.", Toast.LENGTH_SHORT).show();
}
}
}
|
package com.myflappybird.service;
import com.myflappybird.dto.GameDto;
import com.myflappybird.img.Img;
import com.myflappybird.music.Music;
import java.awt.*;
import java.io.IOException;
public class Pillars {
/**
* 数据传输层
*/
GameDto dto;
/**
* 柱子内部类
*/
private class Pillar {
/**
* 柱子的长度
*/
private static final int PILLAR_W = 70;
/**
* 柱子的宽度
*/
private static final int PILLAR_H = 500;
/**
* 柱子的X坐标
*/
private int pillarX;
/**
* 柱子的Y坐标
*/
private int pillarY;
public Pillar(int pillarX, int pillarY) {
this.pillarX = pillarX;
this.pillarY = pillarY;
}
/**
* 绘制柱子
*/
public void drawPillar(Graphics g, Image img) {
g.drawImage(img, pillarX, pillarY, null);
}
}
/**
* 上方柱子
*/
private Pillar abovePillar;
/**
* 下方柱子
*/
private Pillar belowPillar;
/**
* 柱子移动的速度
*/
private final int PILLARS_SPEED = 8;
/**
* 柱子的
*/
private int y;
public Pillars(GameDto dto, int pillarsX) {
this.dto = dto;
y = 200 + (int) (Math.random() * 300);
abovePillar = new Pillar(pillarsX, -y);
belowPillar = new Pillar(pillarsX, 700 - y);
}
/**
* 左移
*/
public void moveX() {
// 计算分数
this.calcScore();
// 是否暂停或小鸟是否死亡
if (this.dto.isPause() || this.dto.isBirdDead()) {
return;
}
// 柱子的上下移动
if (abovePillar.pillarX < -Pillar.PILLAR_W || belowPillar.pillarX < -Pillar.PILLAR_W) {
abovePillar.pillarX = 650;
belowPillar.pillarX = 650;
y = 200 + (int) (Math.random() * 300);
abovePillar.pillarY = -y;
belowPillar.pillarY = 700 - y;
}
abovePillar.pillarX -= PILLARS_SPEED;
belowPillar.pillarX -= PILLARS_SPEED;
}
public void moveY() {
int i = 0;
for (; abovePillar.pillarY >= (-y) && abovePillar.pillarY <= (-y + 50) && i == 0; i++) {
abovePillar.pillarY++;
}
}
/**
* 计算分数
*/
public void calcScore() {
if (this.goThroughBird()) {
int score = this.dto.getScore();
score++;
this.dto.setScore(score);
}
}
/**
* 用以上柱子碰撞检测
*/
public Rectangle getRect1() {
return new Rectangle(abovePillar.pillarX, abovePillar.pillarY, Pillar.PILLAR_W, Pillar.PILLAR_H);
}
/**
* 用以下柱子碰撞检测
*/
public Rectangle getRect2() {
return new Rectangle(belowPillar.pillarX, belowPillar.pillarY, Pillar.PILLAR_W, Pillar.PILLAR_H);
}
/**
* 通过柱子的音效
*/
public void throughMusic() {
if (this.goThroughBird()) {
try {
Music throughMusic = new Music("Music/point.wav");
throughMusic.musicPlay();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 绘制柱子
*/
public void drawPillars(Graphics g) {
// 绘制上柱子
abovePillar.drawPillar(g, Img.pillar0);
// 绘制下柱子
belowPillar.drawPillar(g, Img.pillar1);
}
/**
* 小鸟是否穿过
*/
public boolean goThroughBird() {
return abovePillar.pillarX >= (100 - PILLARS_SPEED / 2) && abovePillar.pillarX <= (100 + PILLARS_SPEED / 2);
}
}
|
package com.example.raiko.top10downloader;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ListView listApps;
private String feedUrl = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=%d/xml";
private int feedLimit = 10;
private String feedCachedUrl = "Invalidated";
public static final String STATE_URL = "feedUrl";
public static final String STATE_LIMIT = "feedLimit";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listApps = (ListView) findViewById(R.id.xmlListView);
if (savedInstanceState != null) {
feedUrl = savedInstanceState.getString(STATE_URL);
feedLimit = savedInstanceState.getInt(STATE_LIMIT);
}
downloadUrl(String.format(feedUrl, feedLimit));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.feeds_menu, menu);
if (feedLimit == 10) {
menu.findItem(R.id.mnu10).setChecked(true);
} else {
menu.findItem(R.id.mnu25).setCheckable(true);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.mnuFree:
feedUrl = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=%d/xml";
break;
case R.id.mnuPaid:
feedUrl = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/toppaidapplications/limit=%d/xml";
break;
case R.id.mnuSongs:
feedUrl = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=%d/xml";
break;
case R.id.mnu10:
case R.id.mnu25:
if (!item.isChecked()){
item.setChecked(true);
feedLimit = 35 - feedLimit;
Log.d(TAG, "onOptionsItemSelected: " + item.getTitle() + " setting feedLimit to " + feedLimit);
} else {
Log.d(TAG, "onOptionsItemSelected: " + item.getTitle() + " feedLimit unchanged");
}
case R.id.mnuRefresh:
feedCachedUrl = "Invalidated";
break;
default:
return super.onOptionsItemSelected(item);
}
downloadUrl(String.format(feedUrl, feedLimit));
return true;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString(STATE_URL, feedUrl);
outState.putInt(STATE_LIMIT, feedLimit);
super.onSaveInstanceState(outState);
}
private void downloadUrl(String feedUrl){
// Checks if feedUrl has changed, if not means user is on same page, no extra download of data needed
if (!feedUrl.equalsIgnoreCase(feedCachedUrl)) {
Log.d(TAG, "downloadUrl: starting ASync task");
DownloadData downloadData = new DownloadData();
downloadData.execute(feedUrl);
feedCachedUrl = feedUrl;
Log.d(TAG, "downloadUrl: done");
} else {
Log.d(TAG, "downloadUrl: URL Not changed");
}
}
private class DownloadData extends AsyncTask<String, Void, String> {
private static final String TAG = "DownloadData";
@Override
protected String doInBackground(String... strings) {
Log.d(TAG, "doInBackground: starts with " + strings[0]);
// Downloads the contents of the xml and stores it in a string while in background
String rssFeed = downloadXML(strings[0]);
if (rssFeed == null) {
Log.e(TAG, "doInBackground: error download");
}
return rssFeed;
}
@Override
// Takes in the result from doInBackground method
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Log.d(TAG, "onPostExecute: parameter is " + s);
// Parses the previously downloaded xml data
ParseApplications parseApplications = new ParseApplications();
parseApplications.parse(s);
// Creates adapter, parameters needed context (comes later), resource is created list_item layout (looks for it in layout folder, hence R.layout not R.id), getApplications is a list of items to display
// ArrayAdapter<FeedEntry> arrayAdapter = new ArrayAdapter<FeedEntry>(MainActivity.this, R.layout.list_item, parseApplications.getApplications());
// Links the list view to the adapter
// listApps.setAdapter(arrayAdapter);
FeedAdapter<FeedEntry> feedAdapter = new FeedAdapter<>(MainActivity.this, R.layout.list_record, parseApplications.getApplications());
listApps.setAdapter(feedAdapter);
}
// @param takes in the url string from doInBackground method
private String downloadXML (String urlPath) {
StringBuilder xmlPath = new StringBuilder();
try {
// Creating a ref to the URL path
URL url = new URL(urlPath);
// Opening the http connection to url, server sends back response codes
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Storing the response code
int response = connection.getResponseCode();
Log.d(TAG, "downloadXML: The response code was " + response);
// // Getting the data from http connection as InputStream bytes
// InputStream inputStream = connection.getInputStream();
// // Translate inputStream data bytes into chars
// InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
// // Read the chars from inputStreamReader, can only read chars and not inputStream byte data directly
// BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
/**
* Does the same thing as 3 lines above
* 1) Sets up bufferedreader to read the data from a stream
* 2) Initialises new InputStreamReader to convert inputStream bytes to chars for buffered reader
* 3) Starts the inputStream from connection URL
*/
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
int charsRead;
// Initialize buffer char array to 500 chars in length.
char[] inputBuffer = new char[500];
// loops until there is data from InputStream
while (true) {
charsRead = bufferedReader.read(inputBuffer);
if (charsRead < 0) {
break;
}
// Holds count for number of characters read from stream
if (charsRead > 0) {
xmlPath.append(String.copyValueOf(inputBuffer, 0, charsRead));
}
}
// Closes the buffer reader, and other data stream methods (InputStream, StreamReader, etc)
bufferedReader.close();
// Converts stringbuilder char sequence to string
return xmlPath.toString();
} catch (MalformedURLException e) {
// Catch the http url exception (subclass of IOexception)
Log.e(TAG, "downloadXML: Invalid URL " + e.getMessage());
} catch (IOException e) {
// Catch IO exceptions from inputstream and readers
Log.e(TAG, "downloadXML: IOException reading data " + e.getMessage());
} catch (SecurityException e) {
Log.e(TAG, "downloadXML: Security Exception? Need Permission? " + e.getMessage());
// e.printStackTrace();
}
return null;
}
}
}
|
package domain;
public interface OverClocking {
void increaseTiming(double newTiming);
}
|
package com.rc.portal.webapp.action;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.springframework.util.StringUtils;
import com.rc.app.framework.webapp.action.BaseAction;
import com.rc.app.framework.webapp.model.page.PageWraper;
import com.rc.commons.util.InfoUtil;
import com.rc.dst.client.util.ClientSubmitPublic;
import com.rc.openapi.dubbo.model.TOrderGoodModel;
import com.rc.openapi.serviceApi.OrderServiceDubboApi;
import com.rc.portal.jms.MessageSender;
import com.rc.portal.payplugin.PaymentPlugin;
import com.rc.portal.payplugin.payWzf.util.Signature;
import com.rc.portal.payplugin.payWzf.util.WXTradeType;
import com.rc.portal.service.CDeliveryWayManager;
import com.rc.portal.service.CLocationCityManager;
import com.rc.portal.service.CPaymentWayManager;
import com.rc.portal.service.OpenSqlManage;
import com.rc.portal.service.PaymentPluginMaager;
import com.rc.portal.service.TCouponCardManager;
import com.rc.portal.service.TCouponManager;
import com.rc.portal.service.TGoodsManager;
import com.rc.portal.service.TLeaderStayMoneyManager;
import com.rc.portal.service.TMemberAccountManager;
import com.rc.portal.service.TMemberBaseMessageExtManager;
import com.rc.portal.service.TMemberReceiverLatLonManager;
import com.rc.portal.service.TOrderFlowManager;
import com.rc.portal.service.TOrderItemManager;
import com.rc.portal.service.TOrderManager;
import com.rc.portal.service.TSysParameterManager;
import com.rc.portal.util.NetworkUtil;
import com.rc.portal.util.OrderEnum;
import com.rc.portal.vo.CDeliveryWay;
import com.rc.portal.vo.CDeliveryWayExample;
import com.rc.portal.vo.CLocationCity;
import com.rc.portal.vo.CLocationCityExample;
import com.rc.portal.vo.CPaymentWay;
import com.rc.portal.vo.CPaymentWayExample;
import com.rc.portal.vo.TCouponCardExample;
import com.rc.portal.vo.TMember;
import com.rc.portal.vo.TMemberAccount;
import com.rc.portal.vo.TMemberBaseMessageExt;
import com.rc.portal.vo.TMemberReceiverLatLon;
import com.rc.portal.vo.TMemberReceiverLatLonExample;
import com.rc.portal.vo.TOrder;
import com.rc.portal.vo.TOrderExample;
import com.rc.portal.vo.TOrderFlow;
import com.rc.portal.vo.TOrderFlowExample;
import com.rc.portal.webapp.model.OrderGoodCart;
import com.rc.portal.webapp.util.PageResult;
/**
* 订单中心
* @author 刘天灵
*
*/
public class MemberOrderAction extends BaseAction{
private static final long serialVersionUID = 646464661L;
private static int PAGE_SIZE = 10;
private PageWraper pw = new PageWraper();
private PageResult rs = new PageResult();
/**
* 优惠券manager
*/
private TCouponManager tcouponmanager;
/**
* 订单manager
*/
private TOrderManager tordermanager;
/**
* 用户收货地址manager
*/
private TMemberReceiverLatLonManager tmemberreceiverlatlonmanager;
/**
* 支付方式
*/
private CPaymentWayManager cpaymentwaymanager;
/**
* opensql
*/
private OpenSqlManage opensqlmanage;
/**
* 商品manager
*/
private TGoodsManager tgoodsmanager;
/**
* 用户资金manager
*/
private TMemberAccountManager tmemberaccountmanager;
/**
* 地区城市码表
*/
private CLocationCityManager clocationcitymanager;
/**
* 订单支付流水表
*/
private TOrderFlowManager torderflowmanager;
/**
* 支付插件
*/
private PaymentPluginMaager paymentpluginmaager;
/**
* 订单商品表
*/
private TOrderItemManager torderitemmanager;
private TOrder order;
/**
* 优惠券
*/
private TCouponCardManager tcouponcardmanager;
private TSysParameterManager tsysparametermanager;
private MessageSender topicMessageSender;
private TLeaderStayMoneyManager tleaderstaymoneymanager;
/*****OrderServiceDubboApi*******/
private OrderServiceDubboApi orderservicedubboapi;
/**
* 配送方式manager
*/
private CDeliveryWayManager cdeliverywaymanager;
/**
* 收货地址
*/
private TMemberReceiverLatLon tmemberreceiver;
/**
* 用户基本信息扩展表
*/
private TMemberBaseMessageExtManager tmemberbasemessageextmanager;
/**
* 订单中心
* @return
* @throws SQLException
*/
public String toAddress() throws SQLException{
return "address";
}
/**
* 订单中心
* @return
* @throws SQLException
*/
public String index() throws SQLException{
TMember member = (TMember)this.getSession().getAttribute("member");
TMemberAccount account = tmemberaccountmanager.selectByPrimaryKey(member.getId());
this.getRequest().setAttribute("account", account);
Object currentGrade = this.opensqlmanage.selectObjectByObject(member.getMemberGradeId().toString(), "t_member_grade.selectCurrentGrade");
this.getRequest().setAttribute("currentGrade", currentGrade);
Object nextGrade = this.opensqlmanage.selectObjectByObject(member.getMemberGradeId().toString(), "t_member_grade.selectNextGrade");
if(nextGrade==null){
this.getRequest().setAttribute("nextGrade", currentGrade);
}else{
this.getRequest().setAttribute("nextGrade", nextGrade);
}
Map<String,Object> param = new HashMap<String,Object>();
param.put("memberId", member.getId());
//待确认订单
Object unconfirmCount = this.opensqlmanage.selectObjectByObject(param, "t_order.select_unconfirm_count");
this.getRequest().setAttribute("unconfirmCount", unconfirmCount);
//待支付订单
Object unpaidCount = this.opensqlmanage.selectObjectByObject(param, "t_order.select_unpaid_count");
this.getRequest().setAttribute("unpaidCount", unpaidCount);
//待评价优惠券
Object toEvaluateCount = this.opensqlmanage.selectObjectByObject(param, "t_order.select_to_evaluate_count");
this.getRequest().setAttribute("toEvaluateCount", toEvaluateCount);
//可使用优惠券
Object couponCardUseCount = this.opensqlmanage.selectObjectByObject(param, "t_coupon_card.selectCountUse");
this.getRequest().setAttribute("couponCardUseCount", couponCardUseCount);
//会员收藏
Object memberCollectCount = this.opensqlmanage.selectObjectByObject(param, "t_member_collect.selectCountToMember");
this.getRequest().setAttribute("memberCollectCount", memberCollectCount);
//会员商品咨询
Object memberConsultCount = this.opensqlmanage.selectObjectByObject(param, "t_goods_consult.selectMemberConsultCount");
this.getRequest().setAttribute("memberConsultCount", memberConsultCount);
return "index";
}
/**
* 订单列表
*/
public String list(){
String type = this.getRequest().getParameter("type");
String time = this.getRequest().getParameter("time");
if(!org.apache.commons.lang.StringUtils.isNumeric(type) || Integer.parseInt(type) > 4 || Integer.parseInt(type) < 1){
type = "1";
}
if(!org.apache.commons.lang.StringUtils.isNumeric(time) || Integer.parseInt(time) > 4 || Integer.parseInt(time) < 1){
time = "1";
}
TMember member = (TMember)this.getSession().getAttribute("member");
Map<String,Object> param = new HashMap<String,Object>();
param.put("memberId", member.getId());
if(org.apache.commons.lang.StringUtils.isNotEmpty(this.getRequest().getParameter("sn"))){
param.put("sn", this.getRequest().getParameter("sn"));
}
if(time.equals("2")){
//一个月之内
Date oneMonth = new Date();
oneMonth.setMonth(oneMonth.getMonth() -1);
param.put("oneMonth", oneMonth);
}else if(time.equals("3")){
//三个月之内
Date threeMonth = new Date();
threeMonth.setMonth(threeMonth.getMonth() -3);
param.put("threeMonth", threeMonth);
}else if(time.equals("4")){
//历史订单
Date history = new Date();
history.setMonth(history.getMonth() -3);
param.put("history", history);
}
if(type.equals("2")){
//未支付订单
pw = this.opensqlmanage.selectForPageByMap(param, "t_order.select_unpaid_count", "t_order.select_unpaid_list", rs.getP_curPage(), PAGE_SIZE);
}else if (type.equals("3")){
//待收货订单
pw = this.opensqlmanage.selectForPageByMap(param, "t_order.select_unconfirm_count", "t_order.select_unconfirm_list", rs.getP_curPage(), PAGE_SIZE);
}else if(type.equals("4")){
//待评价订单
pw = this.opensqlmanage.selectForPageByMap(param, "t_order.select_to_evaluate_count", "t_order.select_to_evaluate_list", rs.getP_curPage(), PAGE_SIZE);
}else{
//全部订单
pw = this.opensqlmanage.selectForPageByMap(param, "t_order.select_count", "t_order.select_list", rs.getP_curPage(), PAGE_SIZE);
}
this.getRequest().setAttribute("type", type);
this.getRequest().setAttribute("time", time);
return "list";
}
/**
* 获取订单商品明细
* @return
*/
public String getOrderItem(){
String id = this.getRequest().getParameter("id");
if(org.apache.commons.lang.StringUtils.isNumeric(id)){
Object orderItems = this.opensqlmanage.selectListByObject(id, "t_order_item.selectOrderItemByOrderId");
this.getRequest().setAttribute("orderItems", orderItems);
}
return "order_item";
}
/**
* 订单详情
* 方法名:detail<BR>
* 创建人:Marlon <BR>
* @return String <BR>
* @throws Exception
*/
public String detail() throws Exception{
String orderId = this.getRequest().getParameter("id");
int logisticFlag = 0;//物流信息列表标识 1显示 0不显示
int flowFlag = 0;//物流进度标识 1显示 0不显示
if (StringUtils.hasText(orderId)) {
com.rc.openapi.dubbo.vo.TOrder tOrder = orderservicedubboapi.getOrderById(Long.parseLong(orderId.trim()));
if (tOrder!=null) {
this.getRequest().setAttribute("order", tOrder);
/**
* 0待支付 1待发货 2待收货 3已完成 4已取消 5已过期 6已关闭
* 4已取消 5已过期 表示不显示物流进度标识
* 0待支付 1待发货 4已取消 表示不显示物流信息标识
*/
int status = tOrder.getOrderStatus();
//支付信息(pay_date付款时间)
com.rc.openapi.dubbo.vo.TOrderFlow orderFlow = orderservicedubboapi.getOrderFlowOrderId(Long.parseLong(orderId.trim()));
this.getRequest().setAttribute("orderFlow", orderFlow);
if (status!=4&&status!=5) {//flowFlag代表0 1 2 3 6
flowFlag = 1;
}
if((status==2||status==3||status==6)){//如果显示物流信息 【去查询】logisticFlag代表 2 3 6
logisticFlag = 1;
//物流信息
com.rc.openapi.dubbo.vo.TOrderShipment orderShipment = orderservicedubboapi.getOrderShipByOrderId(Long.parseLong(orderId.trim()));
this.getRequest().setAttribute("shipment", orderShipment);
}
//该订单下商品项信息的查询
List<TOrderGoodModel> goodList= orderservicedubboapi.getTOrderGoodListByOrderId(Long.parseLong(orderId.trim()), null);
if (goodList!=null && goodList.size()>0) {
List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();//用于存放商品项
Map<String, Object> map = null;//存放商品项单条商品信息
for (TOrderGoodModel good : goodList) {
map = new HashMap<String, Object>();
map.put("goodsNo", good.getGoodsNo());
map.put("goodsId", good.getGoodsid());
map.put("img", good.getAbbreviationPicture());
map.put("goodsName", good.getGoodsName());
map.put("price", good.getPrice());
map.put("num", good.getQuantity());
System.out.println(good.getGoodsNo());
items.add(map);
}
this.getRequest().setAttribute("goods", items);
}
}
this.getRequest().setAttribute("logisticFlag", logisticFlag);
this.getRequest().setAttribute("flowFlag", flowFlag);
}
return "detail";
}
/**
* 根据收货地址,支付方式 查询配送方式
* @param receiverLatLon
* @param paymentWayId
* @return
* @throws NumberFormatException
* @throws SQLException
*/
public List<Map<String,Object>> getDeliveryWayList(TMemberReceiverLatLon receiverLatLon,String paymentWayId) throws NumberFormatException, SQLException{
if(!StringUtils.hasText(paymentWayId)){
paymentWayId="1";
}
CPaymentWay paymentWay= this.cpaymentwaymanager.selectByPrimaryKey(Long.valueOf(paymentWayId.trim()));
Map<String,Object> resultsmap = new HashMap<String,Object>();
List<Map<String,Object>> deliveryWayList = new ArrayList<Map<String,Object>>();
CDeliveryWayExample deliveryWayexample = new CDeliveryWayExample();
deliveryWayexample.createCriteria().andDeliveryCodeNotEqualTo("hdfk");
List<CDeliveryWay> deliveryList = cdeliverywaymanager.selectByExample(deliveryWayexample);
Map<String,Object> resultMap = null;
String receiverFlag ="0";// 0 表示外地
String hdfk_area =tsysparametermanager.getKeys("paymethod_hdfk_area");//支付方式支持货到付款地区
if(receiverLatLon!=null){
boolean ysd_ysdj_areaid_flag = false;
if(StringUtils.hasText(receiverLatLon.getStoreId())){
ysd_ysdj_areaid_flag= true;
}
if(ysd_ysdj_areaid_flag){//判断望京 是望京
receiverFlag="1";//表示 望京
}else if(receiverLatLon.getArea().indexOf(hdfk_area)!=-1){//判断是否是北京
receiverFlag="2";//表示北京
}
}else{
receiverFlag="-1";//表示 没有收获地址
}
if(deliveryList!=null&&deliveryList.size()>0){
for(CDeliveryWay delivery:deliveryList){
resultMap = new HashMap<String,Object>();
resultMap.put("id", delivery.getId());
resultMap.put("name", delivery.getName());
resultMap.put("instro", delivery.getInstro());
resultMap.put("deliveryCode", delivery.getDeliveryCode());
resultMap.put("isflag", "0");//表示否
if(!paymentWay.getPaymentCode().equals("hdfk")){
if(delivery.getDeliveryCode().equals("ptkd")){//普通快递
if(receiverFlag.equals("0")||receiverFlag.equals("2")){//外地 或是北京
resultMap.put("isflag", "1");//表示是
}
}else if(delivery.getDeliveryCode().equals("ysd")){//药士达
if(receiverFlag.equals("1")){//表示 望京
resultMap.put("isflag", "1");//表示是
}
}else if(delivery.getDeliveryCode().equals("ysdj")){//药师到家
if(receiverFlag.equals("1")){//表示 望京
resultMap.put("isflag", "1");//表示是
}
}
}else{
if(receiverFlag.equals("1")){//表示 望京
if(delivery.getDeliveryCode().equals("ysd")|| delivery.getDeliveryCode().equals("ysdj")){//药士达 药师到家
resultMap.put("isflag", "1");//表示是
}
}
}
if("1".equals(resultMap.get("isflag"))){
deliveryWayList.add(resultMap);
}
}
}
return deliveryWayList;
}
/**
* 从购物车跳转到结算页面
* @return
* @throws Exception
*/
public String toOrderAdd() throws Exception{
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
Long memberId =member.getId();
String shortOrderId="";//暂时不用
// 查询收获地址
TMemberReceiverLatLonExample example = new TMemberReceiverLatLonExample();
example.createCriteria().andMemberIdEqualTo(memberId);
example.setOrderByClause(" is_default desc ,id desc");
List<TMemberReceiverLatLon> receiverLatLonList = tmemberreceiverlatlonmanager.selectByExample(example);
String receiverId = null;
TMemberReceiverLatLon receiverLatLon = null;
String receiverSizeFlag ="0"; //0 表示不够10个 1 表示超过10个
if(receiverLatLonList!=null&&receiverLatLonList.size()>0){
receiverLatLon=receiverLatLonList.get(0);
receiverId = String.valueOf(receiverLatLonList.get(0).getId());
this.getRequest().setAttribute("receiverId", Long.valueOf(receiverId));
for(TMemberReceiverLatLon receiverlat:receiverLatLonList){
// if(!StringUtils.hasText(receiverlat.getLatitude())){
// receiverlat.setLocationAddress("");
// }
if(StringUtils.hasText(receiverlat.getLocationAddress())){
String location_address =receiverlat.getLocationAddress();
String address =receiverlat.getAddress();
String area = receiverlat.getArea();
if(StringUtils.hasText(location_address)){
if(!(!address.startsWith(location_address)&&area.indexOf(location_address)==-1)){
receiverlat.setLocationAddress("");
}
}
}
}
if(receiverLatLonList.size()>9){
receiverSizeFlag="1";
}
}
this.getRequest().setAttribute("receiverSizeFlag", receiverSizeFlag);
// 支付方式
CPaymentWayExample paymentWayExample = new CPaymentWayExample();
paymentWayExample.setOrderByClause("sort asc");
List<CPaymentWay> paymentWayList = cpaymentwaymanager.selectByExampleAndReceiverId(paymentWayExample,receiverLatLon);
Long paymentWayId =null;//支付方式id
if(paymentWayList!=null&&paymentWayList.size()>0){
paymentWayId = paymentWayList.get(0).getId();
}
this.getRequest().setAttribute("paymentWayId", paymentWayId);
//获取配送方式
List<Map<String,Object>> deliveryWayList = this.getDeliveryWayList(receiverLatLon, paymentWayId==null?"":String.valueOf(paymentWayId));
Long deliveryId =null;
if(deliveryWayList!=null&&deliveryWayList.size()>0){
deliveryId= (Long) deliveryWayList.get(0).get("id");
}
this.getRequest().setAttribute("deliveryId", deliveryId);
String cartType = this.getRequest().getParameter("cartType"); // 购物车结算商品类型 0 全部 1 非医卡通商品 2 医卡通商品
if(!StringUtils.hasText(cartType)){
cartType="0";
}
//正常购买
// if(!StringUtils.hasText(shortOrderId)){
// 查询可以用的优惠券
List<Map<String, Object>> couponList = this.tordermanager.getCouponByGoods(cartType,null,String.valueOf(memberId));
this.getRequest().setAttribute("couponList", couponList);//优惠券
this.getRequest().setAttribute("couponListSize", couponList.size());//优惠券个数
this.getRequest().setAttribute("receiverList", receiverLatLonList);//收货地址
this.getRequest().setAttribute("paymentWayList", paymentWayList);//支付方式
//计算订单相关金额
Map<String, Object> resultMap =tordermanager.getOrderPrice(cartType,null,receiverId,String.valueOf(memberId),paymentWayId==null?"":String.valueOf(paymentWayId),shortOrderId,deliveryId==null?"":String.valueOf(deliveryId));
if(resultMap!=null){
this.getRequest().setAttribute("goodsList", resultMap.get("goodsList"));//商品
this.getRequest().setAttribute("orderPrice", resultMap.get("orderPrice"));
this.getRequest().setAttribute("shippingFee", resultMap.get("shippingFee"));
this.getRequest().setAttribute("couponDiscount", resultMap.get("couponDiscount"));
this.getRequest().setAttribute("promotionalDiscount",resultMap.get("promotionalDiscount"));
this.getRequest().setAttribute("payableAmount", resultMap.get("orderPrice"));
this.getRequest().setAttribute("goodsPrice", resultMap.get("goodsPrice"));
}
shortOrderId="";
// }else{//秒杀购买
// // 查询购物车商品
// Map<String, Object> paramMap = new HashMap<String, Object>();
// paramMap.put("shortOrderId", Long.parseLong(shortOrderId));
// paramMap.put("memberId", memberId);
// List<OrderGoodCart> goodsList = this.opensqlmanage.selectForListByMap(paramMap,"t_goods.selectGoodsByShortOrderId");
// this.getRequest().setAttribute("receiverList", receiverLatLonList);//收货地址
// this.getRequest().setAttribute("paymentWayList", paymentWayList);//支付方式
// this.getRequest().setAttribute("goodsList", goodsList);//商品
// BigDecimal goodsPrice =new BigDecimal("0");
// if(goodsList!=null&&goodsList.size()>0){
// goodsPrice=goodsList.get(0).getPcPrice().multiply(new BigDecimal(goodsList.get(0).getQuantity()));
// }
// this.getRequest().setAttribute("orderPrice", goodsPrice);
// this.getRequest().setAttribute("shippingFee", new BigDecimal("0"));
// this.getRequest().setAttribute("couponDiscount", new BigDecimal("0"));
// this.getRequest().setAttribute("promotionalDiscount",new BigDecimal("0"));
// this.getRequest().setAttribute("payableAmount", goodsPrice);
// this.getRequest().setAttribute("goodsPrice", goodsPrice);
// }
this.getRequest().setAttribute("shortOrderId", shortOrderId);
this.getRequest().setAttribute("deliveryWayList", deliveryWayList);
// CLocationCityExample cityexample = new CLocationCityExample();
// cityexample.createCriteria().andGradeEqualTo(2);
// cityexample.setOrderByClause(" pinyin asc,name asc ");
// List<CLocationCity> cityList =this.clocationcitymanager.selectByExample(cityexample);
// List<CLocationCity> cityzimuList = null;
// TreeMap<String,List<CLocationCity>> zimuMap = new TreeMap<String,List<CLocationCity>>();
// for(CLocationCity city:cityList){
// if(zimuMap.get(city.getPinyin())!=null){
// cityzimuList = zimuMap.get(city.getPinyin());
// cityzimuList.add(city);
// zimuMap.put(city.getPinyin(), cityzimuList);
// }else{
// cityzimuList = new ArrayList<CLocationCity>();
// cityzimuList.add(city);
// zimuMap.put(city.getPinyin(), cityzimuList);
// }
// }
// this.getRequest().setAttribute("zimuMap", zimuMap);
this.getRequest().setAttribute("cartType", cartType);
return "order_add";
}
/**
* 根据收货地址 查询支付方式
* @throws Exception
*/
public void paymentWayByReceiverId() throws Exception{
String receiverId = this.getRequest().getParameter("receiverId");//收货地址id
TMemberReceiverLatLon receiverLatLon = null;
if(StringUtils.hasText(receiverId)){
receiverLatLon = this.tmemberreceiverlatlonmanager.selectByPrimaryKey(Long.valueOf(receiverId));
}
// 支付方式
CPaymentWayExample paymentWayExample = new CPaymentWayExample();
paymentWayExample.setOrderByClause("sort asc");
List<CPaymentWay> paymentWayList = cpaymentwaymanager.selectByExampleAndReceiverId(paymentWayExample,receiverLatLon);
writeObjectToResponse(paymentWayList, ContentType.application_json);
}
/**
* 动态获取配送方式集合
* @throws Exception
*/
public void deliveryWayList() throws Exception{
String receiverId = this.getRequest().getParameter("receiverId");//收货地址id
String paymentWayId = this.getRequest().getParameter("paymentWayId");//支付方式
TMemberReceiverLatLon receiverLatLon = null;
if(StringUtils.hasText(receiverId)){
receiverLatLon = this.tmemberreceiverlatlonmanager.selectByPrimaryKey(Long.valueOf(receiverId));
}
//获取配送方式
List<Map<String,Object>> deliveryWayList = this.getDeliveryWayList(receiverLatLon, paymentWayId);
writeObjectToResponse(deliveryWayList, ContentType.application_json);
}
/**
* 提交订单
* @throws Exception
*/
public void saveOrder() throws Exception{
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
Long memberId =member.getId();
//错误消息提示
ErrorMessage errorMessage = null;
String receiverId = this.getRequest().getParameter("receiverId");//收货地址id
String paymentWayId = this.getRequest().getParameter("paymentWayId");//支付方式
String couponCardId = this.getRequest().getParameter("couponCardId");//优惠券id
String deliveryId = this.getRequest().getParameter("deliveryId");//配送方式
//秒杀id
String shortOrderId = this.getRequest().getParameter("shortOrderId");
String cartType = this.getRequest().getParameter("cartType"); // 购物车结算商品类型 0 全部 1 非医卡通商品 2 医卡通商品
if(!StringUtils.hasText(cartType)){
cartType="0";
}
boolean flag =true;
TMemberReceiverLatLon tmemberReceiverLatLon=null;
String wjarea ="0";//判断是否属于门店配送范围 0 不属于 1 属于
if(flag&&!StringUtils.hasText(receiverId)){//收货地址
errorMessage= new ErrorMessage(false,"1","");//收货地址错误
flag = false;
}else{
tmemberReceiverLatLon =tmemberreceiverlatlonmanager.selectByPrimaryKey(Long.valueOf(receiverId.trim()));
boolean ysd_ysdj_areaid_flag = false;
if(StringUtils.hasText(tmemberReceiverLatLon.getStoreId())){
ysd_ysdj_areaid_flag= true;
}
if(tmemberReceiverLatLon!=null&&tmemberReceiverLatLon.getAreaId()!=null&&ysd_ysdj_areaid_flag){//判断是否属于门店配送范围
wjarea="1";
}
}
//验证余额支付
CPaymentWay paymentWay= null;
if(flag&&!StringUtils.hasText(paymentWayId)){//支付方式
errorMessage= new ErrorMessage(false,"2","");//支付方式
flag = false;
}else{
paymentWay= cpaymentwaymanager.selectByPrimaryKey(Long.valueOf(paymentWayId.trim()));
}
if(flag&&!StringUtils.hasText(deliveryId)){//配送方式
if(!("0".equals(wjarea)&&paymentWay.getPaymentCode().equals(InfoUtil.getInstance().getInfo("config", "payment.hdfk")))){//不是望京 并且是货到付款
errorMessage= new ErrorMessage(false,"11","");//配送方式
flag = false;
}
}
// 查询购物车商品
Map<String, Object> paramMap = new HashMap<String, Object>();
List<OrderGoodCart> goodsList = null;
if(!StringUtils.hasText(shortOrderId)){
paramMap.put("memberId", memberId);
goodsList = this.opensqlmanage.selectForListByMap(paramMap,"t_goods.selectGoodsByCartMemberid");
if(flag){
if(goodsList!=null&&goodsList.size()>0){
for(OrderGoodCart orderGoodCart:goodsList){
if(orderGoodCart.getIfPremiums()!=null&&orderGoodCart.getIfPremiums().intValue()==0){//不是赠品
if(orderGoodCart.getStquan().intValue()<0){
errorMessage= new ErrorMessage(false,"4","");//购物车部分商品库存不足
flag=false;
break;
}
if(orderGoodCart.getPcStatus().intValue()!=1){
errorMessage= new ErrorMessage(false,"5","");//购物车部分商品已经下架
flag=false;
break;
}
}
}
}else{
errorMessage= new ErrorMessage(false,"3","");//购物车商品为空
flag=false;
}
}
//判断 处方药
if(flag){
String messageContent="";
for(OrderGoodCart orderGoodCart:goodsList){
if(orderGoodCart.getType().intValue()==3){//非购买处方药
messageContent=messageContent+orderGoodCart.getGoodsName()+";";
log.info("======>手机端提交订单"+orderGoodCart.getGoodsName()+"为不可加入购物车的处方药!");
flag=false;
}
}
if(flag){//查询收获地址
for(OrderGoodCart orderGoodCart:goodsList){
if(orderGoodCart.getType().intValue()==2&&("0".equals(wjarea)||!paymentWay.getPaymentCode().equals(InfoUtil.getInstance().getInfo("config", "payment.hdfk")))){//非购买处方药
messageContent=messageContent+orderGoodCart.getGoodsName()+";";
flag=false;
}
}
if(!flag){
errorMessage= new ErrorMessage(false,"10",messageContent);//购物车商品为空
}
}else{
errorMessage= new ErrorMessage(false,"9",messageContent);//购物车商品为空
}
}
}else{
paramMap.put("shortOrderId", Long.parseLong(shortOrderId));
paramMap.put("memberId", memberId);
goodsList = this.opensqlmanage.selectForListByMap(paramMap,"t_goods.selectGoodsByShortOrderId");
if(goodsList!=null&&goodsList.size()>0){
}else{
errorMessage= new ErrorMessage(false,"3","");//购物车商品为空
flag=false;
}
}
if(flag){
if(paymentWay!=null){
if(paymentWay.getPaymentCode().equals(InfoUtil.getInstance().getInfo("config", "payment.yezf"))){//余额支付
//计算订单相关金额
Map<String, Object> resultMap =tordermanager.getOrderPrice(cartType,couponCardId, receiverId,String.valueOf(memberId),paymentWayId,shortOrderId,deliveryId);
//待支付金额
BigDecimal payableAmount = (BigDecimal) resultMap.get("payableAmount");
TMemberAccount memberAccount =tmemberaccountmanager.selectByPrimaryKey(memberId);
if(memberAccount!=null){
if(memberAccount.getRemainingAmount()==null||(memberAccount.getRemainingAmount()!=null&&memberAccount.getRemainingAmount().compareTo(payableAmount)<0)){
errorMessage= new ErrorMessage(false,"8","");//余额支付金额不足
flag=false;
}
}else{
errorMessage= new ErrorMessage(false,"8","");//余额支付金额不足
flag=false;
}
}
}else{
errorMessage= new ErrorMessage(false,"7","");//该支付方式不存在
flag=false;
}
}
//所有校验已经通过
if(flag){
order.setMemberId(memberId);
long orderId =this.tordermanager.saveOrder(cartType,order, receiverId, paymentWayId, couponCardId, shortOrderId,deliveryId);
if(orderId!=0){
errorMessage= new ErrorMessage(true,String.valueOf(orderId),"");//提交成功
}else{
errorMessage= new ErrorMessage(false,"6","");//提交失败
}
}
writeObjectToResponse(errorMessage, ContentType.application_json);
}
/**
* 订单提交成功 跳转支付页面
* @return
* @throws Exception
*/
public String orderSumbitSuccess() throws Exception{
String orderId = this.getRequest().getParameter("orderId");
if(StringUtils.hasText(orderId)){
order = this.tordermanager.selectByPrimaryKey(Long.valueOf(orderId.trim()));
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
if(order!=null&&member.getId().longValue()==order.getMemberId().longValue()){
CPaymentWay paymentWay=this.cpaymentwaymanager.selectByPrimaryKey(order.getPaymentId());
this.getRequest().setAttribute("paymentWay",paymentWay);
if(order.getOrderStatus()==OrderEnum.UNDELIVERY.getIndex()){
return "order_success";
}else if(order.getOrderStatus()==OrderEnum.UNPAY.getIndex()){
String hdfk_area =tsysparametermanager.getKeys("paymethod_hdfk_area");//支付方式支持货到付款地区
String hdfkFlag="0";//是否支持货到付款 0 否 1 是
if(order.getAreaName().indexOf(hdfk_area)!=-1){
hdfkFlag="1";
}
this.getRequest().setAttribute("hdfkFlag", hdfkFlag);
TMemberBaseMessageExt memberBaseMessageExt=this.tmemberbasemessageextmanager.selectByPrimaryKey(order.getMemberId());
String billEmail ="";//账单邮箱
if(memberBaseMessageExt!=null&&memberBaseMessageExt.getBillEmail()!=null){
billEmail= memberBaseMessageExt.getBillEmail();
}
this.getRequest().setAttribute("billEmail", billEmail);
return "order_payment";
}
}else{
return null;
}
}
return null;
}
/**
* 订单支付
* @return
* @throws Exception
*/
public String orderPay() throws Exception{
String orderId = this.getRequest().getParameter("orderId");
String paymentPluginId = this.getRequest().getParameter("paymentPluginId");
Map<String, Object> parameterMap = new HashMap<String, Object>();
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
if(StringUtils.hasText(orderId)){
order = this.tordermanager.selectByPrimaryKey(Long.valueOf(orderId.trim()));
if(member.getId().longValue() == order.getMemberId().longValue()){//判断订单是否该用户的订单
CPaymentWay paymentWay= cpaymentwaymanager.selectByPrimaryKey(order.getPaymentId());
String errorMessage = null;
if(order!=null){
if(order.getOrderStatus()!=OrderEnum.UNPAY.getIndex()){//未支付
errorMessage= "该订单已经支付";//该订单已经支付
}else if(!paymentWay.getPaymentCode().equals(InfoUtil.getInstance().getInfo("config", "payment.xszf"))){//线上支付
errorMessage= "该订单不支持在线支付";//该订单不支持在线支付
}else{
TOrderFlowExample flowExample = new TOrderFlowExample();
flowExample.createCriteria().andMemberIdEqualTo(order.getMemberId()).andOrderIdEqualTo(order.getId());
List<TOrderFlow> orderFlowList = this.torderflowmanager.selectByExample(flowExample);
//订单支付流水表
TOrderFlow orderFlow = null;
PaymentPlugin paymentPlugin =paymentpluginmaager.getPaymentPluginById(paymentPluginId);
if(orderFlowList!=null&&orderFlowList.size()>0){
orderFlow = orderFlowList.get(0);
orderFlow.setPaymentPlugin(paymentPluginId);
orderFlow.setPayMethod(paymentPlugin.getName());
orderFlow.setHavePay(order.getPayableAmount());
orderFlow.setOrderId(order.getId());
this.torderflowmanager.updateByPrimaryKeySelective(orderFlow);
}else{
orderFlow =new TOrderFlow();
orderFlow.setMemberId(order.getMemberId());
orderFlow.setPaymentStatus(0);//支付状态 0 未支付 1已支付
orderFlow.setPaymentPlugin(paymentPluginId);
orderFlow.setPayMethod(paymentPlugin.getName());
orderFlow.setHavePay(order.getPayableAmount());
orderFlow.setCreateTime(new Date());
orderFlow.setOrderId(order.getId());
this.torderflowmanager.insertSelective(orderFlow);
}
// 如果使用医卡通,添加商品清单
if (paymentPluginId.equals("payYktPlugin")) {
Map<String, Object> parMap = new HashMap<String, Object>();
parMap.put("orderId", order.getId());
List<Map<String,Object>> orderItemList =this.opensqlmanage.selectForListByMap(parMap, "t_order_item.selectOrderItemGoodsByOrderid");
this.getRequest().setAttribute("items", orderItemList);
BigDecimal shouldAmount = new BigDecimal(0);
for (Map<String,Object> oi : orderItemList) {
shouldAmount = shouldAmount.add(((BigDecimal)oi.get("price")).multiply(new BigDecimal((Integer)oi.get("quantity"))));
}
// 减免金额
parameterMap.put("costAdjust",order.getPayableAmount().subtract(shouldAmount));
}
if (paymentPluginId.equals("payWzfPlugin")) {
String erWeiMaUrl = getErweiMaUrl( order, orderFlow, this.getRequest(), this.getResponse());
this.getRequest().setAttribute("erWeiMaUrl", erWeiMaUrl);
return "wzf";
}
this.getRequest().setAttribute("requestUrl", paymentPlugin.getRequestUrl());
this.getRequest().setAttribute("requestMethod", paymentPlugin.getRequestMethod());
this.getRequest().setAttribute("requestCharset", paymentPlugin.getRequestCharset());
parameterMap.putAll(paymentPlugin.getParameterMap(opensqlmanage,order,"订单支付", this.getRequest()));
this.getRequest().setAttribute("parameterMap", parameterMap);
if (StringUtils.hasText(paymentPlugin.getRequestCharset())) {
this.getResponse().setContentType("text/html; charset="+ paymentPlugin.getRequestCharset());
}
return "order_payment_submit";
}
}else{
errorMessage= "订单不存在";//订单不存在
}
}
}
return null;
}
/**
* 检测订单是否已经支付
* @return
* @throws Exception
*/
public void checkOrderPay() throws Exception{
String resultFlag ="0";
String ordersn ="";
if(StringUtils.hasText(this.getRequest().getParameter("ordersn"))){//订单编号
ordersn = this.getRequest().getParameter("ordersn");
}
if(StringUtils.hasText(ordersn)){
TOrderExample orderExample = new TOrderExample();
orderExample.createCriteria().andOrderSnEqualTo(ordersn.trim());
List<TOrder> orderList =this.tordermanager.selectByExample(orderExample);
if(orderList!=null&&orderList.size()>0){
this.order = orderList.get(0);
if(order.getOrderStatus().intValue()==OrderEnum.UNDELIVERY.getIndex()){
resultFlag="1";
}
}
}
writeObjectToResponse(resultFlag, ContentType.text_html);
}
/**
* 设为默认收货地址
*/
public void ajaxReceiverSetDefault() throws Exception {
TMember sessionMember = (TMember)this.getSession().getAttribute("member");
String receiverId = this.getRequest().getParameter("receiverId");
if (StringUtils.hasText(receiverId)) {
this.tmemberreceiverlatlonmanager.updateReceiverDefault(Long.valueOf(receiverId),sessionMember.getId());
writeObjectToResponse("1", ContentType.text_html);
} else {
writeObjectToResponse("0", ContentType.text_html);
}
}
/**
* 删除收货地址
*/
public void ajaxDeleteReceiver() throws Exception {
if (StringUtils.hasText(this.getRequest().getParameter("id"))) {
this.tmemberreceiverlatlonmanager.deleteByPrimaryKey(Long.valueOf(this.getRequest().getParameter("id")));
writeObjectToResponse("1", ContentType.text_html);
} else {
writeObjectToResponse("0", ContentType.text_html);
}
}
/**
* 支付回调方法 跳转支付页面
* @return
* @throws Exception
*/
public String pageReturnUrl() throws Exception{
String ordersn ="";
if(StringUtils.hasText(this.getRequest().getParameter("serialNo"))){//医卡通
ordersn =this.getRequest().getParameter("serialNo");
}else if(StringUtils.hasText(this.getRequest().getParameter("out_trade_no"))){//支付宝
ordersn =this.getRequest().getParameter("out_trade_no");
}else if(StringUtils.hasText(this.getRequest().getParameter("orderId"))){//快钱
ordersn =this.getRequest().getParameter("orderId");
}else if(StringUtils.hasText(this.getRequest().getParameter("order_no"))){//微信支付
ordersn =this.getRequest().getParameter("order_no");
}else if(StringUtils.hasText(this.getRequest().getParameter("ordersn"))){//订单编号
ordersn = this.getRequest().getParameter("ordersn");
}
if(StringUtils.hasText(ordersn)){
TOrderExample orderExample = new TOrderExample();
orderExample.createCriteria().andOrderSnEqualTo(ordersn.trim());
List<TOrder> orderList =this.tordermanager.selectByExample(orderExample);
if(orderList!=null&&orderList.size()>0){
this.order = orderList.get(0);
CPaymentWay paymentWay=this.cpaymentwaymanager.selectByPrimaryKey(order.getPaymentId());
this.getRequest().setAttribute("paymentWay",paymentWay);
this.getRequest().setAttribute("payDate", new Date());
return "order_success";
}
}
return null;
}
/**
* 计算订单相关金额
* @throws Exception
*/
public void computeOrderPrice() throws Exception{
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
getResponse().setContentType("text/html;charset=utf-8");
PrintWriter write = getResponse().getWriter();
String couponCardId = this.getRequest().getParameter("couponCardId");//优惠券id
String receiverId = this.getRequest().getParameter("receiverId");//收货地址id
String paymentWayId = this.getRequest().getParameter("paymentWayId");//支付方式
String shortOrderId = this.getRequest().getParameter("shortOrderId");//秒杀id
String deliveryId = this.getRequest().getParameter("deliveryId");//配送方式
String cartType = this.getRequest().getParameter("cartType"); // 购物车结算商品类型 0 全部 1 非医卡通商品 2 医卡通商品
if(!StringUtils.hasText(cartType)){
cartType="0";
}
Map<String, Object> resultMap =tordermanager.getOrderPrice(cartType,couponCardId, receiverId,String.valueOf(member.getId()),paymentWayId,shortOrderId,deliveryId);
resultMap.remove("goodsList");
JSONObject json = JSONObject.fromObject(resultMap);
write.write(json.toString());
write.close();
}
/**
* 检验优惠券是否可以使用
* @throws Exception
*/
public void checkCouponCard() throws Exception{
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
String couponCardNo = this.getRequest().getParameter("couponCardNo");//优惠券卡号
Map<String,String> resultMap = new HashMap<String,String>();
String resultFlag="0";
String name="";
String couponCardId="";
String cartType = this.getRequest().getParameter("cartType"); // 购物车结算商品类型 0 全部 1 非医卡通商品 2 医卡通商品
if(!StringUtils.hasText(cartType)){
cartType="0";
}
try{
if(StringUtils.hasText(couponCardNo)){
TCouponCardExample cardExample = new TCouponCardExample();
cardExample.createCriteria().andCardNoEqualTo(couponCardNo.trim());
List cardList =tcouponcardmanager.selectByExample(cardExample);
if(cardList!=null&&cardList.size()>0){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("couponCardNo", couponCardNo.trim());
paramMap.put("memberId", member.getId());
List<Map<String, Object>> memberCouponList= this.opensqlmanage.selectForListByMap(paramMap, "t_coupon_card.selectCouponCardByCardNo");
if(memberCouponList!=null&&memberCouponList.size()>0){
couponCardId = String.valueOf((Long) memberCouponList.get(0).get("id"));
boolean flag =tordermanager.checkCouponCard(cartType,couponCardId, String.valueOf(member.getId()),memberCouponList);
if(flag){
name =(String) memberCouponList.get(0).get("name");
resultFlag="1";
}
}
}else{
resultFlag="3";
}
}else{
resultFlag="2";
}
}catch(Exception e){
e.printStackTrace();
resultFlag="-1";
}
resultMap.put("resultFlag", resultFlag);
resultMap.put("name", name);
resultMap.put("couponCardId", couponCardId);
writeObjectToResponse(resultMap, ContentType.application_json);
}
/**
* 取消订单
* @throws Exception
*/
public void cancelOrder() throws Exception{
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
String orderId = this.getRequest().getParameter("orderId");
ErrorMessage errorMessage = null;
try{
if(StringUtils.hasText(orderId)){
order = this.tordermanager.selectByPrimaryKey(Long.valueOf(orderId));
if(order!=null){
if(order.getMemberId().longValue()==member.getId().longValue()){
if(order.getOrderStatus().intValue()==OrderEnum.UNPAY.getIndex()||order.getOrderStatus().intValue()==OrderEnum.UNDELIVERY.getIndex()){
tordermanager.cancelOrder(order.getId(), order.getOrderType(), order.getMemberId());
errorMessage = new ErrorMessage(true,"取消成功!","");
}else{
errorMessage = new ErrorMessage(false,"该订单无法取消,请联系客服!","");
}
}else{
errorMessage = new ErrorMessage(false,"非法操作!","");
}
}else{
errorMessage = new ErrorMessage(false,"该订单不存在!","");
}
}else{
errorMessage = new ErrorMessage(false,"该订单不存在!","");
}
}catch(Exception e){
errorMessage = new ErrorMessage(false,"取消失败!","");
e.printStackTrace();
}
writeObjectToResponse(errorMessage, ContentType.application_json);
}
/**
* 完成订单
*/
public void complete() throws Exception {
// 这里获取登陆的用户id
TMember member = (TMember) this.getSession().getAttribute("member");
String id = this.getRequest().getParameter("id");
Map<String, Object> param = new HashMap<String, Object>();
param.put("id", id);
if (id.matches("[0-9]+")) {
param.put("memberId", member.getId());
TOrder order = (TOrder) this.opensqlmanage.selectObjectByObject(param, "t_order.select_member_order_by_id");
if (order.getOrderStatus() == 2) {
TOrder updateOrder = new TOrder();
updateOrder.setId(Long.parseLong(id));
updateOrder.setOrderStatus(3);
String publicServiceUrl = tsysparametermanager.getKeys("public_service_url");
try{
tordermanager.complete(updateOrder,publicServiceUrl);
this.writeObjectToResponse(new ErrorMessage(true, "交易已完成", ""), ContentType.application_json);
}catch(Exception e){
e.printStackTrace();
this.writeObjectToResponse(new ErrorMessage(false, "订单有误,请联系客服", ""), ContentType.application_json);
}
} else {
this.writeObjectToResponse(new ErrorMessage(false, "订单有误,请联系客服", ""), ContentType.application_json);
}
} else {
this.writeObjectToResponse(new ErrorMessage(false, "异常操作", ""), ContentType.application_json);
}
}
/**
* 说明:组织调用payment项目的接口url(用于获取微信支付二维码图片的url)
* @param order 订单
* @param orderFlow 支付流水
* @param request
* @param response
* @return
*/
public String getErweiMaUrl(TOrder order,TOrderFlow orderFlow,HttpServletRequest request, HttpServletResponse response){
String payurl =InfoUtil.getInstance().getInfo("config","pay.payServiceUri");//支付域名
// 商品描述
String body = order.getOrderSn();
String detail = body;
String total_fee =orderFlow.getHavePay().multiply(new BigDecimal(100)).setScale(0).toString();
String spbill_create_ip = NetworkUtil.getIpAddress(request);
String notify_url = payurl+InfoUtil.getInstance().getInfo("config","wxNotifyUri");//回掉方法
String trade_type = WXTradeType.NATIVE.toString();//扫码支付
String product_id = order.getId().toString();
//获取私钥,生成sign
Map<String,Object> sendPaymentMap = new HashMap();
sendPaymentMap.put("body", body);
sendPaymentMap.put("detail", detail);
sendPaymentMap.put("out_trade_no", order.getOrderSn());//订单编号
sendPaymentMap.put("total_fee", total_fee);
sendPaymentMap.put("spbill_create_ip", spbill_create_ip);
sendPaymentMap.put("notify_url", notify_url);
sendPaymentMap.put("trade_type", trade_type);
sendPaymentMap.put("product_id", product_id);
String sign = Signature.getSign(sendPaymentMap,InfoUtil.getInstance().getInfo("config","wx.wxPaymentPk"));
//组织需要传的参数
StringBuilder sendParams = new StringBuilder();
sendParams.append("?body=").append(body)
.append("&detail=").append(detail)
.append("&out_trade_no=").append(order.getOrderSn())//订单编号
.append("&total_fee=").append(total_fee)
.append("&spbill_create_ip=").append(spbill_create_ip)
.append("¬ify_url=").append(notify_url)
.append("&trade_type=").append(trade_type)
.append("&product_id=").append(product_id)
.append("&sign=").append(sign);
//调用paymentService接口,获取微信二维码
String url = payurl+InfoUtil.getInstance().getInfo("config","pay.goUnifiedOrderServiceUri");
System.out.println(url + sendParams);
return url + sendParams;
}
/***
* 去评论页
*
* @return
* @throws SQLException
* @throws NumberFormatException
*/
public String applyGoodsComment() throws NumberFormatException, SQLException {
TMember tMember = (TMember) this.getSession().getAttribute("member");
if (tMember == null) {
return ERROR;
}
String orderId = this.getRequest().getParameter("orderId");
if (orderId == null || orderId.trim().equals("")) {
return ERROR;
}
TOrder tOrder = tordermanager.selectByPrimaryKey(Long.valueOf(orderId));
if (tOrder == null) {
return ERROR;
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("orderId", tOrder.getId());
List<Map<String, Object>> list = opensqlmanage.selectForListByMap(map,
"t_order_item.selectOrderItemByOrderIdApply");
this.getRequest().setAttribute("list", list);
this.getRequest().setAttribute("tOrder", tOrder);
return "add_goodscomment_page";
}
/**
* 检索城市
* @throws SQLException
*/
public void searchCity() throws SQLException{
String cityname = this.getRequest().getParameter("cityname");
if(StringUtils.hasText(cityname)){
CLocationCityExample cityexample = new CLocationCityExample();
cityexample.createCriteria().andGradeEqualTo(2).andNameLike("%"+cityname+"%");
cityexample.setOrderByClause(" pinyin asc");
List<CLocationCity> cityList =this.clocationcitymanager.selectByExample(cityexample);
this.writeObjectToResponse(cityList, ContentType.application_json);
}
}
/**
* 动态获取收货地址列表
* @throws SQLException
*/
public void ajaxReceiverList() throws Exception{
TMember member = (TMember)this.getSession().getAttribute("member");
Long memberId = member.getId();
String publicServiceUrl = tsysparametermanager.getKeys("public_service_url");
Map<String,String> publicMap = new HashMap<String,String>();
publicMap.put("member_id", String.valueOf(memberId));
String resultJsonstr =ClientSubmitPublic.getPublicService(publicMap, publicServiceUrl+"getReceiverAddress");
List<Map<String, Object>> resultList = null;
JSONObject jsonObject = JSONObject.fromObject(resultJsonstr);
if (jsonObject != null) {
JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("list"));
resultList = (List<Map<String, Object>>) JSONArray.toCollection(jsonArray, HashMap.class);
}
if(resultList!=null&&resultList.size()>0){
for(Map<String, Object> map:resultList){
if(map.get("latitude") instanceof JSONNull && map.get("longitude") instanceof JSONNull){
map.put("latitude","");
map.put("longitude","");
}
if(map.get("location_address") instanceof JSONNull){
map.put("location_address","");
}else{
String location_address =(String)map.get("location_address");
String address =(String)map.get("address");
String area = (String)map.get("area");
if(StringUtils.hasText(location_address)){
if(!address.startsWith(location_address)&&area.indexOf(location_address)==-1){
address= location_address+address;
map.put("address",address);
}
}
}
if(map.get("store_id") instanceof JSONNull){
map.put("store_id","");
}
if(map.get("area")!=null&&!"".equals(map.get("area"))){
map.put("areaFirstName", String.valueOf(map.get("area")).split("-")[0]);
}
}
}
this.writeObjectToResponse(resultList,ContentType.application_json);
}
/**
* ajax动态获取收货地址信息
* @throws SQLException
* @throws NumberFormatException
*/
public void ajaxReceiver() throws Exception{
String receiverId = this.getRequest().getParameter("receiverId");//收货地址id
if(StringUtils.hasText(receiverId)){
TMember member = (TMember)this.getSession().getAttribute("member");
Long memberId = member.getId();
String publicServiceUrl = tsysparametermanager.getKeys("public_service_url");
Map<String,String> publicMap = new HashMap<String,String>();
publicMap.put("member_id", String.valueOf(memberId));
publicMap.put("id", receiverId);
String resultJsonstr =ClientSubmitPublic.getPublicService(publicMap, publicServiceUrl+"getReceiverAddressById");
List<Map<String, Object>> resultList = null;
Map<String, Object> resultMap = null;
JSONObject jsonObject = JSONObject.fromObject(resultJsonstr);
if (jsonObject != null) {
resultMap = (Map<String, Object>) JSONObject.toBean(JSONObject.fromObject(jsonObject.get("address")),Map.class);
}
String beijingFlag ="0";//收获地址是否是北京 1 是 0 否
String hdfk_area =tsysparametermanager.getKeys("paymethod_hdfk_area");// 得到支持 货到付款的区域
if(resultMap!=null&&resultMap.get("area")!=null&&String.valueOf(resultMap.get("area")).indexOf(hdfk_area)!=-1){
beijingFlag="1";
}
Map<String,Object> receiverMap = new HashMap<String,Object>();
receiverMap.put("beijingFlag", beijingFlag);
if(resultMap.get("latitude") instanceof JSONNull && resultMap.get("longitude") instanceof JSONNull){
resultMap.put("latitude","");
resultMap.put("longitude","");
}
if(resultMap.get("location_address") instanceof JSONNull){
resultMap.put("location_address","");
}else{
String location_address =(String)resultMap.get("location_address");
String address =(String)resultMap.get("address");
String area = (String)resultMap.get("area");
if(StringUtils.hasText(location_address)){
if(!(!address.startsWith(location_address)&&area.indexOf(location_address)==-1)){
resultMap.put("location_address","");
}
}
}
if(resultMap.get("store_id") instanceof JSONNull){
resultMap.put("store_id","");
}
if (resultMap != null && resultMap.get("area_id") != null) {
CLocationCity cLocationCity = clocationcitymanager.selectByPrimaryKey(Integer.valueOf(resultMap.get("area_id").toString()));
if(cLocationCity!=null){
if(cLocationCity.getGrade().intValue()==3){
cLocationCity = clocationcitymanager.selectByPrimaryKey(cLocationCity.getParentid());
}else if(cLocationCity.getGrade().intValue()==4){
cLocationCity = clocationcitymanager.selectByPrimaryKey(cLocationCity.getParentid());
cLocationCity = clocationcitymanager.selectByPrimaryKey(cLocationCity.getParentid());
}
resultMap.put("citycode", cLocationCity.getCitycode());
}
}
receiverMap.put("receiver", resultMap);
this.writeObjectToResponse(receiverMap,ContentType.application_json);
}
}
/**
* ajax 保存或是修改 收货地址
* @throws SQLException
*/
public void ajaxSaveOrUpdateReceiver() throws Exception{
TMember member = (TMember) this.getSession().getAttribute("member");
Long memberId = member.getId();
Map<String,Object> resultMap = new HashMap<String,Object>();
String receiverId = "";
int receiverSize =0;
String message="";
String publicServiceUrl = tsysparametermanager.getKeys("public_service_url");
Map<String,String> publicMap = new HashMap<String,String>();
publicMap.put("member_id", String.valueOf(memberId));
publicMap.put("mobile", tmemberreceiver.getMobile().trim());
publicMap.put("receiver", tmemberreceiver.getReceiver().trim());
publicMap.put("longitude", tmemberreceiver.getLongitude());
publicMap.put("latitude", tmemberreceiver.getLatitude());
if(StringUtils.hasText(tmemberreceiver.getLocationAddress())){
publicMap.put("locationAddress", tmemberreceiver.getLocationAddress().trim());
}else{
publicMap.put("locationAddress", this.clocationcitymanager.selectByPrimaryKey(Integer.valueOf(this.getRequest().getParameter("tmemberreceiver_areaId"))).getName());
}
publicMap.put("address", tmemberreceiver.getAddress().trim());
if(StringUtils.hasText(tmemberreceiver.getLongitude())&&StringUtils.hasText(tmemberreceiver.getLatitude())){
String memberReceiver_adcode = this.getRequest().getParameter("memberReceiver_adcode");
CLocationCityExample example = new CLocationCityExample();
example.createCriteria().andCitycodeEqualTo(memberReceiver_adcode).andGradeEqualTo(2);
List<CLocationCity> cityList =this.clocationcitymanager.selectByExample(example);
if(cityList!=null&&cityList.size()>0){
publicMap.put("areaId",String.valueOf(cityList.get(0).getId()));
}
publicMap.put("cityName", this.getRequest().getParameter("city_name_set"));
tmemberreceiver.setArea(this.getRequest().getParameter("city_name_set"));
}else{
publicMap.put("areaId",this.getRequest().getParameter("tmemberreceiver_areaId"));
String cityname =this.clocationcitymanager.selectAreaName(Long.valueOf(this.getRequest().getParameter("tmemberreceiver_areaId")));
publicMap.put("cityName", cityname);
tmemberreceiver.setArea(cityname);
tmemberreceiver.setLocationAddress("");
}
publicMap.put("lonlatToAddressFlag", "1");// 是否根据经纬度 反解析地区信息 1表示否 其他表示不用
publicMap.put("isDefault", this.getRequest().getParameter("tmemberreceiver_is_default"));
TMemberReceiverLatLonExample example = new TMemberReceiverLatLonExample();
example.createCriteria().andMemberIdEqualTo(memberId);
List<TMemberReceiverLatLon> receiverLatLonList = tmemberreceiverlatlonmanager.selectByExample(example);
if (tmemberreceiver.getId() != null) {//修改
publicMap.put("id", String.valueOf(tmemberreceiver.getId()));
String resultJsonstr =ClientSubmitPublic.getPublicService(publicMap, publicServiceUrl+"updateReceiverAddress");
JSONObject jsonObject = JSONObject.fromObject(resultJsonstr);
if (jsonObject != null && jsonObject.get("statusCode") != null && "1".equals(jsonObject.get("statusCode"))) {
receiverId=String.valueOf(tmemberreceiver.getId().longValue());
}
} else {
receiverSize=receiverLatLonList.size();
if(!(receiverLatLonList!=null&&receiverLatLonList.size()>9)){
String resultJsonstr =ClientSubmitPublic.getPublicService(publicMap, publicServiceUrl+"addReceiverAddress");
JSONObject jsonObject = JSONObject.fromObject(resultJsonstr);
if (jsonObject != null && jsonObject.get("statusCode") != null && "1".equals(jsonObject.get("statusCode"))) {
receiverId=String.valueOf(jsonObject.get("id"));
}
}else{
message="收货地址超过10个上线,添加失败";
}
}
if(StringUtils.hasText(receiverId)){
tmemberreceiver.setId(Long.valueOf(receiverId.trim()));
}
resultMap.put("tmemberreceiver", tmemberreceiver);
resultMap.put("receiverSize", receiverSize);
resultMap.put("receiverId", receiverId);
resultMap.put("message", message);
this.writeObjectToResponse(resultMap,ContentType.application_json);
}
/**
* ajax 保存或是修改 收货地址
* @throws SQLException
*/
public void ajaxSaveOrUpdateReceiverNew() throws Exception{
TMember member = (TMember) this.getSession().getAttribute("member");
Long memberId = member.getId();
Map<String,Object> resultMap = new HashMap<String,Object>();
String receiverId = "";
int receiverSize =0;
String message="";
String publicServiceUrl = tsysparametermanager.getKeys("public_service_url");
Map<String,String> publicMap = new HashMap<String,String>();
publicMap.put("member_id", String.valueOf(memberId));
publicMap.put("mobile", tmemberreceiver.getMobile().trim());
publicMap.put("receiver", tmemberreceiver.getReceiver().trim());
// if(StringUtils.hasText(tmemberreceiver.getLocationAddress())){
// publicMap.put("locationAddress", tmemberreceiver.getLocationAddress().trim());
// }else{
publicMap.put("locationAddress", this.clocationcitymanager.selectByPrimaryKey(Integer.valueOf(this.getRequest().getParameter("tmemberreceiver_areaId"))).getName());
// }
publicMap.put("address", tmemberreceiver.getAddress().trim());
// if(StringUtils.hasText(tmemberreceiver.getLongitude())&&StringUtils.hasText(tmemberreceiver.getLatitude())){
// String memberReceiver_adcode = this.getRequest().getParameter("memberReceiver_adcode");
// CLocationCityExample example = new CLocationCityExample();
// example.createCriteria().andCitycodeEqualTo(memberReceiver_adcode).andGradeEqualTo(2);
// List<CLocationCity> cityList =this.clocationcitymanager.selectByExample(example);
// if(cityList!=null&&cityList.size()>0){
// publicMap.put("areaId",String.valueOf(cityList.get(0).getId()));
// }
// publicMap.put("cityName", this.getRequest().getParameter("city_name_set"));
// tmemberreceiver.setArea(this.getRequest().getParameter("city_name_set"));
// }else{
publicMap.put("areaId",this.getRequest().getParameter("tmemberreceiver_areaId"));
// String cityname =this.clocationcitymanager.selectAreaName(Long.valueOf(this.getRequest().getParameter("tmemberreceiver_areaId")));
publicMap.put("cityName", this.getRequest().getParameter("city_name_set"));
tmemberreceiver.setArea(this.getRequest().getParameter("city_name_set"));
tmemberreceiver.setLocationAddress(publicMap.get("locationAddress"));
// }
Map<String,String> latlonMap = new HashMap<String,String>();
latlonMap.put("area", publicMap.get("cityName"));
// latlonMap.put("locationAddress", publicMap.get("locationAddress"));
latlonMap.put("address", publicMap.get("address"));
String latlonJsonstr =ClientSubmitPublic.getPublicService(latlonMap, publicServiceUrl+"aMapGeoURIService");
if(StringUtils.hasText(latlonJsonstr)){
JSONObject latlonObject = JSONObject.fromObject(latlonJsonstr);
if(latlonObject != null && latlonObject.get("resCode") != null && latlonObject.getInt("resCode")==1){
String latlon =latlonObject.getJSONObject("result").getString("location");
publicMap.put("longitude", latlon.split(",")[0]);
publicMap.put("latitude", latlon.split(",")[1]);
}
}
publicMap.put("lonlatToAddressFlag", "1");// 是否根据经纬度 反解析地区信息 1表示否 其他表示不用
publicMap.put("isDefault", this.getRequest().getParameter("tmemberreceiver_is_default"));
if(StringUtils.hasText(this.getRequest().getParameter("tmemberreceiver_is_default"))){
tmemberreceiver.setIsDefault(Integer.valueOf(this.getRequest().getParameter("tmemberreceiver_is_default")));
}
TMemberReceiverLatLonExample example = new TMemberReceiverLatLonExample();
example.createCriteria().andMemberIdEqualTo(memberId);
List<TMemberReceiverLatLon> receiverLatLonList = tmemberreceiverlatlonmanager.selectByExample(example);
if (tmemberreceiver.getId() != null) {//修改
publicMap.put("id", String.valueOf(tmemberreceiver.getId()));
String resultJsonstr =ClientSubmitPublic.getPublicService(publicMap, publicServiceUrl+"updateReceiverAddress");
JSONObject jsonObject = JSONObject.fromObject(resultJsonstr);
if (jsonObject != null && jsonObject.get("statusCode") != null && "1".equals(jsonObject.get("statusCode"))) {
receiverId=String.valueOf(tmemberreceiver.getId().longValue());
}
} else {
receiverSize=receiverLatLonList.size();
if(!(receiverLatLonList!=null&&receiverLatLonList.size()>9)){
String resultJsonstr =ClientSubmitPublic.getPublicService(publicMap, publicServiceUrl+"addReceiverAddress");
JSONObject jsonObject = JSONObject.fromObject(resultJsonstr);
if (jsonObject != null && jsonObject.get("statusCode") != null && "1".equals(jsonObject.get("statusCode"))) {
receiverId=String.valueOf(jsonObject.get("id"));
}
}else{
message="收货地址超过10个上线,添加失败";
}
}
if(StringUtils.hasText(receiverId)){
tmemberreceiver.setId(Long.valueOf(receiverId.trim()));
}
resultMap.put("tmemberreceiver", tmemberreceiver);
resultMap.put("receiverSize", receiverSize);
resultMap.put("receiverId", receiverId);
resultMap.put("message", message);
this.writeObjectToResponse(resultMap,ContentType.application_json);
}
/**
* 根据城市查询 区域
* @throws Exception
*/
public void ajaxGetAreaByCity() throws Exception{
String citycode = this.getRequest().getParameter("citycode");
if(StringUtils.hasText(citycode)){
CLocationCityExample cLocationCityExample = new CLocationCityExample();
cLocationCityExample.createCriteria().andCitycodeEqualTo(citycode);
List<CLocationCity> cityAreaList =this.clocationcitymanager.selectByExample(cLocationCityExample);
if(cityAreaList!=null&&cityAreaList.size()>0){
cLocationCityExample = new CLocationCityExample();
cLocationCityExample.createCriteria().andParentidEqualTo(cityAreaList.get(0).getId());
cityAreaList = clocationcitymanager.selectByExample(cLocationCityExample);
this.writeObjectToResponse(cityAreaList,ContentType.application_json);
}
}
}
/**
* 根据城市查询 区域
* @throws Exception
*/
public void ajaxGetTwoAreaByAreaId() throws Exception{
String areaId = this.getRequest().getParameter("areaId");
if(StringUtils.hasText(areaId)){
CLocationCityExample cLocationCityExample = new CLocationCityExample();
cLocationCityExample.createCriteria().andParentidEqualTo(Integer.valueOf(areaId));
List<CLocationCity> cityAreaList = clocationcitymanager.selectByExample(cLocationCityExample);
this.writeObjectToResponse(cityAreaList,ContentType.application_json);
}
}
/**
* 更改订单支付方式为货到付款
*/
public void ajaxChangePayWayHdfk() throws Exception{
String orderId = this.getRequest().getParameter("orderId");
ErrorMessage errorMessage = new ErrorMessage();
errorMessage.setFlag(false);
errorMessage.setMessage("0");
errorMessage.setMessageContent("服务器异常操作失败!");
if(StringUtils.hasText(orderId)){
order = this.tordermanager.selectByPrimaryKey(Long.valueOf(orderId.trim()));
TMember member =(TMember)this.getSession().getAttribute("member");//这里获取登陆的用户id
if(order!=null&&member.getId().longValue()==order.getMemberId().longValue()){
if(order.getOrderStatus().intValue()==0){//待支付
boolean flag =this.tordermanager.changePayWayHdfk(order,4L);
if(flag){
errorMessage.setFlag(true);
errorMessage.setMessage("1");
}
}else{
errorMessage.setMessage("2");//订单不再未支付环节
}
}
}
this.writeObjectToResponse(errorMessage, ContentType.application_json);
}
/**
* 支付成功 payment 调用接口
* @throws SQLException
*/
public void writeStayMoneyByPayment() throws Exception {
String orderSn = this.getRequest().getParameter("orderSn");
InterfaceResult interfaceResult = new InterfaceResult();
if (orderSn != null && !"".equals(orderSn)) {
TOrderExample _tExample = new TOrderExample();
_tExample.createCriteria().andOrderSnEqualTo(orderSn);
List<TOrder> _orderList = tordermanager.selectByExample(_tExample);
if (_orderList != null && _orderList.size() == 1) {
order = _orderList.get(0);
if (order != null && order.getPaymentId() != null && order.getPaymentId() > 0L) {
CPaymentWay cPaymentWay = cpaymentwaymanager.selectByPrimaryKey(order.getPaymentId());
if (cPaymentWay != null && cPaymentWay.getPaymentCode() != null&& "xszf".equals(cPaymentWay.getPaymentCode())) {
String publicServiceUrl = tsysparametermanager.getKeys("public_service_url");
Map<String,String> publicMap = new HashMap<String,String>();
publicMap.put("orderId", String.valueOf(order.getId()));
String resultJsonstr =ClientSubmitPublic.getPublicService(publicMap, publicServiceUrl+"leaderStayMoneyURLService");
if(JSONObject.fromObject(resultJsonstr).get("statsCode").equals("1")){
interfaceResult.setStatus(1);
interfaceResult.setMesssage("写入成功");
this.writeObjectToResponse(interfaceResult, ContentType.application_json);
}else{
log.equals("orderId:"+String.valueOf(order.getId())+"计算佣金失败,失败原因:"+JSONObject.fromObject(resultJsonstr).get("message"));
interfaceResult.setStatus(0);
interfaceResult.setMesssage("返现异常");
this.writeObjectToResponse(interfaceResult, ContentType.application_json);
}
} else {
interfaceResult.setStatus(0);
interfaceResult.setMesssage("非支付订单");
this.writeObjectToResponse(interfaceResult, ContentType.application_json);
}
} else {
interfaceResult.setStatus(0);
interfaceResult.setMesssage("非支付订单");
this.writeObjectToResponse(interfaceResult, ContentType.application_json);
}
} else {
interfaceResult.setStatus(0);
interfaceResult.setMesssage("未查询到该订单");
this.writeObjectToResponse(interfaceResult, ContentType.application_json);
}
} else {
interfaceResult.setStatus(0);
interfaceResult.setMesssage("订单编号为空");
this.writeObjectToResponse(interfaceResult, ContentType.application_json);
}
}
class InterfaceResult {
private int status;
private String messsage;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMesssage() {
return messsage;
}
public void setMesssage(String messsage) {
this.messsage = messsage;
}
}
public class ErrorMessage {
private boolean flag;
private String message;
private String messageContent;
public ErrorMessage() {
super();
}
public ErrorMessage(boolean flag, String message,String messageContent) {
super();
this.flag = flag;
this.message = message;
this.messageContent= messageContent;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessageContent() {
return messageContent;
}
public void setMessageContent(String messageContent) {
this.messageContent = messageContent;
}
}
public Object getModel() {
return null;
}
public void setModel(Object o) {
}
public TOrderManager getTordermanager() {
return tordermanager;
}
public void setTordermanager(TOrderManager tordermanager) {
this.tordermanager = tordermanager;
}
public TMemberReceiverLatLonManager getTmemberreceiverlatlonmanager() {
return tmemberreceiverlatlonmanager;
}
public void setTmemberreceiverlatlonmanager(
TMemberReceiverLatLonManager tmemberreceiverlatlonmanager) {
this.tmemberreceiverlatlonmanager = tmemberreceiverlatlonmanager;
}
public CPaymentWayManager getCpaymentwaymanager() {
return cpaymentwaymanager;
}
public void setCpaymentwaymanager(CPaymentWayManager cpaymentwaymanager) {
this.cpaymentwaymanager = cpaymentwaymanager;
}
public OpenSqlManage getOpensqlmanage() {
return opensqlmanage;
}
public void setOpensqlmanage(OpenSqlManage opensqlmanage) {
this.opensqlmanage = opensqlmanage;
}
public TGoodsManager getTgoodsmanager() {
return tgoodsmanager;
}
public void setTgoodsmanager(TGoodsManager tgoodsmanager) {
this.tgoodsmanager = tgoodsmanager;
}
public TOrder getOrder() {
return order;
}
public void setOrder(TOrder order) {
this.order = order;
}
public TMemberAccountManager getTmemberaccountmanager() {
return tmemberaccountmanager;
}
public TCouponManager getTcouponmanager() {
return tcouponmanager;
}
public void setTcouponmanager(TCouponManager tcouponmanager) {
this.tcouponmanager = tcouponmanager;
}
public PageWraper getPw() {
return pw;
}
public void setPw(PageWraper pw) {
this.pw = pw;
}
public PageResult getRs() {
return rs;
}
public void setRs(PageResult rs) {
this.rs = rs;
}
public TOrderItemManager getTorderitemmanager() {
return torderitemmanager;
}
public void setTorderitemmanager(TOrderItemManager torderitemmanager) {
this.torderitemmanager = torderitemmanager;
}
public void setTmemberaccountmanager(TMemberAccountManager tmemberaccountmanager) {
this.tmemberaccountmanager = tmemberaccountmanager;
}
public TOrderFlowManager getTorderflowmanager() {
return torderflowmanager;
}
public void setTorderflowmanager(TOrderFlowManager torderflowmanager) {
this.torderflowmanager = torderflowmanager;
}
public PaymentPluginMaager getPaymentpluginmaager() {
return paymentpluginmaager;
}
public void setPaymentpluginmaager(PaymentPluginMaager paymentpluginmaager) {
this.paymentpluginmaager = paymentpluginmaager;
}
public TCouponCardManager getTcouponcardmanager() {
return tcouponcardmanager;
}
public void setTcouponcardmanager(TCouponCardManager tcouponcardmanager) {
this.tcouponcardmanager = tcouponcardmanager;
}
public TSysParameterManager getTsysparametermanager() {
return tsysparametermanager;
}
public void setTsysparametermanager(TSysParameterManager tsysparametermanager) {
this.tsysparametermanager = tsysparametermanager;
}
public MessageSender getTopicMessageSender() {
return topicMessageSender;
}
public void setTopicMessageSender(MessageSender topicMessageSender) {
this.topicMessageSender = topicMessageSender;
}
public TLeaderStayMoneyManager getTleaderstaymoneymanager() {
return tleaderstaymoneymanager;
}
public void setTleaderstaymoneymanager(TLeaderStayMoneyManager tleaderstaymoneymanager) {
this.tleaderstaymoneymanager = tleaderstaymoneymanager;
}
public CDeliveryWayManager getCdeliverywaymanager() {
return cdeliverywaymanager;
}
public void setCdeliverywaymanager(CDeliveryWayManager cdeliverywaymanager) {
this.cdeliverywaymanager = cdeliverywaymanager;
}
public CLocationCityManager getClocationcitymanager() {
return clocationcitymanager;
}
public void setClocationcitymanager(CLocationCityManager clocationcitymanager) {
this.clocationcitymanager = clocationcitymanager;
}
public TMemberReceiverLatLon getTmemberreceiver() {
return tmemberreceiver;
}
public void setTmemberreceiver(TMemberReceiverLatLon tmemberreceiver) {
this.tmemberreceiver = tmemberreceiver;
}
public TMemberBaseMessageExtManager getTmemberbasemessageextmanager() {
return tmemberbasemessageextmanager;
}
public void setTmemberbasemessageextmanager(
TMemberBaseMessageExtManager tmemberbasemessageextmanager) {
this.tmemberbasemessageextmanager = tmemberbasemessageextmanager;
}
/**
* 根据城市查询 区域
* @throws Exception
*/
public void ajaxGetFirstAreas() throws Exception{
CLocationCityExample cLocationCityExample = new CLocationCityExample();
cLocationCityExample.createCriteria().andParentidEqualTo(-1);
List<CLocationCity> cityAreaList =this.clocationcitymanager.selectByExample(cLocationCityExample);
if(cityAreaList!=null&&cityAreaList.size()>0){
// cLocationCityExample = new CLocationCityExample();
// cLocationCityExample.createCriteria().andParentidEqualTo(cityAreaList.get(0).getId());
// cityAreaList = clocationcitymanager.selectByExample(cLocationCityExample);
this.writeObjectToResponse(cityAreaList,ContentType.application_json);
}
}
/*********Marlon***********/
public OrderServiceDubboApi getOrderservicedubboapi() {
return orderservicedubboapi;
}
public void setOrderservicedubboapi(
OrderServiceDubboApi orderservicedubboapi) {
this.orderservicedubboapi = orderservicedubboapi;
}
}
|
package com.thoughtmechanix.licenses.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
@Getter
@Setter
@ToString
public class Organization implements Serializable {
String id;
String name;
String contactName;
String contactEmail;
String contactPhone;
}
|
package cn.timebusker.mq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
/**
* @DESC:KafkaProducer:消息投递
* @author:timebusker
* @date:2018/9/13
*/
@Service
public class KafkaProducerService {
private final static Logger logger = LoggerFactory.getLogger(KafkaProducerService.class);
@Autowired
private KafkaTemplate<String,String> kafkaTemplate;
public void produce(String topic,String message){
try {
kafkaTemplate.send(topic,message);
}catch (Exception e){
logger.info(e.getMessage());
}
}
}
|
//package com.tutorial.batch.domain;
//
//import lombok.AccessLevel;
//import lombok.Getter;
//import lombok.NoArgsConstructor;
//import lombok.Setter;
//
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.GenerationType;
//import javax.persistence.Id;
//
//@Getter
//@Setter
//@NoArgsConstructor
//@Entity
//public class PaySuccess {
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
//
// private Long amount;
// private boolean success;
//
// public PaySuccess(Long amount, boolean successStatus) {
// this.amount = amount;
// this.success = successStatus;
// }
//
// public void success() {
// this.success = true;
// }
//}
|
/**
*
*/
package com.paytechnologies.DTO;
/**
* @author Arun
*
*/
public class TripDetailsDTO {
int tripId = 0;
int userId = 0;
String startLocation = "";
String startLocationAlias="";
String endLocation="";
String endLocationAlias="";
String startLanglat="";
String endLanglat="";
String travelDays="";
int tripFrequencyId=0;
String pickTime="";
String flexiblePickTime="";
int userType=0;
int isProfileTrip=0;
/**
* @return the tripId
*/
public int getTripId() {
return tripId;
}
/**
* @param tripId the tripId to set
*/
public void setTripId(int tripId) {
this.tripId = tripId;
}
/**
* @return the userId
*/
public int getUserId() {
return userId;
}
/**
* @param userId the userId to set
*/
public void setUserId(int userId) {
this.userId = userId;
}
/**
* @return the startLocation
*/
public String getStartLocation() {
return startLocation;
}
/**
* @param startLocation the startLocation to set
*/
public void setStartLocation(String startLocation) {
this.startLocation = startLocation;
}
/**
* @return the startLocationAlias
*/
public String getStartLocationAlias() {
return startLocationAlias;
}
/**
* @param startLocationAlias the startLocationAlias to set
*/
public void setStartLocationAlias(String startLocationAlias) {
this.startLocationAlias = startLocationAlias;
}
/**
* @return the endLocation
*/
public String getEndLocation() {
return endLocation;
}
/**
* @param endLocation the endLocation to set
*/
public void setEndLocation(String endLocation) {
this.endLocation = endLocation;
}
/**
* @return the endLocationAlias
*/
public String getEndLocationAlias() {
return endLocationAlias;
}
/**
* @param endLocationAlias the endLocationAlias to set
*/
public void setEndLocationAlias(String endLocationAlias) {
this.endLocationAlias = endLocationAlias;
}
/**
* @return the startLanglat
*/
public String getStartLanglat() {
return startLanglat;
}
/**
* @param startLanglat the startLanglat to set
*/
public void setStartLanglat(String startLanglat) {
this.startLanglat = startLanglat;
}
/**
* @return the endLanglat
*/
public String getEndLanglat() {
return endLanglat;
}
/**
* @param endLanglat the endLanglat to set
*/
public void setEndLanglat(String endLanglat) {
this.endLanglat = endLanglat;
}
/**
* @return the travelDays
*/
public String getTravelDays() {
return travelDays;
}
/**
* @param travelDays the travelDays to set
*/
public void setTravelDays(String travelDays) {
this.travelDays = travelDays;
}
/**
* @return the tripFrequencyId
*/
public int getTripFrequencyId() {
return tripFrequencyId;
}
/**
* @param tripFrequencyId the tripFrequencyId to set
*/
public void setTripFrequencyId(int tripFrequencyId) {
this.tripFrequencyId = tripFrequencyId;
}
/**
* @return the pickTime
*/
public String getPickTime() {
return pickTime;
}
/**
* @param pickTime the pickTime to set
*/
public void setPickTime(String pickTime) {
this.pickTime = pickTime;
}
/**
* @return the flexiblePickTime
*/
public String getFlexiblePickTime() {
return flexiblePickTime;
}
/**
* @param flexiblePickTime the flexiblePickTime to set
*/
public void setFlexiblePickTime(String flexiblePickTime) {
this.flexiblePickTime = flexiblePickTime;
}
/**
* @return the userType
*/
public int getUserType() {
return userType;
}
/**
* @param userType the userType to set
*/
public void setUserType(int userType) {
this.userType = userType;
}
/**
* @return the isProfileTrip
*/
public int getIsProfileTrip() {
return isProfileTrip;
}
/**
* @param isProfileTrip the isProfileTrip to set
*/
public void setIsProfileTrip(int isProfileTrip) {
this.isProfileTrip = isProfileTrip;
}
}
|
package net.lin.www;
import com.google.gson.Gson;
import java.sql.*;
import java.util.LinkedList;
/**
* Created by Lin on 1/11/16.
*/
public class DatabaseManager
{
static String filename = "./data/GiltCity/GiltCity_New York_data_with_contact_info_v1.txt";
public static void main(String[] args)
{
insertVendors(readData(filename));
}
public static void insertVendors(LinkedList<Vendor> vendors)
{
Connection connection = MySQLConnector.getConnection();
for(Vendor vendor : vendors)
{
vendor.print();
String sql = "insert into Merchant(Mname, Source, YPMname, Website, Mphone, Memail, City, City_State, Address, ActivityNum) values " +
"(?,?,?,?,?,?,?,?,?,?)";
try
{
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, vendor.vendorName);
statement.setString(2, vendor.activities.getFirst().source);
statement.setString(3, vendor.yellowPageName);
statement.setString(4, vendor.website);
statement.setString(5, vendor.phoneNumber);
statement.setString(6, vendor.email);
statement.setString(7, vendor.activities.getFirst().city);
statement.setString(8, vendor.city_state);
statement.setString(9, vendor.yellowPageaddress);
statement.setInt(10, vendor.activityNum);
statement.execute();
sql = "SELECT LAST_INSERT_ID();";
int Mid;
Statement midStatement = connection.createStatement();
ResultSet resultSet = midStatement.executeQuery(sql);
if (resultSet.next())
{
Mid = resultSet.getInt("LAST_INSERT_ID()");
System.out.println("Mid: " + Mid);
} else
{
System.out.println("failed to get Mid");
return;
}
midStatement.close();
for(Activity activity : vendor.activities)
{
sql = "insert into Activity(Aname, Price, Description, Aurl, " +
"Aphone, AAddress, City, Mid, Mname, Source, Category) values" +
"(?,?,?,?,?,?,?,?,?,?,?)";
statement = connection.prepareStatement(sql);
statement.setString(1, activity.activityName);
statement.setString(2, activity.price);
statement.setString(3, activity.description);
statement.setString(4, activity.activityURL);
statement.setString(5, activity.activityPhone);
statement.setString(6, activity.activityAddress);
statement.setString(7, activity.city);
statement.setInt(8, Mid);
statement.setString(9, vendor.vendorName);
statement.setString(10, activity.source);
statement.setString(11, activity.category);
statement.execute();
}
statement.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
public static LinkedList<Vendor> readData(String filename)
{
Gson gson = new Gson();
LinkedList<String> vendorStringList = FileOperator.readFile(filename);
LinkedList<Vendor> vendorList = new LinkedList<Vendor>();
for(String v : vendorStringList)
{
Vendor vendor = gson.fromJson(v, Vendor.class);
//-------------------------------
vimblyDataProcessor(vendor);
vendorList.add(vendor);
}
/*for(Vendor temp : vendorList)
{
temp.print();
}*/
return vendorList;
}
public static void vimblyDataProcessor(Vendor vendor)
{
for(Activity activity : vendor.activities)
{
activity.source = "GiltCity";
activity.city = "New York";
activity.category = "everything";
}
}
}
|
package com.techlab.crud;
public class CustomerDb implements Icrudable {
@Override
public void create() {
System.out.println("create in CustomerDb");
}
@Override
public void read() {
System.out.println("read in CustomerDb");
}
@Override
public void update() {
System.out.println("update in CustomerDb");
}
@Override
public void delete() {
System.out.println("delete in CustomerDb");
}
}
|
package com.tencent.mm.ui.chatting.viewitems;
import android.graphics.Bitmap;
import com.tencent.mm.modelappbrand.b.b$h;
import com.tencent.mm.plugin.appbrand.q.k;
import com.tencent.mm.ui.chatting.viewitems.c.c;
import com.tencent.mm.ui.chatting.viewitems.c.d;
class c$d$2 implements b$h {
final /* synthetic */ c uaC;
final /* synthetic */ d uaD;
c$d$2(d dVar, c cVar) {
this.uaD = dVar;
this.uaC = cVar;
}
public final void Kc() {
}
public final void n(Bitmap bitmap) {
if (bitmap == null || bitmap.isRecycled()) {
this.uaC.uar.setVisibility(4);
this.uaC.uas.setVisibility(0);
return;
}
this.uaC.uar.setImageBitmap(bitmap);
this.uaC.uar.setVisibility(0);
this.uaC.uas.setVisibility(4);
}
public final void Kd() {
}
public final String Ke() {
return "CHAT#" + k.bq(this);
}
}
|
package fr.lteconsulting.formations;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet( "/session" )
public class SessionServlet extends HttpServlet
{
Map<String, Map<String, Object>> sessions = new HashMap<>();
@Override
protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException
{
if( "true".equals( req.getParameter( "raz" ) ) )
clearSession( req );
Integer compteur = (Integer) getSession( req, resp ).get( "compteur" );
if( compteur == null )
compteur = 0;
compteur++;
getSession( req, resp ).put( "compteur", compteur );
resp.setContentType( "text/html" );
resp.getWriter().print( "<html><body>"
+ "compteur : " + compteur
+ "</body></html>" );
}
private void clearSession( HttpServletRequest req )
{
String cookieValue = getSopraCookieValue( req );
if( cookieValue != null )
sessions.remove( cookieValue );
}
private Map<String, Object> getSession( HttpServletRequest req, HttpServletResponse resp )
{
// est-ce que on a le cookie SOPRA_COOKIE ?
String cookieValue = getSopraCookieValue( req );
Map<String, Object> session = null;
if( cookieValue != null )
session = sessions.get( cookieValue );
// si j'ai pas trouvé de session j'en crée une et je l'enregistre
if( session == null )
{
cookieValue = UUID.randomUUID().toString();
session = new HashMap<>();
sessions.put( cookieValue, session );
resp.addCookie( new Cookie( "SOPRA_COOKIE", cookieValue ) );
}
return session;
}
private String getSopraCookieValue( HttpServletRequest req )
{
Cookie[] cookies = req.getCookies();
if( cookies == null )
return null;
for( Cookie cookie : cookies )
if( "SOPRA_COOKIE".equals( cookie.getName() ) )
return cookie.getValue();
return null;
}
}
|
package com.ifli.mbcp.dao;
import static org.junit.Assert.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.annotation.Rollback;
import com.ifli.mbcp.BaseMBCPTest;
import com.ifli.mbcp.domain.AddressType;
import com.ifli.mbcp.domain.BDMCode;
import com.ifli.mbcp.domain.BMRMCode;
import com.ifli.mbcp.domain.BranchCode;
import com.ifli.mbcp.domain.Channel;
import com.ifli.mbcp.domain.City;
import com.ifli.mbcp.domain.CustomerAddress;
import com.ifli.mbcp.domain.CustomerDetails;
import com.ifli.mbcp.domain.IndividualProposal;
import com.ifli.mbcp.domain.InsurancePlan;
import com.ifli.mbcp.domain.KindOfLead;
import com.ifli.mbcp.domain.Lead;
import com.ifli.mbcp.domain.LeadCategory;
import com.ifli.mbcp.domain.LeadGeneratorCode;
import com.ifli.mbcp.domain.LeadStatus;
import com.ifli.mbcp.domain.LeadType;
import com.ifli.mbcp.domain.MaritalStatus;
import com.ifli.mbcp.domain.PremiumFrequency;
import com.ifli.mbcp.domain.Proposal;
import com.ifli.mbcp.domain.Salutation;
import com.ifli.mbcp.domain.State;
import com.ifli.mbcp.util.MBCPConstants;
import com.ifli.mbcp.util.MBCPConstants.PageType;
import com.ifli.mbcp.util.MBCPConstants.SearchBy;
import com.ifli.mbcp.vo.SearchCriteriaBean;
/**
* This class is responsible for unit testing all the methods available in
* LeadDAO along with some of the methods available in GenericDAO.<br>
* As of 23-May-2013 The sample data contains minimum of 2 records for each of
* the following entities with Ids 1 and 2 respectively, which is available for
* testing. More sample data can be added in future depending on the methods
* covered in unit testing.<br>
* Please refer to @see sample-data.xml in src/test/resources folder for
* available sample data. <br>
* <b> Entities with sample data</b>
* <ul>
* <li>BMRMCode</li>
* <li>BDMCode</li>
* <li>BranchCode</li>
* <li>Channel</li>
* <li>CustomerDetails</li>
* <li>CustomerAddress</li>
* <li>AddressType</li>
* <li>State</li>
* <li>City</li>
* <li>InsurancePlan</li>
* <li>Lead</li>
* <li>LeadGeneratorCode</li>
* <li>LeadStatus</li>
* <li>LeadCategory</li>
* <li>LeadType</li>
* <li>MaritalStatus</li>
* <li>PremiumFrequency</li>
* <li>Salutation</li>
* <li>PlanType</li>
* <li>Proposal</li>
* <li>TaskType</li>
* <li>Language</li>
* </ul>
*
* @author Niranjan
*
*/
public class LeadDAOTest extends BaseMBCPTest
{
@Autowired
@Qualifier("leadDAO")
private LeadDAO leadDAO;
private Lead testLead;
private CustomerDetails custDetails;
private Salutation salutation;
private MaritalStatus maritalStatus;
private CustomerAddress address;
private LeadCategory leadCategory;
private LeadType leadType;
private LeadStatus leadStatus;
private BranchCode branchCode;
private BDMCode bdmCode;
private BMRMCode bmrmCode;
private LeadGeneratorCode leadGeneratorCode;
private Channel channel;
private SearchCriteriaBean searchCriteria;
/**
* A Lead instance is available with all the mandatory fields pre-populated,
* which can be saved to DB directly, before execution of every test method
*/
@Before
public void init()
{
testLead = new Lead();
custDetails = new CustomerDetails();
salutation = new Salutation();
salutation.setSalutationId((long) 1);
custDetails.setSalutation(salutation);
custDetails.setFirstName("Chamataka");
custDetails.setMiddleName("The");
custDetails.setLastName("Fox");
custDetails.setGender(MBCPConstants.MALE);
custDetails.setMobileNumber("1234567890");
maritalStatus = new MaritalStatus();
maritalStatus.setId((long) 1);
custDetails.setMaritalStatus(maritalStatus);
address = new CustomerAddress();
address.setAddressLine1("Kalia the Crow Stories");
address.setAddressLine2("The Jungle");
address.setAddressLine3("Tinkle");
AddressType addressType = new AddressType();
addressType.setId((long) 1);
address.setAddressType(addressType);
State state = new State();
state.setStateId((long) 1);
address.setState(state);
City city = new City();
city.setCityId((long) 1);
address.setCity(city);
address.setPinCode("112233");
Set<CustomerAddress> customerAddresses = new TreeSet<CustomerAddress>();
customerAddresses.add(address);
custDetails.setCustomerAddress(customerAddresses);
Set<Proposal> proposals = new TreeSet<Proposal>();
IndividualProposal p = new IndividualProposal();
InsurancePlan plan = new InsurancePlan();
plan.setId((long) 1);
PremiumFrequency premiumFrequency = new PremiumFrequency();
premiumFrequency.setId((long) 1);
p.setInsuranceProduct(plan);
p.setPremiumAmount(BigDecimal.valueOf(50000));
p.setPremiumFrequency(premiumFrequency);
proposals.add(p);
testLead.setProposalsMade(proposals);
leadCategory = new LeadCategory();
leadCategory.setId((long) 1);
leadType = new LeadType();
leadType.setId((long) 1);
leadStatus = new LeadStatus();
leadStatus.setId((long) 1);
branchCode = new BranchCode();
branchCode.setId((long) 1);
bdmCode = new BDMCode();
bdmCode.setId((long) 1);
bmrmCode = new BMRMCode();
bmrmCode.setId((long) 1);
leadGeneratorCode = new LeadGeneratorCode();
leadGeneratorCode.setId((long) 1);
channel = new Channel();
channel.setId((long) 1);
testLead.setLeadCustomerDetails(custDetails);
testLead.setBdmCode(bdmCode);
testLead.setBmRmCode(bmrmCode);
testLead.setBranchCode(branchCode);
testLead.setChannelSelection(channel);
testLead.setLeadCategory(leadCategory);
testLead.setLeadGeneratorCode(leadGeneratorCode);
testLead.setLeadStatus(leadStatus);
testLead.setLeadType(leadType);
testLead.setCreatedDate(new Date());
testLead.setModifiedDate(new Date());
//Search Initialization
searchCriteria = new SearchCriteriaBean();
//These are default values for testing the search scenarios
//Override them in respective testmethods to the change the search criteria
searchCriteria.setPageType(PageType.LEAD);
searchCriteria.setLeadType(KindOfLead.INDIVIDUAL);
}
@Test
@Rollback(true)
public void testAddLead()
{
printTitle();
Long testID = (Long) leadDAO.save(testLead);
assertTrue(testID.longValue() > 0);
System.out.println("\n\n*** " + testID.longValue());
}
@Test
public void testFindById()
{
printTitle();
// Lead with Id 1 already exist in sample data
Lead testLead = leadDAO.findById(Lead.class, 1L);
assertNotNull("No Lead found with Id 1", testLead);
// check indeed if the leadId is 1
assertTrue("Selected a wrong Lead", testLead.getLeadId() == 1L);
}
@Test
// @Ignore
public void testSearchByName()
{
printTitle();
String name = "Har";
searchCriteria.setSearchById(SearchBy.FIRST_OR_LAST_NAME.getValue());
searchCriteria.setSearchText(name);
List<Lead> leadList = leadDAO.search(searchCriteria);
assertTrue("No records found for the given Name", !leadList.isEmpty());
Lead testLead = leadList.get(0);
// check indeed if the Firstname or Lastname startswith what we are
// expecting
assertTrue("Name doesn't start with " + name, testLead.getLeadCustomerDetails().getFirstName().startsWith(name)
|| testLead.getLeadCustomerDetails().getLastName().startsWith(name));
}
@Test
// @Ignore
public void testSearchByMobileNo()
{
printTitle();
String expected = "9856321457";
searchCriteria.setSearchById(MBCPConstants.SearchBy.MOBILE_NO.getValue());
searchCriteria.setSearchText(expected);
List<Lead> leadList = leadDAO.search(searchCriteria);
assertTrue("No records found with the given Mobile Number " + expected, leadList.size() > 0);
Lead testLead = leadList.get(0);
// check indeed if the MobileNo is what we are expecting
assertEquals(expected, testLead.getLeadCustomerDetails().getMobileNumber());
}
@Test
@Rollback(true)
public void testUpdateLead()
{
printTitle();
// get the created Lead back from DB to update
Lead newLead = leadDAO.findById(Lead.class, 1l);
// add Comments
newLead.setComments("Hello, This is India First Life Insurance");
// Change the BranchCode
BranchCode newBranchCode = new BranchCode();
newBranchCode.setId((long) 2);
newLead.setBranchCode(newBranchCode);
// update it
leadDAO.update(newLead);
// fetch it back again and compare
Lead updatedLead = leadDAO.findById(Lead.class, 1l);
// currently just comparing the branchCode
assertEquals((long) 2, (long) updatedLead.getBranchCode().getId());
}
@Test
@Rollback(true)
public void testDeleteLead()
{
printTitle();
leadDAO.deleteById(Lead.class, 1L);
Lead testLead = leadDAO.findById(Lead.class, 1L);
assertNull("Lead with Id 1 isn't deleted", testLead);
}
@Test
public void testFindAll()
{
printTitle();
List<Lead> leadList = leadDAO.findAll(Lead.class);
assertTrue("No records found for Lead", leadList.size() > 0);
}
@Test
public void testSearchByInsuranceProductName()
{
printTitle();
String expected = "Jeevan Suraksha";
searchCriteria.setSearchById(MBCPConstants.SearchBy.PRODUCT.getValue());
searchCriteria.setSearchText(expected);
List<Lead> leadList = leadDAO.search(searchCriteria);
assertTrue("No records found for the given Product Name", leadList.size() > 0);
IndividualProposal iP = (IndividualProposal) leadList.get(0).getProposalsMade().iterator().next();
String actual = iP.getInsuranceProduct().getName();
// check indeed if the Product Name in the returned Lead is what we are
// expecting
assertEquals(expected, actual);
}
/*@Test
// @Ignore
public void testSearchLeadByApplicatioNumber()
{
printTitle();
List<Lead> leadList = leadDAO.search(MBCPConstants.SearchBy.APPLICATION_NUMBER.getValue(), "1");
assertTrue("No records found for the given application Number", leadList.size() > 0);
String actual = leadList.get(0).getProposalsMade().iterator().next().getPaddedProposalId();
// Check indeed if the returned Application no. is what we are expecting
assertEquals("P00000001", actual);
}
*/
//@Ignore
@Test
public void testSearchLeadByCreateDate()
{
printTitle();
String expected = "05/31/2013";
searchCriteria.setSearchById(MBCPConstants.SearchBy.LEAD_CREATED_DATE.getValue());
searchCriteria.setSearchText(expected);
List<Lead> leadList = leadDAO.search(searchCriteria);
assertTrue(leadList.size() > 0);
// Check indeed if the dates are equal by converting the result into
// string and then comparing
assertEquals(expected, new SimpleDateFormat("MM/dd/yyyy").format(leadList.get(0).getCreatedDate()));
}
}
|
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package voc.cn.cnvoccoin.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
/**
* Private class created to work around issues with AnimationListeners being
* called before the animation is actually complete and support shadows on older
* platforms.
*/
public class CircleImageView extends android.support.v7.widget.AppCompatImageView {
/**
* 自定义的圆形ImageView,可以直接当组件在布局中使用。
*/
private Paint paint;
public CircleImageView(Context context) {
this(context, null);
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
}
/**
* 绘制圆形图片
*/
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (null != drawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap b = getCircleBitmap(bitmap);
final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
final Rect rectDest = new Rect(0, 0, getWidth(), getHeight());
paint.reset();
canvas.drawBitmap(b, rectSrc, rectDest, paint);
} else {
super.onDraw(canvas);
}
}
/**
* 获取圆形图片方法
*
* @param bitmap
* @return Bitmap
*/
private Bitmap getCircleBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int left = 0, top = 0, right = width, bottom = height;
if (width >= height) {
left = (width - height) / 2;
top = 0;
right = left + height;
bottom = height;
} else if (height > width) {
left = 0;
top = (height - width) / 2;
right = width;
bottom = top + width;
}
final Rect rect = new Rect(left, top, right, bottom);
final int color = 0xff424242;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
int r = Math.min(bitmap.getWidth(), bitmap.getHeight());
int x = bitmap.getWidth();
int y = bitmap.getHeight();
canvas.drawCircle(x / 2, y / 2, r / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
Bitmap result = Bitmap.createBitmap(output, left, top, r, r);
return result;
}
}
|
package manage.studentgui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PrinterException;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import manage.app.Application;
import manage.bean.Grade;
import manage.bean.Student;
import manage.service.impl.StudentServiceImpl;
public class UpdateStudenInforFrame extends JFrame {
//定义Vector
private Vector rows;
private Vector colHead;
/**
* 学号文本框
*/
//定义服务实现类
private StudentServiceImpl studentServiceImpl;
//定义gui组件
private JTable table;
private JScrollPane scroller;
JPanel frame;
JTextField text1;
JTextField text2;
JTextField text3;
JTextField text4;
JTextField text5;
JTextField text6;
JTextField text7;
JButton bupdate;
JButton brefresh;
JButton bexit;
//定义实体类
Student student;
//设置构造方法
public UpdateStudenInforFrame(String title) {
super(title);
Start();
}
//定义执行方法
public void Start(){
//vector实例化
rows=new Vector();
colHead=new Vector();
//gui界面设计
frame = (JPanel) getContentPane();
frame.setLayout(new BorderLayout());
JPanel pnlNorth=new JPanel();
pnlNorth.setLayout(new GridLayout(7,2));
JPanel southJPanel=new JPanel();
southJPanel.setLayout(new FlowLayout());
JLabel label1=new JLabel("学号: ");
JLabel label2=new JLabel("班号: ");
JLabel label3=new JLabel("姓名: ");
JLabel label4=new JLabel("性别: ");
JLabel label5=new JLabel("年龄: ");
JLabel label6=new JLabel("地址: ");
JLabel label7=new JLabel("电话: ");
text1=new JTextField(11);
text2=new JTextField(11);
text3=new JTextField(11);
text4=new JTextField(11);
text5=new JTextField(11);
text6=new JTextField(11);
text7=new JTextField(11);
pnlNorth.add(label1);
pnlNorth.add(text1);
pnlNorth.add(label2);
pnlNorth.add(text2);
pnlNorth.add(label3);
pnlNorth.add(text3);
pnlNorth.add(label4);
pnlNorth.add(text4);
pnlNorth.add(label5);
pnlNorth.add(text5);
pnlNorth.add(label6);
pnlNorth.add(text6);
pnlNorth.add(label7);
pnlNorth.add(text7);
text1.setEditable(false);
bupdate=new JButton("修改");
brefresh=new JButton("刷新");
bexit=new JButton("退出");
southJPanel.add(bupdate);
southJPanel.add(brefresh);
southJPanel.add(bexit);
frame.add(southJPanel,BorderLayout.SOUTH);
frame.add(pnlNorth,BorderLayout.CENTER);
studentServiceImpl =new StudentServiceImpl();
pnlNorth.add(label1);
pnlNorth.add(text1);
update();
System.out.println(student);
//显示结果集方法
pack();
setSize(300,350);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
// 重绘窗体
repaint();
//修改按钮
bupdate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
student=new Student();
student.setStudent_id(Integer.parseInt(text1.getText()));
student.setClass_id(Integer.parseInt(text2.getText()));
student.setStudent_name((text3.getText()));
student.setStudent_sex((text4.getText()));
student.setStudent_age(Integer.parseInt(text5.getText()));
student.setStudent_adress((text6.getText()));
student.setStudent_tel(Integer.parseInt(text7.getText()));
int count=studentServiceImpl.updateinfor(student);
if (count > 0) {
JOptionPane.showMessageDialog(null, "成绩修改成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
// 重新获取全部学生列表
text1.setText("");
text2.setText("");
text3.setText("");
text4.setText("");
text5.setText("");
text6.setText("");
text7.setText("");
update();
// 填充数据
} else {
System.out.print(count);
JOptionPane.showMessageDialog(null, "成绩修改失败!", "警告", JOptionPane.WARNING_MESSAGE);
}
}
});
//设计刷新按钮事件
brefresh.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
//设计退出按钮事件
bexit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
}
public void update(){
String id=Application.id+"";
student=studentServiceImpl.findinforById(id);
text1.setText(student.getStudent_id()+"");
text2.setText(student.getClass_id()+"");
text3.setText(student.getStudent_name()+"");
text4.setText(student.getStudent_sex()+"");
text5.setText(student.getStudent_age()+"");
text6.setText(student.getStudent_adress()+"");
text7.setText(student.getStudent_tel()+"");
}
}
|
package alg;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Scanner;
/**
* Generates a list of tests to be run.
* @author Angel A. Juan - ajuanp(@)gmail.com
* @version 130807
*/
public class TestsManager
{
public static ArrayList<Test> getTestsList(String testsFilePath)
{ ArrayList<Test> list = new ArrayList<Test>();
try
{ FileReader reader = new FileReader(testsFilePath);
Scanner in = new Scanner(reader);
// The two first lines (lines 0 and 1) of this file are like this:
//# instance | maxRouteCosts | serviceCosts | maxTime(sec) | ...
// A-n32-k5 10000000 0 120 ...
in.useLocale(Locale.US);
while( in.hasNextLine() )
{ String s = in.next();
if (s.charAt(0) == '#') // this is a comment line
in.nextLine(); // skip comment lines
else
{ String instanceName = s; // e.g.: A-n32-k5
float maxRouteCosts = in.nextFloat(); // maxCosts in any route
float serviceCosts = in.nextFloat(); // marginal costs per service
float maxTime = in.nextFloat(); // max computational time (in sec)
String distrib = in.next(); // statistical distribution
float beta1 = in.nextFloat(); // distribution parameter
float beta2 = in.nextFloat(); // distribution parameter
int seed = in.nextInt(); // seed for the RNG
float k = in.nextFloat(); // Var[Di] = k * E[Di]
float lambda = in.nextFloat(); // lambda for the inventory costs function
float irpbias = in.nextFloat();
int nPeriod = in.nextInt();
int approach = in.nextInt();
int simPerPeriod = in.nextInt();
Test aTest = new Test(instanceName, maxRouteCosts, serviceCosts,
maxTime, distrib, beta1, beta2, seed, k, lambda, irpbias, nPeriod, approach, simPerPeriod);
list.add(aTest);
}
}
in.close();
}
catch (IOException exception)
{ System.out.println("Error processing tests file: " + exception);
}
return list;
}
}
|
package com.rsm.yuri.projecttaxilivredriver.chat;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.rsm.yuri.projecttaxilivredriver.chat.entities.ChatMessage;
import com.rsm.yuri.projecttaxilivredriver.chat.events.ChatEvent;
import com.rsm.yuri.projecttaxilivredriver.domain.FirebaseAPI;
import com.rsm.yuri.projecttaxilivredriver.domain.FirebaseEventListenerCallback;
import com.rsm.yuri.projecttaxilivredriver.lib.base.EventBus;
/**
* Created by yuri_ on 13/01/2018.
*/
public class ChatRepositoryImpl implements ChatRepository {
private FirebaseAPI firebase;
private EventBus eventBus;
private String receiver;
public ChatRepositoryImpl(FirebaseAPI firebase, EventBus eventBus) {
this.firebase = firebase;
this.eventBus = eventBus;
}
@Override
public void sendMessage(String msg) {
String keySender = firebase.getAuthUserEmail().replace(".","_");
ChatMessage chatMessage = new ChatMessage(keySender, msg, false);
String newChatMessageId = firebase.createChatMessageId(receiver);
chatMessage.setId(newChatMessageId);
DatabaseReference chatsReference = firebase.getChatsReference(receiver);
//chatsReference.push().setValue(chatMessage);
chatsReference.child(chatMessage.getId()).setValue(chatMessage);
}
@Override
public void setReceiver(String receiver) {
this.receiver = receiver;
}
@Override
public void destroyChatListener() {
firebase.destroyChatListener();
}
@Override
public void subscribeForChatUpates() {
//Log.d("d", "subscriveForChatupdates receiver = " + receiver);
firebase.subscribeForChatUpdates(receiver, new FirebaseEventListenerCallback(){
@Override
public void onChildAdded(DataSnapshot dataSnapshot) {
ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
String msgSender = chatMessage.getSender();
msgSender = msgSender.replace("_",".");
String currentUserEmail = firebase.getAuthUserEmail();
chatMessage.setSentByMe(msgSender.equals(currentUserEmail));
if(!chatMessage.isRead() && !chatMessage.isSentByMe())
firebase.setMessageChatRead(receiver, chatMessage.getId());
post(ChatEvent.READ_EVENT, chatMessage);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError error) {
post(ChatEvent.ERROR_EVENT, error.getMessage());
}
});
}
@Override
public void unSubscribeForChatUpates() {
firebase.unSubscribeForChatUpdates(receiver);
}
@Override
public void subscribeForStatusReceiverUpdate() {
firebase.subscribeForStatusReceiverUpdate(receiver, new FirebaseEventListenerCallback(){
@Override
public void onChildAdded(DataSnapshot dataSnapshot) {
/*long status = (long) dataSnapshot.getValue();
Log.d("d", "subscribeForStatusReceiverUpdates onchildAdded status((long) dataSnapshot.getValue()) = " + status);
post(ChatEvent.READ_STATUS_RECEIVER_EVENT, status);*/
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot) {
long status = (long) dataSnapshot.getValue();
Log.d("d", "subscribeForStatusReceiverUpdates onchildChanged status((long) dataSnapshot.getValue()) = " + status);
post(ChatEvent.READ_STATUS_RECEIVER_EVENT, status);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(DatabaseError error) {
post(ChatEvent.ERROR_EVENT, error.getMessage());
}
});
}
@Override
public void unSubscribeForStatusReceiverUpdate() {
firebase.unSubscribeForStatusReceiverUpdate(receiver);
}
@Override
public void changeUserConnectionStatus(long status) {
firebase.changeUserConnectionStatus(status);
}
private void post(int type, ChatMessage message){
post(type, message, 0, null);
}
private void post(int type, long status){
post(type, null, status, null);
}
private void post(int type, String error){
post(type, null, 0,error);
}
private void post(int type, ChatMessage message, long status, String error){
ChatEvent chatEvent = new ChatEvent();
chatEvent.setMsg(message);
chatEvent.setStatusReceiver(status);
chatEvent.setEventType(type);
chatEvent.setError(error);
eventBus.post(chatEvent);
}
}
|
package com.example.healthmanage.ui.activity.healthreport.ui;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;
import com.aries.ui.widget.alert.UIAlertDialog;
import com.example.healthmanage.BR;
import com.example.healthmanage.R;
import com.example.healthmanage.base.BaseActivity;
import com.example.healthmanage.base.BaseApplication;
import com.example.healthmanage.databinding.ActivityCreateHealthReportBinding;
import com.example.healthmanage.ui.activity.healthreport.HealthReportInfo;
import com.example.healthmanage.ui.activity.healthreport.viewmodel.HealthReportViewModel;
import com.example.healthmanage.utils.SizeUtil;
import com.example.healthmanage.utils.ToastUtil;
import com.example.healthmanage.utils.ToolUtil;
import com.example.healthmanage.widget.TitleToolBar;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* 创建健康报告
*/
public class CreateHealthReportActivity extends BaseActivity<ActivityCreateHealthReportBinding, HealthReportViewModel> implements
TitleToolBar.OnTitleIconClickCallBack, View.OnClickListener,CalendarView.OnCalendarInterceptListener,
CalendarView.OnCalendarRangeSelectListener,
CalendarView.OnMonthChangeListener{
private TitleToolBar titleToolBar = new TitleToolBar();
PopupWindow popupWindow;
private CalendarView mCalendarView;
private TextView dialogTitle;
private List<Calendar> calendars;
private String startDate,endDate;
private HealthReportInfo healthReportInfo;
private int userId;
private int startYear,startMonth,startDay;
@Override
public void onClick(View v) {
}
@Override
protected void initData() {
titleToolBar.setTitle("健康报告");
titleToolBar.setLeftIconVisible(true);
titleToolBar.setTitleColor(getResources().getColor(R.color.colorBlack));
dataBinding.layoutTitle.toolbarTitle.setBackgroundColor(getResources().getColor(R.color.white));
titleToolBar.setBackIconSrc(R.drawable.back_black);
viewModel.setTitleToolBar(titleToolBar);
healthReportInfo = new HealthReportInfo();
userId = getIntent().getIntExtra("userId",0);
if (userId==0){
return;
}else {
healthReportInfo.setUserId(userId);
}
InputFilter.LengthFilter filter = new InputFilter.LengthFilter(100){
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if ((dest.length() - (dend - dstart)) >= 100) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
Toast.makeText(CreateHealthReportActivity.this, "最大限制字数100", Toast.LENGTH_SHORT).show();
}
return super.filter(source, start, end, dest, dstart, dend);
}
};
dataBinding.edtHintBloodPressure.setFilters(new InputFilter[]{filter});
dataBinding.edtHintBloodSugar.setFilters(new InputFilter[]{filter});
dataBinding.edtHintBloodOxygen.setFilters(new InputFilter[]{filter});
dataBinding.edtHintTemperature.setFilters(new InputFilter[]{filter});
dataBinding.edtHintSportStatus.setFilters(new InputFilter[]{filter});
dataBinding.edtHintSleepStatus.setFilters(new InputFilter[]{filter});
}
@Override
protected void registerUIChangeEventObserver() {
super.registerUIChangeEventObserver();
dataBinding.tvReportTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initPopupWindow();
}
});
dataBinding.btnConfirmHealthReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TextUtils.isEmpty(viewModel.bloodPressure.getValue())||TextUtils.isEmpty(viewModel.bloodSugar.getValue())||TextUtils.isEmpty(viewModel.bloodOxygen.getValue())
||TextUtils.isEmpty(viewModel.temprature.getValue())||TextUtils.isEmpty(viewModel.sportStatus.getValue())||TextUtils.isEmpty(viewModel.sleepStatus.getValue())
||TextUtils.isEmpty(viewModel.reportName.getValue())||TextUtils.isEmpty(viewModel.reportTime.getValue())){
ToastUtil.showShort("请将未填写的资料补全");
return;
}else {
healthReportInfo.setToken(BaseApplication.getToken());
healthReportInfo.setBloodPressure(viewModel.bloodPressure.getValue());
healthReportInfo.setBloodSugar(viewModel.bloodSugar.getValue());
healthReportInfo.setBloodOxygen(viewModel.bloodOxygen.getValue());
healthReportInfo.setName(viewModel.reportName.getValue());
healthReportInfo.setTemperature(viewModel.temprature.getValue());
healthReportInfo.setSport(viewModel.sportStatus.getValue());
healthReportInfo.setSleep(viewModel.sleepStatus.getValue());
healthReportInfo.setStartTime(startDate);
healthReportInfo.setEndTime(endDate);
viewModel.saveHealthReport(healthReportInfo);
}
}
});
viewModel.saveSuccess.observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean){
new UIAlertDialog.DividerIOSBuilder(CreateHealthReportActivity.this).setMessage("健康报告发送成功")
.setMessageTextColorResource(R.color.colorBlack)
.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.putExtra("year",startYear);
intent.putExtra("month",startMonth);
setResult(RESULT_OK,intent);
finish();
// startActivity(HealthReportActivity.class);
// finish();
}
})
.setMinHeight(SizeUtil.dp2px(160))
.setPositiveButtonTextColorResource(R.color.colorTxtBlue)
.create()
.setDimAmount(0.6f)
.show();
}else {
return;
}
}
});
}
private void initPopupWindow(){
View view = LayoutInflater.from(this).inflate(R.layout.dialog_choose_calendarview, null, false);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
popupWindow.setAnimationStyle(R.style.Animation);
popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
//设置popupWindow显示的位置,参数依次是参照View,x轴的偏移量,y轴的偏移量
popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0,
ToolUtil.getNavigationBarHeight(this));
popupWindow.setFocusable(true);
bgAlpha(0.5f);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
bgAlpha(1);
}
});
Calendar calendar = new Calendar();
mCalendarView = view.findViewById(R.id.calendarView);
dialogTitle = view.findViewById(R.id.tv_date_title);
mCalendarView.setFixMode();
dialogTitle.setText(calendar.getYear()+"年"+calendar.getMonth()+"月");
mCalendarView.setOnCalendarRangeSelectListener(this);
mCalendarView.setOnMonthChangeListener(this);
//设置日期拦截事件,当前有效
mCalendarView.setOnCalendarInterceptListener(this);
mCalendarView.setRange(2000, 1, 1,
2999, 12, 31
);
mCalendarView.post(new Runnable() {
@Override
public void run() {
mCalendarView.scrollToCurrent();
}
});
Button btnConfirm = view.findViewById(R.id.btn_confirm_date);
btnConfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
calendars = mCalendarView.getSelectCalendarRange();
if (mCalendarView.getSelectedCalendar()!=null && calendars.size()==0){
viewModel.reportTime.postValue(mCalendarView.getSelectedCalendar().getMonth()+"-"+mCalendarView.getSelectedCalendar().getDay()+"~"+mCalendarView.getSelectedCalendar().getMonth()+"-"+mCalendarView.getSelectedCalendar().getDay());
startYear = mCalendarView.getSelectedCalendar().getYear();
startMonth = mCalendarView.getSelectedCalendar().getMonth();
startDay = mCalendarView.getSelectedCalendar().getDay();
startDate = startYear +"-"+startMonth+"-"+startDay;
endDate = mCalendarView.getSelectedCalendar().getYear()+"-"+mCalendarView.getSelectedCalendar().getMonth()+"-"+mCalendarView.getSelectedCalendar().getDay();
}else {
if (calendars == null || calendars.size() == 0) {
return;
}
viewModel.reportTime.postValue(calendars.get(0).getMonth()+"-"+calendars.get(0).getDay()+"~"+calendars.get(calendars.size() - 1).getMonth()+"-"+calendars.get(calendars.size() - 1).getDay());
startYear = calendars.get(0).getYear();
startMonth = calendars.get(0).getMonth();
startDay = calendars.get(0).getDay();
startDate = startYear +"-"+startMonth+"-"+startDay;
endDate = calendars.get(calendars.size()-1).getYear()+"-"+calendars.get(calendars.size()-1).getMonth()+"-"+calendars.get(calendars.size()-1).getDay();
}
popupWindow.dismiss();
}
});
}
@Override
protected int initVariableId() {
return BR.ViewModel;
}
@Override
protected int setContentViewSrc(Bundle savedInstanceState) {
return R.layout.activity_create_health_report;
}
@Override
public void initViewListener() {
super.initViewListener();
titleToolBar.setOnClickCallBack(this);
}
@Override
public void onRightIconClick() {
}
@Override
public void onBackIconClick() {
finish();
}
private void bgAlpha(float bgAlpha) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = bgAlpha; //0.0-1.0
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getWindow().setAttributes(lp);
}
@Override
public boolean onCalendarIntercept(Calendar calendar) {
return false;
}
@Override
public void onCalendarInterceptClick(Calendar calendar, boolean isClick) {
}
@Override
public void onCalendarSelectOutOfRange(Calendar calendar) {
}
@Override
public void onSelectOutOfRange(Calendar calendar, boolean isOutOfMinRange) {
Toast.makeText(this,
calendar.toString() + (isOutOfMinRange ? "小于最小选择范围" : "超过最大选择范围"),
Toast.LENGTH_SHORT).show();
}
@Override
public void onCalendarRangeSelect(Calendar calendar, boolean isEnd) {
}
@Override
public void onMonthChange(int year, int month) {
dialogTitle.setText(year+"年"+month+"月");
}
}
|
package com.example.autowiredemo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationDemoApp {
public static void main(String[] args) {
// read spring config file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContextAutoWire.xml");
// --- 1. AutoWire on Constructor
// Coach theCoach = context.getBean("thatSillyCoach", Coach.class);
Coach theCoach = context.getBean("tennisCoach", Coach.class);
System.out.println(theCoach.getDailyWorkout());
System.out.println(theCoach.getDailyFortune());
// --- 2. AutoWire on Setter/Method
Coach basketballCoach = context.getBean("basketballCoach", Coach.class);
System.out.println(basketballCoach.getDailyWorkout());
System.out.println(basketballCoach.getDailyFortune());
// --- 2. AutoWire on Fields / Property file
SwimmingCoach swimmingCoach = context.getBean("swimmingCoach", SwimmingCoach.class);
System.out.println(swimmingCoach.getDailyWorkout());
System.out.println(swimmingCoach.getDailyFortune());
System.out.println(swimmingCoach.getValuesFromPropertyFile());
context.close();
}
}
|
package com.funlib.http.download;
/**
* 下载状态
* @author feng
*
*/
public class DownloadStatus {
public static final int STATUS_STORAGE_FULL = 0; // 没有足够的存储空间
public static final int STATUS_NO_SDCARD = 1; // 没有插入SD卡
public static final int STATUS_PAUSE = 2; // 暂停
public static final int STATUS_DOWNLOADING = 3; // 正在下载
public static final int STATUS_WAITTING = 4; // 等待下载
public static final int STATUS_COMPLETE = 5; // 下载完成
public static final int STATUS_UNKNOWN = 6; // 未知错误
public static final int STATUS_CANCELED = 7; // 取消下载任务
public static final int STATUS_NOT_EXISTS = 8; // 下载任务不存在,可以添加下载
public static final int STATUS_DOWNLOAD_FILE_NOT_FOUND = 9; // 文件不存在
public static final int STATUS_STARTDOWNLOADING = 10; // 将要开始下载
public static final int STATUS_NETERROR = 11; // 将要开始下载
}
|
package db;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ksenia on 11.12.2016.
*/
public class MySQLdb {
private static final String LOGIN_NAME = "Ksenia00";
private static final String DOMAIN = "@tut.by";
private static final String PASSWORD = "AutomationTest";
private static Connection connection;
private static Statement statement;
private static List<String[]> accounts;
public static void createMySQLdb() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/accounts?autoReconnect=true&useSSL=false", "root", "root");
statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE users(id int(3)AUTO_INCREMENT, email VARCHAR(50)NOT NULL, password VARCHAR(20)NOT NULL, PRIMARY KEY(id))");
for (int i = 1; i < 11; i++) {
String login = LOGIN_NAME + i + DOMAIN;
String password = PASSWORD + i;
statement.executeUpdate("INSERT INTO users (email, password) VALUES ('" + login + "','" + password + "')");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String[] readMySQLdb(int account) {
try {
accounts = new ArrayList<String[]>();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/accounts?autoReconnect=true&useSSL=false", "root", "root");
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
int i = 0;
while (resultSet.next()) {
accounts.add(new String[2]);
accounts.get(i)[0] = resultSet.getString(2);
accounts.get(i)[1] = resultSet.getString(3);
i++;
}
} catch (SQLException e) {
e.printStackTrace();
}
return accounts.get(account);
}
public static String getLogin(int acc) {
String[] accData = readMySQLdb(acc-1);
return accData[0];
}
public static String getPassword(int acc) {
String[] accData = readMySQLdb(acc-1);
return accData[1];
}
}
|
package com.cloudogu.smeagol.wiki.domain;
import com.google.common.base.Preconditions;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* Email address value object.
*/
public final class Email {
private static final Pattern EMAIL_PATTERN = Pattern.compile(
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
);
private String value;
private Email(String value) {
this.value = value;
}
/**
* Returns the string representation of the email.
*
* @return string representation
*/
public String getValue() {
return value;
}
/**
* Creates a email from a string.
*
* @param value string representation of email
*
* @return repository name
*/
public static Email valueOf(String value) {
Preconditions.checkArgument(EMAIL_PATTERN.matcher(value).matches(), "%s is not a valid email", value);
return new Email(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Email that = (Email) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return value;
}
}
|
package com.tencent.mm.plugin.appbrand.game;
import android.content.SharedPreferences;
import com.tencent.mm.ipcinvoker.wx_extension.a.a;
import com.tencent.mm.plugin.appbrand.g.b;
import com.tencent.mm.plugin.appbrand.g.f;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.c;
public final class l {
final d fAr;
private final a fAs;
private final f fAt;
private volatile Boolean fAu = null;
l(d dVar, b bVar) {
this.fAr = dVar;
this.fAt = (f) bVar.y(f.class);
this.fAs = new a(this, this.fAr, this.fAt);
}
public final boolean agn() {
if (this.fAu == null) {
boolean z;
long VG = bi.VG();
SharedPreferences chZ = ad.chZ();
int i = chZ != null ? chZ.getInt("useisolatectxwxalibrary", 0) : 0;
if (i == 1) {
z = true;
} else {
if (i != -1) {
a aVar = a.b.dnp;
c fJ = a.fJ("100378");
if (fJ == null || !fJ.isValid()) {
z = false;
} else if (bi.getInt((String) fJ.ckq().get("useisolatectxwxalibrary"), 0) == 1) {
z = true;
}
}
z = false;
}
this.fAu = Boolean.valueOf(z);
x.i("MicroMsg.WAGameWeixinJSContextLogic", "read ShouldUseIsolateCtxWxaLibrary cost time = [%d], mShouldAllowIsolateCtx: [%b]", new Object[]{Long.valueOf(bi.bI(VG)), this.fAu});
}
return this.fAu.booleanValue();
}
public final void ago() {
if (this.fAt == null) {
x.e("MicroMsg.WAGameWeixinJSContextLogic", "injectWeixinJSContextLogic error. not support SubContextAddon.");
return;
}
com.tencent.mm.plugin.appbrand.g.a agg = this.fAt.agg();
if (agg == null || !agg.afV()) {
x.e("MicroMsg.WAGameWeixinJSContextLogic", "bindMainJSContext Main Context is [" + agg + "]");
return;
}
agg.addJavascriptInterface(this.fAs, "WeixinJSContext");
this.fAs.aad();
}
}
|
package ru.bm.eetp.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class IncomingSignatureExtractorImpl implements IncomingSignatureExtractor {
@Autowired
private TagExtractor tagExtractor;
@Override
public Optional<String> extract(String content) {
/* <Signature> ...</Signature>*/
return tagExtractor.extract("Signature", content);
}
}
|
package com.huanuo.npo.service;
import com.huanuo.npo.Config.Car;
import com.huanuo.npo.Dao.PeopleDao;
import com.huanuo.npo.pojo.People;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PeopleServiceTest {
@Autowired
PeopleDao peopleDao;
@Autowired
Car car;
public List<People> get(){
car.Run();
return peopleDao.get();
}
public List post(String name,int age){
People peopleTest=new People();
peopleTest.setName(name);
peopleTest.setAge(age);
return peopleDao.post(peopleTest);
}
public List delete(String name){
People peopleTest=new People();
peopleTest.setName(name);
return peopleDao.delete(peopleTest);
}
}
|
package com.tencent.mm.plugin.offline.ui;
import android.text.TextUtils;
import android.view.MenuItem;
import com.tencent.mm.plugin.offline.c.a;
import com.tencent.mm.plugin.offline.k;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.wallet_core.model.Bankcard;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.base.n.d;
import java.util.List;
class WalletOfflineCoinPurseUI$29 implements d {
final /* synthetic */ com.tencent.mm.ui.widget.a.d eRB;
final /* synthetic */ List kkU;
final /* synthetic */ WalletOfflineCoinPurseUI lMe;
WalletOfflineCoinPurseUI$29(WalletOfflineCoinPurseUI walletOfflineCoinPurseUI, com.tencent.mm.ui.widget.a.d dVar, List list) {
this.lMe = walletOfflineCoinPurseUI;
this.eRB = dVar;
this.kkU = list;
}
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
if (this.eRB != null) {
this.eRB.bzW();
Bankcard bankcard = (Bankcard) this.kkU.get(i);
h.mEJ.h(14515, new Object[]{Integer.valueOf(3)});
if (!(bi.oW(bankcard.field_forbid_title) && bi.oW(bankcard.field_forbidWord) && bankcard.field_support_micropay)) {
h.mEJ.h(14515, new Object[]{Integer.valueOf(4)});
}
String str = bankcard.field_bindSerial;
if (!TextUtils.isEmpty(str) && !str.equals(WalletOfflineCoinPurseUI.D(this.lMe))) {
WalletOfflineCoinPurseUI.a(this.lMe, str);
a.Ja(WalletOfflineCoinPurseUI.D(this.lMe));
k.bkO();
k.bkQ().lIF = WalletOfflineCoinPurseUI.D(this.lMe);
this.lMe.blo();
WalletOfflineCoinPurseUI.E(this.lMe);
WalletOfflineCoinPurseUI.F(this.lMe);
}
}
}
}
|
package com.santander.bi.DAO;
import java.util.List;
import com.santander.bi.model.Area;
public interface AreaDAO {
Area get(int id);
List<Area> getAll();
Area save(Area t);
Area update(Area t);
Area delete(int id);
Area delete(Area p);
void close();
}
|
package mainApp;
import javafx.stage.Window;
public class StageController {
private double width,height,horp,verp;
StageController(Window window){
height = window.getHeight();
width = window.getWidth();
horp = window.getX();
verp = window.getY();
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public double getHorp() {
return horp;
}
public double getVerp() {
return verp;
}
}
|
package DAO;
import java.util.*;
import Bean.Emp;
import java.sql.*;
public class HomeDAO {
public static List<Emp> DisplayEmp(int start, int count , Connection conn){
List<Emp> list = new ArrayList<Emp>();
String sql = "SELECT * FROM emp LIMIT "+ (start-1) +", " +count+ "";
try {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
Emp emp = new Emp();
int id = rs.getInt("id");
String name = rs.getString("name");
float salary = rs.getFloat("salary");
emp.setId(id);
emp.setName(name);
emp.setSalary(salary);
int id1 = emp.getId();
String name1 = emp.getName();
float salary1 = emp.getSalary();
list.add(emp);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
|
package pl.czyzycki.towerdef.gameplay;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.input.GestureDetector;
/**
* Klasa odpowiedzialna za obsługę prostych zdarzeń inputu. Propaguje informacje do GameplayGestureListenera.
*
*/
class GameplayGestureDetector extends GestureDetector {
final GameplayScreen screen;
GameplayGestureDetector(GameplayScreen screen) {
super(20, 0.4f, 1.5f, 0.15f, new GameplayGestureListener(screen));
this.screen = screen;
}
@Override
public boolean keyDown(int keycode) {
if(keycode == Keys.Q) screen.debug.base = !screen.debug.base;
else if(keycode == Keys.W) screen.debug.spawns = !screen.debug.spawns;
else if(keycode == Keys.E) screen.debug.enemies = !screen.debug.enemies;
else if(keycode == Keys.R) screen.debug.towers = !screen.debug.towers;
else if(keycode == Keys.T) screen.debug.bullets = !screen.debug.bullets;
else if(keycode == Keys.Y) screen.debug.camera = !screen.debug.camera;
else if(keycode >= Keys.NUM_1 && keycode <= Keys.NUM_9) {
screen.gui.selectedTowerType = screen.gui.modelTowers.get(keycode - Keys.NUM_1);
} else if(keycode == Keys.NUM_0) {
screen.gui.selectedTowerType = screen.gui.modelTowers.get(9);
}
return super.keyDown(keycode);
}
}
|
/*
* 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 ServiceLiberT;
import LiberT.GestionMethodesServiceIteneraire;
import LiberT.Iteneraire;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* @author Vitor
*/
@Path("int")
public class ServiceInteneraire {
@Context
private UriInfo context;
List<Iteneraire> liste = new ArrayList<Iteneraire>();
/**
* Creates a new instance of ServiceInteneraire
*/
public ServiceInteneraire() {
}
public List<Iteneraire> ObtenirLaListeDIteneraires()
{
return liste;
}
public void DefinirLaListeDIteneraires(List<Iteneraire> list)
{
this.liste = list;
}
//Les Méthodes
public boolean AjouterNouveauIteneraire(Iteneraire route)
{
boolean returnResult = false;
if(route != null)
{
liste.add(route);
returnResult = true;
}
return returnResult;
}
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/tousiteneraires/{ae}")
public GestionMethodesServiceIteneraire RechercherEtAjouterTousItenerairesPourId(@PathParam ("ae") int idListe)
{
GestionMethodesServiceIteneraire gmsi = new GestionMethodesServiceIteneraire();
String ae, partiPeage, arrivePeage;
Iteneraire route = new Iteneraire();
boolean returnResultat = false;
Connection con; Statement st; ResultSet rs;
int beginingTableFieldNumber;
String driver, url, username, password;
String sqlQuery;
driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
url = "jdbc:sqlserver://DESKTOP-VUQIPI7;databaseName=vinci-autoroutepeage";
username = "sa";
password = "zauwitch";
//1 - Rechercher dans la base de donées
//2 - Ajouter chaque iteneraire à la liste iteneraires
try
{
beginingTableFieldNumber = 1; // Ne pas regarder et ajouter le clavier primaire de la table
Class.forName(driver);
con = DriverManager.getConnection(url,username,password);
st=con.createStatement();
con.commit();
//le query sql
sqlQuery = "Select * FROM dbo.itenerario";
rs = st.executeQuery(sqlQuery);
while (rs.next())
{
ae = rs.getString(beginingTableFieldNumber+1);
partiPeage = rs.getString(beginingTableFieldNumber+2);
arrivePeage = rs.getString(beginingTableFieldNumber+3);
//valider
if(route.ValiderAutoRoute(ae)==true&&route.ValierLieuPartiEtSorti(partiPeage)==true&&route.ValierLieuPartiEtSorti(arrivePeage)==true)
{
boolean giveResult = true;
route.DefinirAutoRoute(ae, giveResult);
route.DefinirLieuParti(partiPeage, giveResult);
route.DefinirLieuDArrive(arrivePeage, giveResult);
}
//Ajouter cette route a la liste
liste.add(route);
}
returnResultat=true;
//Ajouter la liste a l'objet GestionMethodesServiceIteneraire
gmsi.DefinirTousIteneraires(liste);
gmsi.DefinirMethodEtat(returnResultat); // nous avons tous l'iteneraires... cette operation marche très bien!
}
catch(SQLException ex)
{
String msg;
msg = ex.getMessage();
gmsi.DefinirMethodEtat(returnResultat); // nous avons tous l'iteneraires... cette operation marche très bien!
//Si nous
}
catch (Exception ex)
{
String msg;
msg = ex.getMessage();
gmsi.DefinirMethodEtat(returnResultat); // nous avons tous l'iteneraires... cette operation marche très bien!
//Si nous
}
return gmsi;
}
/**
* Retrieves representation of an instance of ServiceLiberT.ServiceInteneraire
* @return an instance of java.lang.String
*/
@GET
@Produces(MediaType.APPLICATION_XML)
public String getXml() {
//TODO return proper representation object
throw new UnsupportedOperationException();
}
/**
* PUT method for updating or creating an instance of ServiceInteneraire
* @param content representation for the resource
*/
@PUT
@Consumes(MediaType.APPLICATION_XML)
public void putXml(String content) {
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.examples.ntp;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.time.Duration;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.NtpUtils;
import org.apache.commons.net.ntp.NtpV3Packet;
import org.apache.commons.net.ntp.TimeInfo;
import org.apache.commons.net.ntp.TimeStamp;
/**
* This is an example program demonstrating how to use the NTPUDPClient class. This program sends a Datagram client request packet to a Network time Protocol
* (NTP) service port on a specified server, retrieves the time, and prints it to standard output along with the fields from the NTP message header (e.g.
* stratum level, reference id, poll interval, root delay, mode, ...) See <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc868.txt"> the spec </A> for details.
* <p>
* Usage: NTPClient <hostname-or-address-list>
* </p>
* <p>
* Example: NTPClient clock.psu.edu
* </p>
*/
public final class NTPClient {
private static final NumberFormat numberFormat = new java.text.DecimalFormat("0.00");
public static void main(final String[] args) {
if (args.length == 0) {
System.err.println("Usage: NTPClient <hostname-or-address-list>");
System.exit(1);
}
final NTPUDPClient client = new NTPUDPClient();
// We want to timeout if a response takes longer than 10 seconds
client.setDefaultTimeout(Duration.ofSeconds(10));
try {
client.open();
for (final String arg : args) {
System.out.println();
try {
final InetAddress hostAddr = InetAddress.getByName(arg);
System.out.println("> " + hostAddr.getHostName() + "/" + hostAddr.getHostAddress());
final TimeInfo info = client.getTime(hostAddr);
processResponse(info);
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
} catch (final SocketException e) {
e.printStackTrace();
}
client.close();
}
/**
* Process <code>TimeInfo</code> object and print its details.
*
* @param info <code>TimeInfo</code> object.
*/
public static void processResponse(final TimeInfo info) {
final NtpV3Packet message = info.getMessage();
final int stratum = message.getStratum();
final String refType;
if (stratum <= 0) {
refType = "(Unspecified or Unavailable)";
} else if (stratum == 1) {
refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock, etc.
} else {
refType = "(Secondary Reference; e.g. via NTP or SNTP)";
}
// stratum should be 0..15...
System.out.println(" Stratum: " + stratum + " " + refType);
final int version = message.getVersion();
final int li = message.getLeapIndicator();
System.out.println(" leap=" + li + ", version=" + version + ", precision=" + message.getPrecision());
System.out.println(" mode: " + message.getModeName() + " (" + message.getMode() + ")");
final int poll = message.getPoll();
// poll value typically btwn MINPOLL (4) and MAXPOLL (14)
System.out.println(" poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")");
final double disp = message.getRootDispersionInMillisDouble();
System.out.println(" rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble()) + ", rootdispersion(ms): " + numberFormat.format(disp));
final int refId = message.getReferenceId();
String refAddr = NtpUtils.getHostAddress(refId);
String refName = null;
if (refId != 0) {
if (refAddr.equals("127.127.1.0")) {
refName = "LOCAL"; // This is the ref address for the Local Clock
} else if (stratum >= 2) {
// If reference id has 127.127 prefix then it uses its own reference clock
// defined in the form 127.127.clock-type.unit-num (e.g. 127.127.8.0 mode 5
// for GENERIC DCF77 AM; see refclock.htm from the NTP software distribution.
if (!refAddr.startsWith("127.127")) {
try {
final InetAddress addr = InetAddress.getByName(refAddr);
final String name = addr.getHostName();
if (name != null && !name.equals(refAddr)) {
refName = name;
}
} catch (final UnknownHostException e) {
// some stratum-2 servers sync to ref clock device but fudge stratum level higher... (e.g. 2)
// ref not valid host maybe it's a reference clock name?
// otherwise just show the ref IP address.
refName = NtpUtils.getReferenceClock(message);
}
}
} else if (version >= 3 && (stratum == 0 || stratum == 1)) {
refName = NtpUtils.getReferenceClock(message);
// refname usually have at least 3 characters (e.g. GPS, WWV, LCL, etc.)
}
// otherwise give up on naming the beast...
}
if (refName != null && refName.length() > 1) {
refAddr += " (" + refName + ")";
}
System.out.println(" Reference Identifier:\t" + refAddr);
final TimeStamp refNtpTime = message.getReferenceTimeStamp();
System.out.println(" Reference Timestamp:\t" + refNtpTime + " " + refNtpTime.toDateString());
// Originate Time is time request sent by client (t1)
final TimeStamp origNtpTime = message.getOriginateTimeStamp();
System.out.println(" Originate Timestamp:\t" + origNtpTime + " " + origNtpTime.toDateString());
final long destTimeMillis = info.getReturnTime();
// Receive Time is time request received by server (t2)
final TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
System.out.println(" Receive Timestamp:\t" + rcvNtpTime + " " + rcvNtpTime.toDateString());
// Transmit time is time reply sent by server (t3)
final TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
System.out.println(" Transmit Timestamp:\t" + xmitNtpTime + " " + xmitNtpTime.toDateString());
// Destination time is time reply received by client (t4)
final TimeStamp destNtpTime = TimeStamp.getNtpTime(destTimeMillis);
System.out.println(" Destination Timestamp:\t" + destNtpTime + " " + destNtpTime.toDateString());
info.computeDetails(); // compute offset/delay if not already done
final Long offsetMillis = info.getOffset();
final Long delayMillis = info.getDelay();
final String delay = delayMillis == null ? "N/A" : delayMillis.toString();
final String offset = offsetMillis == null ? "N/A" : offsetMillis.toString();
System.out.println(" Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset); // offset in ms
}
}
|
package patchworks.fragments;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import patchworks.R;
import patchworks.activities.ControllerActivity;
import patchworks.utils.Connection;
import patchworks.utils.ShakeDetector;
public class SlimeFragment extends Fragment {
private Connection connection;
private ImageButton leftButton;
private ImageButton rightButton;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retrieve established connection from activity
if (!ControllerActivity.controllerDebug) {
connection = ((ControllerActivity) getActivity()).getConnection();
connection.debug();
}
// ShakeDetector initialization
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();
mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {
@Override
public void onShake(int count) {
Log.d("SHAKE", "shakey shake");
if (!ControllerActivity.controllerDebug)
connection.sendMessage("shake");
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_slime, container, false);
ControllerActivity.backButton.setVisibility(View.VISIBLE);
leftButton = (ImageButton) view.findViewById(R.id.leftButton);
leftButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!ControllerActivity.controllerDebug)
connection.sendMessage("slime_left");
}
});
rightButton = (ImageButton) view.findViewById(R.id.rightButton);
rightButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!ControllerActivity.controllerDebug)
connection.sendMessage("slime_right");
}
});
return view;
}
@Override
public void onResume() {
super.onResume();
// Add the following line to register the Session Manager Listener onResume
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
@Override
public void onPause() {
// Add the following line to unregister the Sensor Manager onPause
mSensorManager.unregisterListener(mShakeDetector);
super.onPause();
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.StringTokenizer;
public class BOJ_10827_a제곱b {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
BigDecimal a = new BigDecimal(st.nextToken());
int b = Integer.parseInt(st.nextToken());
System.out.println(a.pow(b).toString());
}
}
|
package com.example.flutterplugingg;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.BatteryManager;
import android.os.Build;
import androidx.annotation.NonNull;
import java.util.logging.StreamHandler;
import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/** FlutterpluginggPlugin */
public class FlutterpluginggPlugin implements FlutterPlugin, MethodCallHandler {
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
final MethodChannel channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutterplugingg");
channel.setMethodCallHandler(new FlutterpluginggPlugin());
}
@Override
public void onDetachedFromEngine(FlutterPluginBinding flutterPluginBinding) {
}
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutterplugingg");
//this.context = registrar.context();
channel.setMethodCallHandler(new FlutterpluginggPlugin());
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
if(call.method.equals("getBatteryPercentage")){
Log.e("Testing","Hello!");
}
}
}
|
package anngo.android.anngo.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import anngo.android.anngo.utils.CustomToastMessage;
/**
* Created by Ian on 19/05/2015.
* Description: SQL LITE DATABASE FOR APPLICATION
*/
public class DatabaseHelper extends SQLiteOpenHelper {
// Set database properties
public static final String DATABASE_NAME = "AnnGoDatabase";
public static final int DATABASE_VERSION = 7;
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(SearchPreference.CREATE_STATEMENT);
} catch (SQLException e) {
CustomToastMessage.message(context, "" + e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + SearchPreference.TABLE_NAME);
try {
db.execSQL(SearchPreference.CREATE_STATEMENT);
} catch (SQLException e) {
CustomToastMessage.message(context, "" + e);
}
}
public void addPreference(SearchPreference searchPreference){//Adding a new search preference
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SearchPreference.COLUMN_AVAILABLE_IN_NEXT,searchPreference.getAvailabilityNextHours());
contentValues.put(SearchPreference.COLUMN_SEARCH_RADIUS,searchPreference.getSearchRadius());
contentValues.put(SearchPreference.COLUMN_WINDOWS,searchPreference.getWindowsOS());
contentValues.put(SearchPreference.COLUMN_MAC,searchPreference.getMacOS());
contentValues.put(SearchPreference.COLUMN_LINUX,searchPreference.getLinuxOS());
contentValues.put(SearchPreference.COLUMN_WEEKEND,searchPreference.getWeekend());
contentValues.put(SearchPreference.COLUMN_24HOURS, searchPreference.getTwentyFourHoursAccess());
//Inserting into database
db.insert(SearchPreference.TABLE_NAME, null, contentValues);
db.close();
}
public void updatePreference (SearchPreference searchPreference){//Updating a search preference
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(SearchPreference.COLUMN_AVAILABLE_IN_NEXT,searchPreference.getAvailabilityNextHours());
contentValues.put(SearchPreference.COLUMN_SEARCH_RADIUS,searchPreference.getSearchRadius());
contentValues.put(SearchPreference.COLUMN_WINDOWS,searchPreference.getWindowsOS());
contentValues.put(SearchPreference.COLUMN_MAC,searchPreference.getMacOS());
contentValues.put(SearchPreference.COLUMN_LINUX,searchPreference.getLinuxOS());
contentValues.put(SearchPreference.COLUMN_WEEKEND,searchPreference.getWeekend());
contentValues.put(SearchPreference.COLUMN_24HOURS,searchPreference.getTwentyFourHoursAccess());
//Where Clause - Get the search preference ID
String[] whereArgs={String.valueOf(searchPreference.getId())};
db.update(SearchPreference.TABLE_NAME,contentValues,SearchPreference.COLUMN_ID+" =? ",whereArgs);
db.close();
//Toast to let the user know that database has been updated
CustomToastMessage.message(context, "Preference Saved");
}
public SearchPreference getSearchPreference() {//Return SearchPreference Object
SearchPreference searchPreference = null;
SQLiteDatabase db = this.getReadableDatabase();
// Run select statement and access data via Cursor
Cursor cursor = db.rawQuery("SELECT * FROM " + SearchPreference.TABLE_NAME, null);
//If there is a data source
if(cursor.moveToFirst()) {
do {
//Creating
searchPreference = new SearchPreference(cursor.getInt(0),cursor.getInt(1), cursor.getInt(2), cursor.getInt(3), cursor.getInt(4), cursor.getInt(5), cursor.getInt(6), cursor.getInt(7));
}
//While the cursor can move to the next data source
while(cursor.moveToNext());
}
cursor.close();
// Return contents of table
return searchPreference;
}
}
|
package page;
public class Confirmation {
} // end class Confirmation
|
package com.tencent.xweb;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Build.VERSION;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.xwalk.core.XWalkEnvironment;
public final class a {
static boolean vzP = false;
static String vzQ = "";
static Map<String, String> vzR;
static Map<String, String> vzS;
static Map<String, String> vzT;
private static void init() {
if (!vzP) {
vzP = true;
SharedPreferences cIh = cIh();
String string = cIh.getString("setwebtype", WebView$d.WV_KIND_NONE.toString());
String string2 = cIh.getString("setjscore", com.tencent.xweb.g.a.vAc.toString());
a(adB(string), adB(string2), cIh.getString("cStrTAGConfigVer", ""), adB(cIh.getString("setfullscreenvideo", com.tencent.xweb.WebView.a.vAM.toString())));
}
}
public static String getAbstractInfo() {
init();
if ((vzR == null || vzR.size() == 0) && ((vzS == null || vzS.size() == 0) && (vzT == null || vzT.size() == 0))) {
return "";
}
return "configver : " + vzQ + "\n webtype : " + aD(vzR) + "\n jscore type :" + aD(vzS) + "\n fullscreenVideo :" + aD(vzT);
}
public static WebView$d adv(String str) {
init();
if (vzR == null || str == null) {
return WebView$d.WV_KIND_NONE;
}
return ady((String) vzR.get(str));
}
public static com.tencent.xweb.g.a adw(String str) {
init();
if (vzS == null || str == null) {
return com.tencent.xweb.g.a.vAc;
}
return adz((String) vzS.get(str));
}
public static com.tencent.xweb.WebView.a adx(String str) {
init();
if (vzT == null || str == null) {
return com.tencent.xweb.WebView.a.vAM;
}
return adA((String) vzT.get(str));
}
public static void a(com.tencent.xweb.c.a.a[] aVarArr, String str) {
init();
if (str != null) {
Map hashMap = new HashMap();
Map hashMap2 = new HashMap();
Map hashMap3 = new HashMap();
if (aVarArr == null || aVarArr.length == 0) {
b(hashMap, hashMap2, str, hashMap3);
return;
}
XWalkEnvironment.getAvailableVersion();
int i = VERSION.SDK_INT;
new StringBuilder().append(Build.BRAND).append(" ").append(Build.MODEL);
i = 0;
while (i < aVarArr.length) {
if (!(aVarArr[i] == null || !aVarArr[i].vCo.cID() || aVarArr[i].vCr == null || aVarArr[i].vCr.isEmpty() || aVarArr[i].vCq == null)) {
String[] split = aVarArr[i].vCr.split(",");
String trim;
if (aVarArr[i].vCp.equals("setwebtype")) {
for (String trim2 : split) {
trim2 = trim2.trim();
if (!(trim2 == null || trim2.isEmpty() || hashMap.containsKey(trim2))) {
hashMap.put(trim2, aVarArr[i].vCq);
}
}
} else if (aVarArr[i].vCp.equals("setjscore")) {
for (String trim22 : split) {
trim22 = trim22.trim();
if (!(trim22 == null || trim22.isEmpty() || hashMap2.containsKey(trim22))) {
hashMap2.put(trim22, aVarArr[i].vCq);
}
}
} else if (aVarArr[i].vCp.equals("setfullscreenvideo")) {
for (String trim222 : split) {
trim222 = trim222.trim();
if (!(trim222 == null || trim222.isEmpty() || hashMap3.containsKey(trim222))) {
hashMap3.put(trim222, aVarArr[i].vCq);
}
}
}
}
i++;
}
b(hashMap, hashMap2, str, hashMap3);
}
}
private static WebView$d ady(String str) {
if (str == null || str.isEmpty()) {
return WebView$d.WV_KIND_NONE;
}
WebView$d webView$d = WebView$d.WV_KIND_NONE;
try {
return WebView$d.valueOf(str);
} catch (Exception e) {
return webView$d;
}
}
private static com.tencent.xweb.g.a adz(String str) {
if (str == null || str.isEmpty()) {
return com.tencent.xweb.g.a.vAc;
}
com.tencent.xweb.g.a aVar = com.tencent.xweb.g.a.vAc;
try {
return com.tencent.xweb.g.a.valueOf(str);
} catch (Exception e) {
return aVar;
}
}
private static com.tencent.xweb.WebView.a adA(String str) {
if (str == null || str.isEmpty()) {
return com.tencent.xweb.WebView.a.vAM;
}
com.tencent.xweb.WebView.a aVar = com.tencent.xweb.WebView.a.vAM;
try {
return com.tencent.xweb.WebView.a.valueOf(str);
} catch (Exception e) {
return aVar;
}
}
private static String aD(Map<String, String> map) {
if (map == null) {
return "";
}
StringBuilder stringBuilder = new StringBuilder(128);
for (Entry entry : map.entrySet()) {
if (stringBuilder.length() != 0) {
stringBuilder.append(";");
}
stringBuilder.append((String) entry.getKey());
stringBuilder.append(":");
stringBuilder.append((String) entry.getValue());
}
return stringBuilder.toString();
}
private static Map<String, String> adB(String str) {
Map<String, String> hashMap = new HashMap();
if (!(str == null || str.isEmpty())) {
for (String str2 : str.split(";")) {
if (!(str2 == null || str2.isEmpty())) {
String[] split = str2.split(":");
if (!(split.length != 2 || split[0] == null || split[1] == null)) {
hashMap.put(split[0], split[1]);
}
}
}
}
return hashMap;
}
private static void a(Map<String, String> map, Map<String, String> map2, String str, Map<String, String> map3) {
vzR = map;
vzS = map2;
vzQ = str;
vzT = map3;
}
private static void b(Map<String, String> map, Map<String, String> map2, String str, Map<String, String> map3) {
a(map, map2, str, map3);
String aD = aD(vzR);
String aD2 = aD(vzS);
String aD3 = aD(vzT);
XWalkEnvironment.addXWalkInitializeLog("CommandCfg", "save cmds to : webtype = " + aD + "jstype = " + aD2 + "configver = " + vzQ + "strFullscreenVideoCmds = " + aD3);
Editor edit = cIh().edit();
edit.putString("setwebtype", aD);
edit.putString("setjscore", aD2);
edit.putString("cStrTAGConfigVer", vzQ);
edit.putString("setfullscreenvideo", aD3);
edit.commit();
}
private static SharedPreferences cIh() {
return XWalkEnvironment.getApplicationContext().getSharedPreferences("XWEB.CMDCFG", 0);
}
}
|
/*
* Copyright 2016 Johns Hopkins University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dataconservancy.cos.osf.client.support;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import java.util.Collections;
import java.util.List;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* Wraps an OkHttpClient providing getters and setters for Spring and any other frameworks that follow the JavaBean
* standard.
*
* @author Elliot Metsger (emetsger@jhu.edu)
*/
public class BeanAccessibleOkHttpClient extends OkHttpClient {
/**
* Returns an immutable list of interceptors on the client.
*
* @return immutable list of interceptors
* @see #interceptors
*/
public List<Interceptor> getInterceptors() {
return Collections.unmodifiableList(super.interceptors());
}
/**
* Sets the supplied interceptors on the client by copying the supplied list. Any existing interceptors are
* cleared.
*
* @param interceptors interceptors to set on the client
*/
public void setInterceptors(final List<Interceptor> interceptors) {
this.interceptors().clear();
for (Interceptor toAdd : interceptors) {
this.interceptors().add(toAdd);
}
}
/**
*
* @param timeoutMs
*/
public void setReadTimeout(final int timeoutMs) {
setReadTimeout(timeoutMs, MILLISECONDS);
}
/**
*
* @param timeoutMs
*/
public void setWriteTimeout(final int timeoutMs) {
setWriteTimeout(timeoutMs, MILLISECONDS);
}
/**
*
* @param timeoutMs
*/
public void setConnectTimeout(final int timeoutMs) {
setConnectTimeout(timeoutMs, MILLISECONDS);
}
}
|
package sevenkyu.rounduptofive;
class RoundUpToFive {
public int roundToNext5(int number) {
double divisor = (double) number / 5;
double roundedUpDivisor = Math.ceil(divisor);
return (int) (5 * roundedUpDivisor);
}
}
|
package com.example.lib.event;
/**
* @Author jacky.peng
* @Date 2021/3/18 4:08 PM
* @Version 1.0
*/
public class PageOnDestroyEvent extends PageEvent {
public PageOnDestroyEvent(String name, String id) {
super(name, id);
tag = "PageOnDestroyEvent";
}
}
|
package game.numbers;
import static org.lwjgl.opengl.GL11.*;
import java.util.Random;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import lib.game.*;
import math.geom.Point2i;
public class Numbers extends AbstractGame { //2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048
public static final int KEY_UP = Keyboard.KEY_UP;
public static final int KEY_DOWN = Keyboard.KEY_DOWN;
public static final int KEY_RIGHT = Keyboard.KEY_RIGHT;
public static final int KEY_LEFT = Keyboard.KEY_LEFT;
public static final int KEY_EXIT = Keyboard.KEY_ESCAPE;
Random rand = new Random();
int w = 4, h = 4;
int[][] grid = new int[w][h];
int numberTex;
public Numbers() throws LWJGLException {
super("2048 Clone", 600, 600);
start();
}
@Override
public void init() {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, width, height, 0.0, 1.0, -1.0);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glLoadIdentity();
numberTex = RenderUtils.loadTexture("res/Numbers.png", true);
addRandom();
addRandom();
for(int i=0; i<h; i++) {
for(int j=0; j<w; j++) {
System.out.print(get(j, i) + " ");
}
System.out.println();
}
}
public int get(int i, int j) {
if(i>=0 && i<w && j>=0 && j<h) return grid[i][j];
else return -1;
}
public void set(int i, int j, int num) {
if(i>=0 && i<w && j>=0 && j<h) grid[i][j] = num;
}
public void move(Dir dir) {
switch(dir) {
case UP:
for(int k=0; k<w; k++) {
for(int i=0; i<w; i++) {
for(int j=0; j<h; j++) {
if(get(i, j-1) == 0) {
set(i, j-1, get(i, j));
set(i, j, 0);
}
}
}
}
break;
case DOWN:
for(int k=0; k<w; k++) {
for(int i=0; i<w; i++) {
for(int j=h-2; j>=0; j--) {
if(get(i, j+1) == 0) {
set(i, j+1, get(i, j));
set(i, j, 0);
}
}
}
}
break;
case RIGHT:
for(int k=0; k<w; k++) {
for(int i=w-2; i>=0; i--) {
for(int j=0; j<h; j++) {
if(get(i+1, j) == 0) {
set(i+1, j, get(i, j));
set(i, j, 0);
}
}
}
}
break;
case LEFT:
for(int k=0; k<w; k++) {
for(int i=1; i<w; i++) {
for(int j=0; j<h; j++) {
if(get(i-1, j) == 0) {
set(i-1, j, get(i, j));
set(i, j, 0);
}
}
}
}
break;
}
}
public void combine(Dir dir) {
switch(dir) {
case UP:
for(int i=0; i<w; i++) {
for(int j=1; j<h; j++) {
if(get(i, j-1) == get(i, j)) {
set(i, j-1, 2*get(i, j));
set(i, j, 0);
continue;
}
}
}
break;
case DOWN:
for(int i=w-1; i>=0; i--) {
for(int j=h-2; j>=0; j--) {
if(get(i, j+1) == get(i, j)) {
set(i, j+1, 2*get(i, j));
set(i, j, 0);
continue;
}
}
}
break;
case RIGHT:
for(int i=w-2; i>=0; i--) {
for(int j=h-1; j>=0; j--) {
if(get(i+1, j) == get(i, j)) {
set(i+1, j, 2*get(i, j));
set(i, j, 0);
continue;
}
}
}
break;
case LEFT:
for(int i=1; i<w; i++) {
for(int j=0; j<h; j++) {
if(get(i-1, j) == get(i, j)) {
set(i-1, j, 2*get(i, j));
set(i, j, 0);
continue;
}
}
}
break;
}
}
public void moveUp() {
move(Dir.UP);
combine(Dir.UP);
move(Dir.UP);
addRandom();
}
public void moveDown() {
move(Dir.DOWN);
combine(Dir.DOWN);
move(Dir.DOWN);
addRandom();
}
public void moveRight() {
move(Dir.RIGHT);
combine(Dir.RIGHT);
move(Dir.RIGHT);
addRandom();
}
public void moveLeft() {
move(Dir.LEFT);
combine(Dir.LEFT);
move(Dir.LEFT);
addRandom();
}
public void addRandom() {
if(isFull()) return;
int numInsert = 2*(rand.nextInt(2)+1);
while(true) {
int x = rand.nextInt(w);
int y = rand.nextInt(h);
if(get(x, y) == 0) {set(x, y, numInsert); break;}
}
}
public boolean hasMoves() {
for(int i=0; i<w; i++) {
for(int j=0; j<h; j++) {
if(get(i, j) == 0) return true;
if(get(i+1, j) == get(i, j) || get(i+1, j) == 0) return true;
if(get(i, j+1) == get(i, j) || get(i, j+1) == 0) return true;
}
}
return false;
}
public boolean checkWin() {
for(int i=0; i<w; i++) {
for(int j=0; j<h; j++){
if(get(i, j) == 2048) return true;
}
}
return false;
}
public boolean isFull() {
for(int i=0; i<w; i++) {
for(int j=0; j<h; j++) {
if(get(i, j) == 0) return false;
}
}
return true;
}
@Override
public void update() {
if(checkWin()) {
System.out.println("You Won!");
stop();
}
if(!hasMoves()) {
System.out.println("Game Over");
stop();
}
}
@Override
public void render() {
RenderUtils.clearScreen();
int deltaw = width/w;
int deltah = height/h;
glBegin(GL_QUADS); {
for(int i=0; i<w; i++) {
for(int j=0; j<h; j++) {
if(get(i, j) == 0) continue;
glColor3f(0.5f, 0.5f, 0.5f);
switch(get(i, j)) {
case 2:
glColor3f(1.0f, 1.0f, 1.0f);
break;
case 4:
glColor3f(1.0f, 0.0f, 0.0f);
break;
case 8:
glColor3f(1.0f, 0.549f, 0.0f);
break;
case 16:
glColor3f(1.0f, 0.843f, 0.0f);
break;
case 32:
glColor3f(0.0f, 1.0f, 0.0f);
break;
case 64:
glColor3f(0.0f, 0.980f, 0.604f);
break;
case 128:
glColor3f(0.0f, 0.0f, 1.0f);
break;
case 256:
glColor3f(0.282f, 0.389f, 0.545f);
break;
case 512:
glColor3f(0.502f, 0.0f, 0.502f);
break;
case 1024:
glColor3f(0.729f, 0.333f, 0.827f);
break;
case 2048:
glColor3f(1.0f, 0.0f, 1.0f);
break;
}
// (log2(g[i][j])-1)/11: get fraction of 11 for tex coords
double texStart = (Math.log(get(i, j)) / Math.log(2.0) - 1.0) / 11.0;
// System.out.println(texStart*11);
double texDelta = 1.0/11.0;
glTexCoord2d(texStart+texDelta, 1.0); glVertex2i(i*deltaw+deltaw, j*deltah+deltah);
glTexCoord2d(texStart, 1.0); glVertex2i(i*deltaw, j*deltah+deltah);
glTexCoord2d(texStart, 0.0); glVertex2i(i*deltaw, j*deltah);
glTexCoord2d(texStart+texDelta, 0.0); glVertex2i(i*deltaw+deltaw, j*deltah);
}
}
} glEnd();
}
@Override
public void processInput() {
while(Keyboard.next()) {
if(Keyboard.getEventKeyState()) {
switch(Keyboard.getEventKey()) {
case KEY_UP:
moveUp();
break;
case KEY_DOWN:
moveDown();
break;
case KEY_RIGHT:
moveRight();
break;
case KEY_LEFT:
moveLeft();
break;
case KEY_EXIT:
kill();
break;
}
}
}
}
public static void main(String args[]) {
try {
new Numbers();
} catch (LWJGLException e) {
e.printStackTrace();
}
}
private enum Dir {UP, DOWN, RIGHT, LEFT}
}
|
public class ArrayList<T>{
public T value;
}
|
package com.tencent.mm.ui.contact;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.m;
import com.tencent.mm.ui.x;
public class AddressUI extends FragmentActivity {
public x tLY;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
m supportFragmentManager = getSupportFragmentManager();
if (supportFragmentManager.R(16908290) == null) {
this.tLY = new a();
this.tLY.setArguments(getIntent().getExtras());
supportFragmentManager.bk().a(16908290, this.tLY).commit();
}
}
protected void onSaveInstanceState(Bundle bundle) {
}
}
|
/*
* 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 hr.softwarecity.osijek.utility;
import hr.softwarecity.osijek.model.Entry;
import hr.softwarecity.osijek.model.Node;
import hr.softwarecity.osijek.model.Zone;
import hr.softwarecity.osijek.repositories.EntryRepository;
import hr.softwarecity.osijek.repositories.ZoneRepository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author Tomislav Turek
*/
public class Kruskal {
Map<Double, Map<Integer, Zone[]>> map = new TreeMap<>();
ZoneRepository zoneRepository;
EntryRepository entryRepository;
List<Zone> resultList = new ArrayList<>();
@Autowired
public Kruskal(ZoneRepository zoneRepository, EntryRepository entryRepository) {
this.zoneRepository = zoneRepository;
this.entryRepository = entryRepository;
}
public void fillMap(HashMap<Zone,List<Zone>> zones) {
List<Zone> lista = this.zoneRepository.findAll();
for(int i = 0; i < zones.size(); i++) {
for(Zone z: lista) {
List<Zone> susjedi = zones.get(z);
for(Zone s: susjedi) {
int biteDensity = entryRepository.countByZone(s.getIdZone());
if(biteDensity == 0) continue;
Logger.getLogger("Kruskal.java").log(Level.INFO, "biteDensity " + biteDensity);
List<Entry> entries = entryRepository.findByZone(s.getIdZone());
double points[] = new double[1000];
int k = 0;
for(int j = 0; j < entries.size(); j+=2) {
points[j] = entries.get(k).getLat();
points[j+1] = entries.get(k).getLng();
k++;
}
double[] centros = Calculations.centeroid(points);
//treba promijeni u licinku
double midPoint[] = Calculations.midPoint(z.getStartLat(), z.getStartLng(), z.getEndLat(), z.getEndLng());
//opet duzina od licinke do centeroida zone
double distance = Calculations.calculateDistanceBetweenTwoPoints(centros[0], centros[1], midPoint[0], midPoint[1]);
double weight = Calculations.calculateWeight(0, biteDensity, 1, z.getZoneDanger());
Logger.getLogger("Kruskal.java").log(Level.INFO, "weight for zone " + z.getIdZone() + " with neighbour " + s.getIdZone() + " is " + weight);
Map<Double, Map<Integer, Zone[]>> m = new TreeMap<>();
Map<Integer, Zone[]> h = new HashMap();
Zone[] oneDirection = new Zone[2];
oneDirection[0] = z;
oneDirection[1] = s;
h.put(i, oneDirection);
map.put(weight, h);
}
}
}
}
private boolean isInUnion(Node t, Node goal, Node endGoal) {
for(int i = 0; i < resultList.size() - 1; i++) {
Zone selected = resultList.get(i);
Node first = new Node(selected.getStartLat(), selected.getStartLng());
Node last = new Node(selected.getEndLat(), selected.getEndLng());
if(first == t && last == goal) continue;
if(first == t) {
isInUnion(last, t, endGoal);
} else if(last == t) {
isInUnion(first, t, endGoal);
}
if(first == endGoal || last == endGoal) return true;
}
return false;
}
public List<Zone> getNodeToNode() {
map.values().stream().forEach((Map<Integer, Zone[]> m) -> {
m.values().stream().forEach((Zone[] z) -> {
if(z[0] != null && z[1] != null) {
double pointsA[] = Calculations.centeroid(new double[] { z[0].getStartLat(), z[0].getStartLng(), z[0].getEndLat(), z[0].getEndLng() });
double pointsB[] = Calculations.centeroid(new double[] { z[1].getStartLat(), z[1].getStartLng(), z[1].getEndLat(), z[1].getEndLng() });
Zone n = new Zone();
n.setStartLat(pointsA[0]);
n.setStartLng(pointsA[1]);
n.setEndLat(pointsB[0]);
n.setEndLng(pointsB[1]);
Node q = new Node(pointsA[0], pointsA[1]);
Node t = new Node(pointsB[0], pointsB[1]);
if(!isInUnion(t,q,t) && !isInUnion(t,q,q)) resultList.add(n);
}
});
});
return resultList;
}
}
|
package control;
public class ModelAndView {
String path="";
boolean isRedirect;
ModelAndView(){
super();
}
ModelAndView(String path, boolean isRedirect){
super();
this.path=path;
this.isRedirect=isRedirect;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public boolean isRedirect() {
return isRedirect;
}
public void setRedirect(boolean isRedirect) {
this.isRedirect = isRedirect;
}
public String toString(){
return "ModelAndView [path="+path+", isRedirect="+isRedirect+"]";
}
}
|
package com.tangdi.production.mpnotice.dao;
import java.util.Map;
public interface PushAccessDao {
/**
* 根据平台进行查询
*
* @param platId
* @return
*/
public Map<String, Object> selectByPlatfrom(String platfrom);
/**
* 修改记录
*
* @param param
* @return
*/
public int updateEntity(Map<String, Object> param);
}
|
package com.e6soft.core.mail;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
public class MailExecutor implements Runnable {
private JavaMailSenderImpl mailSender;
private MimeMessage message;
private MailEvent mailEvent;
public MailExecutor(JavaMailSenderImpl mailSender,MimeMessage message,MailEvent mailEvent){
this.mailSender = mailSender;
this.message = message;
this.mailEvent = mailEvent;
}
@Override
public void run() {
StringBuffer bld = new StringBuffer("[");
try {
javax.mail.Address [] as = null;
as = message.getRecipients(Message.RecipientType.TO);
for(Address a:as){
bld.append(a).append(",");
}
bld.append("]");
} catch (MessagingException e) {
e.printStackTrace();
}
try {
mailSender.send(message);
if(mailEvent!=null){
mailEvent.afterSucess(message);
}
} catch (Exception e) {
e.printStackTrace();
if(mailEvent!=null){
mailEvent.afterFail(message);
}
}
}
}
|
package org.apache.hadoop.yarn.server.nodemanager;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ContainerId;
public interface CoresManager {
public void init(Configuration conf);
//called when allcoated container
public Set<Integer> allocateCores(ContainerId cntId, int num);
//preempt #num of cores and returned new assigned cores
public Set<Integer> resetCores(ContainerId cntId, int num);
//called when a container finished execution
public void releaseCores(ContainerId cntId);
}
|
package org.proyectofinal.gestorpacientes.modelo;
import java.util.List;
import org.hibernate.Query;
import org.proyectofinal.gestorpacientes.modelo.entidades.Medico;
import org.proyectofinal.gestorpacientes.modelo.entidades.Paciente;
public class ModeloMedico implements Modelo {
private static ModeloMedico instancia;
private Manejador manejador;
private ModeloMedico(Boolean script, Boolean export) {
manejador = Manejador.getInstancia(script, export);
}
public static ModeloMedico getInstancia(Boolean script, Boolean export) {
if (instancia == null)
instancia = new ModeloMedico(script, export);
return instancia;
}
@Override
public void eliminar(int id) {
manejador.getSession().beginTransaction().begin();
Object medico = manejador.getSession().get(Medico.class, id);
manejador.getSession().delete(medico);
manejador.getSession().getTransaction().commit();
}
@Override
public List<Medico> getListado() {
manejador.getSession().beginTransaction().begin();
Query q = manejador.getSession().getNamedQuery("Medico.getAll");
@SuppressWarnings("rawtypes")
List medicos = q.list();
manejador.getSession().getTransaction().commit();
return medicos;
}
@Override
public Object consultar(int id) {
manejador.getSession().beginTransaction().begin();
return (Medico) manejador.getSession().get(Medico.class, id);
}
@Override
public void modificar(Object obj) {
manejador.getSession().beginTransaction().begin();
Medico medicoOld = (Medico) manejador.getSession().get(Medico.class,
((Paciente) obj).getId());
medicoOld.setNombre(((Medico) obj).getNombre());
medicoOld.setApellido(((Medico) obj).getApellido());
medicoOld.setCedula(((Medico) obj).getCedula());
medicoOld.setTelefonoCasa(((Medico) obj).getTelefonoCasa());
medicoOld.setTelefonoCelular(((Medico) obj).getTelefonoCelular());
medicoOld.setUsuario(((Medico) obj).getUsuario());
manejador.getSession().update(medicoOld);
manejador.getSession().getTransaction().commit();
}
@Override
public void crear(Object obj) {
manejador.getSession().beginTransaction().begin();
manejador.getSession().save(obj);
manejador.getSession().getTransaction().commit();
}
}
|
package com.tencent.mm.plugin.talkroom.model;
import com.tencent.mm.compatible.e.m;
public final class a {
public static final int ovJ;
private static int ovW;
static {
int zj = m.zj();
ovW = zj;
ovJ = (zj & 1024) != 0 ? 16000 : 8000;
}
}
|
package com.khmersolution.moduler.specification;
import com.khmersolution.moduler.domain.User;
import com.khmersolution.moduler.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class JPASpecificationsTest {
public static final String LAST_NAME = "lastName";
public static final String FIRST_NAME = "firstName";
public static final String SEARCH_OP = ":";
public static final String SEARCH_LN = "jonh";
public static final String SEARCH_FN = "tommy";
public static final String QUERY_PATERN = "(\\w+?)(:|<|>)(\\w+?),";
public static final String QUERY_SEARCH_1 = "firstName:jerry,lastName:tommy";
public static final String QUERY_SEARCH_2 = "firstName:hello,lastName:motor";
@Autowired
private UserRepository userRepository;
private User jonhAbc;
private User jonhDoe;
private User jerryTommy;
private User jonhyTommy;
@Before
public void init() {
jonhAbc = User.staticUser("jonh", "abc");
jonhDoe = User.staticUser("jonh", "doe");
jerryTommy = User.staticUser("jerry", "tommy");
jonhyTommy = User.staticUser("jonhy", "tommy");
userRepository.save(Arrays.asList(
jonhAbc, jonhDoe, jerryTommy, jonhyTommy
));
}
@Test
public void searchByLastName() {
List<User> result = this.queryWithCriteria(FIRST_NAME, SEARCH_OP, SEARCH_FN);
Assert.assertNotNull(result);
}
@Test
public void searchByFirstName() {
List<User> result = this.queryWithCriteria(LAST_NAME, SEARCH_OP, SEARCH_LN);
Assert.assertNotNull(result);
}
@Test
public void searchByBuilder1() {
List<User> userList = this.queryWithBuilder(QUERY_PATERN, QUERY_SEARCH_1);
Assert.assertNotNull(userList);
}
@Test
public void searchByBuilder2() {
List<User> userList = this.queryWithBuilder(QUERY_PATERN, QUERY_SEARCH_2);
Assert.assertNull(userList);
}
private List<User> queryWithCriteria(String key, String operation, String value) {
UserSpecification spec = new UserSpecification(new SearchCriteria(key, operation, value));
List<User> results = userRepository.findAll(spec);
log.debug("found list" + results);
return results;
}
private List<User> queryWithBuilder(String patternString, String queryString) {
UserSpecificationsBuilder builder = new UserSpecificationsBuilder();
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(queryString + ",");
while (matcher.find()) {
builder.with(matcher.group(1), matcher.group(2), matcher.group(3));
}
Specification<User> spec = builder.build();
List<User> userList = userRepository.findAll(spec);
log.debug("found list" + userList);
return userList;
}
}
|
package cn.chenhuanming.controller;
import cn.chenhuanming.demo.DemoController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by Administrator on 2017/3/20.
*/
@RestController
public class MainController {
@GetMapping("/main")
String main(){
DemoController demoController = new DemoController();
return demoController.demo();
}
}
|
public class Search {
//k번째로 큰 수 찾기 메소드
static int nth_element(int[] data, int n, int k) {
return nth_element(data, 0, n-1, k);
}
static int nth_element(int[] data, int s, int e, int k) {
int p = partition(data, s, e);
if(k<=p-s) return nth_element(data, s, p-1, k);
if(k==p-s+1) return data[p];
return nth_element(data, p+1, e, k-p+s-1);
}
//k번째로 큰수 찾기 메소드에 필요한 partition메소드
public static int partition(int[] data, int s, int e) {
int pivot = data[e];
int i=s, j=e-1;
while(i<=j) {
if(pivot > data[i]) {
int temp = data[i];
data[i] = data[j];
data[j] = temp;
j--;
}
else i++;
}
data[e]=data[i];
data[i]=pivot;
return i;
}
}
|
package com.company;
import java.util.*;
public class LSDRadixsort {
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
scanner.nextLine();
String name[]=new String[n];
String auxname[]=new String[n];
for(int i=0;i<n;i++)
{
name[i]=scanner.nextLine();
}
int r=26;//number of sections
for(int d=name[0].length()-1;d>=0;d--)
{
int [] count=new int[r+1];
for (int i = 0; i < n; i++)
count[name[i].charAt(d)-97+1]++;
for (int i = 0; i < r; i++)
count[i + 1] += count[i];
for (int i = 0; i < r; i++)
System.out.println(i+"- " + count[i]);
for (int i = 0; i < n; i++) {
auxname[count[name[i].charAt(d)-97]++] = name[i];
}
}
for(int i=0;i<n;i++)
{
name[i]=auxname[i];
System.out.println("name- "+name[i]);
}
}
}
|
package mum.lesson5.problem4;
public class SalariedEmployee extends Employee{
private double weeklySal;
public SalariedEmployee(String fName, String lName, String ssn, double weeklySal) {
super(fName, lName, ssn);
this.weeklySal = weeklySal;
}
public double getWeeklySal() {
return weeklySal;
}
public void setWeeklySal(double weeklySal) {
this.weeklySal = weeklySal;
}
@Override
public double getPaymentAmount() {
return this.weeklySal;
}
public String toString() {
return "First Name: "+getfName()+"\n"+"last Name: "+getlName()+"\n"+"Social Security Number: "+getSsn()+"\n"
+"Weekly Salary: "+getWeeklySal()+"\n";
}
}
|
package org.maven.ide.eclipse.authentication;
public class AuthRegistryException
extends RuntimeException
{
private static final long serialVersionUID = -5478280761254370765L;
public AuthRegistryException( String message ) {
super( message );
}
public AuthRegistryException( Exception cause ) {
super( cause.getMessage(), cause );
}
public AuthRegistryException( String message, Exception cause ) {
super( message, cause );
}
}
|
package com.example.myfavoritemovie.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.myfavoritemovie.R;
import com.example.myfavoritemovie.model.MovieFavorite;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private static final String IMG_BASE = "http://image.tmdb.org/t/p/";
private ArrayList<MovieFavorite> movieArrayList;
private Context context;
public MovieAdapter(Context context) {
this.context = context;
movieArrayList = new ArrayList<>();
}
private ArrayList<MovieFavorite> getMovieArrayList() {
return movieArrayList;
}
public void setMovieArrayList(ArrayList<MovieFavorite> movieArrayList) {
this.movieArrayList = movieArrayList;
notifyDataSetChanged();
}
private Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
@NonNull
@Override
public MovieAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
return new MovieAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MovieAdapter.ViewHolder holder, int position) {
MovieFavorite movie = movieArrayList.get(position);
Glide.with(holder.itemView.getContext())
.load(IMG_BASE + "w185" + movie.getPoster())
.apply(new RequestOptions().override(96, 144))
.into(holder.poster);
holder.title.setText(movie.getTitle());
holder.releaseDate.setText(movie.getReleaseDate());
holder.voteAverage.setRating((float) movie.getVoteAverage() / 2);
}
@Override
public int getItemCount() {
return movieArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView poster;
TextView title;
TextView releaseDate;
RatingBar voteAverage;
public ViewHolder(@NonNull View itemView) {
super(itemView);
poster = itemView.findViewById(R.id.item_poster);
title = itemView.findViewById(R.id.item_title);
releaseDate = itemView.findViewById(R.id.item_release_date);
voteAverage = itemView.findViewById(R.id.item_vote);
}
}
}
|
package edu.ivytech.anonclasses;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;
ConstraintLayout layout;
RadioGroup radioGroup;
RadioButton radioButton2, radioButton3, radioButton4;
SeekBar seekBar;
Spinner spinner;
private SharedPreferences savedValues;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
textView = findViewById(R.id.textView);
layout = findViewById(R.id.layout);
radioGroup = findViewById(R.id.radioGroup);
radioButton2 = findViewById(R.id.radioButton2);
radioButton3 = findViewById(R.id.radioButton3);
radioButton4 = findViewById(R.id.radioButton4);
seekBar = findViewById(R.id.seekBar);
spinner = findViewById(R.id.spinner);
savedValues = getSharedPreferences("savedValues", MODE_PRIVATE);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,R.array.spinnerArray,android.R.layout.simple_spinner_item
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
editText.setOnEditorActionListener(
new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView editorTextView, int i, KeyEvent keyEvent) {
Toast.makeText(MainActivity.this, "Clicked the Edit Text",
Toast.LENGTH_LONG).show();
Log.i("AnonClasses","EditText Clicked");
String text = editorTextView.getText().toString();
textView.setText(text);
return false;
}
}
);
layout.setOnTouchListener(
new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float downX, downY, upX, upY;
int action = motionEvent.getAction();
if (action == MotionEvent.ACTION_DOWN) {
Log.d("MotionEvent","ACTION_DOWN");
downX = motionEvent.getX();
downY = motionEvent.getY();
Log.d("MotionEvent", "downX = " + downX);
Log.d("MotionEvent", "downY = " + downY);
return true;
} else if (action == MotionEvent.ACTION_UP) {
Log.d("MotionEvent", "ACTION_UP");
upX = motionEvent.getX();
upY = motionEvent.getY();
Log.d("MotionEvent", "upX = " + upX);
Log.d("MotionEvent", "upY = " + upY);
return true;
} else {
return false;
}
}
}
);
radioGroup.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch(i) {
case R.id.radioButton2:
Toast.makeText(MainActivity.this, "2", Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
Toast.makeText(MainActivity.this, "3", Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton4:
Toast.makeText(MainActivity.this,"4", Toast.LENGTH_SHORT).show();
break;
}
}
}
);
seekBar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textView.setText(Integer.toString(i));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
}
}
);
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//editText.setText(Integer.toString(i));
String item = (String)adapterView.getItemAtPosition(i);
int itemInt = Integer.parseInt(item);
Log.d("Anon Classes Spinner",item);
Toast.makeText(MainActivity.this,item,Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
);
}
@Override
protected void onPause() {
Editor editor = savedValues.edit();
editor.putString("editText",editText.getText().toString());
editor.commit();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
editText.setText(savedValues.getString("editText",""));
}
}
|
package id.ac.ub.ptiik.papps.tasks;
import java.util.ArrayList;
import id.ac.ub.ptiik.papps.base.Matakuliah;
import id.ac.ub.ptiik.papps.interfaces.MatakuliahIndexInterface;
import id.ac.ub.ptiik.papps.parsers.MatakuliahListParser;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import ap.mobile.utils.Rest;
public class MatakuliahIndexTask extends AsyncTask<Void, Void, ArrayList<Matakuliah>> {
private MatakuliahIndexInterface mCallback;
private String error;
private Context c;
public MatakuliahIndexTask(Context c, MatakuliahIndexInterface mCallback) {
this.mCallback = mCallback;
this.c = c;
}
@Override
protected ArrayList<Matakuliah> doInBackground(Void... params) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if(mCallback !=null)
mCallback.onMatakuliahRetrievingStart();
}
});
try {
String host = PreferenceManager
.getDefaultSharedPreferences(this.c)
.getString("host", "175.45.187.246");
String url = "http://"+host+"/service/index.php/matakuliah/index";
String result = Rest.getInstance().get(url).getResponseText();
ArrayList<Matakuliah> matakuliahList = MatakuliahListParser.Parse(result);
return matakuliahList;
} catch(Exception e) {
e.printStackTrace();
this.error = e.getMessage();
}
return null;
}
@Override
protected void onPostExecute(ArrayList<Matakuliah> matakuliahList) {
if(matakuliahList != null) {
this.mCallback.onMatakuliahRetrieveComplete(matakuliahList);
} else {
this.mCallback.onMatakuliahRetrieveFail(this.error);
}
}
}
|
import GUI.BEGEOT_BUNOUF_GUI_Login;
import GUI.BEGEOT_BUNOUF_GUI_noConnexion;
import UsefulFunctions.BEGEOT_BUNOUF_Database_Connection;
import javax.swing.*;
/**
* Class main du projet
*
* @author Célia
*/
public class BEGEOT_BUNOUF_Main {
public static void main(String[] argv) throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
BEGEOT_BUNOUF_Database_Connection database = new BEGEOT_BUNOUF_Database_Connection();
if (database.getConnexion() == null) {
database.Database_Deconnection();
new BEGEOT_BUNOUF_GUI_noConnexion();
} else {
database.Database_Deconnection();
new BEGEOT_BUNOUF_GUI_Login();
}
}
}
|
public class Main {
public static void main(String[] args) {
Parcel parcel = new Parcel();
parcel.id = 100;
System.out.println("id = " + parcel.id);
Parcel.Destination dest = parcel.new Destination();
dest.homeNumber = 10;
System.out.println("house = " + dest.homeNumber);
new AnonymousClass(5){
public void print(){
System.out.println("Первый анонимный класс");
};
};
new AnonymousClass(5){
public void print(){
System.out.println("Второй анонимный класс");
};
};
StaticNestedClass staticNested = new StaticNestedClass();
staticNested.method();
}
static class StaticNestedClass {
public void method() {
System.out.println("Это мой вложенный класс");
}
}
}
|
/*
* KINGSTAR MEDIA SOLUTIONS Co.,LTD. Copyright c 2005-2013. All rights reserved.
*
* This source code is the property of KINGSTAR MEDIA SOLUTIONS LTD. It is intended
* only for the use of KINGSTAR MEDIA application development. Reengineering, reproduction
* arose from modification of the original source, or other redistribution of this source
* is not permitted without written permission of the KINGSTAR MEDIA SOLUTIONS LTD.
*/
package com.beiyelin.commonwx.mp.util.json;
import com.beiyelin.common.utils.GsonUtils;
import com.google.gson.*;
import com.beiyelin.commonwx.mp.bean.material.WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem;
import java.lang.reflect.Type;
import java.util.Date;
public class WxMpMaterialFileBatchGetGsonItemAdapter implements JsonDeserializer<WxMaterialFileBatchGetNewsItem> {
@Override
public WxMaterialFileBatchGetNewsItem deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
WxMaterialFileBatchGetNewsItem newsItem = new WxMaterialFileBatchGetNewsItem();
JsonObject json = jsonElement.getAsJsonObject();
if (json.get("media_id") != null && !json.get("media_id").isJsonNull()) {
newsItem.setMediaId(GsonUtils.getAsString(json.get("media_id")));
}
if (json.get("update_time") != null && !json.get("update_time").isJsonNull()) {
newsItem.setUpdateTime(new Date(1000 * GsonUtils.getAsLong(json.get("update_time"))));
}
if (json.get("name") != null && !json.get("name").isJsonNull()) {
newsItem.setName(GsonUtils.getAsString(json.get("name")));
}
if (json.get("url") != null && !json.get("url").isJsonNull()) {
newsItem.setUrl(GsonUtils.getAsString(json.get("url")));
}
return newsItem;
}
}
|
/*
LeetCode Problem 876
Middle of the Linked List
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
*/
/*
Approach: This problem can be solved in 2-passes by calculating the length of the list in the first pass and then dividing
it by 2 and travelling to the middle element.
For a single-pass solution, we use 2-pointer technique. We initialize two pointers - fast and slow.
Move fast ahead by 2 places in each iteration and slow by 1 place.
When fast reaches towards end of the linked list, slow points to the middle of the list.
In the case where the list has even number of elements, we have 2 middles, so we return the second one.
Time Complexity: O(n)
*/
public ListNode middleNode(ListNode head) {
ListNode fast=head, slow=head;
while(fast.next!=null && fast.next.next!=null) {
fast = fast.next.next;
slow = slow.next;
}
if(fast.next!=null) {
slow = slow.next;
}
return slow;
}
|
package com.perhab.napalm.statement;
import java.lang.reflect.Method;
import com.perhab.napalm.Result;
public interface Statement {
Result execute();
Method getMethod();
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class hj extends b {
public a bQG;
public b bQH;
public hj() {
this((byte) 0);
}
private hj(byte b) {
this.bQG = new a();
this.bQH = new b();
this.sFm = false;
this.bJX = null;
}
}
|
package bean;
public class Suggest {
private int u_id;
private String u_suggest;
public int getU_id() {
return u_id;
}
public void setU_id(int u_id) {
this.u_id = u_id;
}
public String getU_suggest() {
return u_suggest;
}
public void setU_suggest(String u_suggest) {
this.u_suggest = u_suggest;
}
public Suggest(int u_id, String u_suggest) {
super();
this.u_id = u_id;
this.u_suggest = u_suggest;
}
}
|
package ccri.neighborhood.exercise;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Iterator;
import org.junit.jupiter.api.Test;
public class NeighborIteratorTest {
/**
* Verifies that a cell with a positive value within a 5x5 neighborhood returns the correct number
* of cells. The iterated cells are expected as follows:
* **X**
* *XXX*
* XXXXX
* *XXX*
* **X**
* This setup should yield 13 iterations.
*/
@Test
public void shouldIterateAllNeighbors() {
Neighborhood neighborhood = new NeighborhoodBuilder(5, 5)
.withValueAtLocation(new Location(2, 2), 1)
.build();
Iterator<Location> neighborIterator = neighborhood.neighborIterator(new Location(2, 2), 2);
int count = 0;
while (neighborIterator.hasNext()) {
neighborIterator.next();
count++;
}
assertEquals(13, count);
}
}
|
package finalProject;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Simulation {
public static ThreadPoolExecutor pool;
static final Factory aFactory = new Factory();
volatile static boolean end = false;
volatile static long startTime;
volatile static long endTime;
public static void main(String[] args) throws InterruptedException {
int t = Integer.parseInt(args[0]);
assert t>=1;
pool= (ThreadPoolExecutor) Executors.newFixedThreadPool(t);
startTime= System.currentTimeMillis();
start();
while(!end)TimeUnit.MILLISECONDS.sleep(100);
pool.shutdown();
System.out.print("time taken for "+t+" threads: "+(endTime-startTime)+"ms.");
}
static void start() {
ArrayList<Actor> sim= exampleFor();
sim.forEach(a -> pool.execute(a));
}
/**this example is taken from the same for loop in lecture notes 04-07, which iterates for 10 times and output a 10
* usually a channel is anonymous except when initialization is required.
* @return
*/
static ArrayList<Actor> exampleFor(){
ArrayList<Actor> result = new ArrayList<Actor>();
//merge actor construction
Actor merge = aFactory.createActor("merge");
Actor fork1 = aFactory.createActor("fork");
Actor fork2 = aFactory.createActor("fork");
Actor constantFork =aFactory.createActor("fork");
Actor constantTen = new Constant(10);
Actor lessthan = aFactory.createActor("lessthan");
Actor Switch = aFactory.createActor("switch");
Actor inc = aFactory.createActor("inc");
Actor output = aFactory.createActor("output");
//this channel acts as input;
Channel merge_falseChannel = aFactory.createChannel();
for(int i=0;i<10000;i++)merge_falseChannel.set(0);
merge.ConnectIn(merge_falseChannel, 2);
Factory.connectActors(aFactory.createChannel(), merge, fork1, 0, 0);
Factory.connectActors(aFactory.createChannel(), fork1, constantFork, 1, 0);
Factory.connectActors(aFactory.createChannel(), fork1, Switch, 0, 1);
Factory.connectActors(aFactory.createChannel(), Switch, inc, 0, 0);
Factory.connectActors(aFactory.createChannel(), Switch, output, 1, 0);
Factory.connectActors(aFactory.createChannel(), inc, merge, 0, 1);
Factory.connectActors(aFactory.createChannel(), constantFork, lessthan, 0, 0);
Factory.connectActors(aFactory.createChannel(), constantFork, constantTen, 1, 0);
Factory.connectActors(aFactory.createChannel(), constantTen, lessthan, 0, 1);
Factory.connectActors(aFactory.createChannel(), lessthan, fork2, 0, 0);
Factory.connectActors(aFactory.createChannel(), fork2, Switch, 0, 0);
//this channel is initialized to false for merge
Channel merge_boolChanel = aFactory.createChannel();
merge_boolChanel.set(1);
fork2.ConnectOut(merge_boolChanel, 1);
merge.ConnectIn(merge_boolChanel, 0);
//connect output to a channel
Channel outputSink = aFactory.createChannel();
output.ConnectOut(outputSink, 0);
result.add(merge);result.add(fork1);result.add(lessthan);result.add(fork2);
result.add(Switch);result.add(inc);result.add(output);result.add(constantTen);result.add(constantFork);
return result;
}
}
|
package kh.picsell.advisers;
import javax.servlet.http.HttpSession;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
public class PerfAdviser {
@Autowired
private HttpSession session;
// public Object loginCheck(ProceedingJoinPoint pjp) {
// Object result = null;
// Object loginInfo = session.getAttribute("loginInfo");
//
// if(loginInfo != null) {
// try {
// result = pjp.proceed(pjp.getArgs());
// } catch (Throwable e) {
// e.printStackTrace();
// return "error";
// }
// }else {
// return "error";
// }
// return result;
// }
public Object adminCheck(ProceedingJoinPoint pjp) {
Object result = null;
Object adminInfo = session.getAttribute("adminInfo");
System.out.println("zz");
if(adminInfo != null) {
try {
System.out.println("a");
result = pjp.proceed(pjp.getArgs());
System.out.println("b");
} catch (Throwable e) {
e.printStackTrace();
return "error";
}
}else {
return "error";
}
return result;
}
public Object infoCheck(ProceedingJoinPoint pjp) {
Object result = null;
Object adminInfo = session.getAttribute("adminInfo");
Object loginInfo = session.getAttribute("loginInfo");
if((adminInfo != null) || (loginInfo != null)) {
try {
System.out.println("a");
result = pjp.proceed(pjp.getArgs());
System.out.println("b");
} catch (Throwable e) {
e.printStackTrace();
return "error";
}
}else {
return "error";
}
return result;
}
}
|
package com.lito.fupin.controller.adminPage;
import com.lito.fupin.business.user.IUserBusinessService;
import org.hibernate.validator.constraints.pl.REGON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("admin")
public class AdminPageController {
private final IUserBusinessService iUserBusinessService;
public AdminPageController(IUserBusinessService iUserBusinessService) {
this.iUserBusinessService = iUserBusinessService;
}
/**
* 用户登录页面
*
* @return
*/
@RequestMapping("/loginPage")
public String loginPage() {
return "admin/user/login";
}
/**
* 管理员首页面板
*
* @return
*/
@RequestMapping("/dashboard")
public String dashboard() {
return "admin/dashboard";
}
/**
* 组织管理页面
*
* @return
*/
@RequestMapping("/organize")
public String organizePage(Model model) {
model.addAttribute("organize", true);
return "admin/organize/organize";
}
/**
* 栏目管理页面
*
* @return
*/
@RequestMapping("/category")
public String categoryPage(Model model) {
model.addAttribute("category", true);
return "admin/category/category";
}
/**
* 文章审核页面
*
* @return
*/
@RequestMapping("/approvePaper")
public String approvePaperPage() {
return "admin/paper/approvePaper";
}
/**
* 用户管理页面
*
* @return
*/
@RequestMapping("/user")
public String userPage(Model model, HttpServletRequest httpServletRequest) {
try {
String token = httpServletRequest.getHeader("token");
Map in = new HashMap();
in.put("token", token);
// Map out = iUserBusinessService.listUserByToken(in);
// model.addAttribute("map",out);
model.addAttribute("user", true);
} catch (Exception ex) {
}
return "admin/user/user";
}
/**
* 创建新的文章页面
*
* @return
*/
@RequestMapping("/createPaper")
public String createPaper(Model model) {
model.addAttribute("paper", true);
model.addAttribute("createPaper", true);
return "admin/paper/paperNew";
}
/**
* 需要审核的文章列表
*
* @param model
* @return
*/
@RequestMapping("/auditPaperList")
public String auditPaperListPage(Model model) {
model.addAttribute("paper", true);
model.addAttribute("auditPaperList", true);
return "admin/paper/paperAuditList";
}
/**
* 审核文章详情
*
* @param model
* @return
*/
@RequestMapping("/auditPaperPage")
public String auditPaperPage(Model model) {
return "admin/paper/paperAuditPage";
}
/**
* 我创建的等待审核的文章
*
* @return
*/
@RequestMapping("/pendingPaper")
public String myPendingPaper(Model model) {
model.addAttribute("paper", true);
model.addAttribute("pendingPaper", true);
return "admin/paper/paperPendingList";
}
/**
* 所有我和我的下级机构创建的文章
*
* @param model
* @return
*/
@RequestMapping("/listMyPaperSub")
public String listMyPaperSub(Model model) {
model.addAttribute("paper", true);
model.addAttribute("listMyPaperSub", true);
return "admin/paper/paperListAll";
}
@GetMapping("/paperEditPage")
public String editPaperPage(Model model) {
return "admin/paper/paperEdit";
}
}
|
package org.tomat;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import static java.lang.String.format;
/**
* Created by Jose on 31/10/14.
*/
public class TomatVersion {
private final String versionFromStatic = "1.0-SNAPSHOT";
private final String version;
public TomatVersion(){
version=versionFromStatic;
}
public String getVersion() {
return version;
}
}
|
package com.example.wesley.myweatherapp;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
public class WeatherLoader extends AsyncTaskLoader<List<CityResults>> {
private String mURL;
public WeatherLoader(Context context, String url)
{
super(context);
mURL = url;
}
@Override
protected void onStartLoading() {forceLoad(); }
@Override
public List<CityResults> loadInBackground() {
if(mURL != null){return null;}
List<CityResults> weather = QueryUtils.fetchWeatherData(mURL);
return weather;
}
}
|
class Solution {
public int findCircleNum(int[][] M) {
int[] parent = new int[M.length];
Arrays.setAll(parent, i -> i);
for(int i = 0; i < M.length; i++){
for(int j = 0; j < M[i].length; j++){
if(M[i][j] == 1){
union(i, j, parent);
}
}
}
Set<Integer> set = new HashSet<>();
for(int i = 0; i < parent.length; i++){
find(i, parent); // path compression
set.add(parent[i]);
}
return set.size();
}
public int find(int x, int[] parent){
if(parent[x] != x){
parent[x] = find(parent[x], parent);
}
return parent[x];
}
public void union(int x, int y, int[] parent){
int x_root = find(x, parent);
int y_root = find(y, parent);
parent[x_root] = y_root;
}
}
|
package com.tj.popularmovies;
import android.icu.text.DateFormat;
import android.icu.text.SimpleDateFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.tj.popularmovies.R;
import com.tj.popularmovies.data.Movie;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
public class MovieActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie);
Bundle extras = getIntent().getExtras();
Movie movie = (Movie) extras.getParcelable("MOVIE");
if (movie != null){
setValues(movie);
}
}
private String getReleaseYear(String releaseDate){
String result = "";
java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
try {
Date date = simpleDateFormat.parse(releaseDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
result = String.valueOf(calendar.get(Calendar.YEAR));
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
private void setValues(Movie movie){
((TextView) findViewById(R.id.tv_movie_title)).setText(movie.getTitle());
((TextView) findViewById(R.id.tv_description)).setText(movie.getOverview());
((TextView) findViewById(R.id.tv_rating)).setText(movie.getUserRating() + " / 10");
((TextView) findViewById(R.id.tv_release_date)).setText(getReleaseYear(movie.getReleaseDate()));
Picasso.with(getApplicationContext()).load(movie.getThumbnailImage()).into((ImageView) findViewById(R.id.iv_movie_poster));
}
}
|
package com.tencent.mm.plugin.offline;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.offline.h.1;
import com.tencent.mm.pluginsdk.wallet.h;
import com.tencent.mm.ui.MMActivity;
class h$1$2 implements OnClickListener {
final /* synthetic */ MMActivity gdk;
final /* synthetic */ 1 lJc;
final /* synthetic */ int lJd;
h$1$2(1 1, MMActivity mMActivity, int i) {
this.lJc = 1;
this.gdk = mMActivity;
this.lJd = i;
}
public final void onClick(DialogInterface dialogInterface, int i) {
h.aa(this.gdk, this.lJd);
this.lJc.lJb.a(this.gdk, 0, h.m(this.lJc.lJb));
}
}
|
package com.trainex.uis.main;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.trainex.R;
import com.trainex.model.Session;
public class CallUsActivity extends AppCompatActivity {
private TextView title;
private ImageView imgCall;
private Button btnDone;
private TextView tvThankYou;
private LinearLayout booking;
private String textTitle;
private String textThankYou="";
private TextView tvSessionType;
private TextView tvPriceSession;
private Session session;
private String phone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call_us);
SharedPreferences prefs = getSharedPreferences("MY_SHARE_PREFERENCE", MODE_PRIVATE);
phone = prefs.getString("phone_number","");
init();
bind();
}
private void init(){
title = (TextView) findViewById(R.id.title);
imgCall = (ImageView) findViewById(R.id.imgCall);
btnDone = (Button) findViewById(R.id.btnDone);
tvThankYou = (TextView) findViewById(R.id.tvThankYou);
booking = (LinearLayout) findViewById(R.id.booking);
tvSessionType = (TextView) findViewById(R.id.tvSessionType);
tvPriceSession = (TextView) findViewById(R.id.tvPriceSession);
}
private void bind(){
textTitle = getIntent().getStringExtra("title");
btnDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(CallUsActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
title.setText(textTitle);
textThankYou = getIntent().getStringExtra("thankyou");
if (textThankYou==null){
tvThankYou.setText("Thank you !");
}else{
tvThankYou.setText(textThankYou);
}
if (textTitle.equalsIgnoreCase("Buy A Session")){
booking.setVisibility(View.VISIBLE);
session = (Session) getIntent().getSerializableExtra("session");
String sessionType = session.getTypeSession().replace('_', ' ');
tvSessionType.setText(sessionType);
tvPriceSession.setText(session.getPrice()+" AED");
}
imgCall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CallUsActivity.this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) CallUsActivity.this,
Manifest.permission.CALL_PHONE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed; request the permission
ActivityCompat.requestPermissions((Activity) CallUsActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
MainActivity.PERMISSION_CALL);
Toast.makeText(CallUsActivity.this, "Press again to call", Toast.LENGTH_SHORT).show();
}
} else {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+phone));
startActivity(callIntent);
}
}
});
}
}
|
package com.veveup.dao;
import com.veveup.domain.Message;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface MessageDao {
// @Select("select * from message order by date desc")
// Message findMessageById(Integer id);
// @Select("Select * from message order by date desc")
List<Message> findAll();
List<Message> findAllVisiable();
// @Insert("insert into message(author,content,date) values(#{author},#{content},#{date})")
void InsertMessage(Message message);
Integer InsertMessageAndReturnId(Message message);
void setHiddenById(Integer id);
void addLikesById(Integer id);
void minusLikesById(Integer id);
Message findMessageById(Integer id);
void updateMessage(Message message);
}
|
package com.filez.ldjsbridge.library;
import android.content.Context;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class LDJsBridgeUtils {
//////////////////////////常量//////////////////////////
/*
* 执行JS方法的命令
* */
public final static String CALL_JS_FROM_ANDROID_COMMEND = "javascript:LDJsBridge._handleMessageFromAndroid('%s');";
/*
* 执行JS方法的命令
* */
public final static String CALL_JS_ADD_NODE_COMMEND = "javascript:LDJsBridge._addJsHybridNote('%s');";
/*
* 本地JS文件的名称
* */
public final static String LCOAL_INJECT_JAVASCRIPT_NAME = "LDJsBridge.js";
/*
* callback的唯一ID
* */
public final static String CALLBACK_ID_FORMAT = "JAVA_CB_%s";
/*
* js命令最大的长度
* */
public final static int URL_MAX_CHARACTER_NUM = 2097152;
//////////////////////////公共方法//////////////////////////
/*
* 把Assets的文件内容转换成字符串
* */
public static String assetFile2Str(Context context, String filePath) {
InputStream in = null;
try {
in = context.getAssets().open(filePath);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
if (line != null && !line.matches("^\\s*\\/\\/.*")) { // 去除注释
sb.append(line);
}
} while (line != null);
bufferedReader.close();
in.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/*
* 得到一个唯一数
* */
public static String getUUID() {
return UUID.randomUUID().toString();
}
/*
* json转换成Map
* */
public static Map<String, Object> json2Map(String jsonString) {
JsonParser parser = new JsonParser();
JsonObject jsonObj = parser.parse(jsonString).getAsJsonObject();
return json2Map(jsonObj);
}
/*
* json对象转换成Map
* */
public static Map<String, Object> json2Map(JsonObject jsonObject) {
Map<String, Object> map = new HashMap<String, Object>();
Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for (Iterator<Map.Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext(); ) {
Map.Entry<String, JsonElement> entry = iter.next();
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof JsonArray) {
List array = json2List((JsonArray) value);
map.put((String) key, new Gson().toJson(array));
} else if (value instanceof JsonObject) {
Map tmpMap = json2Map((JsonObject) value);
map.put((String) key, new Gson().toJson(tmpMap));
} else {
if (value instanceof JsonPrimitive){
map.put((String) key, ((JsonPrimitive) value).getAsString());
}
}
}
return map;
}
/*
* jsonObject转换成List
* */
public static List<Object> json2List(JsonArray jsonArray) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < jsonArray.size(); i++) {
Object value = jsonArray.get(i);
if (value instanceof JsonArray) {
list.add(json2List((JsonArray) value));
} else if (value instanceof JsonObject) {
list.add(json2Map((JsonObject) value));
} else {
list.add(value);
}
}
return list;
}
}
|
package com.hakim.registration.logic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hakim.common.Utils.AES;
import com.hakim.registration.dao.DAO_REGI_02_00;
import com.hakim.registration.dto.DTO_REGI_02_00;
import com.hakim.registration.forms.FORM_REGI_02_00;
@Service
public class LOGIC_REGI_02_00 {
@Autowired
private DAO_REGI_02_00 dao_regi_02_00;
/**
*
**/
public String showView(FORM_REGI_02_00 form_regi_02_00) {
DTO_REGI_02_00 dto_regi_02_00 = new DTO_REGI_02_00();
dto_regi_02_00.setGender(form_regi_02_00.getSex());
dto_regi_02_00.setEmail(form_regi_02_00.getEmailAddress());
String enc = AES.encrypt(form_regi_02_00.getPassword());
dto_regi_02_00.setPassword(enc);
try {
dao_regi_02_00.createUser(dto_regi_02_00);
} catch (Exception e) {
e.printStackTrace();
}
return "/registration/regi_02_00";
}
}
|
package com.choryan.spannabletextpacket.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.util.AttributeSet;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.choryan.spannabletextpacket.interf.BackgroundDrawer;
import com.choryan.spannabletextpacket.interf.ForegroundDrawer;
import com.choryan.spannabletextpacket.interf.LineDrawer;
import com.choryan.spannabletextpacket.span.LayerSpan;
import com.choryan.spannabletextpacket.span.SingleWarpSpan;
/**
* @author: ChoRyan Quan
* @date: 6/17/21
*/
public class ShadeTextView extends TextView {
private SpannableStringBuilder spannableStringBuilder;
public ShadeTextView(Context context) {
super(context);
}
public ShadeTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public void setText(CharSequence text, BufferType type) {
if (text instanceof SpannableStringBuilder) {
spannableStringBuilder = (SpannableStringBuilder) text;
LayerSpan[] layerSpans = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), LayerSpan.class);
if (layerSpans != null) {
for (int i = 0; i < spannableStringBuilder.length(); i++) {
layerSpans = spannableStringBuilder.getSpans(i, i + 1, LayerSpan.class);
if (layerSpans != null && layerSpans.length > 0) {
spannableStringBuilder.setSpan(new SingleWarpSpan(layerSpans[layerSpans.length - 1]), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
remove(spannableStringBuilder, LayerSpan.class);
} else {
spannableStringBuilder = null;
}
super.setText(text, type);
}
@Override
protected void onDraw(Canvas canvas) {
if (getLayout() != null && spannableStringBuilder != null) {
Paint.FontMetricsInt fontMetricsInt = new Paint.FontMetricsInt();
getPaint().getFontMetricsInt(fontMetricsInt);
drawLineRect(fontMetricsInt, canvas, getLayout(), BackgroundDrawer.class);
super.onDraw(canvas);
drawLineRect(fontMetricsInt, canvas, getLayout(), ForegroundDrawer.class);
} else {
super.onDraw(canvas);
}
}
private <T> void remove(SpannableStringBuilder sb, Class<T> c) {
T[] spans = sb.getSpans(0, sb.length(), c);
if (spans != null) {
for (T span : spans) {
sb.removeSpan(span);
}
}
}
private <T extends LineDrawer> void drawLineRect(Paint.FontMetricsInt fontMetricsInt, Canvas canvas, Layout layout, Class<T> drawerClass) {
LineDrawer[] drawers = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), drawerClass);
if (drawers != null) {
LineDrawer drawer = null;
int lineStart, lineEnd, spanStar, spanEnd;
float left, right;
int lineCount = getLineCount();
for (int line = 0; line < lineCount; line++) {
lineStart = layout.getLineStart(line);
lineEnd = layout.getLineEnd(line);
for (LineDrawer lineDrawer : drawers) {
drawer = lineDrawer;
spanStar = Math.max(lineStart, spannableStringBuilder.getSpanStart(drawer));
spanEnd = Math.min(lineEnd, spannableStringBuilder.getSpanEnd(drawer));
if (spanEnd > spanStar) {
if (lineStart < spanStar) {
left = layout.getLineLeft(line) + Layout.getDesiredWidth(spannableStringBuilder, lineStart, spanStar, getPaint());
} else {
left = layout.getLineLeft(line);
}
if (lineEnd > spanEnd) {
right = layout.getLineRight(line) - StaticLayout.getDesiredWidth(spannableStringBuilder, spanEnd, lineEnd, getPaint());
} else {
right = layout.getLineRight(line);
}
left += getPaddingLeft();
right += getPaddingLeft();
drawer.draw(canvas, getPaint(), left, layout.getLineTop(line) + getPaddingTop(), right, layout.getLineBottom(line) + getPaddingTop(), layout.getLineBaseline(line));
}
}
}
}
}
}
|
package demo.plagdetect.calfeature;
import org.junit.Test;
import java.io.File;
public class TestTerminalExec {
TerminalExec terminalExec = new TerminalExec();
/**
* @Author duanding
* @Description testRunDiff
* @Date 4:04 PM 2019/9/9
* @Param []
* @return void
**/
@Test
public void testRunDiff(){
File oldFile = new File("/Users/dd/study/iSE/plagiarism_detection/Datalog_clean/1/ValueTest.java");
File newFile = new File("/Users/dd/study/iSE/plagiarism_detection/Datalog_clean/2/ValueTest.java");
File compareFile = new File("/Users/dd/study/iSE/out.txt");
terminalExec.runDiff(oldFile,newFile,compareFile);
}
}
|
package cn.hjf.handyutils;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* A class provide the storage function on file system.
* Created by huangjinfu on 2016/9/29.
*/
public final class FileUtil {
private static final String TAG = "HandyUtils-FileStorage";
/**
* save data, override the old file if exist.
*
* @param absolutePath file path.
* @param data data to storage in above path.
* @return true-save success, false-save failed.
*/
public static boolean save(String absolutePath, byte[] data) {
return save(absolutePath, data, false);
}
/**
* save data, client can choose whether or not override the old file if exist.
*
* @param absolutePath file path.
* @param data data to storage in above path.
* @param append true-append save, false-override save.
* @return true-save success, false-save failed.
*/
public static boolean save(String absolutePath, byte[] data, boolean append) {
File destFile = createFile(absolutePath);
if (destFile == null) {
return false;
}
if (!hasMoreSpace(destFile, data.length)) {
return false;
}
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(destFile, append);
bos = new BufferedOutputStream(fos);
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
Log.e(TAG, e.toString());
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
}
}
}
return false;
}
/**
* save serializable object.
*
* @param absolutePath file path.
* @param object object to storage in above path.
* @return true-save success, false-save failed.
*/
public static boolean save(String absolutePath, Serializable object) {
byte[] objectData = objectToByteArray(object);
if (objectData == null) {
return false;
}
return save(absolutePath, objectData);
}
/**
* read byte[] from file.
*
* @param absolutePath file path from which we read the data.
* @return file data, or null if file not exist or other error occurs.
*/
@Nullable
public static byte[] readBytes(String absolutePath) {
InputStream is;
try {
is = openInputStream(absolutePath);
} catch (FileNotFoundException e) {
Log.e(TAG, e.toString());
return null;
}
BufferedInputStream bis = null;
try {
byte[] data = new byte[0];
bis = new BufferedInputStream(is);
while (bis.available() != 0) {
byte[] temp = new byte[bis.available()];
bis.read(temp);
byte[] newData = new byte[data.length + temp.length];
System.arraycopy(data, 0, newData, 0, data.length);
System.arraycopy(temp, 0, newData, data.length, temp.length);
data = newData;
}
return data;
} catch (Exception e) {
Log.e(TAG, e.toString());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
}
}
}
return null;
}
/**
* read object from file.
*
* @param absolutePath file path from which we read the data.
* @return file data, or null if file not exist or other error occurs.
*/
@Nullable
public static Object readObject(String absolutePath) {
InputStream is;
try {
is = openInputStream(absolutePath);
} catch (FileNotFoundException e) {
Log.e(TAG, e.toString());
return null;
}
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(is);
return ois.readObject();
} catch (Exception e) {
Log.e(TAG, e.toString());
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
}
}
}
return null;
}
/**
* convert serializable object to byte array.
*
* @param object serializable object
* @return byte array which present this object, or null if object is null or other error occurs.
*/
@Nullable
public static byte[] objectToByteArray(Serializable object) {
if (object == null) {
return null;
}
ObjectOutputStream oos = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
return bos.toByteArray();
} catch (IOException e) {
Log.e(TAG, e.toString());
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
}
}
}
return null;
}
/**
* convert byte array to object
*
* @param byteArray byte array which present an object, may generate by {@link FileUtil#objectToByteArray(Serializable)}.
* @return the object, or null if byte array is null or other error occurs.
*/
@Nullable
public static Object byteArrayToObject(byte[] byteArray) {
if (byteArray == null) {
return null;
}
ObjectInputStream ois = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
ois = new ObjectInputStream(bis);
return ois.readObject();
} catch (Exception e) {
Log.e(TAG, e.toString());
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
}
}
}
return null;
}
/**
* copy a file.
*
* @param srcPath the src file path.
* @param destPath the dest file path.
* @param cover true-cover the dest file if exist.
* @return true-actual do copy in cover mode, or dest file exist when not in cover mode, false-copy failed.
*/
public static boolean copy(String srcPath, String destPath, boolean cover) {
//create dest file.
File srcFile = createFile(srcPath);
if (srcFile == null) {
return false;
}
//get src file.
File destFile = createFile(destPath);
if (destFile == null) {
return false;
}
//not cover mode
if (!cover) {
if (destFile.exists()) {
return true;
}
}
//read data from src file
byte[] data = readBytes(srcPath);
if (data == null) {
Log.e(TAG, "data read from : " + srcPath + ", is null");
return false;
}
//do save
return save(destPath, data);
}
/**
* delete a file or a directory.
*
* @param path file or directory to be deleted.
* @return true-delete success or file not exist, false-delete failed.
*/
public static boolean delete(String path) {
File file = createFile(path);
if (file == null) {
return true;
}
if (file.isDirectory()) {
return deleteDir(file);
}
if (file.exists()) {
return file.delete();
}
return true;
}
/**
* detect a specific file whether exist.
*
* @param path detect path.
* @return true-exists, false-not exists.
*/
public static boolean exists(String path) {
File file = new File(path);
return file.exists();
}
/**
* ********************************************************************************************************
* ********************************************************************************************************
*/
/**
* create file and it's parents.
*
* @param absolutePath
* @return
*/
@Nullable
private static File createFile(String absolutePath) {
File destFile = new File(absolutePath);
if (!destFile.getParentFile().exists()) {
if (!destFile.getParentFile().mkdirs()) {
Log.e(TAG, "create parent dirs fail, path : " + absolutePath);
return null;
}
}
return destFile;
}
/**
* calculate remain space whether enough to save the specific file.
*
* @param file file to be saved.
* @param needSpace data length.
* @return true-have enough space, false-have't enough space.
*/
private static boolean hasMoreSpace(File file, long needSpace) {
File existParent = getExistParent(file);
if (existParent.getUsableSpace() <= needSpace) {
Log.e(TAG, "no more space, require : " + needSpace + ", but remain : " + existParent.getUsableSpace());
return false;
}
return true;
}
/**
* find already exist parent along the up direction of the file tree.
*
* @param file
* @return
*/
private static File getExistParent(File file) {
File parent = file.getParentFile();
while (!parent.exists()) {
parent = parent.getParentFile();
}
return parent;
}
/**
* delete a directory.
*
* @param dir
* @return true-delete success, false-delete fail.
*/
private static boolean deleteDir(File dir) {
if (dir == null) {
return false;
}
File[] children = dir.listFiles();
if (children == null) {
return false;
}
boolean deleted = true;
for (int i = 0; i < children.length; i++) {
File child = children[i];
if (child.isDirectory()) {
deleted &= deleteDir(child);
} else {
deleted &= child.delete();
}
}
return deleted & dir.delete();
}
/**
* open a file.
*
* @param path file path.
* @return InputStream object for this file.
* @throws FileNotFoundException
*/
@NonNull
private static InputStream openInputStream(String path) throws FileNotFoundException {
File file = createFile(path);
if (file == null) {
throw new FileNotFoundException(path);
}
return new FileInputStream(file);
}
}
|
package NiuKe;
public class patrent {
private int a =0;
protected int b=1;
int c = 2;
}
|
package models;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name="role")
public class Role extends Model {
private static final long serialVersionUID = 3585034474308003857L;
@Column(name = "title")
private String title;
@ManyToMany(mappedBy = "roles")
private Set<User1> users = new HashSet<>();
public Role() {
super();
}
public Role(Long id) {
super(id);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<User1> getUsers() {
return users;
}
public void setUsers(Set<User1> users) {
this.users = users;
}
}
|
package behavioralPatterns.tamplatePattern.hookTamplate;
public class Hummer1 extends HummerMode{
private boolean alarmFlag = true;
@Override
protected void start() {
System.out.println("start");
}
@Override
protected void stop() {
System.out.println("stop");
}
@Override
protected void alarm() {
System.out.println("alarm");
}
@Override
protected void enginBoom() {
System.out.println("engine");
}
@Override
protected boolean isAlarm() {
return this.alarmFlag;
}
public void setAlarmFlag(boolean isAlarm){
this.alarmFlag = isAlarm;
}
}
|
import java.util.*;
public class SortTest {
public static void main (String [] args) {
int [] testArray;
double selectionSeconds;
double sortSeconds;
int i;
testArray = new int [100000];
for (i = 0; i < testArray.length; i ++) {
testArray [i] = (int)(Math.random () * 10000);
}
selectionSeconds = selectionSort (testArray);
sortSeconds = arraySort (testArray);
System.out.println ("It took " + selectionSeconds + " seconds to sort using selectionSort and " + sortSeconds + " seconds to sort using Array.sort.");
}
public static double selectionSort (int [] array) {
long startTime;
long endTime;
long compTime;
double seconds;
int lastPlace;
int maxLoc;
int temp;
int j;
startTime = System.nanoTime ();
for (lastPlace = array.length - 1; lastPlace > 0; lastPlace --) {
maxLoc = 0;
for (j = 1; j <= lastPlace; j ++) {
if (array [j] > array [maxLoc]) {
maxLoc = j;
}
}
temp = array [maxLoc];
array [maxLoc] = array [lastPlace];
array [lastPlace] = temp;
}
endTime = System.nanoTime ();
compTime = endTime - startTime;
seconds = compTime / 1000000000.0;
return seconds;
}
public static double arraySort (int [] array) {
long startTime;
long endTime;
long compTime;
double seconds;
startTime = System.nanoTime ();
Arrays.sort (array);
endTime = System.nanoTime ();
compTime = endTime - startTime;
seconds = compTime / 1000000000.0;
return seconds;
}
}
|
/*
* Copyright 2016 Johns Hopkins University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dataconservancy.cos.rdf.support;
/**
* Supported OSF OWL properties. Java fields annotated with {@code org.dataconservancy.cos.rdf.annotations.OwlProperty}
* may be mapped to the OWL properties enumerated here.
*
* @author Elliot Metsger (emetsger@jhu.edu)
*/
public enum OwlProperties {
OSF_HAS_FILE ("hasFile", true),
OSF_HAS_CONTRIBUTOR ("hasContributor", true),
OSF_HAS_LINK ("hasLink", true),
OSF_HAS_NODE ("hasNode", true),
OSF_HAS_CHILD ("hasChild", true),
OSF_HAS_PARENT ("hasParent", true),
OSF_HAS_ROOT ("hasRoot", true),
OSF_HAS_RELATIONSHIP ("hasRelationship", true),
OSF_HAS_RELATEDLINK ("hasRelatedLink", true),
OSF_REGISTERED_BY ("registeredBy", true),
OSF_REGISTERED_FROM ("registeredFrom", true),
OSF_FORKED_FROM ("forkedFrom", true),
OSF_HAS_USER ("hasUser", true),
OSF_HAS_LOG_AGENT("hasLogAgent", true),
OSF_HAS_LOG_SOURCE("hasLogSource", true),
OSF_HAS_LOG_TARGET("hasLogTarget", true),
OSF_HAS_LICENSE ("hasLicense", true),
OSF_HAS_HASPROVIDER ("hasProvider", true),
OSF_PROVIDED_BY ("providedBy", true),
OSF_AUTHORED_BY ("authoredBy", true),
OSF_HAS_WIKI ("hasWiki", true),
OSF_HAS_COMMENT ("hasComment", true),
OSF_HAS_IDENTIFIER ("hasIdentifier", true),
DCTERMS_DESCRIPTION (Rdf.Ns.DCTERMS, "description"),
DCTERMS_IDENTIFIER (Rdf.Ns.DCTERMS, "identifier"),
DCTERMS_TITLE (Rdf.Ns.DCTERMS, "title"),
OSF_HAS_ACADEMICINSTITUTION ("hasAcademicInstitution"),
OSF_HAS_ACADEMICPROFILEID ("hasAcademicProfileId"),
OSF_IS_ACTIVE ("isActive"),
OSF_HAS_BAIDUID ("hasBaiduId"),
OSF_IS_BIBLIOGRAPHIC ("isBibliographic"),
OSF_HAS_CATEGORY ("hasCategory"),
OSF_IS_COLLECTION ("isCollection"),
OSF_IS_BOOKMARK ("isBookmark"),
OSF_HAS_CONTENT ("hasContent"),
OSF_HAS_CONTENTTYPE ("hasContentType"),
OSF_IS_DASHBOARD ("isDashboard"),
OSF_HAS_DATECREATED ("hasDateCreated"),
OSF_HAS_DATEMODIFIED ("hasDateModified"),
OSF_HAS_DATEREGISTERED ("hasDateRegistered"),
OSF_HAS_DATEUSERREGISTERED ("hasDateUserRegistered"),
OSF_HAS_DESCRIPTION ("hasDescription"),
OSF_HAS_EMBARGOENDDATE ("hasEmbargoEndDate"),
OSF_HAS_TAG ("hasTag"),
OSF_HAS_ETAG ("hasEtag"),
OSF_HAS_EXTRA ("hasExtra"),
OSF_HAS_HASFAMILYNAME ("hasFamilyName"),
OSF_IS_FORK ("isFork"),
OSF_HAS_FULLNAME ("hasFullName"),
OSF_HAS_HASGITHUB ("hasGitHub"),
OSF_HAS_GIVENNAME ("hasGivenName"),
OSF_HAS_HREF ("hasHref"),
OSF_HAS_ID ("hasId"),
OSF_HAS_IMPACTSTORY ("hasImpactStory"),
OSF_HAS_HASKIND ("hasKind"),
OSF_HAS_LASTTOUCHED ("hasLastTouched"),
OSF_HAS_LINKEDIN ("hasLinkedIn"),
OSF_HAS_LOCALE ("hasLocale"),
OSF_HAS_MATERIALIZEDPATH ("hasMaterializedPath"),
OSF_HAS_META ("hasMeta"),
OSF_HAS_MIDDLENAMES ("hasMiddleNames"),
OSF_HAS_NAME ("hasName"),
OSF_HAS_PATH ("hasPath"),
OSF_IS_PENDINGEMBARGOAPPROVAL ("isPendingEmbargoApproval"),
OSF_IS_PENDINGWITHDRAWL ("isPendingRegistrationApproval"),
OSF_IS_PENDINGREGISTRATIONAPPROVAL ("isPendingRegistrationApproval"),
OSF_HAS_PERSONALWEBSITE ("hasPersonalWebsite"),
OSF_HAS_PERMISSION ("hasPermission"),
OSF_IS_PUBLIC ("isPublic"),
OSF_IS_REGISTRATION ("isRegistration"),
OSF_HAS_REGISTRATIONSUPPLEMENT ("hasRegistrationSupplement"),
OSF_HAS_RELATIONSHIPTYPE ("hasRelationshipType"),
OSF_HAS_RELATEDLINKTYPE ("hasRelatedLinkType"),
OSF_HAS_RESEARCHERID ("hasResearcherId"),
OSF_HAS_RESEARCHGATE ("hasResearchGate"),
OSF_IS_RETRACTED ("isRetracted"),
OSF_HAS_RETRACTIONJUSTIFICATION ("hasRetractionJustification"),
OSF_HAS_SCHOLAR ("hasScholar"),
OSF_HAS_SIZE ("hasSize"),
OSF_HAS_SUFFIX ("hasSuffix"),
OSF_HAS_HASTIMEZONE ("hasTimezone"),
OSF_HAS_TITLE ("hasTitle"),
OSF_HAS_TWITTER ("hasTwitter"),
OSF_HAS_TYPE ("hasType"),
OSF_IS_WITHDRAWN ("isWithdrawn"),
OSF_HAS_WITHDRAW_JUSTIFICATION ("hasWithdrawJustification"),
OSF_HAS_LOG_DATE("hasLogDate"),
OSF_HAS_LOG_ACTION("hasLogAction"),
OSF_HAS_LICENSE_NAME ("hasLicenseName"),
OSF_HAS_LICENSE_TEXT ("hasLicenseText"),
OSF_HAS_BINARYURI ("hasBinaryUri"),
OSF_PROVIDER_NAME ("providerName"),
OSF_HAS_ORCID ("hasOrcid"),
OSF_VERSION ("version"),
OSF_IN_REPLY_TO ("inReplyTo"),
OSF_HAS_IDENTIFIER_CATEGORY ("hasIdentifierCategory"),
OSF_HAS_IDENTIFIER_VALUE ("hasIdentifierValue"),
OSF_HAS_IDENTIFIER_REFERENT ("hasIdentifierReferent");
private String ns = Rdf.Ns.OSF;
private final String localname;
private boolean isObject = false;
private OwlProperties(final String localname) {
this.localname = localname;
}
private OwlProperties(final String ns, final String localname) {
this.ns = ns;
this.localname = localname;
}
private OwlProperties(final String localname, final boolean isObject) {
this.localname = localname;
this.isObject = isObject;
}
private OwlProperties(final String ns, final String localname, final boolean isObject) {
this.ns = ns;
this.localname = localname;
this.isObject = isObject;
}
/**
* The RDF namespace of the property.
*
* @return the namespace
*/
public String ns() {
return ns;
}
/**
* The RDF name of the property sans namespace.
*
* @return the local name
*/
public String localname() {
return localname;
}
/**
* The fully qualified RDF name of this property.
*
* @return the fully qualified name
*/
public String fqname() {
return ns + localname;
}
/**
* TODO: Reconsider if this needs to be represented in the Java. The property definition in the ontology
* TODO: will have this information. If the Java code retrieves the property definition from the ontology,
* TODO: it can determine whether or not it is an ObjectProperty. Removing this information from the Java model
* TODO: eliminates a potential issue where a property is considered a ObjectProperty according to Java but
* TODO: is defined as a DatatypeProperty according to the ontology.
* Whether or not the property represents an OWL Object property or Datatype property.
*
* @return true if the property is an OWL Object property
*/
public boolean object() {
return isObject;
}
}
|
package mude.srl.ssc.service.resource;
import java.util.Calendar;
public class PolicyWrapper {
Integer minDay;
Integer maxDay;
Calendar minHour;
Calendar maxHour;
boolean daily;
public Integer getMinDay() {
return minDay;
}
public void setMinDay(Integer minDay) {
this.minDay = minDay;
}
public Integer getMaxDay() {
return maxDay;
}
public void setMaxDay(Integer maxDay) {
this.maxDay = maxDay;
}
public Calendar getMinHour() {
return minHour;
}
public void setMinHour(Calendar minHour) {
this.minHour = minHour;
}
public Calendar getMaxHour() {
return maxHour;
}
public void setMaxHour(Calendar maxHour) {
this.maxHour = maxHour;
}
public boolean isDaily() {
return daily;
}
public void setDaily(boolean daily) {
this.daily = daily;
}
}
|
package com.mahanthesh.africar.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.donkey.dolly.Dolly;
import com.donkey.dolly.Type;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.mahanthesh.africar.activity.HomepageActivity;
import com.mahanthesh.africar.R;
import com.mahanthesh.africar.utils.Constants;
import com.mahanthesh.africar.utils.Utils;
public class FragmentLogin extends Fragment {
Button btnLogin;
EditText et_email, et_password;
ProgressBar spinner;
Dolly dolly;
private CallbackFragment mCallback;
private FirebaseAuth mAuth;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment,container,false);
btnLogin = view.findViewById(R.id.login_btn);
et_email = view.findViewById(R.id.et_login);
et_password = view.findViewById(R.id.et_password);
spinner = view.findViewById(R.id.login_spinner);
dolly = Dolly.getInstance(getContext());
btnLogin.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
ValidateLogin();
}
});
mAuth = FirebaseAuth.getInstance();
return view;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mCallback = (CallbackFragment) context;
}
@Override
public void onDetach() {
super.onDetach();
mCallback = null;
}
private void ValidateLogin() {
et_email.setError(null);
et_password.setError(null);
String email = et_email.getText().toString();
String password = et_password.getText().toString();
if(TextUtils.isEmpty(email)){
et_email.setError("Required!");
et_email.requestFocus();
return;
}
if(TextUtils.isEmpty(password)){
et_password.setError("Required!");
et_password.requestFocus();
return;
}
login();
}
private void login(){
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
spinner.setVisibility(View.VISIBLE);
String email = et_email.getText().toString();
String password = et_password.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
if(mCallback != null) {
Utils.saveLocalUser(requireContext(), Constants.DEFAULT_USER, et_email.getText().toString(), authResult.getUser().getUid());
spinner.setVisibility(View.INVISIBLE);
//Open Home
dolly.putBoolean("loggedIn", true, Type.NOT_ENCRYPTED);
Intent intent = new Intent(getActivity(), HomepageActivity.class);
startActivity(intent);
Toast.makeText(getContext(), "Successful",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
spinner.setVisibility(View.INVISIBLE);
Toast.makeText(getContext(), e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
|
package com.shsy.tubebaby.utils;
import android.os.Looper;
import android.widget.Toast;
import com.shsy.tubebaby.app.MyApplication;
/**
* 吐司
*/
public class ToastUtil {
public static void makeText(String text) {
Toast.makeText(MyApplication.getMyApplication(), text, Toast.LENGTH_SHORT).show();
}
public static void makeText(Object text) {
Toast.makeText(MyApplication.getMyApplication(), text.toString(), Toast.LENGTH_SHORT).show();
}
public static void makeText(int text) {
Toast.makeText(MyApplication.getMyApplication(),
MyApplication.getMyApplication().getResources().getString(text), Toast.LENGTH_SHORT).show();
}
public static boolean isMainThread() {
return Looper.getMainLooper() == Looper.myLooper();
}
}
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.incallui;
import android.app.ActivityManager.TaskDescription;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.telecom.DisconnectCause;
import android.telecom.PhoneAccount;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telecom.VideoProfile;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.Surface;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.android.contacts.common.interactions.TouchPointManager;
import com.android.contacts.common.testing.NeededForTesting;
import com.android.contacts.common.util.MaterialColorMapUtils.MaterialPalette;
import com.android.dialer.R;
import com.android.incalluibind.ObjectFactory;
import com.google.common.base.Preconditions;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Takes updates from the CallList and notifies the InCallActivity (UI)
* of the changes.
* Responsible for starting the activity for a new call and finishing the activity when all calls
* are disconnected.
* Creates and manages the in-call state and provides a listener pattern for the presenters
* that want to listen in on the in-call state changes.
* TODO: This class has become more of a state machine at this point. Consider renaming.
*/
public class InCallPresenter implements CallList.Listener,
CircularRevealFragment.OnCircularRevealCompleteListener {
private static final String EXTRA_FIRST_TIME_SHOWN =
"com.android.incallui.intent.extra.FIRST_TIME_SHOWN";
private static final Bundle EMPTY_EXTRAS = new Bundle();
private static InCallPresenter sInCallPresenter;
/**
* ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is
* load factor before resizing, 1 means we only expect a single thread to
* access the map so make only a single shard
*/
private final Set<InCallStateListener> mListeners = Collections.newSetFromMap(
new ConcurrentHashMap<InCallStateListener, Boolean>(8, 0.9f, 1));
private final List<IncomingCallListener> mIncomingCallListeners = new CopyOnWriteArrayList<>();
private final Set<InCallDetailsListener> mDetailsListeners = Collections.newSetFromMap(
new ConcurrentHashMap<InCallDetailsListener, Boolean>(8, 0.9f, 1));
private final Set<CanAddCallListener> mCanAddCallListeners = Collections.newSetFromMap(
new ConcurrentHashMap<CanAddCallListener, Boolean>(8, 0.9f, 1));
private final Set<InCallUiListener> mInCallUiListeners = Collections.newSetFromMap(
new ConcurrentHashMap<InCallUiListener, Boolean>(8, 0.9f, 1));
private final Set<InCallOrientationListener> mOrientationListeners = Collections.newSetFromMap(
new ConcurrentHashMap<InCallOrientationListener, Boolean>(8, 0.9f, 1));
private final Set<InCallEventListener> mInCallEventListeners = Collections.newSetFromMap(
new ConcurrentHashMap<InCallEventListener, Boolean>(8, 0.9f, 1));
private AudioModeProvider mAudioModeProvider;
private StatusBarNotifier mStatusBarNotifier;
private ContactInfoCache mContactInfoCache;
private Context mContext;
private CallList mCallList;
private InCallActivity mInCallActivity;
private InCallState mInCallState = InCallState.NO_CALLS;
private ProximitySensor mProximitySensor;
private boolean mServiceConnected = false;
private boolean mAccountSelectionCancelled = false;
private InCallCameraManager mInCallCameraManager = null;
private AnswerPresenter mAnswerPresenter = new AnswerPresenter();
/**
* Whether or not we are currently bound and waiting for Telecom to send us a new call.
*/
private boolean mBoundAndWaitingForOutgoingCall;
/**
* If there is no actual call currently in the call list, this will be used as a fallback
* to determine the theme color for InCallUI.
*/
private PhoneAccountHandle mPendingPhoneAccountHandle;
/**
* Determines if the InCall UI is in fullscreen mode or not.
*/
private boolean mIsFullScreen = false;
private final android.telecom.Call.Callback mCallCallback =
new android.telecom.Call.Callback() {
@Override
public void onPostDialWait(android.telecom.Call telecomCall,
String remainingPostDialSequence) {
final Call call = mCallList.getCallByTelecommCall(telecomCall);
if (call == null) {
Log.w(this, "Call not found in call list: " + telecomCall);
return;
}
onPostDialCharWait(call.getId(), remainingPostDialSequence);
}
@Override
public void onDetailsChanged(android.telecom.Call telecomCall,
android.telecom.Call.Details details) {
final Call call = mCallList.getCallByTelecommCall(telecomCall);
if (call == null) {
Log.w(this, "Call not found in call list: " + telecomCall);
return;
}
for (InCallDetailsListener listener : mDetailsListeners) {
listener.onDetailsChanged(call, details);
}
}
@Override
public void onConferenceableCallsChanged(android.telecom.Call telecomCall,
List<android.telecom.Call> conferenceableCalls) {
Log.i(this, "onConferenceableCallsChanged: " + telecomCall);
onDetailsChanged(telecomCall, telecomCall.getDetails());
}
};
/**
* Is true when the activity has been previously started. Some code needs to know not just if
* the activity is currently up, but if it had been previously shown in foreground for this
* in-call session (e.g., StatusBarNotifier). This gets reset when the session ends in the
* tear-down method.
*/
private boolean mIsActivityPreviouslyStarted = false;
/**
* Whether or not InCallService is bound to Telecom.
*/
private boolean mServiceBound = false;
/**
* When configuration changes Android kills the current activity and starts a new one.
* The flag is used to check if full clean up is necessary (activity is stopped and new
* activity won't be started), or if a new activity will be started right after the current one
* is destroyed, and therefore no need in release all resources.
*/
private boolean mIsChangingConfigurations = false;
/** Display colors for the UI. Consists of a primary color and secondary (darker) color */
private MaterialPalette mThemeColors;
private TelecomManager mTelecomManager;
public static synchronized InCallPresenter getInstance() {
if (sInCallPresenter == null) {
sInCallPresenter = new InCallPresenter();
}
return sInCallPresenter;
}
@NeededForTesting
static synchronized void setInstance(InCallPresenter inCallPresenter) {
sInCallPresenter = inCallPresenter;
}
public InCallState getInCallState() {
return mInCallState;
}
public CallList getCallList() {
return mCallList;
}
public void setUp(Context context,
CallList callList,
AudioModeProvider audioModeProvider,
StatusBarNotifier statusBarNotifier,
ContactInfoCache contactInfoCache,
ProximitySensor proximitySensor) {
if (mServiceConnected) {
Log.i(this, "New service connection replacing existing one.");
// retain the current resources, no need to create new ones.
Preconditions.checkState(context == mContext);
Preconditions.checkState(callList == mCallList);
Preconditions.checkState(audioModeProvider == mAudioModeProvider);
return;
}
Preconditions.checkNotNull(context);
mContext = context;
mContactInfoCache = contactInfoCache;
mStatusBarNotifier = statusBarNotifier;
addListener(mStatusBarNotifier);
mAudioModeProvider = audioModeProvider;
mProximitySensor = proximitySensor;
addListener(mProximitySensor);
addIncomingCallListener(mAnswerPresenter);
addInCallUiListener(mAnswerPresenter);
mCallList = callList;
// This only gets called by the service so this is okay.
mServiceConnected = true;
// The final thing we do in this set up is add ourselves as a listener to CallList. This
// will kick off an update and the whole process can start.
mCallList.addListener(this);
VideoPauseController.getInstance().setUp(this);
Log.d(this, "Finished InCallPresenter.setUp");
}
/**
* Called when the telephony service has disconnected from us. This will happen when there are
* no more active calls. However, we may still want to continue showing the UI for
* certain cases like showing "Call Ended".
* What we really want is to wait for the activity and the service to both disconnect before we
* tear things down. This method sets a serviceConnected boolean and calls a secondary method
* that performs the aforementioned logic.
*/
public void tearDown() {
Log.d(this, "tearDown");
mServiceConnected = false;
attemptCleanup();
VideoPauseController.getInstance().tearDown();
}
private void attemptFinishActivity() {
final boolean doFinish = (mInCallActivity != null && isActivityStarted());
Log.i(this, "Hide in call UI: " + doFinish);
if (doFinish) {
mInCallActivity.setExcludeFromRecents(true);
mInCallActivity.finish();
if (mAccountSelectionCancelled) {
// This finish is a result of account selection cancellation
// do not include activity ending transition
mInCallActivity.overridePendingTransition(0, 0);
}
}
}
/**
* Called when the UI begins, and starts the callstate callbacks if necessary.
*/
public void setActivity(InCallActivity inCallActivity) {
if (inCallActivity == null) {
throw new IllegalArgumentException("registerActivity cannot be called with null");
}
if (mInCallActivity != null && mInCallActivity != inCallActivity) {
Log.w(this, "Setting a second activity before destroying the first.");
}
updateActivity(inCallActivity);
}
/**
* Called when the UI ends. Attempts to tear down everything if necessary. See
* {@link #tearDown()} for more insight on the tear-down process.
*/
public void unsetActivity(InCallActivity inCallActivity) {
if (inCallActivity == null) {
throw new IllegalArgumentException("unregisterActivity cannot be called with null");
}
if (mInCallActivity == null) {
Log.i(this, "No InCallActivity currently set, no need to unset.");
return;
}
if (mInCallActivity != inCallActivity) {
Log.w(this, "Second instance of InCallActivity is trying to unregister when another"
+ " instance is active. Ignoring.");
return;
}
updateActivity(null);
}
/**
* Updates the current instance of {@link InCallActivity} with the provided one. If a
* {@code null} activity is provided, it means that the activity was finished and we should
* attempt to cleanup.
*/
private void updateActivity(InCallActivity inCallActivity) {
boolean updateListeners = false;
boolean doAttemptCleanup = false;
if (inCallActivity != null) {
if (mInCallActivity == null) {
updateListeners = true;
Log.i(this, "UI Initialized");
} else {
// since setActivity is called onStart(), it can be called multiple times.
// This is fine and ignorable, but we do not want to update the world every time
// this happens (like going to/from background) so we do not set updateListeners.
}
mInCallActivity = inCallActivity;
mInCallActivity.setExcludeFromRecents(false);
// By the time the UI finally comes up, the call may already be disconnected.
// If that's the case, we may need to show an error dialog.
if (mCallList != null && mCallList.getDisconnectedCall() != null) {
maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
}
// When the UI comes up, we need to first check the in-call state.
// If we are showing NO_CALLS, that means that a call probably connected and
// then immediately disconnected before the UI was able to come up.
// If we dont have any calls, start tearing down the UI instead.
// NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
// it has been set.
if (mInCallState == InCallState.NO_CALLS) {
Log.i(this, "UI Initialized, but no calls left. shut down.");
attemptFinishActivity();
return;
}
} else {
Log.i(this, "UI Destroyed");
updateListeners = true;
mInCallActivity = null;
// We attempt cleanup for the destroy case but only after we recalculate the state
// to see if we need to come back up or stay shut down. This is why we do the
// cleanup after the call to onCallListChange() instead of directly here.
doAttemptCleanup = true;
}
// Messages can come from the telephony layer while the activity is coming up
// and while the activity is going down. So in both cases we need to recalculate what
// state we should be in after they complete.
// Examples: (1) A new incoming call could come in and then get disconnected before
// the activity is created.
// (2) All calls could disconnect and then get a new incoming call before the
// activity is destroyed.
//
// b/1122139 - We previously had a check for mServiceConnected here as well, but there are
// cases where we need to recalculate the current state even if the service in not
// connected. In particular the case where startOrFinish() is called while the app is
// already finish()ing. In that case, we skip updating the state with the knowledge that
// we will check again once the activity has finished. That means we have to recalculate the
// state here even if the service is disconnected since we may not have finished a state
// transition while finish()ing.
if (updateListeners) {
onCallListChange(mCallList);
}
if (doAttemptCleanup) {
attemptCleanup();
}
}
private boolean mAwaitingCallListUpdate = false;
public void onBringToForeground(boolean showDialpad) {
Log.i(this, "Bringing UI to foreground.");
bringToForeground(showDialpad);
}
/**
* TODO: Consider listening to CallList callbacks to do this instead of receiving a direct
* method invocation from InCallService.
*/
public void onCallAdded(android.telecom.Call call) {
// Since a call has been added we are no longer waiting for Telecom to send us a
// call.
setBoundAndWaitingForOutgoingCall(false, null);
call.registerCallback(mCallCallback);
}
/**
* TODO: Consider listening to CallList callbacks to do this instead of receiving a direct
* method invocation from InCallService.
*/
public void onCallRemoved(android.telecom.Call call) {
call.unregisterCallback(mCallCallback);
}
public void onCanAddCallChanged(boolean canAddCall) {
for (CanAddCallListener listener : mCanAddCallListeners) {
listener.onCanAddCallChanged(canAddCall);
}
}
/**
* Called when there is a change to the call list.
* Sets the In-Call state for the entire in-call app based on the information it gets from
* CallList. Dispatches the in-call state to all listeners. Can trigger the creation or
* destruction of the UI based on the states that is calculates.
*/
@Override
public void onCallListChange(CallList callList) {
if (mInCallActivity != null && mInCallActivity.getCallCardFragment() != null &&
mInCallActivity.getCallCardFragment().isAnimating()) {
mAwaitingCallListUpdate = true;
return;
}
if (callList == null) {
return;
}
mAwaitingCallListUpdate = false;
InCallState newState = getPotentialStateFromCallList(callList);
InCallState oldState = mInCallState;
Log.d(this, "onCallListChange oldState= " + oldState + " newState=" + newState);
newState = startOrFinishUi(newState);
Log.d(this, "onCallListChange newState changed to " + newState);
// Set the new state before announcing it to the world
Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
mInCallState = newState;
// notify listeners of new state
for (InCallStateListener listener : mListeners) {
Log.d(this, "Notify " + listener + " of state " + mInCallState.toString());
listener.onStateChange(oldState, mInCallState, callList);
}
if (isActivityStarted()) {
final boolean hasCall = callList.getActiveOrBackgroundCall() != null ||
callList.getOutgoingCall() != null;
mInCallActivity.dismissKeyguard(hasCall);
}
}
/**
* Called when there is a new incoming call.
*
* @param call
*/
@Override
public void onIncomingCall(Call call) {
InCallState newState = startOrFinishUi(InCallState.INCOMING);
InCallState oldState = mInCallState;
Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
mInCallState = newState;
for (IncomingCallListener listener : mIncomingCallListeners) {
listener.onIncomingCall(oldState, mInCallState, call);
}
}
@Override
public void onUpgradeToVideo(Call call) {
//NO-OP
}
/**
* Called when a call becomes disconnected. Called everytime an existing call
* changes from being connected (incoming/outgoing/active) to disconnected.
*/
@Override
public void onDisconnect(Call call) {
maybeShowErrorDialogOnDisconnect(call);
// We need to do the run the same code as onCallListChange.
onCallListChange(mCallList);
if (isActivityStarted()) {
mInCallActivity.dismissKeyguard(false);
}
}
/**
* Given the call list, return the state in which the in-call screen should be.
*/
public InCallState getPotentialStateFromCallList(CallList callList) {
InCallState newState = InCallState.NO_CALLS;
if (callList == null) {
return newState;
}
if (callList.getIncomingCall() != null) {
newState = InCallState.INCOMING;
} else if (callList.getWaitingForAccountCall() != null) {
newState = InCallState.WAITING_FOR_ACCOUNT;
} else if (callList.getPendingOutgoingCall() != null) {
newState = InCallState.PENDING_OUTGOING;
} else if (callList.getOutgoingCall() != null) {
newState = InCallState.OUTGOING;
} else if (callList.getActiveCall() != null ||
callList.getBackgroundCall() != null ||
callList.getDisconnectedCall() != null ||
callList.getDisconnectingCall() != null) {
newState = InCallState.INCALL;
}
if (newState == InCallState.NO_CALLS) {
if (mBoundAndWaitingForOutgoingCall) {
return InCallState.OUTGOING;
}
}
return newState;
}
public boolean isBoundAndWaitingForOutgoingCall() {
return mBoundAndWaitingForOutgoingCall;
}
public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
// NOTE: It is possible for there to be a race and have handle become null before
// the circular reveal starts. This should not cause any problems because CallCardFragment
// should fallback to the actual call in the CallList at that point in time to determine
// the theme color.
Log.i(this, "setBoundAndWaitingForOutgoingCall: " + isBound);
mBoundAndWaitingForOutgoingCall = isBound;
mPendingPhoneAccountHandle = handle;
if (isBound && mInCallState == InCallState.NO_CALLS) {
mInCallState = InCallState.OUTGOING;
}
}
@Override
public void onCircularRevealComplete(FragmentManager fm) {
if (mInCallActivity != null) {
mInCallActivity.showCallCardFragment(true);
mInCallActivity.getCallCardFragment().animateForNewOutgoingCall();
CircularRevealFragment.endCircularReveal(mInCallActivity.getFragmentManager());
}
}
public void onShrinkAnimationComplete() {
if (mAwaitingCallListUpdate) {
onCallListChange(mCallList);
}
}
public void addIncomingCallListener(IncomingCallListener listener) {
Preconditions.checkNotNull(listener);
mIncomingCallListeners.add(listener);
}
public void removeIncomingCallListener(IncomingCallListener listener) {
if (listener != null) {
mIncomingCallListeners.remove(listener);
}
}
public void addListener(InCallStateListener listener) {
Preconditions.checkNotNull(listener);
mListeners.add(listener);
}
public void removeListener(InCallStateListener listener) {
if (listener != null) {
mListeners.remove(listener);
}
}
public void addDetailsListener(InCallDetailsListener listener) {
Preconditions.checkNotNull(listener);
mDetailsListeners.add(listener);
}
public void removeDetailsListener(InCallDetailsListener listener) {
if (listener != null) {
mDetailsListeners.remove(listener);
}
}
public void addCanAddCallListener(CanAddCallListener listener) {
Preconditions.checkNotNull(listener);
mCanAddCallListeners.add(listener);
}
public void removeCanAddCallListener(CanAddCallListener listener) {
if (listener != null) {
mCanAddCallListeners.remove(listener);
}
}
public void addOrientationListener(InCallOrientationListener listener) {
Preconditions.checkNotNull(listener);
mOrientationListeners.add(listener);
}
public void removeOrientationListener(InCallOrientationListener listener) {
if (listener != null) {
mOrientationListeners.remove(listener);
}
}
public void addInCallEventListener(InCallEventListener listener) {
Preconditions.checkNotNull(listener);
mInCallEventListeners.add(listener);
}
public void removeInCallEventListener(InCallEventListener listener) {
if (listener != null) {
mInCallEventListeners.remove(listener);
}
}
public ProximitySensor getProximitySensor() {
return mProximitySensor;
}
public void handleAccountSelection(PhoneAccountHandle accountHandle, boolean setDefault) {
if (mCallList != null) {
Call call = mCallList.getWaitingForAccountCall();
if (call != null) {
String callId = call.getId();
TelecomAdapter.getInstance().phoneAccountSelected(callId, accountHandle, setDefault);
}
}
}
public void cancelAccountSelection() {
mAccountSelectionCancelled = true;
if (mCallList != null) {
Call call = mCallList.getWaitingForAccountCall();
if (call != null) {
String callId = call.getId();
TelecomAdapter.getInstance().disconnectCall(callId);
}
}
}
/**
* Hangs up any active or outgoing calls.
*/
public void hangUpOngoingCall(Context context) {
// By the time we receive this intent, we could be shut down and call list
// could be null. Bail in those cases.
if (mCallList == null) {
if (mStatusBarNotifier == null) {
// The In Call UI has crashed but the notification still stayed up. We should not
// come to this stage.
StatusBarNotifier.clearAllCallNotifications(context);
}
return;
}
Call call = mCallList.getOutgoingCall();
if (call == null) {
call = mCallList.getActiveOrBackgroundCall();
}
if (call != null) {
TelecomAdapter.getInstance().disconnectCall(call.getId());
call.setState(Call.State.DISCONNECTING);
mCallList.onUpdate(call);
}
}
/**
* Answers any incoming call.
*/
public void answerIncomingCall(Context context, int videoState) {
// By the time we receive this intent, we could be shut down and call list
// could be null. Bail in those cases.
if (mCallList == null) {
StatusBarNotifier.clearAllCallNotifications(context);
return;
}
Call call = mCallList.getIncomingCall();
if (call != null) {
TelecomAdapter.getInstance().answerCall(call.getId(), videoState);
showInCall(false, false/* newOutgoingCall */);
}
}
/**
* Declines any incoming call.
*/
public void declineIncomingCall(Context context) {
// By the time we receive this intent, we could be shut down and call list
// could be null. Bail in those cases.
if (mCallList == null) {
StatusBarNotifier.clearAllCallNotifications(context);
return;
}
Call call = mCallList.getIncomingCall();
if (call != null) {
TelecomAdapter.getInstance().rejectCall(call.getId(), false, null);
}
}
public void acceptUpgradeRequest(int videoState, Context context) {
Log.d(this, " acceptUpgradeRequest videoState " + videoState);
// Bail if we have been shut down and the call list is null.
if (mCallList == null) {
StatusBarNotifier.clearAllCallNotifications(context);
Log.e(this, " acceptUpgradeRequest mCallList is empty so returning");
return;
}
Call call = mCallList.getVideoUpgradeRequestCall();
if (call != null) {
VideoProfile videoProfile = new VideoProfile(videoState);
call.getVideoCall().sendSessionModifyResponse(videoProfile);
call.setSessionModificationState(Call.SessionModificationState.NO_REQUEST);
}
}
public void declineUpgradeRequest(Context context) {
Log.d(this, " declineUpgradeRequest");
// Bail if we have been shut down and the call list is null.
if (mCallList == null) {
StatusBarNotifier.clearAllCallNotifications(context);
Log.e(this, " declineUpgradeRequest mCallList is empty so returning");
return;
}
Call call = mCallList.getVideoUpgradeRequestCall();
if (call != null) {
VideoProfile videoProfile =
new VideoProfile(call.getVideoState());
call.getVideoCall().sendSessionModifyResponse(videoProfile);
call.setSessionModificationState(Call.SessionModificationState.NO_REQUEST);
}
}
/**
* Returns true if the incall app is the foreground application.
*/
public boolean isShowingInCallUi() {
return (isActivityStarted() && mInCallActivity.isVisible());
}
/**
* Returns true if the activity has been created and is running.
* Returns true as long as activity is not destroyed or finishing. This ensures that we return
* true even if the activity is paused (not in foreground).
*/
public boolean isActivityStarted() {
return (mInCallActivity != null &&
!mInCallActivity.isDestroyed() &&
!mInCallActivity.isFinishing());
}
public boolean isActivityPreviouslyStarted() {
return mIsActivityPreviouslyStarted;
}
public boolean isChangingConfigurations() {
return mIsChangingConfigurations;
}
/*package*/
void updateIsChangingConfigurations() {
mIsChangingConfigurations = false;
if (mInCallActivity != null) {
mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
}
Log.d(this, "IsChangingConfigurations=" + mIsChangingConfigurations);
}
/**
* Called when the activity goes in/out of the foreground.
*/
public void onUiShowing(boolean showing) {
// We need to update the notification bar when we leave the UI because that
// could trigger it to show again.
if (mStatusBarNotifier != null) {
mStatusBarNotifier.updateNotification(mInCallState, mCallList);
}
if (mProximitySensor != null) {
mProximitySensor.onInCallShowing(showing);
}
Intent broadcastIntent = ObjectFactory.getUiReadyBroadcastIntent(mContext);
if (broadcastIntent != null) {
broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
if (showing) {
Log.d(this, "Sending sticky broadcast: ", broadcastIntent);
mContext.sendStickyBroadcast(broadcastIntent);
} else {
Log.d(this, "Removing sticky broadcast: ", broadcastIntent);
mContext.removeStickyBroadcast(broadcastIntent);
}
}
if (showing) {
mIsActivityPreviouslyStarted = true;
} else {
updateIsChangingConfigurations();
}
for (InCallUiListener listener : mInCallUiListeners) {
listener.onUiShowing(showing);
}
}
public void addInCallUiListener(InCallUiListener listener) {
mInCallUiListeners.add(listener);
}
public boolean removeInCallUiListener(InCallUiListener listener) {
return mInCallUiListeners.remove(listener);
}
/*package*/
void onActivityStarted() {
Log.d(this, "onActivityStarted");
notifyVideoPauseController(true);
}
/*package*/
void onActivityStopped() {
Log.d(this, "onActivityStopped");
notifyVideoPauseController(false);
}
private void notifyVideoPauseController(boolean showing) {
Log.d(this, "notifyVideoPauseController: mIsChangingConfigurations=" +
mIsChangingConfigurations);
if (!mIsChangingConfigurations) {
VideoPauseController.getInstance().onUiShowing(showing);
}
}
/**
* Brings the app into the foreground if possible.
*/
public void bringToForeground(boolean showDialpad) {
// Before we bring the incall UI to the foreground, we check to see if:
// 1. It is not currently in the foreground
// 2. We are in a state where we want to show the incall ui (i.e. there are calls to
// be displayed)
// If the activity hadn't actually been started previously, yet there are still calls
// present (e.g. a call was accepted by a bluetooth or wired headset), we want to
// bring it up the UI regardless.
if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
showInCall(showDialpad, false /* newOutgoingCall */);
}
}
public void onPostDialCharWait(String callId, String chars) {
if (isActivityStarted()) {
mInCallActivity.showPostCharWaitDialog(callId, chars);
}
}
/**
* Handles the green CALL key while in-call.
* @return true if we consumed the event.
*/
public boolean handleCallKey() {
Log.v(this, "handleCallKey");
// The green CALL button means either "Answer", "Unhold", or
// "Swap calls", or can be a no-op, depending on the current state
// of the Phone.
/**
* INCOMING CALL
*/
final CallList calls = mCallList;
final Call incomingCall = calls.getIncomingCall();
Log.v(this, "incomingCall: " + incomingCall);
// (1) Attempt to answer a call
if (incomingCall != null) {
TelecomAdapter.getInstance().answerCall(
incomingCall.getId(), VideoProfile.STATE_AUDIO_ONLY);
return true;
}
/**
* STATE_ACTIVE CALL
*/
final Call activeCall = calls.getActiveCall();
if (activeCall != null) {
// TODO: This logic is repeated from CallButtonPresenter.java. We should
// consolidate this logic.
final boolean canMerge = activeCall.can(
android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
final boolean canSwap = activeCall.can(
android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
Log.v(this, "activeCall: " + activeCall + ", canMerge: " + canMerge +
", canSwap: " + canSwap);
// (2) Attempt actions on conference calls
if (canMerge) {
TelecomAdapter.getInstance().merge(activeCall.getId());
return true;
} else if (canSwap) {
TelecomAdapter.getInstance().swap(activeCall.getId());
return true;
}
}
/**
* BACKGROUND CALL
*/
final Call heldCall = calls.getBackgroundCall();
if (heldCall != null) {
// We have a hold call so presumeable it will always support HOLD...but
// there is no harm in double checking.
final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
Log.v(this, "heldCall: " + heldCall + ", canHold: " + canHold);
// (4) unhold call
if (heldCall.getState() == Call.State.ONHOLD && canHold) {
TelecomAdapter.getInstance().unholdCall(heldCall.getId());
return true;
}
}
// Always consume hard keys
return true;
}
/**
* A dialog could have prevented in-call screen from being previously finished.
* This function checks to see if there should be any UI left and if not attempts
* to tear down the UI.
*/
public void onDismissDialog() {
Log.i(this, "Dialog dismissed");
if (mInCallState == InCallState.NO_CALLS) {
attemptFinishActivity();
attemptCleanup();
}
}
/**
* Toggles whether the application is in fullscreen mode or not.
*
* @return {@code true} if in-call is now in fullscreen mode.
*/
public boolean toggleFullscreenMode() {
mIsFullScreen = !mIsFullScreen;
Log.v(this, "toggleFullscreenMode = " + mIsFullScreen);
notifyFullscreenModeChange(mIsFullScreen);
return mIsFullScreen;
}
/**
* Changes the fullscreen mode of the in-call UI.
*
* @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
* otherwise.
*/
public void setFullScreen(boolean isFullScreen) {
Log.v(this, "setFullScreen = " + isFullScreen);
if (mIsFullScreen == isFullScreen) {
Log.v(this, "setFullScreen ignored as already in that state.");
return;
}
mIsFullScreen = isFullScreen;
notifyFullscreenModeChange(mIsFullScreen);
}
/**
* @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
* otherwise.
*/
public boolean isFullscreen() {
return mIsFullScreen;
}
/**
* Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
*
* @param isFullscreenMode {@code True} if entering full screen mode.
*/
public void notifyFullscreenModeChange(boolean isFullscreenMode) {
for (InCallEventListener listener : mInCallEventListeners) {
listener.onFullscreenModeChanged(isFullscreenMode);
}
}
/**
* For some disconnected causes, we show a dialog. This calls into the activity to show
* the dialog if appropriate for the call.
*/
private void maybeShowErrorDialogOnDisconnect(Call call) {
// For newly disconnected calls, we may want to show a dialog on specific error conditions
if (isActivityStarted() && call.getState() == Call.State.DISCONNECTED) {
if (call.getAccountHandle() == null && !call.isConferenceCall()) {
setDisconnectCauseForMissingAccounts(call);
}
mInCallActivity.maybeShowErrorDialogOnDisconnect(call.getDisconnectCause());
}
}
/**
* When the state of in-call changes, this is the first method to get called. It determines if
* the UI needs to be started or finished depending on the new state and does it.
*/
private InCallState startOrFinishUi(InCallState newState) {
Log.d(this, "startOrFinishUi: " + mInCallState + " -> " + newState);
// TODO: Consider a proper state machine implementation
// If the state isn't changing we have already done any starting/stopping of activities in
// a previous pass...so lets cut out early
if (newState == mInCallState) {
return newState;
}
// A new Incoming call means that the user needs to be notified of the the call (since
// it wasn't them who initiated it). We do this through full screen notifications and
// happens indirectly through {@link StatusBarNotifier}.
//
// The process for incoming calls is as follows:
//
// 1) CallList - Announces existence of new INCOMING call
// 2) InCallPresenter - Gets announcement and calculates that the new InCallState
// - should be set to INCOMING.
// 3) InCallPresenter - This method is called to see if we need to start or finish
// the app given the new state.
// 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
// StatusBarNotifier explicitly to issue a FullScreen Notification
// that will either start the InCallActivity or show the user a
// top-level notification dialog if the user is in an immersive app.
// That notification can also start the InCallActivity.
// 5) InCallActivity - Main activity starts up and at the end of its onCreate will
// call InCallPresenter::setActivity() to let the presenter
// know that start-up is complete.
//
// [ AND NOW YOU'RE IN THE CALL. voila! ]
//
// Our app is started using a fullScreen notification. We need to do this whenever
// we get an incoming call. Depending on the current context of the device, either a
// incoming call HUN or the actual InCallActivity will be shown.
final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
// A dialog to show on top of the InCallUI to select a PhoneAccount
final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
// A new outgoing call indicates that the user just now dialed a number and when that
// happens we need to display the screen immediately or show an account picker dialog if
// no default is set. However, if the main InCallUI is already visible, we do not want to
// re-initiate the start-up animation, so we do not need to do anything here.
//
// It is also possible to go into an intermediate state where the call has been initiated
// but Telecomm has not yet returned with the details of the call (handle, gateway, etc.).
// This pending outgoing state can also launch the call screen.
//
// This is different from the incoming call sequence because we do not need to shock the
// user with a top-level notification. Just show the call UI normally.
final boolean mainUiNotVisible = !isShowingInCallUi() || !getCallCardFragmentVisible();
boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
// Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
// outgoing call process, so the UI should be brought up to show an error dialog.
showCallUi |= (InCallState.PENDING_OUTGOING == mInCallState
&& InCallState.INCALL == newState && !isActivityStarted());
// Another exception - InCallActivity is in charge of disconnecting a call with no
// valid accounts set. Bring the UI up if this is true for the current pending outgoing
// call so that:
// 1) The call can be disconnected correctly
// 2) The UI comes up and correctly displays the error dialog.
// TODO: Remove these special case conditions by making InCallPresenter a true state
// machine. Telecom should also be the component responsible for disconnecting a call
// with no valid accounts.
showCallUi |= InCallState.PENDING_OUTGOING == newState && mainUiNotVisible
&& isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
// The only time that we have an instance of mInCallActivity and it isn't started is
// when it is being destroyed. In that case, lets avoid bringing up another instance of
// the activity. When it is finally destroyed, we double check if we should bring it back
// up so we aren't going to lose anything by avoiding a second startup here.
boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
if (activityIsFinishing) {
Log.i(this, "Undo the state change: " + newState + " -> " + mInCallState);
return mInCallState;
}
if (showCallUi || showAccountPicker) {
Log.i(this, "Start in call UI");
showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
} else if (startIncomingCallSequence) {
Log.i(this, "Start Full Screen in call UI");
// We're about the bring up the in-call UI for an incoming call. If we still have
// dialogs up, we need to clear them out before showing incoming screen.
if (isActivityStarted()) {
mInCallActivity.dismissPendingDialogs();
}
if (!startUi(newState)) {
// startUI refused to start the UI. This indicates that it needed to restart the
// activity. When it finally restarts, it will call us back, so we do not actually
// change the state yet (we return mInCallState instead of newState).
return mInCallState;
}
} else if (newState == InCallState.NO_CALLS) {
// The new state is the no calls state. Tear everything down.
attemptFinishActivity();
attemptCleanup();
}
return newState;
}
/**
* Determines whether or not a call has no valid phone accounts that can be used to make the
* call with. Emergency calls do not require a phone account.
*
* @param call to check accounts for.
* @return {@code true} if the call has no call capable phone accounts set, {@code false} if
* the call contains a phone account that could be used to initiate it with, or is an emergency
* call.
*/
public static boolean isCallWithNoValidAccounts(Call call) {
if (call != null && !call.isEmergencyCall()) {
Bundle extras = call.getIntentExtras();
if (extras == null) {
extras = EMPTY_EXTRAS;
}
final List<PhoneAccountHandle> phoneAccountHandles = extras
.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
if ((call.getAccountHandle() == null &&
(phoneAccountHandles == null || phoneAccountHandles.isEmpty()))) {
Log.i(InCallPresenter.getInstance(), "No valid accounts for call " + call);
return true;
}
}
return false;
}
/**
* Sets the DisconnectCause for a call that was disconnected because it was missing a
* PhoneAccount or PhoneAccounts to select from.
* @param call
*/
private void setDisconnectCauseForMissingAccounts(Call call) {
android.telecom.Call telecomCall = call.getTelecommCall();
Bundle extras = telecomCall.getDetails().getIntentExtras();
// Initialize the extras bundle to avoid NPE
if (extras == null) {
extras = new Bundle();
}
final List<PhoneAccountHandle> phoneAccountHandles = extras.getParcelableArrayList(
android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
String scheme = telecomCall.getDetails().getHandle().getScheme();
final String errorMsg = PhoneAccount.SCHEME_TEL.equals(scheme) ?
mContext.getString(R.string.callFailed_simError) :
mContext.getString(R.string.incall_error_supp_service_unknown);
DisconnectCause disconnectCause =
new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
call.setDisconnectCause(disconnectCause);
}
}
private boolean startUi(InCallState inCallState) {
boolean isCallWaiting = mCallList.getActiveCall() != null &&
mCallList.getIncomingCall() != null;
// If the screen is off, we need to make sure it gets turned on for incoming calls.
// This normally works just fine thanks to FLAG_TURN_SCREEN_ON but that only works
// when the activity is first created. Therefore, to ensure the screen is turned on
// for the call waiting case, we finish() the current activity and start a new one.
// There should be no jank from this since the screen is already off and will remain so
// until our new activity is up.
if (isCallWaiting) {
if (mProximitySensor.isScreenReallyOff() && isActivityStarted()) {
Log.i(this, "Restarting InCallActivity to turn screen on for call waiting");
mInCallActivity.finish();
// When the activity actually finishes, we will start it again if there are
// any active calls, so we do not need to start it explicitly here. Note, we
// actually get called back on this function to restart it.
// We return false to indicate that we did not actually start the UI.
return false;
} else {
showInCall(false, false);
}
} else {
mStatusBarNotifier.updateNotification(inCallState, mCallList);
}
return true;
}
/**
* Checks to see if both the UI is gone and the service is disconnected. If so, tear it all
* down.
*/
private void attemptCleanup() {
boolean shouldCleanup = (mInCallActivity == null && !mServiceConnected &&
mInCallState == InCallState.NO_CALLS);
Log.i(this, "attemptCleanup? " + shouldCleanup);
if (shouldCleanup) {
mIsActivityPreviouslyStarted = false;
mIsChangingConfigurations = false;
// blow away stale contact info so that we get fresh data on
// the next set of calls
if (mContactInfoCache != null) {
mContactInfoCache.clearCache();
}
mContactInfoCache = null;
if (mProximitySensor != null) {
removeListener(mProximitySensor);
mProximitySensor.tearDown();
}
mProximitySensor = null;
mAudioModeProvider = null;
if (mStatusBarNotifier != null) {
removeListener(mStatusBarNotifier);
}
mStatusBarNotifier = null;
if (mCallList != null) {
mCallList.removeListener(this);
}
mCallList = null;
mContext = null;
mInCallActivity = null;
mListeners.clear();
mIncomingCallListeners.clear();
mDetailsListeners.clear();
mCanAddCallListeners.clear();
mOrientationListeners.clear();
mInCallEventListeners.clear();
Log.d(this, "Finished InCallPresenter.CleanUp");
}
}
public void showInCall(final boolean showDialpad, final boolean newOutgoingCall) {
Log.i(this, "Showing InCallActivity");
mContext.startActivity(getInCallIntent(showDialpad, newOutgoingCall));
}
public void onServiceBind() {
mServiceBound = true;
}
public void onServiceUnbind() {
InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
mServiceBound = false;
}
public boolean isServiceBound() {
return mServiceBound;
}
public void maybeStartRevealAnimation(Intent intent) {
if (intent == null || mInCallActivity != null) {
return;
}
final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
if (extras == null) {
// Incoming call, just show the in-call UI directly.
return;
}
if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
// Account selection dialog will show up so don't show the animation.
return;
}
final PhoneAccountHandle accountHandle =
intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
final Intent incallIntent = getInCallIntent(false, true);
incallIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
mContext.startActivity(incallIntent);
}
public Intent getInCallIntent(boolean showDialpad, boolean newOutgoingCall) {
final Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(mContext, InCallActivity.class);
if (showDialpad) {
intent.putExtra(InCallActivity.SHOW_DIALPAD_EXTRA, true);
}
intent.putExtra(InCallActivity.NEW_OUTGOING_CALL_EXTRA, newOutgoingCall);
return intent;
}
/**
* Retrieves the current in-call camera manager instance, creating if necessary.
*
* @return The {@link InCallCameraManager}.
*/
public InCallCameraManager getInCallCameraManager() {
synchronized(this) {
if (mInCallCameraManager == null) {
mInCallCameraManager = new InCallCameraManager(mContext);
}
return mInCallCameraManager;
}
}
/**
* Handles changes to the device rotation.
*
* @param rotation The device rotation (one of: {@link Surface#ROTATION_0},
* {@link Surface#ROTATION_90}, {@link Surface#ROTATION_180},
* {@link Surface#ROTATION_270}).
*/
public void onDeviceRotationChange(int rotation) {
Log.d(this, "onDeviceRotationChange: rotation=" + rotation);
// First translate to rotation in degrees.
if (mCallList != null) {
mCallList.notifyCallsOfDeviceRotation(toRotationAngle(rotation));
} else {
Log.w(this, "onDeviceRotationChange: CallList is null.");
}
}
/**
* Converts rotation constants to rotation in degrees.
* @param rotation Rotation constants (one of: {@link Surface#ROTATION_0},
* {@link Surface#ROTATION_90}, {@link Surface#ROTATION_180},
* {@link Surface#ROTATION_270}).
*/
public static int toRotationAngle(int rotation) {
int rotationAngle;
switch (rotation) {
case Surface.ROTATION_0:
rotationAngle = 0;
break;
case Surface.ROTATION_90:
rotationAngle = 90;
break;
case Surface.ROTATION_180:
rotationAngle = 180;
break;
case Surface.ROTATION_270:
rotationAngle = 270;
break;
default:
rotationAngle = 0;
}
return rotationAngle;
}
/**
* Notifies listeners of changes in orientation (e.g. portrait/landscape).
*
* @param orientation The orientation of the device (one of: {@link Surface#ROTATION_0},
* {@link Surface#ROTATION_90}, {@link Surface#ROTATION_180},
* {@link Surface#ROTATION_270}).
*/
public void onDeviceOrientationChange(int orientation) {
for (InCallOrientationListener listener : mOrientationListeners) {
listener.onDeviceOrientationChanged(orientation);
}
}
/**
* Configures the in-call UI activity so it can change orientations or not.
*
* @param allowOrientationChange {@code True} if the in-call UI can change between portrait
* and landscape. {@Code False} if the in-call UI should be locked in portrait.
*/
public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
if (mInCallActivity == null) {
Log.e(this, "InCallActivity is null. Can't set requested orientation.");
return;
}
if (!allowOrientationChange) {
mInCallActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
} else {
mInCallActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
}
public void enableScreenTimeout(boolean enable) {
Log.v(this, "enableScreenTimeout: value=" + enable);
if (mInCallActivity == null) {
Log.e(this, "enableScreenTimeout: InCallActivity is null.");
return;
}
final Window window = mInCallActivity.getWindow();
if (enable) {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
/**
* Returns the space available beside the call card.
*
* @return The space beside the call card.
*/
public float getSpaceBesideCallCard() {
if (mInCallActivity != null && mInCallActivity.getCallCardFragment() != null) {
return mInCallActivity.getCallCardFragment().getSpaceBesideCallCard();
}
return 0;
}
/**
* Returns whether the call card fragment is currently visible.
*
* @return True if the call card fragment is visible.
*/
public boolean getCallCardFragmentVisible() {
if (mInCallActivity != null && mInCallActivity.getCallCardFragment() != null) {
return mInCallActivity.getCallCardFragment().isVisible();
}
return false;
}
/**
* Hides or shows the conference manager fragment.
*
* @param show {@code true} if the conference manager should be shown, {@code false} if it
* should be hidden.
*/
public void showConferenceCallManager(boolean show) {
if (mInCallActivity == null) {
return;
}
mInCallActivity.showConferenceFragment(show);
}
/**
* @return True if the application is currently running in a right-to-left locale.
*/
public static boolean isRtl() {
return TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) ==
View.LAYOUT_DIRECTION_RTL;
}
/**
* Extract background color from call object. The theme colors will include a primary color
* and a secondary color.
*/
public void setThemeColors() {
// This method will set the background to default if the color is PhoneAccount.NO_COLOR.
mThemeColors = getColorsFromCall(mCallList.getFirstCall());
if (mInCallActivity == null) {
return;
}
final Resources resources = mInCallActivity.getResources();
final int color;
if (resources.getBoolean(R.bool.is_layout_landscape)) {
color = resources.getColor(R.color.statusbar_background_color, null);
} else {
color = mThemeColors.mSecondaryColor;
}
mInCallActivity.getWindow().setStatusBarColor(color);
final TaskDescription td = new TaskDescription(
resources.getString(R.string.notification_ongoing_call), null, color);
mInCallActivity.setTaskDescription(td);
}
/**
* @return A palette for colors to display in the UI.
*/
public MaterialPalette getThemeColors() {
return mThemeColors;
}
private MaterialPalette getColorsFromCall(Call call) {
if (call == null) {
return getColorsFromPhoneAccountHandle(mPendingPhoneAccountHandle);
} else {
return getColorsFromPhoneAccountHandle(call.getAccountHandle());
}
}
private MaterialPalette getColorsFromPhoneAccountHandle(PhoneAccountHandle phoneAccountHandle) {
int highlightColor = PhoneAccount.NO_HIGHLIGHT_COLOR;
if (phoneAccountHandle != null) {
final TelecomManager tm = getTelecomManager();
if (tm != null) {
final PhoneAccount account = tm.getPhoneAccount(phoneAccountHandle);
// For single-sim devices, there will be no selected highlight color, so the phone
// account will default to NO_HIGHLIGHT_COLOR.
if (account != null) {
highlightColor = account.getHighlightColor();
}
}
}
return new InCallUIMaterialColorMapUtils(
mContext.getResources()).calculatePrimaryAndSecondaryColor(highlightColor);
}
/**
* @return An instance of TelecomManager.
*/
public TelecomManager getTelecomManager() {
if (mTelecomManager == null) {
mTelecomManager = (TelecomManager)
mContext.getSystemService(Context.TELECOM_SERVICE);
}
return mTelecomManager;
}
InCallActivity getActivity() {
return mInCallActivity;
}
AnswerPresenter getAnswerPresenter() {
return mAnswerPresenter;
}
/**
* Private constructor. Must use getInstance() to get this singleton.
*/
private InCallPresenter() {
}
/**
* All the main states of InCallActivity.
*/
public enum InCallState {
// InCall Screen is off and there are no calls
NO_CALLS,
// Incoming-call screen is up
INCOMING,
// In-call experience is showing
INCALL,
// Waiting for user input before placing outgoing call
WAITING_FOR_ACCOUNT,
// UI is starting up but no call has been initiated yet.
// The UI is waiting for Telecomm to respond.
PENDING_OUTGOING,
// User is dialing out
OUTGOING;
public boolean isIncoming() {
return (this == INCOMING);
}
public boolean isConnectingOrConnected() {
return (this == INCOMING ||
this == OUTGOING ||
this == INCALL);
}
}
/**
* Interface implemented by classes that need to know about the InCall State.
*/
public interface InCallStateListener {
// TODO: Enhance state to contain the call objects instead of passing CallList
public void onStateChange(InCallState oldState, InCallState newState, CallList callList);
}
public interface IncomingCallListener {
public void onIncomingCall(InCallState oldState, InCallState newState, Call call);
}
public interface CanAddCallListener {
public void onCanAddCallChanged(boolean canAddCall);
}
public interface InCallDetailsListener {
public void onDetailsChanged(Call call, android.telecom.Call.Details details);
}
public interface InCallOrientationListener {
public void onDeviceOrientationChanged(int orientation);
}
/**
* Interface implemented by classes that need to know about events which occur within the
* In-Call UI. Used as a means of communicating between fragments that make up the UI.
*/
public interface InCallEventListener {
public void onFullscreenModeChanged(boolean isFullscreenMode);
}
public interface InCallUiListener {
void onUiShowing(boolean showing);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.