text
stringlengths 10
2.72M
|
|---|
package presentation.customer.view;
import javafx.beans.property.*;
/**
* Created by 啊 on 2016/12/7.
*/
public class ViewOrder {
private StringProperty orderID;
private StringProperty hotelName;
private StringProperty roomType;
private StringProperty roomNum;
private StringProperty peopleNum;
private StringProperty hasChild;
private StringProperty originPrice;
private StringProperty actualPrice;
private StringProperty unique;
public ViewOrder(int orderID,String hotelName,String roomType,int roomNum,int peopleNum,String hasChild,double originPrice,double actualPrice,String time){
this.orderID=new SimpleStringProperty(String.valueOf(orderID));
this.hotelName=new SimpleStringProperty(hotelName);
this.roomType=new SimpleStringProperty(roomType);
this.roomNum=new SimpleStringProperty(String.valueOf(roomNum));
this.peopleNum=new SimpleStringProperty(String.valueOf(peopleNum));
this.hasChild=new SimpleStringProperty(hasChild);
this.originPrice=new SimpleStringProperty(String.valueOf(originPrice));
this.actualPrice=new SimpleStringProperty(String.valueOf(actualPrice));
this.unique=new SimpleStringProperty(String.valueOf(time));
}
public StringProperty orderIDProperty() {
return orderID;
}
public StringProperty hotelNameProperty() {
return hotelName;
}
public StringProperty roomTypeProperty() {
return roomType;
}
public StringProperty roomNumProperty() {
return roomNum;
}
public StringProperty peopleNumProperty() {
return peopleNum;
}
public StringProperty hasChildProperty() {
return hasChild;
}
public StringProperty originPriceProperty() {
return originPrice;
}
public StringProperty actualPriceProperty() {
return actualPrice;
}
public StringProperty uniqueProperty() {
return unique;
}
public String getRoomType() {
return roomType.get();
}
public String getOriginPrice() {
return originPrice.get();
}
public String getActualPrice() {
return actualPrice.get();
}
public String getHasChild() {
return hasChild.get();
}
public String getHotelName() {
return hotelName.get();
}
public String getOrderID() {
return orderID.get();
}
public String getPeopleNum() {
return peopleNum.get();
}
public String getRoomNum() {
return roomNum.get();
}
public String getUnique() {
return unique.get();
}
}
|
package ua.training.model.dao.service.implementation;
import ua.training.model.dao.DayRationDao;
import ua.training.model.dao.service.DayRationService;
import ua.training.model.entity.DayRation;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
public class DayRationServiceImp implements DayRationService {
private DayRationDao dayRationDao = DAO_FACTORY.createDayRationDao();
@Override
public void insertNewDayRation(DayRation entity) {
dayRationDao.create(entity);
}
@Override
public Optional<DayRation> checkDayRationByDateAndUserId(LocalDate localDate,
Integer idUser) {
return dayRationDao.checkDayRationByDateAndUserId(localDate, idUser);
}
@Override
public List<DayRation> getMonthlyDayRationByUser(Integer monthVal,
Integer year,
Integer userId) {
return dayRationDao.getMonthlyDayRationByUser(monthVal, year, userId);
}
}
|
package courierserviceapp.domain;
import java.util.Objects;
public class DeliveryStaff {
private int id;
private String hpNo;
private boolean available;
public DeliveryStaff(int id, String hpNo, boolean available){
this.id = id;
this.hpNo = hpNo;
this.available = available;
}
public int getId(){
return id;
}
public String getHpNo(){
return hpNo;
}
public boolean getAvailable(){
return available;
}
public void setAvailability(boolean availability){
this.available = availability;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof DeliveryStaff)) {
return false;
}
DeliveryStaff dStaff = (DeliveryStaff) o;
return dStaff.id == id &&
dStaff.hpNo.equals(hpNo) &&
dStaff.available == available;
}
@Override
public int hashCode() {
return Objects.hash(id, hpNo, available);
}
}
|
package utilities;
import drivetrain.DriveIO;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class RobotDashboard { //class to put connect to smart dashboard
private static RobotDashboard dashboard;
public static void init() {
}
public static void update() {
//update gyro values
SmartDashboard.putNumber("getYaw", DriveIO.getInstance().getYaw());
SmartDashboard.putNumber("getPitch", DriveIO.getInstance().getPitch());
SmartDashboard.putNumber("getRoll", DriveIO.getInstance().getRoll());
}
public static RobotDashboard getInstance() { //get singleton instance
if(dashboard == null) {
init();
}
return dashboard;
}
public static String getAutonPosition(){ //get which position auton will cross
return SmartDashboard.getString("Position", "");
}
public static String getAutonObstacle(){ //get which obstacle auton will cross
return SmartDashboard.getString("Obstacle", "");
}
public static String getAutonShooterSetting() { //get whether auton will shoot
return SmartDashboard.getString("Shooter Setting", "");
}
public static void putNumber(String key, int value) { //put number on dashboard
SmartDashboard.putNumber(key, value);
}
public static void putString(String key, String value) { //put string on dashboard
SmartDashboard.putString(key, value);
}
public static void putBoolean(String key, boolean value) { //put boolean on dashboard
SmartDashboard.putBoolean(key, value);
}
}
|
package rdfsynopsis.eval;
public abstract class AbstractCompositeEvaluator extends AbstractEvaluator {
public AbstractCompositeEvaluator(String title, boolean timeStamp) {
super(title, timeStamp);
}
}
|
package com.apress.spring;
import com.apress.spring.service.JournalService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleJpaAppApplicationTests {
@Autowired
JournalService service;
//
@Test
public void contextLoads() {
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.authn.remote;
/**
* Represents a remote group membership
* @author K. Benedyczak
*/
public class RemoteGroupMembership extends RemoteInformationBase
{
public RemoteGroupMembership(String name)
{
super(name);
}
@Override
public String toString()
{
return getName();
}
}
|
package swing;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Test_Swing_JMenu extends JFrame {
public Test_Swing_JMenu() {
super("Teste JMenu");
JMenuBar barraMenu = new JMenuBar();
JMenu menuConta = new JMenu("Conta");
JMenuItem item1menuConta = new JMenuItem("Abrir Conta");
JMenuItem item2menuConta = new JMenuItem("Editar Conta");
JMenuItem item3menuConta = new JMenuItem("Listar Contas");
menuConta.add(item1menuConta);
menuConta.add(item2menuConta);
menuConta.add(item3menuConta);
barraMenu.add(menuConta);
JMenu menuAgencia = new JMenu("Agencia");
JMenuItem item1menuAgencia = new JMenuItem("Abrir Agencia");
JMenuItem item2menuAgencia = new JMenuItem("Editar Agencia");
JMenuItem item3menuAgencia = new JMenuItem("Listar Agencias");
menuAgencia.add(item1menuAgencia);
menuAgencia.add(item2menuAgencia);
menuAgencia.add(item3menuAgencia);
barraMenu.add(menuAgencia);
this.setJMenuBar(barraMenu);
setSize(275, 100);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/**
* @param args
*/
public static void main(String[] args) {
new Test_Swing_JMenu();
}
}
|
package com.jrd.timedmailsender;
import org.junit.Before;
import org.junit.Test;
import javax.mail.MessagingException;
import java.io.IOException;
/**
* Created by jrd on 2016-04-28.
*/
public class MailSenderTest {
private Configuration configuration;
private MailSender mailSender;
private FileManager fileManager;
@Before
public void setup() throws IOException {
configuration = new Configuration("mailSender.properties");
mailSender = new MailSender(configuration);
}
@Test
public void testSendMail() throws MessagingException {
mailSender.sendMail("Test message", configuration.getProperty(Configuration.Keys.file_report_path) + "/report_test1.csv");
}
}
|
package nom.hhx.cache.factory;
import nom.hhx.cache.factory.CacheBuilder.Settings;
import org.junit.Before;
import org.junit.Test;
public class CacheBuilderTest
{
private CacheBuilder builder;
@Before
public void setUp()
{
builder = new CacheBuilder();
}
@Test
public void TestJvmPencentValueFormatCheck()
{
this.builder.setProperty( Settings.JVM_PERCENT_SETNAME, "100" );
this.builder.setProperty( Settings.JVM_PERCENT_SETNAME, "%20" );
}
}
|
public class BarException extends Exception
{
public BarException(String message)
{
super(message);
}
}
|
package swea_d4;
import java.util.Arrays;
import java.util.Scanner;
public class Solution_9282_초콜릿과건포도 {
static int result;
static int n, m;
static int[][] map;
static int[][][][] dp;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int TC = sc.nextInt();
for (int t = 1; t <= TC; t++) {
n = sc.nextInt();
m = sc.nextInt();
map = new int[n][m];
dp = new int[n + 1][m + 1][n + 1][m + 1];
for (int[][][] d1 : dp) {
for (int[][] d2 : d1) {
for (int[] d3 : d2) {
Arrays.fill(d3, Integer.MAX_VALUE);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
map[i][j] = sc.nextInt();
}
}
// 사이즈가 정해져 있을경
// 처리
result = dfs(0, 0, n, m);
// 출력
System.out.println("#" + t + " " + result);
}
}
private static int dfs(int y, int x, int h, int w) {
// 종료
if (w == 1 && h == 1) {
return 0;
}
if (dp[y][x][h][w] != Integer.MAX_VALUE) {
return dp[y][x][h][w];
}
// 실행
// 기존의 덩어리 건포도
int sum = 0;
for (int i = y; i < y + h; i++) {
for (int j = x; j < x + w; j++) {
sum += map[i][j];
}
}
// 가로로 나누어서 비용을 최소로 구함
for (int i = 1; i < h; i++) {
// 위쪽비용
if (dp[y][x][i][w] == Integer.MAX_VALUE) {
dp[y][x][i][w] = dfs(y, x, i, w);
}
// 아래쪽비용
if (dp[y + i][x][h - i][w] == Integer.MAX_VALUE) {
dp[y + i][x][h - i][w] = dfs(y + i, x, h - i, w);
}
dp[y][x][h][w] = Math.min(dp[y][x][h][w], sum + dp[y][x][i][w] + dp[y + i][x][h - i][w]);
}
// 세로로 나누어서 비용을 최소로 구함
for (int i = 1; i < w; i++) {
// 왼쪽비용
if (dp[y][x][h][i] == Integer.MAX_VALUE) {
dp[y][x][h][i] = dfs(y, x, h, i);
}
// 오른쪽비용
if (dp[y][x + i][h][w - i] == Integer.MAX_VALUE) {
dp[y][x + i][h][w - i] = dfs(y, x + i, h, w - i);
}
dp[y][x][h][w] = Math.min(dp[y][x][h][w], sum + dp[y][x][h][i] + dp[y][x + i][h][w - i]);
}
// 재귀호출
return dp[y][x][h][w];
}
}
|
package com.esum.ebms.v2.transaction.log;
import com.esum.framework.common.util.DateUtil;
import com.esum.framework.common.util.MessageIDGenerator;
public class ErrorLog {
private String mErrorLogId = null;
private String mTxId = null;
private String mErrorCodeId = null;
private String mLogTime = DateUtil.getCYMDHMSS();
private String mErrorLocation = null;
private String mErrorMessage = null;
public ErrorLog() {}
public ErrorLog(String txId, String errorCodeId, String errorLocation, String errorMessage) {
mErrorLogId = MessageIDGenerator.generateMessageID();
mTxId = txId;
mErrorCodeId = errorCodeId;
mErrorLocation = errorLocation;
mErrorMessage = errorMessage;
}
public String getErrorLogId() {
return mErrorLogId;
}
public String getTxId() {
return mTxId;
}
public void setTxId(String txId) {
mTxId = txId;
}
public String getErrorCodeId() {
return mErrorCodeId;
}
public void setErrorCodeId(String errorCodeId) {
mErrorCodeId = errorCodeId;
}
public String getLogTime() {
return mLogTime;
}
public void setLogTime(String logTime) {
mLogTime = logTime;
}
public String getErrorLocation() {
return mErrorLocation;
}
public void setErrorLocation(String errorLocation) {
mErrorLocation = errorLocation;
}
public String getErrorMessage() {
return mErrorMessage;
}
public void setErrorMessage(String errorMessage) {
mErrorMessage = errorMessage;
}
}
|
package domain;
import java.io.Serializable;
/**
* Created by rodrique on 4/19/2018.
*/
public abstract class Menu
{
String menuID;
public Menu() {
}
public String getMenuID() {
return menuID;
}
public void setMenuID(String menuID) {
this.menuID = menuID;
}
}
|
package com.xdc;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import com.UtilClass.myDataOutputStream;
import com.hbaseClients.HBaseClient;
public class SplitRasFile {
//private static final short START=60;//数据头偏移量
private static final float INVAILDDATA=1.70141E38f;//填充的无用数据,与地图中无用数据一致,为1.70141E38
private short tileSize;
private int COL;//grd数据的像素列
private int ROW;//grd数据的像素行
private int COL_NUM=0;//数据块的列数
private int ROW_NUM=0;//数据块的行数
private boolean stateX;//数据块是否需要填充X的标志
private boolean stateY;//数据头偏移量否需要填充Y的标志
private short COL_ADD;//数据需要填充的像素列
private short ROW_ADD;//数据需要填充的像素行
private double x1,x2,y1,y2,z1,z2;
private RandomAccessFile raf = null;
public ArrayList<Integer> doSplit(short START,short TILE_SIZE,String RAS_PATH,String DES_PATH) {
// TODO Auto-generated method stub
tileSize = TILE_SIZE;
String rowKey = this.getRowKey(DES_PATH);
ArrayList<Integer> invaildTileNoList = new ArrayList<Integer>();
try {
raf = new RandomAccessFile(RAS_PATH,"r");
this.init(TILE_SIZE,RAS_PATH,rowKey);//初始化
this.split(START,TILE_SIZE,DES_PATH,rowKey,invaildTileNoList);//分片
this.writeHeadFile(DES_PATH+"/headMsg");//写新的头文件信息
} catch (Exception e) {
System.out.println("分片异常!文件转换失败");
e.printStackTrace();
}finally{
try {
raf.close();
System.out.println("转换为tile文件完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
return invaildTileNoList;
}
/**
* 初始化,得到文件相validNo关信息
* @param raf
* @throws IOException
*/
private void init(short TILE_SIZE,String RAS_PATH,String rowKey) throws IOException{//读入数据初始化
RasHead rashead = new RasHead(RAS_PATH);
this.ROW = rashead.getNx();
this.COL = rashead.getNy();
//this.no_use = rashead.getNo_use();
this.x1 = rashead.getX1();
this.x2 = rashead.getX2();
this.y1 = rashead.getY1();
this.y2 = rashead.getY2();
this.z1 = rashead.getZ1();
this.z2 = rashead.getZ2();
System.out.println("ROW="+ROW);
System.out.println("COL="+COL);
if(COL%TILE_SIZE!=0){//数据块列尾需要填充
COL_NUM=(short) ((COL/TILE_SIZE)+1);
COL_ADD=(short) (COL_NUM*TILE_SIZE-COL);
System.out.println("COL_NUM="+COL_NUM);
System.out.println("COL_ADD="+COL_ADD);
stateY = true;
}else{//数据块列尾不需要填充
COL_NUM=(short) (COL/TILE_SIZE);
COL_ADD=0;
stateY = false;
}
if(ROW%TILE_SIZE!=0){//数据块行尾需要填充
ROW_NUM=(short) ((ROW/TILE_SIZE)+1);
ROW_ADD=(short) ((ROW_NUM*TILE_SIZE)-ROW);
System.out.println("ROW_NUM="+ROW_NUM);
System.out.println("ROW_ADD="+ROW_ADD);
stateX = true;
}else{
ROW_NUM=(short) (ROW/TILE_SIZE);
ROW_ADD=0;
stateX = false;
}
saveHeadMsgtoHBase(rowKey);
//元信息写入HBase数据
}
/**
* 处理分块
* @param raf
* @throws IOException
*/
@SuppressWarnings("resource")
private void split(short START,short TILE_SIZE,String DES_PATH,String rowKey,ArrayList<Integer> invaildTileNoList) throws IOException{//切分
long startPX = Long.MAX_VALUE;
int byteSize = TILE_SIZE*4;
byte[] bytes = new byte[byteSize];
//noUseTileNoList数组存储无效块编号,最后导入HBase
StringBuilder valueString = new StringBuilder();
myDataOutputStream mydos = null;
DataOutputStream dos =null;
BufferedOutputStream bos = null;
bos =new BufferedOutputStream(new FileOutputStream(DES_PATH +"/tile"));
dos = new DataOutputStream(bos);//输出流
mydos = new myDataOutputStream(dos);
//无效块标记,true代表是无效块,false代表有效块
boolean label;
for(int x=0;x<ROW_NUM;x++){//x,y代表逻辑上的第x行,第y列的数据块
for(int y=0;y<COL_NUM;y++){
label = true; //默认为无效块
bytes = null;//bytes数组清空
bytes = new byte[byteSize];//再new一个新的bytes数组
startPX = x*COL*4L*TILE_SIZE+y*TILE_SIZE*4L+START;//当前实际要读取的位置,加L是为了强制转换为long类型
int i = 0;
int check = 0;
if((y==COL_NUM-1&&stateY)||(x==ROW_NUM-1&&stateX)){//如果处于边界,且要填充数据
if(y==COL_NUM-1&&stateY){//列
raf.seek(startPX);
while((check=raf.read(bytes, 0, (TILE_SIZE-COL_ADD)*4))!=-1&&i<TILE_SIZE){
if(label == true){
label = isValid(bytes);
}
dos.write(bytes,0,(TILE_SIZE-COL_ADD)*4);//读入有数据信息内容
i++;
short temp = COL_ADD;
while(temp>0){//填充无用数据
mydos.writeFloat(INVAILDDATA);
temp--;
}
startPX+=4L*COL;
if(startPX>=4L*COL*ROW+START){//如果当前操作像素节点超过输入流总节点,退出循环
break;
}
raf.seek(startPX);
}
}
if(x==ROW_NUM-1&&stateX){//行填充
if(!(y==COL_NUM-1&&stateY)){//如果当前不处于所有数据块的最后一块,防止最后一块被写入2次
raf.seek(startPX);
for(int row=0;row<TILE_SIZE-ROW_ADD;row++){
raf.read(bytes,0,byteSize);
if(label == true){
label = isValid(bytes);
}
dos.write(bytes,0,byteSize);
startPX+=4L*COL;
raf.seek(startPX);
}
}
short temp = ROW_ADD;
while(temp>0){//填充无用数据
for(int t=0;t<TILE_SIZE;t++){
mydos.writeFloat(INVAILDDATA);
}
temp--;
}
}
}else{//正常情况读取一块数据块内容
i=0;
raf.seek(startPX);
while(raf.read(bytes, 0, byteSize)!=-1&&i<TILE_SIZE){
if(label == true){
label = isValid(bytes);
}
dos.write(bytes,0,byteSize);//读入有数据信息内容
i++;
startPX+=4L*COL;
raf.seek(startPX);
}
}
if(label == true){
//写出无效值的块号
int TileNo = x*COL_NUM+(y+1);
invaildTileNoList.add(TileNo);
valueString.append(TileNo+" ");
}
}
}
dos.close();
fos.close();
//nonoUseTileNoList中数据导入HBase
StringBuilder family = new StringBuilder("RAS_BLK");
StringBuilder qualifier = new StringBuilder("InvaildTileNo");
StringBuilder[] sbs = {family,qualifier,valueString};
ArrayList<StringBuilder[]> al= new ArrayList<StringBuilder[]>();
al.add(sbs);
HBaseClient.addRecord("RAS_INFO",rowKey,al);
}
/**
* 写新的头文件
* @param headPath
* @throws IOException
*/
private void writeHeadFile(String headPath) throws IOException{
TileHeadFile sp = new TileHeadFile(ROW, COL, x1,x2,y1,y2,z1,z2,ROW_NUM, COL_NUM, ROW_ADD, COL_ADD);
sp.writeHeadFile(headPath);
}
/**
* 判断字节数组中是否全为无效值,是则返回true,否则返回false
* @param bytes
* @return
*/
private boolean isValid(byte[] bytes){
float tmp;
for(int i=0;i<bytes.length;i+=4){
tmp = fromBytestoFloat(bytes, i);
if(tmp != INVAILDDATA) {
return false;
}
}
return true;
}
/**
* 辅助类,bytes转int
* @param b
* @param start
* @return
*/
public int fromBytestoInt(byte[] b,int start){
int temp;
if(b.length >= start+4)
temp=(0xff & b[start]) | (0xff00 & (b[start+1] << 8)) | (0xff0000 & (b[start+2] << 16)) | (0xff000000 & (b[start+3] << 24));
else
temp = Integer.MAX_VALUE;
return temp;
}
/**
* 辅助类,bytes转Float
* @param b
* @param start
* @return
*/
public Float fromBytestoFloat(byte[] b,int start){
Float temp;
int tempi = fromBytestoInt(b,start);
if(tempi ==Integer.MAX_VALUE)
temp = Float.MAX_VALUE;
else
temp = Float.intBitsToFloat(tempi);
return temp;
}
/** 辅助类,获取rowkey,以便后面数据写入HBase、
* @param RAS_PATH
* @return
*/
private String getRowKey(String DES_PATH){
String[] tmpStringList = DES_PATH.split("/");
return tmpStringList[tmpStringList.length-1];
}
/**
* 保存元信息到HBase
* @throws IOException
*/
private void saveHeadMsgtoHBase(String rowKey) throws IOException{
String [] qualifiers = {"TileSize","Row", "Col","XMin","XMax","YMin","YMax","ZMin","ZMax","TileRowNum","TileColNum","TileRowPixelAdd","TileColPixelAdd"};
String [] values = {tileSize+"",ROW+"",COL+"",x1+"",x2+"",y1+"",y2+"",z1+"",z2+"",ROW_NUM+"",COL_NUM+"",ROW_ADD+"",COL_ADD+""};
ArrayList<StringBuilder[]> ls = new ArrayList<StringBuilder[]>();
StringBuilder family = new StringBuilder("RAS_BASE");
for (int i=0; i<qualifiers.length; i++){
StringBuilder Qualifier = new StringBuilder(qualifiers[i]);
StringBuilder value = new StringBuilder(values[i]);
StringBuilder [] sbs = {family,Qualifier,value};
ls.add(sbs);
}
HBaseClient.addRecord("RAS_INFO",rowKey , ls);
}
}
|
package mc.kurunegala.bop.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import mc.kurunegala.bop.dao.AssessmentMapper;
import mc.kurunegala.bop.model.Assessment;
import mc.kurunegala.bop.model.AssessmentSearcher;
@Service
public class AssessmentService {
@Autowired
AssessmentMapper mapper;
public List<Assessment> viewAllActive(int state){
return mapper.selectAllByState(state);
}
public List<Assessment> serachAssessment(AssessmentSearcher searcher) {
return mapper.selectbySeracher(searcher);
}
public Assessment get(int id) {
return mapper.selectByPrimaryKeyWithCustomer(id);
}
public void update(Assessment assessment) {
mapper.updateByPrimaryKeySelective(assessment);
}
/*public String getMaxAssessmentNumber() {
return mapper.viewMaxAssessmentNo();
}*/
}
|
package cn.shizihuihui.ssweddingserver.service;
import cn.shizihuihui.ssweddingserver.entity.Guest;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author song
* @since 2019-10-24
*/
public interface IGuestService extends IService<Guest> {
}
|
package com.blog.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import com.blog.Idao.IUserDao;
import com.blog.bean.PingLun;
import com.blog.bean.User;
import com.blog.util.DBUtil;
public class UserDao implements IUserDao {
ResultSet rs =null;
public boolean userByu_answer(User user){
String sql="update `weblog`.`user` set `u_problem` = ? , `u_answer` = ? where `u_id` = ?";
Object[] params={user.getU_problem(),user.getU_answer(),user.getU_id()};
return DBUtil.executeUpdate(sql, params);
}
public boolean useru_nickname(User user){
String sql="update `weblog`.`user` set `u_nickname` = ? where `u_id` = ?";
Object[] params={user.getU_nickname(),user.getU_id()};
return DBUtil.executeUpdate(sql, params);
}
public boolean userxinxi(User user){
String sql="update `weblog`.`user` set `u_nickname` = ? , `u_touxiang` = ? where `u_id` = ?";
Object[] params={user.getU_nickname(),user.getU_touxiang(),user.getU_id()};
return DBUtil.executeUpdate(sql, params);
}
public boolean Change_a_pass(User user,int u_id){
String sql="update `weblog`.`user` set `u_pass` = ? where `u_id` = ?";
Object[] params={user.getU_pass(),u_id};
return DBUtil.executeUpdate(sql, params);
}
public boolean RegUser(User user){
String sql="insert into `weblog`.`user` (`u_name`, `u_pass`, `u_problem`, `u_answer`,u_nickname) values (?,?,?,?,?)";
Object[] params={user.getU_name(),user.getU_pass(),user.getU_problem(),user.getU_answer(),user.getU_nickname()};
return DBUtil.executeUpdate(sql, params);
}
public int getTotalCount() {//查询总数据量
String sql = "select count(*) from user where is_used=true" ;
return DBUtil.getTotalCount(sql);
}
public List<User> Userlist(int currentPage, int pageSize){
List<User> list=new ArrayList<User>();
User user=null;
String sql="select * from user ORDER BY createtime DESC LIMIT ?,?;";
Object[] params={(currentPage-1)*pageSize,pageSize};
rs = DBUtil.getResulSet(sql, params);
try {
while(rs.next()){
int u_id = rs.getInt("u_id");
String name = rs.getString("u_name");
byte[] u_pass = rs.getBytes("u_pass");
String u_nickname= rs.getString("u_nickname");
String u_touxiang= rs.getString("u_touxiang");
String u_problem= rs.getString("u_problem");
String u_answer= rs.getString("u_answer");
Timestamp timestamp = rs.getTimestamp("createtime");
boolean is_used = rs.getBoolean("is_used");
user =new User();
user.setU_id(u_id);
user.setU_name(name);
user.setU_pass(u_pass);
user.setU_nickname(u_nickname);
user.setU_touxiang(u_touxiang);
user.setU_problem(u_problem);
user.setU_answer(u_answer);
user.setCreatetime(timestamp);
user.setIs_used(is_used);
list.add(user);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
return null;
}finally{
DBUtil.closeAll(rs,DBUtil.pstmt,DBUtil.connection);
}
}
public User UserByname(String u_name){
User user=null;
String sql="select * from user where u_name=?;";
Object[] params={u_name};
rs = DBUtil.getResulSet(sql, params);
try {
if(rs.next()){
int u_id = rs.getInt("u_id");
String name = rs.getString("u_name");
byte[] u_pass = rs.getBytes("u_pass");
String u_nickname= rs.getString("u_nickname");
String u_touxiang= rs.getString("u_touxiang");
String u_problem= rs.getString("u_problem");
String u_answer= rs.getString("u_answer");
Timestamp timestamp = rs.getTimestamp("createtime");
boolean is_used = rs.getBoolean("is_used");
user =new User();
user.setU_id(u_id);
user.setU_name(name);
user.setU_pass(u_pass);
user.setU_nickname(u_nickname);
user.setU_touxiang(u_touxiang);
user.setU_problem(u_problem);
user.setU_answer(u_answer);
user.setCreatetime(timestamp);
user.setIs_used(is_used);
}
return user;
} catch (SQLException e) {
e.printStackTrace();
return null;
}finally{
DBUtil.closeAll(rs,DBUtil.pstmt,DBUtil.connection);
}
}
public boolean userByis_used(int id,int is_used){
String sql = "update `weblog`.`user` set is_used=? where `u_id` = ?" ;
Object[] params = {is_used,id};
return DBUtil.executeUpdate(sql, params) ;
}
}
|
package com.kplex.swarm;
import com.kplex.node.Node;
import com.kplex.particle.ContinuousParticle;
import com.kplex.particle.Particle;
import com.kplex.particle.acceleration.Acceleration;
import com.kplex.particle.acceleration.LinearlyChangingCognitive;
import com.kplex.particle.acceleration.LinearlyChangingSocial;
import com.kplex.particle.fitness.Fitness;
import com.kplex.particle.fitness.SortingFitness;
import com.kplex.particle.inertia.IdealVelocityControlledInertia;
import com.kplex.particle.inertia.Inertia;
import com.kplex.util.Utils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static com.kplex.config.Constants.*;
import static com.kplex.config.Constants.LEARNING_RATE;
public class ContinuousSwarm extends Swarm<ContinuousParticle, List<Double>, List<Double>> {
public ContinuousSwarm(Map<Integer, Node> nodes,
Fitness<List<Double>, List<Double>> fitness,
Inertia inertia,
Acceleration cognitive,
Acceleration social) {
super(nodes, fitness, inertia, cognitive, social);
currentInertia = INITIAL_INERTIA;
particles = IntStream.range(0, POPULATION_SIZE)
.mapToObj(value -> createParticle(nodes, fitness))
.collect(Collectors.toList());
particles.stream()
.max(Comparator.comparingDouble(Particle::getBestFitness))
.ifPresent(particle -> {
globalBestPosition = new ArrayList<>(particle.getBestPosition());
globalBestFitness = particle.getBestFitness();
});
}
@Override
protected void diversifySwarm() {
IntStream.range(0, particles.size())
.filter(value -> ThreadLocalRandom.current().nextDouble() < DIVERSIFICATION_THRESHOLD)
.forEach(index -> particles.set(index, createParticle(nodes, fitness)));
}
@Override
protected void calculateInertia(int iterationCounter) {
currentInertia = inertia.calculate(currentInertia, iterationCounter, this::averageAbsoluteVelocity);
}
@Override
protected void calculateVelocity(ContinuousParticle particle, int iterationCounter) {
particle.setVelocity(
IntStream.range(0, numberOfNodes)
.mapToObj(index -> {
double random_cognitive_factor = ThreadLocalRandom.current().nextDouble();
double random_social_factor = ThreadLocalRandom.current().nextDouble();
return currentInertia * particle.getVelocity().get(index)
+ cognitive.calculate(iterationCounter) * random_cognitive_factor
* (particle.getBestPosition().get(index)
- particle.getPosition().get(index))
+ social.calculate(iterationCounter) * random_social_factor
* (globalBestPosition.get(index) - particle.getPosition().get(index));
})
.collect(Collectors.toList())
);
}
@Override
protected void updatePosition(ContinuousParticle particle) {
particle.setPosition(
IntStream.range(0, numberOfNodes)
.mapToObj(
index -> Utils.boxed(
particle.getPosition().get(index)
+ LEARNING_RATE * particle.getVelocity().get(index)
)
)
.collect(Collectors.toList())
);
}
@Override
protected void updateBestKnownPosition(ContinuousParticle particle, int iterationCounter) {
double fitness = particle.fitness();
if (fitness > particle.getBestFitness()) {
particle.setBestPosition(new ArrayList<>(particle.getPosition()));
particle.setBestFitness(fitness);
}
}
@Override
protected void updateGlobalBestKnownPosition() {
particles.stream()
.filter(particle -> particle.getBestFitness() > globalBestFitness)
.max(Comparator.comparingDouble(Particle::getBestFitness))
.ifPresent(particle -> {
globalBestPosition = new ArrayList<>(particle.getBestPosition());
globalBestFitness = particle.getBestFitness();
});
}
@Override
protected ContinuousParticle createParticle(Map<Integer, Node> nodes,
Fitness<List<Double>, List<Double>> fitness) {
return new ContinuousParticle(nodes, fitness);
}
private double averageAbsoluteVelocity() {
return particles.stream()
.flatMap(continuousParticle -> continuousParticle.getVelocity().stream())
.mapToDouble(Double::doubleValue)
.sum();
}
// TODO parametrize this
public static ContinuousSwarm newSwarm(Map<Integer, Node> nodes) {
return new ContinuousSwarm(
nodes,
SortingFitness.getInstance(),
IdealVelocityControlledInertia.getInstance(),
LinearlyChangingCognitive.getInstance(),
LinearlyChangingSocial.getInstance()
);
}
// TODO temp
public static ContinuousSwarm worstSwarm(List<ContinuousSwarm> swarms) {
return swarms.stream()
.min(Comparator.comparingDouble(Swarm::getGlobalBestFitness))
.orElseThrow(RuntimeException::new);
}
}
|
package com.atguigu.java2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
/*
一 存储对象的容器: 数组,集合
二1.数组在内存存储方面的特点:
1.数组初始化以后,长度就确定了。
2.数组声明的类型,就决定了进行元素初始化时的类型
2.数组在存储数据方面的弊端:
1.数组初始化以后,长度就不可变了,不便于扩展
2.数组中提供的属性和方法少,不便于进行添加、删除、插入等操作,且效率不高。同时无法直接获取存储元素的个数
3.数组存储的数据是有序的、可以重复的。---->存储数据的特点单一
三 集合分为两个体系 : Collection接口(单列集合)和 Map接口(双列集合)
四
|-----Collection(单列集合)
|-----List: 存储的元素是有序的,可重复的
|-----Set: 存储的元素是无序的,不可重复的
五 Collection API
*/
public class CollectionTest {
/*
10、获取集合对象的哈希值
hashCode() - (先理解成地址值,同一个对象的哈希值是相同的,不同的对象的哈希值是不同的)
11、遍历
iterator():返回迭代器对象,用于集合遍历
*/
@Test
public void test5(){
Person p = new Person("aa",18);
System.out.println(p.hashCode());
System.out.println(p.hashCode());
System.out.println(p.hashCode());
Person p2 = new Person("aa",18);
System.out.println(p2.hashCode());
System.out.println(p2.hashCode());
System.out.println(p2.hashCode());
}
/*
8、集合是否相等
boolean equals(Object obj)
9、转成对象数组
Object[] toArray()
*/
@Test
public void test4(){
//equals()比较的是两个集合元素的个数,顺序,内容。只要有一个不符合就为false
Collection c = new ArrayList();
c.add("aaa");
c.add("ccc");
Collection c2 = new ArrayList();
c2.add("aaa");
c2.add("ccc");
c2.add("ccc");
System.out.println(c.equals(c2));
//9、转成对象数组Object[] toArray()
Object[] array = c.toArray();
System.out.println(Arrays.toString(array));
}
/*
6、删除
boolean remove(Object obj) :通过元素的equals方法判断是否是要删除的那个元素。只会删除找到的第一个元素
boolean removeAll(Collection coll):取当前集合的差集
7、取两个集合的交集
boolean retainAll(Collection c):把交集的结果存在当前集合中,不影响c
*/
@Test
public void test3(){
//boolean remove(Object obj) :通过元素的equals方法判断是否是要删除的那个元素。只会删除找到的第一个元素
Collection c = new ArrayList();
c.add("aaa");
c.add("ccc");
c.add(new Person("ccc",18));
// c.remove("ccc");
// c.remove(new Person("ccc",18));
// System.out.println(c);
//boolean removeAll(Collection coll):取当前集合的差集(删除coll和当前集合交集的部分(相同的元素))
// Collection c2 = new ArrayList();
// c2.add("aaa");
// c2.add("ccc");
// c2.add("ddd");
// c.removeAll(c2);
//boolean retainAll(Collection c):把交集的结果存在当前集合中,不影响c (保留c和当前集合中交集的部分(相同的元素))
Collection c2 = new ArrayList();
c2.add("aaa");
c2.add("ccc");
c2.add("ddd");
c.retainAll(c2);
System.out.println(c);
System.out.println(c2);
}
/*
1、添加元素
add(Object obj)
addAll(Collection coll)
2、获取有效元素的个数
int size()
3、清空集合
void clear()
4、是否是空集合
boolean isEmpty()
5、是否包含某个元素
boolean contains(Object obj):是通过元素的equals方法来判断是否是同一个对象
boolean containsAll(Collection c):也是调用元素的equals方法来比较的。拿两个集合的元素挨个比较。
注意 : 我们向Collection添加自定义类的对象,那么该对象所在的类必须重写equals方法。
*/
@Test
public void test2(){
Collection c = new ArrayList();
c.add("ccc");
c.add("ddd");
c.add("fff");
c.add(new Person("cangjie", 18));
c.add(new String("aabb"));
//boolean contains(Object obj):是通过元素的equals方法来判断是否是同一个对象
boolean contains = c.contains("ccc");
//当我们调用contains方法时,会去调用传入到这个方法中的实参所在类的equals方法和当前集合中所有的元素进行内容的比较。
contains = c.contains(new Person("cangjie", 18));
// contains = c.contains(new String("aabb"));
System.out.println(contains);
System.out.println("----------------------------------------------------------");
//boolean containsAll(Collection c):也是调用元素的equals方法来比较的。拿两个集合的元素挨个比较。
Collection c2 = new ArrayList();
c2.add("ccc");
c2.add("ccc");
c2.add("ccc");
c2.add("ccc");
c2.add("ccc");
// c2.add("eee");
boolean bo = c.containsAll(c2);
System.out.println(bo);
}
@Test
public void test(){
//多态
Collection c = new ArrayList();
//add(Object o)添加元素
c.add("ccc");
c.add(111); //自动装箱
Collection c2 = new ArrayList();
c2.add(1);
c2.add(2);
//addAll(Collection c) :将c集合中的元素分别添加到当前集合中
c.addAll(c2);
//3、清空集合void clear()
c.clear();
System.out.println(c);
//size() :当前集合中元素的个数
System.out.println(c.size());
// 4、是否是空集合boolean isEmpty()
System.out.println(c.isEmpty());
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Person")
public class Person extends HttpServlet {
private static final long serialVersionUID = 1L;
public Person() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String id = request.getParameter("id");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String[] notice = request.getParameterValues("notice");
String job = request.getParameter("job");
PrintWriter out = response.getWriter();
out.print("<html> <body>");
out.print("이름 :" + name + "<br>");
out.print("아이디 :" + id + "<br>" );
out.print("암호 :" + password+ "<br>");
out.print("성별 :" + gender+ "<br>");
out.print("알림 :" + Arrays.toString(notice)+ "<br>");
out.print("직업 :" + job+ "<br>");
out.print("</body> </html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package cn.com.signheart.component.core.security.system;
import cn.com.signheart.component.core.core.PlatFormContext;
import cn.com.signheart.component.core.security.model.TbPermissmionPO;
import cn.com.signheart.component.core.security.model.TbRolePO;
import cn.com.signheart.component.core.security.model.TbRolePermissionRefPO;
import cn.com.signheart.component.core.security.service.IAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by ao.ouyang on 15-11-4.
*/
public class AuthMgr {
private static final transient Logger logger = LoggerFactory.getLogger(AuthMgr.class);
private static Map<String,List<TbPermissmionPO>> rolePermission;
static {
rolePermission = new ConcurrentHashMap<>();
}
public static List<TbPermissmionPO> getRolePermission(String roleId){
return rolePermission.get(roleId);
}
public static void putRolePermission(String roleId,List<TbPermissmionPO> permissmionPOs){
rolePermission.put(roleId,permissmionPOs);
}
public static void flushRolePermission(){
rolePermission.clear();
loadRolePermission();
}
public static void loadRolePermission(){
try {
logger.info("读取系统角色权限。");
IAuthService authService = (IAuthService) PlatFormContext.getSpringContext().getBean("authService");
List<TbPermissmionPO> permissmionPOs = authService.searchSysPermission();
List<TbRolePermissionRefPO> rolePermissionRefPOs = authService.searchRolePremRefList();
List<TbRolePO> tbRolePOs = authService.searchRoleList();
for (TbRolePO tbRolePO : tbRolePOs) {
for (TbRolePermissionRefPO tbRolePermissionRefPO : rolePermissionRefPOs) {
if(tbRolePO.getRoleId().equalsIgnoreCase(tbRolePermissionRefPO.getRoleId())){
ArrayList rolePermList = new ArrayList();
if (null != rolePermission.get(tbRolePO.getRoleName())) {
rolePermList = (ArrayList) rolePermission.get(tbRolePO.getRoleName());
}
for (TbPermissmionPO tbPerm : permissmionPOs) {
if (tbPerm.getPermissionId().equalsIgnoreCase(tbRolePermissionRefPO.getPermissionId())) {
rolePermList.add(tbPerm);
}
}
rolePermission.put(tbRolePO.getRoleName(), rolePermList);
}
}
}
logger.info("系统角色权限已冲至内存。");
}catch (Exception e){
logger.info("系统角色权限缓存失败。");
logger.error(e.getMessage(),e);
}
}
}
|
1.使用消息中间件的原因
-当系统过于庞大时 如果单线程的去进行服务之间的调用,响应时间会过于漫长,对系统压力较大
当被调用的所有服务都处理完成才会返回结果.
2.消息中间件作用
-异步通知被调用的服务,直接返回结果(异步)
-服务直接解耦合
-可以帮助服务横向扩展
-服务之间调用可以保证顺序
3.概念
关注数据的发送和接受,利用高效可靠的异步消息传递来集成分布式系统
-----------------------------------------------------------------------------------
3.JMS规范
java中关于面向消息中间件的API,用于在两个应用程序之间或分布式系统中发送消息,进行异步同行
-支持模型 p2p pub/sub
-支持类型 java中常见的数据类型
-队列模式
-队列中的消息只能被一个消费者消费
-客户端包括生产者和消费者
-消费者可以随时消费队列中的消息
-主题模式
-客户端包括发布者和订阅者
-主题中的消息被所有订阅者消费
-消费者不能消费订阅之前就发送到主题中的消息
-JMS消息相关接口
链接工厂--创建链接--链接创建一个会话(单线程,可以创建多个)--会话创建生产者\消费者---生产者吧消息发送到目的地---消费者从目的地获取
4.AMQP协议
提供统一消息服务的应用层标准协议,鲫鱼次协议的客户端与消息中间件可传递消息,不收客户端中间件不同产品不同语言条件限制
-支持模型 direct danout topic队列 headers sysytem
-支持类型 二进制消息
--------------------------------------------------------------------------------------
5.常见 中间件
-ActiveMQ(java优先)
-支持多语言.多协议
-消息持久化
-中小企业消息应用,不适合上千了队列的应用
-rabbitMQ
-AMQP协议的完整实现
-消息持久化
-适合对性稳定要求高的企业级用用
-Kafka
-日志服务储存
-严格的顺序机制
-高吞吐量
-依赖zk
-应用于大数据日志处理或对实时性(少量顺序),可靠性(少量数据丢失)要求稍低的场景使用
-----------------------------------------------------------------------------------------------------
6.Spring中的JMS
-连接池
-singleConnectionFactory
整个一直使用一个链接进行操作
-CachingConnectionFactory
继承single 新增缓存功能
-JMSTemlate
spring中注入直接使用
-MessageListner
时限一个onMessage方法 直接收一个Message参数
|
/*
* Created by SixKeyStudios
* Added in project Technicalities
* File configmanagers.items.nature / NatureConfigManager
* created on 21.5.2019 , 22:25:52
*/
package technicalities.configmanagers.craftingstations;
import technicalities.configmanagers.ConfigManager;
import technicalities.configmanagers.ConfigWrapper;
import java.io.InputStream;
import java.util.ArrayList;
import technicalities.configmanagers.CommonTranslation;
import technicalities.configmanagers.energysources.EnergySourceWrapper;
import technicalities.items.item.ItemRequired;
import technicalities.configmanagers.miscwrappers.StorageWrapper;
import technicalities.configmanagers.recept.ReceptWrapper;
/**
* NatureConfigManager
* - config manager that gets information from nature.tcf and translates it into wrappers
* @author filip
*/
public class CraftingStationConfigManager extends ConfigManager {
////// VARIABLES //////
private int writingToStation = 0; //0 beginning,1 recepts
private String currentStation = null;
private ItemRequired cSItemRequired = null;
private ArrayList<ReceptWrapper> recepts;
private EnergySourceWrapper[] energySourceWrappers;
private StorageWrapper input, output;
////// CONSTRUCTORS //////
/**
* On creaton grabs the file and translates it by its rules to a set of wrappers
* @param configFile file that will be read to the rules of the manager
*/
public CraftingStationConfigManager(InputStream configFile) {
super(configFile);
}
////// METHODS ///////
@Override
public ConfigWrapper stringToWrapper(String line) {
if(writingToStation == 0) {
currentStation = null;
cSItemRequired = null;
recepts = new ArrayList<ReceptWrapper>();
String[] words = line.split(" ");
currentStation = words[0];
cSItemRequired = new ItemRequired(CommonTranslation.toItems(words[1]));
writingToStation = 1;
energySourceWrappers = CommonTranslation.toEnergySourceWrappers(words[2]);
input = CommonTranslation.toStorage(words[3]);
output = CommonTranslation.toStorage(words[4]);
} else if(writingToStation == 1) {
if(line.charAt(0) != '}') {
String receptId = line;
recepts.add((ReceptWrapper)technicalities.Technicalities.RCM.getWrapper(receptId));
} else {
writingToStation = 0;
return new CraftingStationWrapper(
currentStation,
cSItemRequired,
recepts.toArray(new ReceptWrapper[recepts.size()]),
energySourceWrappers,
input,
output
);
}
}
return null;
}
}
|
class ContainsDuplicate {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set=new HashSet<>(Arrays.stream(nums).mapToObj(e -> (int) e).collect(Collectors.toSet()));
//System.out.println(set);
if(set.size()!=nums.length)
return true;
else
return false;
}
}
|
package com.zzp.nacos.user.mapper;
import com.zzp.nacos.user.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 用户表 Mapper 接口
* </p>
*
* @author zzp
* @since 2020-09-17
*/
public interface UserMapper extends BaseMapper<User> {
}
|
package controller;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import model.Noticia;
import model.Secao;
import model.Usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import dao.NoticiaDAO;
@Controller
@Transactional
public class NoticiaController {
@Autowired(required = false)
private NoticiaDAO nDAO;
@RequestMapping("formularioNoticia")
public String formularioNoticia(){
return "formulario_noticia";
}
@RequestMapping("inserirNoticia")
public String inserirNoticia(Noticia n, HttpSession session){
// Usuario u = (Usuario)session.getAttribute("usuario");
// falta so pegar pegar usuario e secao do session
Usuario u = new Usuario(1,"a","a","a","a", null);
Secao s = new Secao(1, "a", "a");
n.setAutor(u);
n.setSecao(s);
n.setDataNoticia(new Date());
nDAO.adicinar(n);
System.out.println(n.toString());
return "usuario_adicionado";
}
@RequestMapping("listarNoticia")
public String listarNoticia(Model m){
List<Noticia> list = nDAO.listar();
m.addAttribute("noticias", list);
return "listar_noticia";
}
@RequestMapping("removerNoticia")
public String removerNoticia(Noticia n){
nDAO.remover(n);
return "redirect:listar_noticia";
}
@RequestMapping ("alterarNoticia")
public String alterarNoticia(Noticia n, BindingResult result){
if (result.hasErrors())
return "formulario_Noticia";
nDAO.alterar(n);
return "redirect:listar_noticia";
}
}
|
/*
* 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 cliente;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelos.Alumno;
import modelos.Asignacion;
import modelos.Curso;
/**
*
* @author Steeltwins
*/
public class GUI_Asignacion extends javax.swing.JFrame {
/**
* Creates new form GUI_Asignacion
*/
public GUI_Asignacion() {
initComponents();
cboAlumno.removeAllItems();
cboCurso.removeAllItems();
getAssignations();
// getStudents();
//getCourses();
}
public void getCourses() {
AsignacionRequest cliente;
cliente = new AsignacionRequest(this, 'c');
Thread peticion = new Thread(cliente);
peticion.start();
}
public void listCourses(ArrayList<Curso> cursos) {
for (int i = 0, j = 0; i < cursos.size(); i++) {
cboCurso.addItem(cursos.get(i).getNombre() + "-" + cursos.get(i).getIdCurso());
}
}
public void getStudents() {
AsignacionRequest cliente;
cliente = new AsignacionRequest(this, 's');
Thread peticion = new Thread(cliente);
peticion.start();
}
public void listStudents(ArrayList<Alumno> alumnos) {
for (int i = 0, j = 0; i < alumnos.size(); i++) {
cboAlumno.addItem(alumnos.get(i).getNombre() + "-" + alumnos.get(i).getIdAlumno());
}
}
public void getAssignations() {
AsignacionRequest cliente;
cliente = new AsignacionRequest(this, 'l');
Thread peticion = new Thread(cliente);
peticion.start();
}
public void listAssignations(ArrayList<Asignacion> asignacion) {
Object[][] assigned = new Object[asignacion.size()][4];
String[] columns = {"idCurso", "idAlumno", "Horario", "Tipo de Curso"};
for (int i = 0, j = 0; i < asignacion.size(); i++) {
assigned[i][j] = "" + asignacion.get(i).getIdCurso();
assigned[i][j + 1] = "" + asignacion.get(i).getIdAlumno();
assigned[i][j + 2] = "" + asignacion.get(i).getHorario();
assigned[i][j + 3] = "" + asignacion.get(i).getTipo();
}
tblShowTable.setModel(new DefaultTableModel(assigned, columns));
}
public void setValuesSearched(Asignacion asignacion) {
// cboAlumno.setSelectedItem(asignacion.getIdAlumno());
// cboCurso.setSelectedItem(asignacion.getIdCurso());
// txtHorario.setText(asignacion.getHorario());
// spTipoDeCurso.setValue(asignacion.getTipo());
Object[][] assigned = new Object[1][4];
String[] columns = {"idCurso", "idAlumno", "Horario", "Tipo de Curso"};
assigned[0][0] = "" + asignacion.getIdCurso();
assigned[0][1] = "" + asignacion.getIdAlumno();
assigned[0][2] = "" + asignacion.getHorario();
assigned[0][3] = "" + asignacion.getTipo();
tblShowTable.setModel(new DefaultTableModel(assigned, columns));
}
public Asignacion buscarAsignacion() {
AsignacionRequest cliente;
Asignacion asignacion = new Asignacion();
//int idCurso = Integer.parseInt(JOptionPane.showInputDialog(null, "Ingrese el id del Curso ", "Buscar asignacion", JOptionPane.QUESTION_MESSAGE));
int i = tblShowTable.getSelectedRow();
int idCurso = Integer.parseInt(tblShowTable.getValueAt(i, 0)+"");
int idAlumno = Integer.parseInt(tblShowTable.getValueAt(i, 1)+"");
asignacion.setIdCurso(idCurso);
//int idAlumno = Integer.parseInt(JOptionPane.showInputDialog(null, "Ingrese el id del Alumno ", "Buscar asignacion", JOptionPane.QUESTION_MESSAGE));
asignacion.setIdAlumno(idAlumno);
cliente = new AsignacionRequest(this, asignacion, 'b');
Thread peticion = new Thread(cliente);
peticion.start();
return asignacion;
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
cboAlumno = new javax.swing.JComboBox<String>();
jLabel2 = new javax.swing.JLabel();
cboCurso = new javax.swing.JComboBox<String>();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtHorario = new javax.swing.JTextField();
jPanel4 = new javax.swing.JPanel();
btnNuevoAsignacion = new javax.swing.JButton();
btnBuscarAsignacion = new javax.swing.JButton();
btnEliminarAsignacion = new javax.swing.JButton();
btnActualizaAsignacion = new javax.swing.JButton();
btnListarAsignaciones = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblShowTable = new javax.swing.JTable();
spTipoDeCurso = new javax.swing.JSpinner();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Gestor de Asignaciones");
jLabel1.setText("Alumno");
cboAlumno.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboAlumno.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cboAlumnoMouseClicked(evt);
}
});
jLabel2.setText("Curso");
cboCurso.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cboCurso.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cboCursoMouseClicked(evt);
}
});
jLabel3.setText("Horario");
jLabel4.setText("Tipo de curso");
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones"));
btnNuevoAsignacion.setText("Nuevo");
btnNuevoAsignacion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNuevoAsignacionActionPerformed(evt);
}
});
btnBuscarAsignacion.setText("Buscar");
btnBuscarAsignacion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarAsignacionActionPerformed(evt);
}
});
btnEliminarAsignacion.setText("Eliminar");
btnEliminarAsignacion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEliminarAsignacionActionPerformed(evt);
}
});
btnActualizaAsignacion.setText("Actualiza");
btnActualizaAsignacion.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnActualizaAsignacionActionPerformed(evt);
}
});
btnListarAsignaciones.setText("Listar");
btnListarAsignaciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnListarAsignacionesActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(btnEliminarAsignacion)
.addGap(18, 18, 18)
.addComponent(btnActualizaAsignacion)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(btnNuevoAsignacion)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnBuscarAsignacion)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnListarAsignaciones)
.addGap(48, 48, 48))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnNuevoAsignacion)
.addComponent(btnBuscarAsignacion))
.addGap(18, 18, 18)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnEliminarAsignacion)
.addComponent(btnActualizaAsignacion))
.addGap(18, 18, 18)
.addComponent(btnListarAsignaciones)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
tblShowTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"idCurso", "idAlumno", "Horario", "Tipo de curso"
}
));
jScrollPane1.setViewportView(tblShowTable);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(42, 42, 42)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(18, 18, 18)
.addComponent(spTipoDeCurso))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(47, 47, 47)
.addComponent(cboAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cboCurso, 0, 116, Short.MAX_VALUE)
.addComponent(txtHorario))))
.addGap(37, 37, 37)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 482, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cboAlumno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(cboCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtHorario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(spTipoDeCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(28, 28, 28)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(51, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnNuevoAsignacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoAsignacionActionPerformed
AsignacionRequest cliente;
Asignacion asignacion = new Asignacion();
System.out.println("idAlumno: " + cboAlumno.getSelectedItem().toString().substring(cboAlumno.getSelectedItem().toString().indexOf("-")));
System.out.println("idAlumno: " + cboCurso.getSelectedItem().toString().substring(cboCurso.getSelectedItem().toString().indexOf("-") + 1));
asignacion.setIdAlumno(Integer.parseInt(cboAlumno.getSelectedItem().toString().substring(cboAlumno.getSelectedItem().toString().indexOf("-") + 1)));
asignacion.setIdCurso(Integer.parseInt(cboCurso.getSelectedItem().toString().substring(cboCurso.getSelectedItem().toString().indexOf("-") + 1)));
asignacion.setHorario(txtHorario.getText());
asignacion.setTipo((int) spTipoDeCurso.getValue());
int option = JOptionPane.showConfirmDialog(null, "¿Seguro que desea crear la asignacion?", "Crear asignacion", JOptionPane.YES_NO_OPTION);
if (option == 0) {
cliente = new AsignacionRequest(this, asignacion, 1, 'u');
Thread peticion = new Thread(cliente);
peticion.start();
}
}//GEN-LAST:event_btnNuevoAsignacionActionPerformed
private void btnBuscarAsignacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarAsignacionActionPerformed
Asignacion asignacion = new Asignacion();
asignacion = buscarAsignacion();
}//GEN-LAST:event_btnBuscarAsignacionActionPerformed
private void btnEliminarAsignacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarAsignacionActionPerformed
AsignacionRequest cliente;
Asignacion asignacion = new Asignacion();
asignacion = buscarAsignacion();
int option = JOptionPane.showConfirmDialog(null, "¿Seguro que desea eliminar la asignacion?", "Eliminar asignacion", JOptionPane.YES_NO_OPTION);
if (option == 0) {
cliente = new AsignacionRequest(this, asignacion, 'd');
Thread peticion = new Thread(cliente);
peticion.start();
}
}//GEN-LAST:event_btnEliminarAsignacionActionPerformed
private void btnActualizaAsignacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizaAsignacionActionPerformed
Asignacion asignacion = new Asignacion();
AsignacionRequest cliente;
asignacion = buscarAsignacion();
asignacion.setHorario(txtHorario.getText());
asignacion.setTipo((int) spTipoDeCurso.getValue());
int option = JOptionPane.showConfirmDialog(null, "¿Seguro que desea actualizar la asignacion?", "Actualizar asignacion", JOptionPane.YES_NO_OPTION);
if (option == 0) {
cliente = new AsignacionRequest(this, asignacion, 2, 'u');//Primer parametro=datos,Segundo parametro: 1=insert 2=update,Tercer parametro:'u'=update&insert 'd'=delete 'b'=buscar 'l'=listar
Thread peticion = new Thread(cliente);
peticion.start();//Peticion asincrona
}
}//GEN-LAST:event_btnActualizaAsignacionActionPerformed
private void btnListarAsignacionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListarAsignacionesActionPerformed
getAssignations();
}//GEN-LAST:event_btnListarAsignacionesActionPerformed
private void cboCursoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cboCursoMouseClicked
cboCurso.removeAllItems();
getCourses();
}//GEN-LAST:event_cboCursoMouseClicked
private void cboAlumnoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cboAlumnoMouseClicked
cboAlumno.removeAllItems();
getStudents();
}//GEN-LAST:event_cboAlumnoMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI_Asignacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI_Asignacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI_Asignacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI_Asignacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI_Asignacion().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnActualizaAsignacion;
private javax.swing.JButton btnBuscarAsignacion;
private javax.swing.JButton btnEliminarAsignacion;
private javax.swing.JButton btnListarAsignaciones;
private javax.swing.JButton btnNuevoAsignacion;
private javax.swing.JComboBox<String> cboAlumno;
private javax.swing.JComboBox<String> cboCurso;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSpinner spTipoDeCurso;
private javax.swing.JTable tblShowTable;
private javax.swing.JTextField txtHorario;
// End of variables declaration//GEN-END:variables
}
|
package com.flushoutsolutions.foheart.modules;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.flushoutsolutions.foheart.application.FoHeart;
import com.flushoutsolutions.foheart.globals.Variables;
import com.flushoutsolutions.foheart.logic.Procedures;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ListCheckScreen
{
private String name;
private String container;
private int style = 1;
private String list = null;
private boolean multiselect = true;
private List<ListCheckScreenItem> listOptions;
private List<Boolean> listOptionsSelected;
private ViewGroup layout;
private String checkedItem;
private String ev_on_select_cell = null;
public ListCheckScreen(String name, String container, ViewGroup layout)
{
this.name = name;
this.layout = layout;
this.container = container;
}
public ListCheckScreen(String name, String container, ViewGroup layout, String properties, String events) throws JSONException
{
this.name = name;
this.layout = layout;
this.container = container;
System.out.println("debug: ListCheckScreen");
listOptions = new ArrayList<ListCheckScreenItem>();
listOptionsSelected = new ArrayList<Boolean>();
JSONObject jsonProperties = new JSONObject(properties);
System.out.println("jsonproperties: " + jsonProperties);
if (!jsonProperties.isNull("style"))
this.style = jsonProperties.getInt("style");
if (!jsonProperties.isNull("list"))
this.list = jsonProperties.getString("list");
if (!jsonProperties.isNull("multiselect"))
this.multiselect = jsonProperties.getBoolean("multiselect");
if(!jsonProperties.isNull("checkedItem"))
this.checkedItem = Variables.parse_vars(jsonProperties.getString("checkedItem"), false);
JSONObject jsonEvents = new JSONObject(events);
if (!jsonEvents.isNull("onSelectCell"))
this.ev_on_select_cell = jsonEvents.getString("onSelectCell");
}
public void set_style(int style)
{
this.style = style;
}
public void set_multiselect(boolean multiselect)
{
this.multiselect = multiselect;
}
public void set_list(String list)
{
this.list = list;
}
public void render() throws JSONException, IOException
{
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 60, FoHeart.getAppContext().getResources().getDisplayMetrics());
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) 4, FoHeart.getAppContext().getResources().getDisplayMetrics());
if (this.list.startsWith("["))
{
JSONArray arrayList = new JSONArray(this.list);
for (int x=0; x<arrayList.length(); x++)
{
JSONObject objectLine = arrayList.getJSONObject(x);
String icon = "";
if (!objectLine.isNull("icon"))
icon = Variables.parse_vars(objectLine.getString("icon"), false);
ListCheckScreenItem listItem;
//validando item como checked
if(objectLine.getString("value").equals(this.checkedItem)){
listItem = new ListCheckScreenItem(FoHeart.getAppContext(), this, x, false, this.style, objectLine.getString("value"), objectLine.getString("title"), objectLine.getString("subtitle"), icon, true);
}else {
listItem = new ListCheckScreenItem(FoHeart.getAppContext(), this, x, false, this.style, objectLine.getString("value"), objectLine.getString("title"), objectLine.getString("subtitle"), icon, false);
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, height);
params.setMargins(0, 0, 0, margin);
listItem.setLayoutParams(params);
listOptions.add(listItem);
listOptionsSelected.add(false);
this.layout.addView(listItem);
}
}
else
{
JSONObject props = new JSONObject(this.list);
JSONArray arrayList = new JSONArray(Variables.get(props.getString("objectList")).toString());
for (int x=0; x<arrayList.length(); x++)
{
JSONObject objectLine = arrayList.getJSONObject(x);
String value = objectLine.getString(Variables.parse_vars(props.getString("index"), false));
String title = objectLine.getString(Variables.parse_vars(props.getString("title"), false));
String subtitle = "";
if (!props.isNull("subtitle"))
if (!"".equals(props.getString("subtitle")))
subtitle = objectLine.getString(Variables.parse_vars(props.getString("subtitle"), false));
String icon = "";
if (!props.isNull("icon"))
if (!"".equals(props.getString("icon")))
icon = objectLine.getString(Variables.parse_vars(props.getString("icon"), false));
ListCheckScreenItem listItem;
//validando item como checked
if(value.equals(this.checkedItem)) {
listItem = new ListCheckScreenItem(FoHeart.getAppContext(), this, x, false, this.style, value, title, subtitle, icon, true);
}else{
listItem = new ListCheckScreenItem(FoHeart.getAppContext(), this, x, false, this.style, value, title, subtitle, icon, false);
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, height);
params.setMargins(0, 0, 0, margin);
listItem.setLayoutParams(params);
System.out.println("listItem " + listItem);
listOptions.add(listItem);
listOptionsSelected.add(false);
this.layout.addView(listItem);
}
}
set_properties();
}
public String get_name_addressed()
{
return this.container + "__"+this.name;
}
public void event_on_select(int position)
{
if (!this.multiselect)
{
for (int x =0; x<listOptions.size(); x++)
{
listOptions.get(x).set_unselected();
listOptionsSelected.set(x, false);
}
listOptions.get(position).set_selected();
listOptionsSelected.set(position, true);
}
set_properties();
if (this.ev_on_select_cell != null && !this.ev_on_select_cell.equals(""))
{
try
{
Procedures mainProcedure = new Procedures();
mainProcedure.initialize(this.ev_on_select_cell, "{'sender':'"+get_name_addressed()+"'}");
mainProcedure.execute();
}
catch (JSONException e1)
{
e1.printStackTrace();
}
}
}
public void set_properties()
{
String valueString = "";
String pattern = this.get_name_addressed()+"__";
String jsonSelectedIndexes = "[";
for (int x =0; x<listOptions.size(); x++)
{
if (listOptions.get(x).get_state())
jsonSelectedIndexes += "{\"index\":"+x+"}, ";
}
if (jsonSelectedIndexes.endsWith(", ")) jsonSelectedIndexes = jsonSelectedIndexes.substring(0, jsonSelectedIndexes.length()-2);
jsonSelectedIndexes += "]";
String jsonSelectedValues = "[";
for (int x =0; x<listOptions.size(); x++)
{
if (listOptions.get(x).get_state())
{
jsonSelectedValues += "{\"value\":\""+listOptions.get(x).get_value()+"\"}, ";
//valueString = valueString + listOptions.get(x).get_value()+";";
valueString = valueString + listOptions.get(x).get_value()+",";
}
}
if (jsonSelectedValues.endsWith(", ")) jsonSelectedValues = jsonSelectedValues.substring(0, jsonSelectedValues.length()-2);
jsonSelectedValues += "]";
String jsonSelectedTitles = "[";
for (int x =0; x<listOptions.size(); x++)
{
if (listOptions.get(x).get_state())
jsonSelectedTitles += "{\"title\":\""+listOptions.get(x).get_title()+"\"}, ";
}
if (jsonSelectedTitles.endsWith(", ")) jsonSelectedTitles = jsonSelectedTitles.substring(0, jsonSelectedTitles.length()-2);
jsonSelectedTitles += "]";
if (valueString.length() > 0) valueString = valueString.substring(0, valueString.length()-1);
Variables.add(pattern+"selectedIndexes", "array.int", jsonSelectedIndexes);
Variables.add(pattern+"selectedValues", "array.string", jsonSelectedValues);
Variables.add(pattern+"selectedTitles", "array.string", jsonSelectedTitles);
Variables.add(pattern+"selectedValuesString", "string", valueString);
}
public void method_clear()
{
int count = this.layout.getChildCount();
for (int x=count-1; x>=0; x--)
{
// System.out.println("dbg "+this.layout.getChildAt(x).getClass());
if (this.layout.getChildAt(x)!=null)
{
Class<? extends View> cls = this.layout.getChildAt(x).getClass();
if (cls.getName().endsWith("ListCheckScreenItem"))
{
ListCheckScreenItem item = (ListCheckScreenItem)this.layout.getChildAt(x);
if (item.parent == this)
this.layout.removeViewAt(x);
}
}
}
}
}
|
package com.framgia.fsalon.screen.login;
import com.framgia.fsalon.BasePresenter;
import com.framgia.fsalon.BaseViewModel;
/**
* This specifies the contract between the view and the presenter.
*/
interface LoginContract {
/**
* View.
*/
interface ViewModel extends BaseViewModel<Presenter> {
void showProgressbar();
void onCustomerLoginSuccess();
void onLoginErrror(String message);
void hideProgressbar();
void onLoginClick();
void onRegisterClick();
void onForgotPassWordClick();
void onInputAccountError();
void onInputPassWordError();
void onAdminLoginSuccess();
void onStylistLoginSuccess();
}
/**
* Presenter.
*/
interface Presenter extends BasePresenter {
void login(String email, String passWord);
void getCurrentUser();
}
}
|
package Model;
import DBconnections.Javaconnect;
import java.sql.*;
import javax.swing.JOptionPane;
public class ExerciseModel {
private Connection con;
private Javaconnect conectDB;
private ResultSet rs;
private PreparedStatement pst;
private String id,username,date,time,exercise,calpermin,exstime,calorieburnt,cbotime;
private int r;
public ExerciseModel(){
conectDB = new Javaconnect();
con= conectDB.getConnection();
}
public ExerciseModel(String id, String username, String date,String time, String exercise, String calpermin, String exstime, String calorieburnt,String cbotime) {
this.id = id;
this.username = username;
this.date = date;
this.time = time;
this.exercise = exercise;
this.calpermin = calpermin;
this.exstime = exstime;
this.calorieburnt = calorieburnt;
this.cbotime = cbotime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getExercise() {
return exercise;
}
public void setExercise(String exercise) {
this.exercise = exercise;
}
public String getCalpermin() {
return calpermin;
}
public void setCalpermin(String calpermin) {
this.calpermin = calpermin;
}
public String getExstime() {
return exstime;
}
public void setExstime(String exstime) {
this.exstime = exstime;
}
public String getCalorieburnt() {
return calorieburnt;
}
public void setCalorieburnt(String calorieburnt) {
this.calorieburnt = calorieburnt;
}
public void setCbotime(String cbotime) {
this.cbotime = cbotime;
}
public String getCbotime() {
return cbotime;
}
public int Record(){
try
{
PreparedStatement pst = con.prepareStatement("INSERT INTO exercise_info(id,username,date,time,exercise,calpermin,"
+ "exstime,calorieburnt)"
+ "values(?,?,?,?,?,?,?,?)");
PreparedStatement ps = con.prepareStatement("INSERT INTO exercises(exsname,exscal) values(?,?)");
ps.setString(1, getExercise());
ps.setString(2, getExstime());
pst.setString(1,null);
pst.setString(2, getUsername());
pst.setString(3, getDate());
pst.setString(4, getTime());
pst.setString(5, getExercise());
pst.setString(6, getCalpermin());
pst.setString(7, getExstime());
pst.setString(8, getCalorieburnt());
r= pst.executeUpdate();
r= ps.executeUpdate();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
return r;
}
public int Updates(){
try {
pst = con.prepareStatement("update exercise_info set exercise = '"+getExercise()+"', calpermin='"+getCalpermin()+"' , exstime = '"+getExstime()+"' , calorieburnt = '"+getCalorieburnt()+"' where time='"+getCbotime()+"' AND username='"+getUsername()+"'");
PreparedStatement ps=con.prepareStatement("update exercises set exscal='"+getCalpermin()+"' "
+ "where exsname='"+getExercise()+"'");
r = pst.executeUpdate();
r= ps.executeUpdate();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
return r;
}
public ResultSet Retrival(){
try {
PreparedStatement pst = con.prepareStatement("Select * from exercise_info where date='"+getDate()+"' and time='"+getTime()+"' AND username='"+getUsername()+"'");
rs = pst.executeQuery();
if(rs.next()){
setExstime(rs.getString(6));
setCalorieburnt(rs.getString(7));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
return rs;
}
public int Delets(){
try {
PreparedStatement pst = con.prepareStatement("Delete from exercise_info where time='"+getCbotime()+"' AND username='"+getUsername()+"'");
r = pst.executeUpdate();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
return r;
}
public ResultSet Retrivedatas(){
try {
pst = con.prepareStatement("select * from exercise_info where time='"+getTime()+"'");
rs=pst.executeQuery();
if(rs.next()){
setCalpermin(rs.getString(6));
setExstime(rs.getString(7));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
return rs;
}
}
|
package com.pky.smartselling.configuration;
import java.util.Optional;
import com.pky.smartselling.domain.employee.Employee;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component
public class AuditorAwareImpl implements AuditorAware<Long> {
@Override
public Optional<Long> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null ||
!authentication.isAuthenticated() ||
authentication instanceof AnonymousAuthenticationToken) {
return Optional.empty();
}
Employee employee = (Employee)authentication.getPrincipal();
return Optional.ofNullable(employee.getEmployeeNo());
}
}
|
package com.ranpeak.ProjectX.activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import com.ranpeak.ProjectX.R;
import com.ranpeak.ProjectX.activity.interfaces.Activity;
import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.viewModel.MyProfileViewModel;
import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.viewModel.MyResumeViewModel;
import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.profileNavFragment.viewModel.MyTaskViewModel;
import com.ranpeak.ProjectX.activity.lobby.forGuestUsers.LobbyForGuestActivity;
import com.ranpeak.ProjectX.settings.SharedPrefManager;
import java.util.Objects;
public class SettingsActivity extends AppCompatActivity implements Activity {
private TextView searchText;
private TextView receiveNotification;
private CheckBox checkBox1;
private TextView receiveeEmailNotifications;
private CheckBox checkBox2;
private Button button;
private Button logOut;
private MyTaskViewModel taskViewModel;
private MyResumeViewModel resumeViewModel;
private MyProfileViewModel profileViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
findViewById();
onListener();
toolbar();
}
@Override
public void findViewById() {
searchText = findViewById(R.id.settings_activity_search_text);
receiveNotification = findViewById(R.id.settings_activity_receive_notification_text);
checkBox1 = findViewById(R.id.settings_activity_checkBox_1);
receiveeEmailNotifications = findViewById(R.id.settings_activity_receive_email_notifications_text);
checkBox2 = findViewById(R.id.settings_activity_checkBox_2);
button = findViewById(R.id.settings_activity_button);
logOut = findViewById(R.id.settings_activity_button_log_out);
}
@Override
public void onListener() {
logOut.setOnClickListener(v->{
SharedPrefManager.getInstance(this).logout();
removeAllDataFromLocalDB();
Intent intent = new Intent(this, LobbyForGuestActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
});
button.setOnClickListener((v) -> {
finish();
});
}
private void toolbar() {
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.toolbar_name);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// todo: goto back activity from here
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void removeAllDataFromLocalDB() {
profileViewModel = ViewModelProviders.of(this).get(MyProfileViewModel.class);
profileViewModel.deleteAllSocialNetworks();
taskViewModel = ViewModelProviders.of(this).get(MyTaskViewModel.class);
taskViewModel.deleteAllUsersTasks();
resumeViewModel = ViewModelProviders.of(this).get(MyResumeViewModel.class);
resumeViewModel.deleteAllUsersResumes();
}
}
|
/* I will define all the variables first. Then I will type cast them to represent their int value.
* Then I need to figure out how to format using the printf command to make the output and comparason look pretty and easy to read.
* Lastly, I will watch the Youtube video for the J-Unit testing.
* I am putting the ascii values for each character next to the variable assignments.
* I got the data from this source: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html
*
*
* @Author Aaron Lack, alack
* Last Edited: 1/27/20
*/
public class Lab2Integer {
public static String characters() {
//I need to ask how to why the main function does not work in JUNIT TESTING.
//Define all 20 characters
char charA = 'A'; //65
char charB = 'B'; //66
char charC = 'C'; //67
char charZ = 'Z'; //90
char charX = 'X'; //88
char char_a = 'a'; //97
char char_b = 'b'; //98
char char_c = 'c'; //99
char char_y = 'y'; //121
char char_u = 'u'; //117
char charZero = '0'; //48
char charNine = '9'; //57
char charTwo = '2'; //50
char charDollar = '$'; //36
char charStar = '*'; //42
char charGreater = '>'; //62
char charPipe = '|'; //124
char charBackslash = '\\' ; //92 Double backslash will not create a new line
char charSpace = (' '); //32 I put space and tab in () to represent a character
char charTab = (' '); //9 The output on the first line for space and tab are present.
String result = "";
result = result + (int) charA + " " +(int) charB + " " + (int) charC + " " + (int) charZ + " " + (int) charX + " " + (int) char_a + " " + (int) char_b + " " + (int) char_c + " " + (int) char_y + " " +(int) char_u + " " + (int) charZero + " " +(int) charNine + " " +(int) charTwo + " " + (int) charDollar + " " + (int) charStar + " " +(int) charGreater + " " + (int) charPipe + " " + (int) charBackslash + " " + (int) charSpace + " " + (int) charTab;
System.out.println("result : " + result);
return result;
}
public static void main(String[] args) {
Lab2Integer.characters();
//className.methodName
}
}
|
/*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the BLK License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.blk.com
*/
package com.sandy.infrastructure.jdbc.support;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.sandy.infrastructure.jdbc.util.AbstractDataAccessUtils;
/**
* description
*
* @author Sandy
* @since 1.0.0 05th 12 2018
*/
public abstract class AbstractJdbcDaoSupport extends JdbcDaoSupport {
@Autowired(required = false)
protected DataSource dataSource;
@Override
protected void checkDaoConfig() {
setDataSource(dataSource);
super.checkDaoConfig();
}
/**
* Convert a name in camelCase to an underscored name in lower case. Any
* upper case letters are converted to lower case with a preceding underscore.
* @param name the string containing original name
* @return the converted name
*/
protected String underscoreName(String name) {
StringBuilder result = new StringBuilder();
if (name != null && name.length() > 0) {
result.append(name.substring(0, 1).toUpperCase());
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
if (s.equals(s.toUpperCase())) {
result.append("_");
result.append(s);
} else {
result.append(s.toUpperCase());
}
}
}
return result.toString();
}
public <T> List<T> queryForList(String sql, Class<T> elementType) {
return this.getJdbcTemplate().query(sql, new BeanPropertyRowMapper<T>(elementType));
}
public <T> List<T> queryForList(String sql, Object[] args, Class<T> elementType) {
return this.getJdbcTemplate().query(sql, args, new BeanPropertyRowMapper<T>(elementType));
}
public <T> List<T> queryForList(String sql, Class<T> elementType, Object... args) throws DataAccessException {
return this.getJdbcTemplate().query(sql, new BeanPropertyRowMapper<T>(elementType), args);
}
public <T> List<T> queryForList(String sql, StatementParameter param, Class<T> elementType) {
return this.getJdbcTemplate().query(sql, param.getArgs(), new BeanPropertyRowMapper<T>(elementType));
}
public <T> T queryForObject(String sql, Class<T> elementType) throws DataAccessException {
Object [] args = {};
return queryForObject(sql, args, elementType);
}
public <T> T queryForObject(String sql, Object[] args, Class<T> elementType) {
List<T> results = queryForList(sql, args, elementType);
return AbstractDataAccessUtils.requiredSingleResult(results);
}
public int queryForInt(String sql){
Number number = this.getJdbcTemplate().queryForObject(sql, Integer.class);
return (number != null ? number.intValue() : 0);
}
public int queryForInt(String sql, Object[] args) {
Number number = this.getJdbcTemplate().queryForObject(sql, args, Integer.class);
return null != number ? number.intValue() : 0;
}
public int queryForInt(String sql, StatementParameter param){
Number number = this.getJdbcTemplate().queryForObject(sql, param.getArgs(), Integer.class);
return (number != null ? number.intValue() : 0);
}
public long queryForLong(String sql, Object[] args) {
Number number = this.getJdbcTemplate().queryForObject(sql, args, Long.class);
return null != number ? number.longValue() : 0L;
}
public long queryForLong(String sql, StatementParameter param){
Number number = this.getJdbcTemplate().queryForObject(sql, param.getArgs(), Long.class);
return number != null ? number.longValue() : 0L;
}
protected Long executeAndReturnKey(StatementNamedParameter param) {
SimpleJdbcInsert insertActor = new SimpleJdbcInsert(this.getJdbcTemplate().getDataSource()).withTableName(param.getTable()).usingGeneratedKeyColumns(param.getKeyColumn());
Number newId = insertActor.executeAndReturnKey(param.getParameters());
return newId.longValue();
}
protected Long execute(StatementNamedParameter param) {
SimpleJdbcInsert insertActor = new SimpleJdbcInsert(this.getJdbcTemplate().getDataSource()).withTableName(param.getTable()).usingGeneratedKeyColumns(param.getKeyColumn());
Number newId = insertActor.execute(param.getParameters());
return newId.longValue();
}
protected int updateForRecord(String sql, StatementParameter param) {
return this.getJdbcTemplate().update(sql, param.getParameters());
}
public boolean updateForBoolean(String sql, StatementParameter param) {
return 0 < updateForRecord(sql, param);
}
}
|
package com.redstoner.remote_console.authentication.methods;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;
import java.util.UUID;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import com.redstoner.remote_console.protected_classes.Main;
/**
* This class represents the PasswordAuthentication to allow for username/password based authentication
*
* @author Pepich1851
*/
public class PasswordAuthentication extends AuthenticationMethod implements Serializable
{
private static final long serialVersionUID = -7251017035793213272L;
private byte[] hashedPassword;
private byte[] salt;
private boolean valid;
private PasswordAuthentication(UUID uuid)
{
super(uuid);
this.salt = uuid.toString().getBytes();
}
/**
* This method will try to change a user's password
*
* @param oldPassword the current password of the user
* @param newPassword the new password of the user
* @param newPasswordConfirmed a confirmation of the user's new password for security reasons
* @return -2 if an exception was thrown, -1 if the oldPassword is wrong, 0 if the new passwords don't match and 1 if the operation was successful
*/
public int changePassword(String oldPassword, String newPassword, String newPasswordConfirmed)
{
try
{
if (newPassword.equals(newPasswordConfirmed))
{
if (Arrays.toString(hash(oldPassword, salt)).equals(Arrays.toString(hashedPassword)))
{
hashedPassword = hash(newPassword, salt);
revalidate();
return 1;
}
else
return -1;
}
else
return 0;
}
catch (NoSuchAlgorithmException | InvalidKeySpecException e)
{
return -2;
}
}
/**
* This method will forcefully override a user's password.
*
* @param oldPassword the current password of the user
* @param newPassword the new password of the user
* @param newPasswordConfirmed a confirmation of the user's new password for security reasons
* @return -2 if an exception was thrown, 0 if the new passwords don't match and 1 if the operation was successful
*/
public int overridePassword(String newPassword, String newPasswordConfirmed)
{
try
{
if (newPassword.equals(newPasswordConfirmed))
{
hashedPassword = hash(newPassword, salt);
revalidate();
return 1;
}
else
return 0;
}
catch (NoSuchAlgorithmException | InvalidKeySpecException e)
{
return -2;
}
}
@Override
public boolean authenticate(String[] args)
{
if (args == null) return false;
if (args.length == 0)
return false;
else
{
try
{
if (Arrays.toString(hash(args[0], salt)).equals(Arrays.toString(hashedPassword)))
return true;
else
return false;
}
catch (NoSuchAlgorithmException | InvalidKeySpecException e)
{
e.printStackTrace();
return false;
}
}
}
@Override
public void save()
{
File saveFile = new File(Main.getDataLocation().getAbsolutePath(), uuid.toString() + "/password-auth.auth");
try
{
if (saveFile.exists()) saveFile.delete();
saveFile.createNewFile();
ObjectOutputStream saveStream = new ObjectOutputStream(new FileOutputStream(saveFile));
saveStream.writeObject(this);
saveStream.flush();
saveStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* Loads the password authentication of a player using their UUID.
*
* @param uuid the UUID of the user
* @return their password authentication
*/
public static PasswordAuthentication load(UUID uuid)
{
File saveFile = new File(Main.getDataLocation().getAbsolutePath(), uuid.toString() + "/password-auth.auth");
if (!saveFile.exists())
return new PasswordAuthentication(uuid);
else
{
try
{
ObjectInputStream loadStream = new ObjectInputStream(new FileInputStream(saveFile));
PasswordAuthentication returnAuth = (PasswordAuthentication) loadStream.readObject();
loadStream.close();
return returnAuth;
}
catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
return null;
}
}
}
public static byte[] hash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String algorithm = "PBKDF2WithHmacSHA512";
int derivedKeyLength = 512;
int iterations = 50000;
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
byte[] result = f.generateSecret(spec).getEncoded();
return result;
}
/**
* Invalidates the authentication method instantly and prevents it from being used
*/
public void invalidate()
{
valid = false;
save();
}
/**
* Revalidates the password
*/
private void revalidate()
{
valid = true;
save();
}
public boolean isValid()
{
return valid;
}
}
|
package boletin_6_1;
import java.util.Scanner;
public class Número {
private int num;
public Número(int num){
this.num = num;
}
public Número(){
Scanner sc = new Scanner(System.in);
}
public int getNum(){
return num;
}
public void setNum(int num){
this.num = num;
}
public void positivo(int num){
if (num >= 0)
System.out.println("Es positivo");
else if (num < 0)
System.out.println("Es negativo");
}
public void pedirInt(){
Scanner sc = new Scanner (System.in);
System.out.println("Introduce un número: ");
setNum(sc.nextInt());
}
}
|
package com.example.hemil.papa_johns;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.hemil.papa_johns.AbstractFactory.AbstractFactory;
import com.example.hemil.papa_johns.AbstractFactory.BarqRootBeer_Drinks;
import com.example.hemil.papa_johns.AbstractFactory.Breadsticks_Sides;
import com.example.hemil.papa_johns.AbstractFactory.Brownie;
import com.example.hemil.papa_johns.AbstractFactory.BuffaloChicken_Sandwich;
import com.example.hemil.papa_johns.AbstractFactory.Cake;
import com.example.hemil.papa_johns.AbstractFactory.ChickenHabanero_Sandwich;
import com.example.hemil.papa_johns.AbstractFactory.Coke_Drinks;
import com.example.hemil.papa_johns.AbstractFactory.DasaniWater_Drinks;
import com.example.hemil.papa_johns.AbstractFactory.Desserts;
import com.example.hemil.papa_johns.AbstractFactory.DietCoke_Drinks;
import com.example.hemil.papa_johns.AbstractFactory.Drinks;
import com.example.hemil.papa_johns.AbstractFactory.FactoryProducer;
import com.example.hemil.papa_johns.AbstractFactory.Fanta_Drinks;
import com.example.hemil.papa_johns.AbstractFactory.ItalianSP_Sandwich;
import com.example.hemil.papa_johns.AbstractFactory.MediterraneanVeggie_Sandwich;
import com.example.hemil.papa_johns.AbstractFactory.ParmesanBreadBites_Sides;
import com.example.hemil.papa_johns.AbstractFactory.Pasta;
import com.example.hemil.papa_johns.AbstractFactory.PhillyCheeseSteak_Sandwich;
import com.example.hemil.papa_johns.AbstractFactory.Pizza;
import com.example.hemil.papa_johns.AbstractFactory.RedSauce_Pasta;
import com.example.hemil.papa_johns.AbstractFactory.SCBwithSpinach_Sides;
import com.example.hemil.papa_johns.AbstractFactory.STBwithBacon_Sides;
import com.example.hemil.papa_johns.AbstractFactory.Sandwiches;
import com.example.hemil.papa_johns.AbstractFactory.Sides;
import com.example.hemil.papa_johns.AbstractFactory.Sprite_Drinks;
import com.example.hemil.papa_johns.AbstractFactory.Stix;
import com.example.hemil.papa_johns.AbstractFactory.StuffedCheesyBread_Sides;
import com.example.hemil.papa_johns.AbstractFactory.WhiteSauce_Pasta;
import com.example.hemil.papa_johns.Memento.Ocaretaker;
import com.example.hemil.papa_johns.Memento.Omemento;
import com.example.hemil.papa_johns.Memento.Ooriginator;
import com.example.hemil.papa_johns.POJO.Order;
import com.example.hemil.papa_johns.Utility.ItemListAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hemil on 11/28/2015.
*/
public class PizzaScreenOne extends AppCompatActivity {
TextView quantityText;
AbstractFactory af;
RadioGroup radioGroup, radioGroup2;
TextView text;
int itemPosition;
Order order;
Ooriginator originator = new Ooriginator();
Ocaretaker ocareTaker = new Ocaretaker();
List<Omemento> list = ocareTaker.getList();
@Override
protected void onCreate(Bundle savedInstanceState) {
itemPosition = getIntent().getExtras().getInt("MenuItem");
Toast.makeText(PizzaScreenOne.this, "Menu Item : "+itemPosition, Toast.LENGTH_SHORT).show();
super.onCreate(savedInstanceState);
setContentView(R.layout.pizza_screen_one);
radioGroup = (RadioGroup) findViewById(R.id.sizeRadioGroup);
radioGroup2 = (RadioGroup) findViewById(R.id.pastaRadioGroup);
text = (TextView) findViewById(R.id.selected_Pizza_Name);
switch(itemPosition){
case 0 :
text.setText(getIntent().getExtras().getString("PizzaName"));
break;
case 2 : text.setText(getIntent().getExtras().getString("PizzaName"));
radioGroup.setVisibility(View.GONE);
radioGroup2.setVisibility(View.VISIBLE);
break;
case 1 :
case 3 :
case 4 :
case 5 : TextView set = (TextView) findViewById(R.id.select_sizeText);
set.setVisibility(View.GONE);
text.setText(getIntent().getExtras().getString("PizzaName"));
radioGroup.setVisibility(View.GONE);
radioGroup2.setVisibility(View.GONE);
break;
}
quantityText = (TextView) findViewById(R.id.quantityText);
quantityText.setText("0");
}
public void decQuantity(View view){
int value = Integer.parseInt(quantityText.getText().toString());
if(value>0){
value = value -1;
quantityText.setText(""+value);
// Toast.makeText(PizzaScreenOne.this, ""+value, Toast.LENGTH_SHORT).show();
}
}
public void incQuantity(View view){
Integer value = Integer.parseInt(quantityText.getText().toString());
value = value +1;
quantityText.setText(""+value);
// Toast.makeText(PizzaScreenOne.this, ""+value, Toast.LENGTH_SHORT).show();
}
public void ContinueOrderMethod(View view){
switch (itemPosition){
case 0 : pizzaEvent(); break;
case 2 : pastaEvent(); break;
case 1 : sandwichEvent(); break;
case 3 : drinksEvent(); break;
case 4 : dessertsEvent(); break;
case 5 : sidesEvent(); break;
}
}
public void pizzaEvent(){
int value = Integer.parseInt(quantityText.getText().toString());
int id = -1;
if(!( radioGroup.getCheckedRadioButtonId() == -1)){
if(((RadioButton) findViewById(R.id.small)).isChecked()){
id =1;
}
if(((RadioButton) findViewById(R.id.medium)).isChecked()){
id =2;
}
if(((RadioButton) findViewById(R.id.large)).isChecked()){
id =3;
}
}
if(value<=0 || id<0)
{
Toast.makeText(PizzaScreenOne.this, ""+"Please select size and quantity ", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(PizzaScreenOne.this, "Size :"+id+" Quantity : "+value, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),PizzaScreenTwo.class);
intent.putExtra("PizzaName", getIntent().getExtras().getString("PizzaName"));
intent.putExtra("PizzaSize", id);
intent.putExtra("PizzaQuantity", value);
switch (getIntent().getExtras().getInt("Position")) {
case 0 :
/* af = FactoryProducer.getFactory("Pizza");
Pizza p1 = af.getPizza("Spinach Pizza", id, value);
Toast.makeText(PizzaScreenOne.this, ""+p1.getCost() , Toast.LENGTH_SHORT).show(); */
intent.putExtra("getPizza","Spinach Pizza");
break;
case 1 :
/* af = FactoryProducer.getFactory("Pizza");
Pizza p2 = af.getPizza("Winsconsin 6 Cheeze Pizza", id, value);
Toast.makeText(PizzaScreenOne.this, ""+p2.getCost() , Toast.LENGTH_SHORT).show(); */
intent.putExtra("getPizza","Winsconsin 6 Cheeze Pizza");
break;
case 2 :
/* af = FactoryProducer.getFactory("Pizza");
Pizza p3 = af.getPizza("Pacific Veggie Pizza", id, value);
Toast.makeText(PizzaScreenOne.this, ""+p3.getCost() , Toast.LENGTH_SHORT).show(); */
intent.putExtra("getPizza","Pacific Veggie Pizza");
break;
case 3 :
/* af = FactoryProducer.getFactory("Pizza");
Pizza p4 = af.getPizza("Memphis BBQ Chicken Pizza", id, value);
Toast.makeText(PizzaScreenOne.this, ""+p4.getCost() , Toast.LENGTH_SHORT).show(); */
intent.putExtra("getPizza","Memphis BBQ Chicken Pizza");
break;
case 4 :
/* af = FactoryProducer.getFactory("Pizza");
Pizza p5 = af.getPizza("Ultimate Pepperoni Feast Pizza", id, value);
Toast.makeText(PizzaScreenOne.this, ""+p5.getCost() , Toast.LENGTH_SHORT).show(); */
intent.putExtra("getPizza","Ultimate Pepperoni Feast Pizza");
break;
}
startActivity(intent);
this.finish();
}
}
public void pastaEvent() {
int value = Integer.parseInt(quantityText.getText().toString());
int id = -1;
if (!(radioGroup2.getCheckedRadioButtonId() == -1)) {
if (((RadioButton) findViewById(R.id.whiteSauce)).isChecked()) {
id = 1;
}
if (((RadioButton) findViewById(R.id.redSauce)).isChecked()) {
id = 2;
}
}
if (value <= 0 || id < 0) {
Toast.makeText(PizzaScreenOne.this, "" + " select size and quantity ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(PizzaScreenOne.this, "Sauce :" + id + " Quantity : " + value, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), PlaceOrder.class);
AbstractFactory af2 = FactoryProducer.getFactory("Pasta");
Pasta p2 = af2.getPasta(getIntent().getExtras().getString("PizzaName"), value);
Pasta temp = p2;
switch (id){
case 1 : temp = new WhiteSauce_Pasta(temp); break;
case 2 : temp = new RedSauce_Pasta(temp); break;
}
Toast.makeText(PizzaScreenOne.this, ""+temp.getName()+" "+temp.getCost(), Toast.LENGTH_SHORT).show();
order = new Order(temp.getName(),temp.getCost());
originator.setState(order);
ocareTaker.add(originator.saveStateToMemento());
for(int i =0;i<list.size();i++){
Log.d("Order", list.get(i).getState().getOrderName());
}
startActivity(intent);
this.finish();
}
}
public void sandwichEvent(){
int value = Integer.parseInt(quantityText.getText().toString());
if (value <= 0 ) {
Toast.makeText(PizzaScreenOne.this, "" + " select quantity ", Toast.LENGTH_SHORT).show();
} else {
Sandwiches sand = null;
switch (getIntent().getExtras().getInt("Position")){
case 0 : sand = new ItalianSP_Sandwich(); break;
case 1 : sand = new BuffaloChicken_Sandwich(); break;
case 2 : sand = new ChickenHabanero_Sandwich(); break;
case 3 : sand = new MediterraneanVeggie_Sandwich(); break;
case 4 : sand = new PhillyCheeseSteak_Sandwich(); break;
}
order = new Order(sand.getName(),sand.getCost(value));
originator.setState(order);
ocareTaker.add(originator.saveStateToMemento());
for(int i =0;i<list.size();i++){
Log.d("Order", list.get(i).getState().getOrderName());
}
Intent intent = new Intent(getApplicationContext(), PlaceOrder.class);
startActivity(intent);
}
}
public void drinksEvent(){
int value = Integer.parseInt(quantityText.getText().toString());
if (value <= 0 ) {
Toast.makeText(PizzaScreenOne.this, "" + " select quantity ", Toast.LENGTH_SHORT).show();
} else {
Drinks drink = null;
switch (getIntent().getExtras().getInt("Position")){
case 0 : drink = new Coke_Drinks(); break;
case 1 : drink = new DietCoke_Drinks(); break;
case 2 : drink = new Sprite_Drinks(); break;
case 3 : drink = new DasaniWater_Drinks(); break;
case 4 : drink = new BarqRootBeer_Drinks(); break;
case 5 : drink = new Fanta_Drinks(); break;
}
order = new Order(drink.getName(),drink.getCost(value));
originator.setState(order);
ocareTaker.add(originator.saveStateToMemento());
for(int i =0;i<list.size();i++){
Log.d("Order", list.get(i).getState().getOrderName());
}
Intent intent = new Intent(getApplicationContext(), PlaceOrder.class);
startActivity(intent);
}
}
public void dessertsEvent(){
int value = Integer.parseInt(quantityText.getText().toString());
if (value <= 0 ) {
Toast.makeText(PizzaScreenOne.this, "" + " select quantity ", Toast.LENGTH_SHORT).show();
} else {
Desserts dessert = null;
switch (getIntent().getExtras().getInt("Position")){
case 0 :
case 1 : dessert = new Brownie(); break;
case 2 : dessert = new Stix(); break;
case 3 : dessert = new Cake(); break;
}
order = new Order(dessert.getName(),dessert.getCost(value));
originator.setState(order);
ocareTaker.add(originator.saveStateToMemento());
for(int i =0;i<list.size();i++){
Log.d("Order", list.get(i).getState().getOrderName());
}
Intent intent = new Intent(getApplicationContext(), PlaceOrder.class);
startActivity(intent);
}
}
public void sidesEvent(){
int value = Integer.parseInt(quantityText.getText().toString());
if (value <= 0 ) {
Toast.makeText(PizzaScreenOne.this, "" + " select quantity ", Toast.LENGTH_SHORT).show();
} else {
Sides side = null;
switch (getIntent().getExtras().getInt("Position")){
case 0 : side = new StuffedCheesyBread_Sides(); break;
case 1 : side = new SCBwithSpinach_Sides(); break;
case 2 : side = new STBwithBacon_Sides(); break;
case 3 : side = new ParmesanBreadBites_Sides(); break;
case 4 : side = new Breadsticks_Sides(); break;
}
order = new Order(side.getName(),side.getCost(value));
originator.setState(order);
ocareTaker.add(originator.saveStateToMemento());
for(int i =0;i<list.size();i++){
Log.d("Order", list.get(i).getState().getOrderName());
}
Intent intent = new Intent(getApplicationContext(), PlaceOrder.class);
startActivity(intent);
}
}
}
|
package org.usfirst.frc.team5114.MyRobot2016.auton.commands;
import org.usfirst.frc.team5114.MyRobot2016.Robot;
import org.usfirst.frc.team5114.MyRobot2016.commands.RunLauncher;
import org.usfirst.frc.team5114.MyRobot2016.subsystems.BallLaunch;
import org.usfirst.frc.team5114.MyRobot2016.subsystems.DriveTrain;
public class HalfDriveAutonCmd extends AutonCmd {
public DriveTrain.Side side;
public HalfDriveAutonCmd(double percentVolt, double seconds, DriveTrain.Side half)
{
super(percentVolt, seconds, "Half Drive");
side = half;
requires(Robot.driveTrain);
}
// Called just before this Command runs the first time
protected void initialize() {
super.initialize();
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.driveTrain.halfDrive(side, power);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return super.isFinished();
}
// Called once after isFinished returns true
protected void end() {
super.end();
Robot.driveTrain.stop();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
super.interrupted();
Robot.driveTrain.stop();
}
}
|
package com.jihu.shiro.demo.configrution;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
@Configuration
public class ShiroConfigration {
}
|
package im.compIII.exghdecore.entidades;
import java.sql.SQLException;
import java.util.Collection;
import im.compIII.exghdecore.banco.MobiliaDB;
import im.compIII.exghdecore.exceptions.CampoVazioException;
import im.compIII.exghdecore.exceptions.ConexaoException;
import im.compIII.exghdecore.exceptions.RelacaoException;
public class Mobilia {
private long id;
private String descricao;
private double custo;
private int tempoEntrega;
private Collection<Comodo> comodos;
public Mobilia(long id, String descricao, double custo, int tempoEntrega) throws CampoVazioException {
this.descricao = descricao;
this.custo = custo;
this.tempoEntrega = tempoEntrega;
this.id = id;
if (descricao.equals(""))
throw new CampoVazioException("descrição");
if (this.custo == 0 || this.custo < 0)
throw new CampoVazioException("custo");
if (this.tempoEntrega == 0 || this.tempoEntrega < 0)
throw new CampoVazioException("tempo de entrega");
}
public Mobilia(String descricao, double custo, int tempoEntrega) throws CampoVazioException {
this.descricao = descricao;
this.custo = custo;
this.tempoEntrega = tempoEntrega;
if (descricao.equals(""))
throw new CampoVazioException("descrição");
if (this.custo == 0 || this.custo < 0)
throw new CampoVazioException("custo");
if (this.tempoEntrega == 0 || this.tempoEntrega < 0)
throw new CampoVazioException("tempo de entrega");
}
public static final Mobilia buscar(long id) throws ClassNotFoundException, ConexaoException, SQLException {
return MobiliaDB.buscar(id);
}
public static final Collection<Mobilia> buscarTodos() throws ClassNotFoundException, ConexaoException, SQLException {
return MobiliaDB.listarTodos();
}
public void adicionar() throws NumberFormatException, ClassNotFoundException, ConexaoException, SQLException, CampoVazioException, RelacaoException{
MobiliaDB db = new MobiliaDB();
db.salvar(this);
}
public void atualizar() throws ClassNotFoundException, ConexaoException, SQLException {
MobiliaDB db = new MobiliaDB();
db.atualizar(this);
}
public String getDescricao() {
return descricao;
}
public long getId() {
return id;
}
public double getCusto() {
return custo;
}
public int getTempoEntrega() {
return tempoEntrega;
}
public Collection<Comodo> getComodos() {
return comodos;
}
public void setComodos(Collection<Comodo> comodos) {
this.comodos = comodos;
}
}
|
package com.example.demo.entity;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
@Entity
@Table(name = "Fe2n_Match")
public class Match {
@Id
@SequenceGenerator(name = "pk_sequence", sequenceName = "Fe2n_Match_id_seq",allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_sequence")
private Integer match_id;
@Column(name = "status",length = 50,nullable = false)
private String status;
@Column(name = "start_date", nullable = false)
private Date start_date;
@Column(name = "end_date", nullable = false)
private Date end_date;
public Integer getId() {
return match_id;
}
public void setId(Integer id) {
this.match_id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStart_date() {
return start_date;
}
public void setStart_date(Date start_date) {
this.start_date = start_date;
}
public Date getEnd_date() {
return end_date;
}
public void setEnd_date(Date end_date) {
this.end_date = end_date;
}
}
|
package OhPe2021;
// Ohjelman nimi on Ekaohjelma
public class Ekaohjelma {
// ohjelman päälohko
public static void main(String[] args) {
System.out.println("Hoi Maailma!");
}
}
|
package wifi;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import rf.RF;
/**
* Use this layer as a starting point for your project code. See
* {@link Dot11Interface} for more details on these routines.
*
* @author
*/
public class LinkLayer implements Dot11Interface {
private RF theRF; // Simulates a physical layer for us to send on
private short ourMAC; // The address we are using
private PrintWriter output; // The output stream we'll write to
private int currentStatus;
public static final int SUCCESS = 1;
public static final int UNSPECIFIED_ERROR = 2;
public static final int RF_INIT_FAILED = 3;
public static final int TX_DELIVERED = 4;
public static final int TX_FAILED = 5;
public static final int BAD_BUF_SIZE = 6;
public static final int BAD_ADDRESS = 7;
public static final int BAD_MAC_ADDRESS = 8;
public static final int ILLEGAL_ARGUMENT = 9;
public static final int INSUFFICIENT_BUFFER_SPACE = 10;
public static final int DEFAULT_WAIT = 1;
public static final int WAIT_ACK = 2;
public static final int BUSY_WAIT = 3;
public static final int SLOT_WAIT = 4;
public static final int IDLE_WAIT = 5;
private int macState;
private int ourSlot = 0;
private boolean needNextPacket = true;
private Packet macPacket;
private long localOffset;
long waited;
public static final int SIFS = RF.aSIFSTime;
public static final int SLOT = RF.aSlotTime;
public static final int DIFS = RF.aSIFSTime + (2*RF.aSlotTime);
private int cWindow = RF.aCWmin;
private static final int QUEUE_SIZE = 4;
private static final int FULL_DEBUG = -1;
private int debug = 0;
private boolean randomSlots = true;
private int beaconDelay = -1;
private long lastBeacon = 0;
private static final long PROCESS_DELAY = 450;
private int beaconOffset = 1900; //After running tests
int retryCounter = 0;
private BlockingQueue<Packet> in = new ArrayBlockingQueue(QUEUE_SIZE);
private BlockingQueue<Packet> out = new ArrayBlockingQueue(QUEUE_SIZE);
private HashMap<Short, Short> sendSequences = new HashMap();
private HashMap<Short, Short> recvSequences = new HashMap();
private HashMap<Short, ArrayList<Short>> recievedACKS = new HashMap();
public synchronized BlockingQueue<Packet> getIn() { // These Queues will facilitate communication between the LinkLayer and its
// Sender and Receiver helper classes.
return in;
}
public synchronized BlockingQueue<Packet> getOut() {
return out;
}
/**
* Constructor takes a MAC address and the PrintWriter to which our output
* will be written.
*
* @param ourMAC
* MAC address
* @param output
* Output stream associated with GUI
*/
public LinkLayer(short ourMAC, PrintWriter output) {
this.ourMAC = ourMAC;
this.output = output;
theRF = new RF(null, null);
macState = DEFAULT_WAIT;
if(theRF == null){
currentStatus = RF_INIT_FAILED;
}
output.println("LinkLayer initialized with MAC address of " + ourMAC);
output.println("Send command 0 to see a list of supported commands");
Receiver theReceiver = new Receiver(this, theRF); // Creates the sender and receiver instances
Sender theSender = new Sender(this, theRF);
Thread r = new Thread(theReceiver); // Threads them
Thread s = new Thread(theSender);
r.start(); // Starts the threads running
s.start();
}
/**
* Increments next sequence number for a given address
*/
private short nextSeqNum(short addr) {
short nextSeq;
if (sendSequences.containsKey(addr)) {
nextSeq = (short) (sendSequences.get(addr) + 1);
} else {
nextSeq = 0;
}
this.sendSequences.put(addr, (short) (nextSeq));
return nextSeq;
}
/**
* Checks given address for received sequences
*/
private short gotRecvSeqNum(short addr) {
short nextSeq;
if (recvSequences.containsKey(addr)) {
nextSeq = (short) (recvSequences.get(addr) + 1);
} else {
nextSeq = 0;
}
this.recvSequences.put(addr, (short) (nextSeq));
return nextSeq;
}
/**
* Send method takes a destination, a buffer (array) of data, and the number
* of bytes to send. See docs for full description.
*/
public int send(short dest, byte[] data, int len) {
if(data.length < len){
currentStatus = ILLEGAL_ARGUMENT;
}
short seqNum = nextSeqNum(dest);
Packet p = new Packet(0, seqNum, dest, ourMAC, data); // Builds a packet using the supplied data
if (out.size() < QUEUE_SIZE) {
if (debug == FULL_DEBUG) {
output.println("Queueing " + p.getData().length + " bytes for " + dest);
}
try {
out.put(p); // Puts the created packet into the outgoing queue
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
currentStatus = SUCCESS;
return len;
} else {
currentStatus = INSUFFICIENT_BUFFER_SPACE;
return 0;
}
}
/**
* Recv method blocks until data arrives, then writes it an address info
* into the Transmission object. See docs for full description.
*/
public int recv(Transmission t) { // Called by the above layer when it wants to receive data
Packet p;
if(t == null){
currentStatus = ILLEGAL_ARGUMENT;
}
try {
p = in.take(); // Grabs the next packet from the incoming queue
if (p.getSeqNum() < recvSequences.get(p.getSrcAddr())) {
output.println("Already got this");
} else {
byte[] data = p.getData(); // Extracts the necessary parts from the packet and puts them into the supplied transmission object
t.setSourceAddr((short) p.getSrcAddr());
t.setDestAddr((short) p.getDestAddr());
t.setBuf(data);
currentStatus = SUCCESS;
return data.length; // Returns the length of the data recieved
}
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
return -1;
}
/**
* Returns a current status code. See docs for full description.
*/
public int status() {
return currentStatus;
}
/**
* Passes command info to your link layer. See docs for full description.
*/
public int command(int cmd, int val) {
switch (cmd) {
case 0:
output.println("Options & Settings:");
output.println("-----------------------------------------");
output.println("Cmd 0: \t View all options and settings.");
output.println("Cmd 1: \t Set debug value. Debug currently at "
+ debug);
output.println("\t Use -1 for full debug output, 0 for no output.");
output.println("Cmd 2: \t Set slot for link layer. 0 for random slot time, else, max slot time.");
output.println("Cmd 3: \t Set desired wait time between start of beacon transmissions (in seconds).");
output.println("-----------------------------------------");
break;
case 1:
currentStatus = SUCCESS;
if (val == FULL_DEBUG) {
debug = FULL_DEBUG;
}
if(val == 0){
debug = 0;
}
output.println("Setting debug to " + debug);
break;
case 2:
currentStatus = SUCCESS;
if (val == 0) {
output.println("Using random slot times");
randomSlots = true;
} else {
output.println("Using maximum slot times");
randomSlots = false;
}
break;
case 3:
currentStatus = SUCCESS;
if (val < 0) {
beaconDelay = -1;
output.println("Disabling beacons");
} else {
output.println("Using a beacon delay of " + val + " seconds");
beaconDelay = val*1000; //Convert to milliseconds
}
break;
default: //Unknown command
currentStatus = ILLEGAL_ARGUMENT;
output.println("Command " + cmd + " not recognized.");
}
return 0;
}
/**
* Returns time including current clock offset
*/
private long getTime(){
return theRF.clock()+localOffset;
}
/**
* Rounds a value up to the nearest 50.
* @param input
* @return
*/
private long roundUp(long input){
if (Math.ceil(input % 50L / 50.0D) == 1.0D) //If already multiple of 50
{
return input + (50L - input % 50L);
}else{
return input;
}
}
/**
* Waits until the given time according to the current local clock (with offset)
* @param time
* @return
*/
private long waitUntil(long time){
long cTime = getTime();
while(cTime < time){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
cTime+=10;
}
return time;
}
/**
* Aligns to wait time with rounding slots of 50.
* @param waitTime
* @return
*/
private long nearestWait(long waitTime){
return roundUp(getTime() + waitTime);
}
/**
* Thread that handles all sending function of the LinkLayer
* @author aking & mlim
*
*/
class Sender implements Runnable {
private RF theRF;
private LinkLayer theLinkLayer;
public Sender(LinkLayer thisLink, RF thisRF) {
theRF = thisRF;
if(theRF == null){
currentStatus = RF_INIT_FAILED;
}
if(thisLink == null){
currentStatus = ILLEGAL_ARGUMENT;
}
theLinkLayer = thisLink;
}
public void run() {
while (true) {
switch(macState){
case DEFAULT_WAIT: //1
long cTime = getTime();
macPacket = null;
if(lastBeacon + beaconDelay <= cTime && beaconDelay > 0){ //Time to send a Beacon
lastBeacon = cTime;
ByteBuffer buf = ByteBuffer.allocate(8);
buf.putLong(getTime() + beaconOffset);
byte[] timeStamp = buf.array();
Packet beacon = new Packet(2, (short) 0, (short)-1, ourMAC, timeStamp );
macPacket = beacon;
if(!theRF.inUse() ){
if(debug == FULL_DEBUG){
output.println("Moving to IDLE_WAIT.");
}
macState = IDLE_WAIT;
}else{
if(debug == FULL_DEBUG){
output.println("Moving to BUSY_WAIT.");
}
macState = BUSY_WAIT;
}
}
else{ //send something other than BEACON
if (!theLinkLayer.getOut().isEmpty() && needNextPacket){ //Something to send
try {
macPacket = theLinkLayer.getOut().take();
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
needNextPacket = false;
}
if(macPacket != null){ //Leave DEFAULT_WAIT
if(!theRF.inUse() ){
if(debug == FULL_DEBUG){
output.println("Moving to IDLE_WAIT.");
}
macState = IDLE_WAIT;
}else{
if(debug == FULL_DEBUG){
output.println("Moving to BUSY_WAIT.");
}
macState = BUSY_WAIT;
}
}
}
break;
case WAIT_ACK: //2
try {
Thread.sleep((long) (2615+SIFS+SLOT)); //Average ACK transmission + SIFS + SLOT (IEEE Spec.)
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
if((!theLinkLayer.recievedACKS.containsKey(macPacket.getDestAddr()) //No ACK received
|| !theLinkLayer.recievedACKS.get(macPacket.getDestAddr()).contains(macPacket.getSeqNum()))) {
retryCounter++;
if(retryCounter == 1){
cWindow = RF.aCWmin;
}else if(cWindow < RF.aCWmax){ //Backoff until maximum window
cWindow = cWindow * 2;
if(cWindow > RF.aCWmax){
cWindow = RF.aCWmax;
}
}else{
cWindow = RF.aCWmax;
}
if(debug == FULL_DEBUG){
output.println("Setting collision window to [0..." + cWindow + "]" );
}
if(retryCounter < RF.dot11RetryLimit){ //Resend ACK packet
if(randomSlots){
Random rand = new Random();
ourSlot = rand.nextInt(cWindow);
}else{
ourSlot = cWindow;
}
if(debug == FULL_DEBUG){
output.println("Moving to BUSY_WAIT");
}
macState = BUSY_WAIT;
macPacket.setRetry(true);
}else{ //Retry limit exhausted. Move to DEFAULT_WAIT.
retryCounter = 0;
needNextPacket = true;
currentStatus = TX_FAILED;
if(debug == FULL_DEBUG){
output.println("Moving to DEFAULT_WAIT after exhausting retry limit.");
}
macState = DEFAULT_WAIT;
}
}else{ //ACK received
retryCounter = 0;
needNextPacket = true;
if(debug == FULL_DEBUG){
output.println("Moving to DEFAULT_WAIT.");
}
macState = DEFAULT_WAIT;
}
currentStatus = TX_DELIVERED;
break;
case BUSY_WAIT: //3
if(debug == FULL_DEBUG){
output.println("Waiting for DIFS to elapse after current Tx...");
}
waited = waitUntil(nearestWait(DIFS)); //Wait DIFS + nearest roundUp
if(debug == FULL_DEBUG){
output.println("DIFS wait is over at " + waited + ", starting slot countdown (" + ourSlot + ")");
}
if(debug == FULL_DEBUG){
output.println("Moving to SLOT_WAIT.");
}
macState = SLOT_WAIT;
break;
case SLOT_WAIT: //4
//Look at current time, align to slots. while our slot is not the current slot, loop through and wait a slot time each time.
//Reduce our slot by 1 each time, until our slot is the current slot.
if(macPacket.getFrameType() == 0){
waitUntil(roundUp(getTime()));
//Wait for our slot
waited = waitUntil(getTime() + (ourSlot *SLOT));
if(debug == FULL_DEBUG){
output.println("Slot waited until " + waited);
}
if(theRF.inUse()){ //RF still busy
if(debug == FULL_DEBUG){
output.println("RF is in use");
output.println("Moving to BUSY_WAIT");
}
macState = BUSY_WAIT;
}else{
if(macPacket.getFrameType() == 2){ //BEACON
if(debug == FULL_DEBUG){
ByteBuffer buf = ByteBuffer.allocate(8);
buf = ByteBuffer.wrap(macPacket.getData());
long timeStamp = buf.getLong();
output.println("Sending BEACON at: "+ getTime()+ " built at " + timeStamp);
}
}
theRF.transmit(macPacket.getFrame());
if (debug == FULL_DEBUG) {
output.println("Transmitting packet after waiting DIFS + SLOT(s) wait at " + getTime());
}
if(macPacket.getDestAddr() == -1){
// Broadcast packet. Don't need to look for an ACK
if(debug == FULL_DEBUG){
output.println("Moving to DEFAULT_WAIT.");
}
needNextPacket = true;
macState = DEFAULT_WAIT;
}
else{
if(debug == FULL_DEBUG){
output.println("Moving to WAIT_ACK.");
}
macState = WAIT_ACK;
}
}
}
break;
case IDLE_WAIT: //5
waited = waitUntil(nearestWait(DIFS));
theRF.transmit(macPacket.getFrame());
if(debug == FULL_DEBUG){
output.println("Transmitting packet after IDLE DIFS wait at " + waited);
}
if(debug == FULL_DEBUG && macPacket.getFrameType() == 2){ //BEACON
ByteBuffer buf = ByteBuffer.allocate(8);
buf = ByteBuffer.wrap(macPacket.getData());
long timeStamp = buf.getLong();
output.println("Sending BEACON at: "+ getTime()+ ", built at " + timeStamp);
}
if(macPacket.getDestAddr() == -1){ //Broadcast
needNextPacket = true;
if(debug == FULL_DEBUG){
output.println("Moving to DEFAULT_WAIT.");
}
macState = DEFAULT_WAIT;
}else{ //Regular wait for ACK
if(debug == FULL_DEBUG){
output.println("Moving to WAIT_ACK.");
}
macState = WAIT_ACK;
}
break;
default:
currentStatus = UNSPECIFIED_ERROR;
}
}
}
}
/**
* Thread that handles all receiving function of the LinkLayer
* @author aking & mlim
*
*/
class Receiver implements Runnable {
private RF theRF;
private LinkLayer theLinkLayer;
public Receiver(LinkLayer thisLink, RF thisRF) {
theRF = thisRF;
if(theRF == null){
currentStatus = RF_INIT_FAILED;
}
if(thisLink == null){
currentStatus = ILLEGAL_ARGUMENT;
}
theLinkLayer = thisLink;
}
public void run() {
while (true) {
try {
Thread.sleep(10); // Sleeps each time through, in order to not monopolize the CPU
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
Packet recvPacket = new Packet(theRF.receive()); // Gets data from the RF layer, turns it into packet form
if(debug == FULL_DEBUG && recvPacket.getFrameType() != 1){
output.println("Tx starting from " + recvPacket.getSrcAddr() + " at local time " + getTime() );
}
short destAddr = recvPacket.getDestAddr();
if(recvPacket.isGoodCRC()){ //Good CRC
if(debug == FULL_DEBUG){
output.println("\tReceived packet with good CRC: " + recvPacket.toString());
}
if ((destAddr & 0xffff) == ourMAC || (destAddr & 0xffff) == 65535) { //Packet for us or Broadcast
if ((destAddr & 0xffff) == ourMAC //Data Packet for Us & Have space in queue
&& recvPacket.getFrameType() == 0
&& theLinkLayer.getIn().size() < QUEUE_SIZE) {
short nextSeq = gotRecvSeqNum(recvPacket.getSrcAddr());
if (recvPacket.getSeqNum() > nextSeq) { //Sequence out of order
output.println("Sequence out of order. Expected: "
+ nextSeq + ". Received: "
+ recvPacket.getSeqNum() + ".");
}
try {
theLinkLayer.getIn().put(recvPacket); // Puts them new Packet into the LinkLayer's inbound queue
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
Packet ack = new Packet(1, recvPacket.getSeqNum(), //Build ACK
recvPacket.getSrcAddr(), ourMAC, null);
try {
Thread.sleep(RF.aSIFSTime); // Sleeps to wait SIFS
} catch (InterruptedException e) {
e.printStackTrace();
}
if (debug == FULL_DEBUG) {
output.println("Sending ACK with sequence number "
+ ack.getSeqNum() + " to MAC address "
+ ack.getDestAddr());
}
theRF.transmit(ack.getFrame()); //Transmit ACK
}
else if ((destAddr & 0xffff) == ourMAC && recvPacket.getFrameType() == 1) { //Receive ACK for us
output.println("Got a valid ACK: " + recvPacket.toString());
if (theLinkLayer.recievedACKS.containsKey(recvPacket.getSrcAddr())) {
if (theLinkLayer.recievedACKS.get(recvPacket.getSrcAddr()).contains(recvPacket.getSeqNum())) {
output.println("Received duplicate ACK for sequence number "+ recvPacket.getSeqNum() + " from " + recvPacket.getSrcAddr());
} else {
theLinkLayer.recievedACKS.get(recvPacket.getSrcAddr()).add(recvPacket.getSeqNum());
}
} else {
ArrayList<Short> newHost = new ArrayList<Short>();
newHost.add(recvPacket.getSeqNum());
theLinkLayer.recievedACKS.put(
recvPacket.getSrcAddr(), newHost);
}
}
else if(recvPacket.getFrameType() == 2){ //Receive BEACON
byte[] payload = recvPacket.getData();
ByteBuffer buf = ByteBuffer.allocate(8);
buf = ByteBuffer.wrap(payload);
long timeStamp = buf.getLong();
long localTime = getTime();
if(timeStamp > localTime){
localOffset = timeStamp - (localTime + PROCESS_DELAY);
if(debug == FULL_DEBUG){
output.println("Adjusted our clock by "+ localOffset+ " due to beacon: \n \t incoming offset was "+timeStamp+
" vs. our "+ localTime + ". Time is now: "+ getTime());
}
}
else{
if(debug == FULL_DEBUG){
output.println("Ignored beacon, incoming time was "+timeStamp+
" vs. our "+ localTime + ". Time is now: "+ getTime());
}
}
}else if((destAddr & 0xffff) == 65535){ //Broadcast
short nextSeq = gotRecvSeqNum(recvPacket.getSrcAddr());
if (recvPacket.getSeqNum() > nextSeq) {
output.println("Broadcast packet had wrong sequence number. Expected: "
+ nextSeq + ". Received: "
+ recvPacket.getSeqNum() + ".");
}
try {
theLinkLayer.getIn().put(recvPacket); // Puts them new Packet into the LinkLayer's inbound queue
} catch (InterruptedException e) {
currentStatus = UNSPECIFIED_ERROR;
e.printStackTrace();
}
}
else{ //Frametype other than DATA, ACK, or BEACON
output.println("Unexpected frame type");
currentStatus = ILLEGAL_ARGUMENT;
}
}
}else{
if(debug == FULL_DEBUG){ //Bad CRC. Ignore.
output.println("\tIgnored packet with bad CRC: " + recvPacket.toString());
}
}
}
}
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.thumbs;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.resources.client.ImageResource.ImageOptions;
public interface ExampleThumbs extends ClientBundle {
public static ExampleThumbs THUMBS = GWT.create(ExampleThumbs.class);
@Source("Accordion-Layout.png")
@ImageOptions(width = 50, height = 50)
ImageResource accordionlayout();
@Source("Accordion-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource accordionlayoutuibinder();
@Source("Accordion-Window.png")
@ImageOptions(width = 50, height = 50)
ImageResource accordionwindow();
@Source("Advanced-Tabs.png") // FIXME: DSB: NEED ICON FOR ADVANCED BOTTOM TABS
@ImageOptions(width = 50, height = 50)
ImageResource advancedbottomtabs();
@Source("Advanced-Combo-Box.png")
@ImageOptions(width = 50, height = 50)
ImageResource advancedcombobox();
@Source("Advanced-Forms.png")
@ImageOptions(width = 50, height = 50)
ImageResource advancedforms();
@Source("Advanced-ListView.png")
@ImageOptions(width = 50, height = 50)
ImageResource advancedlistview();
@Source("Advanced-Tabs.png") // FIXME: DSB: ICON SHOULD SHOW ADVANCED TABS ON TOP
@ImageOptions(width = 50, height = 50)
ImageResource advancedtabs();
@Source("Advanced-Toolbar.png")
@ImageOptions(width = 50, height = 50)
ImageResource advancedtoolbar();
@Source("Aggregation-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource aggregationgrid();
@Source("Fx.png")
@ImageOptions(width = 50, height = 50)
ImageResource animation();
@Source("Fx-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource animationuibinder();
@Source("Area-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource areachart();
@Source("Area-Renderer-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource arearendererchart();
@Source("Async-Json-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource asyncjsontree();
@Source("Async-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource asynctree();
@Source("Async-TreeGrid.png")
@ImageOptions(width = 50, height = 50)
ImageResource asynctreegrid();
@Source("Bar-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource barchart();
@Source("Bar-Renderer-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource barrendererchart();
@Source("Basic-Binding.png")
@ImageOptions(width = 50, height = 50)
ImageResource basicbinding();
@Source("Basic-Binding-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource basicbindinguibinder();
@Source("Basic-DND.png")
@ImageOptions(width = 50, height = 50)
ImageResource basicdnd();
@Source("Basic-Draw.png")
@ImageOptions(width = 50, height = 50)
ImageResource basicdraw();
@Source("Basic-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource basicgrid();
@Source("Basic-Grid-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource basicgriduibinder();
@Source("Basic-Simple-Grid-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource basicsimplegriduibinder();
@Source("Basic-Tabs.png")
@ImageOptions(width = 50, height = 50)
ImageResource basictabs();
@Source("Basic-Tabs-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource basictabsuibinder();
@Source("Basic-Toolbar.png")
@ImageOptions(width = 50, height = 50)
ImageResource basictoolbar();
@Source("Basic-Toolbar-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource basictoolbaruibinder();
@Source("Basic-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource basictree();
@Source("Basic-TreeGrid.png")
@ImageOptions(width = 50, height = 50)
ImageResource basictreegrid();
@Source("Basic-Tree-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource basictreeuibinder();
@Source("BorderLayout.png")
@ImageOptions(width = 50, height = 50)
ImageResource borderlayout();
@Source("Border-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource borderlayoutuibinder();
@Source("BorderLayout-(UiBinder-Dynamic-Attribute).png")
@ImageOptions(width = 50, height = 50)
ImageResource borderlayoutuibinderdynamicattribute();
@Source("Button-Aligning.png")
@ImageOptions(width = 50, height = 50)
ImageResource buttonaligning();
@Source("Button-Aligning-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource buttonaligninguibinder();
@Source("Buttons.png")
@ImageOptions(width = 50, height = 50)
ImageResource buttons();
@Source("Card-Layout.png")
@ImageOptions(width = 50, height = 50)
ImageResource cardlayout();
@Source("Card-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource cardlayoutuibinder();
@Source("Cell-Action-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource cellactiontree();
@Source("Cell-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource cellgrid();
@Source("Center-Layout.png")
@ImageOptions(width = 50, height = 50)
ImageResource centerlayout();
@Source("Center-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource centerlayoutuibinder();
@Source("Checkbox-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource checkboxgrid();
@Source("CheckBox-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource checkboxtree();
@Source("Column-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource columnchart();
@Source("Column-Renderer-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource columnrendererchart();
@Source("Combo-Box.png")
@ImageOptions(width = 50, height = 50)
ImageResource combobox();
@Source("Context-Menu-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource contextmenutree();
@Source("Customized-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource customizedtree();
@Source("Dashboard.png")
@ImageOptions(width = 50, height = 50)
ImageResource dashboard();
@Source("DateCell-ListView.png")
@ImageOptions(width = 50, height = 50)
ImageResource datecelllistview();
@Source("DatePicker.png")
@ImageOptions(width = 50, height = 50)
ImageResource datepicker();
@Source("DatePicker-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource datepickeruibinder();
@Source("Dialog.png")
@ImageOptions(width = 50, height = 50)
ImageResource dialog();
@Source("Draggable.png")
@ImageOptions(width = 50, height = 50)
ImageResource draggable();
@Source("Draggable-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource draggableuibinder();
@Source("Dual-List-Field.png")
@ImageOptions(width = 50, height = 50)
ImageResource duallistfield();
@Source("DualListField-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource duallistfielduibinder();
@Source("Dynamic-Line-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource dynamiclinechart();
@Source("Editable-TreeGrid.png")
@ImageOptions(width = 50, height = 50)
ImageResource editortreegrid();
@Source("Fast-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource fasttree();
@Source("File-Upload.png")
@ImageOptions(width = 50, height = 50)
ImageResource fileupload();
@Source("Filter-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource filterchart();
@Source("Filter-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource filtergrid();
@Source("Filter-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource filtertree();
@Source("Forms-Example.png")
@ImageOptions(width = 50, height = 50)
ImageResource formsexample();
@Source("Forms-Example-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource formsexampleuibinder();
@Source("Gauge-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource gaugechart();
@Source("Grid-Binding.png")
@ImageOptions(width = 50, height = 50)
ImageResource gridbinding();
@Source("Grid-to-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource gridtogrid();
@Source("Grouped-Bar-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource groupedbarchart();
@Source("Grouping-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource groupinggrid();
@Source("HBoxLayout.png")
@ImageOptions(width = 50, height = 50)
ImageResource hboxlayout();
@Source("HBoxLayout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource hboxlayoutuibinder();
@Source("Hello-World.png")
@ImageOptions(width = 50, height = 50)
ImageResource helloworld();
@Source("Hello-World-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource helloworlduibinder();
@Source("Horizontal-Layouot.png")
@ImageOptions(width = 50, height = 50)
ImageResource horizontallayout();
@Source("Horizontal-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource horizontallayoutuibinder();
@Source("HtmlLayout.png")
@ImageOptions(width = 50, height = 50)
ImageResource htmllayoutcontainer();
@Source("Image-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource imagechart();
@Source("Info.png")
@ImageOptions(width = 50, height = 50)
ImageResource notification();
@Source("Inline-Editable-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource inlineeditablegrid();
@Source("Json-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource jsongrid();
@Source("Line-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource linechart();
@Source("Line-Gap-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource linegapchart();
@Source("List-Property.png")
@ImageOptions(width = 50, height = 50)
ImageResource listproperty();
@Source("List-to-List.png")
@ImageOptions(width = 50, height = 50)
ImageResource listtolist();
@Source("ListView.png")
@ImageOptions(width = 50, height = 50)
ImageResource listview();
@Source("List-View-Binding.png")
@ImageOptions(width = 50, height = 50)
ImageResource listviewbinding();
@Source("Live-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource livechart();
@Source("Live-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource livegrid();
@Source("Live-Group-Summary.png")
@ImageOptions(width = 50, height = 50)
ImageResource livegroupsummary();
@Source("LocalStorage-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource localstoragegrid();
@Source("Logos.png")
@ImageOptions(width = 50, height = 50)
ImageResource logos();
@Source("Menu-Bar.png")
@ImageOptions(width = 50, height = 50)
ImageResource menubar();
@Source("Menu-Bar-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource menubaruibinder();
@Source("Message-Box.png")
@ImageOptions(width = 50, height = 50)
ImageResource messagebox();
@Source("Mixed-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource mixedchart();
@Source("Overflow-Toolbar.png")
@ImageOptions(width = 50, height = 50)
ImageResource overflowtoolbar();
@Source("Overflow-Toolbar-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource overflowtoolbaruibinder();
@Source("Overview.png")
@ImageOptions(width = 50, height = 50)
ImageResource overview();
@Source("Paging-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource paginggrid();
@Source("Paging-Grid-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource paginggriduibinder();
@Source("Pie-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource piechart();
@Source("Pie-Renderer-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource pierendererchart();
@Source("Portal-Layout.png")
@ImageOptions(width = 50, height = 50)
ImageResource portallayout();
@Source("Portal-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource portallayoutuibinder();
@Source("Radar-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource radarchart();
@Source("Reordering-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource reorderingtree();
@Source("Reordering-TreeGrid.png")
@ImageOptions(width = 50, height = 50)
ImageResource reorderingtreegrid();
@Source("Request-Factory-Binding.png")
@ImageOptions(width = 50, height = 50)
ImageResource requestfactorybinding();
@Source("RequestFactory-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource requestfactorygrid();
@Source("Resizable.png")
@ImageOptions(width = 50, height = 50)
ImageResource resizable();
@Source("Rotate-Text.png")
@ImageOptions(width = 50, height = 50)
ImageResource rotatetext();
@Source("Row-Editable-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource roweditablegrid();
@Source("RowExpander-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource rowexpandergrid();
@Source("Row-Numberer-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource rownumberergrid();
@Source("Scatter-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource scatterchart();
@Source("Scatter-Renderer-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource scatterrendererchart();
@Source("Slider.png")
@ImageOptions(width = 50, height = 50)
ImageResource slider();
@Source("Slider-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource slideruibinder();
@Source("Stacked-Bar-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource stackedbarchart();
@Source("Status-Toolbar.png")
@ImageOptions(width = 50, height = 50)
ImageResource statustoolbar();
@Source("Status-Toolbar-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource statustoolbaruibinder();
@Source("Styled-Combo-Box.png")
@ImageOptions(width = 50, height = 50)
ImageResource styledcombobox();
@Source("Templates.png")
@ImageOptions(width = 50, height = 50)
ImageResource templates();
@Source("Themed-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource themedchart();
@Source("Converter-Example.png")
@ImageOptions(width = 50, height = 50)
ImageResource bindingconverter();
@Source("Buttons.png") // FIXME: DSB: NEED ICON FOR TOOL BUTTONS EXAMPLE
@ImageOptions(width = 50, height = 50)
ImageResource toolbuttons();
@Source("Tooltip-Chart.png")
@ImageOptions(width = 50, height = 50)
ImageResource tooltipchart();
@Source("ToolTips.png")
@ImageOptions(width = 50, height = 50)
ImageResource tooltips();
@Source("ToolTips-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource tooltipsuibinder();
@Source("TreeGrid-to-TreeGrid.png")
@ImageOptions(width = 50, height = 50)
ImageResource treegridtotreegrid();
@Source("Tree-to-Tree.png")
@ImageOptions(width = 50, height = 50)
ImageResource treetotree();
@Source("VBox-Layout.png")
@ImageOptions(width = 50, height = 50)
ImageResource vboxlayout();
@Source("VBox-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource vboxlayoutuibinder();
@Source("Vertical-Layout.png")
@ImageOptions(width = 50, height = 50)
ImageResource verticallayout();
@Source("Vertical-Layout-(UiBinder).png")
@ImageOptions(width = 50, height = 50)
ImageResource verticallayoutuibinder();
@Source("Xml-Grid.png")
@ImageOptions(width = 50, height = 50)
ImageResource xmlgrid();
}
|
package com.legaoyi.common.util;
import java.security.MessageDigest;
public class PasswordHelper {
public static String SHA1(String password, String salt) throws Exception {
byte[] bytes = salt.getBytes("utf-8");
MessageDigest msgDigest = MessageDigest.getInstance("SHA");
if (salt != null && bytes.length > 0) {
msgDigest.update(bytes);
}
byte[] digest = msgDigest.digest(password.getBytes("utf-8"));
StringBuilder ret = new StringBuilder();
for (int i = 0; i < digest.length; i++) {
String hex = Integer.toHexString(digest[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret.append(hex.toUpperCase());
}
return ret.toString();
}
}
|
package za.ac.cput.views.curriculum.subject;
/**
* UpdateSubject.java
* Author: Shane Knoll (218279124)
* Date: 20 October 2021
*/
import com.google.gson.Gson;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import za.ac.cput.entity.curriculum.Subject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
public class UpdateSubject extends JFrame implements ActionListener {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private static OkHttpClient client = new OkHttpClient();
private JPanel panelNorth, panelCenter, panelSouth;
private JLabel lblPic, lblHeading;
private JLabel lblUpdate;
private JTextField txtUpdate;
private JButton btnSearch;
private JLabel lblSubjectName;
private JTextField txtSubjectName;
private JLabel lblBlank1;
private JLabel lblLecturerId;
private JTextField txtLecturerId;
private JLabel lblBlank2;
private JLabel lblCourseCode;
private JTextField txtCourseCode;
private JLabel lblBlank3;
private JLabel lblSemesterId;
private JTextField txtSemesterId;
private JLabel lblBlank4;
private JButton btnReset, btnExit, btnSaveInformation;
private Font ft1, ft2;
public UpdateSubject() {
super("Update Subject Section");
panelNorth = new JPanel();
panelCenter = new JPanel();
panelSouth = new JPanel();
lblPic = new JLabel(new ImageIcon("film3.png"));
lblHeading = new JLabel("Subject");
lblUpdate= new JLabel("Please insert your Subject Code:");
txtUpdate= new JTextField();
btnSearch= new JButton("Search");
lblSubjectName = new JLabel("Subject Name: ");
txtSubjectName= new JTextField();
lblBlank1 = new JLabel(" ");
lblLecturerId = new JLabel("LecturerID: ");
txtLecturerId = new JTextField();
lblBlank2 = new JLabel(" ");
lblCourseCode = new JLabel("Course Code: ");
txtCourseCode = new JTextField();
lblBlank3 = new JLabel(" ");
lblSemesterId = new JLabel("SemesterID: ");
txtSemesterId = new JTextField();
lblBlank4 = new JLabel(" ");
btnSaveInformation = new JButton("Update");
btnReset = new JButton("Reset");
btnExit = new JButton("Exit");
ft1 = new Font("Arial", Font.BOLD, 32);
ft2 = new Font("Arial", Font.BOLD, 15);
}
public void reset() {
txtUpdate.setText("");
txtSubjectName.setText(" ");
txtLecturerId.setText(" ");
txtCourseCode.setText(" ");
txtSemesterId.setText(" ");
}
public void setGUI() {
panelNorth.setLayout(new FlowLayout());
panelCenter.setLayout(new GridLayout(5 ,3));
panelSouth.setLayout(new GridLayout(1, 3));
panelCenter.setBorder(BorderFactory.createEmptyBorder(100, 0, 20, 0));
lblHeading.setFont(ft1);
lblHeading.setForeground(Color.RED);
panelNorth.setBackground(Color.YELLOW);
panelCenter.setBackground(Color.GREEN);
btnSaveInformation.setBackground(Color.BLUE);
btnSaveInformation.setForeground(Color.WHITE);
btnReset.setBackground(Color.BLACK);
btnReset.setForeground(Color.WHITE);
panelNorth.add(lblPic);
panelNorth.add(lblHeading);
panelCenter.add(lblUpdate);
panelCenter.add(txtUpdate);
panelCenter.add(btnSearch);
panelCenter.add(lblSubjectName);
panelCenter.add(txtSubjectName);
panelCenter.add(lblBlank4);
panelCenter.add(lblCourseCode);
panelCenter.add(txtCourseCode);
panelCenter.add(lblBlank1);
panelCenter.add(lblLecturerId);
panelCenter.add(txtLecturerId);
panelCenter.add(lblBlank2);
panelCenter.add(lblSemesterId);
panelCenter.add(txtSemesterId);
panelCenter.add(lblBlank3);
panelSouth.add(btnSaveInformation);
panelSouth.add(btnReset);
panelSouth.add(btnExit);
this.add(panelNorth, BorderLayout.NORTH);
this.add(panelCenter, BorderLayout.CENTER);
this.add(panelSouth, BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnSearch.addActionListener(this);
btnSaveInformation.addActionListener(this);
btnReset.addActionListener(this);
btnExit.addActionListener(this);
this.setSize(600, 600);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private static String run(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
private Subject getSubject(String id) throws IOException {
Subject sub = null;
try {
final String URL = "http://localhost:8080/subject/read/" + id;
String responseBody = run(URL);
Gson gson = new Gson();
sub= gson.fromJson(responseBody,Subject.class);
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(sub);
return sub;
}
public String post(final String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder().url(url).post(body).build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public void store(String subjectName,int LecturerId,String courseCode,int semesterid){
Subject sub = null;
try {
final String URL = "http://localhost:8080/subject/update";
int lecturerid = Integer.parseInt(String.valueOf(LecturerId));
int semesterId = Integer.parseInt(String.valueOf(semesterid));
sub= new Subject.SubjectBuilder()
.setsubjectCode(txtUpdate.getText())
.setsubjectName(txtSubjectName.getText())
.setcourseCode(txtCourseCode.getText())
.setlecturerID(Integer.parseInt(txtLecturerId.getText()))
.setsemesterID(Integer.parseInt(txtSemesterId.getText()))
.build();
Gson g = new Gson();
String jsonString = g.toJson(sub);
String r = post(URL, jsonString);
System.out.println(r);
if (r != null) {
JOptionPane.showMessageDialog(null, "Your Subject has updated successfully!");
SubjectMenuGUI.main(null);
this.setVisible(false);
} else {
JOptionPane.showMessageDialog(null, "Error: Cannot update your Subject information");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
System.out.println(sub);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==btnSearch) {
try {
Subject sub = getSubject(txtUpdate.getText());
if (sub != null) {
txtSubjectName.setText(sub.getSubjectName());
txtCourseCode.setText(sub.getCourseCode());
txtLecturerId.setText(String.valueOf(sub.getLecturerID()));
txtSemesterId.setText(String.valueOf(sub.getSemesterID()));
} else {
JOptionPane.showMessageDialog(null, "Error, cannot search for your Subject Code");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}else if(e.getSource()==btnSaveInformation){
store(txtSubjectName.getText(),Integer.parseInt(txtLecturerId.getText()),txtCourseCode.getText(),Integer.parseInt(txtSemesterId.getText()));
}else if(e.getSource()==btnReset){
reset();
}
else if(e.getSource()==btnExit){
this.dispose();
new SubjectMenuGUI().setGUI();
}
}
public static void main(String[] args) {
// TODO code application logic here
new UpdateSubject().setGUI();
}
}
|
package com.patrickmcgeever.java8.lambdaexpressions;
/**
* Created by patrick on 12/07/2014.
*/
// This annotation will cause a compile error if I try to add another abstract method
@FunctionalInterface
public interface MyInterface {
default String defaultOne() {
return "Default 1";
}
default String defaultTwo() {
return "Default 2";
}
default String defaultThree() {
return "Default 3";
}
String getStringFunction();
// This abstract function will cause a compile error because of the FunctionalInterface annotation
// String extraFunction();
}
|
package java0722;
import java.util.*;
public class BookMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
NameDTO name = null;
BookDTO book = null;
BookService bookser = new BookService();
List<NameDTO> nameList = new ArrayList<NameDTO>();
nameList.add(0, null);
List<BookDTO> bookList = new ArrayList<BookDTO>();
bookList.add(0, null);
boolean boo = true;
while (boo) {
bookser.text(name);
int num = scan.nextInt();
switch (num) {
case 1:
name = new NameDTO();
name = bookser.enter(name);
nameList.add(name);
break;
case 2:
book = new BookDTO();
book = bookser.enterbook(book);
bookList.add(book);
break;
case 3:
bookList = bookser.ang(bookList, nameList);
break;
case 4:
bookList = bookser.bookin(bookList, nameList);
break;
case 5:
bookser.bookin(bookList);
// false = 대출
// true = 안빌린거
break;
case 6:
System.out.println("프로그램 종료");
boo = false;
break;
}
}
scan.close();
}
}
|
package pl.edu.icm.unity.server.utils;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Performs an action when a file change is detected. This should be executed
* periodically, for example using a scheduled executor service.
*
* @author schuller
*/
public class FileWatcher implements Runnable
{
private final File target;
private final Runnable action;
private long lastAccessed;
public FileWatcher(File target, Runnable action) throws FileNotFoundException
{
if (!target.exists() || !target.canRead())
{
throw new FileNotFoundException("File " + target.getAbsolutePath()
+ " does not exist or is not readable.");
}
this.target = target;
this.action = action;
lastAccessed = target.lastModified();
}
/**
* Check if target file has been touched and invoke the action if it has been.
*/
public void run()
{
if (target.lastModified() > lastAccessed)
{
lastAccessed = target.lastModified();
action.run();
}
}
}
|
package com.example.projet_mobile;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
public EditText mavariableEditText;
public ListView mavariableListView;
private ProgressDialog pDialog;
private String TAG = MainActivity.class.getSimpleName();
//private static String url = "https://api.androidhive.info/contacts/";
private static String url = "https://newsapi.org/v2/top-headlines?sources=le-monde&apiKey=96308c15b3bf408b9a0f25678514fc10";
//private NotesDbAdapter dbadapter;
//boolean myItemShouldBeEnabled = false;
/**********************************************************Méthode OnCreate *****************************************************************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/********* On affiche le layout de base et sa toolbar **********/
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/********** Création de variables pour manipulation input text, listview et bouton d'ajout ***********************/
mavariableEditText = (EditText) findViewById(R.id.mavariableEditText);
mavariableListView = (ListView) findViewById(R.id.mavariableListView);
Button button = (Button) findViewById(R.id.button_add_to_list);
registerForContextMenu(mavariableListView);
/********** clic sur un élément de la liste listener ***********************/
mavariableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// On appelle la fonction permettant de supprimer une entrée de l'array depuis un index
//myItemShouldBeEnabled = true;
//dbadapter.deleteNote(id);
//fillData();
}
});
/********** Quand on appuie sur le bouton d'ajout de tache ***********************/
/*
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addTextToList();
}
});*/
new GetJSON(url,TAG,mavariableListView,this).execute();
}
/******************************** Gestion du CONTEXT menu **************************************************************/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Cursor SelectedTaskCursor = (Cursor) mavariableListView.getItemAtPosition(info.position);
final String SelectedTask = SelectedTaskCursor.getString(SelectedTaskCursor.getColumnIndex("title"));
switch(item.getItemId()){
case R.id.mapsFind:
Uri location = Uri.parse("geo:0,0?q=" +SelectedTask ); //28+rue+de+la+chance
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
startActivity(mapIntent);
break;
case R.id.googleSearch:
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, SelectedTask);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
break;
}
return true;
}
/******************************** Gestion du menu **************************************************************/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_to_do_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
/*********On crée la notification de suppression de toutes les tâches **********/
if (id == R.id.action_remove_all) {
//removeAllTextList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
// Add the buttons
builder.setPositiveButton(R.string.alert_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
removeAllTextList();
}
});
builder.setNegativeButton(R.string.alert_nok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
return super.onOptionsItemSelected(item);
}
/****************************************** Méthode de traitement liste ****************************************************************/
public void addTextToList(){
if(!mavariableEditText.getText().toString().isEmpty()){
/* dbadapter.createNote(mavariableEditText.getText().toString(),"");
fillData();
mavariableEditText.setText("");*/
// LE vrai
/*
todoItems.add(0, mavariableEditText.getText().toString()); // 1
aa.notifyDataSetChanged(); // 2
mavariableEditText.setText(""); // 3 - remise à vide de l'EditText
*/
}
}
public void removeAllTextList(){
//dbadapter.deleteAllNotes();
//fillData();
mavariableEditText.setText("");
}
private void fillData() {
// Get all of the notes from the database and create the item list
/* Cursor c = dbadapter.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
// setListAdapter(notes); NE PAS UTILISER car c'est un AppCompactActivity et non pas un ListActivity
mavariableListView.setAdapter(notes);*/
}
}
|
package com.jgermaine.fyp.rest.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Table(name = "Entries")
@JsonIgnoreProperties(value={"imageString", "report"})
public class Entry {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "entry_id", unique = true, nullable = false)
private int id;
private Date timestamp;
@Lob
@Column(columnDefinition = "mediumblob")
private byte[] image;
@Length(max = 255)
private String comment;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "report_id", nullable=false)
private Report report;
@NotEmpty
@Email
@Length(max = 255)
private String author;
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public Date getTimestamp() {
return timestamp;
}
public Report getReport() {
return report;
}
public void setReport(Report report) {
this.report = report;
}
public String getAuthor() {
return this.author;
}
public void setAuthor(String author) {
this.author = author;
}
}
|
package liu.java.util.concurrent.locks;
public class Test {
}
|
package com.esum.boot;
public class BootMainTestHelper {
public static String XTRUS_HOME="c:\\server\\xtrus-4.4.3-SNAPSHOT";
public static String XTRUS_HOSTNAME="localhost";
}
|
package gov.nih.mipav.model.scripting.parameters;
import gov.nih.mipav.model.scripting.ParserException;
/**
* A unsigned short parameter used in either the recording or execution of a script action.
*/
public class ParameterUShort extends Parameter {
// ~ Instance fields
// ------------------------------------------------------------------------------------------------
/** The parameter's value. */
private short value;
// ~ Constructors
// ---------------------------------------------------------------------------------------------------
/**
* Creates a new ParameterUShort object without any value.
*
* @param paramLabel The label/name to give to this parameter.
*
* @throws ParserException If there is a problem creating the parameter.
*/
public ParameterUShort(final String paramLabel) throws ParserException {
super(paramLabel, Parameter.PARAM_USHORT);
}
/**
* Creates a new ParameterUShort with a new value.
*
* @param paramLabel The label/name to give to this parameter.
* @param paramValue The new parameter value.
*
* @throws ParserException If there is a problem creating the parameter.
*/
public ParameterUShort(final String paramLabel, final short paramValue) throws ParserException {
super(paramLabel, Parameter.PARAM_USHORT);
setValue(paramValue);
}
/**
* Creates a new ParameterUShort object.
*
* @param paramLabel The label/name to give to this parameter.
* @param paramTypeString The type of this parameter, in string form.
* @param paramValue The new parameter value.
*
* @throws ParserException If there is a problem creating the parameter (e.g., a value less than 0).
*/
public ParameterUShort(final String paramLabel, final String paramTypeString, final short paramValue)
throws ParserException {
super(paramLabel, paramTypeString);
setValue(paramValue);
}
/**
* Creates a new ParameterUShort object.
*
* @param paramLabel The label/name to give to this parameter.
* @param paramTypeString The type of this parameter, in string form.
* @param paramValueString The new parameter value in string form.
*
* @throws ParserException If there is a problem creating the parameter (e.g., a value less than 0).
*/
public ParameterUShort(final String paramLabel, final String paramTypeString, final String paramValueString)
throws ParserException {
super(paramLabel, paramTypeString);
setValue(paramValueString);
}
/**
* Creates a new ParameterUShort object.
*
* @param paramLabel The label/name to give to this parameter.
* @param paramType The type of this parameter (should be PARAM_USHORT).
* @param paramValue The new parameter value.
*
* @throws ParserException If there is a problem creating the parameter (e.g., a value less than 0).
*/
public ParameterUShort(final String paramLabel, final int paramType, final short paramValue) throws ParserException {
super(paramLabel, paramType);
setValue(paramValue);
}
/**
* Creates a new ParameterUShort object.
*
* @param paramLabel The label/name to give to this parameter.
* @param paramType The type of this parameter (should be PARAM_USHORT).
* @param paramValueString The new parameter value in string form.
*
* @throws ParserException If there is a problem creating the parameter (e.g., a value less than 0).
*/
public ParameterUShort(final String paramLabel, final int paramType, final String paramValueString)
throws ParserException {
super(paramLabel, paramType);
setValue(paramValueString);
}
// ~ Methods
// --------------------------------------------------------------------------------------------------------
/**
* Returns the parameter value.
*
* @return The parameter value.
*/
public short getValue() {
return value;
}
/**
* Returns the parameter value as a string.
*
* @return The parameter value in string form.
*/
public String getValueString() {
return "" + getValue();
}
/**
* Checks whether a prospective value is valid.
*
* @param paramValue A prospective unsigned short value.
*
* @return <code>True</code> if the value is valid, <code>false</code> otherwise.
*
* @throws ParserException If the given value is not valid (if < 0).
*/
public boolean isValueValid(final short paramValue) throws ParserException {
if (paramValue < 0) {
throw new ParserException(getLabel() + ": An unsigned short parameter must be non-negative: " + paramValue);
}
return true;
}
/**
* Changes the parameter's current value.
*
* @param paramValueString The new parameter value in String form.
*
* @throws ParserException If there is a problem changing the parameter value (< 0).
*/
public void setValue(final String paramValueString) throws ParserException {
try {
setValue(Short.parseShort(paramValueString));
} catch (final NumberFormatException nfe) {
throw new ParserException(getLabel() + ": Invalid parameter value: " + nfe.getMessage());
}
}
/**
* Changes the parameter's current value.
*
* @param paramValue The new parameter value.
*
* @throws ParserException If there is a problem changing the parameter value (< 0).
*/
public void setValue(final short paramValue) throws ParserException {
value = paramValue;
if ( !isValueValid(value)) {
value = 0;
}
setValueAssigned(true);
}
}
|
package algorhithm;
import java.util.Arrays;
public class InsertionSort {
public static void main(String[] args) {
int[] array = {1,7,20,611,21};
int temp = 0;
int j=0;
for(int i=1; i<array.length; i++) {
temp = array[i];
// System.out.println(Arrays.toString(array));
for(j=i-1; j>=0 && temp<array[j]; j--) {
array[j+1] = array[j];
}
array[j+1] = temp;
}
System.out.println(Arrays.toString(array));
}
}
|
package com.beike.dao.edm;
import java.util.Map;
import com.beike.dao.GenericDao;
import com.beike.entity.edm.CancelEdmEmail;
/**
*
* @author 赵静龙 创建时间:2012-10-18
*/
public interface CancelEDMMailDao extends GenericDao<CancelEdmEmail, Long>{
/**
* 保存所取消订阅邮箱信息
* @param edmCancelEmailInfo
*/
public void addCancelEdmMail(Map<String,Object> edmCancelEmailInfo);
}
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* 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 und
*/
package org.wso2.carbon.identity.recovery.handler;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.common.model.User;
import org.wso2.carbon.identity.base.IdentityRuntimeException;
import org.wso2.carbon.identity.core.bean.context.MessageContext;
import org.wso2.carbon.identity.core.handler.InitConfig;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.event.IdentityEventClientException;
import org.wso2.carbon.identity.event.IdentityEventConstants;
import org.wso2.carbon.identity.event.IdentityEventException;
import org.wso2.carbon.identity.event.event.Event;
import org.wso2.carbon.identity.event.handler.AbstractEventHandler;
import org.wso2.carbon.identity.governance.IdentityMgtConstants;
import org.wso2.carbon.identity.recovery.IdentityRecoveryConstants;
import org.wso2.carbon.identity.recovery.IdentityRecoveryException;
import org.wso2.carbon.identity.recovery.RecoveryScenarios;
import org.wso2.carbon.identity.recovery.RecoverySteps;
import org.wso2.carbon.identity.recovery.internal.IdentityRecoveryServiceDataHolder;
import org.wso2.carbon.identity.recovery.model.Property;
import org.wso2.carbon.identity.recovery.model.UserRecoveryData;
import org.wso2.carbon.identity.recovery.store.JDBCRecoveryDataStore;
import org.wso2.carbon.identity.recovery.store.UserRecoveryDataStore;
import org.wso2.carbon.identity.recovery.util.Utils;
import org.wso2.carbon.user.api.Claim;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.UserStoreManager;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import static org.wso2.carbon.identity.recovery.IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_VERIFICATION_EMAIL_NOT_FOUND;
public class UserEmailVerificationHandler extends AbstractEventHandler {
private static final Log log = LogFactory.getLog(UserEmailVerificationHandler.class);
private static final Random RANDOM = new SecureRandom();
private static final Boolean isRandomValueForCredentialsDisabled = isRandomValueForCredentialsDisabled();
public String getName() {
return "userEmailVerification";
}
public String getFriendlyName() {
return "User Email Verification";
}
@Override
public void handleEvent(Event event) throws IdentityEventException {
Map<String, Object> eventProperties = event.getEventProperties();
String eventName = event.getEventName();
UserStoreManager userStoreManager = (UserStoreManager) eventProperties.get(
IdentityEventConstants.EventProperty.USER_STORE_MANAGER);
User user = getUser(eventProperties, userStoreManager);
Map<String, String> claims = (Map<String, String>) eventProperties.get(IdentityEventConstants.EventProperty
.USER_CLAIMS);
boolean enable = false;
if (IdentityEventConstants.Event.PRE_ADD_USER.equals(eventName) ||
IdentityEventConstants.Event.POST_ADD_USER.equals(eventName)) {
enable = Boolean.parseBoolean(Utils.getConnectorConfig(IdentityRecoveryConstants.ConnectorConfig
.ENABLE_EMAIL_VERIFICATION, user.getTenantDomain()));
} else if (IdentityEventConstants.Event.PRE_SET_USER_CLAIMS.equals(eventName) ||
IdentityEventConstants.Event.POST_SET_USER_CLAIMS.equals(eventName)) {
enable = Boolean.parseBoolean(Utils.getConnectorConfig(IdentityRecoveryConstants.ConnectorConfig
.ENABLE_EMAIL_VERIFICATION_ON_UPDATE, user.getTenantDomain()));
if (!enable) {
/* We need to empty 'EMAIL_ADDRESS_PENDING_VALUE_CLAIM' because having a value in that claim implies
a verification is pending. But verification is not enabled anymore. */
if (claims.containsKey(IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM)) {
if (IdentityEventConstants.Event.PRE_SET_USER_CLAIMS.equals(eventName)) {
sendNotificationToExistingEmailOnEmailUpdate(
user, userStoreManager, claims.get(IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM),
IdentityRecoveryConstants.NOTIFICATION_TYPE_NOTIFY_EMAIL_UPDATE_WITHOUT_VERIFICATION);
}
invalidatePendingEmailVerification(user, userStoreManager, claims);
}
claims.remove(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM);
}
}
if (!enable) {
// Email Verification feature is disabled.
if (log.isDebugEnabled()) {
log.debug("Email verification Handler is disabled in tenant: " + user.getTenantDomain() + "for " +
"event: " + eventName);
}
return;
}
String[] roleList = (String[]) eventProperties.get(IdentityEventConstants.EventProperty.ROLE_LIST);
if (roleList != null) {
List<String> roles = Arrays.asList(roleList);
if (roles.contains(IdentityRecoveryConstants.SELF_SIGNUP_ROLE)) {
//This is a self signup request. Will be handled in self signup handler
return;
}
}
if (IdentityEventConstants.Event.PRE_ADD_USER.equals(eventName)) {
Utils.clearEmailVerifyTemporaryClaim();
if (claims == null || claims.isEmpty()) {
// Not required to handle in this handler.
return;
} else if (claims.containsKey(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM) && Boolean.parseBoolean(claims.get(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM))) {
if (!claims.containsKey(IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM)
|| StringUtils.isBlank(claims.get(IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM))) {
throw new IdentityEventClientException(ERROR_CODE_VERIFICATION_EMAIL_NOT_FOUND.getCode(),
ERROR_CODE_VERIFICATION_EMAIL_NOT_FOUND.getMessage());
}
Claim claim = new Claim();
claim.setClaimUri(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM);
claim.setValue(claims.get(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM));
Utils.setEmailVerifyTemporaryClaim(claim);
claims.remove(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM);
Utils.publishRecoveryEvent(eventProperties, IdentityEventConstants.Event.PRE_VERIFY_EMAIL_CLAIM, null);
} else if (claims.containsKey(IdentityRecoveryConstants.ASK_PASSWORD_CLAIM) && Boolean.parseBoolean(claims.get(IdentityRecoveryConstants.ASK_PASSWORD_CLAIM))) {
Claim claim = new Claim();
claim.setClaimUri(IdentityRecoveryConstants.ASK_PASSWORD_CLAIM);
claim.setValue(claims.get(IdentityRecoveryConstants.ASK_PASSWORD_CLAIM));
Utils.setEmailVerifyTemporaryClaim(claim);
claims.remove(IdentityRecoveryConstants.ASK_PASSWORD_CLAIM);
Object credentials = eventProperties.get(IdentityEventConstants.EventProperty.CREDENTIAL);
if (!isRandomValueForCredentialsDisabled) {
setRandomValueForCredentials(credentials);
}
Utils.publishRecoveryEvent(eventProperties, IdentityEventConstants.Event.PRE_ADD_USER_WITH_ASK_PASSWORD,
null);
} else {
return;
// Not required to handle in this handler.
}
}
if (IdentityEventConstants.Event.POST_ADD_USER.equals(eventName)) {
boolean isAccountLockOnCreation = Boolean.parseBoolean(Utils.getConnectorConfig
(IdentityRecoveryConstants.ConnectorConfig.EMAIL_ACCOUNT_LOCK_ON_CREATION, user.getTenantDomain()));
boolean isNotificationInternallyManage = Boolean.parseBoolean(Utils.getConnectorConfig
(IdentityRecoveryConstants.ConnectorConfig.EMAIL_VERIFICATION_NOTIFICATION_INTERNALLY_MANAGE,
user.getTenantDomain()));
Claim claim = Utils.getEmailVerifyTemporaryClaim();
boolean isAccountClaimExist = Utils.isAccountStateClaimExisting(user.getTenantDomain());
if (claim == null) {
return;
// Not required to handle in this handler.
} else if (IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM.equals(claim.getClaimUri())) {
String confirmationCode = UUID.randomUUID().toString();
if (isNotificationInternallyManage) {
if (isAccountClaimExist) {
setUserClaim(IdentityRecoveryConstants.ACCOUNT_STATE_CLAIM_URI,
IdentityRecoveryConstants.PENDING_EMAIL_VERIFICATION, userStoreManager, user);
}
initNotification(user, RecoveryScenarios.SELF_SIGN_UP, RecoverySteps.CONFIRM_SIGN_UP,
IdentityRecoveryConstants.NOTIFICATION_TYPE_EMAIL_CONFIRM);
}
// Need to lock user account.
if (isAccountLockOnCreation) {
lockAccount(user, userStoreManager);
setUserClaim(IdentityRecoveryConstants.ACCOUNT_LOCKED_REASON_CLAIM,
IdentityMgtConstants.LockedReason.PENDING_EMAIL_VERIFICATION.toString(),
userStoreManager, user);
}
Utils.publishRecoveryEvent(eventProperties, IdentityEventConstants.Event.POST_VERIFY_EMAIL_CLAIM,
confirmationCode);
} else if (IdentityRecoveryConstants.ASK_PASSWORD_CLAIM.equals(claim.getClaimUri())) {
String confirmationCode = UUID.randomUUID().toString();
if (isAccountClaimExist) {
setUserClaim(IdentityRecoveryConstants.ACCOUNT_STATE_CLAIM_URI,
IdentityRecoveryConstants.PENDING_ASK_PASSWORD, userStoreManager, user);
}
if (isNotificationInternallyManage) {
initNotification(user, RecoveryScenarios.ASK_PASSWORD, RecoverySteps.UPDATE_PASSWORD,
IdentityRecoveryConstants.NOTIFICATION_TYPE_ASK_PASSWORD, confirmationCode);
} else {
setRecoveryData(user, RecoveryScenarios.ASK_PASSWORD, RecoverySteps.UPDATE_PASSWORD,
confirmationCode);
setAskPasswordConfirmationCodeToThreadLocal(confirmationCode);
}
// Need to lock user account.
if (isAccountLockOnCreation) {
lockAccount(user, userStoreManager);
setUserClaim(IdentityRecoveryConstants.ACCOUNT_LOCKED_REASON_CLAIM,
IdentityMgtConstants.LockedReason.PENDING_ASK_PASSWORD.toString(),
userStoreManager, user);
}
Utils.publishRecoveryEvent(eventProperties, IdentityEventConstants.Event.POST_ADD_USER_WITH_ASK_PASSWORD,
confirmationCode);
}
}
if (IdentityEventConstants.Event.PRE_SET_USER_CLAIMS.equals(eventName)) {
preSetUserClaimsOnEmailUpdate(claims, userStoreManager, user);
claims.remove(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM);
}
if (IdentityEventConstants.Event.POST_SET_USER_CLAIMS.equals(eventName)) {
postSetUserClaimsOnEmailUpdate(user, userStoreManager);
claims.remove(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM);
}
}
@Override
public void init(InitConfig configuration) throws IdentityRuntimeException {
super.init(configuration);
}
@Override
public int getPriority(MessageContext messageContext) {
return 65;
}
public void lockAccount(User user, UserStoreManager userStoreManager) throws IdentityEventException {
if (log.isDebugEnabled()) {
log.debug("Locking user account:" + user.getUserName());
}
setUserClaim(IdentityRecoveryConstants.ACCOUNT_LOCKED_CLAIM, Boolean.TRUE.toString(), userStoreManager, user);
}
protected void initNotification(User user, Enum recoveryScenario, Enum recoveryStep, String notificationType)
throws IdentityEventException {
String secretKey = UUID.randomUUID().toString();
initNotification(user, recoveryScenario, recoveryStep, notificationType, secretKey);
}
protected void initNotification(User user, Enum recoveryScenario, Enum recoveryStep, String notificationType,
String secretKey) throws IdentityEventException {
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
try {
userRecoveryDataStore.invalidate(user);
UserRecoveryData recoveryDataDO = new UserRecoveryData(user, secretKey, recoveryScenario, recoveryStep);
userRecoveryDataStore.store(recoveryDataDO);
triggerNotification(user, notificationType, secretKey, Utils.getArbitraryProperties(), recoveryDataDO);
} catch (IdentityRecoveryException e) {
throw new IdentityEventException("Error while sending notification ", e);
}
}
/**
* This method sets a random value for the credentials, if the ask password flow is enabled.
* @param credentials Credentials object
*/
private void setRandomValueForCredentials(Object credentials) {
char[] temporaryPassword = Utils.generateRandomPassword(12);
((StringBuffer) credentials).replace(0, temporaryPassword.length, new String(temporaryPassword));
}
private static boolean isRandomValueForCredentialsDisabled() {
return Boolean.parseBoolean(IdentityUtil.getProperty(
IdentityRecoveryConstants.ConnectorConfig.ASK_PASSWORD_DISABLE_RANDOM_VALUE_FOR_CREDENTIALS));
}
private void initNotificationForEmailVerificationOnUpdate(String verificationPendingEmailAddress, User user)
throws IdentityEventException {
String secretKey = UUID.randomUUID().toString();
initNotificationForEmailVerificationOnUpdate(user, secretKey, verificationPendingEmailAddress);
}
private void initNotificationForEmailVerificationOnUpdate(User user, String secretKey,
String verificationPendingEmailAddress)
throws IdentityEventException {
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
try {
userRecoveryDataStore.invalidate(user, RecoveryScenarios.EMAIL_VERIFICATION_ON_UPDATE,
RecoverySteps.VERIFY_EMAIL);
UserRecoveryData recoveryDataDO = new UserRecoveryData(user, secretKey,
RecoveryScenarios.EMAIL_VERIFICATION_ON_UPDATE, RecoverySteps.VERIFY_EMAIL);
/* Email address persisted in remaining set ids to maintain context information about the email address
associated with the verification code generated. */
recoveryDataDO.setRemainingSetIds(verificationPendingEmailAddress);
userRecoveryDataStore.store(recoveryDataDO);
triggerNotification(user, IdentityRecoveryConstants.NOTIFICATION_TYPE_VERIFY_EMAIL_ON_UPDATE, secretKey,
Utils.getArbitraryProperties(), verificationPendingEmailAddress, recoveryDataDO);
} catch (IdentityRecoveryException e) {
throw new IdentityEventException("Error while sending notification for user: " +
user.toFullQualifiedUsername(), e);
}
}
protected void invalidateRecoveryData(User user)
throws IdentityEventException {
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
try {
userRecoveryDataStore.invalidate(user);
} catch (IdentityRecoveryException e) {
throw new IdentityEventException("Error while invalidate recovery data for user :" + user.toString(), e);
}
}
protected void setRecoveryData(User user, Enum recoveryScenario, Enum recoveryStep, String secretKey)
throws IdentityEventException {
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
try {
userRecoveryDataStore.invalidate(user);
UserRecoveryData recoveryDataDO = new UserRecoveryData(user, secretKey, recoveryScenario, recoveryStep);
userRecoveryDataStore.store(recoveryDataDO);
} catch (IdentityRecoveryException e) {
throw new IdentityEventException("Error while setting recovery data for user ", e);
}
}
protected UserRecoveryData getRecoveryData(User user) throws IdentityEventException {
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
UserRecoveryData recoveryData;
try {
recoveryData = userRecoveryDataStore.loadWithoutCodeExpiryValidation(user);
} catch (IdentityRecoveryException e) {
throw new IdentityEventException("Error while loading recovery data for user ", e);
}
return recoveryData;
}
protected void setUserClaim(String claimName, String claimValue, UserStoreManager userStoreManager, User user)
throws IdentityEventException {
HashMap<String, String> userClaims = new HashMap<>();
userClaims.put(claimName, claimValue);
try {
userStoreManager.setUserClaimValues(user.getUserName(), userClaims, null);
} catch (UserStoreException e) {
throw new IdentityEventException("Error while setting user claim value :" + user.getUserName(), e);
}
}
protected void triggerNotification(User user, String type, String code, Property[] props) throws
IdentityRecoveryException {
triggerNotification(user, type, code, props, null);
}
protected void triggerNotification(User user, String type, String code, Property[] props,
UserRecoveryData recoveryDataDO) throws IdentityRecoveryException {
triggerNotification(user, type, code, props, null, recoveryDataDO);
}
private void triggerNotification(User user, String type, String code, Property[] props, String
verificationPendingEmailAddress, UserRecoveryData recoveryDataDO) throws IdentityRecoveryException {
if (log.isDebugEnabled()) {
log.debug("Sending : " + type + " notification to user : " + user.toString());
}
String eventName = IdentityEventConstants.Event.TRIGGER_NOTIFICATION;
HashMap<String, Object> properties = new HashMap<>();
properties.put(IdentityEventConstants.EventProperty.USER_NAME, user.getUserName());
properties.put(IdentityEventConstants.EventProperty.TENANT_DOMAIN, user.getTenantDomain());
properties.put(IdentityEventConstants.EventProperty.USER_STORE_DOMAIN, user.getUserStoreDomain());
if (StringUtils.isNotBlank(verificationPendingEmailAddress)) {
properties.put(IdentityRecoveryConstants.SEND_TO, verificationPendingEmailAddress);
}
if (props != null && props.length > 0) {
for (Property prop : props) {
properties.put(prop.getKey(), prop.getValue());
}
}
if (StringUtils.isNotBlank(code)) {
properties.put(IdentityRecoveryConstants.CONFIRMATION_CODE, code);
}
properties.put(IdentityRecoveryConstants.TEMPLATE_TYPE, type);
if (recoveryDataDO != null) {
properties.put(IdentityEventConstants.EventProperty.RECOVERY_SCENARIO,
recoveryDataDO.getRecoveryScenario().name());
}
Event identityMgtEvent = new Event(eventName, properties);
try {
IdentityRecoveryServiceDataHolder.getInstance().getIdentityEventService().handleEvent(identityMgtEvent);
} catch (IdentityEventException e) {
throw Utils.handleServerException(IdentityRecoveryConstants.ErrorMessages.ERROR_CODE_TRIGGER_NOTIFICATION, user
.getUserName(), e);
}
}
protected User getUser(Map eventProperties, UserStoreManager userStoreManager) {
String userName = (String) eventProperties.get(IdentityEventConstants.EventProperty.USER_NAME);
String tenantDomain = (String) eventProperties.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN);
String domainName = userStoreManager.getRealmConfiguration().getUserStoreProperty(
UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
User user = new User();
user.setUserName(userName);
user.setTenantDomain(tenantDomain);
user.setUserStoreDomain(domainName);
return user;
}
private void preSetUserClaimsOnEmailUpdate(Map<String, String> claims, UserStoreManager userStoreManager,
User user) throws IdentityEventException {
if (IdentityRecoveryConstants.SkipEmailVerificationOnUpdateStates.SKIP_ON_CONFIRM.toString().equals
(Utils.getThreadLocalToSkipSendingEmailVerificationOnUpdate())) {
// Not required to handle in this handler.
return;
}
if (Utils.getThreadLocalToSkipSendingEmailVerificationOnUpdate() != null) {
Utils.unsetThreadLocalToSkipSendingEmailVerificationOnUpdate();
}
if (MapUtils.isEmpty(claims)) {
// Not required to handle in this handler.
Utils.setThreadLocalToSkipSendingEmailVerificationOnUpdate(IdentityRecoveryConstants.
SkipEmailVerificationOnUpdateStates.SKIP_ON_INAPPLICABLE_CLAIMS.toString());
return;
}
String emailAddress = claims.get(IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM);
if (StringUtils.isNotBlank(emailAddress)) {
String existingEmail;
String username = user.getUserName();
try {
existingEmail = userStoreManager.getUserClaimValue(username,
IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM, null);
} catch (UserStoreException e) {
String error = String.format("Error occurred while retrieving existing email address for user: %s in " +
"domain : %s", username, user.getTenantDomain());
throw new IdentityEventException(error, e);
}
if (emailAddress.equals(existingEmail)) {
if (log.isDebugEnabled()) {
log.debug(String.format("The email address to be updated: %s is same as the existing email " +
"address for user: %s in domain %s. Hence an email verification will not be " +
"triggered.", emailAddress, username, user.getTenantDomain()));
}
Utils.setThreadLocalToSkipSendingEmailVerificationOnUpdate(IdentityRecoveryConstants
.SkipEmailVerificationOnUpdateStates.SKIP_ON_EXISTING_EMAIL.toString());
invalidatePendingEmailVerification(user, userStoreManager, claims);
return;
}
/*
When 'UseVerifyClaim' is enabled, the verification should happen only if the 'verifyEmail' temporary
claim exists as 'true' in the claim list. If 'UseVerifyClaim' is disabled, no need to check for
'verifyEmail' claim.
*/
if (Utils.isUseVerifyClaimEnabled() && !isVerifyEmailClaimAvailable(claims)) {
Utils.setThreadLocalToSkipSendingEmailVerificationOnUpdate(IdentityRecoveryConstants
.SkipEmailVerificationOnUpdateStates.SKIP_ON_INAPPLICABLE_CLAIMS.toString());
invalidatePendingEmailVerification(user, userStoreManager, claims);
return;
}
claims.put(IdentityRecoveryConstants.EMAIL_ADDRESS_PENDING_VALUE_CLAIM, emailAddress);
claims.remove(IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM);
} else {
Utils.setThreadLocalToSkipSendingEmailVerificationOnUpdate(IdentityRecoveryConstants
.SkipEmailVerificationOnUpdateStates.SKIP_ON_INAPPLICABLE_CLAIMS.toString());
}
}
private void postSetUserClaimsOnEmailUpdate(User user, UserStoreManager userStoreManager) throws
IdentityEventException {
try {
String skipEmailVerificationOnUpdateState = Utils.getThreadLocalToSkipSendingEmailVerificationOnUpdate();
if (!IdentityRecoveryConstants.SkipEmailVerificationOnUpdateStates.SKIP_ON_CONFIRM.toString().equals
(skipEmailVerificationOnUpdateState) && !IdentityRecoveryConstants.
SkipEmailVerificationOnUpdateStates.SKIP_ON_EXISTING_EMAIL.toString().equals
(skipEmailVerificationOnUpdateState) && !IdentityRecoveryConstants
.SkipEmailVerificationOnUpdateStates.SKIP_ON_INAPPLICABLE_CLAIMS.toString().equals
(skipEmailVerificationOnUpdateState)) {
String pendingVerificationEmailClaimValue = getPendingVerificationEmailValue(userStoreManager, user);
if (StringUtils.isNotBlank(pendingVerificationEmailClaimValue)) {
initNotificationForEmailVerificationOnUpdate(pendingVerificationEmailClaimValue, user);
// Trigger alert to existing email.
sendNotificationToExistingEmailOnEmailUpdate(
user, userStoreManager, pendingVerificationEmailClaimValue,
IdentityRecoveryConstants.NOTIFICATION_TYPE_NOTIFY_EMAIL_ON_UPDATE);
}
}
} finally {
Utils.unsetThreadLocalToSkipSendingEmailVerificationOnUpdate();
}
}
private String getPendingVerificationEmailValue(UserStoreManager userStoreManager, User user) throws
IdentityEventException {
Map<String, String> verificationPendingEmailClaimMap;
try {
verificationPendingEmailClaimMap = userStoreManager.getUserClaimValues(user.getUserName(), new String[]{
IdentityRecoveryConstants.EMAIL_ADDRESS_PENDING_VALUE_CLAIM}, null);
} catch (UserStoreException e) {
throw new IdentityEventException("Error while retrieving verification pending email claim value for user: "
+ user.toFullQualifiedUsername(), e);
}
if (MapUtils.isEmpty(verificationPendingEmailClaimMap)) {
return null;
}
for (Map.Entry<String, String> entry : verificationPendingEmailClaimMap.entrySet()) {
String pendingVerificationEmailClaimURI = entry.getKey();
if (pendingVerificationEmailClaimURI
.equals(IdentityRecoveryConstants.EMAIL_ADDRESS_PENDING_VALUE_CLAIM)) {
return entry.getValue();
}
}
return null;
}
/**
* Invalidate pending email verification.
*
* @param user User.
* @param userStoreManager User store manager.
* @param claims User claims.
* @throws IdentityEventException
*/
private void invalidatePendingEmailVerification(User user, UserStoreManager userStoreManager,
Map<String, String> claims ) throws IdentityEventException {
if (StringUtils.isNotBlank(getPendingVerificationEmailValue(userStoreManager, user))) {
claims.put(IdentityRecoveryConstants.EMAIL_ADDRESS_PENDING_VALUE_CLAIM, StringUtils.EMPTY);
try {
UserRecoveryDataStore userRecoveryDataStore = JDBCRecoveryDataStore.getInstance();
userRecoveryDataStore.invalidate(user, RecoveryScenarios.EMAIL_VERIFICATION_ON_UPDATE,
RecoverySteps.VERIFY_EMAIL);
} catch (IdentityRecoveryException e) {
throw new IdentityEventException("Error while invalidating previous email verification data " +
"from recovery store for user: " + user.toFullQualifiedUsername(), e);
}
}
}
/**
* Check if the claims contain the temporary claim 'verifyEmail' and it is set to true.
*
* @param claims User claims.
* @return True if 'verifyEmail' claim is available as true, false otherwise.
*/
private boolean isVerifyEmailClaimAvailable(Map<String, String> claims) {
return (claims.containsKey(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM) &&
Boolean.parseBoolean(claims.get(IdentityRecoveryConstants.VERIFY_EMAIL_CLIAM)));
}
/**
* Send an email notification to existing email when a request is made to update the email address with either
* email verification on update feature enabled or not.
*
* @param user User.
* @param userStoreManager UserStoreManager.
* @param newEmailAddress The new email address provided the user to update the existing email address.
* When the email verification on update feature is enabled, this variable contains the
* verification pending email.
* @param templateType Email template type.
* @throws IdentityEventException IdentityEventException.
*/
private void sendNotificationToExistingEmailOnEmailUpdate(User user, UserStoreManager userStoreManager,
String newEmailAddress, String templateType) throws IdentityEventException {
boolean enable = Boolean.parseBoolean(Utils.getConnectorConfig(IdentityRecoveryConstants.ConnectorConfig
.ENABLE_NOTIFICATION_ON_EMAIL_UPDATE, user.getTenantDomain()));
if (!enable) {
if (log.isDebugEnabled()) {
log.debug("Notify existing email on update feature is disabled for tenant: " + user.getTenantDomain());
}
return;
}
// Get existing email address.
String existingEmail = getEmailClaimValue(user, userStoreManager);
if (StringUtils.isBlank(existingEmail) || existingEmail.equals(newEmailAddress)) {
log.debug("Old email in not available for user : " + user.toFullQualifiedUsername() + ". " +
"Terminated the notification sending process to existing email.");
return;
}
HashMap<String, String> properties = new HashMap<>();
properties.put(IdentityEventConstants.EventProperty.USER_NAME, user.getUserName());
properties.put(IdentityEventConstants.EventProperty.TENANT_DOMAIN, user.getTenantDomain());
properties.put(IdentityEventConstants.EventProperty.USER_STORE_DOMAIN, user.getUserStoreDomain());
if (IdentityRecoveryConstants.NOTIFICATION_TYPE_NOTIFY_EMAIL_ON_UPDATE.equals(templateType)) {
properties.put(IdentityRecoveryConstants.VERIFICATION_PENDING_EMAIL, newEmailAddress);
} else if (IdentityRecoveryConstants.NOTIFICATION_TYPE_NOTIFY_EMAIL_UPDATE_WITHOUT_VERIFICATION.
equals(templateType)) {
properties.put(IdentityRecoveryConstants.NEW_EMAIL_ADDRESS, newEmailAddress);
}
triggerEmailNotificationToExistingEmail(existingEmail, templateType, user, properties);
}
/**
* Get user email claim value.
*
* @param user User.
* @param userStoreManager UserStoreManager.
* @return String user email address.
* @throws IdentityRecoveryException Error retrieving email address.
*/
private String getEmailClaimValue(User user, UserStoreManager userStoreManager) throws IdentityEventException {
String email = StringUtils.EMPTY;
if (user != null && userStoreManager != null) {
String username = user.getUserName();
if (StringUtils.isNotBlank(user.getUserStoreDomain())) {
username = IdentityUtil.addDomainToName(username, user.getUserStoreDomain());
}
try {
email = userStoreManager.getUserClaimValue(username, IdentityRecoveryConstants.EMAIL_ADDRESS_CLAIM,
null);
} catch (UserStoreException e) {
String error = String.format("Error occurred while retrieving existing email address for user: " +
"%s in tenant domain : %s", username, user.getTenantDomain());
throw new IdentityEventException(error, e);
}
}
return email;
}
/**
* Trigger a notification to the existing email address when the user attempts to update the existing email
* address.
*
* @param sendTo Send to email address.
* @param templateType Email template type.
* @param user User.
* @param props Other properties.
* @throws IdentityEventException IdentityEventException while sending notification to user.
*/
private void triggerEmailNotificationToExistingEmail(String sendTo, String templateType, User user, Map<String,
String> props) throws IdentityEventException {
if (log.isDebugEnabled()) {
log.debug("Sending : " + templateType + " notification to user : " + user.toFullQualifiedUsername());
}
HashMap<String, Object> properties = new HashMap<>();
properties.put(IdentityRecoveryConstants.SEND_TO, sendTo);
properties.put(IdentityRecoveryConstants.TEMPLATE_TYPE, templateType);
if (CollectionUtils.size(props) > 0) {
properties.putAll(props);
}
Event identityMgtEvent = new Event(IdentityEventConstants.Event.TRIGGER_NOTIFICATION, properties);
try {
IdentityRecoveryServiceDataHolder.getInstance().getIdentityEventService().handleEvent(identityMgtEvent);
} catch (IdentityEventException e) {
throw new IdentityEventException("Error while sending notification for user: " +
user.toFullQualifiedUsername(), e);
}
}
/**
* To set the confirmation code to ask password thread local.
*
* @param confirmationCode Ask password confirmation code.
*/
private void setAskPasswordConfirmationCodeToThreadLocal(String confirmationCode) {
Object initialValue = IdentityUtil.threadLocalProperties.get()
.get(IdentityRecoveryConstants.AP_CONFIRMATION_CODE_THREAD_LOCAL_PROPERTY);
if (initialValue != null && initialValue.toString()
.equals(IdentityRecoveryConstants.AP_CONFIRMATION_CODE_THREAD_LOCAL_INITIAL_VALUE)) {
IdentityUtil.threadLocalProperties.get()
.put(IdentityRecoveryConstants.AP_CONFIRMATION_CODE_THREAD_LOCAL_PROPERTY,
confirmationCode);
}
}
}
|
package com.phila.samergigabyte.philabooksx;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.etsy.android.grid.StaggeredGridView;
import com.phila.samergigabyte.R;
import java.io.File;
import java.util.ArrayList;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private String attachmentPath;
private File selectedFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Utilities.openFile("*/*",0,MainActivity.this);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
booksSetup();
}
private void booksSetup() {
Net.apiClient(MainActivity.this).PDFs("",new Callback<PDFs>() {
@Override
public void success(PDFs pdFs, Response response) {
ArrayList books=new ArrayList();
for (PDFs.pdf x :pdFs.PDFs){
OnlineBook book=new OnlineBook();
book.bookUrl="79.134.150.46/PDF/uploads/pdfs/"+x.file+".pdf";
book.title=x.name;
books.add(book);
}
OnlineBooksGridAdapter adapter=new OnlineBooksGridAdapter(books,MainActivity.this);
StaggeredGridView gridView = (StaggeredGridView) findViewById(R.id.grid_view);
gridView.setAdapter(adapter);
File[] va= Utilities.getPdfFiles();
ArrayList<OfflineBook>offLibeBooks=new ArrayList<OfflineBook>();
for (int i=0;i<va.length;i++){
OfflineBook book=new OfflineBook();
book.path=va[i].getPath();
book.title=va[i].getName();
offLibeBooks.add(book);
}
StaggeredGridView gridView1 = (StaggeredGridView) findViewById(R.id.grid_view1);
OfflineBooksGridAdapter offlineBooksGridAdapter=new OfflineBooksGridAdapter(offLibeBooks,MainActivity.this);
gridView1.setAdapter(offlineBooksGridAdapter);
Utilities.setListViewHeightBasedOnChildren(gridView);
Utilities.setListViewHeightBasedOnChildren(gridView1);
}
@Override
public void failure(RetrofitError error) {
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.search) {
Intent o=new Intent(this,SearchActivity.class);
startActivity(o);
}
else if (id==R.id.logout){
((MyAppClass)getApplication()).mCurrentUser=null;
Utilities.saveUserToSharedPerff(null,MainActivity.this);
Intent o=new Intent(this,LoginActivity.class);
startActivity(o);
finish();
}
else if(id==R.id.about){
Intent o=new Intent(this,About.class);
startActivity(o);
}
else if(id==R.id.add){
Utilities.openFile("*/*",0,MainActivity.this);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (0 == requestCode) {
if (RESULT_OK == resultCode) {
attachmentPath = FileUtils.getPath(MainActivity.this, data.getData());
if (false == TextUtils.isEmpty(attachmentPath)) {
selectedFile = new File(attachmentPath);
final TypedFile typedFile = new TypedFile("multipart/form-data", new File(attachmentPath));
Net.apiClient(this).uploadPDF(typedFile, new Callback<PDF>() {
@Override
public void success(PDF s, Response response) {
if(s.PDF!=null){
Net.apiClient(MainActivity.this).savePdf(((MyAppClass) getApplicationContext()).mCurrentUser.Users.id.toString(), typedFile.fileName(), s.PDF, new Callback<Object>() {
@Override
public void success(Object o, Response response) {
Log.d("shiiiiiiiii",o.toString());
booksSetup();
}
@Override
public void failure(RetrofitError error) {
}
});
}
}
@Override
public void failure(RetrofitError error) {
Log.d("lol", error.toString());
}
});
} else {
attachmentPath = null;
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
|
package com.zhicai.byteera.activity.traincamp.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.zhicai.byteera.R;
import com.zhicai.byteera.activity.bean.GuessSmallMissionInfo;
import com.zhicai.byteera.commonutil.Constants;
import com.zhicai.byteera.commonutil.ViewHolder;
import java.util.List;
@SuppressWarnings("unused")
public class GuessMissionListAdapter extends BaseAdapter{
public static final String TAG = GuessMissionListAdapter.class.getSimpleName();
private Context mContext;
private List<GuessSmallMissionInfo> list = null;
public GuessMissionListAdapter(Context context, List<GuessSmallMissionInfo> list) {
this.list = list;
this.mContext = context;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_guess_mission_item, parent, false);
}
RelativeLayout rel_unlock = ViewHolder.get(convertView, R.id.rel_unlock); //解锁
RelativeLayout rel_lock = ViewHolder.get(convertView, R.id.rel_lock); //加锁
ImageView img_locked = ViewHolder.get(convertView, R.id.img_locked);
TextView tv_position = ViewHolder.get(convertView,R.id.tv_position);
//TODO 记录当前的状态
TextView tv_missionstatus = ViewHolder.get(convertView,R.id.tv_missionstatus);
GuessSmallMissionInfo guessEntity = list.get(position);
tv_position.setText(guessEntity.getGridviewid()+"");
tv_missionstatus.setText(guessEntity.getMissionstatus() + "");
//TODO 后期要加数据库对其进行判断才行
switch(guessEntity.getMissionstatus()){
case Constants.MISSION_LOCKED: //0
rel_lock.setVisibility(View.VISIBLE);
break;
case Constants.MISSION_PASSED: //1
rel_unlock.setVisibility(View.VISIBLE);
break;
case Constants.MISSION_FAILED: //2
//TODO 保存数据库
break;
}
return convertView;
}
@Override
public int getItemViewType(int position) {
return AdapterView.ITEM_VIEW_TYPE_IGNORE;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int arg0) {
return list.get(arg0);
}
@Override
public long getItemId(int position) {
return position;
}
}
|
package study01;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(args[0]);
System.out.println(args[1]);
/*
1000, 1001번
scanner 함수가 기억나지 않았을 때는 웹 화면에서 입력 받은 숫자를 받아와서 계산하는 방법을 생각함.
더하기 빼기는 쉽지만 어떻게 숫자를 입력 받을 건지?? Scanner 사용은 검색해서 적용함.
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println("a+b="+(a+b)+", a-b="+(a-b));
1002번... 터렛?...
무슨 소리인지 하나도 모르겠다 사진도 뭔지 모르겠고.. 이럴때는 블로그 같은 것을 찾아봐야하나?
1003번
0과 1이 각각 몇 번 출력되는지 구하는 프로그램. 리턴 값을 받아서 변수 a,b를 1씩 증가시키면 되는 거 같은데..
fibo() -> 0,1,1,2,3,5,8,13,21.... 만들어 놓은 함수에서 0,1 리턴을 .. 어떻게 사용?해야하는지..
*/
// 전체 문제를 순서대로 푸는 것이 어려워서 단계별로 푸는 문제에서 알고리즘 풀이를 시작함..
// 2839번
/*문제내용
* 설탕을 정확하게 N킬로그램을 배달. 봉지는 3킬로그램 봉지와 5킬로그램 봉지가 있다. 최대한 적은 봉지들기.
* 18kg 설탕을 배달해야 할 때, 5kg 3개와 3kg 1개를 배달
* 11kg 설탕을 배달해야 할 때, 5kg 1개와 3kg 2개를 배달
* 봉지의 최소 개수를 출력한다. 만약, 정확하게 N킬로그램을 만들 수 없다면 -1을 출력
*
*생각한 풀이
* '/'랑 '%' 사용해서 몫을 저장하고 그걸 더하면 봉지 수를 구할 수 있겠다.
* 5로 나눈 나머지를 3으로 나눠서 나온 나머지의 값이 0이면 5로 나눈 몫을 a에 저장하고 , 5로 나누어 떨어졌을 때도 a에 저장됨.
* 5로 나눴을 때 나머지를 3으로 나눈 몫을 b에 저장한다. >> a+b를 하면 봉지 수 를 구할 수 있다..
* 문제를 제대로 이해하지 못해서 아래 주석처리 해 놓은 코드를 작성함.. 11kg이 왜 3봉지 인지 처음엔 생각도 못하고;
*
* 3<=N<=5000
*
* 3 / 1 (3*1)
* 4 / -1
* 5 / 1 (5*1)
* 6 / 2 (3*2)
* 7 / -1
* 8 / 2 (5*1,3*1)
* 9 / 3 (3*3)
* 10 / 2 (5*2)
* 11 / 3 (5*1,3*2)
* 12 / 4 (3*4)
* 13 / 3 (5*2,3*1)
* 14 / 4 (5*1,3*3)
* 15 / 3 (5*3)
* 16 / 4 (5*2,3*2)
* 17 / 5 (5*1,3*4)
* 18 / (5*3,3*1)
* 19 / 5 (5*2,3*3)
* 26 / 8 (5*1,3*7)
* */
int n = scanner.nextInt();
int a=0,b=0;
// 5로 나누어 떨어지거나 3으로 나누어 떨어지는 경우는 몫이 봉지수가 될 수 있을 것 같다.
// for문을...써서 해본다면 ? i는 몇까지 줘야하나? 1000정도..?
if(n%5==0 || n%3==0){
// n을 5나 3으로 나눴을 때 몫이 큰 경우를 찾는다?
if(!(n%5==0)){ // 5로 나눴을 때 나머지가 있으면 3으로 나누면 될 것 같다
System.out.println("n/3 = "+n/3);
}else{System.out.println("n/5 = "+n/5);}
} else{
for (n = 3; n < 20; n++) {
boolean isOut = false;
for(int i=1;i<=n / 5;i++){
for(int j=1;j<=n / 3;j++){
if((5*i)+(3*j)==n){
System.out.println("i="+i+",j="+j+"-> i+j ="+(i+j));
isOut = true;
break; // continue, break 사용 할 때.. 개념? 알아봐야 함.
}
}
if (isOut == true) {
break;
}
}
// 위 조건을 타면 -1을 출력 안하고 싶은데 그럼 어떻게 조건을 줘야 할지.. ?
if (isOut == false) {
System.out.println("n=" + n);
}
}
}
/*if((n%5)%3==0){ // 5로 나눈 나머지를 3으로 나눠서 나온 나머지의 값이 0이면
a = n/5; // 5로 나눈 몫을 a에 저장하고 , 5로 나누어 떨어졌을 때도 걸러지고...
b = (n%5)/3; // 5로 나눴을 때 나머지를 3으로 나눈 몫을 b에 저장한다
System.out.println(a+b);
}else if(n%3==0){ // 3으로 나누어 떨어지면 3kg짜리 봉지만 가져가면 되니깐...
System.out.println(n/3);
}else{
System.out.println("-1");
}*/
}
// 1003문제에 있던 피보나치 함수...
public static int fibo(int x) {
if(x==0) {
System.out.print("0, ");
return 0;
}else if(x==1){
System.out.print("1, ");
return 1;
}else {
System.out.println("x ::"+x);
System.out.println("x-1 ="+(x-1)+" // x-2 ="+(x-2));
return fibo(x-1)+fibo(x-2);
}
}
}
|
/*
* Copyright © 2020-2022 ForgeRock AS (obst@forgerock.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 com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.account;
import uk.org.openbanking.datamodel.account.OBExternalProductType1Code;
import uk.org.openbanking.datamodel.account.OBProduct1;
import uk.org.openbanking.datamodel.account.OBReadProduct2DataProduct;
public class FRProductConverter {
public static OBProduct1 toOBProduct1(OBReadProduct2DataProduct product) {
OBProduct1 product1 = new OBProduct1()
.accountId(product.getAccountId())
.productName(product.getProductName())
.productIdentifier(product.getProductId())
.secondaryProductIdentifier(product.getSecondaryProductId());
switch (product.getProductType()) {
case BUSINESSCURRENTACCOUNT:
product1.setProductType(OBExternalProductType1Code.BCA);
break;
case PERSONALCURRENTACCOUNT:
product1.setProductType(OBExternalProductType1Code.PCA);
}
return product1;
}
}
|
package com.itea.java.basic.l14.linked;
public class MyLinkedList implements MyList {
private MyLinkedListElement first;
private MyLinkedListElement last;
public void add(Integer elem) {
if (first == null) {
MyLinkedListElement myLinkedListElement = new MyLinkedListElement(null, null, elem);
first = myLinkedListElement;
last = first;
} else {
MyLinkedListElement myLinkedListElement = new MyLinkedListElement(last, null, elem);
last.next = myLinkedListElement;
last = myLinkedListElement;
}
}
public Integer get(int index) {
checkIndex(index);
if (size() == 1) {
return first.value;
}
MyLinkedListElement tmp = first;
for (int i = 0; i < index; i++) {
tmp = tmp.next;
}
//
// while (index-- > 0) {
// tmp = tmp.next;
// }
return tmp.value;
}
private void checkIndex(int index) {
if (size() < index) {
throw new IllegalArgumentException("Index exceeds size!");
}
if (index < 0) {
throw new IllegalArgumentException("Index < 0!");
}
}
public int size() {
if (isEmpty()) {
return 0;
}
MyLinkedListElement tmp = first;
int counter = 1;
while (tmp.next != null) {
tmp = tmp.next;
counter++;
}
return counter;
}
public boolean isEmpty() {
return first == null;
}
public void remove(Integer elem) {
}
public void add(int index, Integer elem) {
}
public MyIterator iterator() {
return new MyLinkedListIterator();
}
private class MyLinkedListIterator implements MyIterator {
private MyLinkedListElement cursor;
public MyLinkedListIterator() {
if (!isEmpty()) {
cursor = first;
}
}
public boolean hasNext() {
return cursor.next != null;
}
public Integer next() {
Integer result = cursor.value;
cursor = cursor.next;
return result;
}
}
private class MyLinkedListElement {
private MyLinkedListElement previous;
private MyLinkedListElement next;
private int value;
public MyLinkedListElement(MyLinkedListElement previous, MyLinkedListElement next, int value) {
this.previous = previous;
this.next = next;
this.value = value;
}
public void setPrevious(MyLinkedListElement previous) {
this.previous = previous;
}
public void setNext(MyLinkedListElement next) {
this.next = next;
}
public void setValue(int value) {
this.value = value;
}
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.orm.domain;
import xyz.noark.core.annotation.orm.Column;
import xyz.noark.core.annotation.orm.Entity;
import xyz.noark.core.annotation.orm.Id;
/**
* 道具实体测试类.
*
* @author 小流氓[176543888@qq.com]
* @since 3.2
*/
@Entity
public class Item {
@Id
@Column(name = "ID")
private int id;
private String name;
private int templateId;
private int grinning;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTemplateId() {
return templateId;
}
public void setTemplateId(int templateId) {
this.templateId = templateId;
}
public int getGrinning() {
return grinning;
}
public void setGrinning(int grinning) {
this.grinning = grinning;
}
}
|
<<<<<<< HEAD
package in.vamsoft.excersise1.shape1;
public class RectangleTest {
/**
* The main method.
* @param args LOGIN - login of user PASSWORD - password
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
Rectangle r = new Rectangle(10 * Math.random(), 20 * Math.random());
System.out.println(r);
}
}
=======
package in.vamsoft.excersise1.shape1;
public class RectangleTest {
public static void main(String[] args) {
for(int i=0; i<10; i++) {
Rectangle r =
new Rectangle(10*Math.random(), 20*Math.random());
System.out.println(r);
}
}
>>>>>>> 35b1b732e68ed3b6596b2e23d9ec90c62220f54e
}
|
package sr.hakrinbank.intranet.api.service.bean;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import sr.hakrinbank.intranet.api.model.Interest;
import sr.hakrinbank.intranet.api.repository.InterestRepository;
import sr.hakrinbank.intranet.api.service.InterestService;
import sr.hakrinbank.intranet.api.util.Constant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by clint on 6/15/17.
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class InterestServiceBean implements InterestService {
@Autowired
private InterestRepository interestRepository;
@Override
@PostFilter("filterObject.deleted() == false")
public List<Interest> findAllInterest() {
return interestRepository.findAll();
}
@Override
public Interest findById(long id) {
return interestRepository.findOne(id);
}
@Override
public void updateInterest(Interest interest) {
if(interest.getDate() == null){
interest.setDate(new Date());
interestRepository.save(interest);
}else{
interestRepository.save(interest);
}
}
@Override
public List<Interest> findAllActiveInterestOrderedByDate() {
return interestRepository.findActiveInterestOrderedByDate();
}
@Override
public List<Interest> findAllActiveInterestBySearchQueryOrDate(String byTitle, String byDate) {
if(byDate != null && !byDate.isEmpty() && byDate != "" && !byDate.contentEquals(Constant.UNDEFINED_VALUE) && !byDate.contentEquals(Constant.NULL_VALUE) && !byDate.contentEquals(Constant.INVALID_DATE)){
LocalDate localDate = LocalDate.parse(byDate, DateTimeFormatter.ofPattern(Constant.DATE_FIELD_FORMAT));
LocalDateTime todayStartOfDay = localDate.atStartOfDay();
Date startOfDay = Date.from(todayStartOfDay.atZone(ZoneId.systemDefault()).toInstant());
LocalDateTime todayEndOfDay = localDate.atTime(LocalTime.MAX);
Date endOfDay = Date.from(todayEndOfDay.atZone(ZoneId.systemDefault()).toInstant());
if(byTitle != null && byTitle != "" && !byTitle.contentEquals(Constant.UNDEFINED_VALUE)){
return interestRepository.findAllActiveInterestBySearchQueryAndDate(byTitle, startOfDay, endOfDay);
}else{
return interestRepository.findAllActiveInterestByDate(startOfDay, endOfDay);
}
}else {
return interestRepository.findAllActiveInterestBySearchQuery(byTitle);
}
}
@Override
public int countInterestOfTheWeek() {
List<Interest> interestList = interestRepository.findActiveInterest();
DateTime currentDate = new DateTime();
int weekOfCurrentDate = currentDate.getWeekOfWeekyear();
int yearOfCurrentDate = currentDate.getYear();
List<Interest> countList = new ArrayList<>();
DateTime specificDate;
int weekOfSpecificDate;
int yearOfSpecificDate;
for(Interest interest: interestList){
specificDate = new DateTime(interest.getDate());
weekOfSpecificDate = specificDate.getWeekOfWeekyear();
yearOfSpecificDate = specificDate.getYear();
if( (yearOfCurrentDate == yearOfSpecificDate) && (weekOfCurrentDate == weekOfSpecificDate) ){
countList.add(interest);
}
}
return countList.size();
}
@Override
public List<Interest> findAllActiveInterest() {
return interestRepository.findActiveInterest();
}
@Override
public Interest findByName(String name) {
return interestRepository.findByName(name);
}
@Override
public List<Interest> findAllActiveInterestBySearchQuery(String qry) {
return interestRepository.findAllActiveInterestBySearchQuery(qry);
}
}
|
package learn.java.proxy.cglib;
public class Test {
public static void main(String[] args) {
AliSmsService proxy = (AliSmsService) CglibProxyFactory.getProxy(AliSmsService.class);
proxy.send("java");
}
}
|
import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
/**
*
*
* @author Kevin Hartman <kfh6034@rit.edu>
*/
public abstract class Employee extends Thread {
protected final Employee supervisor;
private ConcurrentLinkedQueue<Runnable> activeTaskQueue = new ConcurrentLinkedQueue<Runnable>();
private Scheduler scheduler;
private final Object newItemLock = new Object();
private final Semaphore binarySemaphore = new Semaphore(1);
private final Semaphore blockProcessing = new Semaphore(1);
private final Object advancingLock = new Object();
private boolean isBlocking = false;
// Runnables
final protected Runnable askQuestion = new Runnable() {
@Override
public void run() {
if (supervisor == null) return;
//Employee.this.lockProcessing();
if (supervisor.registerSpontaneousTask(new Runnable() {
@Override
public void run() {
Stack<Employee> callStack = new Stack<Employee>();
callStack.add(Employee.this);
supervisor.askQuestion(callStack);
}
})) {
Employee.this.onQuestionAsked(Employee.this.supervisor);
} else {
Employee.this.onQuestionCancelled(Employee.this.supervisor);
//unlockProcessing();
}
synchronized (advancingLock) { try {
advancingLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
};
protected abstract void onQuestionCancelled(Employee notAvailable);
// TODO: This isn't done- it's just an example
final protected Runnable goToLunch = new Runnable() {
@Override
public void run() {
try {
Random rand = new Random();
Thread.sleep((long)(300+300*rand.nextDouble()));
} catch (InterruptedException e) {
}
}
};
public Employee(Scheduler scheduler, Employee supervisor) {
this.scheduler = scheduler;
this.supervisor = supervisor;
}
protected abstract void initRunnables();
protected boolean canAnswerQuestion() {
return new Random().nextBoolean();
}
final public void askQuestion(final Stack<Employee> relayedFrom) {
Employee.this.onQuestionAsked(supervisor);
if (supervisor == null || canAnswerQuestion()) {
relayedFrom.peek().resumeWithAnswer(new Runnable() { //TODO: double check for bugs
@Override
public void run() {
relayedFrom.pop().listenToAnswer(relayedFrom);
}
});
return;
}
// Employee.this.lockProcessing();
supervisor.registerSpontaneousTask(new Runnable() {
@Override
public void run() {
relayedFrom.push(Employee.this);
supervisor.askQuestion(relayedFrom);
}
});
Employee.this.onQuestionAsked(supervisor);
synchronized (advancingLock) { try {
advancingLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
final public void listenToAnswer(final Stack<Employee> relayTo) {
onAnswerReceived(this.supervisor);
if (relayTo.peek() == null) return;
relayTo.peek().resumeWithAnswer(new Runnable() {
@Override
public void run() {
relayTo.pop().listenToAnswer(relayTo);
}
});
}
final public boolean enqueueTask(Runnable newActiveTask, boolean lastTask) {
// TODO: check to see if we can enqueue
try {
binarySemaphore.acquire();
} catch (InterruptedException e) {
System.err.println("The scheduler thread has been unexpectedly interrupted.");
return false;
}
synchronized (newItemLock) {
try {
activeTaskQueue.offer(newActiveTask);
binarySemaphore.release();
newItemLock.notify();
} catch (Throwable t) {
System.err.println("Someone attempted to schedule a null task.");
return false;
}
}
return true;
}
protected abstract void onQuestionAsked(Employee askedTo);
protected abstract void onAnswerReceived(Employee receivedFrom);
final public boolean registerSpontaneousTask(Runnable r) {
return scheduler.registerEvent(r, this, 10, false);
}
final public void resumeWithAnswer(Runnable answer) {
try {
binarySemaphore.acquire();
} catch (Exception e) {
System.err.println("The scheduler thread has been unexpectedly interrupted.");
return;
}
ConcurrentLinkedQueue<Runnable> queueBackup = new ConcurrentLinkedQueue<Runnable>();
while (!activeTaskQueue.isEmpty()) {
queueBackup.offer(activeTaskQueue.poll());
}
enqueueTask(answer, false);
while (!queueBackup.isEmpty()) {
enqueueTask(queueBackup.poll(), false);
}
synchronized (this.advancingLock) {
this.advancingLock.notify();
}
}
protected abstract void registerDaysEvents(Scheduler scheduler);
final public void run() {
try {
while (true) {
boolean mustRelease = false;
while (!activeTaskQueue.isEmpty()) {
activeTaskQueue.poll().run();
binarySemaphore.acquire();
if (activeTaskQueue.size() == 0) {
mustRelease = true;
break;
}
binarySemaphore.release();
}
synchronized (newItemLock) {
if (mustRelease) binarySemaphore.release();
newItemLock.wait();
}
}
} catch (InterruptedException e) {
// Day is over. Run will now terminate automatically
System.out.println("TEST: Thread interrupted successfully.");
}
}
final private void lockProcessing() {
if (isBlocking) return;
try {
blockProcessing.acquire();
isBlocking = true;
} catch (InterruptedException e) {
System.err.println("Could not block employee processing.");
}
}
final private void unlockProcessing() {
if (!isBlocking) return;
blockProcessing.release();
}
public Employee getSupervisor() {
return this.supervisor;
}
}
|
package com.proxiad.games.extranet.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum MandatoryParameter {
INIT_TIMER_SECONDS("INIT_TIME", "3600", ParameterType.NUMBER, null),
AUDIO_BACKGROUND_DEFAULT_VOLUME("AUDIO_BACKGROUND_DEFAULT_VOLUME", "10", ParameterType.NUMBER, null),
PROGRESS_BAR_DURATION("PROGRESS_BAR_DURATION", "300", ParameterType.NUMBER, null),
PROGRESS_BAR_SYNTHESIS("PROGRESS_BAR_SYNTHESIS", "true", ParameterType.BOOLEAN, null),
TERMINAL_MINIMUM_LOCK_TIME("TERMINAL_MINIMUM_LOCK_TIME", "30", ParameterType.NUMBER, null),
TERMINAL_MAXIMUM_LOCK_TIME("TERMINAL_MAXIMUM_LOCK_TIME", "60", ParameterType.NUMBER, null),
TERMINAL_LOCK_TIME_STEP("TERMINAL_LOCK_TIME_STEP", "10", ParameterType.NUMBER, null),
TROLL_DECREASE_TIME("TROLL_DECREASE_TIME", "120", ParameterType.NUMBER, null),
TERMINAL_TERMINATOR_COMMAND_RESPONSE("TERMINAL_TERMINATOR_COMMAND_RESPONSE", "...", ParameterType.FIELDSET, "terminal-style")
;
private String key;
private String defaultValue;
private ParameterType type;
private String optionals;
}
|
package registration;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Optional;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import util.EvaluatedExpression;
import util.RegistrationExpression;
public class ListItem extends JPanel {
private String time;
private HashMap<ListItem, String> map;
private Subscriber sub;
private String faultyStartNumber;
public ListItem(String time, HashMap<ListItem, String> map, Subscriber sub, String faultyStartNumber) {
this.time = time;
this.faultyStartNumber = faultyStartNumber;
this.map = map;
this.sub = sub;
this.setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
JLabel timeLabel = new JLabel("Tid: " + time);
timeLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
timeLabel.setFont(new Font("Arial", Font.PLAIN, 34));
if(faultyStartNumber.length() != 0){
timeLabel.setForeground(Color.RED);}
JButton editButton = new JButton("Edit");
editButton.addActionListener(new EditButtonListener());
JButton removeButton = new JButton("Remove");
removeButton.setName("removeButton");
removeButton.addActionListener(new RemoveButtonListener());
this.add(timeLabel);
JPanel componentSeparator = new JPanel();
componentSeparator.setMaximumSize(new Dimension(10, 10));
this.add(componentSeparator);
this.add(editButton);
this.add(componentSeparator);
this.add(removeButton);
}
public String getText() {
return time;
}
private class EditButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String message = "skriv startnumret: ";
if(faultyStartNumber.length() != 0){
message = "Felaktig input! Du skrev: " + faultyStartNumber + "\nskriv startnumret/intervallet: ";
}
Optional<String> s = Optional.ofNullable((String)JOptionPane.showInputDialog(message));
if(s.isPresent()){
EvaluatedExpression evalTuple = RegistrationExpression.eval(s.get().trim());
if(evalTuple.errorList.isEmpty()) {
for(String correct : evalTuple.evaluatedNbrs) {
map.put(ListItem.this, correct+"; " + time);
sub.update();
}
for(String correct : evalTuple.evaluatedClasses) {
map.put(ListItem.this, correct+"; " + time);
sub.update();
}
return;
}
JOptionPane.showMessageDialog(ListItem.this.getParent(),
"Felaktig input.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
private class RemoveButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
map.remove(ListItem.this);
sub.update();
}
}
}
|
package com.zhaojun.io;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;
/**
* @auther zhaojun0193
* @create 2017/9/23
*/
public class NioClient {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel channel = null;
try{
channel = SocketChannel.open();
//开启异步
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("localhost",8888));
if(channel.finishConnect()){
int i = 0;
while (true){
TimeUnit.SECONDS.sleep(1);
String info = "I'm "+i+++"-th information from client";
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
while (buffer.hasRemaining()){
System.out.println(buffer);
channel.write(buffer);
}
}
}
}catch (IOException e){
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
try {
if(channel != null){
channel.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
}
|
package me.ivt.com.ui.cusbehavior;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class CusBehavior extends CoordinatorLayout.Behavior<View> {
public CusBehavior() {
}
public CusBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* @param parent coorinator
* @param child 观察者
* @param dependency 被观察者
* @return
*/
@Override
public boolean layoutDependsOn(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
return dependency instanceof TextView || super.layoutDependsOn(parent, child, dependency);
}
/**
* 被监听的view发生改变的时候的回调
*
* @param parent
* @param child
* @param dependency
* @return
*/
@Override
public boolean onDependentViewChanged(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull View dependency) {
//获取被监听view的状态
int offset = dependency.getTop() - child.getTop();
//让view 进行平移
ViewCompat.offsetTopAndBottom(child, offset);
return true;
}
}
|
package com.cqut.model;
import java.util.Date;
public class ChargeDetail {
private String chargedetailid;
private String userid;
private Long money;
private Date starttime;
private Date endtime;
public String getChargedetailid() {
return chargedetailid;
}
public void setChargedetailid(String chargedetailid) {
this.chargedetailid = chargedetailid == null ? null : chargedetailid.trim();
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid == null ? null : userid.trim();
}
public Long getMoney() {
return money;
}
public void setMoney(Long money) {
this.money = money;
}
public Date getStarttime() {
return starttime;
}
public void setStarttime(Date starttime) {
this.starttime = starttime;
}
public Date getEndtime() {
return endtime;
}
public void setEndtime(Date endtime) {
this.endtime = endtime;
}
}
|
package easii.com.br.iscoolapp.fragmentos;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import easii.com.br.iscoolapp.R;
import easii.com.br.iscoolapp.adapters.DesafioAdapter;
import easii.com.br.iscoolapp.graficos.MediaDoAluno;
import easii.com.br.iscoolapp.objetos.Desafio;
import easii.com.br.iscoolapp.util.DividerItemDecoration;
import easii.com.br.iscoolapp.util.RecyclerItemClickListener;
/**
* Created by gustavo on 01/05/2017.
*/
public class DesafioFragment extends Fragment {
private List<Desafio> desafios = new ArrayList<>();
private View view;
private RecyclerView recyclerView;
private DesafioAdapter mAdapter;
public DesafioFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_desafio, container, false);
desafios.add(new Desafio("Maior nota", 2, "Gustavo e joao"));
desafios.add(new Desafio("Maior nota da sala", 2, "Gustavo , pedro , mao santa"));
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
mAdapter = new DesafioAdapter(desafios);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(view.getContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(view.getContext(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(view.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
}
})
);
mAdapter.notifyDataSetChanged();
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
return view;
}
}
|
package com.SearchHouse.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.SearchHouse.mapper.PriceContainsMapper;
import com.SearchHouse.pojo.PriceContain;
import com.SearchHouse.service.PriceContainsService;
@Service
@Transactional
public class PriceContainsServiceImpl implements PriceContainsService {
@Resource
PriceContainsMapper priceContainsMapper;
public PriceContainsMapper getPriceContainsMapper() {
return priceContainsMapper;
}
public void setPriceContainsMapper(PriceContainsMapper priceContainsMapper) {
this.priceContainsMapper = priceContainsMapper;
}
@Override
public void addPri(PriceContain priceContain) {
// TODO Auto-generated method stub
priceContainsMapper.addPri(priceContain);
}
@Override
public void deletePri(int houseId) {
// TODO Auto-generated method stub
priceContainsMapper.deletePri(houseId);
}
}
|
package edu.cricket.api.cricketscores.rest.source.model;
import java.util.List;
public class LeagueSeasonGroupStanding {
private Ref team;
private List<LeagueSeasonGroupStandingRecord> records;
public Ref getTeam() {
return team;
}
public void setTeam(Ref team) {
this.team = team;
}
public List<LeagueSeasonGroupStandingRecord> getRecords() {
return records;
}
public void setRecords(List<LeagueSeasonGroupStandingRecord> records) {
this.records = records;
}
}
|
package ua.siemens.dbtool.serializers.WorkPackageType;
import com.google.gson.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import ua.siemens.dbtool.model.auxilary.WorkPackageType;
import ua.siemens.dbtool.model.entities.Project;
import java.lang.reflect.Type;
/**
* The class is custom deserializer for {@link WorkPackageType}
*
* @author Perevoznyk Pavlo
* creation date 17 Jan 2018
* @version 1.0
*/
@Component
public class WorkPackageTypeDeserializer implements JsonDeserializer<WorkPackageType> {
private static final Logger LOG = LoggerFactory.getLogger(WorkPackageTypeDeserializer.class);
public WorkPackageTypeDeserializer() {
}
/**
* The method deserializes wpType.
*
* @return wpType instance with ID PROPERTY ONLY
*/
@Override
public WorkPackageType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
LOG.debug(">> deserialize()");
JsonObject wpTypeJson = json.getAsJsonObject();
WorkPackageType wpType = new WorkPackageType();
JsonElement jsonId = wpTypeJson.get("id");
if (!jsonId.isJsonNull()) {
wpType.setId(jsonId.getAsLong());
}
wpType.setName(wpTypeJson.get("name").getAsString());
wpType.setHasFactHours(wpTypeJson.get("hasFactHours").getAsBoolean());
wpType.setHasHoursBudget(wpTypeJson.get("hasHoursBudget").getAsBoolean());
wpType.setReported(wpTypeJson.get("isReported").getAsBoolean());
wpType.setWp(wpTypeJson.get("isWp").getAsBoolean());
JsonElement projectId = wpTypeJson.get("projectId");
if (projectId != null && !projectId.isJsonNull()) {
Project project = new Project();
project.setId(projectId.getAsLong());
wpType.setProject(project);
}
LOG.debug("<< deserialize()");
return wpType;
}
}
|
package com.lenovohit.hwe.treat.web.his;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.lenovohit.core.utils.JSONUtils;
import com.lenovohit.core.web.MediaTypes;
import com.lenovohit.core.web.utils.Result;
import com.lenovohit.core.web.utils.ResultUtils;
import com.lenovohit.hwe.org.web.rest.OrgBaseRestController;
import com.lenovohit.hwe.treat.model.Pacs;
import com.lenovohit.hwe.treat.service.HisPacsService;
import com.lenovohit.hwe.treat.transfer.RestEntityResponse;
import com.lenovohit.hwe.treat.transfer.RestListResponse;
//化验明细
@RestController
@RequestMapping("/hwe/treat/his/pacs")
public class PacsHisController extends OrgBaseRestController {
@Autowired
private HisPacsService hisPacsService;
// Pacs列表查询
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value = "data", defaultValue = "") String data) {
try {
Pacs model = JSONUtils.deserialize(data, Pacs.class);
RestListResponse<Pacs> response = this.hisPacsService.findList(model, null);
// return ResultUtils.renderFailureResult("hahahah");
if(response.isSuccess()){
return ResultUtils.renderSuccessResult(response.getList());
}else{
return ResultUtils.renderFailureResult(response.getMsg());
}
} catch (Exception e) {
log.error("\n======== forList Failure End ========\nmsg:\n"+e.getMessage());
return ResultUtils.renderFailureResult(e.getMessage());
}
}
// Pacs明细查询
@RequestMapping(value = "/info", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forDetail(@RequestParam(value = "data", defaultValue = "") String data) {
try {
Pacs model = JSONUtils.deserialize(data, Pacs.class);
RestEntityResponse<Pacs> response = this.hisPacsService.getInfo(model, null);
// return ResultUtils.renderFailureResult("aaaa");
if(response.isSuccess())
return ResultUtils.renderSuccessResult(response.getEntity());
else
return ResultUtils.renderFailureResult(response.getMsg());
} catch (Exception e) {
log.error("\n======== forList Failure End ========\nmsg:\n"+e.getMessage());
return ResultUtils.renderFailureResult(e.getMessage());
}
}
}
|
package com.example.reminiscence;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.List;
public class GalleryShowActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter RvGalleryAdapter;
RecyclerView.LayoutManager layoutmanager;
GalleryViewModelClass myViewModel;
//String[] personNameList = {"nieta", "nieto", "amiga1", "amigo2", "brad"};
//int[] personPhoto = {R.drawable.nieta, R.drawable.nieto, R.drawable.amiga1, R.drawable.amigo2, R.drawable.brad};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_names);
recyclerView = findViewById(R.id.rvGallery);
recyclerView.setHasFixedSize(true);
layoutmanager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutmanager);
final GalleryRvAdapter adapter = new GalleryRvAdapter();
recyclerView.setAdapter(adapter);
myViewModel = new ViewModelProvider(this).get(GalleryViewModelClass.class);
myViewModel.getAllPhotos().observe(this, new Observer<List<PhotoName>>() {
@Override
public void onChanged(List<PhotoName> models) {
adapter.submitList(models);
}
});
//RvGalleryAdapter = new RvGalleryAdapter(this, personNameList, personPhoto );
//recyclerView.setAdapter(RvGalleryAdapter);
}
}
|
package liza.weatherappdlc.Api;
import liza.weatherappdlc.Models.CurrentWeather;
import liza.weatherappdlc.Models.WeatherForecast;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface ApiService {
String currentWeatherUrlPath = "/data/2.5/weather?units=imperial";
String forecastWeatherUrlPath = "/data/2.5/forecast?units=imperial";
@GET(currentWeatherUrlPath)
Call<CurrentWeather> getJsonCurrentWeather(@Query("lat") double latitude, @Query("lon") double longitude, @Query("appid")String appID);
@GET(forecastWeatherUrlPath)
Call<WeatherForecast> getJsonWeatherForecast(@Query("lat") double latitude, @Query("lon") double longitude, @Query("appid") String appID);
}
|
/**
* **************************************************************************
* *
* OpenNI 1.x Alpha *
* Copyright (C) 2011 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* OpenNI is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* OpenNI is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with OpenNI. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************
*/
package com.lifespeedtechnologies.OpenTracker;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import org.OpenNI.GeneralException;
public class OpenTrackerDemoUI {
/**
*
*/
public OpenTrackerDemo viewer;
private JFrame frame;
public OpenTrackerDemoUI ( JFrame frame ) {
this.frame = frame;
}
public static void main ( String s[] ) {
JFrame f = new JFrame( "OpenNI User Tracker" );
f.addWindowListener( new WindowAdapter() {
public void windowClosing ( WindowEvent e ) {
System.exit( 0 );
}
} );
OpenTrackerDemoUI app = new OpenTrackerDemoUI( f );
app.viewer = new OpenTrackerDemo();
app.viewer.skel.setVisible( true );
app.viewer.vid.setVisible( true );
app.viewer.ni.setVisible( true );
f.add( app.viewer.skel, "West" );
f.add( app.viewer.vid, "Center" );
f.add( app.viewer.ni, "East" );
f.pack();
f.setVisible( true );
f.addKeyListener( app.viewer.hw );
app.run();
}
void run () {
while ( viewer.shouldRun ) {
try {
viewer.update();
} catch ( GeneralException ex ) {
Logger.getLogger( OpenTrackerDemoUI.class.getName() ).
log( Level.SEVERE, null, ex );
}
}
frame.dispose();
}
}
|
/*
* And the password is strong enough (has one capital letter and one number)
*
*
*/
package Regex;
/**
*
* @author YNZ
*/
public class PasswordValidate {
public static void main(String[] args) {
String pwd0 = "dell";
String pwd1 = "Q343433rtfg9_";
String pwd2 = "19GDddss";
String pwd3 = "2017Well";
String pwd4 = "Well2017";
String pwd5 = "W1212qwerty1212";
String pwd6 = "aasddW12121212";
//String regx = "^(?=(.*\\d){1})(.*\\S)(?=.*[A-Z\\S])[a-z\\S]{3,}";
//String regx = "((?=.*\\d)(?=.*[a-z_])(?=.*[A-Z])(.{8,}))";
String regx = "^((?=.*\\d)(?=.*[a-z_])(?=.*[A-Z])(.{8,}))$";
//String regx = "([\\d]+)([a-z]+)([A-Z]+)(.{8,})";
//String regx = "([A-Z]+)([\\d]+)([a-z]*)(.{8,})";
System.out.println(pwd0.matches(regx));
System.out.println(pwd1.matches(regx));
System.out.println(pwd2.matches(regx));
System.out.println(pwd3.matches(regx));
System.out.println(pwd4.matches(regx));
System.out.println(pwd5.matches(regx));
System.out.println(pwd6.matches(regx));
}
}
|
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
/*
* 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.
*/
/**
*
* @author a80052136
*/
public class SenderDA {
private Connection conn;
public boolean save(Sender s) {
Statement stmt = null;
try {
conn = MySQLDBConnection.getConnection();
stmt = conn.createStatement();
String sql = "INSERT INTO sender(username, email, password) VALUES ('" +
s.getUsername() + "', '" + s.getEmail() + "', '" +
s.getPassword() + "')";
stmt.executeUpdate(sql);
stmt.close();
return true;
}
catch (SQLException se) {
se.printStackTrace();
return false;
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
catch (SQLException se) {
se.printStackTrace();
return false;
}
return true;
}
}
public boolean remove(String username, String email) {
Statement stmt = null;
try {
conn = MySQLDBConnection.getConnection();
stmt = conn.createStatement();
String sql = "DELETE FROM sender WHERE email='" +
email + "' AND username='" + username + "'";
stmt.executeUpdate(sql);
stmt.close();
return true;
}
catch (SQLException se) {
se.printStackTrace();
return false;
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
catch (SQLException se) {
se.printStackTrace();
return false;
}
return true;
}
}
public ArrayList<Sender> getAllSender() {
Statement stmt = null;
Sender s = null;
ArrayList<Sender> senderList = new ArrayList<>();
try {
conn = MySQLDBConnection.getConnection();
stmt = conn.createStatement();
String sql = "SELECT * FROM sender";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
String username = rs.getString("username");
String email = rs.getString("email");
String password = rs.getString("password");
s = new Sender(username, email, password);
senderList.add(s);
}
Collections.sort(senderList);
rs.close();
}
catch (SQLException se) {
se.printStackTrace();
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
catch (SQLException se) {
se.printStackTrace();
}
}
return senderList;
}
}
|
package netty.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;
public class NIOMessageServer {
private ServerSocketChannel serverChannnel;
private Selector selector;
private List<SocketChannel> clients;
public NIOMessageServer() {
try {
serverChannnel = ServerSocketChannel.open();
selector = Selector.open();
clients = new ArrayList<>();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public void setBlocking(boolean blocking) {
try {
serverChannnel.configureBlocking(blocking);
} catch (IOException e) {
e.printStackTrace();
}
}
public void bind(int port) {
try {
serverChannnel.socket().bind(new InetSocketAddress(port));
} catch (IOException e) {
e.printStackTrace();
}
}
public void bindAndSetBacklog(int port, int backlog) {
try {
serverChannnel.socket().bind(new InetSocketAddress(port), backlog);
} catch (IOException e) {
e.printStackTrace();
}
}
public SelectionKey register(int interest) {
try {
return serverChannnel.register(selector, interest);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void work() {
System.out.println("开始work");
while (true) {
try {
int num = selector.select();
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIt = selectionKeys.iterator();
while (keyIt.hasNext()) {
SelectionKey currentKey = keyIt.next();
keyIt.remove();
try {
handleRequest(currentKey);
} finally {
// shutDownGracefully(currentKey);
}
}
} catch (IOException e) {
e.printStackTrace();
}
// System.err.println(clients);
}
}
public void handleRequest(SelectionKey currentKey) throws IOException {
if (!currentKey.isValid()) {
return;
}
if (currentKey.isAcceptable()) {
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) currentKey.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
String welcome = "欢迎" + socketChannel.socket().getPort() + "的到来";
System.out.println("欢迎" + socketChannel.socket().getPort() + "的到来");
ByteBuffer buffer = ByteBuffer.allocate(512);
buffer.put(welcome.getBytes());
buffer.flip();
System.err.println(socketChannel.write(buffer));
buffer.clear();
System.err.println("数据发送完毕");
synchronized (clients) {
clients.add(socketChannel);
}
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
socketChannel.register(selector, SelectionKey.OP_WRITE);
}
if (currentKey.isReadable()) {
System.err.println("有数据来了...");
SocketChannel socketChannel = (SocketChannel) currentKey.channel();
ByteBuffer distBuffer = ByteBuffer.allocate(1024);
int readBytes = socketChannel.read(distBuffer);
if (readBytes > 0) {
distBuffer.flip(); //limit = position; position = 0;
byte[] bytes = new byte[distBuffer.remaining()];
distBuffer.get(bytes); //把distBuffer的数据读到bytes数组中
String inputContent = new String(bytes, "utf-8");
System.out.println("来自" + socketChannel.socket().getPort() + "的消息:" + inputContent);
broadcast(inputContent);
}
if (readBytes < 0) {
shutDownGracefully(currentKey);
}
}
}
public void broadcast(String content) throws IOException {
ByteBuffer distBuffer = ByteBuffer.allocate(1024);
for (SocketChannel socketChannel : clients) {
String sendMessage = "广播给" + socketChannel.socket().getPort() + "的信息是:" + content;
distBuffer.put(sendMessage.getBytes());
distBuffer.flip();
socketChannel.write(distBuffer);
}
}
public void shutDownGracefully(SelectionKey currentKey) throws IOException {
if (currentKey != null) {
currentKey.cancel();
if (currentKey.channel() != null) {
currentKey.channel().close();
}
}
}
public static void main(String[] args) {
NIOMessageServer server = new NIOMessageServer();
server.setBlocking(false);
server.bindAndSetBacklog(9090, 1024);
SelectionKey key = server.register(SelectionKey.OP_ACCEPT);
System.out.println("SelectionKey:" + key);
server.work();
}
}
|
package com.spakai.builder;
import com.spakai.flow.FlowAOutput;
import com.spakai.flow.FlowBOutput;
import com.spakai.flow.FlowCInput;
public class FlowCInputBuilder implements Builder<FlowCInput> {
private final FlowBOutput mandatoryflowBOutput;
private FlowAOutput optionalflowAOutput;
public FlowAOutput getOptionalflowAOutput() {
return optionalflowAOutput;
}
public FlowCInputBuilder setOptionalflowAOutput(FlowAOutput optionalflowAOutput) {
this.optionalflowAOutput = optionalflowAOutput;
return this;
}
public FlowCInputBuilder(FlowBOutput mandatoryflowBOutput) {
this.mandatoryflowBOutput = mandatoryflowBOutput;
}
@Override
public FlowCInput build() {
FlowCInput input = new FlowCInput();
input.setMandatoryFromFlowB(mandatoryflowBOutput.getOutput1FromB());
if (optionalflowAOutput != null) {
input.setOptionalFromFlowA(optionalflowAOutput.getOutput2FromA());
}
return input;
}
}
|
/**
*
*/
package com.miaoqi.authen.core.authentication;
import com.miaoqi.authen.core.properties.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
/**
* @author zhailiang
*
*/
public class AbstractChannelSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
protected AuthenticationSuccessHandler imoocAuthenticationSuccessHandler;
@Autowired
protected AuthenticationFailureHandler imoocAuthenticationFailureHandler;
protected void applyPasswordAuthenticationConfig(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
.loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
.successHandler(this.imoocAuthenticationSuccessHandler)
.failureHandler(this.imoocAuthenticationFailureHandler);
}
}
|
package swiss.kamyh.elo.arena.scenario;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.Team;
import swiss.kamyh.elo.enumerate.ScenarioEnum;
import swiss.kamyh.elo.gui.scorboard.ScoreboardTimerized;
import java.util.ArrayList;
/**
* Created by Vincent on 08.06.2016.
* speed + jump boost
*/
public class BunnyUp extends Scenario implements IScenario{
private ArrayList<Player> participants;
public BunnyUp(ArrayList<Player> participants) {
super(ScenarioEnum.BRAIN_FUCK_TELEPORTATION);
this.participants = participants;
}
@Override
public void activate() {
for(Player p: this.participants)
{
p.addPotionEffect(new PotionEffect(PotionEffectType.JUMP,9999999,2));
}
}
}
|
package com.metoo.module.app.manage.buyer.action;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.metoo.core.domain.virtual.SysMap;
import com.metoo.core.mv.JModelAndView;
import com.metoo.core.query.support.IPageList;
import com.metoo.core.tools.CommUtil;
import com.metoo.foundation.domain.OrderForm;
import com.metoo.foundation.domain.Store;
import com.metoo.foundation.domain.User;
import com.metoo.foundation.domain.query.OrderFormQueryObject;
import com.metoo.foundation.service.IOrderFormService;
import com.metoo.foundation.service.IStoreService;
import com.metoo.foundation.service.ISysConfigService;
import com.metoo.foundation.service.IUserConfigService;
import com.metoo.foundation.service.IUserService;
import com.metoo.manage.admin.tools.OrderFormTools;
import com.metoo.modul.app.desig.pattern.OrderFormFactory;
import com.metoo.module.app.buyer.domain.Result;
import net.sf.json.JSONArray;
/**
* <p>
* Description: 用户订单管理类,多店铺合单
* </p>
*
* @author 46075
*
*/
@Controller
@RequestMapping("/app/v2/")
public class AppOrderBuyerActionV2 {
@Autowired
private ISysConfigService configService;
@Autowired
private IUserConfigService userConfigService;
@Autowired
private IUserService userService;
@Autowired
private IOrderFormService orderFormService;
@Autowired
private OrderFormTools orderFormTools;
@Autowired
private IStoreService storeService;
@Autowired
private OrderFormFactory orderFormFactory;
@RequestMapping(value = "order.json", method = RequestMethod.POST)
public void orderV2(HttpServletRequest request, HttpServletResponse response, String currentPage, String order_id,
String beginTime, String endTime, String order_status, String token, String name, String language) {
Map<String, Object> map = new HashMap<String, Object>();
Result result = null;
ModelAndView mv = new JModelAndView("", configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
OrderFormQueryObject ofqo = new OrderFormQueryObject(currentPage, mv, "addTime", "desc");
if (token.equals("")) {
result = new Result(-100, "token Invalidation");
} else {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user == null) {
result = new Result(-100, "token Invalidation");
} else {
ofqo.addQuery("obj.user_id", new SysMap("user_id", user.getId().toString()), "=");
ofqo.addQuery("obj.order_main", new SysMap("order_main", 1), "=");// 只显示主订单,通过主订单完成子订单的加载[是否为主订单,1为主订单,主订单用在买家用户中心显示订单内容]
// ofqo.addQuery("obj.order_cat", new SysMap("order_cat", 0),
// "=");//[ 订单分类,0为购物订单,1为手机充值订单 2为生活类团购订单 3为商品类团购订单 4旅游报名订单]
List<Integer> order_cart = new ArrayList<Integer>();
order_cart.add(5);
order_cart.add(0);
order_cart.add(6);
ofqo.addQuery("obj.order_cat", new SysMap("order_cat", order_cart), "in");
ofqo.setPageSize(20);// 设定分页查询,每页24件商品
if (!CommUtil.null2String(order_id).equals("")) {
ofqo.addQuery("obj.order_id", new SysMap("order_id", "%" + order_id + "%"), "like");
}
if (!CommUtil.null2String(beginTime).equals("")) {
ofqo.addQuery("obj.addTime", new SysMap("beginTime", CommUtil.formatDate(beginTime)), ">=");
}
if (!CommUtil.null2String(endTime).equals("")) {
String ends = endTime + " 23:59:59";
ofqo.addQuery("obj.addTime",
new SysMap("endTime", CommUtil.formatDate(ends, "yyyy-MM-dd hh:mm:ss")), "<=");
}
String or_status = null;
if (!CommUtil.null2String(order_status).equals("")) {
List<Integer> str = new ArrayList<Integer>();
if (order_status.equals("order_submit")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 10), "=");
or_status = "10";
}
if (order_status.equals("order_pay")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 20), "=");
or_status = "20";
}
if (order_status.equals("order_shipping")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 30), "=");
or_status = "30";
}
/*
* if (order_status.equals("payOnDelivery")) {
* ofqo.addQuery("obj.order_status", new
* SysMap("order_status", 16), "="); or_status = "16,20"; }
*/
if (order_status.equals("pending")) {
str.add(16);
str.add(20);
ofqo.addQuery("obj.order_status", new SysMap("order_status", str), "in");
}
if (order_status.equals("unpaid")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 10), "=");
}
if (order_status.equals("order_receive")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 40), "=");
or_status = "40";
}
if (order_status.equals("order_finish")) {
str.clear();
str.add(50);
str.add(65);
ofqo.addQuery("obj.order_status", new SysMap("order_status", str), "in");
or_status = "50";
}
if (order_status.equals("order_cancel")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 0), "=");
or_status = "0";
}
} else {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 90), "!=");
}
map.put("order_status", order_status);
map.put("imageWebServer", this.configService.getSysConfig().getImageWebServer());
IPageList pList = this.orderFormService.list(ofqo);
List<OrderForm> orders = pList.getResult();
List orderList = new ArrayList();
for (OrderForm order : orders) {
boolean flag = true;
if (!CommUtil.null2String(name).equals("")) {
flag = this.orderFormTools.verifyGoodsName(order, name);
}
if (flag) {
Map orderMap = new HashMap();
Store store = this.storeService.getObjById(CommUtil.null2Long(order.getStore_id()));
orderMap.put("sotre_id", store.getId());
orderMap.put("sotre_name", store.getStore_name());
orderMap.put("sotre_logo", store.getStore_logo() != null
? store.getStore_logo().getPath() + "/" + store.getStore_logo().getName() : "");
orderMap.put("goods", this.orderFormTools.queryGoodsInfo(order.getGoods_info()));
orderMap.put("order_id", order.getId());
orderMap.put("order_number", order.getOrder_id());
orderMap.put("order_pay_type", order.getPayType());
orderMap.put("order_status", order.getOrder_status());
orderMap.put("payment_amount", order.getPayment_amount());
orderMap.put("usd_payment_amount", order.getUsd_payment_amount());
if (order.getPayType().equals("online") && order.getOrder_status() == 10) {
if (order.getPayment_date() != null) {
Long millisecond1 = order.getPayment_date().getTime() + 31 * 60 * 1000;
Long millisecond = Long.valueOf(order.getTest()) + 31 * 60 * 1000;
Calendar current_time = Calendar.getInstance();
Long time = millisecond - current_time.getTimeInMillis();
orderMap.put("count_down", time > 0 ? time : 0);
}
if(order.getUrl_payment() != null){
orderMap.put("url_payment", CommUtil.null2String(order.getUrl_payment()).equals("") ? "" : order.getUrl_payment());
}
}
orderMap.put("childOrder", this.orderFormTools.queryGoodsInfo(order.getChild_order_detail()));
orderList.add(orderMap);
}
}
map.put("orderlist", orderList);
int[] status = new int[] { 0, 10, 16, 30, 40 };
String[] string_status = new String[] { "order_cencel", "order_submit", "order_pending",
"order_shipping", "order_finish" };
Map<String, Object> orders_status = new LinkedHashMap<String, Object>();
List<Map<String, Object>> statusmaps = new ArrayList<Map<String, Object>>();
for (int i = 0; i < status.length; i++) {
Map statusmap = new LinkedHashMap();
int size = this.orderFormService.query("select obj.id from OrderForm obj where obj.user_id="
+ user.getId().toString() + " and obj.order_status =" + status[i] + "", null, -1, -1)
.size();
statusmap.put("order_size_" + status[i], size);
statusmap.put(string_status[i], size);
statusmaps.add(statusmap);
}
map.put("orderstatus", statusmaps);
map.put("order_Pages", pList.getPages());
Map user_map = new HashMap();
user_map.put("user_id", user.getId());
user_map.put("user_id", user.getUserName());
user_map.put("user_email", user.getEmail());
user_map.put("user_sex", user.getSex());
map.put("user", user_map);
result = new Result(4200, "Success", map);
}
}
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().println(Json.toJson(result, JsonFormat.compact()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
/*
* Date date = new Date(); System.out.println("time: "+ date.getTime());
* Calendar calendar = Calendar.getInstance(); System.out.println(
* "time2: "+ calendar.getTime()); System.out.println("time_time:" +
* calendar.getTime().getTime());
*/
Date time = new Date(1842094);
SimpleDateFormat formats = new SimpleDateFormat("hh:mm:ss");
System.out.println("data: " + formats.format(time));
}
// @RequestMapping(value = "order.json", method = RequestMethod.POST)
public void orderV2_1(HttpServletRequest request, HttpServletResponse response, String currentPage, String order_id,
String beginTime, String endTime, String order_status, String token, String name, String language) {
Map<String, Object> map = new HashMap<String, Object>();
Result result = null;
ModelAndView mv = new JModelAndView("user/default/usercenter/buyer_order.html", configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
OrderFormQueryObject ofqo = new OrderFormQueryObject(currentPage, mv, "addTime", "desc");
if (token.equals("")) {
result = new Result(-100, "token Invalidation");
} else {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user == null) {
result = new Result(-100, "token Invalidation");
} else {
ofqo.addQuery("obj.user_id", new SysMap("user_id", user.getId().toString()), "=");
ofqo.addQuery("obj.order_main", new SysMap("order_main", 1), "=");// 只显示主订单,通过主订单完成子订单的加载[是否为主订单,1为主订单,主订单用在买家用户中心显示订单内容]
// ofqo.addQuery("obj.order_cat", new SysMap("order_cat", 0),
// "=");//[ 订单分类,0为购物订单,1为手机充值订单 2为生活类团购订单 3为商品类团购订单 4旅游报名订单]
List<Integer> order_cart = new ArrayList<Integer>();
order_cart.add(5);
order_cart.add(0);
ofqo.addQuery("obj.order_cat", new SysMap("order_cat", order_cart), "in");
ofqo.setPageSize(20);// 设定分页查询,每页24件商品
if (!CommUtil.null2String(order_id).equals("")) {
ofqo.addQuery("obj.order_id", new SysMap("order_id", "%" + order_id + "%"), "like");
}
if (!CommUtil.null2String(beginTime).equals("")) {
ofqo.addQuery("obj.addTime", new SysMap("beginTime", CommUtil.formatDate(beginTime)), ">=");
}
if (!CommUtil.null2String(endTime).equals("")) {
String ends = endTime + " 23:59:59";
ofqo.addQuery("obj.addTime",
new SysMap("endTime", CommUtil.formatDate(ends, "yyyy-MM-dd hh:mm:ss")), "<=");
}
String or_status = null;
if (!CommUtil.null2String(order_status).equals("")) {
if (order_status.equals("order_submit")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 10), "=");
or_status = "10";
}
if (order_status.equals("order_pay")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 20), "=");
or_status = "20";
}
if (order_status.equals("order_shipping")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 30), "=");
or_status = "30";
}
if (order_status.equals("payOnDelivery")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 16), "=");
or_status = "16";
}
if (order_status.equals("order_receive")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 40), "=");
or_status = "40";
}
if (order_status.equals("order_finish")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 50), "=");
ofqo.addQuery("obj.order_status", new SysMap("order_status", 65), "=");
or_status = "50";
}
if (order_status.equals("order_cancel")) {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 0), "=");
or_status = "0";
}
} else {
ofqo.addQuery("obj.order_status", new SysMap("order_status", 90), "!=");
}
map.put("order_status", order_status);
map.put("imageWebServer", this.configService.getSysConfig().getImageWebServer());
IPageList pList = this.orderFormService.list(ofqo);
List<OrderForm> orders = null;
if (CommUtil.null2String(name).equals("")) {
orders = pList.getResult();
} else {
for (OrderForm obj : orders) {
if (this.orderFormTools.verifyGoodsName(obj, name)) {
orders.add(obj);
}
}
}
map.put("orderlist", orderFormFactory.getGoods(orders, "consolidated"));
int[] status = new int[] { 0, 10, 16, 30, 40 };
String[] string_status = new String[] { "order_cencel", "order_submit", "order_pending",
"order_shipping", "order_finish" };
Map<String, Object> orders_status = new LinkedHashMap<String, Object>();
List<Map<String, Object>> statusmaps = new ArrayList<Map<String, Object>>();
for (int i = 0; i < status.length; i++) {
Map statusmap = new LinkedHashMap();
int size = this.orderFormService.query("select obj.id from OrderForm obj where obj.user_id="
+ user.getId().toString() + " and obj.order_status =" + status[i] + "", null, -1, -1)
.size();
statusmap.put("order_size_" + status[i], size);
statusmap.put(string_status[i], size);
statusmaps.add(statusmap);
}
map.put("orderstatus", statusmaps);
map.put("order_Pages", pList.getPages());
result = new Result(4200, "Success", map);
}
}
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().println(Json.toJson(result, JsonFormat.compact()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param request
* @param response
* @param id
* @param token
* @param language
* @return
*/
@RequestMapping(value = "order_view.json")
@ResponseBody
public String getOrderView(HttpServletRequest request, HttpServletResponse response, String id, String token,
String language) {
int code = -1;
String msg = "";
Map map = new HashMap();
Map main = new HashMap();
List<Map> order = new ArrayList<Map>();
if (!CommUtil.null2String(token).equals("")) {
User user = this.userService.getObjByProperty(null, "app_login_token", token);
if (user != null) {
OrderForm obj = this.orderFormService.getObjById(CommUtil.null2Long(id));
// List<Map> goodsList =
// this.orderFormTools.queryGoodsInfo(obj.getGoods_info());
if (obj != null && obj.getUser_id().equals(user.getId().toString())) {
String imgWebServer = this.configService.getSysConfig().getImageWebServer();
if (obj.getChild_order_detail() != null && !obj.getChild_order_detail().equals("")) {
order = this.orderFormTools.queryGoodsInfo(obj.getChild_order_detail());
// main.put("childs", JSONArray.fromObject(childs));
/*
* JSONArray array =
* this.orderFormTools.queryChildOrder(obj.
* getChild_order_detail()); order.add(array);
*/
}
main.put("order_goods_info", obj.getGoods_info());
main.put("enough_free", obj.getEnough_free());
main.put("order_id", obj.getId());
main.put("order_status", obj.getOrder_status());
main.put("enough_reduce_amount", obj.getEnough_reduce_amount());
Map coupon_map = orderFormTools.queryCouponInfo(obj.getCoupon_info());
main.put("coupon_amount", coupon_map.get("coupon_amount"));
main.put("goods_amount", obj.getGoods_amount());
main.put("ship_price", obj.getEnough_free() == 1 ? 0 : obj.getShip_price());
main.put("totalPrice", obj.getEnough_free() == 1 ? obj.getGoods_amount() : obj.getTotalPrice());
order.add(main);
map.put("order_number", obj.getOrder_id());
map.put("order_status", obj.getOrder_status());
map.put("platform_ship_price", obj.getPlatform_ship_price());
map.put("discounts_amount", obj.getDiscounts_amount());
map.put("integral", obj.getIntegral());
map.put("goodsVoucherPrice", obj.getGoods_voucher_price());
/*
* map.put("integral_price", CommUtil.mul(obj.getIntegral(),
* this.configService.getSysConfig().getIntegralExchangeRate
* ()));
*/
map.put("order_coupon_amount", obj.getCoupon_amount());
map.put("order_goods_amount",
CommUtil.add(CommUtil.subtract(obj.getPayment_amount(), obj.getPlatform_ship_price()), obj.getGoods_voucher_price()));
map.put("payment_amount", obj.getPayment_amount());
map.put("usd_payment_amount", obj.getUsd_payment_amount());
map.put("imgWebServer", imgWebServer);
// 店铺
Store store = this.storeService.getObjById(CommUtil.null2Long(obj.getStore_id()));
Map storeMap = new HashMap();
main.put("store_name", store.getStore_name());
main.put("store_id", store.getId());
main.put("store_enough_free", store.getEnough_free());
main.put("store_enough_free_price", store.getEnough_free_price());
main.put("store_logo",
store.getStore_logo() == null ? ""
: this.configService.getSysConfig().getImageWebServer() + "/"
+ store.getStore_logo().getPath() + "/" + store.getStore_logo().getName());
// main.put("store", storeMap);
// 收货地址
map.put("Transport", obj.getTransport());
map.put("Receiver_Name", obj.getReceiver_Name());
map.put("Receiver_area", obj.getReceiver_area());
map.put("Receiver_area_info", obj.getReceiver_area_info());
map.put("Receiver_zip", obj.getReceiver_zip());
map.put("Receiver_telephone", obj.getReceiver_telephone());
map.put("Receiver_mobile", obj.getReceiver_mobile());
map.put("shipCode", obj.getShipCode());
map.put("AddTime", obj.getAddTime());
map.put("ShipTime", obj.getShipTime());
map.put("ConfirmTime", obj.getConfirmTime());
map.put("FinishTime", obj.getFinishTime());
map.put("order", order);
code = 4200;
msg = "Success";
} else {
code = 4205;
msg = "No information was found";
}
} else {
code = -100;
msg = "token Invalidation";
}
} else {
code = -100;
msg = "token Invalidation";
}
return Json.toJson(new Result(code, msg, map), JsonFormat.compact());
}
}
|
/*
* 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 com.koshish.java.hibernate.ecommerce.DAO.impl;
import com.koshish.java.hibernate.ecommerce.DAO.CategoryDAO;
import com.koshish.java.hibernate.ecommerce.entity.Category;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Koshish Rijal
*/
@Repository("categoryDAO")
@Transactional
public class CategoryDAOImpl implements CategoryDAO {
@Autowired
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Override
public List<Category> getAll() {
session = sessionFactory.openSession();
List<Category> categoryList = session.createQuery("from Category").list();
session.close();
return categoryList;
}
@Override
public Category getById(int id) {
session = sessionFactory.openSession();
Category category = (Category) session.get(Category.class, id);
session.close();
return category;
}
@Override
public int delete(int id) {
Category category = getById(id);
if (!category.getProductList().isEmpty()) {
return 0;
}
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.delete(category);
transaction.commit();
session.close();
return 1;
}
@Override
public int update(Category category) {
session=sessionFactory.openSession();
transaction=session.beginTransaction();
session.update(category);
transaction.commit();
session.close();
return 1;
}
@Override
public int insert(Category category) {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
session.save(category);
transaction.commit();
session.close();
return 1;
}
}
|
package com.pelephone_mobile.mypelephone.ui.components.device;
/**
* Created by Gali.Issachar on 18/12/13.
*/
public class DeviceSizeItem {
private String deviceSize;
private String devicePrice;
public DeviceSizeItem(String deviceSize, String devicePrice){
this.deviceSize = deviceSize;
this.devicePrice = devicePrice;
}
public void setDeviceSize(String size){
this.deviceSize = size;
}
public void setDevicePrice(String price){
this.devicePrice = price;
}
public String getDeviceSize(){
return deviceSize;
}
public String getDevicePrice(){
return devicePrice;
}
}
|
package core.server.game.controllers.equipment;
import java.util.Set;
import cards.Card;
import cards.equipments.Equipment;
import cards.equipments.Equipment.EquipmentType;
import commands.client.game.DecisionUIClientCommand;
import commands.client.game.ShowCardSelectionPanelUIClientCommand;
import core.player.PlayerCardZone;
import core.player.PlayerCompleteServer;
import core.server.game.BattleLog;
import core.server.game.GameInternal;
import core.server.game.controllers.AbstractPlayerDecisionActionGameController;
import core.server.game.controllers.CardSelectableGameController;
import core.server.game.controllers.DecisionRequiredGameController;
import core.server.game.controllers.mechanics.RecycleCardsGameController;
import core.server.game.controllers.mechanics.UnequipGameController;
import exceptions.server.game.GameFlowInterruptedException;
import exceptions.server.game.IllegalPlayerActionException;
public class KylinBowGameController
extends AbstractPlayerDecisionActionGameController
implements CardSelectableGameController, DecisionRequiredGameController {
private final PlayerCompleteServer source;
private final PlayerCompleteServer target;
private boolean confirmed;
public KylinBowGameController(PlayerCompleteServer source, PlayerCompleteServer target) {
this.source = source;
this.target = target;
this.confirmed = false;
}
@Override
protected void handleDecisionRequest(GameInternal game) throws GameFlowInterruptedException {
throw new GameFlowInterruptedException(
new DecisionUIClientCommand(
source.getPlayerInfo(),
"Kylin Bow: Use to discard an equipped horse from target?"
)
);
}
@Override
protected void handleDecisionConfirmation(GameInternal game) throws GameFlowInterruptedException {
if (!this.confirmed) {
// skip Action
this.setStage(PlayerDecisionAction.END);
}
}
@Override
protected void handleAction(GameInternal game) throws GameFlowInterruptedException {
throw new GameFlowInterruptedException(
new ShowCardSelectionPanelUIClientCommand(
source.getPlayerInfo(),
target,
Set.of(PlayerCardZone.EQUIPMENT),
Set.of(EquipmentType.HORSEPLUS, EquipmentType.HORSEMINUS)
)
);
}
@Override
public void onDecisionMade(boolean confirmed) {
this.confirmed = confirmed;
}
@Override
public void onCardSelected(GameInternal game, Card card, PlayerCardZone zone) {
Equipment equipment = (Equipment) card;
game.pushGameController(new RecycleCardsGameController(this.target, Set.of(equipment)));
game.pushGameController(new UnequipGameController(this.target, equipment.getEquipmentType()));
game.log(BattleLog
.playerAUsedEquipment(source, source.getWeapon())
.onPlayer(target)
.to("discard their horse: " + BattleLog.formatCard(equipment))
);
}
@Override
public void validateCardSelected(GameInternal game, Card card, PlayerCardZone zone) throws IllegalPlayerActionException {
if (zone != PlayerCardZone.EQUIPMENT) {
throw new IllegalPlayerActionException("Kylin Bow: Discarded card must be an equipment");
}
if (card == null) {
throw new IllegalPlayerActionException("Kylin Bow: Card cannot be null");
}
if (!(card instanceof Equipment)) {
throw new IllegalPlayerActionException("Kylin Bow: Discared card is not an Equipment");
}
Equipment equipment = (Equipment) card;
if (equipment.getEquipmentType() != EquipmentType.HORSEMINUS && equipment.getEquipmentType() != EquipmentType.HORSEPLUS) {
throw new IllegalPlayerActionException("Kylin Bow: Discarded card is not a horse");
}
}
}
|
package com.worldchip.bbp.ect.db;
import java.util.ArrayList;
import java.util.List;
import com.worldchip.bbp.ect.entity.AlarmInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
public class ClockData {
/**
* 添加闹钟
* @param context
* @param values
*/
public static void addClockAlarm(Context context, ContentValues values)
{
DBHelper helper = new DBHelper(context);
helper.insertValues(DBSqlBuilder.BBP_CLOCk_TABLE, values);
Log.e("addClockAlarm", "success");
}
/**
* 获取所有的闹钟
*/
public static List<AlarmInfo> getAllClockAlarm(Context context)
{
return getAlarmInfo(context, null);
}
/**
* 获取所有打开的闹钟
*/
public static List<AlarmInfo> getAllEnableClockAlarm(Context context)
{
return getAlarmInfo(context, "where enabled = 1");
}
/**
* 根据编号获取一个闹钟
*/
public static AlarmInfo getByAlarmInfo(Context context,int _id)
{
List<AlarmInfo> alarms = getAlarmInfo(context, "where _id="+ _id);
if(alarms !=null && alarms.size() > 0){
return alarms.get(0);
}
return null;
}
/**
* 根据编号获取一个闹钟
*/
public static int getAlarmInfoSize(Context context)
{
int count = 0;
DBHelper helper = new DBHelper(context);
Cursor cursor = helper.getCursorBySql("select count(*) from '"+DBSqlBuilder.BBP_CLOCk_TABLE+"' order by _id desc");
if(cursor != null)
{
cursor.moveToFirst();
count = cursor.getInt(0);
}
return count;
}
public static List<AlarmInfo> getAlarmInfo(Context context, String whereStr)
{
List<AlarmInfo> alarmInfos = new ArrayList<AlarmInfo>();
DBHelper helper = new DBHelper(context);
Cursor cursor = null;
if(whereStr==null || whereStr.equals(""))
{
cursor = helper.getCursor(DBSqlBuilder.BBP_CLOCk_TABLE, "order by _id asc");
}else{
cursor =helper.getCursor(DBSqlBuilder.BBP_CLOCk_TABLE, whereStr);
}
while(cursor.moveToNext())
{
Integer id = cursor.getInt(cursor.getColumnIndex("_id"));
Integer hours = cursor.getInt(cursor.getColumnIndex("hours"));
Integer musutes = cursor.getInt(cursor.getColumnIndex("musutes"));
String daysofweek = cursor.getString(cursor.getColumnIndex("daysofweek"));
Integer alarmtime = cursor.getInt(cursor.getColumnIndex("alarmtime"));
Integer enabled = cursor.getInt(cursor.getColumnIndex("enabled"));
String alert = cursor.getString(cursor.getColumnIndex("alert"));
Integer times = cursor.getInt(cursor.getColumnIndex("times"));
Integer isdefault = cursor.getInt(cursor.getColumnIndex("isdefault"));
Integer interval = cursor.getInt(cursor.getColumnIndex("interval"));
AlarmInfo alarmInfo = new AlarmInfo(id, hours, musutes, daysofweek, alarmtime, enabled, alert, times,isdefault,interval);
alarmInfos.add(alarmInfo);
}
cursor.close();
return alarmInfos;
}
/**
* 修改闹钟
*/
public static boolean updataAlarmInfo(Context context,int _id,ContentValues values)
{
DBHelper helper = new DBHelper(context);
boolean flag = helper.updateValues(DBSqlBuilder.BBP_CLOCk_TABLE,values,"_id = "+ _id);
return flag;
}
public static boolean enableAlarm(Context context, int _id, boolean enable)
{
ContentValues values = new ContentValues();
values.put("enabled", enable ? 1 : 0);
DBHelper helper = new DBHelper(context);
boolean flag = helper.updateValues(DBSqlBuilder.BBP_CLOCk_TABLE,values, "_id = " + _id);
return flag;
}
/**
* 删除某个闹钟
* @param context
* @param id
*/
public static boolean delClockById(Context context,long id)
{
DBHelper helper = new DBHelper(context);
boolean falg = helper.deleteRow(DBSqlBuilder.BBP_CLOCk_TABLE, id);
Log.e("delClockById", "falg:"+falg);
Log.e("delClockById", "id:"+id);
return falg;
}
}
|
package controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Person;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class sendMessage extends AsyncRequestHandler {
@Override
public String handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
Person currentUser= (Person) request.getSession().getAttribute("user");
System.out.println(currentUser.getFirstName());
String message = request.getParameter("message");
response.setContentType("text/plain");
return messageToJson(message);
}
private String messageToJson(String message) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(message);
}
}
|
package convertBST538;
import dataStructure.*;
import java.util.Stack;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int sum = 0;
/**
* 递归
* @param root
* @return
*/
public TreeNode convertBST(TreeNode root) {
if(root != null){
//遍历右子树
convertBST(root.right);
//遍历顶点
root.val += sum;
sum = root.val;
//遍历左子树
convertBST(root.left);
}
return root;
}
/**
* 迭代
* @param root
* @return
*/
public TreeNode convertBST2(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while (node != null || !stack.empty()){
while (node != null){
stack.push(node);
node = node.right;
}
node = stack.pop();
node.val += sum;
sum = node.val;
//左子树
node = node.left;
}
return root;
}
}
|
package model;
import java.util.Scanner;
public class Seventwo {
static int min(int a, int b, int c) {
int minimum = 0;
if (a > b) {
if (b > c) {
minimum = c;
} else {
minimum = b;
}
} else {
if (a > c) {
minimum = c;
} else {
minimum = a;
}
}
return minimum;
}
public static void main(String[] args) {
Scanner stdInt = new Scanner(System.in);
int a = stdInt.nextInt();
int b = stdInt.nextInt();
int c = stdInt.nextInt();
int s = min(a, b, c);
System.out.println("a,b,cの最小の数値は" + s + "です");
}
}
|
package com.javarush.test.level10.lesson11.home06;
/* Constructors of the class Human
Write a class Human with 6 fields. Come up with 10 different constructors for it and implement them. Each constructor should have meaning.
*/
public class Solution
{
public static void main(String[] args)
{
}
public static class Human
{
//Write here variables and constructors
String name;
String lastName;
String surname;
int age;
int weight;
int height;
public Human() {
this.name = "Name";
this.lastName = "Last Name";
this.surname = null;
this.age = 0;
this.weight = 70;
this.height = 70;
}
public Human(String name, String lastName, String surname, int age, int weight, int height) {
this.name = name;
this.lastName = lastName;
this.surname = surname;
this.age = age;
this.weight = weight;
this.height = height;
}
public Human(String name) {
this.name = name;
}
public Human(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public Human(String name, String lastName, int age) {
this.name = name;
this.lastName = lastName;
this.age = age;
}
public Human(String name, String lastName, int age, int weight) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.weight = weight;
}
public Human(String name, String lastName, int age, int weight, int height) {
this.name = name;
this.lastName = lastName;
this.age = age;
this.weight = weight;
this.height = height;
}
public Human(int age) {
this.age = age;
}
public Human(int weight, int height) {
this.weight = weight;
this.height = height;
}
public Human(int age, int weight, int height) {
this.age = age;
this.weight = weight;
this.height = height;
}
}
}
|
package com.example.pojo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class EmployeeExampleTest {
@Test
void setOrderByClause() {
}
@Test
void getOrderByClause() {
}
}
|
/***
* Description: Write a Java application in NetBeans that
* utilizes a class written for the application called Document.
* The application creates instances of Document objects and
* utilizes its properties and methods.
***/
package lcpn87documents;
/**
*
* @author Carlie
*/
public class Lcpn87Documents {
public static void main(String[] args) {
//creates document instances
Document document1 = new Document("Another Life","Sally Smith");
document1.setBody("The grass is always greener on the other side.");
Document document2 = new Document("Final Word","Karen Jones");
document2.setBody("We should plan for the worst and hope for the best.");
document2.setTitle("Final Words");
//prints out document contents
System.out.printf("document1:\ntitle: %s\nauthor: %s\nbody: %s\nversion: %s\n", document1.getTitle(),document1.getAuthor(),document1.getBody(),document1.getVersion());
System.out.printf("document2:\ntitle: %s\nauthor: %s\nbody: %s\nversion: %s\n", document2.getTitle(),document2.getAuthor(),document2.getBody(),document2.getVersion());
}
}
|
package com.joseadilson.realm.adapter;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.joseadilson.realm.AddDisciplinaActivity;
import com.joseadilson.realm.R;
import com.joseadilson.realm.model.Disciplina;
import com.joseadilson.realm.model.Estudante;
import io.realm.Realm;
import io.realm.RealmBaseAdapter;
import io.realm.RealmResults;
/**
* Created by jose on 18/01/2017.
*/
public class DisciplinaAdapter extends RealmBaseAdapter<Disciplina> implements ListAdapter {
private Realm realm;
public DisciplinaAdapter(Context context,Realm realm, RealmResults<Disciplina> realmResults, boolean automaticUpdate){
super(context, realmResults, automaticUpdate);
this.realm = realm;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CustomViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_disciplina, parent, false);
holder = new CustomViewHolder();
convertView.setTag(holder);
holder.tvName = (TextView)convertView.findViewById(R.id.tvName);
holder.btAtualizar = (Button) convertView.findViewById(R.id.btAtualizar);
holder.btRemover = (Button) convertView.findViewById(R.id.btRemover);
} else {
holder = (CustomViewHolder)convertView.getTag();
}
final Disciplina d = realmResults.get(position);
int qtdeEstudantes = realm.where(Estudante.class).equalTo("grades.disciplina.id", d.getId()).findAll().size();
holder.tvName.setText(d.getNome() + " "+ qtdeEstudantes);
holder.btAtualizar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent it = new Intent(context, AddDisciplinaActivity.class);
it.putExtra(Disciplina.ID, d.getId());
context.startActivity(it);
}
});
holder.btRemover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
d.removeFromRealm();
realm.commitTransaction();
realm.close();
}
});
return convertView;
}
private static class CustomViewHolder{
TextView tvName;
Button btAtualizar;
Button btRemover;
}
}
|
import java.util.Scanner;
public class Grades {
public static String letterGrade(double score) {
if (score <= 100 && score >= 90) {
return "A";
} else if (score <= 89 && score >= 80 ) {
return "B";
} else if (score <= 79 && score >= 70) {
return "C";
} else if (score <= 69 && score >= 60) {
return "D";
} else if (score <= 59 && score >=0) {
return "F";
}
return null;
}
public static void main(String[] args) {
/* you probably want to use user input for the
* score using Scanner because you will have to convert
* a command line argument to a float, and we haven't
* gotten to string parsing yet
*
* But you can also just set the "score" variable
* to whatever you want in the code, and that's fine too
*/
double score = 66.5;
Scanner in = new Scanner(System.in);
System.out.print("Enter score: ");
score = in.nextDouble();
String grade = letterGrade(score);
// if the grade is not null print this out:
if (grade != null) {
System.out.println("The grade for a score of " + score + " is " + grade);
} else {
// if the grade is null, print this out:
System.out.println("invalid score");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.