text
stringlengths 10
2.72M
|
|---|
package com.github.dmstocking.putitonthelist.grocery_list;
import com.github.dmstocking.putitonthelist.PerController;
import dagger.Subcomponent;
@PerController
@Subcomponent(modules = {
GroceryListModule.class,
})
public interface GroceryListComponent {
void inject(GroceryListController controller);
}
|
//Omar Mustafa Dalal 1180171
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
//Class containing methods used to read input files
public class ReadMethods {
public static City[] readFiles(File cityFile, File connectionFile) {
City[] cities = readCitiesFile(cityFile);
readRoadsFile(connectionFile, cities);
return cities;
}
//Method to read cities from a file
private static City[] readCitiesFile(File file) {
City[] cities;
try {
Scanner in = new Scanner(file);
int V = in.nextInt();
cities = new City[V];
int cCount = 0;
while (in.hasNextLine()&&cCount<V) {
String cityName = in.next();
float x = in.nextFloat();
float y = in.nextFloat();
City city = new City(cityName, x, y);
cities[cCount++] = city;
}
in.close();
return cities;
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
return null;
}
//Method to read roads from a file
private static void readRoadsFile(File file, City[] cities) {
try {
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String c1Name = in.next();
String c2Name = in.next();
float dist = in.nextFloat();
City c1=null;
City c2=null;
for (int i=0; i<cities.length; i++) {
if (c1Name.equals(cities[i].getName())) {
c1 = cities[i];
} else if (c2Name.equals(cities[i].getName())) {
c2 = cities[i];
}
if (c1!=null&&c2!=null) {
break;
}
}
if (!checkExists(c1.getNeighbours(), c2)) {
c1.getNeighbours().add(new CNode(c2, dist));
}
if (!checkExists(c2.getNeighbours(), c1)) {
c2.getNeighbours().add(new CNode(c1, dist));
}
}
in.close();
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
}
//method used to check if city already exists in ArrayList
public static boolean checkExists(ArrayList<CNode> list, City city) {
for (int i=0; i<list.size(); i++) {
if (list.get(i).getCity().equals(city)) {
return true;
}
}
return false;
}
}
|
package com.literature.service.impl;
import com.literature.entity.Permission;
import com.literature.repository.PermissionRepository;
import com.literature.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class PermissionService implements IPermissionService {
@Autowired
private PermissionRepository permissionRepository;
@Override
public Permission createPermission(Permission permission) {
permissionRepository.save(permission);
return permission;
}
@Override
public Permission findById(String id) {
return permissionRepository.findPermissionsById(id);
}
@Override
public void deletePermission(String id) {
permissionRepository.deleteById(id);
}
@Override
public void updatePermission(Permission permission) {
permissionRepository.saveAndFlush(permission);
}
@Override
public List<Permission> findAll() {
return permissionRepository.findAll();
}
@Override
public List<Permission> findByName(String name) {
return permissionRepository.findByName(name);
}
@Override
public List<Permission> findChildByPid(String pid) {
return permissionRepository.findAllByAndParentId(pid);
}
}
|
package io.github.Theray070696.raycore.client.gui.widget;
import net.minecraft.client.gui.FontRenderer;
/**
* Created by Theray070696 on 8/1/2017.
*/
public abstract class Widget
{
protected int xPos;
protected int yPos;
public abstract void keyTyped(char typedChar, int keyCode);
public abstract void drawScreen(int mouseX, int mouseY, float partialTicks, FontRenderer fontRenderer);
public abstract void mouseReleased(int mouseX, int mouseY, int state);
public abstract void mouseClicked(int mouseX, int mouseY, int mouseButton);
}
|
package com.fight.job.admin.thread;
import com.fight.job.admin.dao.ExecutorInfoDao;
import com.fight.job.admin.entity.ExecutorInfoEntity;
import com.fight.job.core.enums.ExecutorStateEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* ExecutorStateCheckThread.
*/
public class ExecutorStateCheckThread {
private static final Logger logger = LogManager.getLogger();
private int sleepTime = 10;
public int getSleepTime() {
return sleepTime;
}
public void setSleepTime(int sleepTime) {
this.sleepTime = sleepTime;
}
@Autowired
ExecutorInfoDao executorDao;
private boolean stop = false;
public void start() {
Thread thread = new Thread(() -> {
while (!stop) {
handle();
sleep();
}
});
thread.start();
}
public void stop() {
this.stop = true;
}
private void handle() {
List<ExecutorInfoEntity> executorList = executorDao.selectAll();
long time = (new Date().getTime() / 1000);
if (executorList != null) {
for (ExecutorInfoEntity executor : executorList) {
if (time - (executor.getUpdateTime().getTime() / 1000) > 30) {
executorDao.updateExecutorState(executor.getIp(), executor.getPort(), executor.getGroupId(),
ExecutorStateEnum.OFFLINE.name());
}
}
}
}
private void sleep() {
try {
TimeUnit.SECONDS.sleep(sleepTime);
} catch (InterruptedException e) {
logger.error(e);
}
}
}
|
package com.tencent.mm.plugin.ipcall.ui;
import com.tencent.mm.plugin.ipcall.a.i;
import com.tencent.mm.plugin.ipcall.b.a;
import com.tencent.mm.sdk.platformtools.ah;
class b$1 implements Runnable {
final /* synthetic */ b ktn;
b$1(b bVar) {
this.ktn = bVar;
}
public final void run() {
if (System.currentTimeMillis() - this.ktn.ktg >= 500) {
this.ktn.kte = a.av(this.ktn.bGc, this.ktn.ktc + this.ktn.ktd);
ah.A(new 1(this, i.aXv().EP(this.ktn.kte)));
return;
}
ah.A(new 2(this));
}
}
|
package com.lqs.hrm.util.entity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.github.pagehelper.util.StringUtil;
import com.lqs.hrm.entity.AttendanceEmployee;
import com.lqs.hrm.entity.AttendanceTime;
import com.lqs.hrm.entity.Department;
import com.lqs.hrm.entity.Employee;
import com.lqs.hrm.entity.EmployeePosition;
import com.lqs.hrm.entity.Position;
import com.lqs.hrm.service.impl.AttendanceEmployeeServiceImpl;
import com.lqs.hrm.service.impl.ContractServiceImpl;
import com.lqs.hrm.service.impl.DepartmentLevelServiceImpl;
import com.lqs.hrm.service.impl.DepartmentServiceImpl;
import com.lqs.hrm.service.impl.EmployeeContractServiceImpl;
import com.lqs.hrm.service.impl.EmployeePositionServiceImpl;
import com.lqs.hrm.service.impl.EmployeeServiceImpl;
import com.lqs.hrm.service.impl.EntryCountServiceImpl;
import com.lqs.hrm.service.impl.PositionServiceImpl;
import com.lqs.hrm.service.impl.StatusServiceImpl;
/**
* 部门实体信息封装工具类
* @author luckyliuqs
*
*/
@Component
public class DepartmentInfoUtil {
@Autowired
private EmployeeServiceImpl employeeService;
@Autowired
private DepartmentServiceImpl departmentService;
@Autowired
private StatusServiceImpl statusService;
@Autowired
private PositionServiceImpl positionService;
@Autowired
private EmployeePositionServiceImpl employeePositionService;
@Autowired
private DepartmentLevelServiceImpl departmentLevelService;
@Autowired
private AttendanceEmployeeServiceImpl attendanceEmployeeService;
/**
* 设置查询出来的部门实体类信息
* @param departmentList
* @throws ParseException
*/
public void setDepartmentInfo(List<Department> list) {
if (list.size() != 0 || list != null) {
for (int i = 0; i < list.size(); i++) {
//System.out.print("================ 部门名称:"+list.get(i).getDeptName()+"===================\n");
//设置部门级别
list.get(i).setDlLeve(departmentLevelService.get(list.get(i).getDlId()).getLevel());
//设置部门主管职位名称
if (list.get(i).getManagePositionid() != null && list.get(i).getManagePositionid().intValue()!= 0) {
list.get(i).setManagePositionName(positionService.get(list.get(i).getManagePositionid()).getPositionName());
}
//设置部门主管人工号和姓名
if(list.get(i).getManagePositionid() != null && list.get(i).getManagePositionid() != 0) {
//设置部门主管职位名称
list.get(i).setManagePositionName(positionService.get(list.get(i).getManagePositionid()).getPositionName());
//获取部门主管职位
List<EmployeePosition> employeePositionList = employeePositionService.listByPositionId(list.get(i).getManagePositionid());
if (employeePositionList == null || employeePositionList.size() == 0) {
//该部门主管职位还未分配给职工
list.get(i).setManageEmpName("");
}else {
//该部门主管职位还已分配给职工,则查找该职工信息
Employee employee = employeeService.get(employeePositionList.get(0).getEmpJobid());
//设置部门主管人工号和姓名
list.get(i).setManageEmpJobId(employee.getEmpJobid());
list.get(i).setManageEmpName(employee.getEmpName());
}
}
//设置上级部门名称
if (list.get(i).getParentId() != null && list.get(i).getParentId() !=0) {
list.get(i).setParentDeptName(departmentService.get(list.get(i).getParentId()).getDeptName());
}
//设置部门状态名称
list.get(i).setStatusName(statusService.get(list.get(i).getStatusId()).getStatusName());
//设置操作人名称
if(list.get(i).getOperatorEmpjobid() != null && !list.get(i).getOperatorEmpjobid().isEmpty()) {
Employee employee = employeeService.get(list.get(i).getOperatorEmpjobid());
if (employee != null) {
list.get(i).setOperatorEmpName(employee.getEmpName());
}
}
//部门职工数量
Integer deptEmpNum = 0;
List<Department> childDepartmentList = listChildDeptByDeptId(list.get(i).getDeptId());
childDepartmentList.add(list.get(i));
for (Department d : childDepartmentList) {
//System.out.print("子部门名称:"+d.getDeptName());
List<Position> positionList = positionService.listByDeptId(d.getDeptId());
for (Position position : positionList) {
List<EmployeePosition> employeePositionList = employeePositionService.listByPositionId(position.getPositionId());
deptEmpNum += employeePositionList.size();
}
//System.out.println();
}
//设置部门职工数量
list.get(i).setDeptEmpnum(deptEmpNum);
//System.out.print(" 部门人数:"+deptEmpNum +"\n");
}
}
}
/**
* 设置查询出来的部门实体类信息
* @param departmentList
* @throws ParseException
*/
public void setDepartmentInfo(Department department) throws ParseException {
if (department != null) {
//设置部门级别
department.setDlLeve(departmentLevelService.get(department.getDlId()).getLevel());
//设置部门主管人工号和姓名
if(department.getManagePositionid() != null && department.getManagePositionid() != 0) {
//设置部门主管职位名称
department.setManagePositionName(positionService.get(department.getManagePositionid()).getPositionName());
//获取部门主管职位
List<EmployeePosition> employeePositionList = employeePositionService.listByPositionId(department.getManagePositionid());
if (employeePositionList == null || employeePositionList.size() == 0) {
//该部门主管职位还未分配给职工
department.setManageEmpName("");
}else {
//该部门主管职位还已分配给职工,则查找该职工信息
Employee employee = employeeService.get(employeePositionList.get(0).getEmpJobid());
//设置部门主管人工号和姓名
department.setManageEmpJobId(employee.getEmpJobid());
department.setManageEmpName(employee.getEmpName());
}
}
//设置上级部门名称
if (department.getParentId() != null && department.getParentId() != 0) {
department.setParentDeptName(departmentService.get(department.getParentId()).getDeptName());
}
//设置部门状态名称
department.setStatusName(statusService.get(department.getStatusId()).getStatusName());
//设置操作人名称
if(department.getOperatorEmpjobid() != null && !department.getOperatorEmpjobid().isEmpty()) {
Employee employee = employeeService.get(department.getOperatorEmpjobid());
if (employee != null) {
department.setOperatorEmpName(employee.getEmpName());
}
}
//部门职工数量
Integer deptEmpNum = 0;
List<Department> childDepartmentList = listChildDeptByDeptId(department.getDeptId());
childDepartmentList.add(department);
for (Department d : childDepartmentList) {
List<Position> positionList = positionService.listByDeptId(d.getDeptId());
for (Position position : positionList) {
List<EmployeePosition> employeePositionList = employeePositionService.listByPositionId(position.getPositionId());
deptEmpNum += employeePositionList.size();
}
}
//设置部门职工数量
department.setDeptEmpnum(deptEmpNum);
}
}
/**
* 获取到指定部门id的部门的所有子部门
*/
public List<Department> listChildDeptByDeptId(Integer deptd) {
//所有子部门信息
List<Department> allDepartmentList = new ArrayList<>();
//获取到所有部门信息
List<Department> childDepartmentList = departmentService.listByParentId(deptd);
for (Department department : childDepartmentList) {
for (Department d : listChildDeptByDeptId(department.getDeptId())) {
if (d != null) {
allDepartmentList.add(d);
}
}
allDepartmentList.add(department);
}
return allDepartmentList;
}
/**
* 获取指定部门下的所有职工数量
* @param department
* @return
*/
public int getDeptEmpNum(Department department) {
//部门职工数量
Integer deptEmpNum = 0;
List<Department> childDepartmentList = listChildDeptByDeptId(department.getDeptId());
childDepartmentList.add(department);
for (Department d : childDepartmentList) {
//System.out.print("子部门名称:"+d.getDeptName());
List<Position> positionList = positionService.listByDeptId(d.getDeptId());
for (Position position : positionList) {
List<EmployeePosition> employeePositionList = employeePositionService.listByPositionId(position.getPositionId());
deptEmpNum += employeePositionList.size();
}
//System.out.println();
}
return deptEmpNum;
}
}
|
package it.unica.pr2;
import java.util.stream.Collectors;
import java.util.*;
public class Utente implements Tuitter{
private String nome;
private TestTuitter.Data data;
public Utente(String nome, TestTuitter.Data data){
this.nome = nome.toLowerCase();
this.data = data;
}
public String username(){
return this.nome;
}
public TestTuitter.Data data(){
return this.data;
}
@Override
public boolean equals(Object obj){
if(this == obj) return true;
if( !(obj instanceof Utente) ) return false;
Utente u = (Utente)obj;
if(this.nome.equals(u.username())){
if( this.data.anno == u.data.anno){
if(this.data.mese == u.data.mese){
if(this.data.giorno == u.data.giorno){
return true;
}
}
}
}
return false;
}
@Override
public String toString(){
return this.nome + ", "+this.data.giorno + "-" +this.data.mese + "-"+this.data.anno;
}
}
|
package com.github.pratzn.oss.common.aop;
import java.lang.reflect.Array;
import java.text.DateFormat;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.aspectj.lang.ProceedingJoinPoint;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.Marker;
import org.slf4j.helpers.MessageFormatter;
import org.slf4j.spi.LocationAwareLogger;
import org.springframework.util.ClassUtils;
public class StatisticsLogAdvice
{
private static final LocationAwareLogger LOGGER = (LocationAwareLogger)LoggerFactory.getLogger(StatisticsLogAdvice.class);
private boolean indentView = true;
private boolean simpleClassName = true;
private boolean showArgsAndResultValue = true;
private int maxLengthOfValue = 1000;
private String indent = " ";
private String mdcIndent = "indent";
private Set<String> excludeClassSet = new LinkedHashSet<String>();
public Object doExecution(ProceedingJoinPoint pjp)
throws Throwable
{
String proxyClassName = pjp.getThis().getClass().getName();
String methodName = null;
if (this.indentView)
{
if (this.simpleClassName) {
methodName = pjp.getSignature().getDeclaringType().getSimpleName() + '.' + pjp.getSignature().getName();
} else {
methodName = pjp.getSignature().getDeclaringTypeName() + '.' + pjp.getSignature().getName();
}
printBegin(proxyClassName, methodName, pjp);
}
StringBuilder buf = new StringBuilder(64);
buf.append(methodName);
buf.append("()");
long startTime = System.currentTimeMillis();
Object result = null;
try
{
result = pjp.proceed();
if ((this.indentView) && (this.showArgsAndResultValue))
{
buf.append(" Return: ");
appendReturnValue(buf, result);
}
}
catch (Throwable ex)
{
if ((this.indentView) && (this.showArgsAndResultValue)) {
buf.append(" Throwable: ").append(ex);
}
throw ex;
}
finally
{
if (this.indentView) {
printEnd(proxyClassName, startTime, buf);
} else {
printRap(proxyClassName, startTime, pjp);
}
}
return result;
}
protected void printRap(String proxyClassName, long startTime, ProceedingJoinPoint pjp)
{
if (this.simpleClassName) {
LOGGER.log((Marker)null, proxyClassName, 20, MessageFormatter.format("[{}ms] {}", Long.valueOf(System.currentTimeMillis() - startTime), pjp.getSignature().toShortString()).getMessage(), null, null);
} else {
LOGGER.log(null, proxyClassName, 20, MessageFormatter.format("[{}ms] {}", Long.valueOf(System.currentTimeMillis() - startTime), pjp.getSignature().toLongString()).getMessage(), null, null);
}
}
protected void printBegin(String proxyClassName, String methodName, ProceedingJoinPoint pjp)
{
StringBuilder buf = new StringBuilder(64);
buf.append(methodName);
buf.append("(");
if (this.showArgsAndResultValue) {
appendArguments(buf, pjp.getArgs());
}
buf.append(")");
LOGGER.log(null, proxyClassName, 10, MessageFormatter.format("BEGIN: {}", buf).getMessage(), null, null);
if (MDC.get(this.mdcIndent) != null) {
MDC.put(this.mdcIndent, MDC.get(this.mdcIndent) + this.indent);
} else {
MDC.put(this.mdcIndent, this.indent);
}
}
protected void printEnd(String proxyClassName, long startTime, StringBuilder buf)
{
MDC.put(this.mdcIndent, MDC.get(this.mdcIndent).substring(this.indent.length()));
LOGGER.log(null, proxyClassName, 10, MessageFormatter.format("END: [{}ms] {}", Long.valueOf(System.currentTimeMillis() - startTime), buf).getMessage(), null, null);
}
protected void appendArguments(StringBuilder buf, Object[] arguments)
{
appendObject(buf, arguments);
}
protected void appendReturnValue(StringBuilder buf, Object returnValue)
{
appendObject(buf, returnValue);
}
protected void appendObject(StringBuilder buf, Object object)
{
if (object == null)
{
buf.append("<null>");
}
else if (object.getClass().isArray())
{
buf.append(object.getClass().getSimpleName());
buf.append('{');
int length = ArrayUtils.getLength(object);
if (length > 0)
{
for (int i = 0; i < length; i++)
{
if (buf.length() > this.maxLengthOfValue)
{
buf.setLength(this.maxLengthOfValue - 3);
buf.append("...");
return;
}
appendObject(buf, Array.get(object, i));
buf.append(", ");
}
buf.setLength(buf.length() - 2);
}
buf.append('}');
}
else if ((object instanceof String))
{
buf.append("'").append(object).append("'");
}
else if (ClassUtils.isPrimitiveOrWrapper(object.getClass()))
{
buf.append(object);
}
else if ((object instanceof Date))
{
buf.append("'");
buf.append(DateFormat.getDateTimeInstance().format((Date)object));
buf.append("'");
}
else if ((object instanceof DateTime))
{
buf.append("'");
buf.append(((DateTime)object).toString(DateTimeFormat.mediumDateTime()));
buf.append("'");
}
else if (this.excludeClassSet.contains(object.getClass().getName()))
{
buf.append(ReflectionToStringBuilder.toString(object, ToStringStyle.SHORT_PREFIX_STYLE, false, false, object.getClass()));
}
else
{
buf.append(ReflectionToStringBuilder.toString(object, ToStringStyle.SHORT_PREFIX_STYLE));
}
if (buf.length() > this.maxLengthOfValue)
{
buf.setLength(this.maxLengthOfValue - 3);
buf.append("...");
}
}
public boolean isIndentView()
{
return this.indentView;
}
public void setIndentView(boolean indentView)
{
this.indentView = indentView;
}
public boolean isSimpleClassName()
{
return this.simpleClassName;
}
public void setSimpleClassName(boolean simpleClassName)
{
this.simpleClassName = simpleClassName;
}
public boolean isShowArgsAndResultValue()
{
return this.showArgsAndResultValue;
}
public void setShowArgsAndResultValue(boolean showArgsAndResultValue)
{
this.showArgsAndResultValue = showArgsAndResultValue;
}
public int getMaxLengthOfValue()
{
return this.maxLengthOfValue;
}
public void setMaxLengthOfValue(int maxLengthOfValue)
{
this.maxLengthOfValue = maxLengthOfValue;
}
public String getIndent()
{
return this.indent;
}
public void setIndent(String indent)
{
this.indent = indent;
}
public String getMdcIndent()
{
return this.mdcIndent;
}
public void setMdcIndent(String mdcIndent)
{
this.mdcIndent = mdcIndent;
}
public Set<String> getExcludeClassSet()
{
return this.excludeClassSet;
}
public void setExcludeClassSet(Set<String> excludeClassSet)
{
this.excludeClassSet = excludeClassSet;
}
}
|
package com.example.OCP.advancedClassDesing.nestedClasses.variablesInNestedClass;
/**
* Created by guille on 10/14/18.
*/
public class privateInterface {
private interface Secret {
public void ssh();
}
class DontTell implements Secret{
@Override
public void ssh() {
System.out.print("EXAMPLE OF PRIVATE INTERFACE");
}
}
}
|
package com.tencent.mm.plugin.appbrand.g.a;
import com.tencent.mm.plugin.appbrand.g.a.f.a;
class f$3 implements Runnable {
final /* synthetic */ String fwG;
final /* synthetic */ f geo;
final /* synthetic */ a gep = null;
f$3(f fVar, String str) {
this.geo = fVar;
this.fwG = str;
}
public final void run() {
if (this.gep != null) {
f.d(this.geo).executeScript(this.fwG).toString();
} else {
f.d(this.geo).executeVoidScript(this.fwG);
}
}
}
|
package com.lubarov.daniel.data.util;
import java.io.IOException;
import java.io.Reader;
/**
* @see IOUtils
*/
public final class RWUtils {
private RWUtils() {}
public static String readUntilEnd(Reader reader) throws IOException {
StringBuilder sb = new StringBuilder();
int nRead;
char[] data = new char[16384];
while ((nRead = reader.read(data, 0, data.length)) != -1)
sb.append(data, 0, nRead);
return sb.toString();
}
}
|
package datechooser.view;
public enum WeekDaysStyle
{
FULL, NORMAL, SHORT;
private WeekDaysStyle() {}
}
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/view/WeekDaysStyle.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/
|
public class Worker {
public void doWork() {
System.out.println("Does unskilled work.");
earnWage();
//doWork is PUBLIC
//so it can be overriden in a subclass.-.
}
private void earnWage() {
System.out.println("Earns minimum wage.");
//Private
//will not be inherited, and can't be overriden
}
}
|
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import services.FibonacciService;
@SpringBootApplication
public class Worker {
public static void main(String[] arg) {
String redisHost = System.getProperty("REDIS_HOST");
String redisPort = System.getProperty("REDIS_PORT");
final Jedis jRedisClient = new Jedis(redisHost, Integer.parseInt(redisPort));
Jedis jRedisSubscriber = new Jedis(redisHost, Integer.parseInt(redisPort));
ConfigurableApplicationContext context = SpringApplication.run(Worker.class, arg);
final FibonacciService fibonacciService = context.getBean("fibonacciService", FibonacciService.class);
jRedisSubscriber.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
jRedisClient.hset("values", message, convert(fibonacciService.fib(convert(message))));
}
}, "insert");
}
private static String convert(int number) {
return String.valueOf(number);
}
private static int convert(String number) {
return Integer.parseInt(number);
}
}
|
//https://leetcode.com/problems/strobogrammatic-number-ii/discuss/358470/Java-easy-recursive-solution-with-explanation
class Solution {
public List<String> findStrobogrammatic(int n) {
List<String>result = new ArrayList<>();
if (n%2==1) {
insertStrobogrammatic(result, "1", n, 1);
insertStrobogrammatic(result, "8", n, 1);
insertStrobogrammatic(result, "0", n, 1);
} else
insertStrobogrammatic(result, "", n, 0);
return result;
}
public void insertStrobogrammatic(List<String>result, String input, int n, int l){
if (l==n)result.add(input);
else {
if (n-l>2) insertStrobogrammatic(result, "0"+input+"0", n, l+2);
insertStrobogrammatic(result, "6"+input+"9", n, l+2);
insertStrobogrammatic(result, "1"+input+"1", n, l+2);
insertStrobogrammatic(result, "8"+input+"8", n, l+2);
insertStrobogrammatic(result, "9"+input+"6", n, l+2);
}
}
}
|
package br.com.treinarminas.academico.classandobject;
public class Pessoa {
int idade;
char sexo;
String nome; // Nao é um tipo primitivo de dados
Endereco endereco;
}
|
package LeetCode.ArraysAndStrings;
public class ExpressiveWords {
int ans;
public int expressiveWords(String S, String[] words) {
ans = 0;
for (String word : words) {
if(isStretchy(word, S))
ans++;
}
return ans;
}
public boolean isStretchy(String s1, String s2){
int count1 = 1, count2 = 1, i = 0, j =0, s1l = s1.length(), s2l = s2.length();
while (i < s1l && j < s2l ){
if(s1.charAt(i) != s2.charAt(j))
return false;
while (i+1 < s1l && s1.charAt(i + 1) == s1.charAt(i)){
i++; count1++;
}
while (j+1 < s2l && s2.charAt(j + 1) == s2.charAt(j)){
j++; count2++;
}
if(count1 != count2 && count2 < 3 || count1 > count2)
return false;
i++; j++; count1 = 1; count2 = 1;
}
if(i != s1l || j != s2l)
return false;
return true;
}
public static void main(String[] args) {
ExpressiveWords e = new ExpressiveWords();
System.out.println(e.expressiveWords("aaa", new String[] {"aaaa"}));
}
}
|
package es.salesianos.controller;
import java.util.Random;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import es.salesianos.model.Dificulty;
import es.salesianos.model.WordList;
@Controller
public class HangleController {
private static Logger log = LogManager.getLogger(HangleController.class);
@Autowired
WordList wordlist;
@Autowired
Dificulty dificulty;
String correctAnswer;
Integer tries;
String userInput;
String feedback;
@GetMapping("/")
public String index() {
return "index";
}
@GetMapping("/yieldRandomSolutionWord")
public String generateAnswer() {
int rnd = new Random().nextInt(wordlist.getWordList().size());
correctAnswer = wordlist.getWordList().get(rnd);
tries = dificulty.getTries();
log.debug("la respuesta a encotnrar es:" + correctAnswer);
return "index";
}
@PostMapping("/checkAnswer")
public ModelAndView checkAnswer(@RequestParam String userInput) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
if (userInput.equalsIgnoreCase(correctAnswer)) {
log.info("Has ganado");
feedback = "Los has logrado has acertado la palabra";
} else {
int rnd = new Random().nextInt(correctAnswer.length());
log.info("pista:" + correctAnswer.charAt(rnd));
feedback = "pista:" +String.valueOf(correctAnswer.charAt(rnd));
}
modelAndView.addObject("feedback", feedback);
return modelAndView;
}
}
|
package controlador;
import java.io.IOException;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import alfrescoConection.InteractiveAuthentication;
public class LoginAlfresco implements TaskListener{
public void notify(DelegateTask delegateTask) {
// Se obtiene ticket de autenticación de login
String alfrescoTiccketURL = "http://127.0.0.1:8080/alfresco/service/api/login?u=admin&pw=admin";
InteractiveAuthentication ticket = new InteractiveAuthentication();
try {
String ticketURLResponse = ticket.getTicket(alfrescoTiccketURL);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.craw_data.models;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Category {
private String categoryId;
private String title;
Set<Topic> topics = new HashSet<>(0);
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Topic> getTopics() {
return topics;
}
public void setTopics(Set<Topic> topics) {
this.topics = topics;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
return Objects.equals(categoryId, category.categoryId) && Objects.equals(title, category.title);
}
@Override
public int hashCode() {
return Objects.hash(categoryId, title);
}
}
|
package Concurrency.ConcurrentPackage;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
public class MyProducer implements Runnable {
private final ArrayBlockingQueue<String> buffer;
private String color;
public MyProducer(ArrayBlockingQueue<String> buffer, String color) {
this.buffer = buffer;
this.color = color;
}
@Override
public void run() {
Random random = new Random();
String[] numbers = {"1", "2", "3", "4", "5"};
for (String number : numbers) {
try {
System.out.println(color + "Adding... " + number);
buffer.put(number);
Thread.sleep(random.nextInt(2000));
} catch (InterruptedException e ) {
System.out.println("Producer was interrupted.");
}
}
System.out.println(color + "Adding EOF and exiting... ");
try {
buffer.put("EOF");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
package communication.netty;
/**
* This enum contains different types of data a {@link io.netty.handler.codec.http.websocketx.WebSocketFrame} may contain.
*/
public enum FrameType {
Binary, Text, Undefined;
}
|
package com.steven.base.util.RecyclerView;
/**
* @user steven
* @createDate 2019/4/3 10:07
* @description Item移动后 触发
*/
public interface OnItemMoveListener {
void onItemMove(int fromPosition, int toPosition);
}
|
package com.example.jbarrientos.bilbapp.Presenter.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import com.example.jbarrientos.bilbapp.Presenter.Adapters.QualificationOfSitiosAdapter;
import com.example.jbarrientos.bilbapp.Model.DataPopulator;
import com.example.jbarrientos.bilbapp.Presenter.NetworkChecker;
import com.example.jbarrientos.bilbapp.Presenter.QueryAsyncTask;
import com.example.jbarrientos.bilbapp.Model.Sitios;
import com.example.jbarrientos.bilbapp.R;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
public class QualificationActivity extends AppCompatActivity {
ListView lista;
private ArrayList<Sitios> versiones = new ArrayList<Sitios>();
private DataPopulator dp = new DataPopulator();
private Boolean networkOn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qualification);
setTitle(R.string.help_icon_5);
String sitioType = getIntent().getStringExtra("extra_text");
lista = (ListView) findViewById(R.id.qualification_list);
networkOn = NetworkChecker.getConnectivity(this);
if(networkOn==true)
{
sitiosQuery(sitioType);
}else{
Toast toast1 = Toast.makeText(this,R.string.network_off,Toast.LENGTH_SHORT);
toast1.show();
}
}
public void sitiosQuery(final String typeSitio){
new QueryAsyncTask<ArrayList<Sitios>>(this) {
@Override
protected ArrayList<Sitios> work() throws Exception{
switch (typeSitio) {
case "fiesta":
try {
versiones = dp.cargaInfoSitios(typeSitio);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case "compras":
try {
versiones = dp.cargaInfoSitios(typeSitio);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case "restaurantes":
try {
versiones = dp.cargaInfoSitios(typeSitio);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case "alojamiento":
try {
versiones = dp.cargaInfoSitios(typeSitio);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case "deportes":
try {
versiones = dp.cargaInfoSitios(typeSitio);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case "monumentos":
try {
versiones = dp.cargaInfoSitios(typeSitio);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case "transportes":
try {
versiones = dp.cargaInfoSitios(typeSitio);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
default:
break;
}
return versiones;
}
@Override
protected void onFinish(ArrayList<Sitios> estado){
QualificationOfSitiosAdapter adaptador = new QualificationOfSitiosAdapter(QualificationActivity.this, versiones);
lista.setAdapter(adaptador);
}
}.execute();
}
}
|
package com.ck.hello.nestpullview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.widget.TextView;
import com.ck.hello.nestrefreshlib.View.RefreshViews.SRecyclerView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SRecyclerView recyclerView = (SRecyclerView) findViewById(R.id.sre);
recyclerView.addDefaultHeaderFooter()
.setRefreshMode(true, true, true, true)
.setAdapter(new LinearLayoutManager(this), new RecyclerView.Adapter() {
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
TextView textView = new TextView(parent.getContext());
textView.setText("dsfdsds");
return new RecyclerView.ViewHolder(textView) {
@Override
public String toString() {
return super.toString();
}
};
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 20;
}
}).setRefreshingListener(new SRecyclerView.OnRefreshListener() {
@Override
public void Refreshing() {
recyclerView.postDelayed(new Runnable() {
@Override
public void run() {
recyclerView.notifyRefreshComplete();
}
}, 1000);
}
@Override
public void Loading() {
super.Loading();
recyclerView.postDelayed(new Runnable() {
@Override
public void run() {
recyclerView.notifyRefreshComplete();
}
}, 1000);
}
});
}
}
|
package com.test;
public class Game {
private String name;
private String team;
private String torunament;
private String manager;
public Game() { }
public Game(String name, String team, String torunament, String manager) {
super();
this.name = name;
this.team = team;
this.torunament = torunament;
this.manager = manager;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public String getTorunament() {
return torunament;
}
public void setTorunament(String torunament) {
this.torunament = torunament;
}
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
}
|
package com.onplan.service.impl;
import com.onplan.domain.transitory.VirtualMachineInfo;
import com.onplan.service.VirtualMachineService;
import javax.inject.Singleton;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.Collection;
@Singleton
public final class VirtualMachineServiceImpl implements VirtualMachineService {
@Override
public VirtualMachineInfo getVirtualMachineInfo() {
long collectionsCount = 0;
long cumulatedTime = 0;
double averageCollectionTime = 0;
Collection<GarbageCollectorMXBean> garbageCollectors =
ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean garbageCollector : garbageCollectors) {
collectionsCount += garbageCollector.getCollectionCount();
cumulatedTime += garbageCollector.getCollectionTime();
}
if(collectionsCount > 0) {
averageCollectionTime = cumulatedTime / collectionsCount;
}
int availableProcessors = Runtime.getRuntime().availableProcessors();
long freeMemory = Runtime.getRuntime().freeMemory();
long totalMemory = Runtime.getRuntime().totalMemory();
long maxMemory = Runtime.getRuntime().maxMemory();
return new VirtualMachineInfo(availableProcessors, maxMemory, totalMemory, freeMemory,
collectionsCount, averageCollectionTime);
}
}
|
package com.tkb.elearning.action.admin;
import java.io.IOException;
import java.util.List;
import com.tkb.elearning.model.AboutLaw;
import com.tkb.elearning.service.AboutLawService;
import com.tkb.elearning.util.UploadUtil;
import com.tkb.elearning.util.VerifyBaseAction;
import sso.spring.DeployInfoUtil;
public class AboutLawAction extends VerifyBaseAction {
private static final long serialVersionUID = 1L;
private AboutLawService aboutLawService; //相關法規服務
private List<AboutLaw> aboutLawList; //相關法規清單
private AboutLaw aboutLaw; //相關法規資料
private int pageNo; //頁碼
private String uploadFile; //文件檔案
private String fileExtension; //文件副檔名
private int[] deleteList; //刪除的ID清單
private String deleteFile; //刪除的文件(舊文件)
/**
* 清單頁面
* @return
*/
public String index() {
if(aboutLaw == null) {
aboutLaw = new AboutLaw();
}
pageTotalCount = aboutLawService.getCount(aboutLaw);
pageNo = super.pageSetting(pageNo);
aboutLawList = aboutLawService.getList(pageCount, pageStart, aboutLaw);
return "list";
}
/**
* 新增頁面
* @return
*/
public String add() {
aboutLaw = new AboutLaw();
return "form";
}
/**
* 新增資料
* @return
* @throws IOException
*/
public String addSubmit() throws IOException {
aboutLaw.setFile(UploadUtil.upload(DeployInfoUtil.getUploadFilePath() + "file/aboutLaw" ,
uploadFile, aboutLaw.getFile(), aboutLaw.getId(), fileExtension));
aboutLawService.add(aboutLaw);
return "index";
}
/**
* 修改頁面
* @return
*/
public String update() {
aboutLaw = aboutLawService.getData(aboutLaw);
return "form";
}
/**
* 修改相關法規
* @return
* @throws IOException
*/
public String updateSubmit() throws IOException {
if(uploadFile !=null){
UploadUtil.delete(DeployInfoUtil.getUploadFilePath() + "file/aboutLaw/" + deleteFile);
}
aboutLaw.setFile(UploadUtil.upload(DeployInfoUtil.getUploadFilePath() + "file/aboutLaw" ,
uploadFile, aboutLaw.getFile(), aboutLaw.getId(), fileExtension));
aboutLawService.update(aboutLaw);
return "index";
}
/**
* 刪除最新消息
* @return
*/
public String delete() throws IOException {
for(int id : deleteList) {
aboutLaw.setId(id);
aboutLaw = aboutLawService.getData(aboutLaw);
aboutLawService.delete(id);
}
return "index";
}
/**
* 瀏覽頁面
* @return
*/
public String view(){
aboutLaw=aboutLawService.getData(aboutLaw);
return "view";
}
public AboutLawService getAboutLawService() {
return aboutLawService;
}
public void setAboutLawService(AboutLawService aboutLawService) {
this.aboutLawService = aboutLawService;
}
public List<AboutLaw> getAboutLawList() {
return aboutLawList;
}
public void setAboutLawList(List<AboutLaw> aboutLawList) {
this.aboutLawList = aboutLawList;
}
public AboutLaw getAboutLaw() {
return aboutLaw;
}
public void setAboutLaw(AboutLaw aboutLaw) {
this.aboutLaw = aboutLaw;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public String getUploadFile() {
return uploadFile;
}
public void setUploadFile(String uploadFile) {
this.uploadFile = uploadFile;
}
public String getFileExtension() {
return fileExtension;
}
public void setFileExtension(String fileExtension) {
this.fileExtension = fileExtension;
}
public int[] getDeleteList() {
return deleteList;
}
public void setDeleteList(int[] deleteList) {
this.deleteList = deleteList;
}
public String getDeleteFile() {
return deleteFile;
}
public void setDeleteFile(String deleteFile) {
this.deleteFile = deleteFile;
}
}
|
package br.ufmg.ppgee.orcslab.upmsp.algorithm;
import br.ufmg.ppgee.orcslab.upmsp.problem.Problem;
import br.ufmg.ppgee.orcslab.upmsp.problem.Solution;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Base class for algorithms that process the input parameters to avoid {@code null} values for the
* random number generator and for the map of algorithm parameters. Algorithms that extends this
* base class must override the protected method {@link #doSolve(Problem, Random, Map, Callback)},
* in which the algorithm's logic will be placed.
*/
public abstract class AbstractAlgorithm implements Algorithm {
@Override
public final Solution solve(Problem problem, Random random, Map<String, Object> parameters, Callback callback) {
// Initialize the map of parameters if it is null
if (parameters == null) {
parameters = new HashMap<>();
}
// Initialize the random number generator if it is null
if (random == null) {
random = new Random();
}
// Set the seed of the random number generator
if (parameters.containsKey("seed")) {
Number seed = (Number) parameters.get("seed");
random.setSeed(seed.longValue());
}
// Callback object
if (callback == null) {
callback = new Callback() {
@Override
public void onNewIncumbent(Solution incumbent, long iteration, long time) { /* Do nothing. */ }
};
}
// Solve the problem
return doSolve(problem, random, parameters, callback);
}
/**
* Method that must implement the algorithm's logic that solves the input problem and returns a
* solution.
* @param problem The problem instance.
* @param random A random number generator.
* @param parameters Algorithm parameters.
* @param callback A callback object.
* @return A solution of the problem.
*/
protected abstract Solution doSolve(Problem problem, Random random, Map<String, Object> parameters, Callback callback);
}
|
package uk.gov.ons.ctp.response.action.export.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.sourceforge.cobertura.CoverageIgnore;
/** Domain entity representing a template mapping. */
@CoverageIgnore
@Entity
@Data
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Table(name = "templatemapping", schema = "actionexporter")
public class TemplateMapping {
@Id
@Column(name = "actiontypenamepk")
private String actionType;
@Column(name = "templatenamefk")
private String template;
@Column(name = "filenameprefix")
private String fileNamePrefix;
@Column(name = "datemodified")
private Date dateModified;
@Column(name = "requesttype")
private String requestType;
}
|
package exercise_chapter6;
import java.util.Scanner;
public class exercise_6_4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("input a nubmer: ");
int number = input.nextInt();
System.out.println("the reverse is : " + reverse(number));
}
public static int reverse(int n) {
String str = String.valueOf(n);
StringBuffer str2 = new StringBuffer(str);
str2.reverse();
return Integer.parseInt(str2.toString());
}
}
|
package com.tencent.mm.ui;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.x;
class aa$10 implements Runnable {
final /* synthetic */ aa toC;
aa$10(aa aaVar) {
this.toC = aaVar;
}
public final void run() {
if (this.toC.tox) {
x.i("MicroMsg.LauncherUI.MainTabUnreadMgr", "remove setTagRunnable");
ah.M(this.toC.toy);
}
}
}
|
package symmetric_tree.v3;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class Solution {
public boolean isSymmetric(TreeNode root) {
return this.isMirror(root, root);
}
private boolean isMirror(TreeNode t0, TreeNode t1) {
while (t0 != null && t1 != null) {
if (t0.val != t1.val || !this.isMirror(t0.left, t1.right)) {
return false;
}
t0 = t0.right;
t1 = t1.left;
}
return t0 == t1;
}
}
|
/*
* Copyright 2018 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 example.offers;
import example.api.v1.Offer;
import reactor.core.publisher.Mono;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.Duration;
/**
* @author graemerocher
* @since 1.0
*/
public interface OffersOperations {
/**
* Save an offer for the given pet, vendor etc.
*
* @param slug pet's slug
* @param price The price
* @param duration The duration of the offer
* @param description The description of the offer
* @return The offer if it was possible to save it as a {@link Mono} or a empty {@link Mono} if no pet exists to create the offer for
*/
Mono<Offer> save(
@NotBlank String slug,
@Digits(integer = 6, fraction = 2) BigDecimal price,
@NotNull Duration duration,
@NotBlank String description);
}
|
package se.kth.iv1350.pointofsale.view;
import se.kth.iv1350.pointofsale.model.SaleDTO;
import se.kth.iv1350.pointofsale.model.SaleObserver;
/**
* Displays the total revenue of all sales since the program started.
*/
public class TotalRevenueDisplay implements SaleObserver {
private int totalRevenue;
/**
* Creates a new instance, where the total revenue is set to 0
*/
protected TotalRevenueDisplay(){
totalRevenue = 0;
}
/**
* Notifies the observer of a specified completed sale.
*
* @param finishedSale the completed sale
*/
@Override
public void newSale (SaleDTO finishedSale) {
addNewSale(finishedSale);
printCurrentState();
}
/**
* Adds the total cost of a specified sale to the total revenue.
*
* @param finishedSale the completed sale
*/
private void addNewSale(SaleDTO finishedSale) {
totalRevenue += finishedSale.getCompletedPayment().getAmountToPay().getAmountInCash();
}
/**
* Displays the total revenue
*/
public void printCurrentState(){
System.out.println("The total revenue is: " + totalRevenue + " SEK");
}
}
|
package com.tencent.mm.pluginsdk.ui.preference;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.tencent.mm.R;
import com.tencent.mm.ui.base.preference.Preference;
public final class HeadImgPreference extends Preference {
private ImageView gwj;
private int height;
public OnClickListener mVS;
private Bitmap qOJ;
public HeadImgPreference(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public HeadImgPreference(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.height = -1;
setLayoutResource(R.i.mm_preference);
}
protected final View onCreateView(ViewGroup viewGroup) {
View onCreateView = super.onCreateView(viewGroup);
ViewGroup viewGroup2 = (ViewGroup) onCreateView.findViewById(R.h.content);
viewGroup2.removeAllViews();
View.inflate(this.mContext, R.i.mm_preference_content_headimg, viewGroup2);
this.gwj = (ImageView) onCreateView.findViewById(R.h.image_headimg);
return onCreateView;
}
public final void O(Bitmap bitmap) {
this.qOJ = null;
if (this.gwj != null) {
this.gwj.setImageBitmap(bitmap);
} else {
this.qOJ = bitmap;
}
}
protected final void onBindView(View view) {
super.onBindView(view);
if (this.gwj == null) {
this.gwj = (ImageView) view.findViewById(R.h.image_headimg);
}
if (this.mVS != null) {
this.gwj.setOnClickListener(this.mVS);
}
if (this.qOJ != null) {
this.gwj.setImageBitmap(this.qOJ);
this.qOJ = null;
}
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.h.mm_preference_ll_id);
if (this.height != -1) {
linearLayout.setMinimumHeight(this.height);
}
}
}
|
package schr0.tanpopo.block.itemblock;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
public class ItemBlockEssenceCharcoalBlock extends ItemBlock
{
public ItemBlockEssenceCharcoalBlock(Block block)
{
super(block);
}
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.tabmodel;
import org.chromium.chrome.browser.Tab;
/**
* Observes changes to the tab model selector.
*/
public interface TabModelSelectorObserver {
/**
* Called whenever the {@link TabModel} has changed.
*/
void onChange();
/**
* Called when a new tab is created.
*/
void onNewTabCreated(Tab tab);
}
|
/*
* 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 modelo;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author alvaro
*/
public class modelo extends database {
public modelo () {}
//A continuacion se suceden los metodos destinados a rellenar las diferentes
//tablas con las que cuenta el programa.
//La primera es rellenar tabla viaje
public DefaultTableModel rellenarTablaViajes() {
System.out.println("Entra");
DefaultTableModel tablemodel = new DefaultTableModel();
int registros = 0;
//introducimos los nombres de las columnas
String[] columNames = {"id","nombre","categoria","descripcion", "fecha salida", "fecha llegada"};
//obtenemos la cantidad de registros existentes en la tabla y se almacena en la variable "registros"
//para formar la matriz de datos
String a;
a = "SELECT count(*) as total FROM viaje";
System.out.println("Despues del string a");
try{
PreparedStatement pstm = this.getConexion().prepareStatement(a);
ResultSet res = pstm.executeQuery();
res.next();
registros = res.getInt("total");
res.close();
}catch(SQLException e){
System.err.println( e.getMessage() );
}
//se crea una matriz con tantas filas y columnas que necesite
Object[][] data = new String[registros][7];
System.out.println("Sigue");
try{
//realizamos la consulta sql y llenamos los datos en la matriz "Object[][] data"
PreparedStatement pstm = this.getConexion().prepareStatement("SELECT * FROM viaje");
ResultSet res = pstm.executeQuery();
//realizamos la consulta de todos los datos de la tabla sobre la BD
int i=0;
while(res.next()){
//introducimos los datos en la tabla en orden, el primer parametro i
//se irá incrementando cada vez que se ejecute el método y asi irá
//sumando numeros de filas.
data[i][0] = res.getString( "id_viaje" );
data[i][1] = res.getString( "nombre_viaje" );
data[i][2] = res.getString( "categoria" );
data[i][3] = res.getString( "descripcion" );
data[i][4] = res.getString("fecha_salida" );
data[i][5] = res.getString( "fecha_llegada" );
i++;
}
res.close();
//se añade la matriz de datos en el DefaultTableModel
tablemodel.setDataVector(data, columNames );
}catch(SQLException e){
System.err.println( e.getMessage() );
}
return tablemodel;
}
//metodo utilizado para rellenar la tabla de rutas
public DefaultTableModel rellenarTablaRutas() {
System.out.println("Entra");
DefaultTableModel tablemodel = new DefaultTableModel();
int registros = 0;
String[] columNames = {"id","nombre"};
//obtenemos la cantidad de registros existentes en la tabla y se almacena en la variable "registros"
//para formar la matriz de datos
String a;
a = "SELECT count(*) as total FROM ruta";
System.out.println("Despues del string a");
try{
PreparedStatement pstm = this.getConexion().prepareStatement(a);
ResultSet res = pstm.executeQuery();
res.next();
registros = res.getInt("total");
res.close();
}catch(SQLException e){
System.err.println( e.getMessage() );
}
//se crea una matriz con tantas filas y columnas que necesite
Object[][] data = new String[registros][3];
System.out.println("Sigue");
try{
//realizamos la consulta sql y llenamos los datos en la matriz "Object[][] data"
PreparedStatement pstm = this.getConexion().prepareStatement("SELECT * FROM ruta");
ResultSet res = pstm.executeQuery();
int i=0;
while(res.next()){
data[i][0] = res.getString( "id_ruta" );
data[i][1] = res.getString( "nombre_ruta" );
i++;
}
res.close();
//se añade la matriz de datos en el DefaultTableModel
tablemodel.setDataVector(data, columNames );
}catch(SQLException e){
System.err.println( e.getMessage() );
}
return tablemodel;
}
//metodo utilizado para rellenar la tabla de hoteles
public DefaultTableModel rellenarTablaHoteles(String id_cliente) {
System.out.println("Entra");
DefaultTableModel tablemodel = new DefaultTableModel();
int registros = 0;
String[] columNames = {"HOTEL"};
//obtenemos la cantidad de registros existentes en la tabla y se almacena en la variable "registros"
//para formar la matriz de datos
String a;
a = "SELECT count(*) as total FROM alojamiento";
System.out.println("Despues del string a");
try{
PreparedStatement pstm = this.getConexion().prepareStatement(a);
ResultSet res = pstm.executeQuery();
res.next();
registros = res.getInt("total");
res.close();
}catch(SQLException e){
System.err.println( e.getMessage() );
}
//se crea una matriz con tantas filas y columnas que necesite
Object[][] data = new String[registros][3];
System.out.println("Sigue");
try{
//realizamos la consulta sql y llenamos los datos en la matriz "Object[][] data"
PreparedStatement pstm = this.getConexion().prepareStatement("SELECT nombre_hotel FROM alojamiento where id_cliente='"+id_cliente+"'");
ResultSet res = pstm.executeQuery();
int i=0;
while(res.next()){
data[i][0] = res.getString( "nombre_hotel" );
i++;
}
res.close();
//se añade la matriz de datos en el DefaultTableModel
tablemodel.setDataVector(data, columNames );
}catch(SQLException e){
System.err.println( e.getMessage() );
}
return tablemodel;
}
//metodo utilizado para rellenar la tabla del resumen de la reserva realizada
public DefaultTableModel rellenarTablaResumenReserva(String id_cliente) {
System.out.println("Entra");
DefaultTableModel tablemodel = new DefaultTableModel();
int registros = 0;
String[] columNames = {"ID CLIENTE", "ID VIAJE", "FECHA SALIDA", "FIANZA"};
//obtenemos la cantidad de registros existentes en la tabla y se almacena en la variable "registros"
//para formar la matriz de datos
String a;
a = "SELECT count(*) as total FROM reserva";
System.out.println("Despues del string a");
try{
PreparedStatement pstm = this.getConexion().prepareStatement(a);
ResultSet res = pstm.executeQuery();
res.next();
registros = res.getInt("total");
res.close();
}catch(SQLException e){
System.err.println( e.getMessage() );
}
//se crea una matriz con tantas filas y columnas que necesite
Object[][] data = new String[registros][4];
System.out.println("Sigue");
try{
//realizamos la consulta sql y llenamos los datos en la matriz "Object[][] data"
PreparedStatement pstm = this.getConexion().prepareStatement("SELECT * FROM reserva where id_cliente='"+id_cliente+"'");
ResultSet res = pstm.executeQuery();
int i=0;
while(res.next()){
data[i][0] = res.getString( "id_cliente" );
data[i][1] = res.getString( "id_viaje" );
data[i][2] = res.getString( "fecha_salida" );
data[i][3] = res.getString( "fianza" );
i++;
}
res.close();
//se añade la matriz de datos en el DefaultTableModel
tablemodel.setDataVector(data, columNames );
}catch(SQLException e){
System.err.println( e.getMessage() );
}
return tablemodel;
}
//con el siguiente metodo cargamos un jComboBox donde aparecen los puntos de las
//rutas con las que cuenta un viaje. Funciona de la misma manera que los metodos
//rellenar tabla, arriba explicado.
public DefaultComboBoxModel rellenaComboPuntos(int id){
DefaultComboBoxModel vector = new DefaultComboBoxModel();
int total=0;
try{
//se arma la consulta
PreparedStatement pstm = this.getConexion().prepareStatement( "SELECT count(*) as total FROM puntoruta");
//se ejecuta la consulta
ResultSet res1 = pstm.executeQuery();
res1.next();
total = res1.getInt("total");
res1.close();
}catch(SQLException e){
System.err.println( e.getMessage() );
}
int i=0;
Object[] data = new String[total];
String q = "select nombre_punto from puntoruta where id_punto in (select id_punto from rutatienepunto where id_ruta in (select id_ruta from viajetieneruta where id_viaje='"+id+"'));" ;
try {
//se arma la consulta
PreparedStatement pstm = this.getConexion().prepareStatement(q);
//se ejecuta la consulta
ResultSet resultado=pstm.executeQuery();
while(resultado.next()){
data[i]=resultado.getString("nombre_punto");
vector.addElement(data[i].toString());
i++;
}
pstm.close();
resultado.close();
}catch(SQLException e){
System.err.println(e.getMessage());
}
return vector;
}
//metodo utulzado para cargar el comboBox de los hoteles que tienen asignados
//los puntos con los que cuentan las rutas de los viajes
public DefaultComboBoxModel rellenarComboHotel(String nombre_punto){
DefaultComboBoxModel vector = new DefaultComboBoxModel();
int total=0;
try{
//se arma la consulta
PreparedStatement pstm = this.getConexion().prepareStatement( "SELECT count(*) as total FROM puntoruta");
//se ejecuta la consulta
ResultSet res1 = pstm.executeQuery();
res1.next();
total = res1.getInt("total");
res1.close();
}catch(SQLException e){
System.err.println( e.getMessage() );
}
int i=0;
Object[] data = new String[total];
String q="select hotel from puntoruta where nombre_punto='"+nombre_punto+"';";
try {
//se arma la consulta
PreparedStatement pstm = this.getConexion().prepareStatement(q);
//se ejecuta la consulta
ResultSet resultado=pstm.executeQuery();
while(resultado.next()){
data[i]=resultado.getString("hotel");
vector.addElement(data[i].toString());
i++;
}
pstm.close();
resultado.close();
}catch(SQLException e){
System.err.println(e.getMessage());
}
return vector;
}
//Con este metodo conseguimos rellenar un jList que contiene informacion de los hoteles.
//esta informacion se obtiene a partir de los puntos que aparecen en un jComboBox, que a su
//vez obtiene la informacion a partir de la tabla viajes.
public DefaultListModel rellenaListaHoteles(String hotel){
DefaultListModel vector = new DefaultListModel();
int total=0;
try{
//se arma la consulta
PreparedStatement pstm = this.getConexion().prepareStatement( "SELECT count(*) as total FROM puntoruta");
//se ejecuta la consulta
ResultSet res1 = pstm.executeQuery();
res1.next();
total = res1.getInt("total");
res1.close();
}catch(SQLException e){
System.err.println( e.getMessage() );
}
int i=0;
Object[] data = new String[total];
String q = "select hotel from puntoruta where hotel='"+hotel+"' and hotel !='Visita, Hotel No Disponible';" ;
try {
//se arma la consulta
PreparedStatement pstm = this.getConexion().prepareStatement(q);
//se ejecuta la consulta
ResultSet resultado=pstm.executeQuery();
while(resultado.next()){
data[i]=resultado.getString("hotel");
vector.addElement(data[i].toString());
i++;
}
pstm.close();
resultado.close();
}catch(SQLException e){
System.err.println(e.getMessage());
}
return vector;
}
//Este metodo "añadirViaje" realiza un insert en la baase de datos sobre la tabla especificada
public void añadirViaje(String nombre,String categoria,String descripcion, Date fecha_salida, Date fecha_llegada){
//introducimos en una variable "Q" la consulta que queremos realizar sobre la base de datos
String q="insert into viaje (nombre_viaje, categoria, descripcion, fecha_salida, fecha_llegada) values ('"+nombre+"','"+categoria+"','"+descripcion+"', '"+fecha_salida+"', '"+fecha_llegada+"')";
System.out.println(q);
try{
//se realiza la consulta
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
//Realiza la misma funcion que el metodo arriba explicado "añadirViaje, pero en este caso
//la consulta que se realiza no es un insert si no un delete
public void eliminarViaje(String id){
String q="delete from viaje where id_viaje='"+id+"'";
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
System.err.println( e.getMessage() );
JOptionPane.showMessageDialog(null,"No se puede realizar la operación:\nZona actualmente activa");
}
}
//al igual que los dos ultimos métodos que se han definido, este, realiza una consulta sobre la
//base de datos, haciendo en este caso un update
public void moificarViaje(String nombre_viaje,String categoria ,String descripcion, String fechaSalida, String fechaLlegada, String id){
String q="update viaje set nombre_viaje ='"+nombre_viaje+"', categoria='"+categoria+"', descripcion='"+descripcion+"', fecha_salida='"+fechaSalida+"', fecha_llegada='"+fechaLlegada+"' where id_viaje='"+id+"';";
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
//realiza un insert sobre la base de datos
public void añadirPunto(String id_punto, String nombre_punto, String tipo, String hotel){
String q="insert into puntoruta (id_punto, nombre_punto, tipo, hotel) values ('"+id_punto+"','"+nombre_punto+"','"+tipo+"','"+hotel+"')";
System.out.println(q);
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
//realiza un insert sobre la base de datos
public void añadirRuta(String id_ruta,String puntoA, String puntoB){
String q="insert into ruta (id_ruta, nombre_ruta) values ('"+id_ruta+"','"+puntoA+"-"+puntoB+"')";
System.out.println(q);
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
//realiza un insert sobre la base de datos
public void añadirRutaTienePunto(String id_ruta, String id_punto){
String q="insert into rutatienepunto (id_ruta, id_punto) values ('"+id_ruta+"', '"+id_punto+"')";
System.out.println(q);
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
//realiza un insert sobre la base de datos
public void asignarRuta(String id_viaje, String id_ruta, Date fechasalida, Date fechallegada){
String q="insert into viajetieneruta (id_viaje, id_ruta, fecha_salida, fecha_llegada) values ('"+id_viaje+"', '"+id_ruta+"', '"+fechasalida+"', '"+fechallegada+"')";
System.out.println(q);
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
//Con este método conseguiremos recoger un dato de la BD, haciendo un select.
public String getContraseña(){
String q = "select contraseña from contraseña";
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
System.err.println( e.getMessage() );
}
return q;
}
//realiza un insert sobre la base de datos
public void añadirAlojamiento(String id_cliente, String nombre_hotel){
String q="insert into alojamiento (id_cliente, nombre_hotel) values ('"+id_cliente+"','"+nombre_hotel+"')";
System.out.println(q);
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
//realiza un delete sobre la base de datos
public void eliminaHotel(String id_cliente, String nombre_hotel){
String q="delete from alojamiento where id_cliente='"+id_cliente+"' and nombre_hotel='"+nombre_hotel+"';";
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
System.err.println( e.getMessage() );
JOptionPane.showMessageDialog(null,"No se puede realizar la operación:\nZona actualmente activa");
}
}
//realiza un insert sobre la base de datos
public void añadirReserva(String id_cliente, String id_viaje, String fecha_salida){
String q="insert into reserva (id_cliente, id_viaje, fecha_salida, fianza) values ('"+id_cliente+"','"+id_viaje+"','"+fecha_salida+"', 'pagada')";
System.out.println(q);
try{
PreparedStatement pstm = this.getConexion().prepareStatement(q);
pstm.execute();
pstm.close();
JOptionPane.showMessageDialog(null,"Operación Realizada");
}catch(SQLException e){
JOptionPane.showMessageDialog(null,"Error: Los datos son incorrectos.\nReviselos y vuelva a intentarlo");
System.err.println( e.getMessage() );
}
}
}
|
package com.mengdo.pub.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author:piaoxj
* @date:15-2-16
* @email:piaoxj89@gmail.com
*/
public class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private static String PARAMTER_NAME_REGEX = "";
private static String PARAMTER_VALUE_REGEX = "";
private static String PARAMTER_VALUE_REGEX_JSON = "";
private static Properties properties = null;
static{
PARAMTER_NAME_REGEX = "[^a-zA-Z0-9_\\-]";
PARAMTER_VALUE_REGEX = "[~`%'\\\\]";
PARAMTER_VALUE_REGEX_JSON = "[~`%^\\\\]";
}
private HttpUtils(){
}
public static Map<String, String> getParameterMap(HttpServletRequest request) {
Map<String,String> paramMap = new HashMap<String,String>();
Map properties = request.getParameterMap();
paramMap = getParameterMap_(properties);
return paramMap;
}
/**
* 此方法为去点ESAPI接口的
* @param properties
* @return
*/
public static Map<String,String> getParameterMap_(Map properties){
Map<String,String> paramMap = new HashMap<String,String>();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
boolean flagName = false;
boolean flagValue = false;
while (entries.hasNext()){
entry = (Map.Entry) entries.next();
name = ((String)entry.getKey()).replaceAll(PARAMTER_NAME_REGEX, "");
if("passwd".equals(name)){
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
paramMap.put(name, value);
}else {
if(!name.equals((String)entry.getKey())){
flagName = true;
}
String temp = "";
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
temp = values[i] + ",";
}
temp = temp.substring(0, temp.length()-1);
value = temp ; //.replaceAll(PARAMTER_VALUE_REGEX, "");
if(!value.equals(temp)){
flagValue = true;
}
}else{
temp = valueObj.toString();
value = temp ; //.replaceAll(PARAMTER_VALUE_REGEX, "");
if(!value.equals(valueObj.toString())){
flagValue = true;
}
}
if(flagName || flagValue){
flagName = false;
flagValue = false;
logger.info("The request parameter : [" + (String)entry.getKey() + "=" + temp + "] replaced by : [" + name + "=" + value + "]");
}
paramMap.put(name, value);
}
}
return paramMap;
}
public static void main(String[] args) {
String str ="2015033175253310^0.01^SUCCESS^true^S";
String value = str.replaceAll(PARAMTER_VALUE_REGEX, "");
System.out.println(value);
}
public static Map<String, String> getParameterMap_N(HttpServletRequest request){
Map<String, String> paramMap = new HashMap<String, String>();
Map<String, Object> reqMap = request.getParameterMap();
Iterator<Map.Entry<String, Object>> entries = reqMap.entrySet().iterator();
while (entries.hasNext()){
Map.Entry<String, Object> entry = entries.next();
String name = entry.getKey();
String value = "";
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
} else if (valueObj instanceof String[]) {
String[] values = (String[]) valueObj;
for (int i = 0; i < values.length; i++) {
value = values[i] + ",";
}
value = value.substring(0, value.length() - 1);
} else {
value = valueObj.toString();
}
paramMap.put(name, value);
}
return paramMap;
}
/**
* 从请求url中获取action名称,即请求命令
* @param request
* @return
*/
public static String getActionName(HttpServletRequest request){
String uri = request.getRequestURI();
String[] stemps = uri.split("/");
String action = "";
if(stemps == null || stemps.length <= 0){
action = uri;
}else{
action = stemps[stemps.length-1];
}
String[] actions = action.split("\\.");
String command = actions[0];
return command;
}
public static String getLocationAddress(){
String ip = null;
Inet4Address ip4 = null;
try{
ip4 = (Inet4Address) Inet4Address.getLocalHost();
ip = ip4.getHostAddress();
}catch (UnknownHostException e){
e.printStackTrace();
}
return ip;
}
/**
* 从请求url中获取remoteIp
* @param request
* @return
*/
public static String getRemoteIp(HttpServletRequest request){
String ip = request.getHeader("x-real-ip");
if(ip == null){
ip = request.getRemoteAddr();
}
//过滤反向代理的ip
String[] stemps = ip.split(",");
if(stemps != null && stemps.length >= 1){
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
ip = ip.trim();
if(ip.length() > 23){
ip = ip.substring(0,23);
}
return ip;
}
public static String getRemoteIpAdm(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
//过滤反向代理的ip
String[] stemps = ip.split(",");
if(stemps != null && stemps.length >= 1){
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
ip = ip.trim();
if(ip.length() > 23){
ip = ip.substring(0,23);
}
return ip;
}
/**
* 从http头里获取编码格式
* @param header
* @return
*/
public static String getEncoding(String header){
String charset = "UTF-8";
if(header == null || header.trim().equals("")){
return charset;
}
if(matcher(header, "(charset)\\s?=\\s?(utf-?8)")){
charset = "UTF-8";
}else if(matcher(header, "(charset)\\s?=\\s?(gbk)")){
charset = "GBK";
}else if(matcher(header, "(charset)\\s?=\\s?(gb2312)")){
charset = "GB2312";
}
return charset;
}
public static boolean matcher(String s, String pattern){
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE);
Matcher matcher = p.matcher(s);
if(matcher.find()){
return true;
}else{
return false;
}
}
/**
* 将map的值转换成字符串
* @param map
* @return
*/
public static String map2String(Map map){
String ret = "";
if (map == null || map.isEmpty()){
return ret;
}
Iterator entries = map.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()){
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
// value = hiddenLogValue(name,value);
ret = ret + name + "=" + value + ";";
}
return ret;
}
// private static String hiddenLogValue(String name, String value) {
// if("cardId".equals(name)||"mobile".equals(name)||"identityCode".equals(name)||"cvv".equals(name)||"validCode".equals(name)){
// value = "******";
// }
// return value;
// }
/**
* 返回给商户的结果串
* @param map
* @return
*/
@SuppressWarnings("rawtypes")
public static String retMerchantString(Map<String, String> map)
{
String ret = "";
Iterator entries = map.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext())
{
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else{
value = valueObj.toString();
}
if(ret.length() <= 0)
ret = name + "=" + value;
else
ret = ret + "&" + name + "=" + value;
}
return ret;
}
/**
* 过滤html标签
* @param inputString
* @return
*/
public static String htmlToTextGb2312(String inputString)
{
String htmlStr = inputString; //含html标签的字符串
String textStr ="";
Pattern p_script;
Matcher m_script;
Pattern p_style;
Matcher m_style;
Pattern p_html;
Matcher m_html;
Pattern p_houhtml;
Matcher m_houhtml;
Pattern p_spe;
Matcher m_spe;
Pattern p_blank;
Matcher m_blank;
Pattern p_table;
Matcher m_table;
Pattern p_enter;
Matcher m_enter;
try {
String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
//定义script的正则表达式.
String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
//定义style的正则表达式.
String regEx_html = "<[^>]+>";
//定义HTML标签的正则表达式
String regEx_houhtml = "/[^>]+>";
//定义HTML标签的正则表达式
String regEx_spe="\\&[^;]+;";
//定义特殊符号的正则表达式
String regEx_blank=" +";
//定义多个空格的正则表达式
String regEx_table="\t+";
//定义多个制表符的正则表达式
String regEx_enter="\n+";
//定义多个回车的正则表达式
p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); //过滤script标签
p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); //过滤style标签
p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); //过滤html标签
p_houhtml = Pattern.compile(regEx_houhtml, Pattern.CASE_INSENSITIVE);
m_houhtml = p_houhtml.matcher(htmlStr);
htmlStr = m_houhtml.replaceAll(""); //过滤html标签
p_spe = Pattern.compile(regEx_spe, Pattern.CASE_INSENSITIVE);
m_spe = p_spe.matcher(htmlStr);
htmlStr = m_spe.replaceAll(""); //过滤特殊符号
p_blank = Pattern.compile(regEx_blank, Pattern.CASE_INSENSITIVE);
m_blank = p_blank.matcher(htmlStr);
htmlStr = m_blank.replaceAll(" "); //过滤过多的空格
p_table = Pattern.compile(regEx_table, Pattern.CASE_INSENSITIVE);
m_table = p_table.matcher(htmlStr);
htmlStr = m_table.replaceAll(" "); //过滤过多的制表符
p_enter = Pattern.compile(regEx_enter, Pattern.CASE_INSENSITIVE);
m_enter = p_enter.matcher(htmlStr);
htmlStr = m_enter.replaceAll(" "); //过滤过多的制表符
textStr = htmlStr;
}catch(Exception e)
{
}
return textStr;//返回文本字符串
}
/**
* 获取本机IP
* @return
*/
public static String getLocalIp(){
String ip="";
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.error("get ip error"+ e.getMessage());
}
return ip;
}
/**
* 将request中的参数转换成Map保留JSON格式
*
* @param request
* @return
* @author dazhang
* @date 2014-11-6
* @time 下午04:24:47
*/
public static Map<String,String> getParameterMapJSON(HttpServletRequest request){
Map<String,String> paramMap = new HashMap<String,String>();
Map properties = request.getParameterMap();
paramMap = getParameterMap_JSON(properties);
return paramMap;
}
/**
* 此方法为去点ESAPI接口的
* 保留JSON格式参数值
*
* @param properties
* @return
* @author dazhang
* @date 2014-11-6
* @time 下午04:11:43
*/
public static Map<String,String> getParameterMap_JSON(Map properties){
Map<String,String> paramMap = new HashMap<String,String>();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
boolean flagName = false;
boolean flagValue = false;
while (entries.hasNext()){
entry = (Map.Entry) entries.next();
name = ((String)entry.getKey()).replaceAll(PARAMTER_NAME_REGEX, "");
if("passwd".equals(name)){
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
paramMap.put(name, value);
}else {
if(!name.equals((String)entry.getKey())){
flagName = true;
}
String temp = "";
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
temp = values[i] + ",";
}
temp = temp.substring(0, temp.length()-1);
value = temp.replaceAll(PARAMTER_VALUE_REGEX_JSON, "");
if(!value.equals(temp)){
flagValue = true;
}
}else{
temp = valueObj.toString();
value = temp.replaceAll(PARAMTER_VALUE_REGEX_JSON, "");
if(!value.equals(valueObj.toString())){
flagValue = true;
}
}
if(flagName || flagValue){
flagName = false;
flagValue = false;
//logger.info("The request parameter : [" + (String)entry.getKey() + "=" + temp + "] replaced by : [" + name + "=" + value + "]");
}
paramMap.put(name, value);
}
}
return paramMap;
}
/**
* InputStream 转 String
* @param stream
* @return
*/
public static String convertStreamToString(InputStream stream){
if(stream == null){
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(stream != null){
try {
stream.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
return sb.toString();
}
/*public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("sign", "{'cardId':'6226123456789012','mobile':'13800138000','identityCode':'110100200012100909','passwd':'123456','validCode':'1234','token':'43210987'}");
System.out.println(getParameterMap_JSON(map));
}*/
}
|
package com.cse308.sbuify.label.payment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
public interface PaymentRepository extends CrudRepository<Payment, Integer> {
Page<Payment> findAllByStatusAndPeriod_Id(PaymentStatus status, Integer periodId, Pageable pageable);
Page<Payment> findAllByStatus(PaymentStatus status, Pageable pageable);
Page<Payment> findAllByPeriod_Id(Integer period, Pageable pageable);
Page<Payment> findAll(Pageable pageable);
}
|
/**
* Establishes the Isoceles Triangle class, extending EquilaterialTriangle, and constructor!
*
* @author C. Thurston
* @version 5/1/2014
*/
public class IsoscelesTriangle extends EquilateralTriangle
{
private double sideB;
public IsoscelesTriangle(double A, double B)
{
super(A);
this.sideB = B;
}
public double getB()
{
return sideB;
}
}
|
package creational.design.pattern.Factory;
public class AlgorithmFactory {
public static final int SHORTEST_PATH = 0;
public static final int SPANNING_TREE=1;
public static AlgorithmInterface createAlgorithm(int type) {
switch (type) {
case SHORTEST_PATH:
return new ShortestPathProblem();
case SPANNING_TREE:
return new SpanningTreeProblem();
default:
return null;
}
}
}
|
package com.croxx.hgwechat.model.didiumbrella;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;
@Entity
public class DidiUmbrellaUser {
@Id
@JsonIgnore
private String openid;
@JsonIgnore
private String session_key;
private String token;
private Date expire_time;
public DidiUmbrellaUser() {
}
public void freshToken(String token) {
this.token = token;
this.expire_time = new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000);
}
/* Getters & Setters */
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getSession_key() {
return session_key;
}
public void setSession_key(String session_key) {
this.session_key = session_key;
}
public String getToken() {
return token;
}
public Date getExpire_time() {
return expire_time;
}
}
|
package gui.resources;
import gui.left_panel.PanelElements;
import javafx.scene.image.Image;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import static gui.resources.Constants.*;
public class Images {
private static final Map<String, Image> images = new HashMap<>();
public static Image getImage(String name) {
return images.get(name);
}
private static InputStream getResourceFile(String name){
return Images.class.getResourceAsStream(name);
}
static {
images.put(PanelElements.USER_PROFILE, new Image(getResourceFile(ImagesPaths.USER_ICON)));
images.put(PanelElements.BET_REGISTRY, new Image(getResourceFile(ImagesPaths.BET_REGISTRY_ICON)));
images.put(PanelElements.BETS_HISTORY, new Image(getResourceFile(ImagesPaths.BETS_HISTORY_ICON)));
images.put(PanelElements.NOTIFICATIONS, new Image(getResourceFile(ImagesPaths.NOTIFICATIONS_ICON)));
images.put(PanelElements.STATISTICS, new Image(getResourceFile(ImagesPaths.STATISTICS_ICON)));
images.put(TRASH_BIN_ICON,new Image(getResourceFile(ImagesPaths.TRASH_ICON)));
images.put(EDIT_ICON,new Image(getResourceFile(ImagesPaths.EDIT_ICON)));
images.put(MARK_ICON,new Image(getResourceFile(ImagesPaths.MARK_ICON)));
images.put(CROSS_ICON,new Image(getResourceFile(ImagesPaths.CROSS_ICON)));
images.put(STATISTICS_BACKGROUND, new Image(getResourceFile(ImagesPaths.STATISTICS_BACKGROUND)));
images.put(APP_LOGO, new Image(getResourceFile(ImagesPaths.PROFIT_STATS_LOGO)));
images.put(BET_REGISTRY_BACKGROUND, new Image(getResourceFile(ImagesPaths.BET_REGISTRY_BACKGROUND)));
images.put(NOTIFICATIONS_BACKGROUND, new Image(getResourceFile(ImagesPaths.NOTIFICATIONS_BACKGROUND)));
images.put(USER_PROFILE_BACKGROUND, new Image(getResourceFile(ImagesPaths.USER_PROFILE_BACKGROUND)));
}
}
|
package com.tencent.mm.plugin.extqlauncher;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.sdk.e.m;
import com.tencent.mm.sdk.e.m.b;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
class b$1 implements b {
final /* synthetic */ b iLM;
b$1(b bVar) {
this.iLM = bVar;
}
public final void a(int i, m mVar, Object obj) {
x.d("MicroMsg.SubCoreExtQLauncher", "onNotifyChange");
if (!this.iLM.iLD) {
au.HU();
if (mVar != c.FW()) {
return;
}
if (mVar == null || obj == null) {
x.e("MicroMsg.SubCoreExtQLauncher", "onConversationChange, wrong args");
} else if (ad.getContext() == null || !au.HX()) {
x.w("MicroMsg.SubCoreExtQLauncher", "wrong account status");
} else {
this.iLM.aJn();
}
}
}
}
|
package com.learn_basic.lock;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
// 创建一个具有固定线程数量的线程池对象(推荐使用构造方法创建)
ExecutorService threadPool = Executors.newFixedThreadPool(10);
final int threadCount = 6;
final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
final int threadnum = i;
threadPool.execute(() -> {
try {
System.out.println("子线程 " + Thread.currentThread().getName() + " 正在执行");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("子线程 " + Thread.currentThread().getName() + " 执行完毕");
countDownLatch.countDown(); // 表示一个文件已经被完成, 计数器减一
}
});
}
System.out.println("执行完了吗?");
countDownLatch.await(); // 阻塞,直到 countDownLatch.getCount() == 0
threadPool.shutdown();
System.out.println("执行完了!");
}
}
|
/*
* Copyright (c) 2016. Universidad Politecnica de Madrid
*
* @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es>
*
*/
package org.librairy.modeler.lda.tasks;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Doubles;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.DataFrame;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.librairy.boot.model.Event;
import org.librairy.boot.model.domain.resources.Domain;
import org.librairy.boot.model.domain.resources.Resource;
import org.librairy.boot.model.modules.RoutingKey;
import org.librairy.boot.storage.dao.DBSessionManager;
import org.librairy.boot.storage.dao.DomainsDao;
import org.librairy.boot.storage.generator.URIGenerator;
import org.librairy.computing.cluster.ComputingContext;
import org.librairy.metrics.aggregation.Bernoulli;
import org.librairy.modeler.lda.dao.ShapeRow;
import org.librairy.modeler.lda.dao.ShapesDao;
import org.librairy.modeler.lda.functions.RowToArray;
import org.librairy.modeler.lda.helper.ModelingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Optional;
/**
* Created on 12/08/16:
*
* @author cbadenes
*/
public class LDASubdomainShapingTask implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(LDASubdomainShapingTask.class);
public static final String ROUTING_KEY_ID = "lda.subdomains.shapes.created";
private final ModelingHelper helper;
private final String domainUri;
public LDASubdomainShapingTask(String domainUri, ModelingHelper modelingHelper) {
this.domainUri = domainUri;
this.helper = modelingHelper;
}
@Override
public void run() {
// get subdomains
try{
LOG.info("generating shapes for sub-domains of: '" + domainUri + "' ..");
Integer size = 100;
Optional<String> offset = Optional.empty();
while(true){
List<Domain> subdomains = helper.getDomainsDao().listSubdomains(domainUri, size, offset, false);
for(Domain subdomain: subdomains){
shapeSubdomain(subdomain.getUri(), domainUri);
}
if (subdomains.size() < size) break;
offset = Optional.of(subdomains.get(size-1).getUri());
}
LOG.info("subdomain shapes created from: '" + domainUri + "' ..");
helper.getEventBus().post(Event.from(domainUri), RoutingKey.of(ROUTING_KEY_ID));
}catch (Exception e){
LOG.error("Unexpected error", e);
}
}
private void shapeSubdomain(String subdomainUri, String domainUri){
try{
final ComputingContext context = helper.getComputingHelper().newContext("lda.subdomains."+ URIGenerator.retrieveId(domainUri));
helper.getComputingHelper().execute(context, () -> {
try{
LOG.info("creating shape for sub-domain '"+ subdomainUri+"'");
DataFrame itemsDF = context.getCassandraSQLContext()
.read()
.format("org.apache.spark.sql.cassandra")
.schema(DataTypes
.createStructType(new StructField[]{
DataTypes.createStructField("resource", DataTypes.StringType, false),
DataTypes.createStructField("domain", DataTypes.StringType, false),
DataTypes.createStructField("type", DataTypes.StringType, false)
}))
.option("inferSchema", "false") // Automatically infer data types
.option("charset", "UTF-8")
.option("mode", "DROPMALFORMED")
.options(ImmutableMap.of("table", DomainsDao.TABLE_NAME, "keyspace", DBSessionManager.getCommonKeyspaceId()))
.load()
.where("domain='"+subdomainUri+"' and type='"+ Resource.Type.ITEM.key() + "'")
;
DataFrame shapesDF = context.getCassandraSQLContext()
.read()
.format("org.apache.spark.sql.cassandra")
.schema(DataTypes
.createStructType(new StructField[]{
DataTypes.createStructField(ShapesDao.RESOURCE_URI, DataTypes.StringType, false),
DataTypes.createStructField(ShapesDao.VECTOR, DataTypes.createArrayType(DataTypes.DoubleType), false)
}))
.option("inferSchema", "false") // Automatically infer data types
.option("charset", "UTF-8")
.option("mode", "DROPMALFORMED")
.options(ImmutableMap.of("table", ShapesDao.TABLE, "keyspace", DBSessionManager.getSpecificKeyspaceId("lda",URIGenerator.retrieveId(domainUri))))
.load();
DataFrame distTopicsDF = itemsDF
.join(shapesDF, itemsDF.col("resource").equalTo(shapesDF.col(ShapesDao.RESOURCE_URI)));
JavaRDD<double[]> rows = distTopicsDF
.toJavaRDD()
.filter(row -> row.get(4) != null)
.map(new RowToArray())
.persist(helper.getCacheModeHelper().getLevel());
;
LOG.info("generating shape for subdomain: " + subdomainUri + " in domain: " + domainUri + " ..");
double[] shape = rows.reduce((a, b) -> Bernoulli.apply(a, b));
rows.unpersist();
if ((shape != null) && (shape.length > 0)){
ShapeRow row = new ShapeRow();
row.setUri(subdomainUri);
row.setVector(Doubles.asList(shape));
row.setId(Long.valueOf(Math.abs(subdomainUri.hashCode())));
helper.getShapesDao().save(domainUri, row);
LOG.info("shape saved!");
}
} catch (Exception e){
// TODO Notify to event-bus when source has not been added
LOG.error("Error scheduling a new topic model for Items from domain: " + domainUri, e);
}
});
} catch (InterruptedException e) {
LOG.info("Execution interrupted.");
}
}
}
|
package codewars;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.Arrays.stream;
/**
* Given an array, find the int that appears an odd number of times.
*
* There will always be only one integer that appears an odd number of times.
*/
public class FindTheOddInt {
public static int findIt(int[] a) {
Map<Integer,Integer> counterMap = new HashMap<>();
for (int value : a) {
if (counterMap.containsKey(value)) {
counterMap.put(value, counterMap.get(value) + 1);
} else {
counterMap.put(value, 1);
}
}
for (Map.Entry i : counterMap.entrySet()){
if(!((int)i.getValue() % 2 == 0)) {
return (int) i.getKey();
}
}
return 1;
}
public static int findIt1(int[] a) {
return stream(a)
.boxed()
.collect(Collectors.groupingBy(Function.identity()))
.entrySet()
.stream()
.filter(e -> e.getValue().size() % 2 == 1)
.mapToInt(e -> e.getKey())
.findFirst()
.getAsInt();
}
public static int findIt2(int[] arr) {
return stream(arr).reduce(0, (x, y) -> x ^ y);
}
}
|
/**
*
*/
package kit.edu.pse.goapp.server.tests;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import org.mockito.Mockito;
import kit.edu.pse.goapp.server.daos.DatabaseConnection;
import kit.edu.pse.goapp.server.daos.UserDaoImpl;
import kit.edu.pse.goapp.server.datamodels.User;
import kit.edu.pse.goapp.server.exceptions.CustomServerException;
/**
* @author Iris
*
*/
public class UserDaoTest extends UserDaoImpl {
@Test(expected = CustomServerException.class)
public void addUserWithoutName() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setGoogleId("test");
dao.addUser(Mockito.mock(DatabaseConnection.class));
}
@Test(expected = CustomServerException.class)
public void addUserWithEmptyName() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setName("");
dao.setGoogleId("test");
dao.addUser(Mockito.mock(DatabaseConnection.class));
}
@Test(expected = CustomServerException.class)
public void addUserWithoutGoogleId() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setName("test");
dao.addUser(Mockito.mock(DatabaseConnection.class));
}
@Test(expected = CustomServerException.class)
public void addUserWithEmptyGoogleId() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setName("test");
dao.setGoogleId("");
dao.addUser(Mockito.mock(DatabaseConnection.class));
}
@Test()
public void addUserSuccessfully() throws Exception {
// Stubbing behavior
DatabaseConnection mock = Mockito.mock(DatabaseConnection.class);
Mockito.when(mock.insert(Mockito.anyString())).thenReturn(1);
UserDaoTest dao = new UserDaoTest();
dao.setName("User 1");
dao.setGoogleId("googleID = 1");
dao.setNotificationEnabled(true);
dao.addUser(mock);
}
@Test(expected = IOException.class)
public void addUserFails() throws Exception {
// Stubbing behavior
DatabaseConnection mock = Mockito.mock(DatabaseConnection.class);
Mockito.when(mock.insert(Mockito.anyString())).thenReturn(-1);
UserDaoTest dao = new UserDaoTest();
dao.setName("User 1");
dao.setGoogleId("googleID = 1");
dao.setNotificationEnabled(true);
dao.addUser(mock);
}
@Test(expected = CustomServerException.class)
public void getUserByIdWithoutId() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.getUserByID(Mockito.mock(DatabaseConnection.class));
}
@Test()
public void getUserByIdSuccessfully() throws Exception {
User expectedUser = new User(1, "test");
// Stubbing behavior
DatabaseConnection mock = Mockito.mock(DatabaseConnection.class);
UserDaoTest dao = new UserDaoTest();
dao.setUserId(1);
dao.setName("test");
User user = dao.getUserByID(mock);
assertEquals(expectedUser.getId(), user.getId());
assertEquals(expectedUser.getName(), user.getName());
}
@Test(expected = CustomServerException.class)
public void deleteUserWithoutId() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.deleteUser(Mockito.mock(DatabaseConnection.class));
}
@Test()
public void deleteUserSuccessfully() throws Exception {
// Stubbing behavior
DatabaseConnection mock = Mockito.mock(DatabaseConnection.class);
UserDaoTest dao = new UserDaoTest();
dao.setUserId(1);
dao.deleteUser(mock);
}
@Test(expected = CustomServerException.class)
public void updateUserWithoutId() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setName("test");
dao.updateUser(Mockito.mock(DatabaseConnection.class));
}
@Test(expected = CustomServerException.class)
public void updateUserWithoutName() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setUserId(1);
dao.updateUser(Mockito.mock(DatabaseConnection.class));
}
@Test(expected = CustomServerException.class)
public void updateUserWithEmptyName() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setUserId(1);
dao.setName("");
dao.updateUser(Mockito.mock(DatabaseConnection.class));
}
@Test()
public void updateUserSuccessfully() throws Exception {
// Stubbing behavior
DatabaseConnection mock = Mockito.mock(DatabaseConnection.class);
UserDaoTest dao = new UserDaoTest();
dao.setUserId(1);
dao.setName("test");
dao.setNotificationEnabled(true);
dao.updateUser(mock);
}
@Test()
public void getAllUsersSuccessfully() throws Exception {
// Stubbing behavior
DatabaseConnection mock = Mockito.mock(DatabaseConnection.class);
UserDaoTest dao = new UserDaoTest();
dao.getAllUsers(mock);
}
@Test(expected = CustomServerException.class)
public void getUserByGoogleIdWithoutGoogleId() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.getUserByGoogleID(Mockito.mock(DatabaseConnection.class));
}
@Test(expected = CustomServerException.class)
public void getUserByGoogleIdWithEmptyGoogleId() throws Exception {
UserDaoTest dao = new UserDaoTest();
dao.setGoogleId("");
dao.getUserByGoogleID(Mockito.mock(DatabaseConnection.class));
}
@Test()
public void getUserByGoogleIdSuccessfully() throws Exception {
User expectedUser = new User(1, "test");
// Stubbing behavior
DatabaseConnection mock = Mockito.mock(DatabaseConnection.class);
UserDaoTest dao = new UserDaoTest();
dao.setGoogleId("google");
dao.setUserId(1);
dao.setName("test");
User user = dao.getUserByGoogleID(mock);
assertEquals(expectedUser.getId(), user.getId());
assertEquals(expectedUser.getName(), user.getName());
}
}
|
package com.example.healthmanage.ui.activity.consultationinfo;
import android.os.Bundle;
import android.widget.RadioGroup;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.healthmanage.BR;
import com.example.healthmanage.R;
import com.example.healthmanage.base.BaseActivity;
import com.example.healthmanage.base.BaseAdapter;
import com.example.healthmanage.databinding.ActivityConsultationInformationBinding;
import com.example.healthmanage.bean.recyclerview.ConsultationInformationRecyclerView;
import com.example.healthmanage.widget.TitleToolBar;
import java.util.List;
public class ConsultationInfoActivity extends BaseActivity<ActivityConsultationInformationBinding, ConsultationInfoViewModel> {
private TitleToolBar titleToolBar = new TitleToolBar();
BaseAdapter consultationInfoAdapter;
@Override
protected void initData() {
titleToolBar.setLeftIconVisible(true);
titleToolBar.setTitle("咨询信息");
viewModel.setTitleToolBar(titleToolBar);
viewModel.getConsultationList(0);
}
@Override
public void initViewListener() {
super.initViewListener();
titleToolBar.setOnClickCallBack(new TitleToolBar.OnTitleIconClickCallBack() {
@Override
public void onRightIconClick() {
}
@Override
public void onBackIconClick() {
finish();
}
});
}
@Override
protected void registerUIChangeEventObserver() {
super.registerUIChangeEventObserver();
consultationInfoAdapter = new BaseAdapter(this, null,
R.layout.recycler_view_item_consultation_information,
BR.ConsultationInformationRecyclerView);
dataBinding.recyclerViewConsultationInformation.setLayoutManager(new LinearLayoutManager(this));
dataBinding.recyclerViewConsultationInformation.setAdapter(consultationInfoAdapter);
viewModel.consultationInfoMutableLiveData.observe(this, new Observer<List<ConsultationInformationRecyclerView>>() {
@Override
public void onChanged(List<ConsultationInformationRecyclerView> consultationInformationRecyclerViews) {
consultationInfoAdapter.setRecyclerViewList(consultationInformationRecyclerViews);
consultationInfoAdapter.notifyDataSetChanged();
}
});
dataBinding.rgTitle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_untreated:
viewModel.getConsultationList(0);
break;
case R.id.rb_processing:
viewModel.getConsultationList(1);
break;
case R.id.rb_processed:
viewModel.getConsultationList(2);
break;
}
}
});
}
@Override
protected int initVariableId() {
return BR.ViewModel;
}
@Override
protected int setContentViewSrc(Bundle savedInstanceState) {
return R.layout.activity_consultation_information;
}
}
|
package com.zmyaro.ltd;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class TitleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_title);
Button playButton = (Button) findViewById(R.id.play_button);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(TitleActivity.this, GameActivity.class);
startActivity(intent);
}
});
}
}
|
package com.es.phoneshop.model.product.Cart;
import com.es.phoneshop.model.product.Product;
import com.es.phoneshop.model.product.exceptions.OutOfStockException;
import com.es.phoneshop.model.product.exceptions.ProductNotFoundException;
import javax.servlet.http.HttpSession;
public interface CartService {
Cart getCart(HttpSession session);
void add(Cart cart, Product product, int quantity) throws OutOfStockException, ProductNotFoundException;
void update(Cart cart, Long productId, int quantity) throws ProductNotFoundException, OutOfStockException;
void delete(Cart cart, Long productId);
}
|
package ru.lischenko_dev.fastmessenger.adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import ru.lischenko_dev.fastmessenger.R;
import ru.lischenko_dev.fastmessenger.common.App;
import ru.lischenko_dev.fastmessenger.common.ThemeManager;
import ru.lischenko_dev.fastmessenger.vkapi.models.VKVideo;
public class MaterialsVideoAdapter extends BaseAdapter {
private ArrayList<MaterialsAdapter> items;
private Context context;
private LayoutInflater inflater;
private ThemeManager manager;
public MaterialsVideoAdapter(Context context, ArrayList<MaterialsAdapter> items) {
this.items = items;
this.context = context;
this.manager = ThemeManager.get(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i) {
return items.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
MaterialsAdapter item = (MaterialsAdapter) getItem(i);
VKVideo video = item.attachment.video;
View v = view;
if (v == null) {
v = inflater.inflate(R.layout.materials_video_list, viewGroup, false);
}
ImageView ivPreview = (ImageView) v.findViewById(R.id.photo);
TextView tvTitle = (TextView) v.findViewById(R.id.tvTitle);
TextView tvViews = (TextView) v.findViewById(R.id.tvSee);
TextView tvDate = (TextView) v.findViewById(R.id.tvDate);
tvTitle.setText(video.title);
tvViews.setText(String.valueOf(video.views));
tvTitle.setTextColor(manager.getPrimaryTextColor());
tvViews.setTextColor(manager.getSecondaryTextColor());
tvDate.setTextColor(manager.getSecondaryTextColor());
tvDate.setText(new SimpleDateFormat("dd.MM.yyyy").format(video.date * 1000));
Picasso.with(context)
.load(video.image_big)
.resize(App.screenWidth / 2, App.screenWidth / 2)
.centerCrop()
.placeholder(new ColorDrawable(Color.GRAY))
.into(ivPreview);
return v;
}
}
|
package HomeWork_2;
public class Circle {
double r; // radius of Circle
double d; // diameter of Circle
public double getLength() { // length of Circle
double l;
return l = 2 * 3.14 * r;
}
public double getArea() { // area of Circle
double a;
return a = 3.14 * (d * d / 4);
}
}
|
package com.baixiaowen.javaconcurrencyprogramming.singleton单例模式8种写法;
/**
* 描述: 饿汉式:(静态常量) [可用]
*
* 优点:比较简单,在类加载的时候就已经完成了初始化
*/
public class Singleton饿汉式静态代码块2 {
private final static Singleton饿汉式静态代码块2 INSTANCE;
static {
INSTANCE = new Singleton饿汉式静态代码块2();
}
private Singleton饿汉式静态代码块2(){}
public static Singleton饿汉式静态代码块2 getInstance(){
return INSTANCE;
}
}
|
package com.spring1.Service;
/**
* com.spring1.Service
*
* @author jh
* @date 2018/8/21 16:54
* description:
*/
public interface UserService {
void save();
void delete();
void update();
void find();
}
|
package com.olal.caclulator.model;
import org.postgresql.util.PGInterval;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
@Entity
@Table(name = "recipes")
public class Recipe implements Serializable {
private Integer id;
private String name;
private boolean isDefault;
private String description;
private Date creationDate;
private PGInterval duration;
private Set<User> belongToUsers;
private RecipeCategory category;
private Set<RecipeProduct> recipeProducts;
public Recipe() {
}
public Recipe(String name, boolean isDefault, String description, Date creationDate, PGInterval duration, RecipeCategory category) {
this.name = name;
this.isDefault = isDefault;
this.description = description;
this.creationDate = creationDate;
this.duration = duration;
this.category = category;
}
public Recipe(String name, boolean isDefault, String description, Date creationDate, PGInterval duration, Set<User> belongToUsers, RecipeCategory category) {
this.name = name;
this.isDefault = isDefault;
this.description = description;
this.creationDate = creationDate;
this.duration = duration;
this.belongToUsers = belongToUsers;
this.category = category;
}
public Recipe(String name, boolean isDefault, String description, Date creationDate, PGInterval duration, RecipeCategory category, Set<RecipeProduct> recipeProducts) {
this.name = name;
this.isDefault = isDefault;
this.description = description;
this.creationDate = creationDate;
this.duration = duration;
this.category = category;
this.recipeProducts = recipeProducts;
}
public Recipe(String name, boolean isDefault, String description, Date creationDate, PGInterval duration, Set<User> belongToUsers, RecipeCategory category, Set<RecipeProduct> recipeProducts) {
this.name = name;
this.isDefault = isDefault;
this.description = description;
this.creationDate = creationDate;
this.duration = duration;
this.belongToUsers = belongToUsers;
this.category = category;
this.recipeProducts = recipeProducts;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
@Column(nullable = false, length = 100)
public String getName() {
return name;
}
@Column(name = "is_default", nullable = false)
public boolean isDefault() {
return isDefault;
}
@Column(nullable = false, length = 1000)
public String getDescription() {
return description;
}
@Column(name = "creation_date", nullable = false)
@Temporal(TemporalType.TIMESTAMP)
public Date getCreationDate() {
return creationDate;
}
@Column(nullable = false)
public PGInterval getDuration() {
return duration;
}
@ManyToOne
@JoinColumn(name = "category_id")
public RecipeCategory getCategory() {
return category;
}
@ManyToMany(mappedBy = "users")
public Set<User> getBelongToUsers() {
return belongToUsers;
}
@OneToMany(mappedBy = "pk.recipe")
public Set<RecipeProduct> getRecipeProducts() {
return recipeProducts;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
}
public void setDescription(String description) {
this.description = description;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public void setDuration(PGInterval duration) {
this.duration = duration;
}
public void setBelongToUsers(Set<User> belongToUsers) {
this.belongToUsers = belongToUsers;
}
public void setCategory(RecipeCategory category) {
this.category = category;
}
public void setRecipeProducts(Set<RecipeProduct> recipeProducts) {
this.recipeProducts = recipeProducts;
}
}
|
package it.unica.pr2.attrezzaturaNautica;
import java.util.*;
public class Timone extends AttrezzaturaNautica{
private Integer angle;
public Timone(Integer angle){
this.angle = angle;
}
public Integer getAngle(){
return this.angle;
}
public void imposta(Integer angle){
this.angle = angle;
}
@Override
public boolean equals(Object obj){
if(this == obj) return true;
if(!(obj instanceof Timone)) return false;
Timone t = (Timone)obj;
if( this.getAngle() == t.getAngle()) return true;
return false;
}
@Override
public String toString(){
String toReturn = this.angle.toString();
if(toReturn.equals("0")) return "0 NORD";
if(toReturn.equals("90")) return "90 EST";
if(toReturn.equals("180")) return "180 SUD";
if(toReturn.equals("270")) return "270 OVEST";
return toReturn;
}
}
|
package my.battleships.Players;
public enum FiringResult {
MISS("MISS"),
HURT ("you HURT the ship!"),
DROWNED("enemy's ship was DROWNED..."),
MINE(" have struck the MINE!"),
MINE_SACRIFICE(" exploded on the enemy's mine... RIP, dear :(");
String status;
FiringResult(String status) {
this.status = status;
}
@Override
public String toString() {
return status;
}
}
|
package com.algorithms4.sort;
/**
* Created by saml on 11/1/2017.
*/
public class ShellSort extends SortTemplate {
public static void sort(Comparable[] a) {
int h = 1;
while (h < a.length / 3) {
h = 3 * h + 1;
}
while (h >= 1) {
for (int i = h; i < a.length; i++) {
for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) {
exch(a, j, j - h);
}
}
h = h / 3;
}
}
public static void main(String[] args) {
Integer[] is = new Integer[12];
is[0] = 4;
is[1] = 5;
is[2] = 7;
is[3] = 1;
is[4] = 2;
is[5] = 3;
is[6] = 5;
is[7] = 6;
is[8] = 7;
is[9] = 2;
is[10] = 4;
is[11] = 3;
Comparable[] a = is;
sort(a);
assert isSorted(a);
show(a);
System.out.println("compare complexity: " + compareCount);
System.out.println("exchange complexity: " + exchangeCount);
}
}
|
package com.company;
public class Airplane {
private int airplaneID;
private int rows;
private int columns;
private int businessClassRows;
private String airplaneDescription;
public String getAirplaneDescription() {
return airplaneDescription;
}
public void setAirplaneDescription(String airplaneDescription) {
this.airplaneDescription = airplaneDescription;
}
public int getAirplaneID() {
return airplaneID;
}
public void setAirplaneID(int airplaneID) {
this.airplaneID = airplaneID;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getColumns() {
return columns;
}
public void setColumns(int columns) {
this.columns = columns;
}
public int getBusinessClassRows() {
return businessClassRows;
}
public void setBusinessClassRows(int businessClassRows) {
this.businessClassRows = businessClassRows;
}
public Airplane(int airplaneID, int rows, int columns, int businessClassRows, String airplaneDescription) {
this.airplaneID = airplaneID;
this.rows = rows;
this.columns = columns;
this.businessClassRows = businessClassRows;
this.airplaneDescription = airplaneDescription;
}
@Override
public String toString() {
return "Airplane { Id = " + getAirplaneID()
+ ", Rows = " + getRows()
+ ", Columns = " + getColumns()
+ ", Business Class Rows = " + getBusinessClassRows()
+ ", Airplane Description = " + getAirplaneDescription() + " }";
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.restrictions.populator.data;
import static java.util.stream.Collectors.toList;
import de.hybris.platform.cms2.common.annotations.HybrisDeprecation;
import de.hybris.platform.cms2.model.restrictions.CMSUserGroupRestrictionModel;
import de.hybris.platform.cmsfacades.data.UserGroupRestrictionData;
import de.hybris.platform.cmsfacades.uniqueidentifier.UniqueItemIdentifierService;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.user.UserGroupModel;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException;
import java.util.NoSuchElementException;
import org.springframework.beans.factory.annotation.Required;
/**
* Converts an {@link UserGroupRestrictionData} dto to a {@link CMSUserGroupRestrictionModel} restriction
*
* @deprecated since 6.6
*/
@Deprecated
@HybrisDeprecation(sinceVersion = "6.6")
public class UserGroupRestrictionDataToModelPopulator implements Populator<UserGroupRestrictionData, CMSUserGroupRestrictionModel>
{
private UniqueItemIdentifierService uniqueItemIdentifierService;
@Override
public void populate(final UserGroupRestrictionData source, final CMSUserGroupRestrictionModel target)
throws ConversionException
{
try
{
target.setIncludeSubgroups(source.isIncludeSubgroups());
target.setUserGroups(source.getUserGroups().stream()
.map(itemId -> getUniqueItemIdentifierService().getItemModel(itemId, UserGroupModel.class).get()).collect(toList()));
}
catch (UnknownIdentifierException | ConversionException | NoSuchElementException e)
{
throw new ConversionException("Conversion failed", e);
}
}
protected UniqueItemIdentifierService getUniqueItemIdentifierService()
{
return uniqueItemIdentifierService;
}
@Required
public void setUniqueItemIdentifierService(final UniqueItemIdentifierService uniqueItemIdentifierService)
{
this.uniqueItemIdentifierService = uniqueItemIdentifierService;
}
}
|
package com.zpjr.cunguan.common.base;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.alibaba.fastjson.JSONObject;
import com.zpjr.cunguan.MyApplication;
import com.zpjr.cunguan.R;
import com.zpjr.cunguan.action.action.setting.ISettingFragmentAction;
import com.zpjr.cunguan.action.impl.setting.SettingFragmentAction;
import com.zpjr.cunguan.common.cache.SharedPreferenceCache;
import com.zpjr.cunguan.common.retrofit.PresenterCallBack;
import com.zpjr.cunguan.common.utils.SnackbarUtil;
import com.zpjr.cunguan.common.views.LoadingDialog;
import com.zpjr.cunguan.common.views.PrompfDialog;
import com.zpjr.cunguan.entity.module.VersionModule;
import com.zpjr.cunguan.ui.activity.login.LoginActivity;
/**
* Description: 业务逻辑-presenter基类
* Autour: LF
* Date: 2017/7/27 15:26
*/
public class BasePresenterImpl {
public LoadingDialog shapeLoadingDialog;
private ISettingFragmentAction mAction;
public BasePresenterImpl() {
}
/**
* apk检查更新
* @param context
*/
public void checkUpdate(final Context context, final View view) {
if (mAction == null) {
mAction = new SettingFragmentAction();
}
mAction.checkUpdates(new PresenterCallBack() {
@Override
public void onSuccess(Object result) {
if (result != null) {
VersionModule module = JSONObject.parseObject(result.toString(), VersionModule.class);
if (module.getVersionCode() <= getAppVersion(context)) {
showUpdateDialog(context, module.getUrl(), module.getName(), module.getVersionName());
}else{
SnackbarUtil.ShortSnackbar(view, "已是最新版本", SnackbarUtil.INFO).show();
}
} else {
SnackbarUtil.ShortSnackbar(view, "检查更新失败,请重试", SnackbarUtil.INFO).show();
}
}
@Override
public void onFail(String errMsg) {
try {
SnackbarUtil.ShortSnackbar(view, errMsg, SnackbarUtil.INFO).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* 获取版本号
*
* @return
*/
public int getAppVersion(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return info.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return 1;
}
/**********************************加载框*******************************/
/**
* 加载框
*
* @param context
*/
public void showLoadingDialog(Context context) {
if (shapeLoadingDialog == null) {
shapeLoadingDialog = new LoadingDialog.Builder(context)
.loadText(context.getResources().getString(R.string.loading_text))
.build();
shapeLoadingDialog.show();
} else {
shapeLoadingDialog.show();
}
}
/**
* 加载内容框
*
* @param context
*/
public void showLoadingDialog(Context context, String content) {
if (shapeLoadingDialog == null) {
shapeLoadingDialog = new LoadingDialog.Builder(context)
.loadText(content)
.build();
shapeLoadingDialog.show();
} else {
shapeLoadingDialog.show();
}
}
public void dismissLoadingDialog() {
if (shapeLoadingDialog != null) {
shapeLoadingDialog.dismiss();
}
}
/*******************************电话拨打弹框*******************************/
Dialog call_dialog;
Button btn_call;
public void showCallDialog(final Context context, final String phone_num) {
if (call_dialog == null) {
View view = ((BaseActivity) context).getLayoutInflater().inflate(R.layout.call_dialog, null);
call_dialog = new Dialog(context, R.style.transparentFrameWindowStyle);
call_dialog.setContentView(view, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Window window = call_dialog.getWindow();
// 设置显示动画
window.setWindowAnimations(R.style.main_menu_animstyle);
WindowManager.LayoutParams wl = window.getAttributes();
wl.x = 0;
wl.y = ((BaseActivity) context).getWindowManager().getDefaultDisplay().getHeight();
// 以下这两句是为了保证按钮可以水平满屏
wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
// 设置显示位置
call_dialog.onWindowAttributesChanged(wl);
// 设置点击外围解散
call_dialog.setCanceledOnTouchOutside(true);
call_dialog.show();
btn_call = (Button) view.findViewById(R.id.btn_call);
btn_call.setText(phone_num);
Button btn_cancle = (Button) view.findViewById(R.id.btn_cancle);
btn_call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (phone_num != null && !phone_num.equals("")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri
.parse("tel:" + phone_num));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
call_dialog.dismiss();
}
}
});
btn_cancle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
call_dialog.dismiss();
}
});
} else {
btn_call.setText(phone_num);
call_dialog.show();
}
}
/*******************************版本更新弹框*******************************/
PrompfDialog updateDialog;
public void showUpdateDialog(final Context context,
final String versionPath,
final String versionName,
final String versionCode) {
if (updateDialog == null) {
updateDialog = new PrompfDialog(context,
R.style.transparentFrameWindowStyle, "更 新", "关 闭",
"检测到最新版本,需要更新吗?", "中平金融");
updateDialog.setCanceledOnTouchOutside(false);
updateDialog.setUpdateOnClickListener(new PrompfDialog.UpdateOnclickListener() {
@Override
public void dismiss() {
}
@Override
public void BtnYesOnClickListener(View v) {
// Intent it = new Intent(context,NotificationUpdateActivity.class);
// it.putExtra("versionPath", versionPath);
// it.putExtra("versionName", versionName);
// it.putExtra("versionCode", versionCode);
// context.startActivity(it);
// phone.setDownload(true);
updateDialog.dismiss();
}
@Override
public void BtnCancleOnClickListener(View v) {
updateDialog.dismiss();
}
});
Window window = updateDialog.getWindow();
window.setGravity(Gravity.CENTER);
updateDialog.show();
} else {
updateDialog.show();
}
}
/*******************************退出登录弹框*******************************/
PrompfDialog logOutDialog;
public void showLogOutDialog(final Context context) {
if (logOutDialog == null) {
logOutDialog = new PrompfDialog(context,
R.style.transparentFrameWindowStyle, "退 出", "关 闭",
"您确定要退出登录账户吗?", "中平金融");
logOutDialog.setCanceledOnTouchOutside(false);
logOutDialog
.setUpdateOnClickListener(new PrompfDialog.UpdateOnclickListener() {
@Override
public void dismiss() {
}
@Override
public void BtnYesOnClickListener(View v) {
SharedPreferenceCache.getInstance().clearUserInfo();
MyApplication.IS_LOGIN = false;
Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
logOutDialog.dismiss();
}
@Override
public void BtnCancleOnClickListener(View v) {
logOutDialog.dismiss();
}
});
Window window = logOutDialog.getWindow();
window.setGravity(Gravity.CENTER);
logOutDialog.show();
} else {
logOutDialog.show();
}
}
}
|
package entity;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Entity
@XmlRootElement
@NamedQuery(name = "Categorie.findAll", query = "SELECT c FROM Categorie c")
public class Categorie implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String id;
private String nom;
private String description;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "categorie")
@JsonManagedReference
private List<Ingredient> ingredients;
@XmlElement(name = "_links")
@Transient //ne persiste pas dans la BD
private List<Link> links = new ArrayList<>();
public List<Link> getLinks() {
return this.links;
}
public void addLink(String rel, String uri) {
this.links.add(new Link(rel, uri));
}
public Categorie() {
}
public Categorie(String name) {
this.nom = name;
this.ingredients = new ArrayList<>();
}
public List<Ingredient> getIngredients() {
return ingredients;
}
public void setIngredients(List<Ingredient> ingredients) {
this.ingredients = ingredients;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setLinks(List<Link> links) {
this.links = links;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
|
package com.tencent.mm.ui.conversation;
import com.tencent.mm.sdk.platformtools.al.a;
class d$1 implements a {
final /* synthetic */ d uom;
d$1(d dVar) {
this.uom = dVar;
}
public final boolean vD() {
if (d.d(this.uom)) {
d.e(this.uom);
}
return false;
}
}
|
/*
* 66661 MOHAMAD HAIDIL BIN IDRIS
* 66783 MUHAMMAD AIMAN BIN MOHD AZMI
* 67872 SYAZZWA NATASYA BINTI MOHD ZAIDI
* 66477 LIM AI XIN
* 64631 AMNAH NADIAH BINTI SUFIAN
*/
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("\n==============================================================================");
System.out.println("This program will be used to convert the following string into its secret code");
System.out.println("==============================================================================\n");
System.out.print("Please enter your string here: ");
String inString = scan.nextLine();
SecretCode obj1 = new SecretCode(inString);
// do the string validation
do {
if (!obj1.checkStringValidity(inString)) {
System.out.println("You've input incorrect string. Please try to input again.\n");
System.out.print("New input: ");
inString = scan.nextLine();
obj1.setInString(inString);
}
} while (!obj1.checkStringValidity(inString));
System.out.println("inString: " + inString);
int length = obj1.getStringLen(inString);
System.out.println("Your string length is: " + length);
System.out.println("Outstring: " + obj1.ShiftChar(inString, length));
scan.close();
}
}
|
package Lambda;
public interface Interf1 {
public void add(int a,int b);
static void m2()
{
System.out.println("static method");
}
default void m1()
{
System.out.println("default method");
}
}
|
package enstabretagne.BE.AnalyseSousMarine.SimEntity.SousMarin;
import enstabretagne.BE.AnalyseSousMarine.SimEntity.MouvementSequenceur.EntityMouvementSequenceurInit;
import enstabretagne.simulation.components.data.SimInitParameters;
public class EntitySousMarinInit extends SimInitParameters {
private EntityMouvementSequenceurInit mvtSeqIni;
private String name;
public EntitySousMarinInit(String nom,EntityMouvementSequenceurInit mvtSeqIni)
{
this.mvtSeqIni = mvtSeqIni;
this.name = nom;
}
public String getName() {
return name;
}
public EntityMouvementSequenceurInit getMvtSeqInitial() {
return mvtSeqIni;
}
}
|
package com.Oovever.easyHttp.util;
import com.Oovever.easyHttp.exception.JSONException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
/**
* Json工具类
* @author OovEver
* 2018/7/1 23:32
*/
public class JsonUtil {
// 将属性转化为JSON字符串
private static final ObjectMapper mapper = new ObjectMapper();
static {
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 设置时间格式
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//反序列化时候,如果json串中的字段出现String("")或者null的就把java对应属性设置为Null
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
// 特性决定parser将是否允许解析使用Java/C++ 样式的注释(包括'/'+'*' 和'//' 变量)。 由于JSON标准说明书上面没有提到注释是否是合法的组成,所以这是一个非标准的特性;
// * 尽管如此,这个特性还是被广泛地使用。
// *
// * 注意:该属性默认是false,因此必须显式允许,即通过JsonParser.Feature.ALLOW_COMMENTS 配置为true
mapper.getFactory().enable(JsonParser.Feature.ALLOW_COMMENTS);
// 允许单引号
mapper.getFactory().enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
//只输出非空属性到Json字符串,属性为null不进行序列化
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
/**
*
* 把json输入流中的内容转换为指定类型的对象
*
* @param jsonInputStream JSON输入流
* @param type 类型
* @return 转化后的对象
* @throws JSONException JSON异常
*/
public static <T> T toBean(InputStream jsonInputStream, TypeReference<T> type) throws JSONException {
try {
return mapper.readValue(jsonInputStream, type);
} catch (Exception t) {
throw new JSONException("把json输入流中的内容转换为指定类型的对象(" + t.getMessage() + ")", t);
}
}
/**
*
* 把json输入流中的内容转换为指定类型的对象
*
* @param jsonInputStream JSON输入流
* @param clazz 类型
* @return 转化后的对象
* @throws JSONException JSON异常
*/
public static <T> T toBean(InputStream jsonInputStream, Class<T> clazz) throws JSONException {
try {
return mapper.readValue(jsonInputStream, clazz);
} catch (Exception t) {
throw new JSONException("把json输入流中的内容转换为指定类型的对象(" + t.getMessage() + ")", t);
}
}
/**
*
* 把json字节数组转换为指定类型的对象
*
* @param jsonByteArray JSON字节数组
* @param type 要转化的类型
* @return 转化后的JSON对象
* @throws JSONException JSON转化过程中出现的异常
*/
public static <T> T toBean(byte[] jsonByteArray, TypeReference<T> type) throws JSONException {
try {
return mapper.readValue(jsonByteArray, type);
} catch (Exception t) {
throw new JSONException("把json字节数组转换为指定类型的对象是出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 把json字节数组转换为指定类型的对象
*
* @param jsonByteArray JSON字节数组
* @param clazz 要转化的类型
* @return 转化后的JSON对象
* @throws JSONException 转化后出现异常
*/
public static <T> T toBean(byte[] jsonByteArray, Class<T> clazz) throws JSONException {
try {
return mapper.readValue(jsonByteArray, clazz);
} catch (Exception t) {
throw new JSONException("把json字节数组转换为指定类型的对象是出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 把json字符串转换为指定类型的对象
*
* @param jsonString JSON字符串
* @param type JSON类型 TypeReference明确指定反序列化类型
* @return 转化后的JSON对象
* @throws JSONException 转化过程中出现的异常
*/
public static <T> T toBean(String jsonString, TypeReference<T> type) throws JSONException {
try {
return mapper.readValue(jsonString, type);
} catch (Exception t) {
throw new JSONException("把json字符串转换为指定类型的对象出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 转换json字符串为指定对象
*
* @param jsonString JSON字符串
* @param clazz JSON类型
* @return 转化后的JSON对象
* @throws JSONException 转化过程中出现的异常
*/
public static <T> T toBean(String jsonString, Class<T> clazz) throws JSONException {
try {
return mapper.readValue(jsonString, clazz);
} catch (Exception t) {
throw new JSONException("把json字符串转换为指定类型的对象出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 把object转换为指定类型的对象
*
* @param obj object对象
* @param type 要转化的类型
* @return 转化后的Object对象
* @throws JSONException 转化过程中出现异常
*/
public static <T> T toBean(Object obj, TypeReference<T> type) throws JSONException {
if (obj instanceof String) {
return toBean(obj.toString(), type);
}
try {
return mapper.convertValue(obj, type);
} catch (Exception t) {
throw new JSONException("把obj转换为指定类型的对象出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 把obj转换为指定对象
*
* @param obj object对象
* @param clazz 要转化的类型
* @return 转化后的Object对象
* @throws JSONException 转化过程中出现异常
*/
public static <T> T toBean(Object obj, Class<T> clazz) throws JSONException {
if (obj instanceof String) {
return toBean(obj.toString(), clazz);
}
try {
return mapper.convertValue(obj, clazz);
} catch (Exception t) {
throw new JSONException("把obj转换为指定对象出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 从reader中读取json信息并转换为指定对象
*
* @param reader reader对象
* @param type 要转化的类型
* @return 转化后的对象
* @throws JSONException 从reader中读取json信息并转换为指定对象出错
*/
public static <T> T toBean(Reader reader, TypeReference<T> type) throws JSONException {
try {
return mapper.readValue(reader, type);
} catch (Exception t) {
throw new JSONException("从reader中读取json信息并转换为指定对象出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 从reader中读取json信息并转换为指定对象
*
* @param reader reader对象
* @param clazz 要转化的类型
* @return 转化后的对象
* @throws JSONException 从reader中读取json信息并转换为指定对象出错
*/
public static <T> T toBean(Reader reader, Class<T> clazz) throws JSONException {
try {
return mapper.readValue(reader, clazz);
} catch (Exception t) {
throw new JSONException("从reader中读取json信息并转换为指定对象出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 把object对象转换为json字符串
*
* @param obj object对象
* @return JSON字符串
* @throws JSONException 把obj转换为json字符串出错
*/
public static String toJson(Object obj) throws JSONException {
if (obj == null) {
return "{}";
}
try {
return mapper.writeValueAsString(obj);
} catch (Exception t) {
throw new JSONException("把obj转换为json字符串出错(" + t.getMessage() + ")", t);
}
}
/**
*
* 把obj转换为json字节数组
*
* @param obj object对象
* @return 将object对象转化为JSON字节数组
* @throws JSONException 把obj转换为json字符串出错
*/
public static byte[] toJsonBytes(Object obj) throws JSONException {
if (obj == null) {
return "{}".getBytes(Charset.forName("UTF-8"));
}
try {
return mapper.writeValueAsBytes(obj);
} catch (Exception t) {
throw new JSONException("把obj转换为json字符串出错(" + t.getMessage() + ")", t);
}
}
/**
* @return 返回mapper对象
*/
public static ObjectMapper getMapper() {
return mapper;
}
}
|
/*
* 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 TFD.DomainModel;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* @author Rosy
*/
@Entity
public class Categoria implements Entidade, Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long idCategoria;
private String nome;
private String quantidade;
public Long getIdCategoria() {
return idCategoria;
}
public void setIdCategoria(Long idCategoria) {
this.idCategoria = idCategoria;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getQuantidade() {
return quantidade;
}
public void setQuantidade(String quantidade) {
this.quantidade = quantidade;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Categoria other = (Categoria) obj;
if (this.idCategoria != other.idCategoria && (this.idCategoria == null || !this.idCategoria.equals(other.idCategoria))) {
return false;
}
return true;
}
@Override
public String toString() {
return idCategoria + " - " + nome;
}
@Override
public Long getId() {
return null;
}
}
|
import java.io.InputStream;
import java.util.Scanner;
public class Menu {
public Menu(InputStream is) {
this.scanner = new Scanner(is);
}
public int character() {
System.out.println("Character 1 - Press 1");
System.out.println("Character 2 - Press 2");
boolean validKey = false;
int key = 1;
while (!validKey) {
key = scanner.nextInt();
try {
// if Character1
if (key == 1) {
System.out.println("Character 1 Loaded");
//SetCharacter1
setCharacter1();
validKey = true;
readKey();
}
// if Character2
if (key == 2) {
System.out.println("Character 2 Loaded");
//SetCharacter2
setCharacter2();
validKey = true;
readKey();}
}catch(Exception e){
System.out.println("Press a valid Key");
}
}
return key;
}
}
|
package loops;
import java.util.Scanner;
public class table {
public void tab(){
int i;
Scanner nn = new Scanner(System.in);
System.out.println("Please enter n value:-");
int n = nn.nextInt();
for(i=1;i<=n;i++){
if(i%3 != 0 && i%5 != 0 && i%7 != 0){
System.out.print(i);
}
System.out.print(" ");
}
}
}
|
package controllers.travelbusiness;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import views.html.travelbusiness.confirmationPage;
import views.html.travelbusiness.agentBookingInfo;
import play.Play;
import play.data.DynamicForm;
import play.db.jpa.Transactional;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import com.fasterxml.jackson.databind.JsonNode;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.travelportal.domain.HotelBookingDates;
import com.travelportal.domain.HotelBookingDetails;
import com.travelportal.domain.NatureOfBusiness;
import com.travelportal.domain.RoomAndDateWiseRate;
import com.travelportal.domain.RoomRegiterBy;
import com.travelportal.domain.RoomRegiterByChild;
import com.travelportal.domain.admin.CurrencyExchangeRate;
import com.travelportal.domain.agent.AgentRegistration;
import com.travelportal.domain.rooms.HotelRoomTypes;
import com.travelportal.domain.rooms.RoomAllotedRateWise;
import com.travelportal.vm.AgentRegisVM;
import com.travelportal.vm.ChildselectedVM;
import com.travelportal.vm.HotelBookDetailsVM;
import com.travelportal.vm.PassengerBookingInfoVM;
import com.travelportal.vm.RateDatedetailVM;
public class AgentInfoController extends Controller {
final static String rootDir = Play.application().configuration().getString("mail.storage.path");
static {
createRootDir();
}
public static void createRootDir() {
File file = new File(rootDir);
if (!file.exists()) {
file.mkdir();
}
}
public static Result confirmationPage() {
String uuId = request().getQueryString("bId");
//String bookingId = "MN-180915-7598";
return ok(confirmationPage.render(uuId));
}
@Transactional(readOnly=true)
public static Result AgentBookingInfo(){
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
List<HotelBookDetailsVM> aDetailsVMs = new ArrayList<>();
long totalPages = 0;
int currentPage = 1;
List<HotelBookingDetails> hoteDetails = null;
totalPages = HotelBookingDetails.getAgentBookingTotal(10,Long.parseLong(session().get("agent")));
hoteDetails = HotelBookingDetails.getfindByAgent(Long.parseLong(session().get("agent")), currentPage, 10, totalPages);
fullBookingInfo(hoteDetails, aDetailsVMs);
//return ok(Json.toJson(aDetailsVMs));
Map<String, Object> map = new HashMap<String, Object>();
map.put("totalPages", totalPages);
map.put("currentPage", currentPage);
map.put("results", aDetailsVMs);
JsonNode onehotelJson = Json.toJson(map);
return ok(agentBookingInfo.render(onehotelJson));
//return ok(agentBookingInfo.render());
}
public static void fullBookingInfo(List<HotelBookingDetails> hoteDetails, List<HotelBookDetailsVM> aDetailsVMs){
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
for(HotelBookingDetails hBookingDetails:hoteDetails){
HotelBookDetailsVM hDetailsVM= new HotelBookDetailsVM();
hDetailsVM.setId(hBookingDetails.getId());
hDetailsVM.setBookingId(hBookingDetails.getBookingId());
hDetailsVM.setAdult(hBookingDetails.getAdult());
hDetailsVM.setCheckIn(format.format(hBookingDetails.getCheckIn()));
hDetailsVM.setCheckOut(format.format(hBookingDetails.getCheckOut()));
if(hBookingDetails.getCityCode() != null){
hDetailsVM.setCityCode(hBookingDetails.getCityCode().getCityCode());
hDetailsVM.setCityNm(hBookingDetails.getCityCode().getCityName());
}
hDetailsVM.setHotelNm(hBookingDetails.getHotelNm());
hDetailsVM.setHotelAddr(hBookingDetails.getHotelAddr());
hDetailsVM.setNoOfroom(hBookingDetails.getNoOfroom());
hDetailsVM.setTotalNightStay(hBookingDetails.getTotalNightStay());
hDetailsVM.setRoom_status(hBookingDetails.getRoom_status());
hDetailsVM.setLatestCancellationDate(hBookingDetails.getLatestCancellationDate());
hDetailsVM.setCancellationNightsCharge(hBookingDetails.getCancellationNightsCharge());
if(hBookingDetails.getRate() != null){
hDetailsVM.setRateId(hBookingDetails.getRate().getId());
}
List<AgentRegisVM>aList = new ArrayList<>();
if(hBookingDetails.getAgentId() != null){
AgentRegistration agent = AgentRegistration.getAgentCode(hBookingDetails.getAgentId().toString());
AgentRegisVM agRegisVM=new AgentRegisVM();
agRegisVM.setAgentCode(agent.getAgentCode());
agRegisVM.setFirstName(agent.getFirstName());
agRegisVM.setLastName(agent.getLastName());
agRegisVM.setCompanyName(agent.getCompanyName());
agRegisVM.setCurrency(agent.getCurrency().getCurrencyName());
agRegisVM.setCreditLimit(agent.getCreditLimit());
agRegisVM.setAvailableLimit(agent.getAvailableLimit());
agRegisVM.setCountry(agent.getCountry().getCountryName());
agRegisVM.setCity(agent.getCity().getCityName());
agRegisVM.setCompanyAddress(agent.getCompanyAddress());
agRegisVM.setCommission(agent.getCommission());
agRegisVM.setBusiness(agent.getBusiness().getNatureofbusiness());
agRegisVM.setDirectCode(agent.getDirectCode());
agRegisVM.setDirectTelNo(agent.getDirectTelNo());
agRegisVM.setFaxCode(agent.getFaxCode());
agRegisVM.setFaxTelNo(agent.getFaxTelNo());
agRegisVM.setFinanceEmailAddr(agent.getFinanceEmailAddr());
agRegisVM.setHear(agent.getHear().getHearAboutUs());
agRegisVM.setLoginId(agent.getLoginId());
agRegisVM.setPassword(agent.getPassword());
agRegisVM.setPaymentMethod(agent.getPaymentMethod());
agRegisVM.setPosition(agent.getPosition());
agRegisVM.setPostalCode(agent.getPostalCode());
agRegisVM.setReceiveNet(agent.getReceiveNet());
agRegisVM.setStatus(agent.getStatus());
agRegisVM.setWebSite(agent.getWebSite());
String[] currencySplit;
currencySplit = agent.getCurrency().getCurrencyName().split(" - ");
agRegisVM.setCurrencyShort(currencySplit[0]);
String[] suppCurrencySplit;
suppCurrencySplit = hBookingDetails.getCurrencyId().getCurrencyName().split(" - ");
List<CurrencyExchangeRate> cList = CurrencyExchangeRate.findCurrencyRate(agent.getCurrency().getId());
for(CurrencyExchangeRate cExchangeRate:cList){
if(cExchangeRate.getCurrencyName().equals(suppCurrencySplit[0])){
hDetailsVM.currencyExchangeRate = cExchangeRate.getCurrencyRate();
}
}
aList.add(agRegisVM);
hDetailsVM.setAgent(aList);
}
if(hBookingDetails.getCountry()!=null){
hDetailsVM.setCountryId(hBookingDetails.getCountry().getCountryCode());
hDetailsVM.setCountryNm(hBookingDetails.getCountry().getCountryName());
}
hDetailsVM.setRoomId(hBookingDetails.getRoomId());
hDetailsVM.setRoomNm(hBookingDetails.getRoomName());
if(hBookingDetails.getNationality()!=null){
hDetailsVM.setNationality(hBookingDetails.getNationality().getCountryCode());
hDetailsVM.setNationalityNm(hBookingDetails.getNationality().getNationality());
}
hDetailsVM.setPayDays_inpromotion(hBookingDetails.getPayDays_inpromotion());
hDetailsVM.setPromotionname(hBookingDetails.getPromotionname());
if(hBookingDetails.getStartRating() != null){
hDetailsVM.setStartRating(hBookingDetails.getStartRating().getId());
hDetailsVM.setStartRatingNm(hBookingDetails.getStartRating().getstarRatingTxt());
}
hDetailsVM.setSupplierCode(hBookingDetails.getSupplierCode());
hDetailsVM.setSupplierNm(hBookingDetails.getSupplierNm());
hDetailsVM.setTotal(hBookingDetails.getTotal());
hDetailsVM.setPayment(hBookingDetails.getPayment());
hDetailsVM.setTravelleraddress(hBookingDetails.getTravelleraddress());
hDetailsVM.setTravelleremail(hBookingDetails.getTravelleremail());
hDetailsVM.setCurrencyId(hBookingDetails.getCurrencyId().getCurrencyCode());
hDetailsVM.setCurrencyNm(hBookingDetails.getCurrencyId().getCurrencyName());
hDetailsVM.setTravellerfirstname(hBookingDetails.getTravellerfirstname());
hDetailsVM.setTravellerlastname(hBookingDetails.getTravellerlastname());
hDetailsVM.setTravellerphnaumber(hBookingDetails.getTravellerphnaumber());
hDetailsVM.setTravellercountry(hBookingDetails.getTravellercountry().getCountryCode());
hDetailsVM.setTypeOfStay_inpromotion(hBookingDetails.getTypeOfStay_inpromotion());
hDetailsVM.setNonRefund(hBookingDetails.getNonRefund());
hDetailsVM.setNonSmokingRoom(hBookingDetails.getNonSmokingRoom());
hDetailsVM.setTwinBeds(hBookingDetails.getTwinBeds());
hDetailsVM.setLateCheckout(hBookingDetails.getLateCheckout());
hDetailsVM.setLargeBed(hBookingDetails.getLargeBed());
hDetailsVM.setHighFloor(hBookingDetails.getHighFloor());
hDetailsVM.setEarlyCheckin(hBookingDetails.getEarlyCheckin());
hDetailsVM.setAirportTransfer(hBookingDetails.getAirportTransfer());
hDetailsVM.setAirportTransferInfo(hBookingDetails.getAirportTransferInfo());
hDetailsVM.setEnterComments(hBookingDetails.getEnterComments());
hDetailsVM.setSmokingRoom(hBookingDetails.getSmokingRoom());
hDetailsVM.setHandicappedRoom(hBookingDetails.getHandicappedRoom());
hDetailsVM.setWheelchair(hBookingDetails.getWheelchair());
List<PassengerBookingInfoVM> pList = new ArrayList<>();
List<RoomRegiterBy> roBy = RoomRegiterBy.getRoomInfoByBookingId(hBookingDetails.getId());
if(roBy != null){
for(RoomRegiterBy rBy:roBy){
PassengerBookingInfoVM paInfoVM = new PassengerBookingInfoVM();
paInfoVM.adult = rBy.getAdult();
paInfoVM.noOfchild =String.valueOf(rBy.getNoOfchild());
paInfoVM.regiterBy = rBy.getRegiterBy();
paInfoVM.total = rBy.getTotal();
List<RateDatedetailVM> rlist = new ArrayList<>();
List<RoomAndDateWiseRate> dateWiseRates = RoomAndDateWiseRate.getRoomRateInfoByRoomId(rBy.getId());
if(dateWiseRates != null){
for(RoomAndDateWiseRate roomDate:dateWiseRates){
RateDatedetailVM rDVM = new RateDatedetailVM();
rDVM.date = roomDate.getDate();
rDVM.day = roomDate.getDay();
rDVM.fulldate = roomDate.getFulldate();
rDVM.month = roomDate.getMonth();
rDVM.rate = String.valueOf(roomDate.getRate());
rlist.add(rDVM);
}
paInfoVM.rateDatedetail = rlist;
}
List<ChildselectedVM> chList = new ArrayList<>();
List<RoomRegiterByChild> rByChild = RoomRegiterByChild.getRoomChildInfoByRoomId(rBy.getId());
if(rByChild != null){
for(RoomRegiterByChild rChild:rByChild){
ChildselectedVM cVm = new ChildselectedVM();
cVm.age = String.valueOf(rChild.getAge());
cVm.breakfast = rChild.getBreakfast();
cVm.childRate = String.valueOf(rChild.getChild_rate());
cVm.freeChild = rChild.getFree_child();
chList.add(cVm);
}
paInfoVM.childselected = chList;
}
pList.add(paInfoVM);
}
hDetailsVM.setPassengerInfo(pList);
}
aDetailsVMs.add(hDetailsVM);
}
}
@Transactional(readOnly=true)
public static Result getagentInfo(int currentPage,String fromDate,String toDate,String status) {
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
List<HotelBookDetailsVM> aDetailsVMs = new ArrayList<>();
long totalPages = 0;
//String status = "Confirm";
List<HotelBookingDetails> hoteDetails = null;
if(status.equals("upComingBooking")){
Date date = new Date();
totalPages = HotelBookingDetails.getTotalUpComingDateWise(10 , Long.parseLong(session().get("agent")),date);
hoteDetails = HotelBookingDetails.getfindByupComingDateWise(Long.parseLong(session().get("agent")), currentPage, 10, totalPages,date);
}else if(fromDate.equals("1") && toDate.equals("1") && status.equals("1")){
totalPages = HotelBookingDetails.getAllagentBookingTotal(10, Long.parseLong(session().get("agent")));
hoteDetails = HotelBookingDetails.getfindByagent(Long.parseLong(session().get("agent")), currentPage, 10, totalPages);
}else if(!fromDate.equals("1") && !toDate.equals("1")){
try {
totalPages = HotelBookingDetails.getAllagentTotalDateWise(10 , Long.parseLong(session().get("agent")) , format.parse(fromDate) , format.parse(toDate) , status);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
hoteDetails = HotelBookingDetails.getfindByagentDateWise(Long.parseLong(session().get("agent")), format.parse(fromDate) , format.parse(toDate), currentPage, 10, totalPages , status);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(fromDate.equals("1") && toDate.equals("1") && !status.equals("1")){
totalPages = HotelBookingDetails.getTotalDateWiseAgentWise(10 , Long.parseLong(session().get("agent")), status);
hoteDetails = HotelBookingDetails.getfindByDateWiseAgentWise(Long.parseLong(session().get("agent")), currentPage, 10, totalPages , status);
}
fullBookingInfo(hoteDetails, aDetailsVMs);
Map<String, Object> map = new HashMap<String, Object>();
map.put("totalPages", totalPages);
map.put("currentPage", currentPage);
map.put("results", aDetailsVMs);
return ok(Json.toJson(map));
}
/*----------------------------------------------------------------------------------------------------------------------------------------*/
@Transactional(readOnly=true)
public static Result getagentInfobynm(int currentPage,String checkIn,String checkOut,String guest,String status,String bookingId) {
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
//HotelBookDetailsVM hDetailsVM= new HotelBookDetailsVM();
List<HotelBookDetailsVM> aDetailsVMs = new ArrayList<>();
long totalPages = 0;
List<HotelBookingDetails> hoteDetails = null;
if(status.equals("upComingBooking")){
Date date = new Date();
totalPages = HotelBookingDetails.getTotalUpComingDateWise(10 , Long.parseLong(session().get("agent")),date);
hoteDetails = HotelBookingDetails.getfindByupComingDateWise(Long.parseLong(session().get("agent")), currentPage, 10, totalPages,date);
}else if(!checkIn.equals("undefined") && !checkOut.equals("undefined")&&!guest.equals("undefined") && bookingId.equals("0")){
try {
totalPages = HotelBookingDetails.getAllagentTotalDateWise1(10 , Long.parseLong(session().get("agent")) , format.parse(checkIn) , format.parse(checkOut) , status,guest);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
hoteDetails = HotelBookingDetails.getfindByagentDateWise1(Long.parseLong(session().get("agent")), format.parse(checkIn) , format.parse(checkOut), currentPage, 10, totalPages , status,guest);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(checkIn.equals("undefined") && checkOut.equals("undefined") && !guest.equals("undefined") && bookingId.equals("0")){
totalPages = HotelBookingDetails.getTotalDateWiseAgentWise1(10 , Long.parseLong(session().get("agent")), status,guest);
hoteDetails = HotelBookingDetails.getfindByDateWiseAgentWise1(Long.parseLong(session().get("agent")), currentPage, 10, totalPages , status,guest);
}
else if(guest.equals("undefined")&& (!checkIn.equals("undefined") || !checkOut.equals("undefined")) && bookingId.equals("0"))
{
Date checkInDate = null;
if(!checkIn.equals("undefined")){
try {
checkInDate = format.parse(checkIn);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Date CheckOutDate = null;
if(!checkOut.equals("undefined")){
try {
CheckOutDate = format.parse(checkOut);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
totalPages = HotelBookingDetails.getTotalDateWiseAgentWise11(10 , Long.parseLong(session().get("agent")), status,checkInDate,CheckOutDate);
hoteDetails = HotelBookingDetails.getfindByDateWiseAgentWise11(Long.parseLong(session().get("agent")), currentPage, 10, totalPages , status,checkInDate , CheckOutDate);
}else if(!bookingId.equals("0")){
HotelBookingDetails hDetails = HotelBookingDetails.findBookingIdDetail(bookingId);
totalPages = HotelBookingDetails.getTotalBookingIdWise(10 , Long.parseLong(session().get("agent")), status, hDetails.getId());
hoteDetails = HotelBookingDetails.getfindByBookingId(Long.parseLong(session().get("agent")), currentPage, 10, totalPages , status, hDetails.getId());
}
fullBookingInfo(hoteDetails, aDetailsVMs);
Map<String, Object> map = new HashMap<String, Object>();
map.put("totalPages", totalPages);
map.put("currentPage", currentPage);
map.put("results", aDetailsVMs);
return ok(Json.toJson(map));
}
@Transactional
public static Result getbookingcancel(long id){
int count= 0;
HotelBookingDetails hBookingDetails = HotelBookingDetails.findBookingById(id);
hBookingDetails.setRoom_status("Cancelled");
hBookingDetails.merge();
Double Credit = 0d;
AgentRegistration aRegistration = AgentRegistration.findByIdOnCode(session().get("agent"));
cancelMail(aRegistration.getEmailAddr(),hBookingDetails);
if(aRegistration.getPaymentMethod().equals("Credit") && aRegistration.getPaymentMethod().equals("Pre-Payment")){
Credit = aRegistration.getAvailableLimit() + hBookingDetails.getTotal();
aRegistration.setAvailableLimit(Credit);
aRegistration.merge();
}
List<HotelBookingDates> hotelBookingDates = HotelBookingDates.getDateBybookingId(id);
//RoomAllotedRateWise rateWise = RoomAllotedRateWise.findByRateId(hBookingDetails.getRate().getId());
for(HotelBookingDates hDates:hotelBookingDates){
if(hBookingDetails.getRate() != null){
RoomAllotedRateWise rateWise = RoomAllotedRateWise.findByRateIdandDate(hBookingDetails.getRate().getId(), hDates.getBookingDate());
if(rateWise != null){
count = rateWise.getRoomCount() - hBookingDetails.getNoOfroom();
rateWise.setRoomCount(count);
rateWise.merge();
}
}
}
return ok();
}
@Transactional(readOnly=false)
public static Result getVoucherOnRequest(long bookingId){
return ok();
}
@Transactional(readOnly=false)
public static Result getVoucherCancel(long bookingId){
return ok();
}
@Transactional(readOnly=false)
public static Result getVoucherConfirm(long bookingId){
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
final String rootDir = Play.application().configuration().getString("mail.storage.path");
File f = new File(rootDir);
if(!f.exists()){
f.mkdir();
}
HotelBookingDetails hBookingDetails = HotelBookingDetails.findBookingById(bookingId);
Document document = new Document();
try {
String fileName = "C://hotelVoucher"+".pdf"; // rootDir+"/hotelVoucher"+".pdf"
PdfWriter.getInstance(document, new FileOutputStream(fileName));
Font font1 = new Font(FontFamily.HELVETICA, 8, Font.NORMAL,
BaseColor.BLACK);
Font font2 = new Font(FontFamily.HELVETICA, 8, Font.BOLD,
BaseColor.BLACK);
Font voucherFont = new Font(FontFamily.HELVETICA, 10, Font.NORMAL,
BaseColor.BLACK);
Font voucherFont1 = new Font(FontFamily.HELVETICA, 10, Font.NORMAL,
BaseColor.RED);
Font voucherPageMsgFont = new Font(FontFamily.HELVETICA, 8, Font.NORMAL,
BaseColor.BLUE);
/*-----------------Table--------------------*/
PdfPTable BookingAddImg = new PdfPTable(1);
BookingAddImg.setWidthPercentage(100);
float[] bookingAddImgWidth = {2f};
BookingAddImg.setWidths(bookingAddImgWidth);
final String RESOURCE = rootDir+"/" +"Tag EXP.jpg";
Image logoimg = Image.getInstance(RESOURCE);
logoimg.scaleAbsolute(500f, 70f);
PdfPCell hotelImg = new PdfPCell(logoimg);
hotelImg.setBorder(Rectangle.NO_BORDER);
hotelImg.setPaddingBottom(5);
BookingAddImg.addCell(hotelImg);
/*PdfPTable BookingAddImg = new PdfPTable(2);
BookingAddImg.setWidthPercentage(100);
float[] bookingAddImgWidth = {1.5f,2.5f};
BookingAddImg.setWidths(bookingAddImgWidth);
final String RESOURCE = rootDir+"/" +"logo.png";
Image logoimg = Image.getInstance(RESOURCE);
logoimg.scaleAbsolute(130f, 25f);
PdfPCell hotelImg = new PdfPCell(logoimg);
hotelImg.setBorder(Rectangle.NO_BORDER);
hotelImg.setPaddingTop(7);
BookingAddImg.addCell(hotelImg);
final String RESOURCE1 = rootDir+"/"+"hotelVoucher.png";
Image voucherimg = Image.getInstance(RESOURCE1);
voucherimg.scaleAbsolute(340f, 60f);
PdfPCell hotelVoucherImg = new PdfPCell(voucherimg);
hotelVoucherImg.setBorder(Rectangle.NO_BORDER);
hotelVoucherImg.setPaddingBottom(6);
BookingAddImg.addCell(hotelVoucherImg);*/
/*-----------------Table--------------------*/
PdfPTable hotelVoucherTitle = new PdfPTable(2);
hotelVoucherTitle.setWidthPercentage(100);
float[] hotelVoucherTitleWidth = {2f,2f};
hotelVoucherTitle.setWidths(hotelVoucherTitleWidth);
PdfPCell voucherTitle = new PdfPCell(new Paragraph("HOTEL",voucherFont));
voucherTitle.setBackgroundColor(new BaseColor(224, 224, 224));
voucherTitle.setHorizontalAlignment(Element.ALIGN_RIGHT);
voucherTitle.setBorder(Rectangle.NO_BORDER);
voucherTitle.setPaddingBottom(4);
hotelVoucherTitle.addCell(voucherTitle);
PdfPCell voucherTitle1 = new PdfPCell(new Paragraph("VOUCHER",voucherFont1));
voucherTitle1.setBackgroundColor(new BaseColor(224, 224, 224));
voucherTitle1.setHorizontalAlignment(Element.ALIGN_LEFT);
voucherTitle1.setBorder(Rectangle.NO_BORDER);
voucherTitle1.setPaddingBottom(4);
hotelVoucherTitle.addCell(voucherTitle1);
PdfPTable hotelVoucherTitlemain = new PdfPTable(1);
hotelVoucherTitlemain.setWidthPercentage(100);
float[] hotelVoucherTitlemainWidth = {2f};
hotelVoucherTitlemain.setWidths(hotelVoucherTitlemainWidth);
PdfPCell voucherTitlemain = new PdfPCell(hotelVoucherTitle);
voucherTitlemain.setBorder(Rectangle.NO_BORDER);
hotelVoucherTitlemain.addCell(voucherTitlemain);
/*-----------------Table--------------------*/
PdfPTable hotelVoucherMsg = new PdfPTable(1);
hotelVoucherMsg.setWidthPercentage(100);
float[] hotelVoucherMsgWidth = {2f};
hotelVoucherMsg.setWidths(hotelVoucherMsgWidth);
PdfPCell hotelVoucherPageMsg = new PdfPCell(new Paragraph("Please present either an electronic or paper copy of your hotel voucher upon check-in",voucherPageMsgFont));
hotelVoucherPageMsg.setBackgroundColor(new BaseColor(255, 255, 255));
hotelVoucherPageMsg.setHorizontalAlignment(Element.ALIGN_CENTER);
hotelVoucherPageMsg.setBorder(Rectangle.NO_BORDER);
hotelVoucherPageMsg.setPaddingTop(10);
hotelVoucherMsg.addCell(hotelVoucherPageMsg);
/*-----------------Table--------------------*/
PdfPTable todayDateTable = new PdfPTable(4);
todayDateTable.setWidthPercentage(100);
float[] todayDateWidth = {2f,2f,2f,2f};
todayDateTable.setWidths(todayDateWidth);
PdfPCell blank = new PdfPCell();
blank.setBorderColor(BaseColor.WHITE);
todayDateTable.addCell(blank);
PdfPCell blank1 = new PdfPCell();
blank1.setBorderColor(BaseColor.WHITE);
todayDateTable.addCell(blank1);
PdfPCell voucherdateLabel = new PdfPCell(new Paragraph("Voucher Issue Date :",font1));
voucherdateLabel.setBorder(Rectangle.NO_BORDER);
todayDateTable.addCell(voucherdateLabel);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String date = sdf.format(new Date());
Paragraph date1 = new Paragraph(date,font2);
PdfPCell datevalue = new PdfPCell(new Paragraph(date1));
datevalue.setBackgroundColor(new BaseColor(224, 224, 224));
datevalue.setHorizontalAlignment(Element.ALIGN_CENTER);
datevalue.setBorderColor(BaseColor.WHITE);
todayDateTable.addCell(datevalue);
/*PdfPTable voucherDateTable = new PdfPTable(2);
voucherDateTable.setWidthPercentage(100);
float[] voucherDateWidth = {2f,2f};
voucherDateTable.setWidths(voucherDateWidth);*/
/*-----------------Table--------------------*/
PdfPTable FacilityNumbarOfRoomTable = new PdfPTable(2);
FacilityNumbarOfRoomTable.setWidthPercentage(100);
float[] FacilityNumbarOfRoomTableWidth = {2f,2f};
FacilityNumbarOfRoomTable.setWidths(FacilityNumbarOfRoomTableWidth);
PdfPCell FacilityNumbarOfRoom = new PdfPCell(new Paragraph("Number of Rooms :",font1));
FacilityNumbarOfRoom.setBorder(Rectangle.NO_BORDER);
FacilityNumbarOfRoom.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityNumbarOfRoomTable.addCell(FacilityNumbarOfRoom);
PdfPCell FacilityNumbarOfRoom1 = new PdfPCell(new Paragraph(String.valueOf(hBookingDetails.getNoOfroom()),font2));
FacilityNumbarOfRoom1.setBorderColor(BaseColor.WHITE);
FacilityNumbarOfRoom1.setBorderWidth(1f);
FacilityNumbarOfRoom1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityNumbarOfRoom1.setHorizontalAlignment(Element.ALIGN_CENTER);
FacilityNumbarOfRoomTable.addCell(FacilityNumbarOfRoom1);
/*-----------------Table--------------------*/
PdfPTable FacilityNumberofExtraBedsTable = new PdfPTable(2);
FacilityNumberofExtraBedsTable.setWidthPercentage(100);
float[] FacilityNumberofExtraBedsTableWidth = {2f,2f};
FacilityNumberofExtraBedsTable.setWidths(FacilityNumberofExtraBedsTableWidth);
PdfPCell FacilityNumberofExtraBeds = new PdfPCell(new Paragraph("Number of Extra Beds :",font1));
FacilityNumberofExtraBeds.setBorder(Rectangle.NO_BORDER);
FacilityNumberofExtraBeds.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityNumberofExtraBedsTable.addCell(FacilityNumberofExtraBeds);
PdfPCell FacilityNumberofExtraBeds1 = new PdfPCell(new Paragraph("8",font2));
FacilityNumberofExtraBeds1.setBorderColor(BaseColor.WHITE);
FacilityNumberofExtraBeds1.setBorderWidth(1f);
FacilityNumberofExtraBeds1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityNumberofExtraBeds1.setHorizontalAlignment(Element.ALIGN_CENTER);
FacilityNumberofExtraBedsTable.addCell(FacilityNumberofExtraBeds1);
/*-----------------Table--------------------*/
PdfPTable FacilityBreakfastTable = new PdfPTable(2);
FacilityBreakfastTable.setWidthPercentage(100);
float[] FacilityBreakfastTableWidth = {2f,2f};
FacilityBreakfastTable.setWidths(FacilityBreakfastTableWidth);
PdfPCell FacilityBreakfast = new PdfPCell(new Paragraph("Breakfast :",font1));
FacilityBreakfast.setBorder(Rectangle.NO_BORDER);
FacilityBreakfast.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityBreakfastTable.addCell(FacilityBreakfast);
PdfPCell FacilityBreakfast1 = new PdfPCell(new Paragraph(hBookingDetails.getHotelNm(),font2));
FacilityBreakfast1.setBorderColor(BaseColor.WHITE);
FacilityBreakfast1.setBorderWidth(1f);
FacilityBreakfast1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityBreakfast1.setHorizontalAlignment(Element.ALIGN_CENTER);
FacilityBreakfastTable.addCell(FacilityBreakfast1);
/*-----------------Table--------------------*/
PdfPTable FacilityRoomTypeTable = new PdfPTable(2);
FacilityRoomTypeTable.setWidthPercentage(100);
float[] FFacilityRoomTypeTableWidth = {2f,2f};
FacilityRoomTypeTable.setWidths(FFacilityRoomTypeTableWidth);
PdfPCell FacilityRoomType = new PdfPCell(new Paragraph("Room Category :",font1));
FacilityRoomType.setBorder(Rectangle.NO_BORDER);
FacilityRoomType.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityRoomTypeTable.addCell(FacilityRoomType);
PdfPCell FacilityRoomType1 = new PdfPCell(new Paragraph(hBookingDetails.getRoomName(),font2));
FacilityRoomType1.setBorderColor(BaseColor.WHITE);
FacilityRoomType1.setBorderWidth(1f);
FacilityRoomType1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityRoomType1.setHorizontalAlignment(Element.ALIGN_CENTER);
FacilityRoomTypeTable.addCell(FacilityRoomType1);
/*-----------------Table--------------------*/
PdfPTable bookigConfimNoTable = new PdfPTable(2);
bookigConfimNoTable.setWidthPercentage(100);
float[] bookigConfimNoTableWidth = {2f,2f};
bookigConfimNoTable.setWidths(bookigConfimNoTableWidth);
PdfPCell bookigConfimNo = new PdfPCell(new Paragraph("Confirmation No / By :",font1));
bookigConfimNo.setBorder(Rectangle.NO_BORDER);
bookigConfimNo.setBackgroundColor(new BaseColor(224, 224, 224));
bookigConfimNoTable.addCell(bookigConfimNo);
PdfPCell bookigConfimNo1 = new PdfPCell(new Paragraph("1234",font2));
bookigConfimNo1.setBorderColor(BaseColor.WHITE);
bookigConfimNo1.setBorderWidth(1f);
bookigConfimNo1.setBackgroundColor(new BaseColor(224, 224, 224));
bookigConfimNo1.setHorizontalAlignment(Element.ALIGN_CENTER);
bookigConfimNoTable.addCell(bookigConfimNo1);
/*-----------------Table--------------------*/
PdfPTable bookingFacilityInfoTable = new PdfPTable(1);
bookingFacilityInfoTable.setWidthPercentage(100);
float[] bookingFacilityInfoWidth = {2f};
bookingFacilityInfoTable.setWidths(bookingFacilityInfoWidth);
PdfPCell FacilityNumbarOfRoomTable1 = new PdfPCell(FacilityNumbarOfRoomTable);
FacilityNumbarOfRoomTable1.setBorder(Rectangle.NO_BORDER);
FacilityNumbarOfRoomTable1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityNumbarOfRoomTable1.setPaddingBottom(4);
bookingFacilityInfoTable.addCell(FacilityNumbarOfRoomTable1);
PdfPCell FacilityNumberofExtraBedsTable1 = new PdfPCell(FacilityNumberofExtraBedsTable);
FacilityNumberofExtraBedsTable1.setBorder(Rectangle.NO_BORDER);
FacilityNumberofExtraBedsTable1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityNumberofExtraBedsTable1.setPaddingBottom(4);
bookingFacilityInfoTable.addCell(FacilityNumberofExtraBedsTable1);
PdfPCell FacilityBreakfastTable1 = new PdfPCell(FacilityBreakfastTable);
FacilityBreakfastTable1.setBorder(Rectangle.NO_BORDER);
FacilityBreakfastTable1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityBreakfastTable1.setPaddingBottom(4);
bookingFacilityInfoTable.addCell(FacilityBreakfastTable1);
PdfPCell FacilityRoomTypeTable1 = new PdfPCell(FacilityRoomTypeTable);
FacilityRoomTypeTable1.setBorder(Rectangle.NO_BORDER);
FacilityRoomTypeTable1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityRoomTypeTable1.setPaddingBottom(4);
bookingFacilityInfoTable.addCell(FacilityRoomTypeTable1);
PdfPCell FacilityMaxOccupancyTable1 = new PdfPCell(bookigConfimNoTable);
FacilityMaxOccupancyTable1.setBorder(Rectangle.NO_BORDER);
FacilityMaxOccupancyTable1.setBackgroundColor(new BaseColor(224, 224, 224));
FacilityMaxOccupancyTable1.setPaddingBottom(4);
bookingFacilityInfoTable.addCell(FacilityMaxOccupancyTable1);
/*-----------------Table--------------------*/
PdfPTable bookingInfoRefNoTable = new PdfPTable(2);
bookingInfoRefNoTable.setWidthPercentage(100);
float[] bookingInfoRefNoWidth = {2f,2f};
bookingInfoRefNoTable.setWidths(bookingInfoRefNoWidth);
PdfPCell bookingInfoRefNo = new PdfPCell(new Paragraph("Booking Reference No :",font1));
bookingInfoRefNo.setBorder(Rectangle.NO_BORDER);
bookingInfoRefNo.setBackgroundColor(new BaseColor(255, 255, 255));
bookingInfoRefNoTable.addCell(bookingInfoRefNo);
PdfPCell bookingInfoRefNo1 = new PdfPCell(new Paragraph(hBookingDetails.getId().toString(),font2));
bookingInfoRefNo1.setBorderColor(BaseColor.WHITE);
bookingInfoRefNo1.setBackgroundColor(new BaseColor(224, 224, 224));
bookingInfoRefNoTable.addCell(bookingInfoRefNo1);
/*-----------------Table--------------------*/
PdfPTable bookingInfoHotelNameTable = new PdfPTable(2);
bookingInfoHotelNameTable.setWidthPercentage(100);
float[] bookingInfoHotelNameWidth = {2f,2f};
bookingInfoHotelNameTable.setWidths(bookingInfoHotelNameWidth);
PdfPCell bookingInfoHotelName = new PdfPCell(new Paragraph("Hotel :",font1));
bookingInfoHotelName.setBorder(Rectangle.NO_BORDER);
bookingInfoHotelName.setBackgroundColor(new BaseColor(255, 255, 255));
bookingInfoHotelNameTable.addCell(bookingInfoHotelName);
PdfPCell bookingInfoHotelName1 = new PdfPCell(new Paragraph(hBookingDetails.getHotelNm().toString(),font2));
bookingInfoHotelName1.setBorderColor(BaseColor.WHITE);
bookingInfoHotelName1.setBackgroundColor(new BaseColor(224, 224, 224));
bookingInfoHotelNameTable.addCell(bookingInfoHotelName1);
/*-----------------Table--------------------*/
PdfPTable hotelAddressTable = new PdfPTable(2);
hotelAddressTable.setWidthPercentage(100);
float[] hotelAddressTableWidth = {2f,2f};
hotelAddressTable.setWidths(hotelAddressTableWidth);
PdfPCell hotelAddress = new PdfPCell(new Paragraph("Hotel Address :",font1));
hotelAddress.setBorder(Rectangle.NO_BORDER);
hotelAddress.setBackgroundColor(new BaseColor(255, 255, 255));
hotelAddressTable.addCell(hotelAddress);
PdfPCell hotelAddress1= new PdfPCell(new Paragraph(hBookingDetails.getHotelAddr(),font2));
hotelAddress1.setBorderColor(BaseColor.WHITE);
hotelAddress1.setBackgroundColor(new BaseColor(224, 224, 224));
hotelAddressTable.addCell(hotelAddress1);
/*-----------------Table--------------------*/
PdfPTable hotelContactNoTable = new PdfPTable(2);
hotelContactNoTable.setWidthPercentage(100);
float[] hotelContactNoTableWidth = {2f,2f};
hotelContactNoTable.setWidths(hotelContactNoTableWidth);
PdfPCell hotelContactNo = new PdfPCell(new Paragraph("Hotel Contact Numbar :",font1));
hotelContactNo.setBorder(Rectangle.NO_BORDER);
hotelContactNo.setBackgroundColor(new BaseColor(255, 255, 255));
hotelContactNoTable.addCell(hotelContactNo);
PdfPCell hotelContactNo1= new PdfPCell(new Paragraph("",font2));
hotelContactNo1.setBorderColor(BaseColor.WHITE);
hotelContactNo1.setBackgroundColor(new BaseColor(224, 224, 224));
hotelContactNoTable.addCell(hotelContactNo1);
/*-----------------Table--------------------*/
PdfPTable bookingInfoTable = new PdfPTable(1);
bookingInfoTable.setWidthPercentage(100);
float[] bookingInfoWidth = {2f};
bookingInfoTable.setWidths(bookingInfoWidth);
PdfPCell bookingInfoRefNoTable1 = new PdfPCell(bookingInfoRefNoTable);
bookingInfoRefNoTable1.setBorderColor(BaseColor.WHITE);
bookingInfoRefNoTable1.setBackgroundColor(new BaseColor(255, 255, 255));
bookingInfoRefNoTable1.setPaddingBottom(4);
bookingInfoTable.addCell(bookingInfoRefNoTable1);
PdfPCell bookingInfoHotelNameTable1 = new PdfPCell(bookingInfoHotelNameTable);
bookingInfoHotelNameTable1.setBorder(Rectangle.NO_BORDER);
bookingInfoHotelNameTable1.setBackgroundColor(new BaseColor(255, 255, 255));
bookingInfoHotelNameTable1.setPaddingBottom(4);
bookingInfoTable.addCell(bookingInfoHotelNameTable1);
PdfPCell hotelAddressTable1 = new PdfPCell(hotelAddressTable);
hotelAddressTable1.setBorder(Rectangle.NO_BORDER);
hotelAddressTable1.setBackgroundColor(new BaseColor(255, 255, 255));
hotelAddressTable1.setPaddingBottom(4);
bookingInfoTable.addCell(hotelAddressTable1);
PdfPCell hotelContactNoTable1 = new PdfPCell(hotelContactNoTable);
hotelContactNoTable1.setBorder(Rectangle.NO_BORDER);
hotelContactNoTable1.setBackgroundColor(new BaseColor(255, 255, 255));
hotelContactNoTable1.setPaddingBottom(4);
bookingInfoTable.addCell(hotelContactNoTable1);
/*-----------------Table--------------------*/
PdfPTable bookingFacilityInfoTable2 = new PdfPTable(2);
bookingFacilityInfoTable2.setWidthPercentage(100);
float[] bookingFacilityInfoWidth2 = {2f,2f};
bookingFacilityInfoTable2.setSpacingBefore(5f);
bookingFacilityInfoTable2.setSpacingAfter(10f);
bookingFacilityInfoTable2.setWidths(bookingFacilityInfoWidth2);
PdfPCell otherTable1 = new PdfPCell(bookingInfoTable);
otherTable1.setBackgroundColor(new BaseColor(255, 255, 255));
otherTable1.setPadding(10);
otherTable1.setBorder(Rectangle.NO_BORDER);
bookingFacilityInfoTable2.addCell(otherTable1);
PdfPCell otherTable = new PdfPCell(bookingFacilityInfoTable);
otherTable.setBackgroundColor(new BaseColor(224, 224, 224));
otherTable.setPadding(10);
otherTable.setBorder(Rectangle.NO_BORDER);
bookingFacilityInfoTable2.addCell(otherTable);
/*------ Table ---------*/
PdfPTable bookingCancellation = new PdfPTable(1);
bookingCancellation.setWidthPercentage(100);
float[] bookingCancellationWidth = {2f};
bookingCancellation.setSpacingBefore(5f);
bookingCancellation.setSpacingAfter(10f);
bookingCancellation.setWidths(bookingCancellationWidth);
PdfPCell cancellationMsg = new PdfPCell(new Paragraph("Any Cancellation received within 2 days prior to arrival date will incur the first night charge. Failure to arrival at your hotel will be treated as No-Show and will incur the first night charge(Hotel policy). ",font1));
cancellationMsg.setBorderColor(BaseColor.WHITE);
otherTable1.setPaddingBottom(8f);
cancellationMsg.setBackgroundColor(new BaseColor(255, 255, 255));
bookingCancellation.addCell(cancellationMsg);
/*------ Table ---------*/
PdfPTable bookingPassengerName = new PdfPTable(2);
bookingPassengerName.setWidthPercentage(100);
float[] passengerNameWidth = {0.8f,2.5f};
bookingPassengerName.setWidths(passengerNameWidth);
PdfPCell passengerNameLabel = new PdfPCell(new Paragraph("Passenger Name :",font2));
passengerNameLabel.setBorderColor(BaseColor.WHITE);
passengerNameLabel.setBorderWidth(1f);
passengerNameLabel.setBackgroundColor(new BaseColor(255, 255, 255));
bookingPassengerName.addCell(passengerNameLabel);
PdfPCell passengerName = new PdfPCell(new Paragraph(hBookingDetails.getTravellerfirstname(),font2));
passengerName.setBorderColor(BaseColor.WHITE);
passengerName.setBorderWidth(1f);
passengerName.setBackgroundColor(new BaseColor(224, 224, 224));
bookingPassengerName.addCell(passengerName);
/*------ Table ---------*/
PdfPTable bookingArrivalDeparture = new PdfPTable(6);
bookingArrivalDeparture.setWidthPercentage(100);
float[] bookinghotelDetailsWidth = {2.2f,1.8f,2.4f,1.6f,2.7f,1.3f};
bookingArrivalDeparture.setWidths(bookinghotelDetailsWidth);
PdfPCell bookingArrival = new PdfPCell(new Paragraph("Arrival Date:",font2));
bookingArrival.setBorderColor(BaseColor.WHITE);
bookingArrival.setBorderWidth(1f);
bookingArrival.setBackgroundColor(new BaseColor(255, 255, 255));
bookingArrivalDeparture.addCell(bookingArrival);
PdfPCell bookingArrival1 = new PdfPCell(new Paragraph(format.format(hBookingDetails.getCheckIn()).toString(),font2));
bookingArrival1.setBorderColor(BaseColor.WHITE);
bookingArrival1.setBorderWidth(1f);
bookingArrival1.setBackgroundColor(new BaseColor(224, 224, 224));
bookingArrivalDeparture.addCell(bookingArrival1);
PdfPCell bookingDeparture = new PdfPCell(new Paragraph("Departure Date:",font2));
bookingDeparture.setBorderColor(BaseColor.WHITE);
bookingDeparture.setBorderWidth(1f);
bookingDeparture.setBackgroundColor(new BaseColor(255, 255, 255));
bookingArrivalDeparture.addCell(bookingDeparture);
PdfPCell bookingDeparture1 = new PdfPCell(new Paragraph(format.format(hBookingDetails.getCheckOut()).toString(),font2));
bookingDeparture1.setBorderColor(BaseColor.WHITE);
bookingDeparture1.setBorderWidth(1f);
bookingDeparture1.setBackgroundColor(new BaseColor(224, 224, 224));
bookingArrivalDeparture.addCell(bookingDeparture1);
PdfPCell bookingNumberOfNight = new PdfPCell(new Paragraph("Number Of Night(s) :",font2));
bookingNumberOfNight.setBorderColor(BaseColor.WHITE);
bookingNumberOfNight.setBorderWidth(1f);
bookingNumberOfNight.setBackgroundColor(new BaseColor(255, 255, 255));
bookingArrivalDeparture.addCell(bookingNumberOfNight);
PdfPCell bookingNumberOfNight1 = new PdfPCell(new Paragraph(String.valueOf(hBookingDetails.getTotalNightStay()),font2));
bookingNumberOfNight1.setBorderColor(BaseColor.WHITE);
bookingNumberOfNight1.setBorderWidth(1f);
bookingNumberOfNight1.setBackgroundColor(new BaseColor(224, 224, 224));
bookingArrivalDeparture.addCell(bookingNumberOfNight1);
/*------ Table ---------*/
PdfPTable bookingPayDetailsTable = new PdfPTable(6);
bookingArrivalDeparture.setWidthPercentage(100);
float[] bookingPayDetailsTableWidth = {3f,1f,2f,1f,2f,1f};
bookingPayDetailsTable.setWidths(bookingPayDetailsTableWidth);
PdfPCell toatlPassengerAdult = new PdfPCell(new Paragraph("Total Passenger Adult :",font2));
toatlPassengerAdult.setBackgroundColor(new BaseColor(224, 224, 224));
toatlPassengerAdult.setBorderColor(BaseColor.WHITE);
toatlPassengerAdult.setBorderWidth(1f);
bookingPayDetailsTable.addCell(toatlPassengerAdult);
String[] noAdults;
noAdults = hBookingDetails.getAdult().split(" ");
PdfPCell toatlPassengerAdult1 = new PdfPCell(new Paragraph(noAdults[0],font2));
toatlPassengerAdult1.setBackgroundColor(new BaseColor(224, 224, 224));
toatlPassengerAdult1.setBorderColor(BaseColor.WHITE);
toatlPassengerAdult1.setBorderWidth(1f);
bookingPayDetailsTable.addCell(toatlPassengerAdult1);
PdfPCell noOfChild = new PdfPCell(new Paragraph("Child :",font2));
noOfChild.setBackgroundColor(new BaseColor(224, 224, 224));
noOfChild.setBorderColor(BaseColor.WHITE);
noOfChild.setBorderWidth(1f);
bookingPayDetailsTable.addCell(noOfChild);
PdfPCell noOfChild1 = new PdfPCell(new Paragraph(String.valueOf(hBookingDetails.getNoOfchild()),font2));
noOfChild1.setBackgroundColor(new BaseColor(224, 224, 224));
noOfChild1.setBorderColor(BaseColor.WHITE);
noOfChild1.setBorderWidth(1f);
bookingPayDetailsTable.addCell(noOfChild1);
PdfPCell infact = new PdfPCell(new Paragraph("Infant :",font2));
infact.setBackgroundColor(new BaseColor(224, 224, 224));
infact.setBorderColor(BaseColor.WHITE);
infact.setBorderWidth(1f);
bookingPayDetailsTable.addCell(infact);
PdfPCell infact1 = new PdfPCell(new Paragraph(hBookingDetails.getRoom_status().toString(),font2));
infact1.setBackgroundColor(new BaseColor(224, 224, 224));
infact1.setBorderColor(BaseColor.WHITE);
infact1.setBorderWidth(1f);
bookingPayDetailsTable.addCell(infact1);
/*------ Table ---------*/
PdfPTable bookedbyPayableTitle = new PdfPTable(1);
bookedbyPayableTitle.setWidthPercentage(100);
float[] bookedbyPayableTitleeWidth = {1f};
bookedbyPayableTitle.setWidths(bookedbyPayableTitleeWidth);
PdfPCell bookedbyPayableTitlerowtitle = new PdfPCell(new Paragraph("booked & Payable By:",font2));
bookedbyPayableTitlerowtitle.setBackgroundColor(new BaseColor(255, 255, 255));
bookedbyPayableTitlerowtitle.setBorderColor(BaseColor.WHITE);
bookedbyPayableTitle.addCell(bookedbyPayableTitlerowtitle);
/*------ Table ---------*/
PdfPTable bookedbyPayable = new PdfPTable(1);
bookedbyPayable.setWidthPercentage(100);
float[] bookedbyPayableWidth = {1f};
bookedbyPayable.setWidths(bookedbyPayableWidth);
PdfPCell bookedbyPayableInfo = new PdfPCell(new Paragraph("THE EXPEDITION CO., LTD. \n 700/86, Srinakarin Road, Suanluang, Suanluang, Bangkok - 10250. \n Thailand \n Emergency Contact No : 9877654444",font2));
bookedbyPayableInfo.setBackgroundColor(new BaseColor(224, 224, 224));
bookedbyPayableInfo.setBorderColor(BaseColor.WHITE);
bookedbyPayable.addCell(bookedbyPayableInfo);
/*------ Table ---------*/
PdfPTable bookinghotelDetails = new PdfPTable(1);
bookinghotelDetails.setWidthPercentage(100);
float[] bookingArrivalDepartureWidth = {2f};
bookinghotelDetails.setWidths(bookingArrivalDepartureWidth);
PdfPCell bookingPassenger = new PdfPCell(bookingPassengerName);
bookingPassenger.setBackgroundColor(new BaseColor(255, 255, 255));
bookingPassenger.setPaddingBottom(6);
bookingPassenger.setBorderColor(BaseColor.WHITE);
bookinghotelDetails.addCell(bookingPassenger);
PdfPCell arrivalDeparture = new PdfPCell(bookingArrivalDeparture);
arrivalDeparture.setBackgroundColor(new BaseColor(255, 255, 255));
arrivalDeparture.setBorderColor(BaseColor.WHITE);
arrivalDeparture.setPaddingBottom(6);
bookinghotelDetails.addCell(arrivalDeparture);
PdfPCell payDetails = new PdfPCell(bookingPayDetailsTable);
payDetails.setBackgroundColor(new BaseColor(255, 255, 255));
payDetails.setBorderColor(BaseColor.WHITE);
payDetails.setPaddingBottom(6);
bookinghotelDetails.addCell(payDetails);
PdfPCell bookedbyPayabletitleRow = new PdfPCell(bookedbyPayableTitle);
bookedbyPayabletitleRow.setBackgroundColor(new BaseColor(255, 255, 255));
bookedbyPayabletitleRow.setBorderColor(BaseColor.WHITE);
bookinghotelDetails.addCell(bookedbyPayabletitleRow);
PdfPCell bookedbyInfo = new PdfPCell(bookedbyPayable);
bookedbyInfo.setBackgroundColor(new BaseColor(255, 255, 255));
bookinghotelDetails.addCell(bookedbyInfo);
/*------ Table ---------*/
PdfPTable hotelStampSig = new PdfPTable(1);
hotelStampSig.setWidthPercentage(100);
float[] hotelStampSigWidth = {2f};
hotelStampSig.setWidths(hotelStampSigWidth);
PdfPCell blankforpersonSig = new PdfPCell(new Paragraph(".",font1));
blankforpersonSig.setBorderColor(BaseColor.WHITE);
hotelStampSig.addCell(blankforpersonSig);
PdfPCell sigPersonName = new PdfPCell(new Paragraph("THUNYASORN SWETPRASAT (Mr.Puk)",font1));
sigPersonName.setHorizontalAlignment(Element.ALIGN_CENTER);
sigPersonName.setBorderColor(BaseColor.WHITE);
sigPersonName.setPaddingTop(6);
hotelStampSig.addCell(sigPersonName);
PdfPCell blankLine = new PdfPCell(new Paragraph("_________"));
blankLine.setHorizontalAlignment(Element.ALIGN_CENTER);
blankLine.setBorderColor(BaseColor.WHITE);
hotelStampSig.addCell(blankLine);
PdfPCell blankForStamp = new PdfPCell(new Paragraph(".",font1));
blankForStamp.setBorderColor(BaseColor.WHITE);
hotelStampSig.addCell(blankForStamp);
PdfPCell companyStamp = new PdfPCell(new Paragraph("FOR\nTHE EXPEDITION CO., LTD. ",font1));
companyStamp.setHorizontalAlignment(Element.ALIGN_CENTER);
companyStamp.setBorderColor(BaseColor.WHITE);
companyStamp.setPaddingTop(6);
hotelStampSig.addCell(companyStamp);
/*------ Table ---------*/
PdfPTable hotelStampSig1 = new PdfPTable(1);
hotelStampSig1.setWidthPercentage(100);
float[] hotelStampSig1Width = {2f};
hotelStampSig1.setWidths(hotelStampSig1Width);
PdfPCell StampSig1 = new PdfPCell(hotelStampSig);
StampSig1.setBorderColor(BaseColor.RED);
hotelStampSig1.addCell(StampSig1);
/*------ Table ---------*/
PdfPTable bookingPaymentDetails = new PdfPTable(2);
bookingPaymentDetails.setWidthPercentage(100);
float[] bookingPaymentDetailsWidth = {2f,0.6f};
bookingPaymentDetails.setWidths(bookingPaymentDetailsWidth);
PdfPCell hotelPaymentDatails = new PdfPCell(bookinghotelDetails);
hotelPaymentDatails.setBackgroundColor(new BaseColor(255, 255, 255));
bookingPaymentDetails.addCell(hotelPaymentDatails);
PdfPCell stampSig = new PdfPCell(hotelStampSig1);
stampSig.setBorderColor(BaseColor.GRAY);
stampSig.setBackgroundColor(new BaseColor(255, 255, 255));
stampSig.setPaddingLeft(8);
stampSig.setPaddingBottom(8);
stampSig.setPaddingTop(8);
stampSig.setPaddingRight(8);
bookingPaymentDetails.addCell(stampSig);
/*------ Table ---------*/
PdfPTable hotelPaymentMainTable = new PdfPTable(1);
hotelPaymentMainTable.setWidthPercentage(100);
float[] hotelPaymentMainTableWidth = {2f};
hotelPaymentMainTable.setSpacingBefore(5f);
hotelPaymentMainTable.setSpacingAfter(10f);
hotelPaymentMainTable.setWidths(hotelPaymentMainTableWidth);
PdfPCell mainDetails = new PdfPCell(bookingPaymentDetails);
mainDetails.setBorderColor(BaseColor.GRAY);
mainDetails.setPadding(8);
mainDetails.setBorderWidth(1f);
hotelPaymentMainTable.addCell(mainDetails);
/*------ Table ---------*/
PdfPTable remarkTable = new PdfPTable(1);
remarkTable.setWidthPercentage(100);
float[] remarkTableWidth = {2f};
remarkTable.setWidths(remarkTableWidth);
PdfPCell remarks = new PdfPCell(new Phrase("Remarks :",font2));
remarks.setBorderColor(BaseColor.WHITE);
remarks.setBackgroundColor(new BaseColor(255, 255, 255));
remarkTable.addCell(remarks);
/*------ Table ---------*/
PdfPTable customerServiceTable = new PdfPTable(1);
customerServiceTable.setWidthPercentage(100);
float[] customerServiceWidth = {2f};
bookingCancellation.setSpacingBefore(5f);
bookingCancellation.setSpacingAfter(10f);
customerServiceTable.setWidths(customerServiceWidth);
PdfPCell callOur = new PdfPCell(new Phrase("* All special requests are subject to availability upon arrival. ",font2));
callOur.setBorderColor(BaseColor.WHITE);
callOur.setBackgroundColor(new BaseColor(255, 255, 255));
customerServiceTable.addCell(callOur);
/*------ Table ---------*/
PdfPTable notesFieldTable = new PdfPTable(1);
notesFieldTable.setWidthPercentage(100);
float[] notesFieldWidth = {2f};
notesFieldTable.setWidths(notesFieldWidth);
PdfPCell note = new PdfPCell(new Phrase("Note",font2));
note.setBorderColor(BaseColor.WHITE);
note.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note);
PdfPCell note1 = new PdfPCell(new Phrase("* IMPORTANT : All rooms are guaranteed on the day of arrival. In the case of a no-show, your room(s) will be released and you will be subject to the terms and condition of the cancellation policy specified at the time of booking, informed by your travel agent. ",font1));
note1.setBorderColor(BaseColor.WHITE);
note1.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note1);
PdfPCell note2 = new PdfPCell(new Phrase(" The price of the booking does not include mini-bar items, telephone usage, laundry service etc. The hotel will bill you directly. ",font1));
note2.setBorderColor(BaseColor.WHITE);
note2.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note2);
PdfPCell note3 = new PdfPCell(new Phrase(" In case where breakfast is included with the room rate, please note that certain hotels may charge extra for children travelling with their parents. ",font1));
note3.setBorderColor(BaseColor.WHITE);
note3.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note3);
PdfPCell note4 = new PdfPCell(new Phrase(" If not booked through us, and if applicable the hotel will bill you directly. Upon arrival, if you have any questions, please verify with the hotel. ",font1));
note4.setBorderColor(BaseColor.WHITE);
note4.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note4);
PdfPCell note5 = new PdfPCell(new Phrase(" Early Check-In & Late Check-out, is subject to availability at the discretion of the hotel. ",font1));
note5.setBorderColor(BaseColor.WHITE);
note5.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note5);
PdfPCell note6 = new PdfPCell(new Phrase(" For any change in the booking please contact our office at the above mentioned phone number. ",font1));
note6.setBorderColor(BaseColor.WHITE);
note6.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note6);
PdfPCell note7 = new PdfPCell(new Phrase(" The Expedition Co., Ltd. Does not hold any responsibility for any of your belongings in the hotel. ",font1));
note7.setBorderColor(BaseColor.WHITE);
note7.setBackgroundColor(new BaseColor(255, 255, 255));
notesFieldTable.addCell(note7);
/*------ Table ---------*/
PdfPTable notesTable = new PdfPTable(1);
notesTable.setWidthPercentage(100);
float[] notesWidth = {2f};
notesTable.setSpacingBefore(5f);
notesTable.setSpacingAfter(10f);
notesTable.setWidths(notesWidth);
PdfPCell noteShow = new PdfPCell(notesFieldTable);
noteShow.setBorderColor(BaseColor.GRAY);
noteShow.setBorderWidth(1f);
noteShow.setBackgroundColor(new BaseColor(255, 255, 255));
notesTable.addCell(noteShow);
/*------ Table ---------*/
PdfPTable AddAllTableInMainTable = new PdfPTable(1);
AddAllTableInMainTable.setWidthPercentage(100);
float[] AddAllTableInMainTableWidth = {2f};
AddAllTableInMainTable.setWidths(AddAllTableInMainTableWidth);
PdfPCell BookingAddImg1 = new PdfPCell(BookingAddImg);
BookingAddImg1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(BookingAddImg1);
PdfPCell hotelVoucherTitlemain1 = new PdfPCell(hotelVoucherTitlemain);
hotelVoucherTitlemain1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(hotelVoucherTitlemain1);
PdfPCell hotelVoucherMsg1 = new PdfPCell(hotelVoucherMsg);
hotelVoucherMsg1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(hotelVoucherMsg1);
PdfPCell todayDateTable1 = new PdfPCell(todayDateTable);
todayDateTable1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(todayDateTable1);
PdfPCell bookingFacilityInfoTable21 = new PdfPCell(bookingFacilityInfoTable2);
bookingFacilityInfoTable21.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(bookingFacilityInfoTable21);
PdfPCell bookingCancellation1 = new PdfPCell(bookingCancellation);
bookingCancellation1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(bookingCancellation1);
PdfPCell hotelPaymentMainTable1 = new PdfPCell(hotelPaymentMainTable);
hotelPaymentMainTable1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(hotelPaymentMainTable1);
PdfPCell remarkTable1 = new PdfPCell(remarkTable);
remarkTable1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(remarkTable1);
PdfPCell customerServiceTable1 = new PdfPCell(customerServiceTable);
customerServiceTable1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(customerServiceTable1);
PdfPCell notesTable1 = new PdfPCell(notesTable);
notesTable1.setBorder(Rectangle.NO_BORDER);
AddAllTableInMainTable.addCell(notesTable1);
/*------ Table ---------*/
PdfPTable AddMainTable = new PdfPTable(1);
AddMainTable.setWidthPercentage(100);
float[] AddMainTableWidth = {2f};
AddMainTable.setWidths(AddMainTableWidth);
PdfPCell AddAllTableInMainTable1 = new PdfPCell(AddAllTableInMainTable);
AddAllTableInMainTable1.setPadding(10);
AddAllTableInMainTable1.setBorderWidth(1f);
AddMainTable.addCell(AddAllTableInMainTable1);
document.open();// PDF document opened........
document.add(AddMainTable);
//document.add(Chunk.NEWLINE);
response().setContentType("application/pdf");
response().setHeader("Content-Disposition",
"inline; filename=");
document.close();
System.out.println("Pdf created successfully..");
File file = new File(fileName);
return ok(file);
} catch (Exception e) {
e.printStackTrace();
return ok();
}
}
public static void cancelMail(String email,HotelBookingDetails hBookingDetails){
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date = new Date();
final String username=Play.application().configuration().getString("username");
final String password=Play.application().configuration().getString("password");
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try{
Message feedback = new MimeMessage(session);
try {
feedback.setFrom(new InternetAddress(username,"CheckInRooms"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
feedback.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
feedback.setSubject("Booking in cancel");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Dear Sir/ Madam, \n\n your Booking in cancellation Policy \n\n your Booking Id "+hBookingDetails.getId()+" ");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
feedback.setContent(multipart);
Transport.send(feedback);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
@Transactional(readOnly=true)
public static Result getRoomType(Long supplierCode){
List<HotelRoomTypes> hRoomTypes = HotelRoomTypes.getHotelRoomDetails(supplierCode);
return ok(Json.toJson(hRoomTypes));
}
@Transactional(readOnly=true)
public static Result cancellationBookingMail(){
DateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
Date date = new Date();
List<HotelBookingDetails> hBookingDetails = HotelBookingDetails.allBookingData();
Calendar currentD = Calendar.getInstance();
currentD.setTime(date);
currentD.set(Calendar.MILLISECOND, 0);
for(HotelBookingDetails hDetails:hBookingDetails){
AgentRegistration aRegistration = AgentRegistration.findById(hDetails.getAgentId());
Date canclDate = null;
Calendar canclD = Calendar.getInstance();
canclD.setTime(hDetails.getLatestCancellationDate());
canclD.set(Calendar.MILLISECOND, 0);
if(currentD.get(Calendar.DAY_OF_YEAR) == canclD.get(Calendar.DAY_OF_YEAR) && currentD.get(Calendar.YEAR)==canclD.get(Calendar.YEAR) && currentD.get(Calendar.MONTH) == canclD.get(Calendar.MONTH)){
final String username=Play.application().configuration().getString("username");
final String password=Play.application().configuration().getString("password");
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.checkinrooms.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try{
Message feedback = new MimeMessage(session);
try {
feedback.setFrom(new InternetAddress(username,"CheckInRooms"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
feedback.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(aRegistration.getEmailAddr())); //aRegistration.getEmailAddr()
feedback.setSubject("You SignIn For travel_portal");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Dear Sir/ Madam, \n\n your Booking in cancellation Policy \n\n your Booking Id "+hDetails.getId()+" ");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
feedback.setContent(multipart);
Transport.send(feedback);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
return ok();
}
@Transactional(readOnly = false)
public static Result bookingCancelAndCharge(Long bookingId,String nightRate,String pandingAmount) {
DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(nightRate);
System.out.println(session().get("agent"));
HotelBookingDetails hBookingDetails = HotelBookingDetails.findBookingById(bookingId);
hBookingDetails.setRoom_status("Cancelled");
hBookingDetails.setCancelBookingCharges(Double.parseDouble(nightRate));
hBookingDetails.merge();
Double Credit = 0d;
AgentRegistration aRegistration = AgentRegistration.findByIdOnCode(session().get("agent"));
cancelMail(aRegistration.getEmailAddr(),hBookingDetails);
if(aRegistration.getPaymentMethod().equals("Credit") || aRegistration.getPaymentMethod().equals("Pre-Payment")){
Credit = aRegistration.getAvailableLimit() + Double.parseDouble(pandingAmount);
aRegistration.setAvailableLimit(Credit);
aRegistration.merge();
}
return ok();
}
@Transactional(readOnly = false)
public static Result getNatureOfBusiness(){
List<NatureOfBusiness> natureOfBusinesses = NatureOfBusiness.getNatureOfBusiness();
//List<String> natureList = new ArrayList<>();
// for(NatureOfBusiness natBusiness:natureOfBusinesses){
// natureList.add(natBusiness.getNatureofbusiness());
//}
return ok(Json.toJson(natureOfBusinesses));
}
@Transactional(readOnly=false)
public static Result editAgent() {
DynamicForm form = DynamicForm.form().bindFromRequest();
AgentRegistration aRegistration = AgentRegistration.getAgentCode(form.get("agentCode"));
aRegistration.setFirstName(form.get("firstName"));
aRegistration.setLastName(form.get("lastName"));
aRegistration.setCompanyAddress(form.get("companyAddress"));
aRegistration.setCompanyName(form.get("companyName"));
aRegistration.setBusiness(NatureOfBusiness.getNatureOfBusinessByName(form.get("business")));
aRegistration.setPosition(form.get("position"));
aRegistration.setDirectCode(form.get("directCode"));
aRegistration.setDirectTelNo(form.get("directTelNo"));
aRegistration.setWebSite(form.get("webSite"));
aRegistration.merge();
return ok();
}
@Transactional(readOnly=false)
public static Result getConfirmationInfo(String bookingId,String confirmationId,String nameConfirm,String status){
System.out.println("-=-==bookingId=-=-=");
System.out.println(bookingId);
HotelBookingDetails hBookingDetails = HotelBookingDetails.findBookingIdDetail(bookingId);
hBookingDetails.setRoom_status(status);
hBookingDetails.setConfirmationId(confirmationId);
hBookingDetails.setConfirmProcessUser(nameConfirm);
hBookingDetails.merge();
return ok();
}
@Transactional(readOnly=false)
public static Result getVoucherPdfPath(String bookingId) {
response().setContentType("application/pdf");
response().setHeader("Content-Disposition", "inline; filename="+"HotelVoucher.pdf");
String PdfFile = rootDir + File.separator + "BookingVoucherDocuments"+File.separator+ bookingId + File.separator+"HotelVoucher.pdf";
File f = new File(PdfFile);
response().setHeader("Content-Length", ((int)f.length())+"");
return ok(f);
}
}
|
package com.example.accounting_app.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.accounting_app.R;
import com.example.accounting_app.adapter.adapter_fragment_statements;
import com.example.accounting_app.function.Pie_Chart;
import com.example.accounting_app.listener.listener_fragment_statements;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
/**
* @Creator cetwag, yuebanquan
* @Version V2.0.0
* @Time 2019.6.27
* @Description 报表模块碎片
*/
public class fragment_statements extends Fragment {
public Pie_Chart piec;//图表功能类
//报表碎片中的日期选择弹窗的标志
public static final int FRAGMENT_STATEMENTS_SELECT_TIME = 2;
listener_fragment_statements listener;
public TextView tv_time_selected;
public Spinner spi_income_pay;
adapter_fragment_statements adapter;
public com.github.mikephil.charting.charts.PieChart piechart;
public LinearLayout Lin_statements_item;
public LinearLayout Lin_major;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//inflater使将xml布局文件转换为视图的一个类,container表示在container里面显示这个视图
View view = inflater.inflate(R.layout.fragment_statements, container, false);
//屏幕适配
ScreenAdapterTools.getInstance().loadView(view);
return view;
}
/**
* @parameter
* @description 根据fragment的生命周期,onActivityCreated在onCreateView后执行
* @Time 2019/6/29 21:29
*/
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//控件初始化
init();
//监听功能函数
listener.listener_Fragment_statements();
//适配器功能函数
adapter.adapter_Fragment_statements();
//饼状图绘制
piec.pie_chart_data_pay();
//饼状图监听绘制
listener.select_pay_income();
}
/**
* @parameter
* @description 控件初始化
* @Time 2019/6/29 21:26
*/
void init() {
tv_time_selected = getView().findViewById(R.id.tv_time_selected);
spi_income_pay = getView().findViewById(R.id.spi_income_pay);
piechart = getView().findViewById(R.id.pie_chart);
listener = new listener_fragment_statements(this);
adapter = new adapter_fragment_statements(this);
piec = new Pie_Chart(this);
Lin_statements_item = getView().findViewById(R.id.Lin_statements_item);
Lin_major = getView().findViewById(R.id.Lin_major);
Lin_major.setVisibility(View.GONE);//隐藏示例item
}
}
|
package com.jack.rookiepractice.test;
import lombok.Data;
/**
* @author jack
* @Classname Student
* Create by jack 2019/12/19
* @date: 2019/12/19 21:31
* @Description:
*/
@Data
public class Student {
private int age;
private String name;
}
|
package com.milos.domain.util;
import java.util.Date;
public class TimeUtil {
public static long diffInMillis(Date dt1, Date dt2) {
return Math.abs(dt1.getTime() - dt2.getTime());
}
}
|
package jupiterpa.masterdata;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import jupiterpa.IMasterDataServer;
import jupiterpa.IMasterDataServer.EIDTyped;
import jupiterpa.IMasterDataServer.MasterDataException;
import jupiterpa.IMasterDataClient;
import jupiterpa.util.EID;
import lombok.Data;
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"mock","test"})
public class MasterDataTest {
IMasterDataServer md;
ServiceMock master;
ServiceMock dependent;
public class ServiceMock implements IMasterDataClient {
String name;
List<EIDTyped> invalidated = new ArrayList<EIDTyped>();
public ServiceMock(String name) {
this.name = name;
}
@Override
public void invalidate(EIDTyped id) {
invalidated.add(id);
}
@Override
public void initialLoad() throws MasterDataException {
// TODO Auto-generated method stub
}
}
@Data
public class DataMock {
EIDTyped eid;
}
@Before
public void setup() {
md = new MasterDataService();
master = new ServiceMock("Master");
dependent = new ServiceMock("Dep");
}
private DataMock getMock(String type, EID id) throws MasterDataException {
EIDTyped eid = new EIDTyped(type,id);
DataMock data = new DataMock();
data.setEid(eid);
return data;
}
@Test
public void oneMaster() throws MasterDataException {
md.registerType("T1", master);
DataMock input = getMock("T1",EID.get('1'));
md.post(input.getEid(),input);
DataMock result = (DataMock) md.get(input.getEid());
assertThat(result, equalTo(input));
}
@Test
public void masterClient() throws MasterDataException {
md.registerType("T1", master);
md.registerClient("T1", dependent);
DataMock input = getMock("T1",EID.get('1'));
md.post(input.getEid(), input);
assertThat(dependent.invalidated, contains(input.getEid()));
}
@Test
public void lateDependent() throws MasterDataException {
md.registerType("T1", master);
DataMock input1 = getMock("T1",EID.get('1'));
md.post(input1.getEid(), input1);
md.registerClient("T1", dependent);
DataMock input2 = getMock("T1",EID.get('1'));
md.post(input2.getEid(), input2);
assertThat(dependent.invalidated, contains(input2.getEid()));
assertThat(dependent.invalidated.size(), equalTo(1));
}
@Test
public void postDependent() throws MasterDataException {
md.registerType("T1", master);
md.registerType("T2", master);
md.registerClient("T1", dependent);
md.registerClient("T2", dependent);
DataMock input1 = getMock("T1",EID.get('1'));
md.post(input1.getEid(), input1);
DataMock input2 = getMock("T2",EID.get('2'));
md.postDependent(input2.getEid(), input2, input1.getEid());
assertThat(dependent.invalidated, hasItem(input1.getEid()));
assertThat(dependent.invalidated, hasItem(input2.getEid()));
}
@Test
public void delete() throws MasterDataException {
md.registerType("T1", master);
md.registerClient("T1", dependent);
DataMock input1 = getMock("T1",EID.get('1'));
md.post(input1.getEid(), input1);
md.delete(input1.getEid());
assertThat( md.getAll("T1").size(), equalTo(0));
}
@Test
public void deleteDependent() throws MasterDataException {
md.registerType("T1", master);
md.registerType("T2", master);
md.registerClient("T1", dependent);
md.registerClient("T2", dependent);
DataMock input1 = getMock("T1",EID.get('1'));
md.post(input1.getEid(), input1);
DataMock input2 = getMock("T2",EID.get('2'));
md.postDependent(input2.getEid(), input2, input1.getEid());
md.delete(input2.getEid());
assertThat( md.getAll("T2").size(), equalTo(0));
assertThat( md.getAll("T1").size(), equalTo(1));
md.delete(input1.getEid());
assertThat( md.getAll("T1").size(), equalTo(0));
}
@Test
public void doubleRegistration() {
try {
md.registerType("T1", master);
md.registerType("T1", dependent);
}
catch (MasterDataException x) {
return;
}
fail("Exception missing");
}
@Test
public void unknownTypeRegistration() {
try {
md.registerType("T1", master);
md.registerClient("T2", dependent);
}
catch (MasterDataException x) {
return;
}
fail("Exception missing");
}
@Test
public void unknownTypePost() {
try {
DataMock entry = getMock("T1",EID.get('1'));
md.post(entry.getEid(), entry);
}
catch (MasterDataException x) {
return;
}
fail("Exception missing");
}
@Test
public void unknownParentPost() {
try {
md.registerType("T1", master);
md.registerType("T2", master);
md.registerClient("T1", dependent);
md.registerClient("T2", dependent);
DataMock input1 = getMock("T1",EID.get('1'));
md.post(input1.getEid(), input1);
} catch (MasterDataException x) {
fail("Unexpected Exception");
}
try {
EIDTyped unknown = new EIDTyped("T",EID.get('T'));
DataMock input2 = getMock("T2",EID.get('2'));
md.postDependent(input2.getEid(), input2, unknown);
} catch (MasterDataException x) {
return;
}
fail("Exception missing");
}
@Test
public void dependentNotDeleted() {
DataMock input1 = null;
try {
md.registerType("T1", master);
md.registerType("T2", master);
md.registerClient("T1", dependent);
md.registerClient("T2", dependent);
input1 = getMock("T1",EID.get('1'));
md.post(input1.getEid(), input1);
DataMock input2 = getMock("T2",EID.get('2'));
md.postDependent(input2.getEid(), input2, input1.getEid());
} catch (MasterDataException x) {
fail("Unexpected Exception");
}
try {
md.delete(input1.getEid());
} catch (MasterDataException x) {
return;
}
fail("Exception missing");
}
@Test
public void deleteUnknown() {
DataMock input1 = null;
DataMock input2 = null;
try {
md.registerType("T1", master);
md.registerType("T2", master);
md.registerClient("T1", dependent);
md.registerClient("T2", dependent);
input1 = getMock("T1",EID.get('1'));
md.post(input1.getEid(), input1);
input2 = getMock("T1",EID.get('1'));
} catch (MasterDataException x) {
fail("Unexpected Exception");
}
try {
md.delete(input2.getEid());
} catch (MasterDataException x) {
return;
}
fail("Exception missing");
}
}
|
/*
什么时候使用静态?
从两方面下手:
1.什么时候定义静态变量(类变量)❓
对象中出现共享数据(数据指的是具体值,张三,而不是属性,name),
该数据被静态所修饰,存在于 内存共享区(数据区);
而对象中特有的数据要定义成非静态存在于堆内存
2.什么时候定义静态函数❓
当功能内部没有访问到非静态数据( 对象特有的数据,
对象还没创建,主要意思是拿不到的数据,像在它之前出现在栈中的数据都是可以的),
那么该功能可以定义为静态的。
静态的应用
若每一个应用程序中都有共性的功能,可以将这些功能抽取,独立封装,以便复用
*/
// class StaticDemo{
// public static void main(String[] args){
// int[] arr = {3,4,1,8};
// int max = getMax(arr);
// System.out.println("max=" + max);
// }
// public static int getMax(int[] arr){
// int max = 0;
// for(int x = 1; x < arr.length; x++){
// if (arr[i] > arr[max]){
// max = x;
// }
// }
// return arr[max];
// }
// }
// class Test{
// }
class ArrayTool{
// 将ArrayTool作为一个工具类,禁止其进行实例化。
private ArrayTool(){};
// 获取最大值
// public int getMax(int[] arr){
public static int getMax(int[] arr){
int max = 0;
for(int x = 1; x < arr.length; x++){
if (arr[x] > arr[max]){
max = x;
}
}
return arr[max];
}
// 获取最小值
// public int getMin(int[] arr){
public static int getMin(int[] arr){
int min = 0;
for(int x = 1; x < arr.length; x++){
if (arr[x] < arr[min]){
min = x;
}
}
return arr[min];
}
// 选择
public static void selectSort(int[] arr){
for (int x=0; x<arr.length-1; x++){
for(int y=x+1; y< arr.length; y++){
if (arr[x] > arr[y]){
swap(arr,x,y);
}
}
}
}
// 冒泡
public static void bubbleSort(int[] arr){
for (int x=0; x<arr.length+1; x++){
for (int y=0; y<arr.length-x-1; y++){
if (arr[y]>arr[y+1]){
swap(arr, y, y+1);
}
}
}
}
// 打印数组
public static void printArray(int[] arr){
for (int x = 0; x < arr.length; x++){
if (x == arr.length-1){
System.out.println(arr[x]);
return;
}
System.out.print(arr[x]);
}
}
// 交换index功能
// 小细节,它是工具类内部调用的,没必要提供出去,将不需要暴露出去的都隐藏起来,将其私有化
// 但是static还是要的,因为本工具类已经被禁止实例化调用了(private),
// 所有的方法都是静态的,静态内容只能调用静态内容
// public static void swap(int[] arr, int a, int b){
private static void swap(int[] arr, int a, int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
|
package com.devinchen.library.common.base.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.devinchen.library.common.base.holder.BaseHolder;
import java.util.List;
import java.util.Random;
/**
* CommonLibraryDemo
* com.devinchen.library.common.base.adapter
* Created by Devin Chen on 2017/5/25 12:00.
* explain:双布局风格的BaseAdapter
* 要求两个布局必须具有相同的子控件,否则使用同一个holder会出错
*/
public abstract class BaseDoubleAdapter<DataSet, Model, Holder extends BaseHolder> extends BaseAdapter {
public Context context;
public DataSet mData;
public BaseDoubleAdapter(Context context, DataSet mData) {
this.context = context;
this.mData = mData;
}
@Override
public int getCount() {
if (mData == null) {
return 0;
} else {
if (mData instanceof List) {
return ((List<Model>) mData).size();
} else {
return ((Model[]) mData).length;
}
}
}
@Override
public Model getItem(int position) {
if (mData instanceof List) {
return ((List<Model>) mData).get(position);
} else {
return ((Model[]) mData)[position];
}
}
@Override
public long getItemId(int position) {
return position;
}
/**
* 通过随机数决定该使用哪一种风格的布局
*
* @param position
* @return
*/
@Override
public int getItemViewType(int position) {
return new Random().nextInt(10000) % 2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if (convertView == null) {
if (getItemViewType(position) == 0) {
convertView = LayoutInflater.from(context).inflate(layoutFirstId(), parent, false);
} else {
convertView = LayoutInflater.from(context).inflate(layoutSecondId(), parent, false);
}
holder = createHolder(convertView);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
refreshView(holder, position);
return null;
}
/**
* 填充数据
*
* @param holder
* @param position
*/
protected abstract void refreshView(Holder holder, int position);
/**
* 创建holder
*
* @param convertView
* @return
*/
protected abstract Holder createHolder(View convertView);
/**
* 第一种布局
*
* @return
*/
protected abstract int layoutFirstId();
/**
* 第二种布局
*
* @return
*/
protected abstract int layoutSecondId();
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package atm;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.*;
/**
*
* @author Moustafa(DAR4)
*/
public class check extends JFrame implements ActionListener{
JPanel pane = new JPanel();
JLabel lpass = new JLabel("Password");
JLabel lbalance = new JLabel("Balance");
JPasswordField tpass = new JPasswordField();
JTextField tbalance = new JTextField();
JButton bcheck = new JButton("Check Balance");
JButton bmenu = new JButton("Back Menu");
Connection cn;
Statement st;
public void database()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn = DriverManager.getConnection("jdbc:odbc:ATM");
}catch(ClassNotFoundException e) {
System.err.println("Failed to load driver");
e.printStackTrace();
}catch(SQLException e){
System.err.println("Unable to connect");
e.printStackTrace();
}
}
public check()
{
pane.setLayout(null);
setLocation(400,250);
setSize(300,200);
setTitle("Check Balance");
setResizable(false);
setVisible(true);
lpass.setBounds(10,20,80,20);
lbalance.setBounds(10,40,80,20);
tpass.setBounds(100,20,100,20);
tbalance.setBounds(100,40,100,20);
tbalance.setEditable(false);
bcheck.setBounds(80,70,130,20);
bmenu.setBounds(80,120,140,20);
bcheck.addActionListener(this);
bmenu.addActionListener(this);
pane.add(lpass);
pane.add(lbalance);
pane.add(tpass);
pane.add(tbalance);
pane.add(bcheck);
pane.add(bmenu);
add(pane);
database();
}
public void actionPerformed(ActionEvent e){
Object source = e.getSource();
if(source == bmenu)
{
transaction ob1 = new transaction();
dispose();
}
else if ( source == bcheck)
{
try{
boolean b = false;
st= cn.createStatement();
ResultSet rs=st.executeQuery("SELECT * FROM Table1 WHERE password ='"+tpass.getText()+"'");
while(rs.next()){
b= true;
tbalance.setText(rs.getString(8));
JOptionPane.showMessageDialog(null,"Balance Found.");
}
if(b == false)
JOptionPane.showMessageDialog(null,"Balance Not Found. Try again");
st.close();
}
catch(SQLException s){
}
catch(Exception x){
}
}
}
public static void main(String[]args){
check ob = new check();
}
}
|
package au.gov.ga.geodesy.igssitelog.support.marshalling.moxy;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.matchers.JUnitMatchers;
import java.time.Instant;
import static org.junit.Assert.*;
/**
* Created by brookes on 9/06/16.
*/
public class DateAdapterTest {
DateAdapter dateAdapter = new DateAdapter();
@Test
public void testUnmarshalDateWithWhiteSpace() throws Exception {
String testDate = "1939-08-12\n ";
String expected = "1939-08-12";
Instant actual = dateAdapter.unmarshal(testDate);
MatcherAssert.assertThat(actual.toString(), Matchers.containsString(expected));
}
}
|
package com.example.enroute.demo.application;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import osgi.enroute.configurer.api.RequireConfigurerExtender;
import osgi.enroute.google.angular.capabilities.RequireAngularWebResource;
import osgi.enroute.rest.api.REST;
import osgi.enroute.twitter.bootstrap.capabilities.RequireBootstrapWebResource;
import osgi.enroute.webserver.capabilities.RequireWebServerExtender;
@RequireAngularWebResource(resource = { "angular.js", "angular-resource.js", "angular-route.js" }, priority = 1000)
@RequireBootstrapWebResource(resource = "css/bootstrap.css")
@RequireWebServerExtender
@RequireConfigurerExtender
@Component(name = "com.example.enroute.demo")
public class DemoApplication implements REST {
static Logger logger = LoggerFactory.getLogger(DemoApplication.class);
public String getUpper(String string) {
return string.toUpperCase();
}
public RandomDTO getRandom() throws UnknownHostException {
final RandomDTO result = new RandomDTO();
result.created = DateTimeFormatter.ISO_DATE_TIME.format(LocalDateTime.now());
result.uuid = UUID.randomUUID().toString();
result.hostname = InetAddress.getLocalHost().getHostName();
logger.info("Generated result: {}", result);
return result;
}
}
|
package DataStructures;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.Vector;
public class GraphicData {
Vector<NodeData> list = new Vector<>();
//Creates a new NodeData and inserts it into the list
public void newNode(String text, Double x, Double y){
NodeData newNode = new NodeData(x.longValue(),y.longValue(),text);
list.add(newNode);
}
public void newNode(NodeData nodeData){
list.add(nodeData);
}
//Connects two nodes
public void connectNodes(String node1, String node2, Boolean isDouble){
//Gets the nodes for the connection
NodeData nodeData1 = this.getNode(node1);
NodeData nodeData2 = this.getNode(node2);
//Connects origin with destiny
nodeData1.addNewConnection(nodeData2,isDouble);
//If the connection is non-directed, connects the destiny with the origin
if(isDouble) nodeData2.addNewConnection(nodeData1,isDouble);
}
//Returns a node from a string corresponding to its name
public NodeData getNode(String data){
NodeData result = null;
for (NodeData node:list) {
if(node.getLabel() == data){
result = node;
break;
}
}
return result;
}
//Returns the corresponding JSON Object for the GraphicData instance
public JSONObject toJSON(){
JSONObject js = new JSONObject();
JSONArray arr = new JSONArray();
for (NodeData node:this.list) {
arr.add(node.toJSON());
}
js.put("nodes", arr);
return js;
}
//Gets the coordinates of all the nodes
public Vector<Vector<Long>> getCoords(){
Vector<Vector<Long>> coords = new Vector<>();
Vector<Long> xCoords = new Vector<>();
Vector<Long> yCoords = new Vector<>();
for (NodeData node:this.list) {
xCoords.add(node.getX());
yCoords.add(node.getY());
}
coords.add(xCoords); coords.add(yCoords);
return coords;
}
//Gets the names of all the nodes
public Vector<String> getNames() {
Vector<String> names = new Vector<>();
for (NodeData node:this.list) {
names.add(node.getLabel());
}
return names;
}
//Gets the node list
public Vector<NodeData> getList() {
return list;
}
}
|
package com.tencent.mm.model;
import com.tencent.mm.protocal.c.ajs;
import com.tencent.mm.protocal.k;
import com.tencent.mm.protocal.k.c;
import com.tencent.mm.protocal.k.e;
public class az$b extends e implements c {
public ajs dBV = new ajs();
public final int G(byte[] bArr) {
this.dBV = (ajs) new ajs().aG(bArr);
k.a(this, this.dBV.six);
return this.dBV.six.rfn;
}
public final int getCmdId() {
return 0;
}
}
|
package com.fleet.netty.server.config;
import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author April Han
*/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
logger.info("channel active......");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info("channel read......");
logger.info("服务端收到消息: {}", JSON.toJSONString(msg));
ctx.write("你也好");
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.info("channel caught......");
cause.printStackTrace();
ctx.close();
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
logger.info("channel inactive......");
}
}
|
package com.duanxr.yith.easy;
import java.util.Stack;
/**
* @author 段然 2021/6/30
*/
public class ComplementOfBaseTenInteger {
/**
* Every non-negative integer n has a binary representation. For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on. Note that except for n = 0, there are no leading zeroes in any binary representation.
*
* The complement of a binary representation is the number in binary you get when changing every 1 to a 0 and 0 to a 1. For example, the complement of "101" in binary is "010" in binary.
*
* For a given number n in base-10, return the complement of it's binary representation as a base-10 integer.
*
*
*
* Example 1:
*
* Input: n = 5
* Output: 2
* Explanation: 5 is "101" in binary, with complement "010" in binary, which is 2 in base-10.
* Example 2:
*
* Input: n = 7
* Output: 0
* Explanation: 7 is "111" in binary, with complement "000" in binary, which is 0 in base-10.
* Example 3:
*
* Input: n = 10
* Output: 5
* Explanation: 10 is "1010" in binary, with complement "0101" in binary, which is 5 in base-10.
*
*
* Note:
*
* 0 <= n < 109
* This question is the same as 476: https://leetcode.com/problems/number-complement/
*
* 每个非负整数 N 都有其二进制表示。例如, 5 可以被表示为二进制 "101",11 可以用二进制 "1011" 表示,依此类推。注意,除 N = 0 外,任何二进制表示中都不含前导零。
*
* 二进制的反码表示是将每个 1 改为 0 且每个 0 变为 1。例如,二进制数 "101" 的二进制反码为 "010"。
*
* 给你一个十进制数 N,请你返回其二进制表示的反码所对应的十进制整数。
*
*
*
* 示例 1:
*
* 输入:5
* 输出:2
* 解释:5 的二进制表示为 "101",其二进制反码为 "010",也就是十进制中的 2 。
* 示例 2:
*
* 输入:7
* 输出:0
* 解释:7 的二进制表示为 "111",其二进制反码为 "000",也就是十进制中的 0 。
* 示例 3:
*
* 输入:10
* 输出:5
* 解释:10 的二进制表示为 "1010",其二进制反码为 "0101",也就是十进制中的 5 。
*
*
* 提示:
*
* 0 <= N < 10^9
* 本题与 476:https://leetcode-cn.com/problems/number-complement/ 相同
*
*/
class Solution {
public int bitwiseComplement(int n) {
if (n == 0) {
return 1;
}
int checkPoint = (Integer.MAX_VALUE >> 1) ^ Integer.MAX_VALUE;
int mask = Integer.MAX_VALUE;
int nn = ~n & Integer.MAX_VALUE >> 1;
for (int i = 0; i <= 32; i++) {
if ((n << i & checkPoint) == checkPoint) {
nn = nn & mask;
break;
}
mask = mask >> 1;
}
return nn;
}
}
class Solution1 {
public int bitwiseComplement(int n) {
if (n == 0) {
return 1;
}
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < 32; i++) {
stack.push(n & 1);
n = n >>> 1;
}
int nn = 0;
boolean hasOne = false;
while (!stack.isEmpty()) {
nn = nn << 1;
Integer pop = stack.pop();
if (pop == 0 && hasOne) {
nn += 1;
} else if (pop == 1) {
hasOne = true;
}
}
return nn;
}
}
}
|
package com.tencent.mm.plugin.appbrand.appcache;
import com.tencent.mm.a.e;
import com.tencent.mm.sdk.d.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.io.File;
import org.json.JSONObject;
class j$1 extends c {
final /* synthetic */ j ffE;
j$1(j jVar) {
this.ffE = jVar;
}
public final void enter() {
super.enter();
x.i("MicroMsg.LibIncrementalTestCase[incremental]", "WriteMockLibInfo enter");
String abT = af.abT();
if (bi.oW(abT)) {
j.a(this.ffE, "!!MockLibInfo Path Error!!");
return;
}
try {
JSONObject jSONObject = new JSONObject();
jSONObject.put("version", j.a(this.ffE));
File file = new File(abT);
file.delete();
file.createNewFile();
byte[] bytes = jSONObject.toString().getBytes("UTF-8");
int b = e.b(file.getAbsolutePath(), bytes, bytes.length);
if (b != 0) {
j.a(this.ffE, "MockLibInfo Write Error " + b);
} else {
j.a(this.ffE, j.b(this.ffE));
}
} catch (Exception e) {
j.a(this.ffE, "MockLibInfo Write Exception " + e.getMessage());
}
}
}
|
package cine;
public class Ticket {
public Ticket() {
// TODO Auto-generated constructor stub
}
}
|
package com.Collections_PriorityQueue_HashMap_TreeMap;
//2. Write a Java program to copy a Tree Map content to another Tree Map.
import java.util.TreeMap;
public class TreeMap_CopyContent {
public static void main(String args[]) {
// Create a tree map
TreeMap<String, String> tree_map1 = new TreeMap<String, String>();
// Put elements to the map
tree_map1.put("C1", "Red");
tree_map1.put("C2", "Green");
tree_map1.put("C3", "Black");
tree_map1.put("C4", "White");
tree_map1.put("C5", "Blue");
System.out.println("Tree Map 1: " + tree_map1);
TreeMap<String, String> tree_map2 = new TreeMap<String, String>();
tree_map2.put("A1", "Orange");
tree_map2.put("A2", "Pink");
System.out.println("Tree Map 2: " + tree_map2);
tree_map1.putAll(tree_map2);
System.out.println("After coping map2 to map1: " + tree_map1);
}
}
|
package com.action;
import com.entity.Usera;
import com.hibernate.HibernateSessionFactory;
import java.io.PrintStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.hibernate.Session;
public class LoginAction
{
private Usera user;
private String errormsg;
public String verify()
{
System.out.println(this.user.getUsername() + ":::" + this.user.getPassword());
String username = this.user.getUsername() == null ? "" : this.user.getUsername();
String password = this.user.getPassword() == null ? "" : this.user.getPassword();
Session session = HibernateSessionFactory.getSession();
/*
* System.out.println("通过账号查询出的密码:" + db_password);
* */
String hql = "select password from Usera where username=?";
Query query = session.createQuery(hql);
query.setParameter(0, username);
String db_password = (String)query.uniqueResult();
System.out.println("通过账号查询出的密码:" + db_password);
/*
* System.out.println("通过账号查询出的flag:" + flag);
* */
String hql1 = "select flag from Usera where username=?";
Query query1 = session.createQuery(hql1);
query1.setParameter(0, username);
String flag = query1.uniqueResult().toString();
System.out.println("通过账号查询出的flag:" + flag);
if (db_password == null)
{
this.errormsg = "账号或密码错误abc";
return "error";
}
session.close();
if (db_password.equals(this.user.getPassword())) {
HttpServletRequest request=ServletActionContext.getRequest();
HttpSession session1=request.getSession();
session1.setAttribute("username", username);
if(flag.equals("1")){
session1.setAttribute("flag", "管理员");
}else{
session1.setAttribute("flag", "员工");
}
return "success";
}
this.errormsg = "账号或密码错误abc";
return "error";
}
public Usera getUser()
{
return this.user;
}
public void setUser(Usera user)
{
this.user = user;
}
public String getErrormsg()
{
return this.errormsg;
}
public void setErrormsg(String errormsg)
{
this.errormsg = errormsg;
}
}
|
package ch.epfl.seti.server;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NavigableMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import ch.epfl.seti.client.typelib.SVector;
import ch.epfl.seti.server.TaskInfo.Type;
import ch.epfl.seti.shared.ReduceTask;
import ch.epfl.seti.shared.Task;
import com.google.gwt.user.client.rpc.IsSerializable;
public class Database {
private HashMap<Integer, TaskInfo> m_tasks = new HashMap<Integer, TaskInfo>();
@SuppressWarnings("rawtypes")
private HashMap<Object, SVector> m_reduceTasks = new HashMap<Object, SVector>();
private final static HBaseWrapper s_wrapper = HBaseWrapper
.createHBaseConnection();
private static ByteArrayOutputStream s_bos = null;
private static ObjectOutputStream s_oos = null;
static {
try {
s_bos = new ByteArrayOutputStream();
s_oos = new ObjectOutputStream(s_bos);
} catch (IOException e) {
e.printStackTrace();
}
}
public Database() {
restoreState();
initCheckpointExecutor();
}
public void trackTask(int id, TaskInfo ti) {
m_tasks.put(id, ti);
checkpointNewChange(ti.getProjectName(), "task_id" + id, ti);
}
public TaskInfo getPendingTaskInfo(int id) {
return m_tasks.get(id);
}
/** Checks if a project has all the Map tasks solved */
public boolean projectHasAllMapTasksSolved(String projectName) {
boolean result = true;
for (TaskInfo ti : m_tasks.values()) {
/** For-each task belonging to the project */
if (ti.getProjectName().equals(projectName)) {
/** Check if the map task is solved */
if (ti.getType() == Type.MAP && !ti.isSolved())
return false;
}
return true;
}
return result;
}
interface TaskInfoPredicate {
public boolean isValid(TaskInfo ti);
}
@SuppressWarnings("rawtypes")
private Task getTaskSatisfyingPredicate(String projectName, Type type,
TaskInfoPredicate predicate) {
/**
* Use timestamp to pick the best task satisfying a given predicate; we pick
* the oldest task and, at the end, we update its timestamp
*/
TaskInfo bestTaskInfo = null;
long currentTime = System.currentTimeMillis();
long minTime = currentTime;
for (TaskInfo ti : m_tasks.values()) {
/** For-each task belonging to the project */
if (ti.getProjectName().equals(projectName)) {
/** Check if the map task is solved */
if (ti.getType() == type) {
assert ti.getTask() != null;
if (predicate.isValid(ti)) {
if (ti.getLastTimestamp() <= minTime) {
minTime = ti.getLastTimestamp();
bestTaskInfo = ti;
}
}
}
}
}
if (bestTaskInfo != null) {
bestTaskInfo.setLastTimestamp(currentTime);
return bestTaskInfo.getTask();
}
return null;
}
@SuppressWarnings("rawtypes")
private Task getTaskSatisfyingPredicate(String projectName,
TaskInfoPredicate predicate) {
Task result;
/** Search for a map task that is late */
result = getTaskSatisfyingPredicate(projectName, Type.MAP, predicate);
if (result == null) {
/**
* If the no map task is late, then look for a late reduce task only if
* the map tasks are finished
*/
if (projectHasAllMapTasksSolved(projectName)) {
result = getTaskSatisfyingPredicate(projectName, Type.REDUCE, predicate);
}
}
return result;
}
/**
* Returns any task that is late; the Map tasks are considered first We are
* using this function to implement the speculative execution, when two
* clients receive the same task to be solved.
*/
@SuppressWarnings("rawtypes")
public Task getRunningTask(String projectName) {
Task result;
/** Search for a late task */
result = getTaskSatisfyingPredicate(projectName, new TaskInfoPredicate() {
@Override
public boolean isValid(TaskInfo ti) {
return ti.isLate() && !ti.isSolved();
}
});
if (result == null) {
/** If no late task is found, then return any non-solved task */
result = getTaskSatisfyingPredicate(projectName, new TaskInfoPredicate() {
@Override
public boolean isValid(TaskInfo ti) {
return !ti.isSolved();
}
});
}
return result;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public ReduceTask getReduceTask(String projectName) {
Iterator<Object> it = m_reduceTasks.keySet().iterator();
if (it.hasNext()) {
IsSerializable key = (IsSerializable) it.next();
SVector values = m_reduceTasks.get(key);
m_reduceTasks.remove(key);
return new ReduceTask(key, values).setId(ServerServiceImpl.s_generator
.getAndIncrement());
}
return null;
}
public boolean hasReduceTasks(String projectName) {
return !m_reduceTasks.keySet().isEmpty();
}
/**
* Store the result of a map.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void putMapResult(TaskInfo ti, Object key, Object value) {
SVector list = null;
if (!m_reduceTasks.containsKey(key)) {
m_reduceTasks.put(key, new SVector());
}
list = m_reduceTasks.get(key);
list.add(value);
checkpointNewChange(ti.getProjectName(), key, value);
}
@SuppressWarnings({ "rawtypes" })
public boolean isMapResultValid(TaskInfo ti, Object key, Object value) {
boolean result = false;
if (m_reduceTasks.containsKey(key)) {
SVector list = m_reduceTasks.get(key);
result = list.contains(value);
}
return result;
}
private ThreadPoolExecutor m_threadPool = null;
private void initCheckpointExecutor() {
int m_poolSize = 4;
int m_maxPoolSize = 4;
long m_keepAliveTime = 60;
int m_queueSize = 1024;
final ArrayBlockingQueue<Runnable> m_queue = new ArrayBlockingQueue<Runnable>(m_queueSize);
m_threadPool = new ThreadPoolExecutor(m_poolSize, m_maxPoolSize, m_keepAliveTime,
TimeUnit.SECONDS, m_queue);
}
private void checkpointNewChange(final String projectName, final Object key, final Object value) {
m_threadPool.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
byte[] akey;
s_oos.writeObject(key);
akey = s_bos.toByteArray();
s_oos.reset();
s_bos.reset();
byte[] avalue;
s_oos.writeObject(value);
avalue = s_bos.toByteArray();
/** Storing the actual object */
s_wrapper.putData(projectName, akey, avalue);
s_oos.reset();
s_bos.reset();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void restoreState() {
/** XXX: link the the projects from the ProjectLoader class */
HashMap<String, IInputGenerator> projects = new HashMap<String, IInputGenerator>();
try {
for (String projectName : projects.keySet()) {
Scan scan = new Scan(Bytes.toBytes(projectName));
ResultScanner scanner = s_wrapper.getHTable().getScanner(scan);
for (Result result : scanner) {
NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> map = result
.getMap();
for (byte[] it : map.keySet()) {
NavigableMap<byte[], NavigableMap<Long, byte[]>> data = map.get(it);
for (byte[] key : data.keySet()) {
NavigableMap<Long, byte[]> values = data.get(key);
for (Long timestamp : values.keySet()) {
byte[] value = values.get(timestamp);
Object o_key = new ObjectInputStream(new ByteArrayInputStream(
key)).readObject();
Object o_value = new ObjectInputStream(
new ByteArrayInputStream(value)).readObject();
/** Restore the results */
if (!m_reduceTasks.containsKey(key)) {
m_reduceTasks.put(key, new SVector());
}
SVector list = m_reduceTasks.get(o_key);
list.add(o_value);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.pawi.data.enums;
/**
* The {@link ResultType} enumeration represents the result type of a {@link Result} It is used as well to sort the results into the output file. The order the
* enumerations are set here is the same order, they are formatted into the output file.
**/
public enum ResultType {
ALL_WORDS_COUNT, //
CONTENT_WORD_COUNT, //
BOILERPLATE_WORD_COUNT, //
CLASSIFIED_AS_CONTENT_WORDS, //
CLASSIFIED_AS_BOILERPLATE_WORDS, //
TRUE_POSITIVE_WORDS, //
FALSE_POSITIVE_WORDS, //
TRUE_NEGATIVE_WORDS, //
FALSE_NEGATIVE_WORDS, //
PRESICION, //
RECALL, //
FALLOUT, //
FMEASURE, //
ACCURACY;//
}
|
public class Widget
{
private double widgetsPerHour = 10.0;
private int shifts = 2;
private int hoursPerShift = 8;
private int numWidgets;
public void setNumWidgets(int n)
{
numWidgets = n;
}
public int getNumWidgets()
{
return numWidgets;
}
public double getDaysToProduce()
{
double widgetsPerDay = widgetsPerHour * shifts * hoursPerShift;
return numWidgets / widgetsPerDay;
}
}
|
package com.base.crm.product.entity;
import com.base.common.util.PageTools;
public class ProductAssort {
private Long id;
private String assortName;
private String status;
private String updatedDate;
private String createdDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAssortName() {
return assortName;
}
public void setAssortName(String assortName) {
this.assortName = assortName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(String updatedDate) {
this.updatedDate = updatedDate;
}
public String getCreatedDate() {
return createdDate;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
// query
private String startDate;
private String endDate;
// @JsonIgnore
private PageTools pageTools;
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public PageTools getPageTools() {
return pageTools;
}
public void setPageTools(PageTools pageTools) {
this.pageTools = pageTools;
}
}
|
package br.org.funcate.glue.tool;
import java.awt.Cursor;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import br.org.funcate.eagles.kernel.dispatcher.EventHandler;
import br.org.funcate.eagles.kernel.listener.ListenersHandler;
import br.org.funcate.eagles.kernel.listener.ListenersHandlerImpl;
import br.org.funcate.eagles.kernel.transmitter.DirectedEventTransmitter;
import br.org.funcate.eagles.kernel.transmitter.EventTransmitter;
import br.org.funcate.glue.event.MouseDraggedEvent;
import br.org.funcate.glue.event.MousePressedEvent;
import br.org.funcate.glue.model.CalculatorService;
import br.org.funcate.glue.model.canvas.DistanceMeasuringToolService;
public class DistanceTool implements Tool {
private ListenersHandler listeners;
private EventHandler eventHandler;
@SuppressWarnings("unused")
private EventTransmitter transmitter;
private List<String> eventsToListen;
private Cursor cursor;
public DistanceTool() {
listeners = new ListenersHandlerImpl();
eventHandler = new EventHandler();
transmitter = new DirectedEventTransmitter(this);
cursor = new Cursor(Cursor.CROSSHAIR_CURSOR);
eventsToListen = new ArrayList<String>();
eventsToListen.add(MousePressedEvent.class.getName());
eventsToListen.add(MouseDraggedEvent.class.getName());
}
@Override
public ListenersHandler getListenersHandler() {
return this.listeners;
}
@Override
public EventHandler getEventHandler() {
return this.eventHandler;
}
@Override
public void dispatch(EventTransmitter tc, EventObject e) throws Exception {
tc.dispatch(e);
}
@Override
public void handle(EventObject e) {
if (e instanceof MousePressedEvent) {
this.handle((MousePressedEvent) e);
} else if (e instanceof MouseDraggedEvent) {
this.handle((MouseDraggedEvent) e);
}
}
public void handle(MousePressedEvent e) {
double[] point = CalculatorService.convertFromWorldToPixel(e.getX(), e.getY());
DistanceMeasuringToolService.pressDistanceTool((int) point[0], (int) point[1]);
}
public void handle(MouseDraggedEvent e) {
double[] point = CalculatorService.convertFromWorldToPixel(e.getX(), e.getY());
DistanceMeasuringToolService.dragDistanceTool((int) point[0], (int) point[1]);
}
@Override
public void setCursor(Cursor cursor) {
this.cursor = cursor;
}
@Override
public Cursor getCursor() {
return cursor;
}
@Override
public List<String> getEventsToListen() {
return eventsToListen;
}
}
|
public class JSONFileParser implements MyCustomFileParserInterface{
String text;
String fileType = "JSON";
@Override
public void setText(String text) {
this.text = text;
}
@Override
public void findWord(String word) {
System.out.println("Searching for a word in a " + fileType + " file.");
}
@Override
public void replaceWord(String word) {
System.out.println("Replacing a word in a " + fileType + " file.");
}
@Override
public void deleteWord(String word) {
System.out.println("Deleting a word in a " + fileType + " file.");
}
@Override
public void addWord(String word) {
System.out.println("Adding a word in a " + fileType + " file.");
}
}
|
package samples.findbugs;
public class HashCodeContainsEquals {
private static final int LONG_SHIFT_VALUE = 32;
private final long id;
private final long version;
public HashCodeContainsEquals(final long id, final long version) {
this.id = id;
this.version = version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> LONG_SHIFT_VALUE));
result = prime * result + (int) (version ^ (version >>> LONG_SHIFT_VALUE));
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final HashCodeContainsEquals other = (HashCodeContainsEquals) obj;
if (id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return "HashCodeContainsEquals [id=" + id + ", version=" + version + "]";
}
}
|
package org.newdawn.slick.tests;
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.AngelCodeFont;
import org.newdawn.slick.Animation;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;
import org.newdawn.slick.opengl.SlickCallable;
public class SlickCallableTest extends BasicGame {
private Image image;
private Image back;
private float rot;
private AngelCodeFont font;
private Animation homer;
public SlickCallableTest() {
super("Slick Callable Test");
}
public void init(GameContainer container) throws SlickException {
this.image = new Image("testdata/rocket.png");
this.back = new Image("testdata/sky.jpg");
this.font = new AngelCodeFont("testdata/hiero.fnt", "testdata/hiero.png");
SpriteSheet sheet = new SpriteSheet("testdata/homeranim.png", 36, 65);
this.homer = new Animation(sheet, 0, 0, 7, 0, true, 150, true);
}
public void render(GameContainer container, Graphics g) throws SlickException {
g.scale(2.0F, 2.0F);
g.fillRect(0.0F, 0.0F, 800.0F, 600.0F, this.back, 0.0F, 0.0F);
g.resetTransform();
g.drawImage(this.image, 100.0F, 100.0F);
this.image.draw(100.0F, 200.0F, 80.0F, 200.0F);
this.font.drawString(100.0F, 200.0F, "Text Drawn before the callable");
SlickCallable callable = new SlickCallable() {
protected void performGLOperations() throws SlickException {
SlickCallableTest.this.renderGL();
}
};
callable.call();
this.homer.draw(450.0F, 250.0F, 80.0F, 200.0F);
this.font.drawString(150.0F, 300.0F, "Text Drawn after the callable");
}
public void renderGL() {
FloatBuffer pos = BufferUtils.createFloatBuffer(4);
pos.put(new float[] { 5.0F, 5.0F, 10.0F, 0.0F }).flip();
FloatBuffer red = BufferUtils.createFloatBuffer(4);
red.put(new float[] { 0.8F, 0.1F, 0.0F, 1.0F }).flip();
GL11.glLight(16384, 4611, pos);
GL11.glEnable(16384);
GL11.glEnable(2884);
GL11.glEnable(2929);
GL11.glEnable(2896);
GL11.glMatrixMode(5889);
GL11.glLoadIdentity();
float h = 0.75F;
GL11.glFrustum(-1.0D, 1.0D, -h, h, 5.0D, 60.0D);
GL11.glMatrixMode(5888);
GL11.glLoadIdentity();
GL11.glTranslatef(0.0F, 0.0F, -40.0F);
GL11.glRotatef(this.rot, 0.0F, 1.0F, 1.0F);
GL11.glMaterial(1028, 5634, red);
gear(0.5F, 2.0F, 2.0F, 10, 0.7F);
}
private void gear(float inner_radius, float outer_radius, float width, int teeth, float tooth_depth) {
float r0 = inner_radius;
float r1 = outer_radius - tooth_depth / 2.0F;
float r2 = outer_radius + tooth_depth / 2.0F;
float da = 6.2831855F / teeth / 4.0F;
GL11.glShadeModel(7424);
GL11.glNormal3f(0.0F, 0.0F, 1.0F);
GL11.glBegin(8);
int i;
for (i = 0; i <= teeth; i++) {
float angle = i * 2.0F * 3.1415927F / teeth;
GL11.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), width * 0.5F);
if (i < teeth) {
GL11.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos((angle + 3.0F * da)), r1 * (float)Math.sin((angle + 3.0F * da)),
width * 0.5F);
}
}
GL11.glEnd();
GL11.glBegin(7);
for (i = 0; i < teeth; i++) {
float angle = i * 2.0F * 3.1415927F / teeth;
GL11.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), width * 0.5F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + da)), r2 * (float)Math.sin((angle + da)), width * 0.5F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + 2.0F * da)), r2 * (float)Math.sin((angle + 2.0F * da)), width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos((angle + 3.0F * da)), r1 * (float)Math.sin((angle + 3.0F * da)), width * 0.5F);
}
GL11.glEnd();
GL11.glNormal3f(0.0F, 0.0F, -1.0F);
GL11.glBegin(8);
for (i = 0; i <= teeth; i++) {
float angle = i * 2.0F * 3.1415927F / teeth;
GL11.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), -width * 0.5F);
GL11.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), -width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos((angle + 3.0F * da)), r1 * (float)Math.sin((angle + 3.0F * da)), -width * 0.5F);
GL11.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), -width * 0.5F);
}
GL11.glEnd();
GL11.glBegin(7);
for (i = 0; i < teeth; i++) {
float angle = i * 2.0F * 3.1415927F / teeth;
GL11.glVertex3f(r1 * (float)Math.cos((angle + 3.0F * da)), r1 * (float)Math.sin((angle + 3.0F * da)), -width * 0.5F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + 2.0F * da)), r2 * (float)Math.sin((angle + 2.0F * da)), -width * 0.5F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + da)), r2 * (float)Math.sin((angle + da)), -width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), -width * 0.5F);
}
GL11.glEnd();
GL11.glNormal3f(0.0F, 0.0F, 1.0F);
GL11.glBegin(8);
for (i = 0; i < teeth; i++) {
float angle = i * 2.0F * 3.1415927F / teeth;
GL11.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos(angle), r1 * (float)Math.sin(angle), -width * 0.5F);
float u = r2 * (float)Math.cos((angle + da)) - r1 * (float)Math.cos(angle);
float v = r2 * (float)Math.sin((angle + da)) - r1 * (float)Math.sin(angle);
float len = (float)Math.sqrt((u * u + v * v));
u /= len;
v /= len;
GL11.glNormal3f(v, -u, 0.0F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + da)), r2 * (float)Math.sin((angle + da)), width * 0.5F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + da)), r2 * (float)Math.sin((angle + da)), -width * 0.5F);
GL11.glNormal3f((float)Math.cos(angle), (float)Math.sin(angle), 0.0F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + 2.0F * da)), r2 * (float)Math.sin((angle + 2.0F * da)), width * 0.5F);
GL11.glVertex3f(r2 * (float)Math.cos((angle + 2.0F * da)), r2 * (float)Math.sin((angle + 2.0F * da)), -width * 0.5F);
u = r1 * (float)Math.cos((angle + 3.0F * da)) - r2 * (float)Math.cos((angle + 2.0F * da));
v = r1 * (float)Math.sin((angle + 3.0F * da)) - r2 * (float)Math.sin((angle + 2.0F * da));
GL11.glNormal3f(v, -u, 0.0F);
GL11.glVertex3f(r1 * (float)Math.cos((angle + 3.0F * da)), r1 * (float)Math.sin((angle + 3.0F * da)), width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos((angle + 3.0F * da)), r1 * (float)Math.sin((angle + 3.0F * da)), -width * 0.5F);
GL11.glNormal3f((float)Math.cos(angle), (float)Math.sin(angle), 0.0F);
}
GL11.glVertex3f(r1 * (float)Math.cos(0.0D), r1 * (float)Math.sin(0.0D), width * 0.5F);
GL11.glVertex3f(r1 * (float)Math.cos(0.0D), r1 * (float)Math.sin(0.0D), -width * 0.5F);
GL11.glEnd();
GL11.glShadeModel(7425);
GL11.glBegin(8);
for (i = 0; i <= teeth; i++) {
float angle = i * 2.0F * 3.1415927F / teeth;
GL11.glNormal3f(-((float)Math.cos(angle)), -((float)Math.sin(angle)), 0.0F);
GL11.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), -width * 0.5F);
GL11.glVertex3f(r0 * (float)Math.cos(angle), r0 * (float)Math.sin(angle), width * 0.5F);
}
GL11.glEnd();
}
public void update(GameContainer container, int delta) {
this.rot += delta * 0.1F;
}
public static void main(String[] argv) {
try {
AppGameContainer container = new AppGameContainer((Game)new SlickCallableTest());
container.setDisplayMode(800, 600, false);
container.start();
} catch (SlickException e) {
e.printStackTrace();
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\SlickCallableTest.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.