text stringlengths 10 2.72M |
|---|
package com.sezioo.permission.beans;
import javax.validation.constraints.Min;
import lombok.Getter;
import lombok.Setter;
public class PageQuery {
@Getter
@Setter
@Min(value = 1,message="当前页码不合法")
private int pageNo;
@Getter
@Setter
@Min(value = 1,message="每页展示数量不合法")
private int pageSize;
@Setter
private int offset;
public int getOffset() {
return (pageNo - 1) * pageSize;
}
}
|
/**
*
*/
package com.needii.dashboard.service;
import java.util.List;
import java.util.Set;
import com.needii.dashboard.model.Category;
import com.needii.dashboard.utils.Option;
/**
* @author kelvin
*
*/
public interface CategoryService {
List<Category> findAll();
List<Category> findAll(Option option);
List<Category> findAll(long parent_id);
List<Category> findByIdIn(Set<Long> ids);
Long count(Option option);
Category findOne(long id);
Category findOne(long id, String language);
void create(Category category);
void update(Category category);
void delete(Category category);
}
|
package com.bofsoft.laio.laiovehiclegps.Widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bofsoft.laio.laiovehiclegps.R;
/**
* 主页测页布局,自定义的每行Item布局
* Created by Bofsoft on 2017/5/16.
*/
public class MyDrawerLayoutItem extends LinearLayout {
private TextView textView;
private ImageView imageView;
private LinearLayout linearLayout;
public MyDrawerLayoutItem(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.widget_mydrawerlayout_item, this);
init();
}
private void init() {
findView();
}
private void findView() {
textView = (TextView) findViewById(R.id.myDrawerLayoutItem_Function);
imageView = (ImageView) findViewById(R.id.myDrawerLayoutItem_Image);
}
//自定义文字
public void setTextView(String function) {
textView.setText(function);
}
//自定义图片
public void setImageView(int resId) {
imageView.setImageResource(resId);
}
}
|
package com.gxtc.huchuan.data;
import com.gxtc.commlibrary.data.BaseRepository;
import com.gxtc.huchuan.bean.NewsBean;
import com.gxtc.huchuan.bean.TopicShareListBean;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.AllApi;
import com.gxtc.huchuan.http.service.LiveApi;
import com.gxtc.huchuan.http.service.MineApi;
import com.gxtc.huchuan.ui.live.intro.TopicShareListContract;
import com.gxtc.huchuan.ui.news.NewsCollectContract;
import java.util.HashMap;
import java.util.List;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by sjr on 2017/2/15.
* 分享榜
*/
public class TopicShareListRepository extends BaseRepository implements TopicShareListContract.Source {
@Override
public void getData(int start, String chatRoomId, String chatInfoId, ApiCallBack<TopicShareListBean> callBack) {
Subscription sub = MineApi.getInstance().getShareNotice(UserManager.getInstance().getToken(),
"0", chatRoomId, chatInfoId, String.valueOf(start))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<TopicShareListBean>>(callBack));
addSub(sub);
}
@Override
public void getSeriesShareData(String id, int start, ApiCallBack<TopicShareListBean> callBack) {
Subscription sub =
LiveApi.getInstance()
.getSeriesShareData(UserManager.getInstance().getToken(), start, id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<TopicShareListBean>>(callBack));
addSub(sub);
}
}
|
package com.mirri.mirribilandia.item;
import android.content.Context;
import android.os.Bundle;
import com.mirri.mirribilandia.R;
import com.mirri.mirribilandia.ui.UrlConnectionAsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class EventContent implements UrlConnectionAsyncTask.UrlConnectionListener {
public static final List<EventContent.EventItem> ITEMS = new ArrayList<>();
public static final Map<String, EventContent.EventItem> ITEM_MAP = new HashMap<>();
public EventContent(Context context){
try {
new UrlConnectionAsyncTask(new URL(context.getString(R.string.event_url)), this, context).execute(new Bundle());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private static void addItem(EventContent.EventItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
@Override
public void handleResponse(JSONObject response, Bundle extra) {
if(response.length() != 0) {
try {
final int code = response.getInt("code");
if(code == 2) {
final JSONArray event = response.getJSONObject("extra").getJSONArray("data");
String dateString = new SimpleDateFormat("yyyy-MM-dd", Locale.US).format(new Date());
for(int i = 0; i < event.length(); i++) {
System.out.println(event.getJSONObject(i).getString("data").substring(0,10));
if(dateString.equals(event.getJSONObject(i).getString("data").substring(0,10))) {
addItem(new EventItem(event.getJSONObject(i).getString("id"), event.getJSONObject(i).getString("nome"), event.getJSONObject(i).getString("descrizione"), event.getJSONObject(i).getString("attrazione"), event.getJSONObject(i).getString("data")));
}
}
} else {
//Toast.makeText(context, "Errore sconosciuto, riprovare", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public static class EventItem {
public final String id;
public final String name;
public final String description;
public final String attraction;
public final String date;
EventItem(String id, String name, String description, String attraction, String date) {
this.id = id;
this.name = name;
this.description = description;
this.attraction = attraction;
this.date = date;
}
}
}
|
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
int number = 0;
String numberString;
Scanner scanner = new Scanner(System.in);
while (number != 11) {
System.out.println("\nEnter a number between 1 and 10: ");
number = scanner.nextInt();
switch (number) {
case 1:
numberString = "The number 1 is UNO in Spanish.";
break;
case 2:
numberString = "The number 2 is DOS in Spanish.";
break;
case 3:
numberString = "The number 3 is TRES in Spanish.";
break;
case 4:
numberString = "The number 4 is CUATRO in Spanish.";
break;
case 5:
numberString = "The number 5 is CINCO in Spanish.";
break;
case 6:
numberString = "The number 6 is SEIS in Spanish.";
break;
case 7:
numberString = "The number 7 is SIETE in Spanish.";
break;
case 8:
numberString = "The number 8 is OCHO in Spanish.";
break;
case 9:
numberString = "The number 9 is NUEVE in Spanish.";
break;
case 10:
numberString = "The number 10 is DIES in Spanish.";
break;
default:
numberString = "Invalid entry.";
}
System.out.println(numberString);
}
}
}
|
/*
* 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 Jobsheet7_1841720126Ela;
/**
*
* @author User
*/
public class Utama1841720126Ela {
public static void main(String[] args) {
System.out.println("Program Testing Class Manager & Staff");
Manager1841720126Ela man[] = new Manager1841720126Ela[2];
Staff1841720126Ela staff1[] = new Staff1841720126Ela[2];
Staff1841720126Ela staff2[] = new Staff1841720126Ela[3];
System.out.println();
man[0] = new Manager1841720126Ela();
man[0].setmNamaEla("Tedjo");
man[0].setmNipEla("101");
man[0].setmGolonganEla("1");
man[0].setmTunjanganEla(5000000);
man[0].setmBagianEla("Administrasi");
System.out.println();
man[1] = new Manager1841720126Ela();
man[1].setmNamaEla("Atika");
man[1].setmNipEla("102");
man[1].setmGolonganEla("1");
man[1].setmTunjanganEla(2500000);
man[1].setmBagianEla("Pemasran");
System.out.println();
staff1[0] = new Staff1841720126Ela();
staff1[0].setmNamaEla("Usman");
staff1[0].setmNipEla("0003");
staff1[0].setmGolonganEla("2");
staff1[0].setmLemburEla(10);
staff1[0].setmGajiLemburEla(10000);
System.out.println();
staff1[1] = new Staff1841720126Ela();
staff1[1].setmNamaEla("Anugrah");
staff1[1].setmNipEla("0005");
staff1[1].setmGolonganEla("2");
staff1[1].setmLemburEla(10);
staff1[1].setmGajiLemburEla(55000);
man[0].setStEla(staff1);
System.out.println();
staff2[0] = new Staff1841720126Ela();
staff2[0].setmNamaEla("Hendra");
staff2[0].setmNipEla("0004");
staff2[0].setmGolonganEla("3");
staff2[0].setmLemburEla(15);
staff2[0].setmGajiLemburEla(5500);
System.out.println();
staff2[1] = new Staff1841720126Ela();
staff2[1].setmNamaEla("Arie");
staff2[1].setmNipEla("0006");
staff2[1].setmGolonganEla("4");
staff2[1].setmLemburEla(5);
staff2[1].setmGajiLemburEla(100000);
System.out.println();
staff2[2] = new Staff1841720126Ela();
staff2[2].setmNamaEla("Mentari");
staff2[2].setmNipEla("0007");
staff2[2].setmGolonganEla("3");
staff2[2].setmLemburEla(6);
staff2[2].setmGajiLemburEla(20000);
man[1].setStEla(staff2);
System.out.println();
man[0].lihatInfoEla();
man[1].lihatInfoEla();
}
}
|
package com.ems.service;
import com.ems.domain.Address;
public class AddressService {
public Address getAddressById(long addressId){
return null;
}
} |
package com.weathair.dto.forum;
import com.weathair.entities.User;
import com.weathair.entities.forum.Topic;
public class PostResponseDto {
private Integer id;
private String title;
private String text;
private Topic topic;
private User user;
public PostResponseDto() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Topic getTopic() {
return topic;
}
public void setTopic(Topic topic) {
this.topic = topic;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
|
/*
* Created on 2004-12-3
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.aof.webapp.action;
import org.apache.struts.action.ActionMapping;
/**
* @author nicebean
*
*/
public class SecureActionMapping extends ActionMapping {
private String permission;
public SecureActionMapping() {
super();
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
}
|
/*
* 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 Repository;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author Lenovo
*/
public class DbContext {
public static final String user_name = "Hospital";
public static final String password = "gWpKKeWvKpbKq8db";
public static final String db_name = "hospital";
public static final String host = "localhost";
public static final int port = 3306;
public static String url = "jdbc:mysql://localhost/" + db_name +"?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url,user_name,password);
}
public void showErrorMessage(SQLException exception){
System.out.println("Error : " + exception.getMessage());
System.out.println("Error code : "+ exception.getErrorCode());
}
}
|
package Graph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
public class Graph {
private ArrayList<String> vertexList; //存储顶点集合
private int[][] edges; //存储图对应的邻结矩阵
private int numOfEdges; //表示边的数目
//定义给数组boolean[], 记录某个结点是否被访问
private boolean[] isVisited;
//构造器,初始化矩阵和vertexList
public Graph(int n){
edges=new int[n][n];
vertexList=new ArrayList<String>(n);
numOfEdges=0;
}
//插入结点
public void insertVertex(String vertex){
vertexList.add(vertex);
}
//添加边
public void insertEdge(int v1, int v2, int weight){
edges[v1][v2]=weight;
edges[v2][v1]=weight;
numOfEdges++;
}
//图中常用的方法
//返回结点的个数
public int getNumOfVertex(){
return vertexList.size();
}
//得到边的数目
public int getNumOfEdges(){
return numOfEdges;
}
//返回结点i(下标)对应的数据 0->"A" 1->"B" 2->"C"
public String getValueByIndex(int i){
return vertexList.get(i);
}
//返回v1和v2的权值
public int getWeight(int v1, int v2){
return edges[v1][v2];
}
//显示图对应的矩阵
public void showGraph(){
for(int[] link:edges){
System.out.println(Arrays.toString(link));
}
}
//得到第一个邻接结点的下标 w
public int getFirstNeighbor(int index){
for(int j=0;j<vertexList.size();j++){
if(edges[index][j]>0) return j;
}
return -1;
}
//根据前一个邻接结点的下标来获取下一个邻接结点
public int getNextNeighbor(int v1, int v2){
for(int j = v2 + 1; j < vertexList.size(); j++) {
if(edges[v1][j] > 0) {
return j;
}
}
return -1;
}
//深度优先遍历算法
private void dfs(boolean[] isVisited, int i){
System.out.print(getValueByIndex(i)+ "->");
isVisited[i]=true;
int w=getFirstNeighbor(i);
while(w!=-1){
if(isVisited[w]!=true) dfs(isVisited,w);
w=getNextNeighbor(i,w);
}
}
//对dfs 进行一个重载, 遍历我们所有的结点,并进行 dfs
public void dfs(){
isVisited=new boolean[vertexList.size()];
for(int i=0;i<vertexList.size();i++)
{
while(isVisited[i]!=true){
dfs(isVisited,i);
}
}
}
//对一个结点进行广度优先遍历的方法
private void bfs(boolean[] isVisited, int i){
int u,w;
LinkedList queue = new LinkedList();
System.out.print(getValueByIndex(i)+ "->");
isVisited[i]=true;
queue.addLast(i);
while(!queue.isEmpty()){
u= (int) queue.removeFirst();
w=getFirstNeighbor(u);
while(w!=-1){
if(isVisited[w]!=true) {
System.out.print(getValueByIndex(w) + "->");
isVisited[w] = true;
queue.addLast(w);
}
w=getNextNeighbor(i,w);
}
}
}
//遍历所有的结点,都进行广度优先搜索
public void bfs() {
isVisited = new boolean[vertexList.size()];
for(int i = 0; i < getNumOfVertex(); i++) {
if(!isVisited[i]) {
bfs(isVisited, i);
}
}
}
public static void main(String[] args) {
int n = 8; //结点的个数
String Vertexs[] = {"1", "2", "3", "4", "5", "6", "7", "8"};
Graph graph=new Graph(n);
for(String s:Vertexs){
graph.insertVertex(s);
}
//更新边的关系
graph.insertEdge(0, 1, 1);
graph.insertEdge(0, 2, 1);
graph.insertEdge(1, 3, 1);
graph.insertEdge(1, 4, 1);
graph.insertEdge(3, 7, 1);
graph.insertEdge(4, 7, 1);
graph.insertEdge(2, 5, 1);
graph.insertEdge(2, 6, 1);
graph.insertEdge(5, 6, 1);
graph.showGraph();
System.out.println("深度遍历");
graph.dfs();
System.out.println("广度优先");
graph.bfs();
}
}
|
package com.junzhao.rongyun.weight;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.junzhao.shanfen.R;
/**
* Created by Administrator on 2018/4/10.
*/
public class DialogAccount extends Dialog {
TextView tv_quxiao, tv_nextpass;
TVNextClick payType;
Context context;
EditText ed_passaccount,ed_passname;
// public DialogZhiFu(@NonNull Context context) {
// super(context);
// this.context=context;
// }
public DialogAccount(@NonNull Activity context) {
super(context);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCanceledOnTouchOutside(false);
setContentView(R.layout.dia_account);
tv_quxiao = findViewById(R.id.tv_quxiao);
tv_nextpass = findViewById(R.id.tv_nextpass);
ed_passaccount = findViewById(R.id.ed_passaccount);
ed_passname = findViewById(R.id.ed_passname);
tv_nextpass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
payType.click(ed_passname.getText().toString(),ed_passaccount.getText().toString());
}
});
tv_quxiao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
public void setTVNextClick(TVNextClick payType) {
this.payType = payType;
}
//回调实现删除
public interface TVNextClick {
void click(String name,String account);
}
}
|
package ltd.getman.testjobproject.domain.models.sort;
import java.util.List;
import ltd.getman.testjobproject.domain.models.mechanizm.Mechanizm;
/**
* Created by Artem Getman on 18.05.17.
* a.e.getman@gmail.com
*/
public class BubbleSort extends BaseSortedClass {
public BubbleSort() {
super(TYPE.BUBBLE);
}
@Override public <T extends Mechanizm> List<T> sort(List<T> mechanizmList) {
for (int i = mechanizmList.size() - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
if (mechanizmList.get(j).compareTo(mechanizmList.get(j + 1)) > 0) {
T t = mechanizmList.get(j);
mechanizmList.set(j, mechanizmList.get(j + 1));
mechanizmList.set(j + 1, t);
}
}
}
return mechanizmList;
}
}
|
package com.github.ytjojo.supernestedlayout;
import android.content.Context;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
/**
* Created by Administrator on 2017/5/5 0005.
*/
public class Utils {
/**
* @return Whether it is possible for the child view of this layout to
* scroll up. Override this if the child view is TOP custom view.
*/
public static boolean canChildScrollUp(View scrollingTarget) {
if (android.os.Build.VERSION.SDK_INT < 14) {
if (scrollingTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) scrollingTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return ViewCompat.canScrollVertically(scrollingTarget, -1) || scrollingTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(scrollingTarget, -1);
}
}
public static float dip2px(Context context,float dip){
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dip * scale + 0.5f);
}
public static int constrain(int input, int a, int b) {
int result = input;
final int min = Math.min(a, b);
final int max = Math.max(a, b);
result = result > min ? result : min;
result = result < max ? result : max;
return result;
}
public static float constrain(float input, float a, float b) {
float result = input;
final float min = Math.min(a, b);
final float max = Math.max(a, b);
result = result > min ? result : min;
result = result < max ? result : max;
return result;
}
public static boolean intersection(Path path1, Path path2, Rect rect){
Region clip = new Region(rect.left,rect.top,rect.right,rect.bottom);
Region region1 = new Region();
region1.setPath(path1, clip);
Region region2 = new Region();
region2.setPath(path2, clip);
if (!region1.quickReject(region2) && region1.op(region2, Region.Op.INTERSECT)) {
// Collision!
return true;
}
return false;
}
public static Path op(Path path1, Path path2, Rect rect,Region.Op op){
Region clip = new Region(rect.left,rect.top,rect.right,rect.bottom);
Region region1 = new Region();
region1.setPath(path1, clip);
Region region2 = new Region();
region2.setPath(path2, clip);
Region region = new Region();
region.op(region1,region2,op);
return region.getBoundaryPath();
}
public static boolean isHeightMatchParentLinearView(View child, SuperNestedLayout.LayoutParams lp){
if(lp ==null){
lp = (SuperNestedLayout.LayoutParams) child.getLayoutParams();
}
if(lp.getLayoutFlags() == SuperNestedLayout.LayoutParams.LAYOUT_FLAG_LINEARVERTICAL&& lp.height == ViewGroup.MarginLayoutParams.MATCH_PARENT){
return true;
}
return false;
}
static boolean objectEquals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
}
|
package com.imooc.files.controller;
import com.imooc.api.controller.files.FileUploadControllerApi;
import com.imooc.exception.GraceException;
import com.imooc.files.FileResource;
import com.imooc.files.GridFSConfig;
import com.imooc.files.service.UploadService;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.pojo.bo.NewAdminBO;
import com.imooc.utils.FileUtils;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.model.Filters;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@RestController
public class FileUploadController implements FileUploadControllerApi {
final static Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@Autowired
private UploadService uploadService;
@Autowired
private FileResource fileResource;
@Autowired
private GridFSBucket gridFSBucket;
@Override
public GraceJSONResult uploadFace(String userId, MultipartFile file) throws IOException {
String path ="";
if (file != null){
// 获得文件名
String fileName = file.getOriginalFilename();
// 判断文件名不能为空
if (StringUtils.isBlank(fileName)){
return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
}else {
String fileNameArr[] = fileName.split("\\.");
//获得后缀
String suffix = fileNameArr[fileNameArr.length-1];
if (!suffix.equalsIgnoreCase("png") &&
!suffix.equalsIgnoreCase("jpg") &&
!suffix.equalsIgnoreCase("jpeg")){
return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
}
path = uploadService.uploadFdfs(file, suffix);
}
}else {
return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
}
if (StringUtils.isNotBlank(path)){
path = "http://1.15.44.134:8888/" + path;
}else {
return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
}
logger.info("path = {}",path);
return GraceJSONResult.ok(path);
}
@Override
public GraceJSONResult uploadSomeFiles(String userId, MultipartFile[] files) throws IOException {
// 声明一个list 用于存放多个图片的地址路径 返回到前端
List<String> imageUrlList = new ArrayList<>();
if (files!=null && files.length>0){
for (MultipartFile file:files){
String path ="";
if (file != null){
// 获得文件名
String fileName = file.getOriginalFilename();
// 判断文件名不能为空
if (StringUtils.isBlank(fileName)){
return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
}else {
String fileNameArr[] = fileName.split("\\.");
//获得后缀
String suffix = fileNameArr[fileNameArr.length-1];
if (!suffix.equalsIgnoreCase("png") &&
!suffix.equalsIgnoreCase("jpg") &&
!suffix.equalsIgnoreCase("jpeg")){
// return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
continue;
}
path = uploadService.uploadFdfs(file, suffix);
}
}else {
//return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
continue;
}
if (StringUtils.isNotBlank(path)){
path = "http://1.15.44.134:8888/" + path;
// TODO 放入前端之前应该先做一次审核
imageUrlList.add(path);
}else {
// return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
continue;
}
logger.info("path = {}",path);
}
}
return GraceJSONResult.ok(imageUrlList);
}
@Override
public GraceJSONResult uploadToGridFS(NewAdminBO bo) throws IOException {
// 获得图片的base64
String img64 = bo.getImg64();
// 将 base64 字符串转换为byte数组
byte[] bytes = new BASE64Decoder().decodeBuffer(img64.trim());
//转换为输入流
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
// 上传到gridfs中
ObjectId fileId = gridFSBucket.uploadFromStream(bo.getUsername() + ".png", byteArrayInputStream);
// 获得文件在gridfs的主键id
String fileIdStr = fileId.toString();
return GraceJSONResult.ok(fileIdStr);
}
@Override
public void readInGridFS(String faceId,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 1 判断是否为空
if (StringUtils.isBlank(faceId) || faceId.equalsIgnoreCase("null")){
GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
}
// 2 从gridFS读取
File adminFace = readGridFSByFaceId(faceId);
// 3 把人脸图片输出到浏览器
FileUtils.downloadFileByStream(response,adminFace);
}
@Override
public GraceJSONResult readFace64InGridFS(String faceId, HttpServletRequest request, HttpServletResponse response) throws IOException {
// 0 获得gridfs中人脸文件
File myfile = readGridFSByFaceId(faceId);
// 1 转换文件为base64
String s = FileUtils.fileToBase64(myfile);
return GraceJSONResult.ok(s);
}
/**
* 下载人脸
* @param faceId
* @return
* @throws FileNotFoundException
*/
private File readGridFSByFaceId(String faceId) throws FileNotFoundException {
GridFSFindIterable id = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));// 条件和faceId做匹配
GridFSFile GridFS = id.first();//列表拿第一个
if (GridFS == null){
GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
}
String fileName = GridFS.getFilename();
File file = new File("/home/yuze/IdeaProjects/imooc_news/temp");
if (!file.exists()){
file.mkdirs();
}
File myFile = new File("/home/yuze/IdeaProjects/imooc_news/temp/"+fileName);
// 创建输出流
FileOutputStream outputStream = new FileOutputStream(myFile);
// 下载到服务器或 本地
gridFSBucket.downloadToStream(new ObjectId(faceId),outputStream);
return myFile;
}
}
|
package am.bizis.cds.dpfdp4;
import java.util.HashSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import am.bizis.cds.IVeta;
import am.bizis.cds.Veta;
import am.bizis.exception.ConditionException;
import am.bizis.exception.MissingElementException;
import am.bizis.exception.MultipleElementsOfSameTypeException;
/**
* Trida EPO tvori z vet Pisemnost
* @author alex
*/
public class EPO {
public EPO() {
}
/**
* Vytvori EPO xml dokument ze zadanych vet
* @param content pole vet. Kazda veta ma stanoveno, nejvyse a nejmene kolikrat se muze v dokumentu vyskytovat
* @return DPFDP4
* @throws ParserConfigurationException
* @throws MissingElementException nesplnena zavislost: jeden element pozaduje vlozeni jineho (napr. predepsane prilohy,
* obecne prilohy, ...) - pozadovany element ovsem nebyl vlozen
* @throws MultipleElementsOfSameTypeException element se vystytuje vicekrat, nez je maximalni dovoleny pocet jeho vyskytu
* @throws ConditionException nesplnena podminka v nektere vete
*/
public Document makeXML(IVeta[] content) throws ParserConfigurationException,MultipleElementsOfSameTypeException,MissingElementException,ConditionException{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder=docFactory.newDocumentBuilder();
Document EPO=docBuilder.newDocument();
//<Pisemnost>
Element rootElement=EPO.createElement("Pisemnost");
rootElement.setAttribute("nazevSW", "BizIS");
rootElement.setAttribute("verzeSW", "1.00.000");
EPO.appendChild(rootElement);
//<DPFDP4>
Element dpfdp4=EPO.createElement("DPFDP4");
dpfdp4.setAttribute("verzePis", "04.01.01");
rootElement.appendChild(dpfdp4);
//mnozina vet, ktere musi byt v dokumentu obsazeny
HashSet<String> reqs=new HashSet<String>();
reqs.add("VetaD");
reqs.add("VetaP");//Pro danovy subjekt musi byt vuplneno DIC nebo RC/IC
//vety
for(IVeta v:content){
if(v.getClass().equals(VetaT.class)||v.getClass().equals(Vetac.class)||v.getClass().equals(VetaU.class)||
v.getClass().equals(VetaU.class)||v.getClass().equals(VetaS.class)){
v=null;
//throw new IllegalArgumentException("Veta T nebyla ocekavana");
}
else if(v!=null){
Element n=(Element)EPO.adoptNode(Veta.getElement(v.toString(), v.getAttrs()));
//kontrola, ze pocet vet jednotlivych typu nepresahuje maximalni hodnoty
if(dpfdp4.getElementsByTagName(n.getTagName()).getLength()<v.getMaxPocet()) dpfdp4.appendChild(n);
else throw new MultipleElementsOfSameTypeException(n.getTagName());
//pokud ma veta zavislosti, vlozime do seznamu
if (v.getDependency()!=null) for(String dep:v.getDependency()){
reqs.add(dep.toString());
}
}
}
//if(j.getLength()>0){//je vlozena veta J - nastavim polozky vety V
//NamedNodeMap nnm=dpfdp4.getElementsByTagName("VetaV").item(0).getAttributes();
//najit VetaO, nastavit KcZd7 - uz mam udelany XML dokument a ted jej modifikuji
/*NamedNodeMap nnm0=dpfdp4.getElementsByTagName("VetaO").item(0).getAttributes();
Element zd7=EPO.createElement("kc_zd7");
zd7.setNodeValue(nnm.getNamedItem("kc_zd7p").getNodeValue());
nnm0.setNamedItem(zd7);*/
//double uhrn=Double.parseDouble(nnm0.getNamedItem("kc_uhrn").getNodeValue())+Double.parseDouble(zd7.getNodeValue())+Double.parseDouble(zd9.getNodeValue());
//nnm0.getNamedItem("kc_uhrn").setNodeValue(uhrn+"");
//}
//vytvorim mnozinu PredepsanychPriloh z dpfdp4
HashSet<String> pps=new HashSet<String>();
NodeList nl=dpfdp4.getElementsByTagName("PredepsanaPriloha");//vsechny predepsane prilohy
for(int i=0;i<nl.getLength();i++){
Node n=nl.item(i).getAttributes().getNamedItem("kod");//kod dane PP
if(n!=null) pps.add(n.getNodeValue());//vlozim do mnoziny
}
//kontrola zavislosti
int obecna=0;
for(String s:reqs){
if(PredepsanaPriloha.getNazvy().contains(s)&&!pps.contains(s))//zavislost je predepsana priloha a dana PP neni v mnozine PP obsazenych v dpfdp4
throw new MissingElementException(s);
else if(s.equals("ObecnaPriloha")) obecna++;
else if(dpfdp4.getElementsByTagName(s).getLength()<1) throw new MissingElementException(s);
}
//kontrola dostatecneho poctu obecnych priloh, tady je problem, pokud se jedna OP pozaduje dvakrat
if(dpfdp4.getElementsByTagName("ObecnaPriloha").getLength()<obecna) throw new MissingElementException("ObecnaPriloha");
//TODO: VetaB
//Element VetaB=getVetaB();
//EPO.appendChild(VetaB);
return EPO;
}
/**
* Vytvori element VetaB zaznam o prilohach prikladanych k DAP DPF
*
* vklada se "pocet listu dane prilohy"
* udela se, az se v praxi otestuje, co se tu vlastne s tema prilohama dela
* a vymysli se, jak ten pocet listu zjistit
*
* @return VetaB
* @throws ParserConfigurationException
*/
//private Element getVetaB() throws ParserConfigurationException{
// DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder docBuilder=docFactory.newDocumentBuilder();
// Document EPO=docBuilder.newDocument();
// Element VetaB=EPO.createElement("VetaB");
// return VetaB;
//}
}
|
package com.programapprentice.app;
/**
* User: program-apprentice
* Date: 9/28/15
* Time: 11:20 PM
*/
public class FindPeakElement_162 {
public int findPeakElement(int[] nums) {
if(nums == null) {
return -1;
}
if(nums.length == 1) {
return 0;
}
int output = -1;
if(nums[1] < nums[0]) {
output = 0;
}
for(int i = 1; i < nums.length; i++) {
if(i == nums.length-1) {
if(nums[i-1] < nums[i]) {
output = i;
}
} else {
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
return i;
}
}
}
return output;
}
}
|
package core;
public class Percentual implements Expressao {
private Expressao valor;
private double percentual;
public Percentual(Expressao valor, double percentual) {
this.valor = valor;
this.percentual = percentual;
}
@Override
public double resolver() {
return valor.resolver() * percentual / 100;
}
}
|
package nl.kasperschipper.alligatorithm;
import nl.kasperschipper.alligatorithm.config.JobConfiguration;
import nl.kasperschipper.alligatorithm.services.JobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AlligatorithmApplication implements ApplicationRunner
{
private Logger LOG = LoggerFactory.getLogger(AlligatorithmApplication.class);
@Value("${console.mode}")
private boolean runInConsoleMode;
private JobService jobService;
public static void main(String[] args)
{
SpringApplication.run(AlligatorithmApplication.class, args);
}
@Override
public void run(ApplicationArguments args)
{
if (runInConsoleMode)
{
LOG.info("Enter input file name:");
String inputFile = System.console().readLine();
LOG.info("Enter expected file name:");
String expectedFile = System.console().readLine();
JobConfiguration config = new JobConfiguration();
config.setInputFilePath(inputFile);
config.setOutputFilePath(expectedFile);
this.jobService.setJobConfiguration(config);
}
this.jobService.performJob();
}
@Autowired
public void setJobService(JobService jobService)
{
this.jobService = jobService;
}
}
|
/*
6.a.- Se va a implementar un simulador de Vehículos. Existen dos tipos de Vehículo: Coche y Camión.
* a) Sus características comunes son la matrícula y la velocidad.
* En el momento de crearlos, la matrícula se recibe por parámetro y la velocidad se inicializa a 0.
* El método toString() de los vehículos devuelve información acerca de la matrícula y la velocidad.
* Además se pueden acelerar, pasando por parámetro la cantidad en km/h que se tiene que acelerar.
*/
package POLIMORFISMO;
public class Vehiculo {
private String matricula;
private double velocidad;
public Vehiculo(String matricula) {
this.matricula = matricula;
velocidad = 0;
}
public String getMatricula() {
return matricula;
}
public double getVelocidad() {
return velocidad;
}
public String toString() {
return "Matricula: " + matricula + "\nVelocidad: " + velocidad + "\n";
}
//Ojo! trows DemasiadoRapidoException es requerido en ñla superclase
//por ser un método redefinido en la subclase camion
public void acelerar(double acelerar) throws DemasiadoRapidoException {
velocidad += acelerar;
}
}
|
package network.nerve.swap.model.po.stable;
import io.nuls.base.basic.AddressTool;
import network.nerve.swap.model.NerveToken;
import java.util.Arrays;
/**
* @author Niels
*/
public class StableSwapPairPo {
private byte[] address;
private NerveToken tokenLP;
private NerveToken[] coins;
private int[] decimalsOfCoins;
public StableSwapPairPo(byte[] address) {
this.address = address;
}
public byte[] getAddress() {
return address;
}
public void setAddress(byte[] address) {
this.address = address;
}
public NerveToken getTokenLP() {
return tokenLP;
}
public void setTokenLP(NerveToken tokenLP) {
this.tokenLP = tokenLP;
}
public NerveToken[] getCoins() {
return coins;
}
public void setCoins(NerveToken[] coins) {
this.coins = coins;
}
public int[] getDecimalsOfCoins() {
return decimalsOfCoins;
}
public void setDecimalsOfCoins(int[] decimalsOfCoins) {
this.decimalsOfCoins = decimalsOfCoins;
}
@Override
public StableSwapPairPo clone() {
StableSwapPairPo po = new StableSwapPairPo(address);
po.setTokenLP(tokenLP);
po.setCoins(coins);
po.setDecimalsOfCoins(decimalsOfCoins);
return po;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("{");
sb.append("\"address\":")
.append('\"').append(AddressTool.getStringAddressByBytes(address)).append('\"');
sb.append(",\"tokenLP\":")
.append('\"').append(tokenLP.str()).append('\"');
sb.append(",\"coins\":[");
for (NerveToken coin : coins) {
sb.append('\"').append(coin.str()).append("\",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
sb.append(",\"decimalsOfCoins\":")
.append(Arrays.toString(decimalsOfCoins));
sb.append("}");
return sb.toString();
}
}
|
package com.example.min.diaryforfamily.data;
/**
* Created by MIN on 2017. 6. 22..
*/
public class Act {
String status;
@Override
public String toString() {
return status;
}
}
|
package io.pigbrain.tree.avltree;
import org.junit.Assert;
import org.junit.Test;
public class AVLTreeTest {
@Test
public void addTest1() {
AVLTree tree = new AVLTree();
tree.add(5);
tree.add(3);
tree.add(1);
AVLNode root = tree.getRoot();
Assert.assertTrue(root.getData() == 3);
Assert.assertTrue(root.getLeftChild().getData() == 1);
Assert.assertTrue(root.getRightChild().getData() == 5);
}
@Test
public void addTest2() {
AVLTree tree = new AVLTree();
tree.add(1);
tree.add(3);
tree.add(5);
AVLNode root = tree.getRoot();
Assert.assertTrue(root.getData() == 3);
Assert.assertTrue(root.getLeftChild().getData() == 1);
Assert.assertTrue(root.getRightChild().getData() == 5);
}
@Test
public void addTest3() {
AVLTree tree = new AVLTree();
tree.add(1);
tree.add(5);
tree.add(3);
AVLNode root = tree.getRoot();
Assert.assertTrue(root.getData() == 3);
Assert.assertTrue(root.getLeftChild().getData() == 1);
Assert.assertTrue(root.getRightChild().getData() == 5);
}
}
|
package com.freeraven.datastructures.strings.uniqueness;
/**
* Created by zvlad on 6/28/16.
*/
public interface CharactersUniquenessChecker {
boolean check(String stringToCheck);
}
|
package com.pykj.design.principle.lawofdemeter.example;
/**
* @description: TODO
* @author: zhangpengxiang
* @time: 2020/4/20 16:33
*/
public class Course {
}
|
package com.ifeng.recom.mixrecall.common.config;
import com.ctrip.framework.apollo.Apollo;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ifeng.recom.mixrecall.common.config.constant.ApolloConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
public class NumRatioConfig {
private static Map<String,Map<String, Map<String,String>>> NumRationConfigMap;
private static Logger logger = LoggerFactory.getLogger(Apollo.class);
static {
NumRationConfigMap = Maps.newHashMap();
}
public void init(Config debugConfig) {
String yml = debugConfig.getProperty(ApolloConstant.Pull_Num_Ratio, "");
loadNumRatioConfig(yml);
}
public void onChangeJob(ConfigChangeEvent configChangeEvent) {
//property未更新,不执行修改
if (!configChangeEvent.changedKeys().contains(ApolloConstant.Test_Users)) {
return;
}
ConfigChange configChange = configChangeEvent.getChange(ApolloConstant.Test_Users);
String yml = configChange.getNewValue();
logger.info("update debug user configuration: {}", yml);
loadNumRatioConfig(yml);
}
/**
* @param updateTestUserMap
*/
// public void updateTestUsers(Map<String, Set<String>> updateTestUserMap) {
// if (updateTestUserMap != null) {
// ColdStartPolicyMap.putAll(updateTestUserMap);
// }
// }
/**
* @param key
* @param userSet
*/
public void putUserRatioMap(String key, Map<String,Map<String,String>> userSet) {
if (NumRationConfigMap != null) {
NumRationConfigMap.put(key, userSet);
}
}
/**
* @param debugerSetKey
* @return
*/
public static Map<String,Map<String,String>> getRatioNum(String userkey) {
Map<String,Map<String,String>> ratioMap = NumRationConfigMap.get(userkey);
if (ratioMap != null) {
return ratioMap;
}
return Maps.newHashMap();
}
/**
* 解析yml配置到动态分配召回数量
*/
public void loadNumRatioConfig(String yml) {
Yaml yaml = new Yaml();
try {
if (StringUtils.isBlank(yml)) {
logger.warn("parse debug user configuration empty! ");
}
Object obj = yaml.load(yml);
Map<String, Object> userMap = (Map) obj;
for (String key : userMap.keySet()) {
Map<String,Map<String,String>> maps = (Map<String,Map<String,String>>) userMap.get(key);
// Set<String> userSet = Sets.newHashSet();
putUserRatioMap(key, maps);
}
} catch (Exception e) {
logger.error("parse debug user configuration error: {}", e);
}
}
public static void main(String[] args){
// NumRatioConfig.init()
Map<String,Map<String,String>> s = NumRatioConfig.getRatioNum(ApolloConstant.Pull_Num_Ratio);
int ss = 5;
}
}
|
package com.aikiinc.coronavirus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.aikiinc.coronavirus.model.CoronaVirus;
import com.aikiinc.coronavirus.service.CoronaVirusProcessing;
import com.aikiinc.coronavirus.service.CoronaVirusService;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@CrossOrigin(origins = { "http://localhost:9000", "http://localhost:4200", "https://pure-shore-41784.herokuapp.com" })
@RestController
@RequestMapping("/api/virus/corona")
public class CornaVirusController implements CoronaVirusService {
private Logger log = LoggerFactory.getLogger(CornaVirusController.class);
@Autowired
private CoronaVirusProcessing coronaVirusProcessing;
public CornaVirusController(CoronaVirusProcessing process) {
this.coronaVirusProcessing = process;
if (coronaVirusProcessing != null) {
log.info("Calling data processing");
coronaVirusProcessing.process();
}
}
@GetMapping(value = "/")
public ModelAndView index() {
ModelAndView mv = new ModelAndView();
mv.addObject("message", "Hello message");
mv.setViewName("index.html");
return mv;
}
@GetMapping(value = "/dateLoaded")
public @ResponseBody String getDateLoaded() {
return coronaVirusProcessing.getDateLoaded();
}
@GetMapping(value = "/regionsMap")
public Map<String, List<CoronaVirus>> getCoronaVirusRegionsMap() {
return coronaVirusProcessing.getCoronaVirusRegionsMap();
}
@GetMapping(value = "/regions")
public Set<String> getRegionKeys() {
return coronaVirusProcessing.getRegionKeys();
}
@GetMapping(value = "/list")
public List<CoronaVirus> getCoronaVirusList() {
log.info("List all");
return coronaVirusProcessing.getCoronaVirusList();
}
@GetMapping(value = "/region")
public List<CoronaVirus> getCoronaVirusByRegion(@RequestParam("region") String region) {
return coronaVirusProcessing.getCoronaVirusByRegion(region);
}
@GetMapping(value = "/countyKeys")
public Set<String> getCountyBoroughKeys() {
return coronaVirusProcessing.getCountyBoroughKeys();
}
@GetMapping(value = "/countyMap")
public Map<String, List<CoronaVirus>> getCoronaVirusCountyBoroughMap() {
return coronaVirusProcessing.getCoronaVirusCountyBoroughMap();
}
}
|
package com.eighteengray.procamera.model.imageloader;
import android.content.Context;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
/**
* Created by Razer on 2017/12/6.
*/
public class GlideImageLoader implements IImageLoader
{
private static IImageLoader instance;
private static Context context;
private GlideImageLoader(Context c){
this.context = c;
}
public static IImageLoader getInstance(){
if(instance == null){
synchronized (GlideImageLoader.class){
if(instance == null){
instance = new GlideImageLoader(context);
}
}
}
return instance;
}
@Override
public void loadImage(String uri, ImageView imageView)
{
Glide.with(context).load(uri).into(imageView);
}
@Override
public void loadImage(String uri, ImageView imageView, ImageLoadListener imageLoadListener)
{
Glide.with(context).load(uri).into(imageView);
}
}
|
package com.designpattern.dp4singletonpattern.lazy.v4;
/**
* 静态内部类单例模式(懒汉式单例模式 )
* 只有在外部用到的时候 内部类 才会加载
* 兼顾 饿汉单例 的内存浪费问题 和 懒汉单例的synchronized性能问题
*/
public class LazyInnerClassSingleton {
// 使用LazySimpleSingleton的时候,默认会先初始化内部类,不使用的话内部类是不会加载的
private LazyInnerClassSingleton(){
// 在构造函数中增加判断 防止【反射破坏单例模式】
if(LazyHolder.LAZY!=null){
throw new RuntimeException("不允许创建多个单例");
}
}
// static 单例的内存空间共享 final保证方法不会被重写重载
public static final LazyInnerClassSingleton getInstance(){
// 在返回结果之前,才会(一定会)先加载内部类
return LazyHolder.LAZY;
}
// static 内存空间共享 持有单例对象的静态内部类 在用到的时候才会被加载
private static class LazyHolder{
// static 单例的内存空间共享 final保证方法不会被重写重载
private static final LazyInnerClassSingleton LAZY = new LazyInnerClassSingleton();
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.web.socket.sockjs.client;
import java.net.URI;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.Lifecycle;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketHttpHeaders;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec;
import org.springframework.web.socket.sockjs.frame.SockJsMessageCodec;
import org.springframework.web.socket.sockjs.transport.TransportType;
import org.springframework.web.util.UriComponentsBuilder;
/**
* A SockJS implementation of
* {@link org.springframework.web.socket.client.WebSocketClient WebSocketClient}
* with fallback alternatives that simulate a WebSocket interaction through plain
* HTTP streaming and long polling techniques.
*
* <p>Implements {@link Lifecycle} in order to propagate lifecycle events to
* the transports it is configured with.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.1
* @see <a href="https://github.com/sockjs/sockjs-client">https://github.com/sockjs/sockjs-client</a>
* @see org.springframework.web.socket.sockjs.client.Transport
*/
public class SockJsClient implements WebSocketClient, Lifecycle {
private static final boolean jackson2Present = ClassUtils.isPresent(
"com.fasterxml.jackson.databind.ObjectMapper", SockJsClient.class.getClassLoader());
private static final Log logger = LogFactory.getLog(SockJsClient.class);
private static final Set<String> supportedProtocols = Set.of("ws", "wss", "http", "https");
private final List<Transport> transports;
@Nullable
private String[] httpHeaderNames;
private InfoReceiver infoReceiver;
@Nullable
private SockJsMessageCodec messageCodec;
@Nullable
private TaskScheduler connectTimeoutScheduler;
private volatile boolean running;
private final Map<URI, ServerInfo> serverInfoCache = new ConcurrentHashMap<>();
/**
* Create a {@code SockJsClient} with the given transports.
* <p>If the list includes an {@link XhrTransport} (or more specifically an
* implementation of {@link InfoReceiver}) the instance is used to initialize
* the {@link #setInfoReceiver(InfoReceiver) infoReceiver} property, or
* otherwise is defaulted to {@link RestTemplateXhrTransport}.
* @param transports the (non-empty) list of transports to use
*/
public SockJsClient(List<Transport> transports) {
Assert.notEmpty(transports, "No transports provided");
this.transports = new ArrayList<>(transports);
this.infoReceiver = initInfoReceiver(transports);
if (jackson2Present) {
this.messageCodec = new Jackson2SockJsMessageCodec();
}
}
private static InfoReceiver initInfoReceiver(List<Transport> transports) {
for (Transport transport : transports) {
if (transport instanceof InfoReceiver infoReceiver) {
return infoReceiver;
}
}
return new RestTemplateXhrTransport();
}
/**
* The names of HTTP headers that should be copied from the handshake headers
* of each call to {@link SockJsClient#doHandshake(WebSocketHandler, WebSocketHttpHeaders, URI)}
* and also used with other HTTP requests issued as part of that SockJS
* connection, e.g. the initial info request, XHR send or receive requests.
* <p>By default if this property is not set, all handshake headers are also
* used for other HTTP requests. Set it if you want only a subset of handshake
* headers (e.g. auth headers) to be used for other HTTP requests.
* @param httpHeaderNames the HTTP header names
*/
public void setHttpHeaderNames(@Nullable String... httpHeaderNames) {
this.httpHeaderNames = httpHeaderNames;
}
/**
* The configured HTTP header names to be copied from the handshake
* headers and also included in other HTTP requests.
*/
@Nullable
public String[] getHttpHeaderNames() {
return this.httpHeaderNames;
}
/**
* Configure the {@code InfoReceiver} to use to perform the SockJS "Info"
* request before the SockJS session starts.
* <p>If the list of transports provided to the constructor contained an
* {@link XhrTransport} or an implementation of {@link InfoReceiver} that
* instance would have been used to initialize this property, or otherwise
* it defaults to {@link RestTemplateXhrTransport}.
* @param infoReceiver the transport to use for the SockJS "Info" request
*/
public void setInfoReceiver(InfoReceiver infoReceiver) {
Assert.notNull(infoReceiver, "InfoReceiver is required");
this.infoReceiver = infoReceiver;
}
/**
* Return the configured {@code InfoReceiver} (never {@code null}).
*/
public InfoReceiver getInfoReceiver() {
return this.infoReceiver;
}
/**
* Set the SockJsMessageCodec to use.
* <p>By default {@link org.springframework.web.socket.sockjs.frame.Jackson2SockJsMessageCodec
* Jackson2SockJsMessageCodec} is used if Jackson is on the classpath.
*/
public void setMessageCodec(SockJsMessageCodec messageCodec) {
Assert.notNull(messageCodec, "SockJsMessageCodec is required");
this.messageCodec = messageCodec;
}
/**
* Return the SockJsMessageCodec to use.
*/
public SockJsMessageCodec getMessageCodec() {
Assert.state(this.messageCodec != null, "No SockJsMessageCodec set");
return this.messageCodec;
}
/**
* Configure a {@code TaskScheduler} for scheduling a connect timeout task
* where the timeout value is calculated based on the duration of the initial
* SockJS "Info" request. The connect timeout task ensures a more timely
* fallback but is otherwise entirely optional.
* <p>By default this is not configured in which case a fallback may take longer.
* @param connectTimeoutScheduler the task scheduler to use
*/
public void setConnectTimeoutScheduler(TaskScheduler connectTimeoutScheduler) {
this.connectTimeoutScheduler = connectTimeoutScheduler;
}
@Override
public void start() {
if (!isRunning()) {
this.running = true;
for (Transport transport : this.transports) {
if (transport instanceof Lifecycle lifecycle && !lifecycle.isRunning()) {
lifecycle.start();
}
}
}
}
@Override
public void stop() {
if (isRunning()) {
this.running = false;
for (Transport transport : this.transports) {
if (transport instanceof Lifecycle lifecycle && lifecycle.isRunning()) {
lifecycle.stop();
}
}
}
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public CompletableFuture<WebSocketSession> execute(
WebSocketHandler handler, String uriTemplate, Object... uriVars) {
Assert.notNull(uriTemplate, "uriTemplate must not be null");
URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri();
return execute(handler, null, uri);
}
@Override
public final CompletableFuture<WebSocketSession> execute(
WebSocketHandler handler, @Nullable WebSocketHttpHeaders headers, URI url) {
Assert.notNull(handler, "WebSocketHandler is required");
Assert.notNull(url, "URL is required");
String scheme = url.getScheme();
if (!supportedProtocols.contains(scheme)) {
throw new IllegalArgumentException("Invalid scheme: '" + scheme + "'");
}
CompletableFuture<WebSocketSession> connectFuture = new CompletableFuture<>();
try {
SockJsUrlInfo sockJsUrlInfo = new SockJsUrlInfo(url);
ServerInfo serverInfo = getServerInfo(sockJsUrlInfo, getHttpRequestHeaders(headers));
createRequest(sockJsUrlInfo, headers, serverInfo).connect(handler, connectFuture);
}
catch (Exception exception) {
if (logger.isErrorEnabled()) {
logger.error("Initial SockJS \"Info\" request to server failed, url=" + url, exception);
}
connectFuture.completeExceptionally(exception);
}
return connectFuture;
}
@Nullable
private HttpHeaders getHttpRequestHeaders(@Nullable HttpHeaders webSocketHttpHeaders) {
if (getHttpHeaderNames() == null || webSocketHttpHeaders == null) {
return webSocketHttpHeaders;
}
else {
HttpHeaders httpHeaders = new HttpHeaders();
for (String name : getHttpHeaderNames()) {
List<String> values = webSocketHttpHeaders.get(name);
if (values != null) {
httpHeaders.put(name, values);
}
}
return httpHeaders;
}
}
private ServerInfo getServerInfo(SockJsUrlInfo sockJsUrlInfo, @Nullable HttpHeaders headers) {
URI infoUrl = sockJsUrlInfo.getInfoUrl();
ServerInfo info = this.serverInfoCache.get(infoUrl);
if (info == null) {
long start = System.currentTimeMillis();
String response = this.infoReceiver.executeInfoRequest(infoUrl, headers);
long infoRequestTime = System.currentTimeMillis() - start;
info = new ServerInfo(response, infoRequestTime);
this.serverInfoCache.put(infoUrl, info);
}
return info;
}
private DefaultTransportRequest createRequest(
SockJsUrlInfo urlInfo, @Nullable HttpHeaders headers, ServerInfo serverInfo) {
List<DefaultTransportRequest> requests = new ArrayList<>(this.transports.size());
for (Transport transport : this.transports) {
for (TransportType type : transport.getTransportTypes()) {
if (serverInfo.isWebSocketEnabled() || !TransportType.WEBSOCKET.equals(type)) {
requests.add(new DefaultTransportRequest(urlInfo, headers, getHttpRequestHeaders(headers),
transport, type, getMessageCodec()));
}
}
}
if (CollectionUtils.isEmpty(requests)) {
throw new IllegalStateException(
"No transports: " + urlInfo + ", webSocketEnabled=" + serverInfo.isWebSocketEnabled());
}
for (int i = 0; i < requests.size() - 1; i++) {
DefaultTransportRequest request = requests.get(i);
Principal user = getUser();
if (user != null) {
request.setUser(user);
}
if (this.connectTimeoutScheduler != null) {
request.setTimeoutValue(serverInfo.getRetransmissionTimeout());
request.setTimeoutScheduler(this.connectTimeoutScheduler);
}
request.setFallbackRequest(requests.get(i + 1));
}
return requests.get(0);
}
/**
* Return the user to associate with the SockJS session and make available via
* {@link org.springframework.web.socket.WebSocketSession#getPrincipal()}.
* <p>By default this method returns {@code null}.
* @return the user to associate with the session (possibly {@code null})
*/
@Nullable
protected Principal getUser() {
return null;
}
/**
* By default, the result of a SockJS "Info" request, including whether the
* server has WebSocket disabled and how long the request took (used for
* calculating transport timeout time) is cached. This method can be used to
* clear that cache hence causing it to re-populate.
*/
public void clearServerInfoCache() {
this.serverInfoCache.clear();
}
/**
* A simple value object holding the result from a SockJS "Info" request.
*/
private static class ServerInfo {
private final boolean webSocketEnabled;
private final long responseTime;
public ServerInfo(String response, long responseTime) {
this.responseTime = responseTime;
this.webSocketEnabled = !response.matches(".*[\"']websocket[\"']\\s*:\\s*false.*");
}
public boolean isWebSocketEnabled() {
return this.webSocketEnabled;
}
public long getRetransmissionTimeout() {
return (this.responseTime > 100 ? 4 * this.responseTime : this.responseTime + 300);
}
}
}
|
package com.example.dto;
import java.util.Date;
import java.util.List;
public abstract class AbstractDTO<T> {
private Long id;
private Date createdDate;
private String createdBy;
private Date modifiedDate;
private String modifiedBy;
private List<T> results;
private long totalItem;
private int totalPage;
private int limit;
private int currentPage;
private String keySearch;
private String columnName;
private String sortType;
public String getSortType() {
return sortType;
}
public void setSortType(String sortType) {
this.sortType = sortType;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getKeySearch() {
return keySearch;
}
public void setKeySearch(String keySearch) {
this.keySearch = keySearch;
}
public long getTotalItem() {
return totalItem;
}
public void setTotalItem(long totalItem) {
this.totalItem = totalItem;
}
public List<T> getResults() {
return results;
}
public void setResults(List<T> results) {
this.results = results;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
}
|
package com.thoughtworks.shoppingweb.web;
import com.thoughtworks.shoppingweb.domain.Address;
import com.thoughtworks.shoppingweb.domain.ShopCart;
import com.thoughtworks.shoppingweb.service.AddressService;
import com.thoughtworks.shoppingweb.service.ShopCartService;
import com.thoughtworks.shoppingweb.service.UserService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
/**
* Created by szwang on 4/12/16.
*/
public class ShopCartControllerTest {
@InjectMocks
ShopCartController shopCartController;
@Mock
ShopCartService shopCartService;
@Mock
UserService userService;
@Mock
AddressService addressService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
shopCartController.shopCartService = shopCartService;
shopCartController.userService=userService;
shopCartController.addressService=addressService;
}
@Test
public void shouldReturnTrueWhenInsertShopCartSuccess() throws Exception {
ShopCart shopCart=new ShopCart();
Mockito.when(shopCartService.insertToCart(shopCart)).thenReturn(true);
ResponseEntity responseEntity=shopCartController.productCart(shopCart);
assertEquals(HttpStatus.OK,responseEntity.getStatusCode());
assertEquals(true,responseEntity.getBody());
}
@Test
public void shouldReturnFalseWhenInsertShopCartFail() throws Exception {
ShopCart shopCart=new ShopCart();
Mockito.when(shopCartService.insertToCart(shopCart)).thenReturn(false);
ResponseEntity responseEntity=shopCartController.productCart(shopCart);
assertEquals(HttpStatus.OK,responseEntity.getStatusCode());
assertEquals(false,responseEntity.getBody());
}
@Test
public void shouldReturnNotNullWhenSelectShopCartSuccess() throws Exception {
String userName="wsz";
Mockito.when(shopCartService.cartProduct(userName)).thenReturn(new ArrayList<ShopCart>());
Mockito.when(shopCartService.allCartProduct(userName)).thenReturn(new ArrayList<ShopCart>());
Mockito.when(userService.searchUser(userName)).thenReturn(true);
ResponseEntity responseEntity=shopCartController.shopCartShow(userName);
Map map=new HashMap<String, Object>();
map.put("cartProduct",new ArrayList<ShopCart>());
map.put("allCartProduct",new ArrayList<ShopCart>());
map.put("searchUser",true);
ResponseEntity responseEntity1= new ResponseEntity<Map>((Map<String, Object>) map, HttpStatus.OK);
assertEquals(responseEntity1,responseEntity);
}
@Test
public void shouldReturnNotNullWhenGoToMySHopCartSuccess() throws Exception {
String userName="wsz";
List<ShopCart> shopCarts=new ArrayList<ShopCart>();
List<Address> addresses=new ArrayList<Address>();
Mockito.when(shopCartService.allCartProduct(userName)).thenReturn(shopCarts);
Mockito.when(addressService.getaddresses(userName)).thenReturn(addresses);
Model returnModel = new ExtendedModelMap();
shopCartController.goToMyShopCart(userName,returnModel);
List<ShopCart> shopCarts1 = (List<ShopCart>) returnModel.asMap().get("allCartProduct");
assertEquals(shopCarts, shopCarts1);
List<Address> addresses1 = (List<Address>) returnModel.asMap().get("allAddresses");
assertEquals(addresses, addresses1);
}
} |
package com.example.tourguiderapp.view;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.tourguiderapp.R;
public class ResetPasswordActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
listenBackLogin();
listenDone();
}
private void listenBackLogin(){
findViewById(R.id.btnBackLogin).setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(ResetPasswordActivity.this, ForgotPasswordActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
}
private void listenDone(){
findViewById(R.id.btnDone).setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(ResetPasswordActivity.this, CitiesActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
}
}
|
package application.address.model;
import messageCenter.ReceiverBTP;
/**
* Created by leo on 11/02/2015.
* ljsa at cin.ufpe.br
*/
public class UserBTP extends User {
public UserBTP (String username, String ip) {
super(username, ip);
}
@Override
public void login() {
}
@Override
public boolean connectServer(String ip, String port) {
return false;
}
@Override
public void connectionRequest(User user2) {
}
@Override
public void receiveConnectionRequest(User user1) {
}
@Override
public void openServer() {
}
@Override
public void acceptRequest() {
}
@Override
public void openClient() {
}
@Override
public void sendMessage(String destinationIp) {
}
@Override
public void receiveACK() {
}
} |
package com.fhate.studyhelper.model;
import java.util.ArrayList;
public class ScheduleDay {
public String day;
public ArrayList<Lesson> lessons;
public ScheduleDay(String day, ArrayList<Lesson> lessons) {
this.day = day;
this.lessons = lessons;
}
}
|
package com.metoo.foundation.test;
import java.util.ArrayList;
import java.util.Iterator;
import org.junit.Test;
public class IteratorTest {
@Test
public void test1() {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
arrayList.add(Integer.valueOf(i));
}
// 复现方法一
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
Integer integer = iterator.next();
if (integer.intValue() == 5) {
arrayList.remove(integer);
}
}
// 复现方法二
iterator = arrayList.iterator();
for (Integer value : arrayList) {
Integer integer = iterator.next();
if (integer.intValue() == 5) {
arrayList.remove(integer);
}
}
}
}
|
package com.jay.mvp_dagger2_sample.ui.activity.splash;
/**
* Created by JINISYS on 26/03/2018.
*/
public interface ISplashPresenter {
void testConnection();
}
|
package com.npaw.responseservice;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ResponseServiceApplication {
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
try {
SpringApplication.run(ResponseServiceApplication.class, args);
} catch (Throwable e) {
if(e.getClass().getName().contains("SilentExitException")) {
LOGGER.debug("Spring is restarting the main thread - See spring-boot-devtools");
} else {
LOGGER.error("Application crashed!", e);
}
}
}
}
|
package com.getkhaki.api.bff.hibernate.dialect;
import org.hibernate.dialect.MariaDB103Dialect;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.type.StandardBasicTypes;
public class CustomMariaDbDialect extends MariaDB103Dialect {
public CustomMariaDbDialect() {
super();
registerFunction("timestampdiff",
new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "timestampdiff(?1, ?2, ?3)")
);
registerFunction("dayofweek",
new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "DAYOFWEEK(?1)")
);
}
}
|
package leyou.mapper;
public interface CustomerMapper {
}
|
import java.util.*;
public class ComponentTable {
final private ArrayList<String> usedKeys = new ArrayList<>();
final private Hashtable<String, String> test = new Hashtable<>();
ComponentTable() {}
}
|
package evolutionYoutube;
import java.util.List;
import com.vaadin.navigator.View;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.Button.ClickEvent;
import database.BD_general;
public class Videos_subidos extends Videos_subidos_ventana implements View {
/**
*
*/
private static final long serialVersionUID = 1L;
public Mi_perfil _unnamed_Mi_perfil_;
public Lista_videos_subidos _unnamed_Lista_videos_subidos_;
public Videos_subidos() {
lista_videos_subidos.addComponent(new Lista_videos_subidos());
principal.addClickListener(new Button.ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
((MyUI) UI.getCurrent()).usuario_registrado();
}
});
micuenta.addClickListener(new Button.ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
((MyUI) UI.getCurrent()).mi_perfil_registrado();
}
});
videos_subidos.addClickListener(new Button.ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
((MyUI) UI.getCurrent()).videos_subidos();
}
});
mis_listas.addClickListener(new Button.ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
((MyUI) UI.getCurrent()).mis_listas();
}
});
suscripciones.addClickListener(new Button.ClickListener() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void buttonClick(ClickEvent event) {
((MyUI) UI.getCurrent()).suscripciones();
}
});
}
} |
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Random;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author INM381-User
*/
public class VPSSearchResult implements Serializable {
private int _vpsSearchResultID;
private Vehicle[] searchResult;
private static final long serialVersionUID = 742L;
public VPSSearchResult() {
Random rand = new Random();
int n =rand.nextInt(50)+1;
this._vpsSearchResultID =n;
this.searchResult =new Vehicle[20];
}
/**
* @return the searchResult
*/
public Vehicle[] getSearchResult() {
return searchResult;
}
/**
* @param searchResult the searchResult to set
*/
public void setSearchResult(Vehicle[] searchResult) {
this.searchResult = searchResult;
}
/**
* @return the _vpsSearchResultID
*/
public int getVpsSearchResultID() {
return _vpsSearchResultID;
}
/**
* @param vpsSearchResultID the _vpsSearchResultID to set
*/
public void setVpsSearchResultID(int vpsSearchResultID) {
this._vpsSearchResultID = vpsSearchResultID;
}
}
|
package common.db.task;
import java.util.List;
import common.db.entity.Task;
public interface TaskHandler {
int processTask(List<Task> task);
}
|
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddGoodsListGetResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.Map;
import java.util.TreeMap;
public class PddGoodsListGetRequest extends PopBaseHttpRequest<PddGoodsListGetResponse>{
/**
* 商品外部编码(sku),同其他接口中的outer_id 、out_id、out_sku_sn、outer_sku_sn、out_sku_id、outer_sku_id 都为商家编码(sku维度)。outer_id,is_onsale,goods_name三选一,优先级is_onsale>outer_id>goods_name
*/
@JsonProperty("outer_id")
private String outerId;
/**
* 上下架状态,0-下架,1-上架,outer_id,is_onsale,goods_name三选一,优先级is_onsale>outer_id>goods_name
*/
@JsonProperty("is_onsale")
private Integer isOnsale;
/**
* 商品名称模糊查询,outer_id,is_onsale,goods_name三选一,优先级is_onsale>outer_id>goods_name
*/
@JsonProperty("goods_name")
private String goodsName;
/**
* 返回数量,默认 100,最大100。
*/
@JsonProperty("page_size")
private Integer pageSize;
/**
* 返回页码 默认 1,页码从 1 开始PS:当前采用分页返回,数量和页数会一起传,如果不传,则采用 默认值
*/
@JsonProperty("page")
private Integer page;
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.goods.list.get";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddGoodsListGetResponse> getResponseClass() {
return PddGoodsListGetResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
if(outerId != null) {
paramsMap.put("outer_id", outerId.toString());
}
if(isOnsale != null) {
paramsMap.put("is_onsale", isOnsale.toString());
}
if(goodsName != null) {
paramsMap.put("goods_name", goodsName.toString());
}
if(pageSize != null) {
paramsMap.put("page_size", pageSize.toString());
}
if(page != null) {
paramsMap.put("page", page.toString());
}
return paramsMap;
}
public void setOuterId(String outerId) {
this.outerId = outerId;
}
public void setIsOnsale(Integer isOnsale) {
this.isOnsale = isOnsale;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void setPage(Integer page) {
this.page = page;
}
} |
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://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.springframework.web.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import org.springframework.core.ResolvableType;
import org.springframework.core.log.LogFormatUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
/**
* Used by {@link DefaultRestClient} and {@link DefaultRestClientBuilder}.
*
* @author Arjen Poutsma
* @since 6.1
*/
final class StatusHandler {
private final ResponsePredicate predicate;
private final RestClient.ResponseSpec.ErrorHandler errorHandler;
private StatusHandler(ResponsePredicate predicate, RestClient.ResponseSpec.ErrorHandler errorHandler) {
this.predicate = predicate;
this.errorHandler = errorHandler;
}
public static StatusHandler of(Predicate<HttpStatusCode> predicate,
RestClient.ResponseSpec.ErrorHandler errorHandler) {
Assert.notNull(predicate, "Predicate must not be null");
Assert.notNull(errorHandler, "ErrorHandler must not be null");
return new StatusHandler(response -> predicate.test(response.getStatusCode()), errorHandler);
}
public static StatusHandler fromErrorHandler(ResponseErrorHandler errorHandler) {
Assert.notNull(errorHandler, "ResponseErrorHandler must not be null");
return new StatusHandler(errorHandler::hasError, (request, response) ->
errorHandler.handleError(request.getURI(), request.getMethod(), response));
}
public static StatusHandler defaultHandler(List<HttpMessageConverter<?>> messageConverters) {
return new StatusHandler(response -> response.getStatusCode().isError(),
(request, response) -> {
HttpStatusCode statusCode = response.getStatusCode();
String statusText = response.getStatusText();
HttpHeaders headers = response.getHeaders();
byte[] body = RestClientUtils.getBody(response);
Charset charset = RestClientUtils.getCharset(response);
String message = getErrorMessage(statusCode.value(), statusText, body, charset);
RestClientResponseException ex;
if (statusCode.is4xxClientError()) {
ex = HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset);
}
else if (statusCode.is5xxServerError()) {
ex = HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
}
else {
ex = new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
}
if (!CollectionUtils.isEmpty(messageConverters)) {
ex.setBodyConvertFunction(initBodyConvertFunction(response, body, messageConverters));
}
throw ex;
});
}
private static Function<ResolvableType, ?> initBodyConvertFunction(ClientHttpResponse response, byte[] body, List<HttpMessageConverter<?>> messageConverters) {
Assert.state(!CollectionUtils.isEmpty(messageConverters), "Expected message converters");
return resolvableType -> {
try {
HttpMessageConverterExtractor<?> extractor =
new HttpMessageConverterExtractor<>(resolvableType.getType(), messageConverters);
return extractor.extractData(new ClientHttpResponseDecorator(response) {
@Override
public InputStream getBody() {
return new ByteArrayInputStream(body);
}
});
}
catch (IOException ex) {
throw new RestClientException("Error while extracting response for type [" + resolvableType + "]", ex);
}
};
}
private static String getErrorMessage(int rawStatusCode, String statusText, @Nullable byte[] responseBody,
@Nullable Charset charset) {
String preface = rawStatusCode + " " + statusText + ": ";
if (ObjectUtils.isEmpty(responseBody)) {
return preface + "[no body]";
}
charset = (charset != null ? charset : StandardCharsets.UTF_8);
String bodyText = new String(responseBody, charset);
bodyText = LogFormatUtils.formatValue(bodyText, -1, true);
return preface + bodyText;
}
public boolean test(ClientHttpResponse response) throws IOException {
return this.predicate.test(response);
}
public void handle(HttpRequest request, ClientHttpResponse response) throws IOException {
this.errorHandler.handle(request, response);
}
@FunctionalInterface
private interface ResponsePredicate {
boolean test(ClientHttpResponse response) throws IOException;
}
}
|
package sview;
import java.util.Map;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationObjectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.View;
public class ViewAdapter implements View {
private final static String DEFAULT_CONTENT_TYPE = "text/html";
private String sviewName;
private SViewFactory sviewFactory;
private boolean isPrettyPrint = true;
private String contentType;
public ViewAdapter() {
}
public void setSViewName(String sviewName) {
this.sviewName = sviewName;
}
public void setSViewFactory(SViewFactory sviewFactory) {
this.sviewFactory = sviewFactory;
}
public void setPrettyPrint(boolean isPrettyPrint) {
this.isPrettyPrint = isPrettyPrint;
}
public String getContentType() {
return contentType;
}
public void render(Map model, HttpServletRequest request,HttpServletResponse response) throws Exception {
ViewBinding viewBinding = new ViewBinding((Map<String,Object>) model,request,response);
SView sview = sviewFactory.getSView(sviewName,viewBinding);
this.contentType = sview.contenttype();
SViewWriteRenderer renderer = new SViewWriteRenderer();
sview.render(renderer);
response.setContentType(this.contentType);
PrintWriter out = response.getWriter();
renderer.print(out,isPrettyPrint);
out.close();
}
}
|
/*
* Copyright 2016 Grzegorz Skorupa <g.skorupa at gmail.com>.
*
* 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.cricketmsf.in.file;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import org.cricketmsf.Adapter;
import org.cricketmsf.Event;
import org.cricketmsf.Kernel;
import org.cricketmsf.in.InboundAdapter;
/**
*
* @author greg
*/
public class FileTailer extends InboundAdapter implements Adapter, WatchdogIface {
private final String INBOUND_METHOD_NAME = "newline";
private String fileName;
File file;
boolean directory = false;
long lastKnownPosition = 1;
private int samplingInterval = 1000;
private boolean continuing = false;
/**
* This method is executed while adapter is instantiated during the service
* start. It's used to configure the adapter according to the configuration.
*
* @param properties map of properties readed from the configuration file
* @param adapterName name of the adapter set in the configuration file (can
* be different from the interface and class name.
*/
@Override
public void loadProperties(HashMap<String, String> properties, String adapterName) {
super.getServiceHooks(adapterName);
setFile(properties.getOrDefault("path", ""));
Kernel.getInstance().getLogger().print("\tpath=" + fileName);
setSamplingInterval(properties.getOrDefault("sampling-interval", "1000"));
Kernel.getInstance().getLogger().print("\tsampling-interval=" + samplingInterval);
}
@Override
public void checkStatus() {
if (file == null) {
return;
}
if (!directory) {
long fileLength = file.length();
if ((!continuing) || (fileLength > lastKnownPosition)) {
try (RandomAccessFile readWriteFileAccess = new RandomAccessFile(file, "rw")) {
readWriteFileAccess.seek(lastKnownPosition - 1);
String newLine;
while ((newLine = readWriteFileAccess.readLine()) != null) {
// create event
if (!newLine.isEmpty() && continuing) {
handle(INBOUND_METHOD_NAME, newLine);
}
}
continuing = true;
lastKnownPosition = readWriteFileAccess.getFilePointer();
} catch (IOException e) {
}
}
}
}
@Override
public void run() {
try {
while (true) {
checkStatus();
Thread.sleep(samplingInterval);
Thread.yield();
}
} catch (InterruptedException e) {
Kernel.getInstance().dispatchEvent(Event.logWarning(this.getClass().getSimpleName(), "interrupted"));
}
}
/**
* @param samplingInterval the samplingInterval to set
*/
public void setSamplingInterval(String samplingInterval) {
try {
this.samplingInterval = Integer.parseInt(samplingInterval);
} catch (NumberFormatException e) {
Kernel.getInstance().getLogger().print(e.getMessage());
}
}
/**
* @param folderName the folderName to set
*/
public void setFile(String folderName) {
this.fileName = folderName;
file = new File(folderName);
try {
if (!file.exists()) {
file = null;
Kernel.getInstance().getLogger().print("file not found");
} else if (file.isDirectory()) {
directory = true;
Kernel.getInstance().getLogger().print("directory found");
}
} catch (SecurityException e) {
Kernel.getInstance().getLogger().print(e.getMessage());
}
}
}
|
package edu.cricket.api.cricketscores.task;
import edu.cricket.api.cricketscores.async.RefreshPreGamesTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class PreGamesTask {
private static final Logger log = LoggerFactory.getLogger(PreGamesTask.class);
RestTemplate restTemplate = new RestTemplate();
@Autowired
TaskExecutor taskExecutor;
@Autowired
RefreshPreGamesTask refreshPreGamesTask;
public void refreshPreEventsAsync() {
taskExecutor.execute(refreshPreGamesTask);
}
public void refreshPreEvents() {
refreshPreEventsAsync();
}
public void refreshPreEvent(long gameId){
refreshPreGamesTask.refreshPreMatch(gameId);
}
/*
private void updatePreGameInfo(GameAggregate gameAggregate) {
try {
Long gameId = gameAggregate.getId();
long sourceEventId = gameId/13;
String eventRef = "http://core.espnuk.org/v2/sports/cricket/events/"+sourceEventId;
EventDetail eventDetail = restTemplate.getForObject(eventRef, EventDetail.class);
Competition competition = eventDetail.getCompetitions().get(0);
Event event = new Event();
int intClassId = competition.getCompetitionClass().getInternationalClassId();
if (intClassId > 10) {
preEvents.remove(gameId);
return;
}
event.setInternationalClassId(intClassId);
int genClassId = competition.getCompetitionClass().getGeneralClassId();
if (intClassId == 0 && genClassId > 10){
preEvents.remove(gameId);
return;
}
event.setGeneralClassId(genClassId);
event.setEventId(String.valueOf(Integer.parseInt(competition.getId()) * 13));
event.setStartDate(DateUtils.getDateFromString(eventDetail.getDate()));
event.setEndDate(DateUtils.getDateFromString(eventDetail.getEndDate()));
event.setVenue(getEventVenue(eventDetail.getVenues().get(0).get$ref()));
setSeason(eventDetail, event);
event.setType(competition.getCompetitionClass().getEventType());
event.setNote(competition.getNote());
MatchStatus matchStatus = restTemplate.getForObject(competition.getStatus().get$ref(), MatchStatus.class);
if (null != matchStatus) {
event.setPeriod(matchStatus.getPeriod());
if (null != matchStatus.getType()) {
event.setDescription(matchStatus.getType().getDescription());
event.setDescription(matchStatus.getType().getDescription());
event.setDetail(matchStatus.getType().getDetail());
event.setState(matchStatus.getType().getState());
}
}
List<Competitor> competitorList = competition.getCompetitors();
if (null != competitorList && competitorList.size() == 2) {
edu.cricket.api.cricketscores.rest.response.model.Competitor team1 = new edu.cricket.api.cricketscores.rest.response.model.Competitor();
team1.setTeamName(getEventTeam(competitorList.get(0).getTeam().get$ref()));
team1.setScore(getEventScore(competitorList.get(0).getScore().get$ref()));
team1.setWinner(competitorList.get(0).isWinner());
long sourceTeam1Id = Long.valueOf(team1.getTeamName().split(":")[1]) / 13;
team1.setSquad(eventSquadsTask.getLeagueTeamPlayers(event.getLeagueId(), sourceTeam1Id, event));
event.setTeam1(team1);
edu.cricket.api.cricketscores.rest.response.model.Competitor team2 = new edu.cricket.api.cricketscores.rest.response.model.Competitor();
team2.setTeamName(getEventTeam(competitorList.get(1).getTeam().get$ref()));
team2.setScore(getEventScore(competitorList.get(1).getScore().get$ref()));
long sourceTeam2Id = Long.valueOf(team2.getTeamName().split(":")[1]) / 13;
team2.setSquad(eventSquadsTask.getLeagueTeamPlayers(event.getLeagueId(), sourceTeam2Id, event));
event.setTeam2(team2);
}
gameAggregate.setEventInfo(event);
}catch (Exception e) {
e.printStackTrace();
}
}*/
/*
public String getEventVenue(String $ref){
Venue venue = restTemplate.getForObject($ref , Venue.class);
return venue.getFullName();
}
public String getEventTeam(String $ref){
Team team = restTemplate.getForObject($ref , Team.class);
return teamNameService.getTeamName(team.getId());
}
public String getEventScore(String $ref){
Score score = restTemplate.getForObject($ref , Score.class);
return score.getValue();
}*/
}
|
package com.ut.module_lock.adapter;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* author : chenjiajun
* time : 2018/11/28
* desc :
*/
public class RecyclerListAdapter<T> extends RecyclerView.Adapter<ListViewHolder> {
private List<T> itemsList = new ArrayList<>();
private int itemResourceId;
private int varId;
private OnItemClickListener listener;
public void setOnItemListener(OnItemClickListener listener) {
this.listener = listener;
}
public RecyclerListAdapter(List<T> list, int itemResourceId, int varId) {
if (list != null) {
itemsList = list;
}
this.itemResourceId = itemResourceId;
this.varId = varId;
}
public void addData(List<T> newData) {
itemsList.addAll(newData);
notifyDataSetChanged();
}
@NonNull
@Override
public ListViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
ViewDataBinding dataBinding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), itemResourceId, viewGroup, false);
return new ListViewHolder(dataBinding.getRoot());
}
@Override
public void onBindViewHolder(@NonNull ListViewHolder listViewHolder, int i) {
listViewHolder.binding.setVariable(varId, itemsList.get(i));
listViewHolder.binding.getRoot().setOnClickListener(v -> {
if (listener != null) {
listener.onClicked(v, i);
}
});
}
@Override
public int getItemCount() {
return itemsList.size();
}
public interface OnItemClickListener {
void onClicked(View view, int position);
}
}
|
package com.k2data.k2app.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
/**
* 用 orika 代替
*
* @author lidong9144@163.com 17-3-24.
*/
@Deprecated
public class PojoUtils {
/**
* 复制{@link Object}的成员变量的值到目标{@link Object}的相同名称的的成员变量上,不区分大小写。
*
* @param provider 提供值的{@link Object}实例
* @param accepter 接受数据的{@link Object}实例
*/
public static void copyProperties(Object provider, Object accepter) {
final Class<?> providerCls = provider.getClass();
final Class<?> accepterCls = accepter.getClass();
for (Class<?> cls = providerCls; cls != null; cls = cls.getSuperclass()) {
for (Field providerField : cls.getDeclaredFields()) {
final String propertyName = providerField.getName();
final Method providerReader = ReflectUtils.getReadMethod(cls, propertyName);
if (providerReader == null) {
continue;
}
final Method accepterWriter = ReflectUtils.getWriteMethod(accepterCls, propertyName);
if (accepterWriter == null) {
continue;
}
final Class<?> parameterType = accepterWriter.getParameterTypes()[0];
Object paramValue = ConvertUtils.convert(ReflectUtils.invokeMethod(provider, providerReader), parameterType);
if (paramValue != null) {
ReflectUtils.invokeMethod(accepter, accepterWriter, paramValue);
}
}
}
}
/**
* 复制{@link Map}的值,用{@code Setter}方法赋值到{@link Map}的{@code KEY}对应的目标{@link Object}的成员变量上
* 其中如果{@code prefix}和{@code suffix}非空的话,就要从{@link Map}的{@code KEY}中去掉前后缀后比较
*
* @param provider 提供值的{@link Map}实例
* @param prefix 前缀
* @param suffix 后缀
*/
public static <T> void copyProperties(final Map<String, T> provider, final Object accepter, final String prefix, final String suffix) {
final String vPrefix = ((StringUtils.isBlank(prefix))? "" : prefix);
final String vSuffix = ((StringUtils.isBlank(suffix))? "" : suffix);
final Class<?> cls = accepter.getClass();
for (Map.Entry<String, T> entry : provider.entrySet()) {
final String key = entry.getKey();
if (!StringUtils.startsWithIgnoreCase(key, vPrefix) || !StringUtils.endsWithIgnoreCase(key, vSuffix)) {
continue;
}
final String name = StringUtils.removeEnd(StringUtils.removeStart(key.toLowerCase(), vPrefix.toLowerCase()), vSuffix.toLowerCase());
if (StringUtils.isBlank(name))
continue;
final T value = provider.get(key);
final Method writer = ReflectUtils.getWriteMethod(cls, name);
if (writer != null) {
final Class<?> parameterType = writer.getParameterTypes()[0];
Object paramValue = ConvertUtils.convert(value, parameterType);
if (paramValue != null) {
ReflectUtils.invokeMethod(accepter, writer, paramValue);
}
}
}
}
}
|
/*
* Merge HRIS API
* The unified API for building rich integrations with multiple HR Information System platforms.
*
* The version of the OpenAPI document: 1.0
* Contact: hello@merge.dev
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package merge_hris_client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import merge_hris_client.model.Deduction;
import merge_hris_client.model.Earning;
import merge_hris_client.model.RemoteData;
import merge_hris_client.model.Tax;
import org.threeten.bp.OffsetDateTime;
/**
* # The EmployeePayrollRun Object ### Description The `EmployeePayrollRun` object is used to represent a payroll run for a specific employee. ### Usage Example Fetch from the `LIST EmployeePayrollRun` endpoint and filter by `ID` to show all employee payroll runs.
*/
@ApiModel(description = "# The EmployeePayrollRun Object ### Description The `EmployeePayrollRun` object is used to represent a payroll run for a specific employee. ### Usage Example Fetch from the `LIST EmployeePayrollRun` endpoint and filter by `ID` to show all employee payroll runs.")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-06-09T12:47:41.903246-07:00[America/Los_Angeles]")
public class EmployeePayrollRun {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private UUID id;
public static final String SERIALIZED_NAME_REMOTE_ID = "remote_id";
@SerializedName(SERIALIZED_NAME_REMOTE_ID)
private String remoteId;
public static final String SERIALIZED_NAME_EMPLOYEE = "employee";
@SerializedName(SERIALIZED_NAME_EMPLOYEE)
private UUID employee;
public static final String SERIALIZED_NAME_PAYROLL_RUN = "payroll_run";
@SerializedName(SERIALIZED_NAME_PAYROLL_RUN)
private UUID payrollRun;
public static final String SERIALIZED_NAME_GROSS_PAY = "gross_pay";
@SerializedName(SERIALIZED_NAME_GROSS_PAY)
private Float grossPay;
public static final String SERIALIZED_NAME_NET_PAY = "net_pay";
@SerializedName(SERIALIZED_NAME_NET_PAY)
private Float netPay;
public static final String SERIALIZED_NAME_START_DATE = "start_date";
@SerializedName(SERIALIZED_NAME_START_DATE)
private OffsetDateTime startDate;
public static final String SERIALIZED_NAME_END_DATE = "end_date";
@SerializedName(SERIALIZED_NAME_END_DATE)
private OffsetDateTime endDate;
public static final String SERIALIZED_NAME_CHECK_DATE = "check_date";
@SerializedName(SERIALIZED_NAME_CHECK_DATE)
private OffsetDateTime checkDate;
public static final String SERIALIZED_NAME_EARNINGS = "earnings";
@SerializedName(SERIALIZED_NAME_EARNINGS)
private List<Earning> earnings = null;
public static final String SERIALIZED_NAME_DEDUCTIONS = "deductions";
@SerializedName(SERIALIZED_NAME_DEDUCTIONS)
private List<Deduction> deductions = null;
public static final String SERIALIZED_NAME_TAXES = "taxes";
@SerializedName(SERIALIZED_NAME_TAXES)
private List<Tax> taxes = null;
public static final String SERIALIZED_NAME_REMOTE_DATA = "remote_data";
@SerializedName(SERIALIZED_NAME_REMOTE_DATA)
private List<RemoteData> remoteData = null;
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "fb8c55b6-1cb8-4b4c-9fb6-17924231619d", value = "")
public UUID getId() {
return id;
}
public EmployeePayrollRun remoteId(String remoteId) {
this.remoteId = remoteId;
return this;
}
/**
* The third-party API ID of the matching object.
* @return remoteId
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "19202938", value = "The third-party API ID of the matching object.")
public String getRemoteId() {
return remoteId;
}
public void setRemoteId(String remoteId) {
this.remoteId = remoteId;
}
public EmployeePayrollRun employee(UUID employee) {
this.employee = employee;
return this;
}
/**
* The employee whose payroll is being run.
* @return employee
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "d2f972d0-2526-434b-9409-4c3b468e08f0", value = "The employee whose payroll is being run.")
public UUID getEmployee() {
return employee;
}
public void setEmployee(UUID employee) {
this.employee = employee;
}
public EmployeePayrollRun payrollRun(UUID payrollRun) {
this.payrollRun = payrollRun;
return this;
}
/**
* The payroll being run.
* @return payrollRun
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "35347df1-95e7-46e2-93cc-66f1191edca5", value = "The payroll being run.")
public UUID getPayrollRun() {
return payrollRun;
}
public void setPayrollRun(UUID payrollRun) {
this.payrollRun = payrollRun;
}
public EmployeePayrollRun grossPay(Float grossPay) {
this.grossPay = grossPay;
return this;
}
/**
* The gross pay from the run.
* @return grossPay
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "1342.67", value = "The gross pay from the run.")
public Float getGrossPay() {
return grossPay;
}
public void setGrossPay(Float grossPay) {
this.grossPay = grossPay;
}
public EmployeePayrollRun netPay(Float netPay) {
this.netPay = netPay;
return this;
}
/**
* The net pay from the run.
* @return netPay
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "865.78", value = "The net pay from the run.")
public Float getNetPay() {
return netPay;
}
public void setNetPay(Float netPay) {
this.netPay = netPay;
}
public EmployeePayrollRun startDate(OffsetDateTime startDate) {
this.startDate = startDate;
return this;
}
/**
* The day and time the payroll run started.
* @return startDate
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The day and time the payroll run started.")
public OffsetDateTime getStartDate() {
return startDate;
}
public void setStartDate(OffsetDateTime startDate) {
this.startDate = startDate;
}
public EmployeePayrollRun endDate(OffsetDateTime endDate) {
this.endDate = endDate;
return this;
}
/**
* The day and time the payroll run ended.
* @return endDate
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The day and time the payroll run ended.")
public OffsetDateTime getEndDate() {
return endDate;
}
public void setEndDate(OffsetDateTime endDate) {
this.endDate = endDate;
}
public EmployeePayrollRun checkDate(OffsetDateTime checkDate) {
this.checkDate = checkDate;
return this;
}
/**
* The day and time the payroll run was checked.
* @return checkDate
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The day and time the payroll run was checked.")
public OffsetDateTime getCheckDate() {
return checkDate;
}
public void setCheckDate(OffsetDateTime checkDate) {
this.checkDate = checkDate;
}
/**
* Get earnings
* @return earnings
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "[{\"employee_payroll_run\":\"35347df1-95e7-46e2-93cc-66f1191edca5\",\"amount\":1002.34,\"type\":\"SALARY\"},{\"employee_payroll_run\":\"35347df1-95e7-46e2-93cc-66f1191edca5\",\"amount\":8342.34,\"type\":\"OVERTIME\"}]", value = "")
public List<Earning> getEarnings() {
return earnings;
}
/**
* Get deductions
* @return deductions
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "[{\"employee_payroll_run\":\"35347df1-95e7-46e2-93cc-66f1191edca5\",\"name\":\"Social Security\",\"employee_deduction\":34.54,\"company_deduction\":78.78}]", value = "")
public List<Deduction> getDeductions() {
return deductions;
}
/**
* Get taxes
* @return taxes
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "[{\"employee_payroll_run\":\"35347df1-95e7-46e2-93cc-66f1191edca5\",\"name\":\"California State Income Tax\",\"amount\":100.25,\"employer_tax\":\"False\"}]", value = "")
public List<Tax> getTaxes() {
return taxes;
}
/**
* Get remoteData
* @return remoteData
**/
@javax.annotation.Nullable
@ApiModelProperty(example = "[{\"path\":\"/employee-payroll\",\"data\":[\"Varies by platform\"]}]", value = "")
public List<RemoteData> getRemoteData() {
return remoteData;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EmployeePayrollRun employeePayrollRun = (EmployeePayrollRun) o;
return Objects.equals(this.id, employeePayrollRun.id) &&
Objects.equals(this.remoteId, employeePayrollRun.remoteId) &&
Objects.equals(this.employee, employeePayrollRun.employee) &&
Objects.equals(this.payrollRun, employeePayrollRun.payrollRun) &&
Objects.equals(this.grossPay, employeePayrollRun.grossPay) &&
Objects.equals(this.netPay, employeePayrollRun.netPay) &&
Objects.equals(this.startDate, employeePayrollRun.startDate) &&
Objects.equals(this.endDate, employeePayrollRun.endDate) &&
Objects.equals(this.checkDate, employeePayrollRun.checkDate) &&
Objects.equals(this.earnings, employeePayrollRun.earnings) &&
Objects.equals(this.deductions, employeePayrollRun.deductions) &&
Objects.equals(this.taxes, employeePayrollRun.taxes) &&
Objects.equals(this.remoteData, employeePayrollRun.remoteData);
}
@Override
public int hashCode() {
return Objects.hash(id, remoteId, employee, payrollRun, grossPay, netPay, startDate, endDate, checkDate, earnings, deductions, taxes, remoteData);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class EmployeePayrollRun {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" remoteId: ").append(toIndentedString(remoteId)).append("\n");
sb.append(" employee: ").append(toIndentedString(employee)).append("\n");
sb.append(" payrollRun: ").append(toIndentedString(payrollRun)).append("\n");
sb.append(" grossPay: ").append(toIndentedString(grossPay)).append("\n");
sb.append(" netPay: ").append(toIndentedString(netPay)).append("\n");
sb.append(" startDate: ").append(toIndentedString(startDate)).append("\n");
sb.append(" endDate: ").append(toIndentedString(endDate)).append("\n");
sb.append(" checkDate: ").append(toIndentedString(checkDate)).append("\n");
sb.append(" earnings: ").append(toIndentedString(earnings)).append("\n");
sb.append(" deductions: ").append(toIndentedString(deductions)).append("\n");
sb.append(" taxes: ").append(toIndentedString(taxes)).append("\n");
sb.append(" remoteData: ").append(toIndentedString(remoteData)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
package com.junyoung.searchwheretogoapi.controller;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.junyoung.searchwheretogoapi.model.api.ListResponse;
import com.junyoung.searchwheretogoapi.model.common.ResponseType;
import com.junyoung.searchwheretogoapi.service.place.search.PlaceSearchHistoryQueryService;
import com.junyoung.searchwheretogoapi.util.TestDataUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc;
@AutoConfigureMockMvc(addFilters = false)
@SpringBootTest
class PlaceSearchHistoryControllerTest {
@Autowired private MockMvc mockMvc;
@MockBean private PlaceSearchHistoryQueryService placeSearchHistoryQueryService;
@BeforeEach
void setUp() {
given(placeSearchHistoryQueryService.getPlaceSearchHistories(any(), any()))
.willReturn(new ListResponse<>(TestDataUtil.createPlaceSearchHistories(10), 10));
SecurityContextHolder.getContext().setAuthentication(TestDataUtil.createAuthToken());
}
@Test
void test_get_place_search_histories_success() throws Exception {
mockMvc
.perform(get("/v1.0/places/histories"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.header.isSuccessful").value(true))
.andExpect(jsonPath("$.header.resultMessage").value("SUCCESS"))
.andExpect(jsonPath("$.body.data").isArray())
.andExpect(jsonPath("$.body.totalCount").value(10));
}
@Test
void test_get_place_search_histories_empty_user() throws Exception {
SecurityContextHolder.getContext().setAuthentication(null);
mockMvc
.perform(get("/v1.0/places/histories"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.header.isSuccessful").value(false))
.andExpect(
jsonPath("$.header.resultMessage").value(ResponseType.NOT_LOGIN_USER.getMessage()));
}
}
|
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.concurrent.TimeUnit;
@Configuration
public class WebConfig {
@Bean
WebMvcConfigurer configurer() {
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/bootstrap/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/bootstrap/")
.setCacheControl(CacheControl.maxAge(30L, TimeUnit.DAYS).cachePublic());
registry.addResourceHandler("/jquery/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/jquery/")
.setCacheControl(CacheControl.maxAge(30L, TimeUnit.DAYS).cachePublic());
}
};
}
}
|
package mw.wspolne.model;
import lombok.Getter;
import lombok.Setter;
import java.text.DecimalFormat;
/**
* Created with IntelliJ IDEA.
* User: Mariusz.Wojcik
* Date: 11.03.14
* Time: 16:29
* To change this template use File | Settings | File Templates.
*/
@Setter
@Getter
public class MiernikZajetosci {
private String rodzaj;
private long rozmiar;
private int liczbaPlikow;
public String getRozmiarMB() {
double pRozmiar = rozmiar;
DecimalFormat df = new DecimalFormat("#.##");
return df.format(pRozmiar / (1024 * 1024));
}
public String getRodzaj() {
return rodzaj;
}
public void setRodzaj(String rodzaj) {
this.rodzaj = rodzaj;
}
}
|
/**
* Created by Alexander Lomat on 15.05.19
* version 0.0.3
*/
package by.epam.onemusic.pool;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
public class ConnectionPool {
private static final Logger LOGGER = LogManager.getLogger();
private static ConnectionPool instance;
private BlockingDeque<ProxyConnection> freeConnections;
private BlockingDeque<ProxyConnection> usedConnections;
private static ReentrantLock reentrantLock = new ReentrantLock();
private static AtomicBoolean isCreated = new AtomicBoolean(false);
private DBPropertiesHandler dbPropertiesHandler = DBPropertiesHandler.getInstance();
private ConnectionPool() {
init();
}
private void init() {
int dequeSize = dbPropertiesHandler.getDbPoolSize();
freeConnections = new LinkedBlockingDeque<>(dequeSize);
usedConnections = new LinkedBlockingDeque<>(dequeSize);
for (int i = 0; i < dequeSize; i++) {
try {
freeConnections.add(ConnectionPool.createConnection());
} catch (SQLException e) {
LOGGER.error("Error while adding to connections pool", e);
e.printStackTrace();
}
}
if (freeConnections.getFirst() == null) {
LOGGER.fatal("Connection pool is empty.");
throw new ExceptionInInitializerError("Connection pool is empty.");
//TODO STOP APPLICATION
}
}
private static ProxyConnection createConnection() throws SQLException {
DBPropertiesHandler dbPropertiesHandler = DBPropertiesHandler.getInstance();
Connection connection = DriverManager.getConnection(
dbPropertiesHandler.getConnectionString(),
dbPropertiesHandler.getDbUser(),
dbPropertiesHandler.getDbPass());
ProxyConnection proxyConnection = new ProxyConnection(connection);
return proxyConnection;
}
public static ConnectionPool getInstance() {
if (!isCreated.get()) {
try {
reentrantLock.lock();
if (instance == null) {
instance = new ConnectionPool();
isCreated.set(true);
LOGGER.info("Connection pool was created.");
}
} finally {
reentrantLock.unlock();
}
}
return instance;
}
public ProxyConnection takeConnection() {
ProxyConnection connection = null;
try {
connection = freeConnections.take();
usedConnections.put(connection);
int size = freeConnections.size();
LOGGER.info("Connection was taken. There are " + size + " free connections.");
} catch (InterruptedException e) {
LOGGER.error("Connection was interrupted.");
Thread.currentThread().interrupt();
}
return connection;
}
public void releaseConnection(Connection connection) {
if (connection instanceof ProxyConnection) {
ProxyConnection tmp = (ProxyConnection) connection;
try {
if (!tmp.getAutoCommit()) {
tmp.setAutoCommit(true);
}
} catch (SQLException e) {
e.printStackTrace();
LOGGER.error("Error while setting autocommit.");
}
usedConnections.remove(connection);
freeConnections.offer(tmp);
int size = usedConnections.size();
LOGGER.info("Connection was released. Remaining " + size + " working connections.");
} else {
LOGGER.info("Connection was not released.");
}
}
public void closePool() throws InterruptedException, SQLException {
for (int i = 0; i < dbPropertiesHandler.getDbPoolSize(); i++) {
ProxyConnection connection = freeConnections.take();
connection.realClose();
}
}
}
|
package vn.edu.techkids.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView txt = (TextView)this.findViewById(R.id.textView);
Intent intent = getIntent();
Bundle b = intent.getBundleExtra("goitin");
txt.setText(b.getString("DU_LIEU"));
Button btn = (Button)this.findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.model;
import com.beans.TblOrderDetail;
import com.help.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
/**
*
* @author ADMIN
*/
public class OrderDetailModel implements IAdstractModel<TblOrderDetail> {
private static OrderDetailModel instanse = null;
Session session = null;
public OrderDetailModel() {
}
public static OrderDetailModel getInstance() {
if (instanse == null) {
instanse = new OrderDetailModel();
}
return instanse;
}
public boolean deleteProduct(TblOrderDetail obj) {
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.delete(obj);
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
session.getTransaction().rollback();
return false;
}
return true;
}
public TblOrderDetail getObjectByID(int objID) {
TblOrderDetail ordDetail = null;
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String strQuery = "from TblOrderDetail where ordID=" + objID;
Query sqlQuery = session.createQuery(strQuery);
ordDetail = (TblOrderDetail) sqlQuery.uniqueResult();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
return ordDetail;
}
public List<TblOrderDetail> getListObjectByID(int objID) {
List<TblOrderDetail> listObject = null;
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
String strQuery = "from TblOrderDetail where oID = " + objID + " order by ordID DESC";
Query sqlQuery = session.createQuery(strQuery);
listObject = sqlQuery.list();
session.getTransaction().begin();
return listObject;
}
@Override
public List<TblOrderDetail> getListObject() {
return null;
}
@Override
public boolean insertObject(TblOrderDetail t) {
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
session.getTransaction().rollback();
return false;
}
return true;
}
@Override
public boolean deleteObject(int objID) {
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.delete(objID);
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
session.getTransaction().rollback();
return false;
}
return true;
}
@Override
public boolean updateObject(TblOrderDetail t) {
try {
session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.update(t);
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
session.getTransaction().rollback();
return false;
}
return true;
}
@Override
public List<TblOrderDetail> searchObject(String obj) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package com.mzdhr.aadpractice.background;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.Nullable;
import android.util.Log;
import com.mzdhr.aadpractice.model.NoteEntry;
import com.mzdhr.aadpractice.model.NoteRepository;
import com.mzdhr.aadpractice.util.NotificationUtils;
import java.util.Date;
/**
* Service
* This is the base class for all services. When you extend this class, it's important to create a
* new thread in which the service can complete all of its work; the service uses your application's
* main thread by default, which can slow the performance of any activity that your application is
* running.
* https://developer.android.com/guide/components/services
* <p>
* Service and IntentService
* Using IntentService makes your implementation of a started service very simple. If, however,
* you require your service to perform multi-threading (instead of processing start requests
* through a work queue), you can extend the Service class to handle each intent.
*/
public class WriteService extends Service {
private static final String TAG = WriteService.class.getSimpleName();
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private static final Object sSyncObject = new Object();
private static NoteRepository sNoteRepository;
/**
* Handler that receives messages from the thread
*/
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
NotificationUtils.clearAllNotifications(getApplicationContext());
synchronized (sSyncObject) {
if (sNoteRepository == null) {
sNoteRepository = NoteRepository.getInstance(getApplication());
}
}
NoteEntry noteEntry = new NoteEntry("This is note from a service", "body", new Date());
sNoteRepository.insert(noteEntry);
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}
@Override
public void onCreate() {
/**
* Start up the thread running the service. Note that we create a
* separate thread because the service normally runs in the process's
* main thread, which we don't want to block. We also make it
* background priority so CPU-intensive work doesn't disrupt our UI.
*/
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: Service starting!");
// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null.
return null;
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: Service done!");
super.onDestroy();
}
}
|
package com.revature.ersservlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.revature.daoimplementations.EmployeeDaoImpl;
import com.revature.daoimplementations.UserDaoImpl;
import com.revature.project1.models.User;
/**
* Servlet implementation class EmployeeDetails
*/
public class EmployeeDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public EmployeeDetails() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
int userId = (Integer) session.getAttribute("item1");
UserDaoImpl user = new UserDaoImpl();
RequestDispatcher rd = request.getRequestDispatcher("employeeHomepage.jsp");
rd.include(request, response);
//UserDaoImpl user = new UserDaoImpl();
out.print(user.viewUser(userId).toString());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package kiki.AccountCal.Beta;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TableAdapter extends BaseAdapter{
private Context context;
private List<TableRow> table;
//construct
public TableAdapter(Context context,List<TableRow> table){
this.context=context;
this.table=table;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return table.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return table.get(arg0);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
TableRow tableRow=table.get(position);
return new TableRowView(this.context,tableRow);
}
/**
* 实现表格行的样式
* */
class TableRowView extends LinearLayout{
public TableRowView(Context context, TableRow tableRow) {
// TODO Auto-generated constructor stub
super(context);
this.setOrientation(LinearLayout.HORIZONTAL); //??????
int bgTypeNum=tableRow.getStyle();
for(int i=0;i<tableRow.getSize();i++){ //逐个添加格单元到行
TableCell tableCell=tableRow.getCellValue(i);
LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(
tableCell.width,tableCell.height); //按照单元格大小设置空间
layoutParams.setMargins(0, 0, 1, 1); //预留空隙制造边框
if(tableCell.type==TableCell.STRING){ //如果是文字的话
TextView textCell=new TextView(context);
textCell.setLines(1);
textCell.setGravity(Gravity.CENTER);
if(bgTypeNum==0){
textCell.setBackgroundColor(Color.BLACK);
}else{
textCell.setBackgroundColor(Color.rgb(51, 161, 201));
}
textCell.setText(String.valueOf(tableCell.value));
addView(textCell,layoutParams);
}else if(tableCell.type==TableCell.IMAGE){
ImageView imgCell=new ImageView(context);
imgCell.setBackgroundColor(Color.BLACK);
imgCell.setImageResource((Integer)tableCell.value);
addView(imgCell,layoutParams);
}
}
this.setBackgroundColor(Color.WHITE);
}
}
/**
* TableRow实现表格的行
* */
static public class TableRow{
private TableCell[] cell;
private int STYLE_ROW;
public TableRow(TableCell[] cell){
this.cell=cell;
this.STYLE_ROW=0;
}
public TableRow(TableCell[] cell,int STYLE_ROW){ //带属性的tablerow构造函数
this.cell=cell;
this.STYLE_ROW=STYLE_ROW;
}
public int getSize(){
return cell.length;
}
public int getStyle(){
return STYLE_ROW;
}
public TableCell getCellValue(int index){
if(index>cell.length)
return null;
return cell[index];
}
}
/**
* TableCell 实现表格的格单元
* */
static public class TableCell{
static public final int STRING=0;
static public final int IMAGE=1;
public Object value;
public int width;
public int height;
private int type;
public TableCell(Object value,int width,int height,int type){
this.value=value;
this.width=width;
this.height=height;
this.type=type;
}
}
}
|
package testqueue;
import static org.junit.Assert.*;
import queue_singlelinkedlist.FifoQueue;
import org.junit.Test;
public class TestAppendFifoQueue {
private FifoQueue<Integer >myQueue1 = new FifoQueue<Integer>();
private FifoQueue<Integer >myQueue2 = new FifoQueue<Integer>();
@Test
public void twoEmptyQueues(){
myQueue1.append(myQueue2);
}
@Test
public void test() {
myQueue1.offer(1);
myQueue1.offer(2);
myQueue2.offer(3);
myQueue2.offer(4);
fail("Not yet implemented");
}
}
|
/*
* 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 tqs.weatherapp2.repository;
import tqs.weatherapp2.model.Forecast;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
/**
*
* @author claudio
*/
public interface ForecastRepo extends CrudRepository<Forecast, Double> {
boolean existsByLatitudeAndLongitude(Double latitude, Double longitude);
Forecast findByLatitudeAndLongitude(Double latitude, Double longitude);
}
|
package com.jit.staticmethods01;
public class Test implements Interf{
public static void main(String[] args) {
Test t =new Test();
//t.m1();
//Test.m1();
Interf.m1();
}
}
|
package com.accenture.test.assesment.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class CustomerModel {
private int custId;
private String customerName;
private int active;
private String emailAddress;
private String mobileNumber;
private String phoneNumber;
private String state;
private String country;
private String language;
private BusinessProblemModel businessProblemModel;
public CustomerModel() {
/*
* Default Constructor
*
*/
}
public int getCustId() {
return custId;
}
@JsonIgnore
public void setCustId(int custId) {
this.custId = custId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
@JsonIgnore
public BusinessProblemModel getBusinessProblemModel() {
return businessProblemModel;
}
public void setBusinessProblemModel(BusinessProblemModel businessProblemModel) {
this.businessProblemModel = businessProblemModel;
}
}
|
package com.oleksii.arrmy.CrewPortal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CrewPortalApplication {
public static void main(String[] args){
SpringApplication.run(CrewPortalApplication.class, args);
}
}
|
package com.company;
public class Cat extends Animal {
private int laserBeam;
private int bazookas;
private int rubicCubes;
public Cat(String name, int brain, int body, int size, int weight, int laserBeam, int bazookas, int rubicCubes) {
super(name, brain, body, size, weight);
this.laserBeam = laserBeam;
this.bazookas = bazookas;
this.rubicCubes = rubicCubes;
}
}
|
/*
* 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 controller;
import java.io.*;
import java.net.*;
public class Serverr {
public static void main(String[] args) {
try{
ServerSocket s = new ServerSocket(6666);
Socket socket = s.accept();
DataInputStream in = new DataInputStream( socket.getInputStream() );
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
String data ="";
String c = "";
while( !data.equals("stop") ){
System.out.println("Server says:");
data = br.readLine();
dos.writeUTF(data);
dos.flush();
c = (String)in.readUTF();
System.out.println("Cleint says:"+c);
}
br.close();
in.close();
dos.close();
s.close();
System.out.println("Welecome "+data);
s.close();
}catch( IOException e ){
System.out.println(e.getMessage());
}
}
}
|
package com.example.testproject.first_setting;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.fragment.app.Fragment;
import com.example.testproject.R;
public class FifthPermissionSettingFragment extends Fragment {
private Button btnNext;
public FifthPermissionSettingFragment() {
// Required empty public constructor
}
public static FifthPermissionSettingFragment newInstance() {
return new FifthPermissionSettingFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_set_fifth_permission_setting, container, false);
btnNext = view.findViewById(R.id.btn_next);
if (getActivity() != null) {
btnNext.setOnClickListener(v -> ((FirstSettingActivity)getActivity()).addFragment(SixthCallSetFragment.newInstance()));
}
return view;
}
} |
package algorithms.search;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import algorithms.maze.Position;
/**
* Solution is a class that represents the path between the start point and the goal point-
* it is the Solution for a searchable - consists from a linkedList
* @author Tuval Lifshitz
*
*/
public class Solution implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Position> mySolution;
/**
* initialize the LinkedList
*/
public Solution(){
mySolution = new LinkedList<Position>();
}
/**
* return the Soultion of the maze
* @return the Solution for the maze
*/
public List<Position> getMySolution() {
return mySolution;
}
/**
* Setting a Solution for the class
* @param mySolution the Solution to copy
*/
public void setMySolution(List<Position> mySolution) {
this.mySolution = mySolution;
}
}
|
//解析jar文件。获取jar中。后缀为class文件的全限定名。而且判断。该class文件。是否继承和实现某个接口。
//以下是测试类
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.*;
public class JarDir {
public static void main (String args[])
throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
List<String > size=new ArrayList<String>();
//JarFile jarFile = new JarFile("D:/projectList2017_10_24reconciliation_ba_pageconfig/reconciliation_ba/target/classes/deploy/1311-v1.0.0.jar");
String des="E:/projectall/androidProject/testa/lib";
String namess="yjp.jar";
@SuppressWarnings("resource")
JarFile jarFile = new JarFile(des+ File.separator+namess);
File file=new File(des+File.separator+namess);
URL url=file.toURI().toURL();
ClassLoader loader=new URLClassLoader(new URL[]{url});
// 当你有了该JAR文件的一个引用之后,你就可以读取其文件内容中的目录信息了。JarFile的entries方法返回所有entries的枚举集合 (Enumeration)。通过每一个entry,你可以从它的manifest文件得到它的属性,任何认证信息,以及其他任何该entry的信息,如它的名字或者大小等。
Enumeration<?> files = jarFile.entries();
while (files .hasMoreElements()) {
//process(files .nextElement(),size,loader);
JarEntry element = (JarEntry) files.nextElement();
String name = element.getName();
long size1 = element.getSize();
long time = element.getTime();
long compressedSize = element.getCompressedSize();
System.out.print(name+"\t");
System.out.print(size1+"\t");
System.out.print(compressedSize+"\t");
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(new Date(time)));
}
System.out.println(size.toString());
}
private static void process(Object obj,List<String > size ,ClassLoader loader) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
JarEntry entry = (JarEntry)obj;
String name = entry.getName();
//格式化
formatName( size, name, loader);
}
private static void formatName(List<String> size, String name,ClassLoader loader) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
if(!name.endsWith(".MF")){
if(name.endsWith(".class")){
String d=name.replaceAll("/",".");
int n=6;
//第一个参数是开始截取的位置,第二个是结束位置。
String names=d.substring(0,name.length()-n);
/*动态加载指定jar包调用其中某个类的方法*/
Class<?> cls=loader.loadClass(names);//加载指定类,注意一定要带上类的包名
Class<?> lifeCycle= com.jcraft.jsch.ChannelShell.class;
System.out.println(names+"="+lifeCycle.isAssignableFrom(cls));
if(lifeCycle.isAssignableFrom(cls)){
size.add(names);
}
}
}
}
}
|
package me.rainnny;
import me.rainnny.util.RainnnyFile;
import net.md_5.bungee.config.Configuration;
import java.util.List;
public class Settings {
public static List<String> MOTD_LINES;
public static String MOTD_NEWS;
public static String STAFF_CONNECT;
public static String STAFF_SWITCH;
public static String STAFF_DISCONNECT;
public static String STAFF_STAFFCHAT;
public static String STAFF_MANAGERCHAT;
public static String HUB_CONNECTING;
public static List<String> HUB_SERVERS;
public static String REQUEST_SENT;
public static String REQUEST_STAFF;
public static String REPORT_SENT;
public static String REPORT_STAFF;
public static boolean ANTIVPN_ENABLED;
public static List<String> ANTIVPN_KICK;
public static boolean WHITELISTED;
public static String WHITELISTED_PLAYERCOUNT;
public static List<String> WHITELISTED_KICK;
public static List<String> WHITELISTED_PLAYERS;
public static boolean LOGS;
static {
Configuration config = RainnnyFile.config;
MOTD_LINES = config.getStringList("motd.lines");
MOTD_NEWS = config.getString("motd.news");
STAFF_CONNECT = config.getString("staff.connect");
STAFF_SWITCH = config.getString("staff.server-switch");
STAFF_DISCONNECT = config.getString("staff.disconnect");
STAFF_STAFFCHAT = config.getString("staff.staffchat");
STAFF_MANAGERCHAT = config.getString("staff.managerchat");
HUB_CONNECTING = config.getString("hub.connecting");
HUB_SERVERS = config.getStringList("hub.servers");
REQUEST_SENT = config.getString("request.sent");
REQUEST_STAFF = config.getString("request.staff");
REPORT_SENT = config.getString("report.sent");
REPORT_STAFF = config.getString("report.staff");
ANTIVPN_ENABLED = config.getBoolean("anti-vpn.enabled");
ANTIVPN_KICK = config.getStringList("anti-vpn.kick");
WHITELISTED = config.getBoolean("whitelist.toggled");
WHITELISTED_PLAYERCOUNT = config.getString("whitelist.player-count");
WHITELISTED_KICK = config.getStringList("whitelist.kick");
WHITELISTED_PLAYERS = config.getStringList("whitelist.players");
LOGS = config.getBoolean("logs");
}
} |
package api.valorevaluacion;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RepositorioValorEvaluacion extends JpaRepository<EntidadValorEvaluacion, Integer> {
}
|
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.http.user;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.yx.conf.AppInfo;
import org.yx.http.HttpErrorCode;
import org.yx.http.HttpHeaderName;
import org.yx.http.HttpSettings;
import org.yx.http.kit.InnerHttpUtil;
import org.yx.log.Log;
import org.yx.util.S;
import org.yx.util.StringUtil;
import org.yx.util.UUIDSeed;
public abstract class AbstractLoginServlet implements LoginServlet {
private static final String LOGIN_NAME = "*login*";
private UserSession session;
protected String type = "";
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final long begin = System.currentTimeMillis();
boolean success = false;
try {
if (!acceptMethod(req, resp)) {
Log.get("sumk.http.login").warn("不是有效的method,只能使用GET或POST");
return;
}
resp.setContentType("application/json;charset=" + InnerHttpUtil.charset(req));
final String sid = createSessionId(req);
String user = getUserName(req);
LoginObject obj = login(sid, user, req);
Charset charset = InnerHttpUtil.charset(req);
if (obj == null) {
InnerHttpUtil.error(req, resp, HttpErrorCode.LOGINFAILED, user + " : login failed");
return;
}
if (obj.getErrorMsg() != null) {
InnerHttpUtil.error(req, resp, HttpErrorCode.LOGINFAILED, obj.getErrorMsg());
return;
}
byte[] key = createEncryptKey(req);
boolean singleLogin = WebSessions.isSingleLogin(this.getType(req));
if (!session.setSession(sid, obj.getSessionObject(), key, singleLogin)) {
Log.get("sumk.http.login").debug("{} :sid:{} login failed", user, sid);
InnerHttpUtil.error(req, resp, HttpErrorCode.LOGINFAILED, user + " : login failed");
return;
}
String userId = obj.getSessionObject().getUserId();
resp.setHeader(HttpHeaderName.sessionId(), sid);
if (StringUtil.isNotEmpty(userId)) {
resp.setHeader(HttpHeaderName.token(), userId);
}
outputKey(resp, key);
if (HttpSettings.isCookieEnable()) {
String contextPath = req.getContextPath();
if (!contextPath.startsWith("/")) {
contextPath = "/" + contextPath;
}
String attr = ";Path=".concat(contextPath);
setSessionCookie(req, resp, sid, attr);
setTokenCookie(req, resp, userId, attr);
setTypeCookie(req, resp, attr);
}
resp.getOutputStream().write(new byte[] { '\t', '\n' });
if (obj.getResponseData() != null) {
resp.getOutputStream().write(obj.getResponseData().getBytes(charset));
}
success = true;
} catch (Exception e) {
Log.get("sumk.http.login").error(e.toString(), e);
InnerHttpUtil.error(req, resp, HttpErrorCode.LOGINFAILED, "login fail");
} finally {
InnerHttpUtil.record(LOGIN_NAME, System.currentTimeMillis() - begin, success);
}
}
protected boolean acceptMethod(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String method = req.getMethod().toUpperCase();
if (!"GET".equals(method) && !"POST".equals(method)) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, method + " not allowd");
return false;
}
return true;
}
protected String getUserName(HttpServletRequest req) {
return req.getParameter(AppInfo.get("sumk.http.username", "username"));
}
protected void setSessionCookie(HttpServletRequest req, HttpServletResponse resp, final String sid, String attr) {
StringBuilder cookie = new StringBuilder();
cookie.append(HttpHeaderName.sessionId()).append('=').append(sid).append(attr);
resp.addHeader("Set-Cookie", cookie.toString());
}
protected void setTokenCookie(HttpServletRequest req, HttpServletResponse resp, String userId, String attr) {
if (WebSessions.isSingleLogin(this.getType(req)) && StringUtil.isNotEmpty(userId)) {
StringBuilder cookie = new StringBuilder();
cookie.append(HttpHeaderName.token()).append('=').append(userId).append(attr);
resp.addHeader("Set-Cookie", cookie.toString());
}
}
protected void outputKey(HttpServletResponse resp, byte[] key) throws IOException {
resp.getOutputStream().write(S.base64.encode(key));
}
protected byte[] createEncryptKey(HttpServletRequest req) {
byte[] key = UUIDSeed.seq().substring(4).getBytes();
return key;
}
protected String createSessionId(HttpServletRequest req) {
return UUIDSeed.random();
}
@Override
public void init(ServletConfig config) {
session = WebSessions.loadUserSession();
}
protected UserSession userSession() {
return session;
}
/**
* @param sessionId
* http头部sid的信息
* @param user
* 对应于http parameter的username
* @param req
* 用户请求的HttpServletRequest对象
* @return 登陆信息,无论成功与否,返回值不能是null
*/
protected abstract LoginObject login(String sessionId, String user, HttpServletRequest req);
@Override
public String getType(HttpServletRequest req) {
return type;
}
protected void setTypeCookie(HttpServletRequest req, HttpServletResponse resp, String attr) {
StringBuilder cookie = new StringBuilder();
String type = this.getType(req);
if (StringUtil.isNotEmpty(type)) {
cookie.append(HttpHeaderName.type()).append('=').append(type).append(attr);
resp.addHeader("Set-Cookie", cookie.toString());
}
}
@Override
public boolean acceptType(String type) {
if (StringUtil.isEmpty(type)) {
return StringUtil.isEmpty(this.type);
}
return type.equals(this.type);
}
}
|
package com.edasaki.rpg.holograms;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.world.ChunkLoadEvent;
import com.edasaki.core.utils.ChunkWrapper;
import com.edasaki.core.utils.RScheduler;
import com.edasaki.core.utils.RTicks;
import com.edasaki.rpg.AbstractManagerRPG;
import com.edasaki.rpg.SakiRPG;
public class HologramManager extends AbstractManagerRPG {
public static ArrayList<Hologram> holograms = new ArrayList<Hologram>();
public static HashMap<ChunkWrapper, ArrayList<Hologram>> hologramsPerChunk = new HashMap<ChunkWrapper, ArrayList<Hologram>>();
public HologramManager(SakiRPG plugin) {
super(plugin);
}
@Override
public void initialize() {
reload();
}
public static void reload() {
for (Hologram h : holograms) {
unregister(h);
}
holograms.clear();
File dir = new File(plugin.getDataFolder(), "holograms");
if (!dir.exists())
dir.mkdirs();
for (File f : dir.listFiles()) {
if (f.getName().endsWith(".txt")) {
readHologram(f);
}
}
}
public static void readHologram(File f) {
Scanner scan = null;
try {
scan = new Scanner(f);
while (scan.hasNextLine()) {
String s = scan.nextLine().trim();
if (s.startsWith("//") || s.length() == 0)
continue;
try {
String[] data = s.split(" ");
double x = Double.parseDouble(data[0]);
double y = Double.parseDouble(data[1]);
double z = Double.parseDouble(data[2]);
World w = plugin.getServer().getWorld(data[3]);
if (w == null) {
throw new Exception("Error: could not find holo world at line " + s + " in file " + f);
}
Location loc = new Location(w, x, y, z);
StringBuilder sb = new StringBuilder();
for (int k = 4; k < data.length; k++) {
sb.append(data[k]);
sb.append(' ');
}
Hologram holo = new Hologram(ChatColor.translateAlternateColorCodes('&', sb.toString().trim()), loc);
holo.spawn();
register(holo);
} catch (Exception e) {
System.out.println("Error reading hologram on line " + s + " in file " + f);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (scan != null)
scan.close();
}
}
public static void register(Hologram holo) {
ChunkWrapper cw = new ChunkWrapper(holo.loc.getChunk());
if (!hologramsPerChunk.containsKey(cw)) {
hologramsPerChunk.put(cw, new ArrayList<Hologram>());
}
hologramsPerChunk.get(cw).add(holo);
holograms.add(holo);
}
public static void unregister(Hologram holo) {
try {
holo.despawn();
} catch (Exception e) {
e.printStackTrace();
}
ChunkWrapper cw = new ChunkWrapper(holo.loc.getChunk());
if (hologramsPerChunk.containsKey(cw)) {
hologramsPerChunk.get(cw).remove(holo);
}
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
handleChunk(event.getChunk());
}
public static void handleChunk(Chunk chunk) {
final ChunkWrapper cw = new ChunkWrapper(chunk);
if (!hologramsPerChunk.containsKey(cw))
return;
RScheduler.schedule(plugin, new Runnable() {
public void run() {
ArrayList<Hologram> holos = hologramsPerChunk.get(cw);
for (Hologram h : holos)
h.spawn();
}
}, RTicks.seconds(2));
}
}
|
package com.indoorpositioning.services;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.indoorpositioning.PositioningVariables;
import com.indoorpositioning.persistence.History;
import com.indoorpositioning.persistence.HistoryRepository;
import com.indoorpositioning.persistence.Receiver;
import com.indoorpositioning.persistence.ReceiverRepository;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.awt.Color;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@Service
public class HistoryService {
@Resource
private HistoryRepository historyRepository;
@Resource
private ReceiverRepository receiverRepository;
public List<Object> getLocation(Integer id_bk){
//Pageable limita el numero de filas devueltos por la bd
Pageable pagRcvHistories = PageRequest.of(0,PositioningVariables.maxHistoriesRcv);
//Obtener todos los receivers
List<Receiver> rcvList = receiverRepository.findAll();
//Esta lista contiene el historial conocido de las n ultimas n(pageable) historias de cada receptor
List<History> historyList = new ArrayList<>();
Integer id_rcv;
//Esta lista contendra This list will contain the last n (pageable) histories of a receiver
List<History> lastHistories=new ArrayList<>();
Integer n=0;
Pageable pagLastNHistory;
//Adaptamos el formato de las fechas
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
History lastHistory;
Date lastHistoryDate;
Date dateLimit;
String lastHistoryDateStr;
String dateLimitStr;
while (historyList.isEmpty()) {
//Obtener la n-th history ordenada por fecha descendiente
pagLastNHistory=PageRequest.of(n, 1);
try {
lastHistory=historyRepository.getLastHistoryOfBk(id_bk,pagLastNHistory).get(0);
System.out.println("Ultima hist: "+lastHistory.getDate());
} catch (NullPointerException e) {
e.printStackTrace();
//No hay mas histories para el beacon
return null;
}
lastHistoryDate=lastHistory.getDate();
//lastHistory date -maxHistoriesDiff_Minutes minutes
dateLimit=subtractMinToDate(lastHistoryDate, PositioningVariables.maxHistoriesDiff_Minutes);
lastHistoryDateStr=dateFormat.format(lastHistoryDate);
dateLimitStr=dateFormat.format(dateLimit);
System.out.println("lhd: "+lastHistoryDateStr);
System.out.println("dlim: "+dateLimitStr);
//Bucle a traves de todos los rcvs
for (int i = 0; i < rcvList.size(); i++) {
id_rcv = rcvList.get(i).getId_rcv();
System.out.println("RCV: "+id_rcv);
lastHistories = historyRepository.getLastHistoriesOfBkInRcv(id_bk, id_rcv,dateLimitStr,lastHistoryDateStr, pagRcvHistories);
System.out.println("Ultims hist: "+lastHistories.size());
//Si hay histories del receiver para el beacon seleccionado calcula la ubicacion conocida rssi
if (lastHistories.size() >= PositioningVariables.minHistoriesRcv) {
History meanHistory = calculateRSSIMean(lastHistories);
historyList.add(meanHistory);
System.out.println("mean: "+meanHistory.getId_history()+" "+meanHistory.getRssi()+" "+meanHistory.getDate());
}
}
if (historyList.size()<PositioningVariables.minRcvs) {
System.out.println("EMPTY");
System.out.println("SIZE: "+historyList.size());
System.out.println("MINSIZE: "+PositioningVariables.minRcvs);
//Vacia el historyList array por que no hay demasiados receivers para el calculo
historyList.clear();
//Para obtener el siguientes last history
n++;
}
}
//Ordena la lista por rssi: rssi1>rss2>....
historyList.sort((o1, o2) -> o2.getRssi().compareTo(o1.getRssi()));
//Crea una nueva lista con el primer (best) n receivers (maxRcvs)
List<History> historySubList = new ArrayList<>();
//Si hay menos receivers que el maximo permitido para hacer el calculo entonces obtener todos
if (historyList.size() < PositioningVariables.maxRcvs) {
List<Receiver> unusedReceivers=getUnusedReceivers(historyList, rcvList);
return getRcvPositionsAndDistances(historyList,unusedReceivers);
}
//If there are more receivers than the maximum permitted to make the calculation then get the first (best) n receivers (maxRcvs)
//Si hay mas receivers que el maximo permitido para hacer el calculo entonces obtener el primer (best) n receivers (maxRcvs)
else {
for (int i=0; i<PositioningVariables.maxRcvs; i++) {
historySubList.add(historyList.get(i));
}
List<Receiver> unusedReceivers=getUnusedReceivers(historySubList, rcvList);
return getRcvPositionsAndDistances(historySubList,unusedReceivers);
}
}
private Date subtractMinToDate(Date d1,Integer minutes) {
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
cal.add(Calendar.MINUTE, -minutes);
return cal.getTime();
}
private List<Receiver> getUnusedReceivers(List<History> usedHistories,List<Receiver> rcvList){
List<Receiver> unusedReceivers=new ArrayList<>();
Boolean rcvUsed;
for (int i = 0; i < rcvList.size(); i++) {
rcvUsed=false;
for (History history : usedHistories) {
if (history.getReceiver().getId_rcv()==rcvList.get(i).getId_rcv()) {
rcvUsed=true;
break;
}
}
if (!rcvUsed) {
unusedReceivers.add(rcvList.get(i));
}
}
return unusedReceivers;
}
//Crea una history con el rssi conocido del ultimo n (especificado by pageable variable) histories
private History calculateRSSIMean(List<History> lastHistories) {
Float calc = (float) 0.0;
//Getting the last history as reference
//Obtener la ultima historia como referencia
History history = lastHistories.get(0);
for (int i=0; i<lastHistories.size(); i++) {
calc += lastHistories.get(i).getRssi();
}
Integer meanRSSI = Math.round(calc / lastHistories.size());
history.setRssi(meanRSSI);
return history;
}
// Genera una lista 'x_y_distance' con la posición x e y del receptor y la distancia (basada en el rssi) de cada historial seleccionado (listo para evaluar)
private List<Object> getRcvPositionsAndDistances(List<History> historySubList, List<Receiver> unusedReceivers){
// Fecha de la historia más reciente
String usedLastHistoryDate = getLastHistoryDate(historySubList);
History h;
Double distance = 0.0;
// Simula una lista de x_pos, y_pos y tripletas de distancia
List<Double> x_y_distance = new ArrayList<>();
for (int i=0; i<historySubList.size(); i++) {
h = historySubList.get(i);
distance = rssiFormula((double)h.getRssi());
x_y_distance.add((double)h.getReceiver().getX_pos());
x_y_distance.add((double)h.getReceiver().getY_pos());
x_y_distance.add(distance);
}
return calculatePosition(x_y_distance,unusedReceivers,usedLastHistoryDate);
}
private String getLastHistoryDate(List<History> historySubList) {
String lastHistoryDate=null;
String historyDate=null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (History history : historySubList) {
historyDate=dateFormat.format(history.getDate());
// Si es el primer historial que se evalúa o la fecha guardada es anterior a la evaluada
//A.compareTo(B): 0 si son iguales, 1 si A> B y -1 si A <B
if (lastHistoryDate==null||lastHistoryDate.compareTo(historyDate)==-1) {
lastHistoryDate=historyDate;
}
}
return lastHistoryDate;
}
// Para calcular la diferencia horaria entre la fecha del historial y ahora
private Integer calculateDayDiff(String lastHistoryDateStr) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now=new Date();
Date lastHistoryDate=null;
try {
lastHistoryDate = dateFormat.parse(lastHistoryDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
// Fecha de diferencia en milisegundos
long diff_millis = now.getTime() - lastHistoryDate.getTime();
Integer diff_hours=(int) (diff_millis / (1000 * 60 * 60));
return diff_hours;
}
// Para determinar el color de la baliza dependiendo de cuándo llegó el último historial
private Color calculateBeaconColor(Integer diff_hours) {
Color c=null;
if (diff_hours<PositioningVariables.dateDiffRange1_Hours) {
c=PositioningVariables.range1Color;
}
else if (diff_hours>=PositioningVariables.dateDiffRange1_Hours&&diff_hours<PositioningVariables.dateDiffRange2_Hours) {
c=PositioningVariables.range2Color;
}
else {
c=PositioningVariables.range3Color;
}
return c;
}
// Para calcular la distancia en función del valor rssi
private static Double rssiFormula(Double rssi) {
Double n = 1.7;
Double rssiFactor = -55.0;
Double raise = (rssiFactor-rssi) / (10*n);
Double result = Math.pow(10, raise);
return result;
}
// Itera a través de la lista 'x_y_distance' para calcular la posición x e y de la baliza
private List<Object> calculatePosition(List<Double> x_y_distance,List<Receiver> unusedReceivers,String usedLastHistoryDate){
Double sumFactors = 0.0;
Double x_pos = 0.0;
Double y_pos = 0.0;
// Iterar a través de la lista para obtener los sumFactors
for (int i=0; i<x_y_distance.size(); i=i+3) {
Double distance = x_y_distance.get(i+2);
sumFactors += (1/distance);
}
for (int j=0; j<x_y_distance.size(); j=j+3) {
Double x = x_y_distance.get(j);
Double y = x_y_distance.get(j+1);
Double distance = x_y_distance.get(j+2);
//Factor de multiplicación
Double f = (1/distance) / sumFactors;
x_pos += x*f;
y_pos += y*f;
}
List<Receiver> usedReceiverData = new ArrayList<>();
Receiver r;
for (int i=0; i<x_y_distance.size(); i=i+3) {
// Objeto receptor temporal para pintarlo en el mapa
r = new Receiver(0, (int)Math.round(x_y_distance.get(i)),(int)Math.round(x_y_distance.get(i+1)));
usedReceiverData.add(r);
}
if(x_pos != null && y_pos != null) {
// Redondeando la posición
Integer pointX = (int) Math.round(x_pos);
Integer pointY = (int) Math.round(y_pos);
// Determinar la diferencia de fecha y el color relacionado
Integer diff_hours=calculateDayDiff(usedLastHistoryDate);
Color color=calculateBeaconColor(diff_hours);
LocationPainter lp = new LocationPainter();
try {
// Pinta la ubicación de la baliza y todos los receptores (incluso los que no se utilizan en el cálculo) en el mapa / imagen
byte [] bi = lp.createImageWithLocation("src/main/resources/static/images/plano-airbus.png", pointX, pointY, usedReceiverData,unusedReceivers,color);
// Para devolver ambas informaciones: el mapa / ubicación pintada y la fecha del historial más reciente utilizado
List<Object> response=new ArrayList<>();
response.add(bi);
response.add(usedLastHistoryDate);
return response;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
|
package com.test.demo;
public class MyTestClass {
public static void main(String[] str){
System.out.print("我是测试java工程");
}
}
|
package ua.com.blackjack;
import java.util.ArrayList;
import java.util.List;
import ua.com.blackjack.card.*;
public class Hand {
private List<Card> cards;
private final int BLACKJACK = 21;
public Hand() {
cards = new ArrayList<>();
}
public void addCard(Card card) {
cards.add(card);
}
public int countPoints() {
int result = 0;
int aceCount = 0;
for (Card card : cards) {
result += card.getScore();
if (card.isAce()) {
aceCount++;
}
}
while (aceCount > 0) {
if (result > BLACKJACK) {
result = result - 10;
aceCount--;
} else {
break;
}
}
return result;
}
public boolean isBusted() {
return this.countPoints() > BLACKJACK;
}
public boolean isBlackjack() {
return this.countPoints() == BLACKJACK;
}
public Card getCard(int index) {
return cards.get(index);
}
public int getNumberOfCards() {
return cards.size();
}
@Override
public String toString() {
return cards.toString() + ". Total points: " + countPoints();
}
}
|
/*
* 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 lk.vcnet.storemodule.client.user_interfaces;
import java.awt.Dimension;
import lk.vcnet.storemodule.client.main.ClientMain;
/**
*
* @author user
*/
public class SearchBrand extends javax.swing.JInternalFrame {
/**
* Creates new form SearchBrand
*/
public static SearchBrand instance;
public SearchBrand() {
initComponents();
setVisible(true);
Dimension dm=this.getSize();
this.setLocation((ClientMain.getDisplaySize().width - dm.width)/2, (ClientMain.getDisplaySize().height - 80 - dm.height)/2);
}
public static synchronized SearchBrand getInstance()
{
if(instance==null) instance=new SearchBrand();
return instance;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
tbrandname = new javax.swing.JTextField();
cBID = new javax.swing.JComboBox();
jPanel2 = new javax.swing.JPanel();
bsearch = new javax.swing.JButton();
bupdate = new javax.swing.JButton();
bdelete = new javax.swing.JButton();
bclear = new javax.swing.JButton();
bcancel = new javax.swing.JButton();
setTitle("SEARCH & CHANGE BRAND DETAILS");
jLabel1.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N
jLabel1.setText("Brand ID");
jLabel2.setFont(new java.awt.Font("Courier New", 1, 14)); // NOI18N
jLabel2.setText("Brand Name");
tbrandname.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tbrandnameActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tbrandname, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
.addComponent(cBID, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cBID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tbrandname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(45, Short.MAX_VALUE))
);
bsearch.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
bsearch.setText("SEARCH");
bsearch.setPreferredSize(new java.awt.Dimension(120, 29));
bupdate.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
bupdate.setText("UPDATE");
bupdate.setPreferredSize(new java.awt.Dimension(120, 29));
bdelete.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
bdelete.setText("DELETE");
bdelete.setPreferredSize(new java.awt.Dimension(120, 29));
bclear.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
bclear.setText("CLEAR");
bclear.setPreferredSize(new java.awt.Dimension(120, 29));
bcancel.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
bcancel.setText("BACK");
bcancel.setPreferredSize(new java.awt.Dimension(120, 29));
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(bsearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(bclear, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bdelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bupdate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(bcancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(bsearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(bupdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(bdelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(bclear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(bcancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void tbrandnameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbrandnameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tbrandnameActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bcancel;
private javax.swing.JButton bclear;
private javax.swing.JButton bdelete;
private javax.swing.JButton bsearch;
private javax.swing.JButton bupdate;
private javax.swing.JComboBox cBID;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField tbrandname;
// End of variables declaration//GEN-END:variables
}
|
package algorithms.search.symboltable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import algorithms.search.ST;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by Chen Li on 2017/6/17.
*/
public abstract class SearchSTTest {
@Test
public void testPut() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("1", "3");
assertEquals("size wrong!", st.size(), 2);
}
@Test
public void testGet() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("1", "3");
assertEquals("get wrong", st.get("1"), "3");
}
@Test
public void testGetNonExist() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("1", "3");
assertEquals("get wrong", st.get("4"), null);
}
@Test
public void testContains() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("1", "3");
assertEquals("get wrong", st.contains("1"), true);
}
@Test
public void testDeleteOne() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.delete("1");
assertEquals("delete wrong", 0, st.size());
}
@Test
public void testDeleteFirst() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("3", "3");
st.delete("1");
assertEquals("delete wrong", 2, st.size());
assertEquals("delete wrong", "2", st.get("2"));
assertEquals("delete wrong", "3", st.get("3"));
}
@Test
public void testDeleteSecond() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("3", "3");
st.delete("2");
assertEquals("delete wrong", st.size(), 2);
assertEquals("delete wrong", st.get("1"), "1");
assertEquals("delete wrong", st.get("3"), "3");
}
@Test
public void testDeleteNonExist() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("3", "3");
st.delete("4");
assertEquals("delete wrong", st.size(), 3);
}
@Test
public void testSizeEmpty() throws Exception {
ST<String,String> st = createST();
assertEquals("size wrong", st.size(), 0);
}
@Test
public void testSizeNonEmpty() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
st.put("2", "2");
st.put("1", "3");
assertEquals("size wrong", st.size(), 2);
}
@Test
public void testIsEmptyFirst() throws Exception {
ST<String,String> st = createST();
assertEquals("IsEmpty wrong", st.isEmpty(), true);
}
@Test
public void testIsEmptyFalse() throws Exception {
ST<String,String> st = createST();
st.put("1", "1");
assertEquals("IsEmpty wrong", st.isEmpty(), false);
}
@Test
public void testEmptyKeys() throws Exception {
ST<String,String> st = createST();
Iterable keys = st.keys();
Iterator keysIterator = keys.iterator();
assertEquals("keys wrong", keysIterator.hasNext(), false);
}
@Test
public void testKeys() throws Exception {
ST<String,String> st = createST();
List<String> originalKeys = new ArrayList<>();
for (int i = 0; i < 10; i++) {
String key = String.valueOf(i);
st.put(key, key);
originalKeys.add(key);
}
List<String> gotKeys = new ArrayList<>();
for (String key : st.keys()) {
gotKeys.add(key);
}
boolean equalKeys = CollectionUtils.isEqualCollection(originalKeys, gotKeys);
assertEquals("keys wrong", equalKeys, true);
}
public abstract ST<String, String> createST();
}
|
package com.qa.concepts;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class DragAndDrop {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver","D:/AutomationJars/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get("http://jqueryui.com/droppable/");
Thread.sleep(8000);
driver.switchTo().frame(0);
Actions action = new Actions(driver);
WebElement src = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
action.clickAndHold(src)
.moveToElement(target)
.release()
.build().perform();
}
}
|
package com.db.persistence.services;
/**
* Created by taljmars on 4/28/17.
*/
public interface SessionsSvc extends TokenAwareSvc {
void setToken(String token);
/**
* The following publish all the private changes to the public database.
* After this action no object should exist under the private session of the user.
*/
void publish();
/**
* The following discard all the changes the user have made in it session.
* After this action no object should exist under the private session.
*/
void discard();
}
|
package com.paces.game.estados;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;
import com.paces.game.Main;
import com.paces.game.planets.Planetas;
public class BlueSun extends Planetas {
public BlueSun(float escala, float x, float y, float z, float luzDirX, float luzDirY, float luzDirZ){
eje = 0f;
batch = new SpriteBatch();
font = new BitmapFont();
setSrings();
textura = Main.assets.manager.get("MPrincipal/texturaSolAzul.png");
ambiente = new Environment();
dirLuz = new DirectionalLight().set(1.8f, 1.8f, 1.8f, luzDirX, luzDirY, luzDirZ);
ModelBuilder modelBuilder = new ModelBuilder();
modelo = modelBuilder.createSphere(escala, escala, escala, 32, 32,new Material(TextureAttribute.createDiffuse(textura)),
VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal | VertexAttributes.Usage.TextureCoordinates);
instancia = new ModelInstance(modelo, x, y, z);
instancia.transform.rotate(1f, 0f, 0f, eje);
ambiente.set(new ColorAttribute(ColorAttribute.AmbientLight, .1f, .1f, .1f, .3f));
ambiente.add(dirLuz);
}
@Override
public void rotacion(float rotateX, float rotateY, float rotateZ, float degRotate) {
instancia.transform.rotate(rotateX, rotateY, rotateZ, degRotate);
}
@Override
public void animacion() {
Vector3 escalaFinal = new Vector3(1f ,1f, 1f);
if(x <= escalaFinal.x){
x = x + 0.01f;
y = y + 0.01f;
z = z + 0.01f;
instancia.transform.setToScaling(x, y, z);
instancia.transform.rotate(1f, 0f, 0f, eje);
}
}
@Override
public void mostrarInfo() {
}
@Override
public void setSrings() {
}
}
|
package com.app;
public class SimpleFactory {
public Object createObject(String name){
if("emp".equalsIgnoreCase(name)){
return new Employee(10,"ABCD");
}else{
return new Address(104,"Rayachoty");
}
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.aop.aspectj;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.aspectj.weaver.tools.PointcutExpression;
import org.aspectj.weaver.tools.PointcutPrimitive;
import org.aspectj.weaver.tools.UnsupportedPointcutPrimitiveException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import test.annotation.EmptySpringAnnotation;
import test.annotation.transaction.Tx;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.testfixture.beans.IOther;
import org.springframework.beans.testfixture.beans.ITestBean;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.beans.testfixture.beans.subpkg.DeepBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* @author Rob Harrop
* @author Rod Johnson
* @author Chris Beams
*/
public class AspectJExpressionPointcutTests {
public static final String MATCH_ALL_METHODS = "execution(* *(..))";
private Method getAge;
private Method setAge;
private Method setSomeNumber;
private final Map<String, Method> methodsOnHasGeneric = new HashMap<>();
@BeforeEach
public void setUp() throws NoSuchMethodException {
getAge = TestBean.class.getMethod("getAge");
setAge = TestBean.class.getMethod("setAge", int.class);
setSomeNumber = TestBean.class.getMethod("setSomeNumber", Number.class);
// Assumes no overloading
for (Method method : HasGeneric.class.getMethods()) {
methodsOnHasGeneric.put(method.getName(), method);
}
}
@Test
public void testMatchExplicit() {
String expression = "execution(int org.springframework.beans.testfixture.beans.TestBean.getAge())";
Pointcut pointcut = getPointcut(expression);
ClassFilter classFilter = pointcut.getClassFilter();
MethodMatcher methodMatcher = pointcut.getMethodMatcher();
assertMatchesTestBeanClass(classFilter);
// not currently testable in a reliable fashion
//assertDoesNotMatchStringClass(classFilter);
assertThat(methodMatcher.isRuntime()).as("Should not be a runtime match").isFalse();
assertMatchesGetAge(methodMatcher);
assertThat(methodMatcher.matches(setAge, TestBean.class)).as("Expression should match setAge() method").isFalse();
}
@Test
public void testMatchWithTypePattern() throws Exception {
String expression = "execution(* *..TestBean.*Age(..))";
Pointcut pointcut = getPointcut(expression);
ClassFilter classFilter = pointcut.getClassFilter();
MethodMatcher methodMatcher = pointcut.getMethodMatcher();
assertMatchesTestBeanClass(classFilter);
// not currently testable in a reliable fashion
//assertDoesNotMatchStringClass(classFilter);
assertThat(methodMatcher.isRuntime()).as("Should not be a runtime match").isFalse();
assertMatchesGetAge(methodMatcher);
assertThat(methodMatcher.matches(setAge, TestBean.class)).as("Expression should match setAge(int) method").isTrue();
}
@Test
public void testThis() throws SecurityException, NoSuchMethodException{
testThisOrTarget("this");
}
@Test
public void testTarget() throws SecurityException, NoSuchMethodException {
testThisOrTarget("target");
}
/**
* This and target are equivalent. Really instanceof pointcuts.
* @param which this or target
*/
private void testThisOrTarget(String which) throws SecurityException, NoSuchMethodException {
String matchesTestBean = which + "(org.springframework.beans.testfixture.beans.TestBean)";
String matchesIOther = which + "(org.springframework.beans.testfixture.beans.IOther)";
AspectJExpressionPointcut testBeanPc = new AspectJExpressionPointcut();
testBeanPc.setExpression(matchesTestBean);
AspectJExpressionPointcut iOtherPc = new AspectJExpressionPointcut();
iOtherPc.setExpression(matchesIOther);
assertThat(testBeanPc.matches(TestBean.class)).isTrue();
assertThat(testBeanPc.matches(getAge, TestBean.class)).isTrue();
assertThat(iOtherPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isTrue();
assertThat(testBeanPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isFalse();
}
@Test
public void testWithinRootPackage() throws SecurityException, NoSuchMethodException {
testWithinPackage(false);
}
@Test
public void testWithinRootAndSubpackages() throws SecurityException, NoSuchMethodException {
testWithinPackage(true);
}
private void testWithinPackage(boolean matchSubpackages) throws SecurityException, NoSuchMethodException {
String withinBeansPackage = "within(org.springframework.beans.testfixture.beans.";
// Subpackages are matched by **
if (matchSubpackages) {
withinBeansPackage += ".";
}
withinBeansPackage = withinBeansPackage + "*)";
AspectJExpressionPointcut withinBeansPc = new AspectJExpressionPointcut();
withinBeansPc.setExpression(withinBeansPackage);
assertThat(withinBeansPc.matches(TestBean.class)).isTrue();
assertThat(withinBeansPc.matches(getAge, TestBean.class)).isTrue();
assertThat(withinBeansPc.matches(DeepBean.class)).isEqualTo(matchSubpackages);
assertThat(withinBeansPc.matches(
DeepBean.class.getMethod("aMethod", String.class), DeepBean.class)).isEqualTo(matchSubpackages);
assertThat(withinBeansPc.matches(String.class)).isFalse();
assertThat(withinBeansPc.matches(OtherIOther.class.getMethod("absquatulate"), OtherIOther.class)).isFalse();
}
@Test
public void testFriendlyErrorOnNoLocationClassMatching() {
AspectJExpressionPointcut pc = new AspectJExpressionPointcut();
assertThatIllegalStateException().isThrownBy(() ->
pc.matches(ITestBean.class))
.withMessageContaining("expression");
}
@Test
public void testFriendlyErrorOnNoLocation2ArgMatching() {
AspectJExpressionPointcut pc = new AspectJExpressionPointcut();
assertThatIllegalStateException().isThrownBy(() ->
pc.matches(getAge, ITestBean.class))
.withMessageContaining("expression");
}
@Test
public void testFriendlyErrorOnNoLocation3ArgMatching() {
AspectJExpressionPointcut pc = new AspectJExpressionPointcut();
assertThatIllegalStateException().isThrownBy(() ->
pc.matches(getAge, ITestBean.class, (Object[]) null))
.withMessageContaining("expression");
}
@Test
public void testMatchWithArgs() throws Exception {
String expression = "execution(void org.springframework.beans.testfixture.beans.TestBean.setSomeNumber(Number)) && args(Double)";
Pointcut pointcut = getPointcut(expression);
ClassFilter classFilter = pointcut.getClassFilter();
MethodMatcher methodMatcher = pointcut.getMethodMatcher();
assertMatchesTestBeanClass(classFilter);
// not currently testable in a reliable fashion
//assertDoesNotMatchStringClass(classFilter);
assertThat(methodMatcher.matches(setSomeNumber, TestBean.class, 12D)).as("Should match with setSomeNumber with Double input").isTrue();
assertThat(methodMatcher.matches(setSomeNumber, TestBean.class, 11)).as("Should not match setSomeNumber with Integer input").isFalse();
assertThat(methodMatcher.matches(getAge, TestBean.class)).as("Should not match getAge").isFalse();
assertThat(methodMatcher.isRuntime()).as("Should be a runtime match").isTrue();
}
@Test
public void testSimpleAdvice() {
String expression = "execution(int org.springframework.beans.testfixture.beans.TestBean.getAge())";
CallCountingInterceptor interceptor = new CallCountingInterceptor();
TestBean testBean = getAdvisedProxy(expression, interceptor);
assertThat(interceptor.getCount()).as("Calls should be 0").isEqualTo(0);
testBean.getAge();
assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1);
testBean.setAge(90);
assertThat(interceptor.getCount()).as("Calls should still be 1").isEqualTo(1);
}
@Test
public void testDynamicMatchingProxy() {
String expression = "execution(void org.springframework.beans.testfixture.beans.TestBean.setSomeNumber(Number)) && args(Double)";
CallCountingInterceptor interceptor = new CallCountingInterceptor();
TestBean testBean = getAdvisedProxy(expression, interceptor);
assertThat(interceptor.getCount()).as("Calls should be 0").isEqualTo(0);
testBean.setSomeNumber(30D);
assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1);
testBean.setSomeNumber(90);
assertThat(interceptor.getCount()).as("Calls should be 1").isEqualTo(1);
}
@Test
public void testInvalidExpression() {
String expression = "execution(void org.springframework.beans.testfixture.beans.TestBean.setSomeNumber(Number) && args(Double)";
assertThatIllegalArgumentException().isThrownBy(
getPointcut(expression)::getClassFilter); // call to getClassFilter forces resolution
}
private TestBean getAdvisedProxy(String pointcutExpression, CallCountingInterceptor interceptor) {
TestBean target = new TestBean();
Pointcut pointcut = getPointcut(pointcutExpression);
DefaultPointcutAdvisor advisor = new DefaultPointcutAdvisor();
advisor.setAdvice(interceptor);
advisor.setPointcut(pointcut);
ProxyFactory pf = new ProxyFactory();
pf.setTarget(target);
pf.addAdvisor(advisor);
return (TestBean) pf.getProxy();
}
private void assertMatchesGetAge(MethodMatcher methodMatcher) {
assertThat(methodMatcher.matches(getAge, TestBean.class)).as("Expression should match getAge() method").isTrue();
}
private void assertMatchesTestBeanClass(ClassFilter classFilter) {
assertThat(classFilter.matches(TestBean.class)).as("Expression should match TestBean class").isTrue();
}
@Test
public void testWithUnsupportedPointcutPrimitive() {
String expression = "call(int org.springframework.beans.testfixture.beans.TestBean.getAge())";
assertThatExceptionOfType(UnsupportedPointcutPrimitiveException.class).isThrownBy(() ->
getPointcut(expression).getClassFilter()) // call to getClassFilter forces resolution...
.satisfies(ex -> assertThat(ex.getUnsupportedPrimitive()).isEqualTo(PointcutPrimitive.CALL));
}
@Test
public void testAndSubstitution() {
Pointcut pc = getPointcut("execution(* *(..)) and args(String)");
PointcutExpression expr = ((AspectJExpressionPointcut) pc).getPointcutExpression();
assertThat(expr.getPointcutExpression()).isEqualTo("execution(* *(..)) && args(String)");
}
@Test
public void testMultipleAndSubstitutions() {
Pointcut pc = getPointcut("execution(* *(..)) and args(String) and this(Object)");
PointcutExpression expr = ((AspectJExpressionPointcut) pc).getPointcutExpression();
assertThat(expr.getPointcutExpression()).isEqualTo("execution(* *(..)) && args(String) && this(Object)");
}
private Pointcut getPointcut(String expression) {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(expression);
return pointcut;
}
public static class OtherIOther implements IOther {
@Override
public void absquatulate() {
// Empty
}
}
@Test
public void testMatchGenericArgument() {
String expression = "execution(* set*(java.util.List<org.springframework.beans.testfixture.beans.TestBean>) )";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
// TODO this will currently map, would be nice for optimization
//assertTrue(ajexp.matches(HasGeneric.class));
//assertFalse(ajexp.matches(TestBean.class));
Method takesGenericList = methodsOnHasGeneric.get("setFriends");
assertThat(ajexp.matches(takesGenericList, HasGeneric.class)).isTrue();
assertThat(ajexp.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)).isTrue();
assertThat(ajexp.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)).isFalse();
assertThat(ajexp.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)).isFalse();
assertThat(ajexp.matches(getAge, TestBean.class)).isFalse();
}
@Test
public void testMatchVarargs() throws Exception {
@SuppressWarnings("unused")
class MyTemplate {
public int queryForInt(String sql, Object... params) {
return 0;
}
}
String expression = "execution(int *.*(String, Object...))";
AspectJExpressionPointcut jdbcVarArgs = new AspectJExpressionPointcut();
jdbcVarArgs.setExpression(expression);
assertThat(jdbcVarArgs.matches(
MyTemplate.class.getMethod("queryForInt", String.class, Object[].class),
MyTemplate.class)).isTrue();
Method takesGenericList = methodsOnHasGeneric.get("setFriends");
assertThat(jdbcVarArgs.matches(takesGenericList, HasGeneric.class)).isFalse();
assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class)).isFalse();
assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class)).isFalse();
assertThat(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class)).isFalse();
assertThat(jdbcVarArgs.matches(getAge, TestBean.class)).isFalse();
}
@Test
public void testMatchAnnotationOnClassWithAtWithin() throws Exception {
String expression = "@within(test.annotation.transaction.Tx)";
testMatchAnnotationOnClass(expression);
}
@Test
public void testMatchAnnotationOnClassWithoutBinding() throws Exception {
String expression = "within(@test.annotation.transaction.Tx *)";
testMatchAnnotationOnClass(expression);
}
@Test
public void testMatchAnnotationOnClassWithSubpackageWildcard() throws Exception {
String expression = "within(@(test.annotation..*) *)";
AspectJExpressionPointcut springAnnotatedPc = testMatchAnnotationOnClass(expression);
assertThat(springAnnotatedPc.matches(TestBean.class.getMethod("setName", String.class), TestBean.class)).isFalse();
assertThat(springAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)).isTrue();
expression = "within(@(test.annotation.transaction..*) *)";
AspectJExpressionPointcut springTxAnnotatedPc = testMatchAnnotationOnClass(expression);
assertThat(springTxAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo"), SpringAnnotated.class)).isFalse();
}
@Test
public void testMatchAnnotationOnClassWithExactPackageWildcard() throws Exception {
String expression = "within(@(test.annotation.transaction.*) *)";
testMatchAnnotationOnClass(expression);
}
private AspectJExpressionPointcut testMatchAnnotationOnClass(String expression) throws Exception {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
assertThat(ajexp.matches(getAge, TestBean.class)).isFalse();
assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isTrue();
assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isTrue();
assertThat(ajexp.matches(BeanB.class.getMethod("setName", String.class), BeanB.class)).isTrue();
assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
return ajexp;
}
@Test
public void testAnnotationOnMethodWithFQN() throws Exception {
String expression = "@annotation(test.annotation.transaction.Tx)";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
assertThat(ajexp.matches(getAge, TestBean.class)).isFalse();
assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertThat(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertThat(ajexp.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isTrue();
assertThat(ajexp.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
}
@Test
public void testAnnotationOnCglibProxyMethod() throws Exception {
String expression = "@annotation(test.annotation.transaction.Tx)";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
ProxyFactory factory = new ProxyFactory(new BeanA());
factory.setProxyTargetClass(true);
BeanA proxy = (BeanA) factory.getProxy();
assertThat(ajexp.matches(BeanA.class.getMethod("getAge"), proxy.getClass())).isTrue();
}
@Test
public void testAnnotationOnDynamicProxyMethod() throws Exception {
String expression = "@annotation(test.annotation.transaction.Tx)";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
ProxyFactory factory = new ProxyFactory(new BeanA());
factory.setProxyTargetClass(false);
IBeanA proxy = (IBeanA) factory.getProxy();
assertThat(ajexp.matches(IBeanA.class.getMethod("getAge"), proxy.getClass())).isTrue();
}
@Test
public void testAnnotationOnMethodWithWildcard() throws Exception {
String expression = "execution(@(test.annotation..*) * *(..))";
AspectJExpressionPointcut anySpringMethodAnnotation = new AspectJExpressionPointcut();
anySpringMethodAnnotation.setExpression(expression);
assertThat(anySpringMethodAnnotation.matches(getAge, TestBean.class)).isFalse();
assertThat(anySpringMethodAnnotation.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertThat(anySpringMethodAnnotation.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isTrue();
assertThat(anySpringMethodAnnotation.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
}
@Test
public void testAnnotationOnMethodArgumentsWithFQN() throws Exception {
String expression = "@args(*, test.annotation.EmptySpringAnnotation))";
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression);
assertThat(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class),
ProcessesSpringAnnotatedParameters.class)).isTrue();
// True because it maybeMatches with potential argument subtypes
assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class),
ProcessesSpringAnnotatedParameters.class)).isTrue();
assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class),
ProcessesSpringAnnotatedParameters.class, new TestBean(), new BeanA())).isFalse();
}
@Test
public void testAnnotationOnMethodArgumentsWithWildcards() throws Exception {
String expression = "execution(* *(*, @(test..*) *))";
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression);
assertThat(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("foo"), HasTransactionalAnnotation.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(
HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("getAge"), BeanA.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(BeanA.class.getMethod("setName", String.class), BeanA.class)).isFalse();
assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class),
ProcessesSpringAnnotatedParameters.class)).isTrue();
assertThat(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, BeanA.class),
ProcessesSpringAnnotatedParameters.class)).isFalse();
}
public static class HasGeneric {
public void setFriends(List<TestBean> friends) {
}
public void setEnemies(List<TestBean> enemies) {
}
public void setPartners(List<?> partners) {
}
public void setPhoneNumbers(List<String> numbers) {
}
}
public static class ProcessesSpringAnnotatedParameters {
public void takesAnnotatedParameters(TestBean tb, SpringAnnotated sa) {
}
public void takesNoAnnotatedParameters(TestBean tb, BeanA tb3) {
}
}
@Tx
public static class HasTransactionalAnnotation {
public void foo() {
}
public Object bar(String foo) {
throw new UnsupportedOperationException();
}
}
@EmptySpringAnnotation
public static class SpringAnnotated {
public void foo() {
}
}
interface IBeanA {
@Tx
int getAge();
}
static class BeanA implements IBeanA {
@SuppressWarnings("unused")
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
@Tx
@Override
public int getAge() {
return age;
}
}
@Tx
static class BeanB {
@SuppressWarnings("unused")
private String name;
public void setName(String name) {
this.name = name;
}
}
}
class CallCountingInterceptor implements MethodInterceptor {
private int count;
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
count++;
return methodInvocation.proceed();
}
public int getCount() {
return count;
}
public void reset() {
this.count = 0;
}
}
|
package cn.edu.cqu.jwc.mis.ta.model;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name = "attachment2")
public class Attachment2 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "course_id")
@NotEmpty
private String courseId;
@Column(name = "course_name")
@NotEmpty
private String courseName;
@Column(name = "course_college")
@NotEmpty
private String courseCollege;
@Column(name = "course_type1")
@NotEmpty
private String courseType1;
@Column(name = "course_type2")
@NotEmpty
private String courseType2;
@Column(name = "course_credit")
@NotEmpty
private Float courseCredit;
@Column(name = "theory_period")
@NotEmpty
private Integer theoryPeriod;
@Column(name = "experiment_period")
@NotEmpty
private Integer experimentPeriod;
@Column(name = "machine_period")
@NotEmpty
private Integer machinePeriod;
@Column(name = "total_number_classes")
@NotEmpty
private Integer totalNumberClasses;
@Column(name = "total_number_students")
@NotEmpty
private Integer totalNumberStudents;
@Column(name = "student_info")
@NotEmpty
private String studentInfo;
@Column(name = "academic_year")
@NotEmpty
private String academicYear;
@Column(name = "term")
@NotEmpty
private String term;
@Column(name = "submit_date")
@NotEmpty
private Date submitDate;
@Column(name = "nbr_of_attend_lecture")
@NotEmpty
private Integer nbrOfAttendLecture;
@Column(name = "nbr_of_chk_homework")
@NotEmpty
private Integer nbrOfChkHomework;
@Column(name = "nbr_of_coach")
@NotEmpty
private Integer nbrOfCoach;
@Column(name = "nbr_of_exercise")
@NotEmpty
private Integer nbrOfExercise;
@Column(name = "nbr_of_exam")
@NotEmpty
private Integer nbrOfExam;
@Column(name = "nbr_of_report")
@NotEmpty
private Integer nbrOfReport;
@Column(name = "nbr_of_discuss")
@NotEmpty
private Integer nbrOfDiscuss;
@Column(name = "nbr_of_thesis")
@NotEmpty
private Integer nbrOfThesis;
@Column(name = "nbr_of_reading")
@NotEmpty
private Integer nbrOfReading;
@Column(name = "other_stuff")
@NotEmpty
private String otherStuff;
@Column(name = "assessment_method")
@NotEmpty
private String assessmentMethod;
@Column(name = "usual_percent")
@NotEmpty
private String usualPercent;
@Column(name = "nbr_of_ta")
@NotEmpty
private Integer nbrOfTa;
@Column(name = "application_reason")
@NotEmpty
private String applicationReason;
@Column(name = "implementation_measure")
@NotEmpty
private String implementationMeasure;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCourseId() {
return courseId;
}
public void setCourseId(String courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseCollege() {
return courseCollege;
}
public void setCourseCollege(String courseCollege) {
this.courseCollege = courseCollege;
}
public String getCourseType1() {
return courseType1;
}
public void setCourseType1(String courseType1) {
this.courseType1 = courseType1;
}
public String getCourseType2() {
return courseType2;
}
public void setCourseType2(String courseType2) {
this.courseType2 = courseType2;
}
public Float getCourseCredit() {
return courseCredit;
}
public void setCourseCredit(Float courseCredit) {
this.courseCredit = courseCredit;
}
public Integer getTheoryPeriod() {
return theoryPeriod;
}
public void setTheoryPeriod(Integer theoryPeriod) {
this.theoryPeriod = theoryPeriod;
}
public Integer getExperimentPeriod() {
return experimentPeriod;
}
public void setExperimentPeriod(Integer experimentPeriod) {
this.experimentPeriod = experimentPeriod;
}
public Integer getMachinePeriod() {
return machinePeriod;
}
public void setMachinePeriod(Integer machinePeriod) {
this.machinePeriod = machinePeriod;
}
public Integer getTotalNumberClasses() {
return totalNumberClasses;
}
public void setTotalNumberClasses(Integer totalNumberClasses) {
this.totalNumberClasses = totalNumberClasses;
}
public Integer getTotalNumberStudents() {
return totalNumberStudents;
}
public void setTotalNumberStudents(Integer totalNumberStudents) {
this.totalNumberStudents = totalNumberStudents;
}
public String getStudentInfo() {
return studentInfo;
}
public void setStudentInfo(String studentInfo) {
this.studentInfo = studentInfo;
}
public String getAcademicYear() {
return academicYear;
}
public void setAcademicYear(String academicYear) {
this.academicYear = academicYear;
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
public Date getSubmitDate() {
return submitDate;
}
public void setSubmitDate(Date submitDate) {
this.submitDate = submitDate;
}
public Integer getNbrOfAttendLecture() {
return nbrOfAttendLecture;
}
public void setNbrOfAttendLecture(Integer nbrOfAttendLecture) {
this.nbrOfAttendLecture = nbrOfAttendLecture;
}
public Integer getNbrOfChkHomework() {
return nbrOfChkHomework;
}
public void setNbrOfChkHomework(Integer nbrOfChkHomework) {
this.nbrOfChkHomework = nbrOfChkHomework;
}
public Integer getNbrOfCoach() {
return nbrOfCoach;
}
public void setNbrOfCoach(Integer nbrOfCoach) {
this.nbrOfCoach = nbrOfCoach;
}
public Integer getNbrOfExercise() {
return nbrOfExercise;
}
public void setNbrOfExercise(Integer nbrOfExercise) {
this.nbrOfExercise = nbrOfExercise;
}
public Integer getNbrOfExam() {
return nbrOfExam;
}
public void setNbrOfExam(Integer nbrOfExam) {
this.nbrOfExam = nbrOfExam;
}
public Integer getNbrOfReport() {
return nbrOfReport;
}
public void setNbrOfReport(Integer nbrOfReport) {
this.nbrOfReport = nbrOfReport;
}
public Integer getNbrOfDiscuss() {
return nbrOfDiscuss;
}
public void setNbrOfDiscuss(Integer nbrOfDiscuss) {
this.nbrOfDiscuss = nbrOfDiscuss;
}
public Integer getNbrOfThesis() {
return nbrOfThesis;
}
public void setNbrOfThesis(Integer nbrOfThesis) {
this.nbrOfThesis = nbrOfThesis;
}
public Integer getNbrOfReading() {
return nbrOfReading;
}
public void setNbrOfReading(Integer nbrOfReading) {
this.nbrOfReading = nbrOfReading;
}
public String getOtherStuff() {
return otherStuff;
}
public void setOtherStuff(String otherStuff) {
this.otherStuff = otherStuff;
}
public String getAssessmentMethod() {
return assessmentMethod;
}
public void setAssessmentMethod(String assessmentMethod) {
this.assessmentMethod = assessmentMethod;
}
public String getUsualPercent() {
return usualPercent;
}
public void setUsualPercent(String usualPercent) {
this.usualPercent = usualPercent;
}
public Integer getNbrOfTa() {
return nbrOfTa;
}
public void setNbrOfTa(Integer nbrOfTa) {
this.nbrOfTa = nbrOfTa;
}
public String getApplicationReason() {
return applicationReason;
}
public void setApplicationReason(String applicationReason) {
this.applicationReason = applicationReason;
}
public String getImplementationMeasure() {
return implementationMeasure;
}
public void setImplementationMeasure(String implementationMeasure) {
this.implementationMeasure = implementationMeasure;
}
}
|
/*
* 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 server.data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import server.domain.Seat;
import java.util.List;
/**
*
* @author luisburgos
*/
public class SeatsRepository extends Repository<Seat> {
@Override
public int save(Seat entity) {
int iRet = -1;
try {
Connection con = DBManager.getInstance().getConnection();
String SQL = "INSERT INTO asiento (estado, event_id, number) values(?,?,?)";
PreparedStatement pstmt = con.prepareStatement(SQL);
pstmt.setString(1, entity.getState());
pstmt.setInt(2, entity.getEventId());
pstmt.setInt(3, entity.getSeatNumber());
iRet = pstmt.executeUpdate();
pstmt.close();
} catch (SQLException se) {
System.out.println(se);
}
return iRet;
}
/**
* Actualiza en la base de datos el estado de un asiento.
* @param seat Objeto tipo asiento
* @return Entero indicando el resultado de la ejecución de la sentencia SQL.
*/
@Override
public int update(Seat seat) {
int iRet = -1;
try {
Connection con = DBManager.getInstance().getConnection();
String SQL = "UPDATE asiento SET estado=? WHERE event_id=? AND number=?";
PreparedStatement pstmt = con.prepareStatement(SQL);
pstmt.setString(1, seat.getState());
pstmt.setInt(2, seat.getEventId());
pstmt.setInt(3, seat.getSeatNumber());
iRet = pstmt.executeUpdate();
pstmt.close();
} catch (SQLException se) {
System.out.println(se);
}
return iRet;
}
@Override
public int delete(Seat entity) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void deleteAll() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List findAll() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
*
* @param event_id Identificador del evento que se quiere obtener la lista de asientos
* @return Lista de asiento correspondientes a un evento.
*/
@Override
public List findByName(int event_id) {
ArrayList seatList = new ArrayList();
try {
String query = "SELECT * FROM asiento WHERE event_id=? ORDER BY number";
Connection con = DBManager.getInstance().getConnection();
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setInt(1, event_id);
ResultSet rs = pstmt.executeQuery();
while (rs.next()){
Seat seat = new Seat();
seat.setSeatNumber(rs.getInt("number"));
seat.setState(rs.getString("estado"));
seatList.add(seat);
}
pstmt.close();
} catch (SQLException se) {
System.out.println(se);
}
return seatList;
}
@Override
public Seat findByID(int event_id) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
// Name: Nanako Chung
// Date: March 21st, 2017
// Description: this program creates a 5x5 dimension with either a circle or a square (chosen at random). If mouse is clicked, the shapes will shuffle
// sets up processing within eclipse
import processing.core.PApplet;
public class ArrayVisualization extends PApplet{
public static void main(String[] args) {
PApplet.main("ArrayVisualization");
}
//method that sets up size of sketch in pixels
public void settings(){
size(500,500);
}
//method that runs once at the beginning
public void setup(){
//color of the shape is white
fill(225,225,225);
//color of the background is black
background(0,0,0);
//creates an empty 5x5 array
int[][] array=new int[5][5];
// iterates over each column
for (int col=0; col<array.length; col++) {
// iterates over each row in the column
for (int row=0; row<array.length; row++) {
// assigns either a 0 or 1 (at random) to each position in the array
array[col][row]=(int)(Math.random()*2);
// if the position contains a 0, call the ellipse function and position it accordingly
if (array[col][row]==0) {
ellipse((50+100*row), (50+100*col), 50,50);
// otherwise, call the rectangle function to create a square
} else {
rect((25+100*row), (25+100*col), 50,50);
}
}
}
}
//runs over & over again as long as program is still running
public void draw() {
background(0);
// if the mouse is pressed, then call the setup() function to run it one time and capture that frame
if (mousePressed) {
setup();
}
}
}
|
public class Q997_FindTheTownJudge {
// // Method 1 5ms 99.24%
// public int findJudge(int N, int[][] trust) {
// int[][] people = new int[N][2];
// for(int[] person : trust) {
// people[person[0]-1][0]++;
// people[person[1]-1][1]++;
// }
// for(int i = 0; i < N; i++) {
// if(people[i][0] == 0 && people[i][1] == N - 1) {
// return i + 1;
// }
// }
// return -1;
// }
public int findJudge(int N, int[][] trust) {
int[] people = new int[N];
for(int[] person : trust) {
// judge doesn't trust anyone
people[person[0]-1]--;
// people all except judge trust judge
people[person[1]-1]++;
}
for(int i = 0; i < N; i++) {
if(people[i] == N - 1) {
return i + 1;
}
}
return -1;
}
}
|
package com.reptile.util.constants;
/**
* @author LiuEnYuan
* @version 1.1 reptile constants contains this project all constants
**/
public final class ReptileConstants {
/** define jdbc properties position **/
public static final String JDBC_PROPERTIES_POSITION = "src/main/resources/jdbc.properties";
/** search http url first **/
public static final String HTTP_URL_FIRST = "https://search.jd.com/Search?keyword=Python&enc=utf-8&wq=Python&pvid=d0216c44f0df45eab90fab25455ac9f7";
/** search http url second **/
public static final String HTTP_URL_SECOND = "https://search.jd.com/Search?keyword=Python&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=Python&page=5&s=109&click=0";
/** character encoding **/
public static final String CHARACTER_ENCODING = "UTF-8";
/** http response status **/
public static final String OK = "OK";
/**
* document elements ul
**/
public static final String ELEMENTS_SELECT_CSS_UL = "ul[class=gl-warp clearfix]";
/**
* document elements li
**/
public static final String ELEMENTS_SELECT_CSS_LI = "li[class=gl-item]";
/** get book id html data **/
public static final String ELEMENTS_BOOK_ID = "data-sku";
/** get book name html data **/
public static final String ELEMENTS_BOOK_CSS_NAME = "div[class=p-name]";
/** get book name html data style **/
public static final String ELEMENTS_BOOK_CSS_NAME_EM = "em";
/** get book price html data **/
public static final String ELEMENTS_BOOK_CSS_PRICE = "div[class=p-price]";
/** get book price html data style strong **/
public static final String ELEMENTS_BOOK_PRICE_CSS_STRONG = "strong";
/** get book price html data style i **/
public static final String ELEMENTS_BOOK_PRICE_CSS_I = "i";
public static final String SQL_INSERT = "insert into tb_book(BookId,BookName,BookPrice)" + "values(?,?,?)";
}
|
package br.com.mixfiscal.prodspedxnfe.services.ex;
public class DadosSpedNaoCarregadosException extends Exception {
public DadosSpedNaoCarregadosException() {
super();
}
public DadosSpedNaoCarregadosException(String message) {
super(message);
}
public DadosSpedNaoCarregadosException(Throwable cause) {
super(cause);
}
public DadosSpedNaoCarregadosException(String message, Throwable cause) {
super(message, cause);
}
}
|
package question4;
import java.io.*;
import java.net.*;
public class UpperCaseInputStreamTest extends junit.framework.TestCase{
public void testAccès_README_TXT(){
try{
InputStream is = new BufferedInputStream( new FileInputStream(new File("question4/README.TXT")));
int c = is.read();
assertTrue(" erreur de lecture ???", c!= -1);
is.close();
}catch(Exception e){
fail(" Erreur sur ce fichier : README.TXT ??? " + e.getMessage());
}
}
public void testUpperCase_README_TXT() throws Exception{
InputStream is = new UpperCaseInputStream(new FileInputStream(new File("question4/README.TXT"))); // déclaration à décorer ....
int c = is.read();
while( c != -1){
assertTrue("erreur !, '" + Character.valueOf((char)c) + "' ne semble pas être une majuscule ...", Character.isUpperCase((char)c) || (char)c==' ');
c = is.read();
}
is.close();
}
public void testPushPackUpperCase_README_TXT() throws Exception{
// à terminer
fail(" à terminer !!!");
}
}
|
/**
*/
package Metamodell.model.metamodell.tests;
import Metamodell.model.metamodell.MetamodellFactory;
import Metamodell.model.metamodell.SenderReceiverport;
import junit.textui.TestRunner;
/**
* <!-- begin-user-doc -->
* A test case for the model object '<em><b>Sender Receiverport</b></em>'.
* <!-- end-user-doc -->
* @generated
*/
public class SenderReceiverportTest extends PortTest {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static void main(String[] args) {
TestRunner.run(SenderReceiverportTest.class);
}
/**
* Constructs a new Sender Receiverport test case with the given name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SenderReceiverportTest(String name) {
super(name);
}
/**
* Returns the fixture for this Sender Receiverport test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private SenderReceiverport getFixture() {
return (SenderReceiverport)fixture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#setUp()
* @generated
*/
protected void setUp() throws Exception {
setFixture(MetamodellFactory.eINSTANCE.createSenderReceiverport());
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see junit.framework.TestCase#tearDown()
* @generated
*/
protected void tearDown() throws Exception {
setFixture(null);
}
} //SenderReceiverportTest
|
package com.pwq.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.regex.Pattern;
/**
* @Description:格式化数据
* @author: york
* @date: 2016-07-30 16:07
* @version: v1.0
*/
public class FormatMUtils {
protected static Logger logger= LoggerFactory.getLogger(FormatUtils.class);
/**
* @Description:格式化钱相关数据、
* @param @param money
* @return 格式:【100/100.00】
* */
public static String FormatMoney(String money){
try{
if(StringUtils.isBlank(money)){
return "";
}
String retMoney = money;
retMoney = retMoney.replaceAll(" ", "");
retMoney = retMoney.replaceAll(",", "");
//去掉【元】
if(retMoney.contains("元")){
retMoney = retMoney.replaceAll("元", "");
}
//去掉【万】
if(retMoney.contains("万")){
retMoney = retMoney.replaceAll("万", "");
//去掉【万】以后判断是否是浮点类型、
if(StringUtils.isFloat(retMoney)){
BigDecimal bigDecimalA =new BigDecimal(retMoney);
BigDecimal bigDecimalB = new BigDecimal("10000");
bigDecimalA = bigDecimalA.multiply(bigDecimalB);
retMoney = bigDecimalA.toString();
}
//记录错误转化日志
else{
return money;
}
}
retMoney = moneyZerofill(retMoney);
return retMoney;
}catch (Exception ex){
logger.info("格式化转换异常:" + money);
return money;
}
}
/**
* @Description:格式化日期、只保留月份
* @param @param retDate
* @param @param bDay
*
* @return
* bDay:false ==》格式:【yyyy-mm】
* bDay:true ==》格式:【yyyy-mm-dd】
* */
public static String FormatDate(String date, boolean bDay){
try{
if(StringUtils.isBlank(date)){
return "";
}
String retDate = date.trim();
//mm[-/]dd[ HH:mm:ss]
if(Pattern.compile("^\\d{2}[-/]\\d{2}[ \\d{2}:\\d{2}:\\d{2}]").matcher(retDate).find()){
retDate = retDate.replaceAll("/", "-");
String year = DateUtils.getCurrentYear();
if(bDay) retDate = year + "-" + retDate.substring(0,5);
else retDate = year + "-" + retDate.substring(0,2);
}
//yyyy[-/年]m[-/月][dd[日][ HH:mm:ss]]
else if(Pattern.compile("^\\d{4}[-/年]\\d{1,2}[[-/月]\\d{1,2}[日]?[ \\d{2}:\\d{2}:\\d{2}]?]?").matcher(retDate).find()){
if(retDate.contains("年") && retDate.contains("月")){
retDate = retDate.replace("年", "-").replace("日", "");
//判断月是否是最后一个字符
boolean bLastMonth = retDate.indexOf("月") == retDate.length()-1 ? true :false;
if(bLastMonth){
retDate = retDate.replace("月", "");
}
else{
retDate = retDate.replace("月", "-");
}
//2011-01|2011-1
if(retDate.length() < 8){
retDate = retDate + "-01";
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
retDate = format.format(format.parse(retDate));
}
if(bDay) retDate =retDate.length() >= 10 ? retDate.substring(0,4) + "-"+ retDate.substring(5,7) + "-" + retDate.substring(8,10):retDate.substring(0,4) + "-"+ retDate.substring(5,7) + "-01";
else retDate = retDate.substring(0,4) + "-"+ retDate.substring(5,7) ;
}
//yyyymm[dd]
else if(Pattern.compile("^\\d{6}[\\d{2}]*$").matcher(retDate).find()){
if(bDay) retDate = retDate.length() >= 8 ? retDate.substring(0,4) + "-"+ retDate.substring(4,6)+ "-"+ retDate.substring(6,8): retDate.substring(0,4) + "-"+ retDate.substring(4,6)+ "-01";
else retDate = retDate.substring(0,4) + "-"+ retDate.substring(4,6);
}
//判断格式是否匹配、不匹配则记录日志文件
if(!Pattern.compile("^\\d{4}-\\d{2}-\\d{2}").matcher(retDate).find() && !Pattern.compile("^\\d{4}-\\d{2}").matcher(retDate).find()){
//记录日志
return date;
}
return retDate;
}catch (Exception ex){
logger.info("格式化转换异常:" + date);
return date;
}
}
public static String moneyZerofill(String money){
if(StringUtils.isBlank(money)){
return "";
}
try {
money = money.replace(",", "");
DecimalFormat df=new DecimalFormat("######################.00");
BigDecimal bd=new BigDecimal(money);
String val=df.format(bd);
return val.startsWith(".")?"0"+val:val;
} catch (Exception e) {
logger.info("格式化转换异常:" + money);
return money;
}
}
public static String FormatAccStatus(String status) {
if(StringUtils.isBlank(status)) {
return "";
}
if(StringUtils.contains(status, "正常")) {
return "正常";
} else if(StringUtils.contains(status, "封存")) {
return "封存";
} else if(StringUtils.contains(status, "销户")) {
return "销户";
} else {
return status;
}
}
/**
* unicode 转字符串
*/
public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
// 转换出每一个代码点
int data = Integer.parseInt(hex[i], 16);
// 追加成string
string.append((char) data);
}
return string.toString();
}
}
|
package uquest.com.bo.models.services.encuesta;
import uquest.com.bo.models.entity.Encuesta;
import java.util.Date;
import java.util.List;
public interface IEncuestaService {
public List<Encuesta> findAll();
public Encuesta save(Encuesta encuesta);
public Encuesta findOne(Long id);
public void delete(Long id);
public List<Encuesta> findAllEncuestas();
public List<Encuesta> findAllEncuestasByUsuarioId(Long id);
public List<Encuesta> findAllEncuestasByUsername(String user);
public List<Encuesta> findAllPublic();
public List<Long> available();
public void finalizar(Long id);
public List<Encuesta> getEncuestasByCarrera(Long id);
public List<Encuesta> getEncuestasByCarreraList(Long id);
public Encuesta findByUID(String uid);
public void updateDate(Date fechaIni, Date fechaFin, Long encuestaId);
}
|
package br.com.douglastuiuiu.biometricengine.queue.config;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author douglas
* @since 21/03/2017
*/
@EnableRabbit
@Configuration
public class RabbitConfig {
@Value("${spring.rabbitmq.host}")
private String host;
@Value("${spring.rabbitmq.port}")
private Integer port;
@Value("${spring.rabbitmq.username}")
private String user;
@Value("${spring.rabbitmq.password}")
private String password;
@Value("${spring.rabbitmq.virtualHost}")
private String virtualHost;
@Bean
public ConnectionFactory rabbitConnectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
connectionFactory.setPort(port);
connectionFactory.setUsername(user);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(virtualHost);
connectionFactory.setPublisherConfirms(true);
return connectionFactory;
}
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(rabbitConnectionFactory());
factory.setMessageConverter(new Jackson2JsonMessageConverter());
return factory;
}
@Bean
public AmqpTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(rabbitConnectionFactory());
template.setMessageConverter(new Jackson2JsonMessageConverter());
return template;
}
}
|
import java.math.*;
import java.io.*;
import java.util.*;
class diffeven
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
int a=kb.nextInt();
int b=kb.nextInt();
if(Math.abs(a-b)%2==0)
{
System.out.println("even");
}
else
{
System.out.println("odd");
}
}
}
|
/**
* Enumeration клас, що містить перелік організацій,
* створені спільнотою могилянців.
*/
public enum Organizations {
TA_MOHYLYANKA_1,
MASTANDUP_2,
SPUDEIISKI_VISNYK_3,
SPUDEIISKE_BRATSTVO_NAUKMA_4,
BUDDY_NAUKMA_5,
POLITOLOGY_STUDENTS_ASSOCIATION_6,
DEBATE_CLUB_7,
ECOCLUB_GREENWAVE_8,
ANCIENT_DANCE_CLUB_9,
FIDO_10,
SQUAD21_11,
THEATRICAL_STUDIO_4THSTUDIO_12,
KMA_LEGAL_HACKERS_13,
none_14;
}
|
package yola.form.tests;
public class Given {
public final static String TEST_FORM_URL = "https://goo.gl/forms/t16Uov7ZHXCrB2ZE2";
public final static String VALID_EMAIL = "test@test.com";
public final static String VALID_MM = "01";
public final static String VALID_SS = "01";
public final static String VALID_YYYY = "2001";
public final static String VALID_NAME = "Test-Test";
public final static String MIN_MONTH_VALUE = "01";
public final static String MAX_MONTH_VALUE = "12";
public final static String MIN_DAY_VALUE = "01";
public final static String MAX_DAY_VALUE = "31";
public final static String MIN_YEAR_VALUE = "0001";
public final static String MAX_YEAR_VALUE = "9999";
public final static String FEBRUARY_MONTH_VALUE = "02";
public final static String LAST_FEBRUARY_DAY_VALUE_OF_LEAP_YEAR = "29";
public final static String LEAP_YEAR_VALUE = "2016";
public final static String SINGLE_NUMBER_VALUE = "5";
public final static String NAME_WITH_INVALID_LENGTH = "Test-With 21--symbols";
public final static String TEXT_WITH_200_SYMBOLS = "Test Test 123 ~!@#$%^&*()_-+<.>,\"\"'':; Test" +
" Test 123 Test Test 123 Test Test 123 Test Test 123 Test Test 123 Test Test 123 Test Test " +
"123 Test Test 123 Test Test 123 Test Test 123 Test Test 123 Test12";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.